title
stringlengths
3
221
text
stringlengths
17
477k
parsed
listlengths
0
3.17k
How to define custom methods in C#?
To define a custom method in C#, use the following syntax − <Access Specifier> <Return Type> <Method Name>(Parameter List) { Method Body } The following are the various elements of a method − Access Specifier − This determines the visibility of a variable or a method from another class. Access Specifier − This determines the visibility of a variable or a method from another class. Return type − A method may return a value. The return type is the data type of the value the method returns. If the method is not returning any values, then the return type is void. Return type − A method may return a value. The return type is the data type of the value the method returns. If the method is not returning any values, then the return type is void. Method name − Method name is a unique identifier and it is case sensitive. It cannot be same as any other identifier declared in the class. Method name − Method name is a unique identifier and it is case sensitive. It cannot be same as any other identifier declared in the class. Parameter list − Enclosed between parentheses, the parameters are used to pass and receive data from a method. The parameter list refers to the type, order, and number of the parameters of a method. Parameters are optional; that is, a method may contain no parameters. Parameter list − Enclosed between parentheses, the parameters are used to pass and receive data from a method. The parameter list refers to the type, order, and number of the parameters of a method. Parameters are optional; that is, a method may contain no parameters. Method body − This contains the set of instructions needed to complete the required activity. Method body − This contains the set of instructions needed to complete the required activity. Let us see an example − Live Demo using System; namespace Demo { class NumberManipulator { public int FindMax(int num1, int num2) { /* local variable declaration */ int result; if (num1 > num2) result = num1; else result = num2; return result; } static void Main(string[] args) { /* local variable definition */ int a = 90; int b = 15; int ret; NumberManipulator n = new NumberManipulator(); //calling the FindMax method ret = n.FindMax(a, b); Console.WriteLine("Max value is : {0}", ret ); Console.ReadLine(); } } } Max value is : 90
[ { "code": null, "e": 1122, "s": 1062, "text": "To define a custom method in C#, use the following syntax −" }, { "code": null, "e": 1201, "s": 1122, "text": "<Access Specifier> <Return Type> <Method Name>(Parameter List) {\nMethod Body\n}" }, { "code": null, "e": 1254, "s": 1201, "text": "The following are the various elements of a method −" }, { "code": null, "e": 1350, "s": 1254, "text": "Access Specifier − This determines the visibility of a variable or a method from another class." }, { "code": null, "e": 1446, "s": 1350, "text": "Access Specifier − This determines the visibility of a variable or a method from another class." }, { "code": null, "e": 1628, "s": 1446, "text": "Return type − A method may return a value. The return type is the data type of the value the method returns. If the method is not returning any values, then the return type is void." }, { "code": null, "e": 1810, "s": 1628, "text": "Return type − A method may return a value. The return type is the data type of the value the method returns. If the method is not returning any values, then the return type is void." }, { "code": null, "e": 1950, "s": 1810, "text": "Method name − Method name is a unique identifier and it is case sensitive. It cannot be same as any other identifier declared in the class." }, { "code": null, "e": 2090, "s": 1950, "text": "Method name − Method name is a unique identifier and it is case sensitive. It cannot be same as any other identifier declared in the class." }, { "code": null, "e": 2359, "s": 2090, "text": "Parameter list − Enclosed between parentheses, the parameters are used to pass and receive data from a method. The parameter list refers to the type, order, and number of the parameters of a method. Parameters are optional; that is, a method may contain no parameters." }, { "code": null, "e": 2628, "s": 2359, "text": "Parameter list − Enclosed between parentheses, the parameters are used to pass and receive data from a method. The parameter list refers to the type, order, and number of the parameters of a method. Parameters are optional; that is, a method may contain no parameters." }, { "code": null, "e": 2722, "s": 2628, "text": "Method body − This contains the set of instructions needed to complete the required activity." }, { "code": null, "e": 2816, "s": 2722, "text": "Method body − This contains the set of instructions needed to complete the required activity." }, { "code": null, "e": 2840, "s": 2816, "text": "Let us see an example −" }, { "code": null, "e": 2851, "s": 2840, "text": " Live Demo" }, { "code": null, "e": 3512, "s": 2851, "text": "using System;\n\nnamespace Demo {\n class NumberManipulator {\n public int FindMax(int num1, int num2) {\n /* local variable declaration */\n int result;\n\n if (num1 > num2)\n result = num1;\n else\n result = num2;\n return result;\n }\n\n static void Main(string[] args) {\n /* local variable definition */\n int a = 90;\n int b = 15;\n int ret;\n NumberManipulator n = new NumberManipulator();\n\n //calling the FindMax method\n ret = n.FindMax(a, b);\n Console.WriteLine(\"Max value is : {0}\", ret );\n Console.ReadLine();\n }\n }\n}" }, { "code": null, "e": 3530, "s": 3512, "text": "Max value is : 90" } ]
Replace an element of a Java LinkedList
An element in an Java LinkedList can be replaced using the java.util.ArrayList.set() method. This method has two parameters i.e the index at which the LinkedList element is to be replaced and the element that it should be replaced with. ArrayList.set() method returns the element that was at the position specified at the index previously. A program that demonstrates this is given as follows − Live Demo import java.util.LinkedList; public class Demo { public static void main(String[] args) { LinkedList<String> l = new LinkedList<String>(); l.add("Pear"); l.add("Apple"); l.add("Mango"); l.add("Guava"); l.add("Orange"); System.out.println("The LinkedList is: " + l); l.set(2, "Peach"); System.out.println("The LinkedList is: " + l); } } The LinkedList is: [Pear, Apple, Mango, Guava, Orange] The LinkedList is: [Pear, Apple, Peach, Guava, Orange] Now let us understand the above program. The LinkedList l is created. Then LinkedList.add() is used to add the elements to the LinkedList. Then LinkedList.set() is used to replace the element “Mango” with “Peach” at index 2. Then the LinkedList is displayed. A code snippet which demonstrates this is as follows − LinkedList<String> l = new LinkedList<String>(); l.add("Pear"); l.add("Apple"); l.add("Mango"); l.add("Guava"); l.add("Orange"); System.out.println("The LinkedList is: " + l); l.set(2, "Peach"); System.out.println("The LinkedList is: " + l);
[ { "code": null, "e": 1402, "s": 1062, "text": "An element in an Java LinkedList can be replaced using the java.util.ArrayList.set() method. This method has two parameters i.e the index at which the LinkedList element is to be replaced and the element that it should be replaced with. ArrayList.set() method returns the element that was at the position specified at the index previously." }, { "code": null, "e": 1457, "s": 1402, "text": "A program that demonstrates this is given as follows −" }, { "code": null, "e": 1468, "s": 1457, "text": " Live Demo" }, { "code": null, "e": 1864, "s": 1468, "text": "import java.util.LinkedList;\npublic class Demo {\n public static void main(String[] args) {\n LinkedList<String> l = new LinkedList<String>();\n l.add(\"Pear\");\n l.add(\"Apple\");\n l.add(\"Mango\");\n l.add(\"Guava\");\n l.add(\"Orange\");\n System.out.println(\"The LinkedList is: \" + l);\n l.set(2, \"Peach\");\n System.out.println(\"The LinkedList is: \" + l);\n }\n}" }, { "code": null, "e": 1974, "s": 1864, "text": "The LinkedList is: [Pear, Apple, Mango, Guava, Orange]\nThe LinkedList is: [Pear, Apple, Peach, Guava, Orange]" }, { "code": null, "e": 2015, "s": 1974, "text": "Now let us understand the above program." }, { "code": null, "e": 2288, "s": 2015, "text": "The LinkedList l is created. Then LinkedList.add() is used to add the elements to the LinkedList. Then LinkedList.set() is used to replace the element “Mango” with “Peach” at index 2. Then the LinkedList is displayed. A code snippet which demonstrates this is as follows −" }, { "code": null, "e": 2530, "s": 2288, "text": "LinkedList<String> l = new LinkedList<String>();\nl.add(\"Pear\");\nl.add(\"Apple\");\nl.add(\"Mango\");\nl.add(\"Guava\");\nl.add(\"Orange\");\nSystem.out.println(\"The LinkedList is: \" + l);\nl.set(2, \"Peach\");\nSystem.out.println(\"The LinkedList is: \" + l);" } ]
Implement stack using array | Practice | GeeksforGeeks
Write a program to implement a Stack using Array. Your task is to use the class as shown in the comments in the code editor and complete the functions push() and pop() to implement a stack. Example 1: Input: push(2) push(3) pop() push(4) pop() Output: 3, 4 Explanation: push(2) the stack will be {2} push(3) the stack will be {2 3} pop() poped element will be 3, the stack will be {2} push(4) the stack will be {2 4} pop() poped element will be 4 Example 2: Input: pop() push(4) push(5) pop() Output: -1, 5 Your Task: You are required to complete two methods push() and pop(). The push() method takes one argument, an integer 'x' to be pushed into the stack and pop() which returns an integer present at the top and popped out from the stack. If the stack is empty then return -1 from the pop() method. Expected Time Complexity : O(1) for both push() and pop(). Expected Auixilliary Space : O(1) for both push() and pop(). Constraints: 1 <= Q <= 100 1 <= x <= 100 -2 harshscode5 days ago void MyStack :: push(int x){ top++; arr[top]=x; }int MyStack :: pop(){ if(top==-1) return -1; int x=arr[top]; top--; return x; } 0 hharshit81182 weeks ago void MyStack :: push(int x){ if(top<999){ top++; arr[top] = x; }} //Function to remove an item from top of the stack.int MyStack :: pop(){ if(top == -1){ return -1; } int x = arr[top]; top--; return x;} -3 tasyamyadav422 weeks ago System.out.println ("Hello World suuuuuuuuuuuuuuuu"); -2 zerefkhan2 weeks ago C++ code Total Time taken : 0.01/1.12 void MyStack :: push(int x) { arr[++top] = x; } //Function to remove an item from top of the stack. int MyStack :: pop() { if(top == -1) return -1; return arr[top--]; } +1 tarunkanade4 weeks ago 0.2/1.3 //Function to push an integer into the stack. void push(int a) { // Your code here top++; arr[top] = a; } //Function to remove an item from top of the stack. int pop() { // Your code here if(top == -1){ return -1; } return arr[top--]; } 0 atif836141 month ago stack using array java solution : void push(int elem){ if(top==arr.length){ return; } top++; arr[top]=elem; } // pop opreation : int pop(){ if(top==-1){ return -1; } int tempdata=arr[top]; top --; return tempdata; } 0 ruchitchudasama1231 month ago void MyStack :: push(int x) { top++; arr[top]=x; } //Function to remove an item from top of the stack. int MyStack :: pop() { if(top==-1)return top; int x=arr[top]; top--; return x; } 0 sayantankuila1 month ago C solution void push(struct Stack* stack, int item){ //code here if(stack->top == stack->capacity-1){ return; } stack->top++; stack->array[stack->top] = item;} //Function to remove an item from top of the stack.int pop(struct Stack* stack){ //code here if(stack->top == -1){ return -1; } int val = stack->array[stack->top]; stack->top--; return val; } 0 adarsh471111 month ago C solution: void push(struct Stack* stack, int item){ if(stack->top == stack->capacity-1) return; stack->top++; stack->array[stack->top]=item;} //Function to remove an item from top of the stack.int pop(struct Stack* stack){ if(stack->top == -1) return -1; stack->top--; return stack->array[stack->top+1];} 0 0niharika21 month ago void MyStack :: push(int x){ arr[top+1] = x; top = top + 1;} int MyStack :: pop(){ if(top==-1) return top; int x = arr[top]; top = top - 1; return x;} We strongly recommend solving this problem on your own before viewing its editorial. Do you still want to view the editorial? Login to access your submissions. Problem Contest Reset the IDE using the second button on the top right corner. Avoid using static/global variables in your code as your code is tested against multiple test cases and these tend to retain their previous values. Passing the Sample/Custom Test cases does not guarantee the correctness of code. On submission, your code is tested against multiple test cases consisting of all possible corner cases and stress constraints. You can access the hints to get an idea about what is expected of you as well as the final solution code. You can view the solutions submitted by other users from the submission tab.
[ { "code": null, "e": 429, "s": 238, "text": "Write a program to implement a Stack using Array. Your task is to use the class as shown in the comments in the code editor and complete the functions push() and pop() to implement a stack. " }, { "code": null, "e": 440, "s": 429, "text": "Example 1:" }, { "code": null, "e": 719, "s": 440, "text": "Input: \npush(2)\npush(3)\npop()\npush(4) \npop()\nOutput: 3, 4\nExplanation: \npush(2) the stack will be {2}\npush(3) the stack will be {2 3}\npop() poped element will be 3,\n the stack will be {2}\npush(4) the stack will be {2 4}\npop() poped element will be 4" }, { "code": null, "e": 730, "s": 719, "text": "Example 2:" }, { "code": null, "e": 781, "s": 730, "text": "Input: \npop()\npush(4)\npush(5)\npop()\nOutput: -1, 5\n" }, { "code": null, "e": 1077, "s": 781, "text": "Your Task:\nYou are required to complete two methods push() and pop(). The push() method takes one argument, an integer 'x' to be pushed into the stack and pop() which returns an integer present at the top and popped out from the stack. If the stack is empty then return -1 from the pop() method." }, { "code": null, "e": 1197, "s": 1077, "text": "Expected Time Complexity : O(1) for both push() and pop().\nExpected Auixilliary Space : O(1) for both push() and pop()." }, { "code": null, "e": 1238, "s": 1197, "text": "Constraints:\n1 <= Q <= 100\n1 <= x <= 100" }, { "code": null, "e": 1241, "s": 1238, "text": "-2" }, { "code": null, "e": 1262, "s": 1241, "text": "harshscode5 days ago" }, { "code": null, "e": 1413, "s": 1262, "text": "void MyStack :: push(int x){ top++; arr[top]=x; }int MyStack :: pop(){ if(top==-1) return -1; int x=arr[top]; top--; return x; }" }, { "code": null, "e": 1415, "s": 1413, "text": "0" }, { "code": null, "e": 1439, "s": 1415, "text": "hharshit81182 weeks ago" }, { "code": null, "e": 1521, "s": 1439, "text": "void MyStack :: push(int x){ if(top<999){ top++; arr[top] = x; }}" }, { "code": null, "e": 1676, "s": 1521, "text": "//Function to remove an item from top of the stack.int MyStack :: pop(){ if(top == -1){ return -1; } int x = arr[top]; top--; return x;}" }, { "code": null, "e": 1679, "s": 1676, "text": "-3" }, { "code": null, "e": 1704, "s": 1679, "text": "tasyamyadav422 weeks ago" }, { "code": null, "e": 1758, "s": 1704, "text": "System.out.println (\"Hello World suuuuuuuuuuuuuuuu\");" }, { "code": null, "e": 1761, "s": 1758, "text": "-2" }, { "code": null, "e": 1782, "s": 1761, "text": "zerefkhan2 weeks ago" }, { "code": null, "e": 1791, "s": 1782, "text": "C++ code" }, { "code": null, "e": 1820, "s": 1791, "text": "Total Time taken : 0.01/1.12" }, { "code": null, "e": 2004, "s": 1822, "text": "void MyStack :: push(int x)\n{\n arr[++top] = x;\n}\n\n//Function to remove an item from top of the stack.\nint MyStack :: pop()\n{\n if(top == -1) return -1;\n return arr[top--];\n}" }, { "code": null, "e": 2007, "s": 2004, "text": "+1" }, { "code": null, "e": 2030, "s": 2007, "text": "tarunkanade4 weeks ago" }, { "code": null, "e": 2039, "s": 2030, "text": "0.2/1.3 " }, { "code": null, "e": 2360, "s": 2039, "text": "//Function to push an integer into the stack.\n void push(int a)\n\t{\n\t // Your code here\n\t top++;\n\t arr[top] = a;\n\t} \n\t\n //Function to remove an item from top of the stack.\n\tint pop()\n\t{\n // Your code here\n if(top == -1){\n return -1;\n }\n \n return arr[top--];\n\t}" }, { "code": null, "e": 2362, "s": 2360, "text": "0" }, { "code": null, "e": 2383, "s": 2362, "text": "atif836141 month ago" }, { "code": null, "e": 2401, "s": 2383, "text": "stack using array" }, { "code": null, "e": 2417, "s": 2401, "text": "java solution :" }, { "code": null, "e": 2438, "s": 2417, "text": "void push(int elem){" }, { "code": null, "e": 2459, "s": 2438, "text": "if(top==arr.length){" }, { "code": null, "e": 2467, "s": 2459, "text": "return;" }, { "code": null, "e": 2469, "s": 2467, "text": "}" }, { "code": null, "e": 2476, "s": 2469, "text": "top++;" }, { "code": null, "e": 2491, "s": 2476, "text": "arr[top]=elem;" }, { "code": null, "e": 2493, "s": 2491, "text": "}" }, { "code": null, "e": 2513, "s": 2493, "text": "// pop opreation :" }, { "code": null, "e": 2524, "s": 2513, "text": "int pop(){" }, { "code": null, "e": 2537, "s": 2524, "text": "if(top==-1){" }, { "code": null, "e": 2548, "s": 2537, "text": "return -1;" }, { "code": null, "e": 2550, "s": 2548, "text": "}" }, { "code": null, "e": 2573, "s": 2550, "text": "int tempdata=arr[top];" }, { "code": null, "e": 2581, "s": 2573, "text": "top --;" }, { "code": null, "e": 2598, "s": 2581, "text": "return tempdata;" }, { "code": null, "e": 2600, "s": 2598, "text": "}" }, { "code": null, "e": 2602, "s": 2600, "text": "0" }, { "code": null, "e": 2632, "s": 2602, "text": "ruchitchudasama1231 month ago" }, { "code": null, "e": 2841, "s": 2632, "text": "void MyStack :: push(int x)\n{\n top++;\n arr[top]=x;\n}\n\n//Function to remove an item from top of the stack.\nint MyStack :: pop()\n{\n if(top==-1)return top;\n int x=arr[top];\n top--;\n return x;\n}" }, { "code": null, "e": 2843, "s": 2841, "text": "0" }, { "code": null, "e": 2868, "s": 2843, "text": "sayantankuila1 month ago" }, { "code": null, "e": 2879, "s": 2868, "text": "C solution" }, { "code": null, "e": 3044, "s": 2879, "text": "void push(struct Stack* stack, int item){ //code here if(stack->top == stack->capacity-1){ return; } stack->top++; stack->array[stack->top] = item;}" }, { "code": null, "e": 3263, "s": 3044, "text": "//Function to remove an item from top of the stack.int pop(struct Stack* stack){ //code here if(stack->top == -1){ return -1; } int val = stack->array[stack->top]; stack->top--; return val; }" }, { "code": null, "e": 3265, "s": 3263, "text": "0" }, { "code": null, "e": 3288, "s": 3265, "text": "adarsh471111 month ago" }, { "code": null, "e": 3300, "s": 3288, "text": "C solution:" }, { "code": null, "e": 3445, "s": 3302, "text": "void push(struct Stack* stack, int item){ if(stack->top == stack->capacity-1) return; stack->top++; stack->array[stack->top]=item;}" }, { "code": null, "e": 3619, "s": 3445, "text": "//Function to remove an item from top of the stack.int pop(struct Stack* stack){ if(stack->top == -1) return -1; stack->top--; return stack->array[stack->top+1];}" }, { "code": null, "e": 3621, "s": 3619, "text": "0" }, { "code": null, "e": 3643, "s": 3621, "text": "0niharika21 month ago" }, { "code": null, "e": 3708, "s": 3643, "text": "void MyStack :: push(int x){ arr[top+1] = x; top = top + 1;}" }, { "code": null, "e": 3812, "s": 3708, "text": "int MyStack :: pop(){ if(top==-1) return top; int x = arr[top]; top = top - 1; return x;}" }, { "code": null, "e": 3958, "s": 3812, "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": 3994, "s": 3958, "text": " Login to access your submissions. " }, { "code": null, "e": 4004, "s": 3994, "text": "\nProblem\n" }, { "code": null, "e": 4014, "s": 4004, "text": "\nContest\n" }, { "code": null, "e": 4077, "s": 4014, "text": "Reset the IDE using the second button on the top right corner." }, { "code": null, "e": 4225, "s": 4077, "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": 4433, "s": 4225, "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": 4539, "s": 4433, "text": "You can access the hints to get an idea about what is expected of you as well as the final solution code." } ]
How to get file name from a path in PHP?
To get the file name from a path, the code is as follows− Live Demo <?php $file = pathinfo('/home/cg/root/6985034/main.php'); echo $file['basename'], "\n"; ?> This will produce the following output− main.php Let us now see another example − Live Demo <?php $path = "/home/cg/root/6985034/main.php"; $file = basename($path, ".php"); echo $file; ?> This will produce the following output− main
[ { "code": null, "e": 1120, "s": 1062, "text": "To get the file name from a path, the code is as follows−" }, { "code": null, "e": 1131, "s": 1120, "text": " Live Demo" }, { "code": null, "e": 1228, "s": 1131, "text": "<?php\n $file = pathinfo('/home/cg/root/6985034/main.php');\n echo $file['basename'], \"\\n\";\n?>" }, { "code": null, "e": 1268, "s": 1228, "text": "This will produce the following output−" }, { "code": null, "e": 1277, "s": 1268, "text": "main.php" }, { "code": null, "e": 1310, "s": 1277, "text": "Let us now see another example −" }, { "code": null, "e": 1321, "s": 1310, "text": " Live Demo" }, { "code": null, "e": 1426, "s": 1321, "text": "<?php\n $path = \"/home/cg/root/6985034/main.php\";\n $file = basename($path, \".php\");\n echo $file;\n?>" }, { "code": null, "e": 1466, "s": 1426, "text": "This will produce the following output−" }, { "code": null, "e": 1471, "s": 1466, "text": "main" } ]
What does backward() do in PyTorch?
The backward() method is used to compute the gradient during the backward pass in a neural network. The gradients are computed when this method is executed. The gradients are computed when this method is executed. These gradients are stored in the respective variables. These gradients are stored in the respective variables. The gradients are computed with respect to these variables, and the gradients are accessed using .grad. The gradients are computed with respect to these variables, and the gradients are accessed using .grad. If we do not call the backward() method for computing the gradient, the gradients are not computed. If we do not call the backward() method for computing the gradient, the gradients are not computed. And, if we access the gradients using .grad, the result is None. And, if we access the gradients using .grad, the result is None. Let's have a couple of examples to demonstrate how it works. In this example, we attempt to access the gradients without calling the backward() method. We notice that all the gradients are None. # import torch library import torch # define three tensor x = torch.tensor(2., requires_grad = False) w = torch.tensor(3., requires_grad = True) b = torch.tensor(1., requires_grad = True) print("x:", x) print("w:", w) print("b:", b) # define a function of the above defined tensors y = w * x + b print("y:", y) # print the gradient w.r.t above tensors print("x.grad:", x.grad) print("w.grad:", w.grad) print("b.grad:", b.grad) x: tensor(2.) w: tensor(3., requires_grad=True) b: tensor(1., requires_grad=True) y: tensor(7., grad_fn=<AddBackward0>) x.grad: None w.grad: None b.grad: None In this second example, the backward() method is called for the function y. Then, the gradients are accessed. The gradient with respect to a tensor that doesn't require grad is again None. The gradient with respect to the tensor with gradient is not None. # import torch library import torch # define three tensors x = torch.tensor(2., requires_grad = False) w = torch.tensor(3., requires_grad = True) b = torch.tensor(1., requires_grad = True) print("x:", x) print("w:", w) print("b:", b) # define a function y y = w * x + b print("y:", y) # take the backward() for y y.backward() # print the gradients w.r.t. above x, w, and b print("x.grad:", x.grad) print("w.grad:", w.grad) print("b.grad:", b.grad) x: tensor(2.) w: tensor(3., requires_grad=True) b: tensor(1., requires_grad=True) y: tensor(7., grad_fn=<AddBackward0>) x.grad: None w.grad: tensor(2.) b.grad: tensor(1.)
[ { "code": null, "e": 1162, "s": 1062, "text": "The backward() method is used to compute the gradient during the\nbackward pass in a neural network." }, { "code": null, "e": 1219, "s": 1162, "text": "The gradients are computed when this method is executed." }, { "code": null, "e": 1276, "s": 1219, "text": "The gradients are computed when this method is executed." }, { "code": null, "e": 1332, "s": 1276, "text": "These gradients are stored in the respective variables." }, { "code": null, "e": 1388, "s": 1332, "text": "These gradients are stored in the respective variables." }, { "code": null, "e": 1492, "s": 1388, "text": "The gradients are computed with respect to these variables, and the gradients are accessed using .grad." }, { "code": null, "e": 1596, "s": 1492, "text": "The gradients are computed with respect to these variables, and the gradients are accessed using .grad." }, { "code": null, "e": 1696, "s": 1596, "text": "If we do not call the backward() method for computing the gradient, the gradients are not computed." }, { "code": null, "e": 1796, "s": 1696, "text": "If we do not call the backward() method for computing the gradient, the gradients are not computed." }, { "code": null, "e": 1861, "s": 1796, "text": "And, if we access the gradients using .grad, the result is None." }, { "code": null, "e": 1926, "s": 1861, "text": "And, if we access the gradients using .grad, the result is None." }, { "code": null, "e": 1987, "s": 1926, "text": "Let's have a couple of examples to demonstrate how it works." }, { "code": null, "e": 2121, "s": 1987, "text": "In this example, we attempt to access the gradients without calling the\nbackward() method. We notice that all the gradients are None." }, { "code": null, "e": 2551, "s": 2121, "text": "# import torch library\nimport torch\n\n# define three tensor\nx = torch.tensor(2., requires_grad = False)\nw = torch.tensor(3., requires_grad = True)\nb = torch.tensor(1., requires_grad = True)\nprint(\"x:\", x)\nprint(\"w:\", w)\nprint(\"b:\", b)\n\n# define a function of the above defined tensors\ny = w * x + b\nprint(\"y:\", y)\n\n# print the gradient w.r.t above tensors\nprint(\"x.grad:\", x.grad)\nprint(\"w.grad:\", w.grad)\nprint(\"b.grad:\", b.grad)" }, { "code": null, "e": 2710, "s": 2551, "text": "x: tensor(2.)\nw: tensor(3., requires_grad=True)\nb: tensor(1., requires_grad=True)\ny: tensor(7., grad_fn=<AddBackward0>)\nx.grad: None\nw.grad: None\nb.grad: None" }, { "code": null, "e": 2966, "s": 2710, "text": "In this second example, the backward() method is called for the function\ny. Then, the gradients are accessed. The gradient with respect to a tensor\nthat doesn't require grad is again None. The gradient with respect to the\ntensor with gradient is not None." }, { "code": null, "e": 3417, "s": 2966, "text": "# import torch library\nimport torch\n\n# define three tensors\nx = torch.tensor(2., requires_grad = False)\nw = torch.tensor(3., requires_grad = True)\nb = torch.tensor(1., requires_grad = True)\nprint(\"x:\", x)\nprint(\"w:\", w)\nprint(\"b:\", b)\n\n# define a function y\ny = w * x + b\nprint(\"y:\", y)\n\n# take the backward() for y\ny.backward()\n# print the gradients w.r.t. above x, w, and b\nprint(\"x.grad:\", x.grad)\nprint(\"w.grad:\", w.grad)\nprint(\"b.grad:\", b.grad)" }, { "code": null, "e": 3588, "s": 3417, "text": "x: tensor(2.)\nw: tensor(3., requires_grad=True)\nb: tensor(1., requires_grad=True)\ny: tensor(7., grad_fn=<AddBackward0>)\nx.grad: None\nw.grad: tensor(2.)\nb.grad: tensor(1.)" } ]
How to spilt a binary file into multiple files using Python?
To split a big binary file in multiple files, you should first read the file by the size of chunk you want to create, then write that chunk to a file, read the next chunk and repeat until you reach the end of original file. For example, you have a file called my_song.mp3 and want to split it in files of size 500 bytes each. CHUNK_SIZE = 500 file_number = 1 with open('my_song.mp3') as f: chunk = f.read(CHUNK_SIZE) while chunk: with open('my_song_part_' + str(file_number)) as chunk_file: chunk_file.write(chunk) file_number += 1 chunk = f.read(CHUNK_SIZE) In your current directory, now you'll find chunks of your original file scattered across multiple files with prefix as: my_song_part_
[ { "code": null, "e": 1286, "s": 1062, "text": "To split a big binary file in multiple files, you should first read the file by the size of chunk you want to create, then write that chunk to a file, read the next chunk and repeat until you reach the end of original file." }, { "code": null, "e": 1388, "s": 1286, "text": "For example, you have a file called my_song.mp3 and want to split it in files of size 500 bytes each." }, { "code": null, "e": 1665, "s": 1388, "text": "CHUNK_SIZE = 500\nfile_number = 1\nwith open('my_song.mp3') as f:\n chunk = f.read(CHUNK_SIZE)\n while chunk:\n with open('my_song_part_' + str(file_number)) as chunk_file:\n chunk_file.write(chunk)\n file_number += 1\n chunk = f.read(CHUNK_SIZE)" }, { "code": null, "e": 1799, "s": 1665, "text": "In your current directory, now you'll find chunks of your original file scattered across multiple files with prefix as: my_song_part_" } ]
Bootstrap table-hover class
Using the .table-hover class, a light gray background will be added to rows while the cursor hovers over them. You can try to run the following code to implement the table-hover class − Live Demo <!DOCTYPE html> <html> <head> <title>Bootstrap Table</title> <meta name = "viewport" content = "width=device-width, initial-scale = 1"> <link rel = "stylesheet" href = "https://stackpath.bootstrapcdn.com/bootstrap/4.1.1/css/bootstrap.min.css"> <script src = "https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <script src = "https://stackpath.bootstrapcdn.com/bootstrap/4.1.1/js/bootstrap.min.js"></script> </head> <body> <table class = "table table-hover table-bordered table-striped"> <caption>Footballer Rank</caption> <thead> <tr> <th>Footballer</th> <th>Rank</th> <th>Country</th> </tr> </thead> <tbody> <tr> <td>Messi</td> <td>1</td> <td>Argentina</td> </tr> <tr> <td>Neymar</td> <td>2</td> <td>Brazil</td> </tr> <tr> <td>Ronaldo</td> <td>3</td> <td>Portugal</td> </tr> </tbody> </table> </body> </html>
[ { "code": null, "e": 1173, "s": 1062, "text": "Using the .table-hover class, a light gray background will be added to rows while the cursor hovers over them." }, { "code": null, "e": 1248, "s": 1173, "text": "You can try to run the following code to implement the table-hover class −" }, { "code": null, "e": 1258, "s": 1248, "text": "Live Demo" }, { "code": null, "e": 2468, "s": 1258, "text": "<!DOCTYPE html>\n<html>\n <head>\n <title>Bootstrap Table</title>\n <meta name = \"viewport\" content = \"width=device-width, initial-scale = 1\">\n <link rel = \"stylesheet\" href = \"https://stackpath.bootstrapcdn.com/bootstrap/4.1.1/css/bootstrap.min.css\">\n <script src = \"https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js\"></script>\n <script src = \"https://stackpath.bootstrapcdn.com/bootstrap/4.1.1/js/bootstrap.min.js\"></script>\n </head>\n <body>\n <table class = \"table table-hover table-bordered table-striped\">\n <caption>Footballer Rank</caption>\n <thead>\n <tr>\n <th>Footballer</th>\n <th>Rank</th>\n <th>Country</th>\n </tr>\n </thead>\n <tbody>\n <tr>\n <td>Messi</td>\n <td>1</td>\n <td>Argentina</td>\n </tr>\n <tr>\n <td>Neymar</td>\n <td>2</td>\n <td>Brazil</td>\n </tr>\n <tr>\n <td>Ronaldo</td>\n <td>3</td>\n <td>Portugal</td>\n </tr>\n </tbody>\n </table>\n </body>\n</html>" } ]
How to repeat HTML element multiple times using ngFor based on a number? - GeeksforGeeks
24 Jun, 2020 In Angular ngFor is directive which accomplishes the motive of displaying repeated or list of contents with least lines of code, this serves the same purpose as for loops in conventional programming languages. We can print repeated lines of content based on a number using the javascript/typescript function Array() which will generate a list of number from 0 to n-1. We traverse this list to produce n repeated lines of content. Example 1:Demo.Component.ts import { Component, OnInit } from '@angular/core'; @Component({ selector: 'app-demo', templateUrl: './demo.component.html', styleUrls: ['./demo.component.css']}) export class DemoComponent implements OnInit { constructor() { } ngOnInit() { } //function to return list of numbers from 0 to n-1 numSequence(n: number): Array<number> { return Array(n); }} Demo.Component.html <mat-card class="example-card" > <mat-card-header> <h2 >Sequence of Numbers from 0 to 5</h2 > </mat-card-header> <mat-card-content> <!-- n traverses through a list of [0, 1, 2, 3, 4, 5] i.e 0 to 5 i stores the index in each iteration --> <span *ngFor="let n of numSequence(6); let i = index;">{{i}} </span> </mat-card-content></mat-card> Output: Example 2:Inserting template in typescript file and repeating the same element 6 times.Demo2.component.ts import { Component, OnInit } from '@angular/core'; @Component({ selector: 'app-demo', //template encapsulated within the component ts file // instead of separate template(html) template: ' <mat-card class="example-card" > <mat-card-header class="example-header"> <h2 >Repeated GeeksforGeeks</h2 > </mat-card-header> <mat-card-content> <ul> <!--n traverses through a list of [0, 1, 2, 3, 4, 5] i.e 0 to 5 prints GeeksforGeeks for 6 times --> <li example-card-text *ngFor="let n of numSequence(6)"> <b>GeeksforGeeks</b></li> </ul> </mat-card-content></mat-card>', styleUrls: ['./demo.component.css']}) export class DemoComponent implements OnInit { constructor() { } ngOnInit() { } //function to return list of numbers from 0 to n-1 numSequence(n: number): Array<number> { return Array(n); }} Output: AngularJS-Misc Picked AngularJS HTML JavaScript Web Technologies HTML Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Angular PrimeNG Dropdown Component How to make a Bootstrap Modal Popup in Angular 9/8 ? Angular 10 (blur) Event How to create module with Routing in Angular 9 ? How to setup 404 page in angular routing ? Top 10 Projects For Beginners To Practice HTML and CSS Skills How to insert spaces/tabs in text using HTML/CSS? How to set the default value for an HTML <select> element ? How to update Node.js and NPM to next version ? How to set input type date in dd-mm-yyyy format using HTML ?
[ { "code": null, "e": 24572, "s": 24544, "text": "\n24 Jun, 2020" }, { "code": null, "e": 24782, "s": 24572, "text": "In Angular ngFor is directive which accomplishes the motive of displaying repeated or list of contents with least lines of code, this serves the same purpose as for loops in conventional programming languages." }, { "code": null, "e": 25002, "s": 24782, "text": "We can print repeated lines of content based on a number using the javascript/typescript function Array() which will generate a list of number from 0 to n-1. We traverse this list to produce n repeated lines of content." }, { "code": null, "e": 25030, "s": 25002, "text": "Example 1:Demo.Component.ts" }, { "code": "import { Component, OnInit } from '@angular/core'; @Component({ selector: 'app-demo', templateUrl: './demo.component.html', styleUrls: ['./demo.component.css']}) export class DemoComponent implements OnInit { constructor() { } ngOnInit() { } //function to return list of numbers from 0 to n-1 numSequence(n: number): Array<number> { return Array(n); }}", "e": 25400, "s": 25030, "text": null }, { "code": null, "e": 25420, "s": 25400, "text": "Demo.Component.html" }, { "code": "<mat-card class=\"example-card\" > <mat-card-header> <h2 >Sequence of Numbers from 0 to 5</h2 > </mat-card-header> <mat-card-content> <!-- n traverses through a list of [0, 1, 2, 3, 4, 5] i.e 0 to 5 i stores the index in each iteration --> <span *ngFor=\"let n of numSequence(6); let i = index;\">{{i}} </span> </mat-card-content></mat-card>", "e": 25792, "s": 25420, "text": null }, { "code": null, "e": 25800, "s": 25792, "text": "Output:" }, { "code": null, "e": 25906, "s": 25800, "text": "Example 2:Inserting template in typescript file and repeating the same element 6 times.Demo2.component.ts" }, { "code": "import { Component, OnInit } from '@angular/core'; @Component({ selector: 'app-demo', //template encapsulated within the component ts file // instead of separate template(html) template: ' <mat-card class=\"example-card\" > <mat-card-header class=\"example-header\"> <h2 >Repeated GeeksforGeeks</h2 > </mat-card-header> <mat-card-content> <ul> <!--n traverses through a list of [0, 1, 2, 3, 4, 5] i.e 0 to 5 prints GeeksforGeeks for 6 times --> <li example-card-text *ngFor=\"let n of numSequence(6)\"> <b>GeeksforGeeks</b></li> </ul> </mat-card-content></mat-card>', styleUrls: ['./demo.component.css']}) export class DemoComponent implements OnInit { constructor() { } ngOnInit() { } //function to return list of numbers from 0 to n-1 numSequence(n: number): Array<number> { return Array(n); }}", "e": 26779, "s": 25906, "text": null }, { "code": null, "e": 26787, "s": 26779, "text": "Output:" }, { "code": null, "e": 26802, "s": 26787, "text": "AngularJS-Misc" }, { "code": null, "e": 26809, "s": 26802, "text": "Picked" }, { "code": null, "e": 26819, "s": 26809, "text": "AngularJS" }, { "code": null, "e": 26824, "s": 26819, "text": "HTML" }, { "code": null, "e": 26835, "s": 26824, "text": "JavaScript" }, { "code": null, "e": 26852, "s": 26835, "text": "Web Technologies" }, { "code": null, "e": 26857, "s": 26852, "text": "HTML" }, { "code": null, "e": 26955, "s": 26857, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 26964, "s": 26955, "text": "Comments" }, { "code": null, "e": 26977, "s": 26964, "text": "Old Comments" }, { "code": null, "e": 27012, "s": 26977, "text": "Angular PrimeNG Dropdown Component" }, { "code": null, "e": 27065, "s": 27012, "text": "How to make a Bootstrap Modal Popup in Angular 9/8 ?" }, { "code": null, "e": 27089, "s": 27065, "text": "Angular 10 (blur) Event" }, { "code": null, "e": 27138, "s": 27089, "text": "How to create module with Routing in Angular 9 ?" }, { "code": null, "e": 27181, "s": 27138, "text": "How to setup 404 page in angular routing ?" }, { "code": null, "e": 27243, "s": 27181, "text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills" }, { "code": null, "e": 27293, "s": 27243, "text": "How to insert spaces/tabs in text using HTML/CSS?" }, { "code": null, "e": 27353, "s": 27293, "text": "How to set the default value for an HTML <select> element ?" }, { "code": null, "e": 27401, "s": 27353, "text": "How to update Node.js and NPM to next version ?" } ]
Find the K closest points to origin using Priority Queue - GeeksforGeeks
24 Nov, 2021 Given a list of n points on 2D plane, the task is to find the K (k < n) closest points to the origin O(0, 0). Note: The distance between a point P(x, y) and O(0, 0) using the standard Euclidean Distance. Examples: Input: [(1, 0), (2, 1), (3, 6), (-5, 2), (1, -4)], K = 3 Output: [(1, 0), (2, 1), (1, -4)] Explanation: Square of Distances of points from origin are (1, 0) : 1 (2, 1) : 5 (3, 6) : 45 (-5, 2) : 29 (1, -4) : 17 Hence for K = 3, the closest 3 points are (1, 0), (2, 1) & (1, -4).Input: [(1, 3), (-2, 2)], K = 1 Output: [(-2, 2)] Explanation: Square of Distances of points from origin are (1, 3) : 10 (-2, 2) : 8 Hence for K = 1, the closest point is (-2, 2). Approach using sorting based on distance: This approach is explained in this article.Approach using Priority Queue for comparison: To solve the problem mentioned above, the main idea is to store the coordinates of the point in a priority queue of pairs, according to the distance of the point from the origin. For assigning the maximum priority to the least distant point from the origin, we use the Comparator class in Priority Queue. Then print the first K elements of the priority queue.Below is the implementation of above approach: C++ Java Javascript Python3 // C++ implementation to find the K// closest points to origin// using Priority Queue #include <bits/stdc++.h>using namespace std; // Comparator class to assign// priority to coordinatesclass comp { public: bool operator()(pair<int, int> a, pair<int, int> b) { int x1 = a.first * a.first; int y1 = a.second * a.second; int x2 = b.first * b.first; int y2 = b.second * b.second; // return true if distance // of point 1 from origin // is greater than distance of // point 2 from origin return (x1 + y1) > (x2 + y2); }}; // Function to find the K closest pointsvoid kClosestPoints(int x[], int y[], int n, int k){ // Create a priority queue priority_queue<pair<int, int>, vector<pair<int, int> >, comp> pq; // Pushing all the points // in the queue for (int i = 0; i < n; i++) { pq.push(make_pair(x[i], y[i])); } // Print the first K elements // of the queue for (int i = 0; i < k; i++) { // Store the top of the queue // in a temporary pair pair<int, int> p = pq.top(); // Print the first (x) // and second (y) of pair cout << p.first << " " << p.second << endl; // Remove top element // of priority queue pq.pop(); }} // Driver codeint main(){ // x coordinate of points int x[] = { 1, -2 }; // y coordinate of points int y[] = { 3, 2 }; int K = 1; int n = sizeof(x) / sizeof(x[0]); kClosestPoints(x, y, n, K); return 0;} // Java implementation to find the K// closest points to origin// using Priority Queueimport java.util.*; // Point class to store// a pointclass Pair implements Comparable<Pair>{ int first, second; Pair(int a, int b) { first = a; second = b; } public int compareTo(Pair o) { int x1 = first * first; int y1 = second * second; int x2 = o.first * o.first; int y2 = o.second * o.second; return (x1 + y1) - (x2 + y2); }} class GFG{ // Function to find the K closest pointsstatic void kClosestPoints(int x[], int y[], int n, int k){ // Create a priority queue PriorityQueue<Pair> pq = new PriorityQueue<>(); // Pushing all the points // in the queue for(int i = 0; i < n; i++) { pq.add(new Pair(x[i], y[i])); } // Print the first K elements // of the queue for(int i = 0; i < k; i++) { // Remove the top of the queue // and store in a temporary pair Pair p = pq.poll(); // Print the first (x) // and second (y) of pair System.out.println(p.first + " " + p.second); }} // Driver codepublic static void main(String[] args){ // x coordinate of points int x[] = { 1, -2 }; // y coordinate of points int y[] = { 3, 2 }; int K = 1; int n = x.length; kClosestPoints(x, y, n, K);}} // This code is contributed by jrishabh99 <script> // Javascript implementation to find the K// closest points to origin// using Priority Queue // Function to find the K closest pointsfunction kClosestPoints(x, y, n, k){ // Create a priority queue var pq = []; // Pushing all the points // in the queue for (var i = 0; i < n; i++) { pq.push([x[i], y[i]]); } // Print the first K elements // of the queue for (var i = 0; i < k; i++) { // Store the top of the queue // in a temporary pair var p = pq[pq.length-1]; // Print the first (x) // and second (y) of pair document.write( p[0] + " " + p[1] + "<br>"); // Remove top element // of priority queue pq.pop(); }} // Driver code// x coordinate of pointsvar x = [1, -2]; // y coordinate of pointsvar y = [3, 2];var K = 1;var n = x.length;kClosestPoints(x, y, n, K); // This code is contributed by rutvik_56.</script> # Python3 implementation to find the K# closest points to origin# using Priority Queue import heapq as hq# Function to find the K closest pointsdef kClosestPoints(x, y, n, k): # Create a priority queue pq=[] # Pushing all the points # in the queue for i in range(n): hq.heappush(pq, (x[i]*x[i]+y[i]*y[i],x[i],y[i])) # Print the first K elements # of the queue for i in range(k) : # Store the top of the queue # in a temporary pair p = hq.heappop(pq) # Print the first (x) # and second (y) of pair print("{} {}".format(p[1],p[2])) # Driver codeif __name__ == '__main__': # x coordinate of points x = [1, -2] # y coordinate of points y = [3, 2] K = 1 n=len(x) kClosestPoints(x, y, n, K) -2 2 Time Complexity: O(N + K * log(N))Auxiliary Space: O(N) jrishabh99 pankajsharmagfg rutvik_56 amartyaghoshgfg Amazon priority-queue STL Data Structures Geometric Mathematical Queue Sorting Amazon Data Structures Mathematical Sorting Queue Geometric STL priority-queue Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments SDE SHEET - A Complete Guide for SDE Preparation DSA Sheet by Love Babbar Introduction to Algorithms Introduction to Tree Data Structure Insertion and Deletion in Heaps Program for distance between two points on earth How to check if a given point lies inside or outside a polygon? How to check if two given line segments intersect? Find if two rectangles overlap Convex Hull | Set 1 (Jarvis's Algorithm or Wrapping)
[ { "code": null, "e": 25384, "s": 25356, "text": "\n24 Nov, 2021" }, { "code": null, "e": 25598, "s": 25384, "text": "Given a list of n points on 2D plane, the task is to find the K (k < n) closest points to the origin O(0, 0). Note: The distance between a point P(x, y) and O(0, 0) using the standard Euclidean Distance. Examples:" }, { "code": null, "e": 26055, "s": 25598, "text": "Input: [(1, 0), (2, 1), (3, 6), (-5, 2), (1, -4)], K = 3 Output: [(1, 0), (2, 1), (1, -4)] Explanation: Square of Distances of points from origin are (1, 0) : 1 (2, 1) : 5 (3, 6) : 45 (-5, 2) : 29 (1, -4) : 17 Hence for K = 3, the closest 3 points are (1, 0), (2, 1) & (1, -4).Input: [(1, 3), (-2, 2)], K = 1 Output: [(-2, 2)] Explanation: Square of Distances of points from origin are (1, 3) : 10 (-2, 2) : 8 Hence for K = 1, the closest point is (-2, 2)." }, { "code": null, "e": 26592, "s": 26055, "text": "Approach using sorting based on distance: This approach is explained in this article.Approach using Priority Queue for comparison: To solve the problem mentioned above, the main idea is to store the coordinates of the point in a priority queue of pairs, according to the distance of the point from the origin. For assigning the maximum priority to the least distant point from the origin, we use the Comparator class in Priority Queue. Then print the first K elements of the priority queue.Below is the implementation of above approach:" }, { "code": null, "e": 26596, "s": 26592, "text": "C++" }, { "code": null, "e": 26601, "s": 26596, "text": "Java" }, { "code": null, "e": 26612, "s": 26601, "text": "Javascript" }, { "code": null, "e": 26620, "s": 26612, "text": "Python3" }, { "code": "// C++ implementation to find the K// closest points to origin// using Priority Queue #include <bits/stdc++.h>using namespace std; // Comparator class to assign// priority to coordinatesclass comp { public: bool operator()(pair<int, int> a, pair<int, int> b) { int x1 = a.first * a.first; int y1 = a.second * a.second; int x2 = b.first * b.first; int y2 = b.second * b.second; // return true if distance // of point 1 from origin // is greater than distance of // point 2 from origin return (x1 + y1) > (x2 + y2); }}; // Function to find the K closest pointsvoid kClosestPoints(int x[], int y[], int n, int k){ // Create a priority queue priority_queue<pair<int, int>, vector<pair<int, int> >, comp> pq; // Pushing all the points // in the queue for (int i = 0; i < n; i++) { pq.push(make_pair(x[i], y[i])); } // Print the first K elements // of the queue for (int i = 0; i < k; i++) { // Store the top of the queue // in a temporary pair pair<int, int> p = pq.top(); // Print the first (x) // and second (y) of pair cout << p.first << \" \" << p.second << endl; // Remove top element // of priority queue pq.pop(); }} // Driver codeint main(){ // x coordinate of points int x[] = { 1, -2 }; // y coordinate of points int y[] = { 3, 2 }; int K = 1; int n = sizeof(x) / sizeof(x[0]); kClosestPoints(x, y, n, K); return 0;}", "e": 28239, "s": 26620, "text": null }, { "code": "// Java implementation to find the K// closest points to origin// using Priority Queueimport java.util.*; // Point class to store// a pointclass Pair implements Comparable<Pair>{ int first, second; Pair(int a, int b) { first = a; second = b; } public int compareTo(Pair o) { int x1 = first * first; int y1 = second * second; int x2 = o.first * o.first; int y2 = o.second * o.second; return (x1 + y1) - (x2 + y2); }} class GFG{ // Function to find the K closest pointsstatic void kClosestPoints(int x[], int y[], int n, int k){ // Create a priority queue PriorityQueue<Pair> pq = new PriorityQueue<>(); // Pushing all the points // in the queue for(int i = 0; i < n; i++) { pq.add(new Pair(x[i], y[i])); } // Print the first K elements // of the queue for(int i = 0; i < k; i++) { // Remove the top of the queue // and store in a temporary pair Pair p = pq.poll(); // Print the first (x) // and second (y) of pair System.out.println(p.first + \" \" + p.second); }} // Driver codepublic static void main(String[] args){ // x coordinate of points int x[] = { 1, -2 }; // y coordinate of points int y[] = { 3, 2 }; int K = 1; int n = x.length; kClosestPoints(x, y, n, K);}} // This code is contributed by jrishabh99", "e": 29692, "s": 28239, "text": null }, { "code": "<script> // Javascript implementation to find the K// closest points to origin// using Priority Queue // Function to find the K closest pointsfunction kClosestPoints(x, y, n, k){ // Create a priority queue var pq = []; // Pushing all the points // in the queue for (var i = 0; i < n; i++) { pq.push([x[i], y[i]]); } // Print the first K elements // of the queue for (var i = 0; i < k; i++) { // Store the top of the queue // in a temporary pair var p = pq[pq.length-1]; // Print the first (x) // and second (y) of pair document.write( p[0] + \" \" + p[1] + \"<br>\"); // Remove top element // of priority queue pq.pop(); }} // Driver code// x coordinate of pointsvar x = [1, -2]; // y coordinate of pointsvar y = [3, 2];var K = 1;var n = x.length;kClosestPoints(x, y, n, K); // This code is contributed by rutvik_56.</script>", "e": 30632, "s": 29692, "text": null }, { "code": "# Python3 implementation to find the K# closest points to origin# using Priority Queue import heapq as hq# Function to find the K closest pointsdef kClosestPoints(x, y, n, k): # Create a priority queue pq=[] # Pushing all the points # in the queue for i in range(n): hq.heappush(pq, (x[i]*x[i]+y[i]*y[i],x[i],y[i])) # Print the first K elements # of the queue for i in range(k) : # Store the top of the queue # in a temporary pair p = hq.heappop(pq) # Print the first (x) # and second (y) of pair print(\"{} {}\".format(p[1],p[2])) # Driver codeif __name__ == '__main__': # x coordinate of points x = [1, -2] # y coordinate of points y = [3, 2] K = 1 n=len(x) kClosestPoints(x, y, n, K)", "e": 31425, "s": 30632, "text": null }, { "code": null, "e": 31430, "s": 31425, "text": "-2 2" }, { "code": null, "e": 31489, "s": 31432, "text": "Time Complexity: O(N + K * log(N))Auxiliary Space: O(N) " }, { "code": null, "e": 31500, "s": 31489, "text": "jrishabh99" }, { "code": null, "e": 31516, "s": 31500, "text": "pankajsharmagfg" }, { "code": null, "e": 31526, "s": 31516, "text": "rutvik_56" }, { "code": null, "e": 31542, "s": 31526, "text": "amartyaghoshgfg" }, { "code": null, "e": 31549, "s": 31542, "text": "Amazon" }, { "code": null, "e": 31564, "s": 31549, "text": "priority-queue" }, { "code": null, "e": 31568, "s": 31564, "text": "STL" }, { "code": null, "e": 31584, "s": 31568, "text": "Data Structures" }, { "code": null, "e": 31594, "s": 31584, "text": "Geometric" }, { "code": null, "e": 31607, "s": 31594, "text": "Mathematical" }, { "code": null, "e": 31613, "s": 31607, "text": "Queue" }, { "code": null, "e": 31621, "s": 31613, "text": "Sorting" }, { "code": null, "e": 31628, "s": 31621, "text": "Amazon" }, { "code": null, "e": 31644, "s": 31628, "text": "Data Structures" }, { "code": null, "e": 31657, "s": 31644, "text": "Mathematical" }, { "code": null, "e": 31665, "s": 31657, "text": "Sorting" }, { "code": null, "e": 31671, "s": 31665, "text": "Queue" }, { "code": null, "e": 31681, "s": 31671, "text": "Geometric" }, { "code": null, "e": 31685, "s": 31681, "text": "STL" }, { "code": null, "e": 31700, "s": 31685, "text": "priority-queue" }, { "code": null, "e": 31798, "s": 31700, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 31807, "s": 31798, "text": "Comments" }, { "code": null, "e": 31820, "s": 31807, "text": "Old Comments" }, { "code": null, "e": 31869, "s": 31820, "text": "SDE SHEET - A Complete Guide for SDE Preparation" }, { "code": null, "e": 31894, "s": 31869, "text": "DSA Sheet by Love Babbar" }, { "code": null, "e": 31921, "s": 31894, "text": "Introduction to Algorithms" }, { "code": null, "e": 31957, "s": 31921, "text": "Introduction to Tree Data Structure" }, { "code": null, "e": 31989, "s": 31957, "text": "Insertion and Deletion in Heaps" }, { "code": null, "e": 32038, "s": 31989, "text": "Program for distance between two points on earth" }, { "code": null, "e": 32102, "s": 32038, "text": "How to check if a given point lies inside or outside a polygon?" }, { "code": null, "e": 32153, "s": 32102, "text": "How to check if two given line segments intersect?" }, { "code": null, "e": 32184, "s": 32153, "text": "Find if two rectangles overlap" } ]
Python SQLite - Where Clause
If you want to fetch, delete or, update particular rows of a table in SQLite, you need to use the where clause to specify condition to filter the rows of the table for the operation. For example, if you have a SELECT statement with where clause, only the rows which satisfies the specified condition will be retrieved. Following is the syntax of the WHERE clause in SQLite − SELECT column1, column2, columnN FROM table_name WHERE [search_condition] You can specify a search_condition using comparison or logical operators. like >, <, =, LIKE, NOT, etc. The following examples would make this concept clear. Assume we have created a table with name CRICKETERS using the following query − sqlite> CREATE TABLE CRICKETERS ( First_Name VARCHAR(255), Last_Name VARCHAR(255), Age int, Place_Of_Birth VARCHAR(255), Country VARCHAR(255) ); sqlite> And if we have inserted 5 records in to it using INSERT statements as − sqlite> insert into CRICKETERS values('Shikhar', 'Dhawan', 33, 'Delhi', 'India'); sqlite> insert into CRICKETERS values('Jonathan', 'Trott', 38, 'CapeTown', 'SouthAfrica'); sqlite> insert into CRICKETERS values('Kumara', 'Sangakkara', 41, 'Matale', 'Srilanka'); sqlite> insert into CRICKETERS values('Virat', 'Kohli', 30, 'Delhi', 'India'); sqlite> insert into CRICKETERS values('Rohit', 'Sharma', 32, 'Nagpur', 'India'); sqlite> Following SELECT statement retrieves the records whose age is greater than 35 − sqlite> SELECT * FROM CRICKETERS WHERE AGE > 35; First_Name Last_Name Age Place_Of_B Country ---------- ---------- ---- ---------- ------------- Jonathan Trott 38 CapeTown SouthAfrica Kumara Sangakkara 41 Matale Srilanka sqlite> The Cursor object/class contains all the methods to execute queries and fetch data, etc. The cursor method of the connection class returns a cursor object. Therefore, to create a table in SQLite database using python − Establish connection with a database using the connect() method. Establish connection with a database using the connect() method. Create a cursor object by invoking the cursor() method on the above created connection object. Create a cursor object by invoking the cursor() method on the above created connection object. Now execute the CREATE TABLE statement using the execute() method of the Cursor class. Now execute the CREATE TABLE statement using the execute() method of the Cursor class. Following example creates a table named Employee and populates it. Then using the where clause it retrieves the records with age value less than 23. import sqlite3 #Connecting to sqlite conn = sqlite3.connect('example.db') #Creating a cursor object using the cursor() method cursor = conn.cursor() #Doping EMPLOYEE table if already exists. cursor.execute("DROP TABLE IF EXISTS EMPLOYEE") sql = '''CREATE TABLE EMPLOYEE( FIRST_NAME CHAR(20) NOT NULL, LAST_NAME CHAR(20), AGE INT, SEX CHAR(1), INCOME FLOAT )''' cursor.execute(sql) #Populating the table cursor.execute('''INSERT INTO EMPLOYEE( FIRST_NAME, LAST_NAME, AGE, SEX, INCOME) VALUES ('Ramya', 'Rama priya', 27, 'F', 9000)''') cursor.execute('''INSERT INTO EMPLOYEE (FIRST_NAME, LAST_NAME, AGE, SEX, INCOME) VALUES ('Vinay', 'Battacharya', 20, 'M', 6000)''') cursor.execute('''INSERT INTO EMPLOYEE( FIRST_NAME, LAST_NAME, AGE, SEX, INCOME) VALUES ('Sharukh', 'Sheik', 25, 'M', 8300)''') cursor.execute('''INSERT INTO EMPLOYEE( FIRST_NAME, LAST_NAME, AGE, SEX, INCOME) VALUES ('Sarmista', 'Sharma', 26, 'F', 10000)''') cursor.execute('''INSERT INTO EMPLOYEE( FIRST_NAME, LAST_NAME, AGE, SEX, INCOME) VALUES ('Tripthi', 'Mishra', 24, 'F', 6000)''') #Retrieving specific records using the where clause cursor.execute("SELECT * from EMPLOYEE WHERE AGE <23") print(cursor.fetchall()) #Commit your changes in the database conn.commit() #Closing the connection conn.close() [('Vinay', 'Battacharya', 20, 'M', 6000.0)] 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": 3388, "s": 3205, "text": "If you want to fetch, delete or, update particular rows of a table in SQLite, you need to use the where clause to specify condition to filter the rows of the table for the operation." }, { "code": null, "e": 3524, "s": 3388, "text": "For example, if you have a SELECT statement with where clause, only the rows which satisfies the specified condition will be retrieved." }, { "code": null, "e": 3580, "s": 3524, "text": "Following is the syntax of the WHERE clause in SQLite −" }, { "code": null, "e": 3655, "s": 3580, "text": "SELECT column1, column2, columnN\nFROM table_name\nWHERE [search_condition]\n" }, { "code": null, "e": 3813, "s": 3655, "text": "You can specify a search_condition using comparison or logical operators. like >, <, =, LIKE, NOT, etc. The following examples would make this concept clear." }, { "code": null, "e": 3893, "s": 3813, "text": "Assume we have created a table with name CRICKETERS using the following query −" }, { "code": null, "e": 4061, "s": 3893, "text": "sqlite> CREATE TABLE CRICKETERS (\n First_Name VARCHAR(255),\n Last_Name VARCHAR(255),\n Age int,\n Place_Of_Birth VARCHAR(255),\n Country VARCHAR(255)\n);\nsqlite>" }, { "code": null, "e": 4133, "s": 4061, "text": "And if we have inserted 5 records in to it using INSERT statements as −" }, { "code": null, "e": 4563, "s": 4133, "text": "sqlite> insert into CRICKETERS values('Shikhar', 'Dhawan', 33, 'Delhi', 'India');\nsqlite> insert into CRICKETERS values('Jonathan', 'Trott', 38, 'CapeTown', 'SouthAfrica');\nsqlite> insert into CRICKETERS values('Kumara', 'Sangakkara', 41, 'Matale', 'Srilanka');\nsqlite> insert into CRICKETERS values('Virat', 'Kohli', 30, 'Delhi', 'India');\nsqlite> insert into CRICKETERS values('Rohit', 'Sharma', 32, 'Nagpur', 'India');\nsqlite>" }, { "code": null, "e": 4643, "s": 4563, "text": "Following SELECT statement retrieves the records whose age is greater than 35 −" }, { "code": null, "e": 4896, "s": 4643, "text": "sqlite> SELECT * FROM CRICKETERS WHERE AGE > 35;\nFirst_Name Last_Name Age Place_Of_B Country\n---------- ---------- ---- ---------- -------------\nJonathan Trott 38 CapeTown SouthAfrica\nKumara Sangakkara 41 Matale Srilanka\nsqlite>\n" }, { "code": null, "e": 5052, "s": 4896, "text": "The Cursor object/class contains all the methods to execute queries and fetch data, etc. The cursor method of the connection class returns a cursor object." }, { "code": null, "e": 5115, "s": 5052, "text": "Therefore, to create a table in SQLite database using python −" }, { "code": null, "e": 5180, "s": 5115, "text": "Establish connection with a database using the connect() method." }, { "code": null, "e": 5245, "s": 5180, "text": "Establish connection with a database using the connect() method." }, { "code": null, "e": 5340, "s": 5245, "text": "Create a cursor object by invoking the cursor() method on the above created connection object." }, { "code": null, "e": 5435, "s": 5340, "text": "Create a cursor object by invoking the cursor() method on the above created connection object." }, { "code": null, "e": 5522, "s": 5435, "text": "Now execute the CREATE TABLE statement using the execute() method of the Cursor class." }, { "code": null, "e": 5609, "s": 5522, "text": "Now execute the CREATE TABLE statement using the execute() method of the Cursor class." }, { "code": null, "e": 5758, "s": 5609, "text": "Following example creates a table named Employee and populates it. Then using the where clause it retrieves the records with age value less than 23." }, { "code": null, "e": 7093, "s": 5758, "text": "import sqlite3\n\n#Connecting to sqlite\nconn = sqlite3.connect('example.db')\n\n#Creating a cursor object using the cursor() method\ncursor = conn.cursor()\n\n#Doping EMPLOYEE table if already exists.\ncursor.execute(\"DROP TABLE IF EXISTS EMPLOYEE\")\nsql = '''CREATE TABLE EMPLOYEE(\n FIRST_NAME CHAR(20) NOT NULL,\n LAST_NAME CHAR(20),\n AGE INT,\n SEX CHAR(1),\n INCOME FLOAT\n)'''\ncursor.execute(sql)\n\n#Populating the table\ncursor.execute('''INSERT INTO EMPLOYEE(\n FIRST_NAME, LAST_NAME, AGE, SEX, INCOME) VALUES \n ('Ramya', 'Rama priya', 27, 'F', 9000)''')\n\ncursor.execute('''INSERT INTO EMPLOYEE\n (FIRST_NAME, LAST_NAME, AGE, SEX, INCOME) VALUES \n ('Vinay', 'Battacharya', 20, 'M', 6000)''')\n\ncursor.execute('''INSERT INTO EMPLOYEE(\n FIRST_NAME, LAST_NAME, AGE, SEX, INCOME) VALUES \n ('Sharukh', 'Sheik', 25, 'M', 8300)''')\n\ncursor.execute('''INSERT INTO EMPLOYEE(\n FIRST_NAME, LAST_NAME, AGE, SEX, INCOME) VALUES \n ('Sarmista', 'Sharma', 26, 'F', 10000)''')\n\ncursor.execute('''INSERT INTO EMPLOYEE(\n FIRST_NAME, LAST_NAME, AGE, SEX, INCOME) VALUES \n ('Tripthi', 'Mishra', 24, 'F', 6000)''')\n\n#Retrieving specific records using the where clause\ncursor.execute(\"SELECT * from EMPLOYEE WHERE AGE <23\")\nprint(cursor.fetchall())\n\n#Commit your changes in the database\nconn.commit()\n\n#Closing the connection\nconn.close()" }, { "code": null, "e": 7138, "s": 7093, "text": "[('Vinay', 'Battacharya', 20, 'M', 6000.0)]\n" }, { "code": null, "e": 7175, "s": 7138, "text": "\n 187 Lectures \n 17.5 hours \n" }, { "code": null, "e": 7191, "s": 7175, "text": " Malhar Lathkar" }, { "code": null, "e": 7224, "s": 7191, "text": "\n 55 Lectures \n 8 hours \n" }, { "code": null, "e": 7243, "s": 7224, "text": " Arnab Chakraborty" }, { "code": null, "e": 7278, "s": 7243, "text": "\n 136 Lectures \n 11 hours \n" }, { "code": null, "e": 7300, "s": 7278, "text": " In28Minutes Official" }, { "code": null, "e": 7334, "s": 7300, "text": "\n 75 Lectures \n 13 hours \n" }, { "code": null, "e": 7362, "s": 7334, "text": " Eduonix Learning Solutions" }, { "code": null, "e": 7397, "s": 7362, "text": "\n 70 Lectures \n 8.5 hours \n" }, { "code": null, "e": 7411, "s": 7397, "text": " Lets Kode It" }, { "code": null, "e": 7444, "s": 7411, "text": "\n 63 Lectures \n 6 hours \n" }, { "code": null, "e": 7461, "s": 7444, "text": " Abhilash Nelson" }, { "code": null, "e": 7468, "s": 7461, "text": " Print" }, { "code": null, "e": 7479, "s": 7468, "text": " Add Notes" } ]
Solidity - Variables
Solidity supports three types of variables. State Variables − Variables whose values are permanently stored in a contract storage. State Variables − Variables whose values are permanently stored in a contract storage. Local Variables − Variables whose values are present till function is executing. Local Variables − Variables whose values are present till function is executing. Global Variables − Special variables exists in the global namespace used to get information about the blockchain. Global Variables − Special variables exists in the global namespace used to get information about the blockchain. Solidity is a statically typed language, which means that the state or local variable type needs to be specified during declaration. Each declared variable always have a default value based on its type. There is no concept of "undefined" or "null". Variables whose values are permanently stored in a contract storage. pragma solidity ^0.5.0; contract SolidityTest { uint storedData; // State variable constructor() public { storedData = 10; // Using State variable } } Variables whose values are available only within a function where it is defined. Function parameters are always local to that function. pragma solidity ^0.5.0; contract SolidityTest { uint storedData; // State variable constructor() public { storedData = 10; } function getResult() public view returns(uint){ uint a = 1; // local variable uint b = 2; uint result = a + b; return result; //access the local variable } } pragma solidity ^0.5.0; contract SolidityTest { uint storedData; // State variable constructor() public { storedData = 10; } function getResult() public view returns(uint){ uint a = 1; // local variable uint b = 2; uint result = a + b; return storedData; //access the state variable } } Run the above program using steps provided in Solidity First Application chapter. 0: uint256: 10 These are special variables which exist in global workspace and provide information about the blockchain and transaction properties. While naming your variables in Solidity, keep the following rules in mind. You should not use any of the Solidity reserved keywords as a variable name. These keywords are mentioned in the next section. For example, break or boolean variable names are not valid. You should not use any of the Solidity reserved keywords as a variable name. These keywords are mentioned in the next section. For example, break or boolean variable names are not valid. Solidity variable names should not start with a numeral (0-9). They must begin with a letter or an underscore character. For example, 123test is an invalid variable name but _123test is a valid one. Solidity variable names should not start with a numeral (0-9). They must begin with a letter or an underscore character. For example, 123test is an invalid variable name but _123test is a valid one. Solidity variable names are case-sensitive. For example, Name and name are two different variables. Solidity variable names are case-sensitive. For example, Name and name are two different variables. 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": 2599, "s": 2555, "text": "Solidity supports three types of variables." }, { "code": null, "e": 2686, "s": 2599, "text": "State Variables − Variables whose values are permanently stored in a contract storage." }, { "code": null, "e": 2773, "s": 2686, "text": "State Variables − Variables whose values are permanently stored in a contract storage." }, { "code": null, "e": 2854, "s": 2773, "text": "Local Variables − Variables whose values are present till function is executing." }, { "code": null, "e": 2935, "s": 2854, "text": "Local Variables − Variables whose values are present till function is executing." }, { "code": null, "e": 3049, "s": 2935, "text": "Global Variables − Special variables exists in the global namespace used to get information about the blockchain." }, { "code": null, "e": 3163, "s": 3049, "text": "Global Variables − Special variables exists in the global namespace used to get information about the blockchain." }, { "code": null, "e": 3412, "s": 3163, "text": "Solidity is a statically typed language, which means that the state or local variable type needs to be specified during declaration. Each declared variable always have a default value based on its type. There is no concept of \"undefined\" or \"null\"." }, { "code": null, "e": 3481, "s": 3412, "text": "Variables whose values are permanently stored in a contract storage." }, { "code": null, "e": 3654, "s": 3481, "text": "pragma solidity ^0.5.0;\ncontract SolidityTest {\n uint storedData; // State variable\n constructor() public {\n storedData = 10; // Using State variable\n }\n}" }, { "code": null, "e": 3790, "s": 3654, "text": "Variables whose values are available only within a function where it is defined. Function parameters are always local to that function." }, { "code": null, "e": 4121, "s": 3790, "text": "pragma solidity ^0.5.0;\ncontract SolidityTest {\n uint storedData; // State variable\n constructor() public {\n storedData = 10; \n }\n function getResult() public view returns(uint){\n uint a = 1; // local variable\n uint b = 2;\n uint result = a + b;\n return result; //access the local variable\n }\n}" }, { "code": null, "e": 4456, "s": 4121, "text": "pragma solidity ^0.5.0;\ncontract SolidityTest {\n uint storedData; // State variable\n constructor() public {\n storedData = 10; \n }\n function getResult() public view returns(uint){\n uint a = 1; // local variable\n uint b = 2;\n uint result = a + b;\n return storedData; //access the state variable\n }\n}" }, { "code": null, "e": 4538, "s": 4456, "text": "Run the above program using steps provided in Solidity First Application chapter." }, { "code": null, "e": 4554, "s": 4538, "text": "0: uint256: 10\n" }, { "code": null, "e": 4687, "s": 4554, "text": "These are special variables which exist in global workspace and provide information about the blockchain and transaction properties." }, { "code": null, "e": 4762, "s": 4687, "text": "While naming your variables in Solidity, keep the following rules in mind." }, { "code": null, "e": 4949, "s": 4762, "text": "You should not use any of the Solidity reserved keywords as a variable name. These keywords are mentioned in the next section. For example, break or boolean variable names are not valid." }, { "code": null, "e": 5136, "s": 4949, "text": "You should not use any of the Solidity reserved keywords as a variable name. These keywords are mentioned in the next section. For example, break or boolean variable names are not valid." }, { "code": null, "e": 5335, "s": 5136, "text": "Solidity variable names should not start with a numeral (0-9). They must begin with a letter or an underscore character. For example, 123test is an invalid variable name but _123test is a valid one." }, { "code": null, "e": 5534, "s": 5335, "text": "Solidity variable names should not start with a numeral (0-9). They must begin with a letter or an underscore character. For example, 123test is an invalid variable name but _123test is a valid one." }, { "code": null, "e": 5634, "s": 5534, "text": "Solidity variable names are case-sensitive. For example, Name and name are two different variables." }, { "code": null, "e": 5734, "s": 5634, "text": "Solidity variable names are case-sensitive. For example, Name and name are two different variables." }, { "code": null, "e": 5769, "s": 5734, "text": "\n 38 Lectures \n 4.5 hours \n" }, { "code": null, "e": 5786, "s": 5769, "text": " Abhilash Nelson" }, { "code": null, "e": 5821, "s": 5786, "text": "\n 62 Lectures \n 8.5 hours \n" }, { "code": null, "e": 5838, "s": 5821, "text": " Frahaan Hussain" }, { "code": null, "e": 5873, "s": 5838, "text": "\n 31 Lectures \n 3.5 hours \n" }, { "code": null, "e": 5887, "s": 5873, "text": " Swapnil Kole" }, { "code": null, "e": 5894, "s": 5887, "text": " Print" }, { "code": null, "e": 5905, "s": 5894, "text": " Add Notes" } ]
Materialize - Tabs
Materialize provides tabs CSS class to make a ul element as a tab. The following table mentions the available classes and their effects. tabs Identifies ul as a materialize tab component. Required for ul element. active Makes a tab active. Following is an example of using a tab. <!DOCTYPE html> <html> <head> <title>The Materialize Tabs Example</title> <meta name="viewport" content="width=device-width, initial-scale=1"> <link rel="stylesheet" href="https://fonts.googleapis.com/icon?family=Material+Icons"> <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/materialize/0.97.3/css/materialize.min.css"> <script type="text/javascript" src="https://code.jquery.com/jquery-2.1.1.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/materialize/0.97.3/js/materialize.min.js"></script> </head> <body class="container"> <h3>Tabs Demo</h3> <div class="row"> <div class="col s12"> <ul class="tabs"> <li class="tab col s3"><a href="#inbox">Inbox</a></li> <li class="tab col s3"><a class="active" href="#unread">Unread</a></li> <li class="tab col s3 disabled"><a href="#outbox">Outbox (Disabled)</a></li> <li class="tab col s3"><a href="#sent">Sent</a></li> </ul> </div> <div id="inbox" class="col s12">Inbox</div> <div id="unread" class="col s12">Unread</div> <div id="outbox" class="col s12">Outbox (Disabled)</div> <div id="sent" class="col s12">Sent</div> </div> </body> </html> Verify the output. Print Add Notes Bookmark this page
[ { "code": null, "e": 2324, "s": 2187, "text": "Materialize provides tabs CSS class to make a ul element as a tab. The following table mentions the available classes and their effects." }, { "code": null, "e": 2329, "s": 2324, "text": "tabs" }, { "code": null, "e": 2400, "s": 2329, "text": "Identifies ul as a materialize tab component. Required for ul element." }, { "code": null, "e": 2407, "s": 2400, "text": "active" }, { "code": null, "e": 2427, "s": 2407, "text": "Makes a tab active." }, { "code": null, "e": 2467, "s": 2427, "text": "Following is an example of using a tab." }, { "code": null, "e": 3825, "s": 2467, "text": "<!DOCTYPE html>\n<html>\n <head>\n <title>The Materialize Tabs Example</title>\n <meta name=\"viewport\" content=\"width=device-width, initial-scale=1\">\n <link rel=\"stylesheet\" href=\"https://fonts.googleapis.com/icon?family=Material+Icons\">\n <link rel=\"stylesheet\" href=\"https://cdnjs.cloudflare.com/ajax/libs/materialize/0.97.3/css/materialize.min.css\">\n <script type=\"text/javascript\" src=\"https://code.jquery.com/jquery-2.1.1.min.js\"></script>\n <script src=\"https://cdnjs.cloudflare.com/ajax/libs/materialize/0.97.3/js/materialize.min.js\"></script>\n </head>\n <body class=\"container\">\n <h3>Tabs Demo</h3>\n <div class=\"row\">\n <div class=\"col s12\">\n <ul class=\"tabs\">\n <li class=\"tab col s3\"><a href=\"#inbox\">Inbox</a></li>\n <li class=\"tab col s3\"><a class=\"active\" href=\"#unread\">Unread</a></li> \n <li class=\"tab col s3 disabled\"><a href=\"#outbox\">Outbox (Disabled)</a></li>\n <li class=\"tab col s3\"><a href=\"#sent\">Sent</a></li>\n </ul>\n </div>\n <div id=\"inbox\" class=\"col s12\">Inbox</div>\n <div id=\"unread\" class=\"col s12\">Unread</div>\n <div id=\"outbox\" class=\"col s12\">Outbox (Disabled)</div>\n <div id=\"sent\" class=\"col s12\">Sent</div>\n </div>\n </body>\n</html>" }, { "code": null, "e": 3844, "s": 3825, "text": "Verify the output." }, { "code": null, "e": 3851, "s": 3844, "text": " Print" }, { "code": null, "e": 3862, "s": 3851, "text": " Add Notes" } ]
Language Model Concept behind Word Suggestion Feature | by Vitou Phy | Towards Data Science
You may have seen word suggestion feature on your smartphone. As you type in one word, the keyboard understands what you are typing and suggests the next relevant word. If you select the suggested word, it will then suggest another one, and another and another until you end up having these funny sentences. This is a simple concept, known as language modeling. So what language modeling does is it reads the written text and it attempts to assign probability to the next word. Let’s look at an example. Intuitively, suppose we have 100 words to be considered for the next word, language model takes previous word into consideration and give probability to those 100 words. Then, it can give top 3 options to the users as part of word suggestion feature. Now, let’s give a formal definition to LM. Commonly, language model is known as a way to give probability to a sentence. But wait! Isn’t earlier we mentioned LM assign probability to the next word? Let’s break down the equation above to investigate this further. As you can see in Equation 1, LM not only can assign probability to the next word given but also can give the probability to the whole sentence. Then, the LM can understand which sentence might sound good and which might not. Awesome, right? But what’s under the hood of such awesome function? There are many ways to create this language model. In this post, we will explore a simple method, called n-gram. One key idea is ngram looks only at n words at a time. Let’s work with the example “the cat sat on the mat”. Suppose n=2 (also known as bigram), it will try to predict the second word based on the first one. For example: the cat: Bigram tries to remember that after “the”, it should be “cat”. cat sat: after “cat”, it should be “sat”. sat on: after “sat”, it’s “on” The same thing goes with n=3. For the words “the cat sat”, trigram knows “sat” comes after “the cat”. I guess you get the idea. This concept is scalable to n words (n-gram). So, how does ngram know all of these pattern? It’s probability theory. For simplicity, we will look the case of bigram. From the example above, we know that “cat” comes after “the”, which can be denoted as P(cat | the). P(cat | the) : the probability that the next word is “cat” given the word “the”. To compute this probability, simply use this the formula below. where c(the cat) is number of occurrence of “the cat” in the entire corpus. The same goes for c(the). Intuitively, this equation says that: Among all of the words “the”, how many of them are followed by “cat”? And voila, now we have P(cat | the). Bigram is simple and quite powerful but there are many cases it will fail to perform. For instance: In the beginning of the sentence, the model sees “the” followed by “cat”. If we use bigram and rely only on one previous word, it is very difficult to guess that the underline word is “mat” since it probably generates “cat” again. Fortunately, trigram or 4-gram can resolve this issue. i.e. If we see “sat on the”, it is more likely that the next word is “mat”. However, that does not mean the longer sequence we consider, the better the prediction. For 6-gram, for instance, it might not be very common to see the exact “the cat sat on the”. Thus, it is not very efficient. Most of the time, bigram and trigram are the common choices. There are also times where your dataset is small and 3-gram fails to recognize some exact words; thus, resulting in the probability of 0. That would make your entire 3-gram implementation not that useful anymore. Easily you can do a simple if-else, and use 2-gram in case 3-gram fails. Or use 1-gram in the case of 2-gram fails. There is called, back-off. Another technique, interpolation, is considering different ngrams at the same time. The idea is to give weight (λ) to your n-gram so your 3-gram model can also look at the value of 2-gram and 1-gram. i.e. 60% on 3-gram 35% on 2-gram 05% on 1-gram Config the weight manually until you feel it’s right. You can also use some automatic method, but we won’t go over that in this post. You can refer to this for further info on how to properly set these weights. Now let’s try to use this LM to generate a sentence based on random initial word. For this task, we will use Harry Potter and the Sorcerer’s Stone Movie Script to train our ngram. For the code below, you can find on this kernel as well. Then, we can count the frequency of unigram, bigram and trigram. This will be used later to compute probability. Now that we can the count of the n-gram, we can compute its probability. We will use linear interpolation of 0.01, 0.4, and 0.5 respectively for 1-gram, 2-gram and 3-gram. Let’s attempt to generate 20 words. The initial will be randomized, and choose the best next word. So, how will this perform? Below are the results of each generation. Generation #1:protecting the stone , but i think i 'll be a wizard . . . . . . . .Generation #2:platform 9 3/4 ? think you 're going to be the same . . . . . . . Generation #3:sacrifice himself , he 's got a little bit . . . . . . . . . . . N-gram is a simple yet powerful technique to do language modeling by just looking at 2 to 3 words. It is quite practical in many applications, for instance, word suggestion on mobile device, thanks to its easy and fast in computation. N-gram, however, is not robust when it comes to generating long sentence where the current word depends on the very first word in the sentence. This long term dependency is more suitable for the model like neural network, but that is a topic for later post.
[ { "code": null, "e": 479, "s": 171, "text": "You may have seen word suggestion feature on your smartphone. As you type in one word, the keyboard understands what you are typing and suggests the next relevant word. If you select the suggested word, it will then suggest another one, and another and another until you end up having these funny sentences." }, { "code": null, "e": 675, "s": 479, "text": "This is a simple concept, known as language modeling. So what language modeling does is it reads the written text and it attempts to assign probability to the next word. Let’s look at an example." }, { "code": null, "e": 969, "s": 675, "text": "Intuitively, suppose we have 100 words to be considered for the next word, language model takes previous word into consideration and give probability to those 100 words. Then, it can give top 3 options to the users as part of word suggestion feature. Now, let’s give a formal definition to LM." }, { "code": null, "e": 1047, "s": 969, "text": "Commonly, language model is known as a way to give probability to a sentence." }, { "code": null, "e": 1189, "s": 1047, "text": "But wait! Isn’t earlier we mentioned LM assign probability to the next word? Let’s break down the equation above to investigate this further." }, { "code": null, "e": 1415, "s": 1189, "text": "As you can see in Equation 1, LM not only can assign probability to the next word given but also can give the probability to the whole sentence. Then, the LM can understand which sentence might sound good and which might not." }, { "code": null, "e": 1596, "s": 1415, "text": "Awesome, right? But what’s under the hood of such awesome function? There are many ways to create this language model. In this post, we will explore a simple method, called n-gram." }, { "code": null, "e": 1705, "s": 1596, "text": "One key idea is ngram looks only at n words at a time. Let’s work with the example “the cat sat on the mat”." }, { "code": null, "e": 1817, "s": 1705, "text": "Suppose n=2 (also known as bigram), it will try to predict the second word based on the first one. For example:" }, { "code": null, "e": 1889, "s": 1817, "text": "the cat: Bigram tries to remember that after “the”, it should be “cat”." }, { "code": null, "e": 1931, "s": 1889, "text": "cat sat: after “cat”, it should be “sat”." }, { "code": null, "e": 1962, "s": 1931, "text": "sat on: after “sat”, it’s “on”" }, { "code": null, "e": 2090, "s": 1962, "text": "The same thing goes with n=3. For the words “the cat sat”, trigram knows “sat” comes after “the cat”. I guess you get the idea." }, { "code": null, "e": 2207, "s": 2090, "text": "This concept is scalable to n words (n-gram). So, how does ngram know all of these pattern? It’s probability theory." }, { "code": null, "e": 2356, "s": 2207, "text": "For simplicity, we will look the case of bigram. From the example above, we know that “cat” comes after “the”, which can be denoted as P(cat | the)." }, { "code": null, "e": 2437, "s": 2356, "text": "P(cat | the) : the probability that the next word is “cat” given the word “the”." }, { "code": null, "e": 2501, "s": 2437, "text": "To compute this probability, simply use this the formula below." }, { "code": null, "e": 2748, "s": 2501, "text": "where c(the cat) is number of occurrence of “the cat” in the entire corpus. The same goes for c(the). Intuitively, this equation says that: Among all of the words “the”, how many of them are followed by “cat”? And voila, now we have P(cat | the)." }, { "code": null, "e": 2848, "s": 2748, "text": "Bigram is simple and quite powerful but there are many cases it will fail to perform. For instance:" }, { "code": null, "e": 3210, "s": 2848, "text": "In the beginning of the sentence, the model sees “the” followed by “cat”. If we use bigram and rely only on one previous word, it is very difficult to guess that the underline word is “mat” since it probably generates “cat” again. Fortunately, trigram or 4-gram can resolve this issue. i.e. If we see “sat on the”, it is more likely that the next word is “mat”." }, { "code": null, "e": 3423, "s": 3210, "text": "However, that does not mean the longer sequence we consider, the better the prediction. For 6-gram, for instance, it might not be very common to see the exact “the cat sat on the”. Thus, it is not very efficient." }, { "code": null, "e": 3484, "s": 3423, "text": "Most of the time, bigram and trigram are the common choices." }, { "code": null, "e": 3697, "s": 3484, "text": "There are also times where your dataset is small and 3-gram fails to recognize some exact words; thus, resulting in the probability of 0. That would make your entire 3-gram implementation not that useful anymore." }, { "code": null, "e": 3840, "s": 3697, "text": "Easily you can do a simple if-else, and use 2-gram in case 3-gram fails. Or use 1-gram in the case of 2-gram fails. There is called, back-off." }, { "code": null, "e": 4045, "s": 3840, "text": "Another technique, interpolation, is considering different ngrams at the same time. The idea is to give weight (λ) to your n-gram so your 3-gram model can also look at the value of 2-gram and 1-gram. i.e." }, { "code": null, "e": 4059, "s": 4045, "text": "60% on 3-gram" }, { "code": null, "e": 4073, "s": 4059, "text": "35% on 2-gram" }, { "code": null, "e": 4087, "s": 4073, "text": "05% on 1-gram" }, { "code": null, "e": 4298, "s": 4087, "text": "Config the weight manually until you feel it’s right. You can also use some automatic method, but we won’t go over that in this post. You can refer to this for further info on how to properly set these weights." }, { "code": null, "e": 4535, "s": 4298, "text": "Now let’s try to use this LM to generate a sentence based on random initial word. For this task, we will use Harry Potter and the Sorcerer’s Stone Movie Script to train our ngram. For the code below, you can find on this kernel as well." }, { "code": null, "e": 4648, "s": 4535, "text": "Then, we can count the frequency of unigram, bigram and trigram. This will be used later to compute probability." }, { "code": null, "e": 4820, "s": 4648, "text": "Now that we can the count of the n-gram, we can compute its probability. We will use linear interpolation of 0.01, 0.4, and 0.5 respectively for 1-gram, 2-gram and 3-gram." }, { "code": null, "e": 4919, "s": 4820, "text": "Let’s attempt to generate 20 words. The initial will be randomized, and choose the best next word." }, { "code": null, "e": 4988, "s": 4919, "text": "So, how will this perform? Below are the results of each generation." }, { "code": null, "e": 5229, "s": 4988, "text": "Generation #1:protecting the stone , but i think i 'll be a wizard . . . . . . . .Generation #2:platform 9 3/4 ? think you 're going to be the same . . . . . . . Generation #3:sacrifice himself , he 's got a little bit . . . . . . . . . . ." } ]
How To Manually Order Boxplot in Seaborn? - GeeksforGeeks
04 Oct, 2021 Seaborn is an amazing visualization library for statistical graphics plotting in Python. It provides beautiful default styles and color palettes to make statistical plots more attractive. It is built on the top of matplotlib library and also closely integrated into the data structures from pandas.Seaborn aims to make visualization of the central part of exploring and understanding data. It provides dataset-oriented APIs, so that we can switch between different visual representations for the same variables for a better understanding of the dataset. Box Plot is the visual representation of the depicting groups of numerical data through their quartiles. Boxplot is also used for detecting the outlier in the data set. It captures the summary of the data efficiently with a simple box and whiskers and allows us to compare easily across groups. Boxplot summarizes sample data using 25th, 50th, and 75th percentiles. These percentiles are also known as the lower quartile, median and upper quartile. In this article, we will discuss how to order a boxplot manually. The dataset used in the below example is https://www.kaggle.com/ranjeetjain3/seaborn-tips-dataset Import libraries Python3 # import required modulesimport pandas as pdimport numpy as npimport matplotlib.pyplot as pltimport seaborn as sns Load dataset Python3 # load datasettips= sns.load_dataset('tips') # display top most rowstips.head() Output: Plot the boxplot. Python3 # illustrate box plotfx = sns.boxplot(x='day', y='total_bill', data=tips, hue='sex', palette='Set2') Output: Plotting the boxplot using seaborn. See the difference in the order of the above figure and after setting the order as per our needs. Palette will change the color of the graph (you can try Set1 and Set3 as well) Python3 # illustrating box plot with orderfx = sns.boxplot(x='day', y='total_bill', data=tips, order=[ 'Sun', 'Sat', 'Fri', 'Thur'], hue='sex', palette='Set2') Output: Both graphs together: Below is the complete program based on the above approach: Example 1 Python3 # import required modulesimport pandas as pdimport numpy as npimport matplotlib.pyplot as pltimport seaborn as sns # load datasettips= sns.load_dataset('tips') # display top most rowstips.head() # illustrating box plot with ordersns.boxplot(x='day', y='total_bill', data=tips, order=[ 'Sun', 'Sat', 'Fri', 'Thur'], hue='sex', palette='Set2') Output: Example 2 Now, Plotting the boxplot using different features. Observe the order on the x-axis in the figure given below: Python3 # import required modulesimport pandas as pdimport numpy as npimport matplotlib.pyplot as pltimport seaborn as sns # load datasettips = sns.load_dataset('tips') # display top most rowstips.head() # plotting the boxplot taking time on x-axisfx = sns.boxplot(x="time", y="total_bill", hue="smoker", data=tips, palette="Set1") # illustrating box plot with orderax = sns.boxplot(x="time", y="total_bill", hue="smoker", order=['Dinner', 'Lunch'], data=tips, palette="Set1") Output: Before- After- Here we have manually ordered the boxplot. sweetyty Python-Seaborn Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Adding new column to existing DataFrame in Pandas How to get column names in Pandas dataframe Python Dictionary Python map() function Taking input in Python Defaultdict in Python Read JSON file using Python Enumerate() in Python Iterate over a list in Python Different ways to create Pandas Dataframe
[ { "code": null, "e": 26369, "s": 26341, "text": "\n04 Oct, 2021" }, { "code": null, "e": 26923, "s": 26369, "text": "Seaborn is an amazing visualization library for statistical graphics plotting in Python. It provides beautiful default styles and color palettes to make statistical plots more attractive. It is built on the top of matplotlib library and also closely integrated into the data structures from pandas.Seaborn aims to make visualization of the central part of exploring and understanding data. It provides dataset-oriented APIs, so that we can switch between different visual representations for the same variables for a better understanding of the dataset." }, { "code": null, "e": 27372, "s": 26923, "text": "Box Plot is the visual representation of the depicting groups of numerical data through their quartiles. Boxplot is also used for detecting the outlier in the data set. It captures the summary of the data efficiently with a simple box and whiskers and allows us to compare easily across groups. Boxplot summarizes sample data using 25th, 50th, and 75th percentiles. These percentiles are also known as the lower quartile, median and upper quartile." }, { "code": null, "e": 27438, "s": 27372, "text": "In this article, we will discuss how to order a boxplot manually." }, { "code": null, "e": 27536, "s": 27438, "text": "The dataset used in the below example is https://www.kaggle.com/ranjeetjain3/seaborn-tips-dataset" }, { "code": null, "e": 27553, "s": 27536, "text": "Import libraries" }, { "code": null, "e": 27561, "s": 27553, "text": "Python3" }, { "code": "# import required modulesimport pandas as pdimport numpy as npimport matplotlib.pyplot as pltimport seaborn as sns", "e": 27676, "s": 27561, "text": null }, { "code": null, "e": 27692, "s": 27679, "text": "Load dataset" }, { "code": null, "e": 27700, "s": 27692, "text": "Python3" }, { "code": "# load datasettips= sns.load_dataset('tips') # display top most rowstips.head() ", "e": 27801, "s": 27700, "text": null }, { "code": null, "e": 27809, "s": 27801, "text": "Output:" }, { "code": null, "e": 27827, "s": 27809, "text": "Plot the boxplot." }, { "code": null, "e": 27835, "s": 27827, "text": "Python3" }, { "code": "# illustrate box plotfx = sns.boxplot(x='day', y='total_bill', data=tips, hue='sex', palette='Set2')", "e": 27936, "s": 27835, "text": null }, { "code": null, "e": 27944, "s": 27936, "text": "Output:" }, { "code": null, "e": 28157, "s": 27944, "text": "Plotting the boxplot using seaborn. See the difference in the order of the above figure and after setting the order as per our needs. Palette will change the color of the graph (you can try Set1 and Set3 as well)" }, { "code": null, "e": 28165, "s": 28157, "text": "Python3" }, { "code": "# illustrating box plot with orderfx = sns.boxplot(x='day', y='total_bill', data=tips, order=[ 'Sun', 'Sat', 'Fri', 'Thur'], hue='sex', palette='Set2')", "e": 28333, "s": 28165, "text": null }, { "code": null, "e": 28341, "s": 28333, "text": "Output:" }, { "code": null, "e": 28363, "s": 28341, "text": "Both graphs together:" }, { "code": null, "e": 28422, "s": 28363, "text": "Below is the complete program based on the above approach:" }, { "code": null, "e": 28432, "s": 28422, "text": "Example 1" }, { "code": null, "e": 28440, "s": 28432, "text": "Python3" }, { "code": "# import required modulesimport pandas as pdimport numpy as npimport matplotlib.pyplot as pltimport seaborn as sns # load datasettips= sns.load_dataset('tips') # display top most rowstips.head() # illustrating box plot with ordersns.boxplot(x='day', y='total_bill', data=tips, order=[ 'Sun', 'Sat', 'Fri', 'Thur'], hue='sex', palette='Set2')", "e": 28822, "s": 28440, "text": null }, { "code": null, "e": 28830, "s": 28822, "text": "Output:" }, { "code": null, "e": 28840, "s": 28830, "text": "Example 2" }, { "code": null, "e": 28953, "s": 28840, "text": "Now, Plotting the boxplot using different features. Observe the order on the x-axis in the figure given below: " }, { "code": null, "e": 28961, "s": 28953, "text": "Python3" }, { "code": "# import required modulesimport pandas as pdimport numpy as npimport matplotlib.pyplot as pltimport seaborn as sns # load datasettips = sns.load_dataset('tips') # display top most rowstips.head() # plotting the boxplot taking time on x-axisfx = sns.boxplot(x=\"time\", y=\"total_bill\", hue=\"smoker\", data=tips, palette=\"Set1\") # illustrating box plot with orderax = sns.boxplot(x=\"time\", y=\"total_bill\", hue=\"smoker\", order=['Dinner', 'Lunch'], data=tips, palette=\"Set1\")", "e": 29465, "s": 28961, "text": null }, { "code": null, "e": 29473, "s": 29465, "text": "Output:" }, { "code": null, "e": 29481, "s": 29473, "text": "Before-" }, { "code": null, "e": 29488, "s": 29481, "text": "After-" }, { "code": null, "e": 29531, "s": 29488, "text": "Here we have manually ordered the boxplot." }, { "code": null, "e": 29540, "s": 29531, "text": "sweetyty" }, { "code": null, "e": 29555, "s": 29540, "text": "Python-Seaborn" }, { "code": null, "e": 29562, "s": 29555, "text": "Python" }, { "code": null, "e": 29660, "s": 29562, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 29669, "s": 29660, "text": "Comments" }, { "code": null, "e": 29682, "s": 29669, "text": "Old Comments" }, { "code": null, "e": 29732, "s": 29682, "text": "Adding new column to existing DataFrame in Pandas" }, { "code": null, "e": 29776, "s": 29732, "text": "How to get column names in Pandas dataframe" }, { "code": null, "e": 29794, "s": 29776, "text": "Python Dictionary" }, { "code": null, "e": 29816, "s": 29794, "text": "Python map() function" }, { "code": null, "e": 29839, "s": 29816, "text": "Taking input in Python" }, { "code": null, "e": 29861, "s": 29839, "text": "Defaultdict in Python" }, { "code": null, "e": 29889, "s": 29861, "text": "Read JSON file using Python" }, { "code": null, "e": 29911, "s": 29889, "text": "Enumerate() in Python" }, { "code": null, "e": 29941, "s": 29911, "text": "Iterate over a list in Python" } ]
DB2 - Triggers
This chapter describes triggers, their types, creation and dropping of the triggers. A trigger is a set of actions, which are performed for responding to an INSERT, UPDATE or DELETE operation on a specified table in the database. Triggers are stored in the database at once. They handle governance of data. They can be accessed and shared among multiple applications. The advantage of using triggers is, if any change needs to be done in the application, it is done at the trigger; instead of changing each application that is accessing the trigger. Triggers are easy to maintain and they enforce faster application development. Triggers are defined using an SQL statement “CREATE TRIGGER”. There are two types of triggers: They are executed before any SQL operation. They are executed after any SQL operation. Let us see how to create a sequence of trigger: Syntax: db2 create sequence <seq_name> Example: Creating a sequence of triggers for table shopper.sales1 db2 create sequence sales1_seq as int start with 1 increment by 1 Syntax: db2 create trigger <trigger_name> no cascade before insert on <table_name> referencing new as <table_object> for each row set <table_object>.<col_name>=nextval for <sequence_name> Example: Creating trigger for shopper.sales1 table to insert primary key numbers automatically db2 create trigger sales1_trigger no cascade before insert on shopper.sales1 referencing new as obj for each row set obj.id=nextval for sales1_seq Now try inserting any values: db2 insert into shopper.sales1(itemname, qty, price) values('bicks', 100, 24.00) Let us see how to retrieve values from a table: Syntax: db2 select * from <tablename> Example: db2 select * from shopper.sales1 Output: ID ITEMNAME QTY ------- ------------ ---------- 3 bicks 100 2 bread 100 2 record(s) selected. Let us see how to create an after trigger: Syntax: db2 create trigger <trigger_name> no cascade before insert on <table_name> referencing new as <table_object> for each row set <table_object>.<col_name>=nextval for <sequence_name> Example: [To insert and retrieve the values] db2 create trigger sales1_tri_after after insert on shopper.sales1 for each row mode db2sql begin atomic update shopper.sales1 set price=qty*price; end Output: //inseting values in shopper.sales1 db2 insert into shopper.sales1(itemname,qty,price) values('chiken',100,124.00) //output ID ITEMNAME QTY PRICE ----- -------------- ----------- ----------- 3 bicks 100 2400.00 4 chiken 100 12400.00 2 bread 100 2400.00 3 record(s) selected. Here is how a database trigger is dropped: Syntax: db2 drop trigger <trigger_name> Example: db2 drop trigger slaes1_trigger 10 Lectures 1.5 hours Nishant Malik 41 Lectures 8.5 hours Parth Panjabi 53 Lectures 11.5 hours Parth Panjabi 33 Lectures 7 hours Parth Panjabi 44 Lectures 3 hours Arnab Chakraborty 178 Lectures 14.5 hours Arnab Chakraborty Print Add Notes Bookmark this page
[ { "code": null, "e": 2013, "s": 1928, "text": "This chapter describes triggers, their types, creation and dropping of the triggers." }, { "code": null, "e": 2619, "s": 2013, "text": "A trigger is a set of actions, which are performed for responding to an INSERT, UPDATE or DELETE operation on a specified table in the database. Triggers are stored in the database at once. They handle governance of data. They can be accessed and shared among multiple applications. The advantage of using triggers is, if any change needs to be done in the application, it is done at the trigger; instead of changing each application that is accessing the trigger. Triggers are easy to maintain and they enforce faster application development. Triggers are defined using an SQL statement “CREATE TRIGGER”." }, { "code": null, "e": 2652, "s": 2619, "text": "There are two types of triggers:" }, { "code": null, "e": 2696, "s": 2652, "text": "They are executed before any SQL operation." }, { "code": null, "e": 2739, "s": 2696, "text": "They are executed after any SQL operation." }, { "code": null, "e": 2787, "s": 2739, "text": "Let us see how to create a sequence of trigger:" }, { "code": null, "e": 2795, "s": 2787, "text": "Syntax:" }, { "code": null, "e": 2827, "s": 2795, "text": "db2 create sequence <seq_name> " }, { "code": null, "e": 2893, "s": 2827, "text": "Example: Creating a sequence of triggers for table shopper.sales1" }, { "code": null, "e": 2960, "s": 2893, "text": "db2 create sequence sales1_seq as int start with 1 increment by 1 " }, { "code": null, "e": 2968, "s": 2960, "text": "Syntax:" }, { "code": null, "e": 3151, "s": 2968, "text": "db2 create trigger <trigger_name> no cascade before insert on \n<table_name> referencing new as <table_object> for each row set \n<table_object>.<col_name>=nextval for <sequence_name> " }, { "code": null, "e": 3246, "s": 3151, "text": "Example: Creating trigger for shopper.sales1 table to insert primary key numbers automatically" }, { "code": null, "e": 3395, "s": 3246, "text": "db2 create trigger sales1_trigger no cascade before insert on \nshopper.sales1 referencing new as obj for each row set \nobj.id=nextval for sales1_seq" }, { "code": null, "e": 3425, "s": 3395, "text": "Now try inserting any values:" }, { "code": null, "e": 3508, "s": 3425, "text": "db2 insert into shopper.sales1(itemname, qty, price) \nvalues('bicks', 100, 24.00) " }, { "code": null, "e": 3556, "s": 3508, "text": "Let us see how to retrieve values from a table:" }, { "code": null, "e": 3564, "s": 3556, "text": "Syntax:" }, { "code": null, "e": 3594, "s": 3564, "text": "db2 select * from <tablename>" }, { "code": null, "e": 3603, "s": 3594, "text": "Example:" }, { "code": null, "e": 3636, "s": 3603, "text": "db2 select * from shopper.sales1" }, { "code": null, "e": 3644, "s": 3636, "text": "Output:" }, { "code": null, "e": 3805, "s": 3644, "text": " ID ITEMNAME QTY \n------- ------------ ---------- \n 3 bicks 100 \n 2 bread 100 \n \n 2 record(s) selected. " }, { "code": null, "e": 3848, "s": 3805, "text": "Let us see how to create an after trigger:" }, { "code": null, "e": 3856, "s": 3848, "text": "Syntax:" }, { "code": null, "e": 4039, "s": 3856, "text": "db2 create trigger <trigger_name> no cascade before insert on \n<table_name> referencing new as <table_object> for each row set\n <table_object>.<col_name>=nextval for <sequence_name> " }, { "code": null, "e": 4084, "s": 4039, "text": "Example: [To insert and retrieve the values]" }, { "code": null, "e": 4240, "s": 4084, "text": "db2 create trigger sales1_tri_after after insert on shopper.sales1 \nfor each row mode db2sql begin atomic update shopper.sales1 \nset price=qty*price; end " }, { "code": null, "e": 4248, "s": 4240, "text": "Output:" }, { "code": null, "e": 4635, "s": 4248, "text": "//inseting values in shopper.sales1 \ndb2 insert into shopper.sales1(itemname,qty,price) \nvalues('chiken',100,124.00) \n//output \nID ITEMNAME QTY PRICE \n----- -------------- ----------- ----------- \n 3 bicks 100 2400.00 \n 4 chiken 100 12400.00 \n 2 bread 100 2400.00 \n\n\t3 record(s) selected. " }, { "code": null, "e": 4678, "s": 4635, "text": "Here is how a database trigger is dropped:" }, { "code": null, "e": 4686, "s": 4678, "text": "Syntax:" }, { "code": null, "e": 4720, "s": 4686, "text": "db2 drop trigger <trigger_name> " }, { "code": null, "e": 4729, "s": 4720, "text": "Example:" }, { "code": null, "e": 4764, "s": 4729, "text": "db2 drop trigger slaes1_trigger " }, { "code": null, "e": 4799, "s": 4764, "text": "\n 10 Lectures \n 1.5 hours \n" }, { "code": null, "e": 4814, "s": 4799, "text": " Nishant Malik" }, { "code": null, "e": 4849, "s": 4814, "text": "\n 41 Lectures \n 8.5 hours \n" }, { "code": null, "e": 4864, "s": 4849, "text": " Parth Panjabi" }, { "code": null, "e": 4900, "s": 4864, "text": "\n 53 Lectures \n 11.5 hours \n" }, { "code": null, "e": 4915, "s": 4900, "text": " Parth Panjabi" }, { "code": null, "e": 4948, "s": 4915, "text": "\n 33 Lectures \n 7 hours \n" }, { "code": null, "e": 4963, "s": 4948, "text": " Parth Panjabi" }, { "code": null, "e": 4996, "s": 4963, "text": "\n 44 Lectures \n 3 hours \n" }, { "code": null, "e": 5015, "s": 4996, "text": " Arnab Chakraborty" }, { "code": null, "e": 5052, "s": 5015, "text": "\n 178 Lectures \n 14.5 hours \n" }, { "code": null, "e": 5071, "s": 5052, "text": " Arnab Chakraborty" }, { "code": null, "e": 5078, "s": 5071, "text": " Print" }, { "code": null, "e": 5089, "s": 5078, "text": " Add Notes" } ]
Choose the Suitable Transformer Framework for Your Needs | by Xu LIANG | Towards Data Science
Based on your preference for PyTroch or TensorFlow, I recommend using Fairseq or Tensor2Tensor. If you are a researcher, Fairseq is flexible enough for customization. But if you are working on some real application and considering deployment, it would be better to choose Tensor2Tensor. A sequence modeling toolkit that allows researchers and developers to train custom models for translation, summarization, language modeling and other text generation tasks. Transformer (self-attention) networks: Vaswani et al. (2017): Attention Is All You Need Ott et al. (2018): Scaling Neural Machine Translation Edunov et al. (2018): Understanding Back-Translation at Scale New Baevski and Auli (2018): Adaptive Input Representations for Neural Language Modeling New Shen et al. (2019): Mixture Models for Diverse Machine Translation: Tricks of the Trade We can use encoder and decoder easily. class fairseq.models.transformer.TransformerModel(encoder, decoder) Transformer model from “Attention Is All You Need” (Vaswani, et al, 2017). Parameters: encoder (TransformerEncoder) — the encoder decoder (TransformerDecoder) — the decoder Library of deep learning models and datasets designed to make deep learning more accessible and accelerate ML research. You can try solving the problem with different transformer models and hyperparameters as described in the paper: Standard transformer: --model=transformer --hparams_set=transformer_tiny Universal transformer: --model=universal_transformer --hparams_set=universal_transformer_tiny Adaptive universal transformer: --model=universal_transformer --hparams_set=adaptive_universal_transformer_tiny Here is a walkthrough to implement the Transformer model from Attention Is All You Need on WMT data. An open-source (MIT) neural machine translation system. It is designed to be research friendly to try out new ideas in translation, summary, image-to-text, morphology, and many other domains. OpenNMT provides implementations in 2 popular deep learning frameworks: OpenNMT-py Extensible and fast implementation benefiting from PyTorch ease of use. Documentation Pretrained models The transformer implementation code OpenNMT-tf Modular and stable implementation relying on the TensorFlow ecosystem. Documentation Pretrained models AllenNLP An Apache 2.0 NLP research library, built on PyTorch, for developing state-of-the-art deep learning models on a wide variety of linguistic tasks. AllenNLP supports a Transformer encoder, which is implemented as StackedSelfAttentionEncoder encoder = StackedSelfAttentionEncoder( input_dim=EN_EMBEDDING_DIM, hidden_dim=HIDDEN_DIM, projection_dim=128, feedforward_hidden_dim=128, num_layers=1, num_attention_heads=8) Recommend reading: Building Seq2Seq Machine Translation Models using AllenNLP PaddlePaddle (PArallel Distributed Deep LEarning) is an easy-to-use, efficient, flexible and scalable deep learning platform, which is originally developed by Baidu scientists and engineers for the purpose of applying deep learning to many products at Baidu. Implementation of the Transformer model in “Attention is All You Need”: English, Chinese Sequence-to-sequence framework with a focus on Neural Machine Translation based on Apache MXNet. Transformer Models with self-attention Vaswani et al ’17, Implementation Lingvo is a framework for building neural networks in Tensorflow, particularly sequence models. A widely used backend framework can assure that your model might be used by many people. And if there is some organization behind the frameworks, it is very possible that this framework can exist in a long time. So I collect the related information. The reader who might see this article mainly research and engineer. So I focus on the debug and deployment in the pros and cons. Based on your preference for PyTroch or TensorFlow, I recommend using Fairseq or Tensor2Tensor. If you are a researcher, Fairseq is flexible enough for customization. But if you are working on some real application and considering deployment, it would be better to choose Tensor2Tensor. Check out my other posts on Medium with a categorized view!GitHub: BrambleXuLinkedIn: Xu LiangBlog: BrambleXu
[ { "code": null, "e": 268, "s": 172, "text": "Based on your preference for PyTroch or TensorFlow, I recommend using Fairseq or Tensor2Tensor." }, { "code": null, "e": 459, "s": 268, "text": "If you are a researcher, Fairseq is flexible enough for customization. But if you are working on some real application and considering deployment, it would be better to choose Tensor2Tensor." }, { "code": null, "e": 632, "s": 459, "text": "A sequence modeling toolkit that allows researchers and developers to train custom models for translation, summarization, language modeling and other text generation tasks." }, { "code": null, "e": 671, "s": 632, "text": "Transformer (self-attention) networks:" }, { "code": null, "e": 720, "s": 671, "text": "Vaswani et al. (2017): Attention Is All You Need" }, { "code": null, "e": 774, "s": 720, "text": "Ott et al. (2018): Scaling Neural Machine Translation" }, { "code": null, "e": 836, "s": 774, "text": "Edunov et al. (2018): Understanding Back-Translation at Scale" }, { "code": null, "e": 925, "s": 836, "text": "New Baevski and Auli (2018): Adaptive Input Representations for Neural Language Modeling" }, { "code": null, "e": 1017, "s": 925, "text": "New Shen et al. (2019): Mixture Models for Diverse Machine Translation: Tricks of the Trade" }, { "code": null, "e": 1056, "s": 1017, "text": "We can use encoder and decoder easily." }, { "code": null, "e": 1124, "s": 1056, "text": "class fairseq.models.transformer.TransformerModel(encoder, decoder)" }, { "code": null, "e": 1199, "s": 1124, "text": "Transformer model from “Attention Is All You Need” (Vaswani, et al, 2017)." }, { "code": null, "e": 1211, "s": 1199, "text": "Parameters:" }, { "code": null, "e": 1254, "s": 1211, "text": "encoder (TransformerEncoder) — the encoder" }, { "code": null, "e": 1297, "s": 1254, "text": "decoder (TransformerDecoder) — the decoder" }, { "code": null, "e": 1417, "s": 1297, "text": "Library of deep learning models and datasets designed to make deep learning more accessible and accelerate ML research." }, { "code": null, "e": 1530, "s": 1417, "text": "You can try solving the problem with different transformer models and hyperparameters as described in the paper:" }, { "code": null, "e": 1603, "s": 1530, "text": "Standard transformer: --model=transformer --hparams_set=transformer_tiny" }, { "code": null, "e": 1697, "s": 1603, "text": "Universal transformer: --model=universal_transformer --hparams_set=universal_transformer_tiny" }, { "code": null, "e": 1809, "s": 1697, "text": "Adaptive universal transformer: --model=universal_transformer --hparams_set=adaptive_universal_transformer_tiny" }, { "code": null, "e": 1910, "s": 1809, "text": "Here is a walkthrough to implement the Transformer model from Attention Is All You Need on WMT data." }, { "code": null, "e": 2102, "s": 1910, "text": "An open-source (MIT) neural machine translation system. It is designed to be research friendly to try out new ideas in translation, summary, image-to-text, morphology, and many other domains." }, { "code": null, "e": 2174, "s": 2102, "text": "OpenNMT provides implementations in 2 popular deep learning frameworks:" }, { "code": null, "e": 2185, "s": 2174, "text": "OpenNMT-py" }, { "code": null, "e": 2257, "s": 2185, "text": "Extensible and fast implementation benefiting from PyTorch ease of use." }, { "code": null, "e": 2271, "s": 2257, "text": "Documentation" }, { "code": null, "e": 2289, "s": 2271, "text": "Pretrained models" }, { "code": null, "e": 2325, "s": 2289, "text": "The transformer implementation code" }, { "code": null, "e": 2336, "s": 2325, "text": "OpenNMT-tf" }, { "code": null, "e": 2407, "s": 2336, "text": "Modular and stable implementation relying on the TensorFlow ecosystem." }, { "code": null, "e": 2421, "s": 2407, "text": "Documentation" }, { "code": null, "e": 2439, "s": 2421, "text": "Pretrained models" }, { "code": null, "e": 2448, "s": 2439, "text": "AllenNLP" }, { "code": null, "e": 2594, "s": 2448, "text": "An Apache 2.0 NLP research library, built on PyTorch, for developing state-of-the-art deep learning models on a wide variety of linguistic tasks." }, { "code": null, "e": 2687, "s": 2594, "text": "AllenNLP supports a Transformer encoder, which is implemented as StackedSelfAttentionEncoder" }, { "code": null, "e": 2886, "s": 2687, "text": "encoder = StackedSelfAttentionEncoder( input_dim=EN_EMBEDDING_DIM, hidden_dim=HIDDEN_DIM, projection_dim=128, feedforward_hidden_dim=128, num_layers=1, num_attention_heads=8)" }, { "code": null, "e": 2964, "s": 2886, "text": "Recommend reading: Building Seq2Seq Machine Translation Models using AllenNLP" }, { "code": null, "e": 3223, "s": 2964, "text": "PaddlePaddle (PArallel Distributed Deep LEarning) is an easy-to-use, efficient, flexible and scalable deep learning platform, which is originally developed by Baidu scientists and engineers for the purpose of applying deep learning to many products at Baidu." }, { "code": null, "e": 3312, "s": 3223, "text": "Implementation of the Transformer model in “Attention is All You Need”: English, Chinese" }, { "code": null, "e": 3409, "s": 3312, "text": "Sequence-to-sequence framework with a focus on Neural Machine Translation based on Apache MXNet." }, { "code": null, "e": 3482, "s": 3409, "text": "Transformer Models with self-attention Vaswani et al ’17, Implementation" }, { "code": null, "e": 3578, "s": 3482, "text": "Lingvo is a framework for building neural networks in Tensorflow, particularly sequence models." }, { "code": null, "e": 3828, "s": 3578, "text": "A widely used backend framework can assure that your model might be used by many people. And if there is some organization behind the frameworks, it is very possible that this framework can exist in a long time. So I collect the related information." }, { "code": null, "e": 3957, "s": 3828, "text": "The reader who might see this article mainly research and engineer. So I focus on the debug and deployment in the pros and cons." }, { "code": null, "e": 4244, "s": 3957, "text": "Based on your preference for PyTroch or TensorFlow, I recommend using Fairseq or Tensor2Tensor. If you are a researcher, Fairseq is flexible enough for customization. But if you are working on some real application and considering deployment, it would be better to choose Tensor2Tensor." } ]
How do I hide and show a menu item in the Android ActionBar?
This example demonstrates how do I hide and show a menu item in the Android ActionBar. 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: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"> <ToggleButton android:id="@+id/btnMenuItem" android:layout_width="match_parent" android:layout_height="wrap_content" /> </LinearLayout> Step 3 − Add the following code to src/MainActivity.java import androidx.appcompat.app.AppCompatActivity; import android.os.Bundle; import android.view.Menu; import android.view.MenuInflater; import android.view.MenuItem; import android.widget.CompoundButton; import android.widget.ToggleButton; public class MainActivity extends AppCompatActivity { ToggleButton button1; Menu myMenu; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); button1 = findViewById(R.id.btnMenuItem); button1.setOnCheckedChangeListener(onCheckedChangeListener); } CompoundButton.OnCheckedChangeListener onCheckedChangeListener = new CompoundButton.OnCheckedChangeListener() { @Override public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) { if(myMenu != null) { if (buttonView == button1) { myMenu.findItem(R.id.menu_action_share).setVisible(isChecked); myMenu.findItem(R.id.menu_action_share).setEnabled(isChecked); } } } }; public boolean onCreateOptionsMenu(Menu menu) { MenuInflater inflater = getMenuInflater(); inflater.inflate(R.menu.menuitem, menu); myMenu = menu; MenuItem item = menu.findItem(R.id.menu_action_share); if (item != null) { item.setVisible(true); } return true; } } Step 4 − Right click on res, create menu folder. Right click on the menu folder, create a menu resource file (menuitem.xml) and add the following code − <?xml version="1.0" encoding="utf-8"?> <menu xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto"> <item android:id="@+id/menu_action_share" android:icon="@drawable/ic_share_black_24dp" android:title="Share" app:showAsAction="ifRoom"/> </menu> Step 5 − Add the following code to androidManifest.xml <?xml version="1.0" encoding="utf-8"?> <manifest xmlns:android="http://schemas.android.com/apk/res/android" package="app.com.sample"> <application android:allowBackup="true" android:icon="@mipmap/ic_launcher" android:label="@string/app_name" android:roundIcon="@mipmap/ic_launcher_round" android:supportsRtl="true" android:theme="@style/AppTheme"> <activity android:name=".MainActivity"> <intent-filter> <action android:name="android.intent.action.MAIN" /> <category android:name="android.intent.category.LAUNCHER" /> </intent-filter> </activity> </application> </manifest> Let's try to run your application. I assume you have connected your actual Android Mobile device with your computer. To run the app from android studio, open one of your project's activity files and click Run icon from the toolbar. Select your mobile device as an option and then check your mobile device which will display your default screen − Click here to download the project code
[ { "code": null, "e": 1149, "s": 1062, "text": "This example demonstrates how do I hide and show a menu item in the Android ActionBar." }, { "code": null, "e": 1278, "s": 1149, "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": 1343, "s": 1278, "text": "Step 2 − Add the following code to res/layout/activity_main.xml." }, { "code": null, "e": 1834, "s": 1343, "text": "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<LinearLayout xmlns:android=\"http://schemas.android.com/apk/res/android\" 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 <ToggleButton\n android:id=\"@+id/btnMenuItem\"\n android:layout_width=\"match_parent\"\n android:layout_height=\"wrap_content\" />\n</LinearLayout>" }, { "code": null, "e": 1891, "s": 1834, "text": "Step 3 − Add the following code to src/MainActivity.java" }, { "code": null, "e": 3306, "s": 1891, "text": "import androidx.appcompat.app.AppCompatActivity;\nimport android.os.Bundle;\nimport android.view.Menu;\nimport android.view.MenuInflater;\nimport android.view.MenuItem;\nimport android.widget.CompoundButton;\nimport android.widget.ToggleButton;\npublic class MainActivity extends AppCompatActivity {\n ToggleButton button1;\n Menu myMenu;\n @Override\n protected void onCreate(Bundle savedInstanceState) {\n super.onCreate(savedInstanceState);\n setContentView(R.layout.activity_main);\n button1 = findViewById(R.id.btnMenuItem);\n button1.setOnCheckedChangeListener(onCheckedChangeListener);\n }\n CompoundButton.OnCheckedChangeListener onCheckedChangeListener = new CompoundButton.OnCheckedChangeListener() {\n @Override\n public void onCheckedChanged(CompoundButton buttonView,\n boolean isChecked) {\n if(myMenu != null) {\n if (buttonView == button1) {\n myMenu.findItem(R.id.menu_action_share).setVisible(isChecked);\n myMenu.findItem(R.id.menu_action_share).setEnabled(isChecked);\n }\n }\n }\n };\n public boolean onCreateOptionsMenu(Menu menu) {\n MenuInflater inflater = getMenuInflater();\n inflater.inflate(R.menu.menuitem, menu);\n myMenu = menu;\n MenuItem item = menu.findItem(R.id.menu_action_share);\n if (item != null) {\n item.setVisible(true);\n }\n return true;\n }\n}" }, { "code": null, "e": 3459, "s": 3306, "text": "Step 4 − Right click on res, create menu folder. Right click on the menu folder, create a menu resource file (menuitem.xml) and add the following code −" }, { "code": null, "e": 3788, "s": 3459, "text": "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<menu xmlns:android=\"http://schemas.android.com/apk/res/android\" xmlns:app=\"http://schemas.android.com/apk/res-auto\">\n <item\n android:id=\"@+id/menu_action_share\"\n android:icon=\"@drawable/ic_share_black_24dp\"\n android:title=\"Share\"\n app:showAsAction=\"ifRoom\"/>\n</menu>" }, { "code": null, "e": 3843, "s": 3788, "text": "Step 5 − Add the following code to androidManifest.xml" }, { "code": null, "e": 4513, "s": 3843, "text": "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<manifest xmlns:android=\"http://schemas.android.com/apk/res/android\" package=\"app.com.sample\">\n <application\n android:allowBackup=\"true\"\n android:icon=\"@mipmap/ic_launcher\"\n android:label=\"@string/app_name\"\n android:roundIcon=\"@mipmap/ic_launcher_round\"\n android:supportsRtl=\"true\"\n android:theme=\"@style/AppTheme\">\n <activity android:name=\".MainActivity\">\n <intent-filter>\n <action android:name=\"android.intent.action.MAIN\" />\n <category android:name=\"android.intent.category.LAUNCHER\" />\n </intent-filter>\n </activity>\n </application>\n</manifest>" }, { "code": null, "e": 4861, "s": 4513, "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": 4901, "s": 4861, "text": "Click here to download the project code" } ]
Print alternate elements of an array
08 Jun, 2021 Given an array, arr[] of size N, the task is to print the elements of the given array present at odd indices (1-based indexing). Examples: Input: arr[] = {1, 2, 3, 4, 5}Output: 1 3 5Explanation:Array element present at odd positions are: {1, 3, 5}.Therefore, the required output is 1 3 5. Input: arr[] = {-5, 1, 4, 2, 12}Output: -5 4 12 Naive Approach: The simplest approach to solve this problem is to traverse the given array and check if the position of the current element is odd or not. If found to be true, then print the current element. Below is the implementation of the above approach: C++ C Java Python3 C# Javascript // C++ program to implement// the above approach #include <bits/stdc++.h>using namespace std; // Function to print// Alternate elements// of the given arrayvoid printAlter(int arr[], int N){ // Print elements // at odd positions for (int currIndex = 0; currIndex < N; currIndex++) { // If currIndex stores even index // or odd position if (currIndex % 2 == 0) { cout << arr[currIndex] << " "; } }} // Driver Codeint main(){ int arr[] = { 1, 2, 3, 4, 5 }; int N = sizeof(arr) / sizeof(arr[0]); printAlter(arr, N);} // C program to implement// the above approach #include <stdio.h> // Function to print// Alternate elements// of the given arrayvoid printAlter(int arr[], int N){ // Print elements // at odd positions for (int currIndex = 0; currIndex < N; currIndex++) { // If currIndex stores even index // or odd position if (currIndex % 2 == 0) { printf("%d ", arr[currIndex]); } }} // Driver Codeint main(){ int arr[] = { 1, 2, 3, 4, 5 }; int N = sizeof(arr) / sizeof(arr[0]); printAlter(arr, N);} // Java program to implement// the above approachimport java.io.*; class GFG{ // Function to print// Alternate elements// of the given arraystatic void printAlter(int[] arr, int N){ // Print elements // at odd positions for(int currIndex = 0; currIndex < N; currIndex++) { // If currIndex stores even index // or odd position if (currIndex % 2 == 0) { System.out.print(arr[currIndex] + " "); } }} // Driver Codepublic static void main(String[] args){ int[] arr = { 1, 2, 3, 4, 5 }; int N = arr.length; printAlter(arr, N);}} // This code is contributed by akhilsaini # Python3 program to implement# the above approach # Function to print# Alternate elements# of the given arraydef printAlter(arr, N): # Print elements # at odd positions for currIndex in range(0, N): # If currIndex stores even index # or odd position if (currIndex % 2 == 0): print(arr[currIndex], end = " ") # Driver Codeif __name__ == "__main__": arr = [ 1, 2, 3, 4, 5 ] N = len(arr) printAlter(arr, N) # This code is contributed by akhilsaini // C# program to implement// the above approachusing System; class GFG{ // Function to print// Alternate elements// of the given arraystatic void printAlter(int[] arr, int N){ // Print elements // at odd positions for(int currIndex = 0; currIndex < N; currIndex++) { // If currIndex stores even index // or odd position if (currIndex % 2 == 0) { Console.Write(arr[currIndex] + " "); } }} // Driver Codepublic static void Main(){ int[] arr = { 1, 2, 3, 4, 5 }; int N = arr.Length; printAlter(arr, N);}} // This code is contributed by akhilsaini // javascript program to implement// the above approach // Function to print// Alternate elements// of the given arrayfunction printAlter(arr, N){ // Print elements // at odd positions for(var currIndex = 0; currIndex < N; currIndex++) { // If currIndex stores even index // or odd position if (currIndex % 2 == 0) { document.write(arr[currIndex] + " "); } }} // Driver Code var arr = [ 1, 2, 3, 4, 5 ] var N = arr.length; printAlter(arr, N); // This code is contributed by bunnyram19. 1 3 5 Time Complexity: O(N)Auxiliary Space: O(1) Efficient Approach: To optimize the above approach, the idea is to traverse only those elements of the given array which are present at odd positions. Follow the steps below to solve the problem: Iterate a loop with a loop variable currIndex from 0 to N. Print the value of arr[currIndex] and increment the value of currIndex by 2 until currIndex exceeds N. Below is the implementation of the above approach: C++ C Java Python3 C# Javascript // C++ program to implement// the above approach #include <bits/stdc++.h>using namespace std; // Function to print// Alternate elements// of the given arrayvoid printAlter(int arr[], int N){ // Print elements // at odd positions for (int currIndex = 0; currIndex < N; currIndex += 2) { // Print elements of array cout << arr[currIndex] << " "; }} // Driver Codeint main(){ int arr[] = { 1, 2, 3, 4, 5 }; int N = sizeof(arr) / sizeof(arr[0]); printAlter(arr, N);} // C program to implement// the above approach #include <stdio.h> // Function to print// Alternate elements// of the given arrayvoid printAlter(int arr[], int N){ // Print elements // at odd positions for (int currIndex = 0; currIndex < N; currIndex += 2) { // Print elements of array printf("%d ", arr[currIndex]); }} // Driver Codeint main(){ int arr[] = { 1, 2, 3, 4, 5 }; int N = sizeof(arr) / sizeof(arr[0]); printAlter(arr, N);} // Java program to implement// the above approachimport java.io.*; class GFG{ // Function to print// Alternate elements// of the given arraystatic void printAlter(int[] arr, int N){ // Print elements // at odd positions for(int currIndex = 0; currIndex < N; currIndex += 2) { // Print elements of array System.out.print(arr[currIndex] + " "); }} // Driver Codepublic static void main(String[] args){ int[] arr = { 1, 2, 3, 4, 5 }; int N = arr.length; printAlter(arr, N);}} // This code is contributed by akhilsaini # Python3 program to implement# the above approach # Function to print# Alternate elements# of the given arraydef printAlter(arr, N): # Print elements # at odd positions for currIndex in range(0, N, 2): # Print elements of array print(arr[currIndex], end = " ") # Driver Codeif __name__ == "__main__": arr = [ 1, 2, 3, 4, 5 ] N = len(arr) printAlter(arr, N) # This code is contributed by akhilsaini // C# program to implement// the above approachusing System; class GFG{ // Function to print// Alternate elements// of the given arraystatic void printAlter(int[] arr, int N){ // Print elements // at odd positions for(int currIndex = 0; currIndex < N; currIndex += 2) { // Print elements of array Console.Write(arr[currIndex] + " "); }} // Driver Codepublic static void Main(){ int[] arr = { 1, 2, 3, 4, 5 }; int N = arr.Length; printAlter(arr, N);}} // This code is contributed by akhilsaini <script> // Function to print// Alternate elements// of the given arrayfunction printAlter(arr, N){ // Print elements // at odd positions for (var currIndex = 0; currIndex < N; currIndex += 2) { // Print elements of array document.write( arr[currIndex] + " "); }} var arr= [ 1, 2, 3, 4, 5 ]; var N = 5; printAlter(arr, N); </script> 1 3 5 Time Complexity: O(N)Auxiliary Space: O(1) Slice by using python list slicing by setting step value to 2. Below is the implementation: Python3 # Python3 program to implement# the above approach # Function to print# Alternate elements# of the given arraydef printAlter(arr, N): # Print elements # at odd positions by using slicing # we use * to print with spaces print(*arr[::2]) # Driver Codeif __name__ == "__main__": arr = [1, 2, 3, 4, 5] N = len(arr) printAlter(arr, N) # This code is contributed by vikkycirus 1 3 5 Time Complexity: O(N) Space Complexity: O(1) akhilsaini vikkycirus bunnyram19 akshitsaxenaa09 clintra sweetyty Arrays School Programming Searching Arrays Searching Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 53, "s": 25, "text": "\n08 Jun, 2021" }, { "code": null, "e": 182, "s": 53, "text": "Given an array, arr[] of size N, the task is to print the elements of the given array present at odd indices (1-based indexing)." }, { "code": null, "e": 192, "s": 182, "text": "Examples:" }, { "code": null, "e": 342, "s": 192, "text": "Input: arr[] = {1, 2, 3, 4, 5}Output: 1 3 5Explanation:Array element present at odd positions are: {1, 3, 5}.Therefore, the required output is 1 3 5." }, { "code": null, "e": 390, "s": 342, "text": "Input: arr[] = {-5, 1, 4, 2, 12}Output: -5 4 12" }, { "code": null, "e": 598, "s": 390, "text": "Naive Approach: The simplest approach to solve this problem is to traverse the given array and check if the position of the current element is odd or not. If found to be true, then print the current element." }, { "code": null, "e": 649, "s": 598, "text": "Below is the implementation of the above approach:" }, { "code": null, "e": 653, "s": 649, "text": "C++" }, { "code": null, "e": 655, "s": 653, "text": "C" }, { "code": null, "e": 660, "s": 655, "text": "Java" }, { "code": null, "e": 668, "s": 660, "text": "Python3" }, { "code": null, "e": 671, "s": 668, "text": "C#" }, { "code": null, "e": 682, "s": 671, "text": "Javascript" }, { "code": "// C++ program to implement// the above approach #include <bits/stdc++.h>using namespace std; // Function to print// Alternate elements// of the given arrayvoid printAlter(int arr[], int N){ // Print elements // at odd positions for (int currIndex = 0; currIndex < N; currIndex++) { // If currIndex stores even index // or odd position if (currIndex % 2 == 0) { cout << arr[currIndex] << \" \"; } }} // Driver Codeint main(){ int arr[] = { 1, 2, 3, 4, 5 }; int N = sizeof(arr) / sizeof(arr[0]); printAlter(arr, N);}", "e": 1265, "s": 682, "text": null }, { "code": "// C program to implement// the above approach #include <stdio.h> // Function to print// Alternate elements// of the given arrayvoid printAlter(int arr[], int N){ // Print elements // at odd positions for (int currIndex = 0; currIndex < N; currIndex++) { // If currIndex stores even index // or odd position if (currIndex % 2 == 0) { printf(\"%d \", arr[currIndex]); } }} // Driver Codeint main(){ int arr[] = { 1, 2, 3, 4, 5 }; int N = sizeof(arr) / sizeof(arr[0]); printAlter(arr, N);}", "e": 1820, "s": 1265, "text": null }, { "code": "// Java program to implement// the above approachimport java.io.*; class GFG{ // Function to print// Alternate elements// of the given arraystatic void printAlter(int[] arr, int N){ // Print elements // at odd positions for(int currIndex = 0; currIndex < N; currIndex++) { // If currIndex stores even index // or odd position if (currIndex % 2 == 0) { System.out.print(arr[currIndex] + \" \"); } }} // Driver Codepublic static void main(String[] args){ int[] arr = { 1, 2, 3, 4, 5 }; int N = arr.length; printAlter(arr, N);}} // This code is contributed by akhilsaini", "e": 2497, "s": 1820, "text": null }, { "code": "# Python3 program to implement# the above approach # Function to print# Alternate elements# of the given arraydef printAlter(arr, N): # Print elements # at odd positions for currIndex in range(0, N): # If currIndex stores even index # or odd position if (currIndex % 2 == 0): print(arr[currIndex], end = \" \") # Driver Codeif __name__ == \"__main__\": arr = [ 1, 2, 3, 4, 5 ] N = len(arr) printAlter(arr, N) # This code is contributed by akhilsaini", "e": 3017, "s": 2497, "text": null }, { "code": "// C# program to implement// the above approachusing System; class GFG{ // Function to print// Alternate elements// of the given arraystatic void printAlter(int[] arr, int N){ // Print elements // at odd positions for(int currIndex = 0; currIndex < N; currIndex++) { // If currIndex stores even index // or odd position if (currIndex % 2 == 0) { Console.Write(arr[currIndex] + \" \"); } }} // Driver Codepublic static void Main(){ int[] arr = { 1, 2, 3, 4, 5 }; int N = arr.Length; printAlter(arr, N);}} // This code is contributed by akhilsaini", "e": 3672, "s": 3017, "text": null }, { "code": "// javascript program to implement// the above approach // Function to print// Alternate elements// of the given arrayfunction printAlter(arr, N){ // Print elements // at odd positions for(var currIndex = 0; currIndex < N; currIndex++) { // If currIndex stores even index // or odd position if (currIndex % 2 == 0) { document.write(arr[currIndex] + \" \"); } }} // Driver Code var arr = [ 1, 2, 3, 4, 5 ] var N = arr.length; printAlter(arr, N); // This code is contributed by bunnyram19.", "e": 4253, "s": 3672, "text": null }, { "code": null, "e": 4259, "s": 4253, "text": "1 3 5" }, { "code": null, "e": 4304, "s": 4261, "text": "Time Complexity: O(N)Auxiliary Space: O(1)" }, { "code": null, "e": 4500, "s": 4304, "text": "Efficient Approach: To optimize the above approach, the idea is to traverse only those elements of the given array which are present at odd positions. Follow the steps below to solve the problem:" }, { "code": null, "e": 4559, "s": 4500, "text": "Iterate a loop with a loop variable currIndex from 0 to N." }, { "code": null, "e": 4662, "s": 4559, "text": "Print the value of arr[currIndex] and increment the value of currIndex by 2 until currIndex exceeds N." }, { "code": null, "e": 4713, "s": 4662, "text": "Below is the implementation of the above approach:" }, { "code": null, "e": 4717, "s": 4713, "text": "C++" }, { "code": null, "e": 4719, "s": 4717, "text": "C" }, { "code": null, "e": 4724, "s": 4719, "text": "Java" }, { "code": null, "e": 4732, "s": 4724, "text": "Python3" }, { "code": null, "e": 4735, "s": 4732, "text": "C#" }, { "code": null, "e": 4746, "s": 4735, "text": "Javascript" }, { "code": "// C++ program to implement// the above approach #include <bits/stdc++.h>using namespace std; // Function to print// Alternate elements// of the given arrayvoid printAlter(int arr[], int N){ // Print elements // at odd positions for (int currIndex = 0; currIndex < N; currIndex += 2) { // Print elements of array cout << arr[currIndex] << \" \"; }} // Driver Codeint main(){ int arr[] = { 1, 2, 3, 4, 5 }; int N = sizeof(arr) / sizeof(arr[0]); printAlter(arr, N);}", "e": 5253, "s": 4746, "text": null }, { "code": "// C program to implement// the above approach #include <stdio.h> // Function to print// Alternate elements// of the given arrayvoid printAlter(int arr[], int N){ // Print elements // at odd positions for (int currIndex = 0; currIndex < N; currIndex += 2) { // Print elements of array printf(\"%d \", arr[currIndex]); }} // Driver Codeint main(){ int arr[] = { 1, 2, 3, 4, 5 }; int N = sizeof(arr) / sizeof(arr[0]); printAlter(arr, N);}", "e": 5732, "s": 5253, "text": null }, { "code": "// Java program to implement// the above approachimport java.io.*; class GFG{ // Function to print// Alternate elements// of the given arraystatic void printAlter(int[] arr, int N){ // Print elements // at odd positions for(int currIndex = 0; currIndex < N; currIndex += 2) { // Print elements of array System.out.print(arr[currIndex] + \" \"); }} // Driver Codepublic static void main(String[] args){ int[] arr = { 1, 2, 3, 4, 5 }; int N = arr.length; printAlter(arr, N);}} // This code is contributed by akhilsaini", "e": 6326, "s": 5732, "text": null }, { "code": "# Python3 program to implement# the above approach # Function to print# Alternate elements# of the given arraydef printAlter(arr, N): # Print elements # at odd positions for currIndex in range(0, N, 2): # Print elements of array print(arr[currIndex], end = \" \") # Driver Codeif __name__ == \"__main__\": arr = [ 1, 2, 3, 4, 5 ] N = len(arr) printAlter(arr, N) # This code is contributed by akhilsaini", "e": 6777, "s": 6326, "text": null }, { "code": "// C# program to implement// the above approachusing System; class GFG{ // Function to print// Alternate elements// of the given arraystatic void printAlter(int[] arr, int N){ // Print elements // at odd positions for(int currIndex = 0; currIndex < N; currIndex += 2) { // Print elements of array Console.Write(arr[currIndex] + \" \"); }} // Driver Codepublic static void Main(){ int[] arr = { 1, 2, 3, 4, 5 }; int N = arr.Length; printAlter(arr, N);}} // This code is contributed by akhilsaini", "e": 7349, "s": 6777, "text": null }, { "code": "<script> // Function to print// Alternate elements// of the given arrayfunction printAlter(arr, N){ // Print elements // at odd positions for (var currIndex = 0; currIndex < N; currIndex += 2) { // Print elements of array document.write( arr[currIndex] + \" \"); }} var arr= [ 1, 2, 3, 4, 5 ]; var N = 5; printAlter(arr, N); </script>", "e": 7730, "s": 7349, "text": null }, { "code": null, "e": 7736, "s": 7730, "text": "1 3 5" }, { "code": null, "e": 7781, "s": 7738, "text": "Time Complexity: O(N)Auxiliary Space: O(1)" }, { "code": null, "e": 7844, "s": 7781, "text": "Slice by using python list slicing by setting step value to 2." }, { "code": null, "e": 7873, "s": 7844, "text": "Below is the implementation:" }, { "code": null, "e": 7881, "s": 7873, "text": "Python3" }, { "code": "# Python3 program to implement# the above approach # Function to print# Alternate elements# of the given arraydef printAlter(arr, N): # Print elements # at odd positions by using slicing # we use * to print with spaces print(*arr[::2]) # Driver Codeif __name__ == \"__main__\": arr = [1, 2, 3, 4, 5] N = len(arr) printAlter(arr, N) # This code is contributed by vikkycirus", "e": 8277, "s": 7881, "text": null }, { "code": null, "e": 8283, "s": 8277, "text": "1 3 5" }, { "code": null, "e": 8305, "s": 8283, "text": "Time Complexity: O(N)" }, { "code": null, "e": 8328, "s": 8305, "text": "Space Complexity: O(1)" }, { "code": null, "e": 8339, "s": 8328, "text": "akhilsaini" }, { "code": null, "e": 8350, "s": 8339, "text": "vikkycirus" }, { "code": null, "e": 8361, "s": 8350, "text": "bunnyram19" }, { "code": null, "e": 8377, "s": 8361, "text": "akshitsaxenaa09" }, { "code": null, "e": 8385, "s": 8377, "text": "clintra" }, { "code": null, "e": 8394, "s": 8385, "text": "sweetyty" }, { "code": null, "e": 8401, "s": 8394, "text": "Arrays" }, { "code": null, "e": 8420, "s": 8401, "text": "School Programming" }, { "code": null, "e": 8430, "s": 8420, "text": "Searching" }, { "code": null, "e": 8437, "s": 8430, "text": "Arrays" }, { "code": null, "e": 8447, "s": 8437, "text": "Searching" } ]
Stacked Percentage Bar Plot In MatPlotLib
01 Oct, 2020 A Stacked Percentage Bar Chart is a simple bar chart in the stacked form with a percentage of each subgroup in a group. Stacked bar plots represent different groups on the top of one another. The height of the bar depends on the resulting height of the combination of the results of the groups. It goes from the bottom to the value instead of going from zero to value. A percent stacked bar chart is almost the same as a stacked barchart. Subgroups are displayed on top of each other, but data are normalized to make in a sort that the sum of every subgroup is the same as the total for each one. The dataset used in the following examples is shown below : The dataset can be downloaded from here. Procedure: The procedure to draw Stacked Percentage Bar Chart is the following steps which are described below with examples : 1. Draw a stacked bar chart using data (dataset, dictionary, etc.). Python3 # importing packagesimport pandas as pdimport matplotlib.pyplot as plt # load datasetdf = pd.read_excel("Hours.xlsx") # view datasetprint(df) # plot a Stacked Bar Chart using matplotlibdf.plot( x = 'Name', kind = 'barh', stacked = True, title = 'Stacked Bar Graph', mark_right = True) Output: Name Studied Slept Other 0 Ram 4.855064 9.639962 9.504974 1 Yash 8.625440 0.058927 15.315634 2 Alpha 3.828192 0.723199 19.448609 3 Deep 7.150955 3.899420 12.949625 4 Alex 6.477900 8.198181 9.323919 5 Jack 1.922270 1.331427 20.746303 6 Sufia 8.978216 0.993438 14.028347 2. Add Percentage on subgroups of each group. Python3 # importing packagesimport pandas as pdimport numpy as npimport matplotlib.pyplot as plt # load datasetdf = pd.read_excel("Hours.xlsx") # view datasetprint(df) # plot a Stacked Bar Chart using matplotlibdf.plot( x = 'Name', kind = 'barh', stacked = True, title = 'Percentage Stacked Bar Graph', mark_right = True) df_total = df["Studied"] + df["Slept"] + df["Other"]df_rel = df[df.columns[1:]].div(df_total, 0)*100 for n in df_rel: for i, (cs, ab, pc) in enumerate(zip(df.iloc[:, 1:].cumsum(1)[n], df[n], df_rel[n])): plt.text(cs - ab / 2, i, str(np.round(pc, 1)) + '%', va = 'center', ha = 'center') Output: Name Studied Slept Other 0 Ram 4.855064 9.639962 9.504974 1 Yash 8.625440 0.058927 15.315634 2 Alpha 3.828192 0.723199 19.448609 3 Deep 7.150955 3.899420 12.949625 4 Alex 6.477900 8.198181 9.323919 5 Jack 1.922270 1.331427 20.746303 6 Sufia 8.978216 0.993438 14.028347 Python3 # importing packagesimport pandas as pdimport numpy as npimport matplotlib.pyplot as plt # load datasetdf = pd.read_xlsx("Hours.xlsx") # view datasetprint(df) # plot a Stacked Bar Chart using matplotlibdf.plot( x = 'Name', kind = 'barh', stacked = True, title = 'Percentage Stacked Bar Graph', mark_right = True) df_total = df["Studied"] + df["Slept"] + df["Other"]df_rel = df[df.columns[1:]].div(df_total, 0) * 100 for n in df_rel: for i, (cs, ab, pc) in enumerate(zip(df.iloc[:, 1:].cumsum(1)[n], df[n], df_rel[n])): plt.text(cs - ab / 2, i, str(np.round(pc, 1)) + '%', va = 'center', ha = 'center', rotation = 20, fontsize = 8) Output: Name Studied Slept Other 0 Ram 4.855064 9.639962 9.504974 1 Yash 8.625440 0.058927 15.315634 2 Alpha 3.828192 0.723199 19.448609 3 Deep 7.150955 3.899420 12.949625 4 Alex 6.477900 8.198181 9.323919 5 Jack 1.922270 1.331427 20.746303 6 Sufia 8.978216 0.993438 14.028347 Matplotlib Pyplot-class Python-matplotlib Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 52, "s": 24, "text": "\n01 Oct, 2020" }, { "code": null, "e": 650, "s": 52, "text": "A Stacked Percentage Bar Chart is a simple bar chart in the stacked form with a percentage of each subgroup in a group. Stacked bar plots represent different groups on the top of one another. The height of the bar depends on the resulting height of the combination of the results of the groups. It goes from the bottom to the value instead of going from zero to value. A percent stacked bar chart is almost the same as a stacked barchart. Subgroups are displayed on top of each other, but data are normalized to make in a sort that the sum of every subgroup is the same as the total for each one. " }, { "code": null, "e": 710, "s": 650, "text": "The dataset used in the following examples is shown below :" }, { "code": null, "e": 751, "s": 710, "text": "The dataset can be downloaded from here." }, { "code": null, "e": 878, "s": 751, "text": "Procedure: The procedure to draw Stacked Percentage Bar Chart is the following steps which are described below with examples :" }, { "code": null, "e": 946, "s": 878, "text": "1. Draw a stacked bar chart using data (dataset, dictionary, etc.)." }, { "code": null, "e": 954, "s": 946, "text": "Python3" }, { "code": "# importing packagesimport pandas as pdimport matplotlib.pyplot as plt # load datasetdf = pd.read_excel(\"Hours.xlsx\") # view datasetprint(df) # plot a Stacked Bar Chart using matplotlibdf.plot( x = 'Name', kind = 'barh', stacked = True, title = 'Stacked Bar Graph', mark_right = True)", "e": 1257, "s": 954, "text": null }, { "code": null, "e": 1265, "s": 1257, "text": "Output:" }, { "code": null, "e": 1587, "s": 1265, "text": " Name Studied Slept Other\n0 Ram 4.855064 9.639962 9.504974\n1 Yash 8.625440 0.058927 15.315634\n2 Alpha 3.828192 0.723199 19.448609\n3 Deep 7.150955 3.899420 12.949625\n4 Alex 6.477900 8.198181 9.323919\n5 Jack 1.922270 1.331427 20.746303\n6 Sufia 8.978216 0.993438 14.028347\n\n" }, { "code": null, "e": 1633, "s": 1587, "text": "2. Add Percentage on subgroups of each group." }, { "code": null, "e": 1641, "s": 1633, "text": "Python3" }, { "code": "# importing packagesimport pandas as pdimport numpy as npimport matplotlib.pyplot as plt # load datasetdf = pd.read_excel(\"Hours.xlsx\") # view datasetprint(df) # plot a Stacked Bar Chart using matplotlibdf.plot( x = 'Name', kind = 'barh', stacked = True, title = 'Percentage Stacked Bar Graph', mark_right = True) df_total = df[\"Studied\"] + df[\"Slept\"] + df[\"Other\"]df_rel = df[df.columns[1:]].div(df_total, 0)*100 for n in df_rel: for i, (cs, ab, pc) in enumerate(zip(df.iloc[:, 1:].cumsum(1)[n], df[n], df_rel[n])): plt.text(cs - ab / 2, i, str(np.round(pc, 1)) + '%', va = 'center', ha = 'center')", "e": 2324, "s": 1641, "text": null }, { "code": null, "e": 2332, "s": 2324, "text": "Output:" }, { "code": null, "e": 2655, "s": 2332, "text": " Name Studied Slept Other\n0 Ram 4.855064 9.639962 9.504974\n1 Yash 8.625440 0.058927 15.315634\n2 Alpha 3.828192 0.723199 19.448609\n3 Deep 7.150955 3.899420 12.949625\n4 Alex 6.477900 8.198181 9.323919\n5 Jack 1.922270 1.331427 20.746303\n6 Sufia 8.978216 0.993438 14.028347\n\n" }, { "code": null, "e": 2663, "s": 2655, "text": "Python3" }, { "code": "# importing packagesimport pandas as pdimport numpy as npimport matplotlib.pyplot as plt # load datasetdf = pd.read_xlsx(\"Hours.xlsx\") # view datasetprint(df) # plot a Stacked Bar Chart using matplotlibdf.plot( x = 'Name', kind = 'barh', stacked = True, title = 'Percentage Stacked Bar Graph', mark_right = True) df_total = df[\"Studied\"] + df[\"Slept\"] + df[\"Other\"]df_rel = df[df.columns[1:]].div(df_total, 0) * 100 for n in df_rel: for i, (cs, ab, pc) in enumerate(zip(df.iloc[:, 1:].cumsum(1)[n], df[n], df_rel[n])): plt.text(cs - ab / 2, i, str(np.round(pc, 1)) + '%', va = 'center', ha = 'center', rotation = 20, fontsize = 8)", "e": 3376, "s": 2663, "text": null }, { "code": null, "e": 3384, "s": 3376, "text": "Output:" }, { "code": null, "e": 3706, "s": 3384, "text": " Name Studied Slept Other\n0 Ram 4.855064 9.639962 9.504974\n1 Yash 8.625440 0.058927 15.315634\n2 Alpha 3.828192 0.723199 19.448609\n3 Deep 7.150955 3.899420 12.949625\n4 Alex 6.477900 8.198181 9.323919\n5 Jack 1.922270 1.331427 20.746303\n6 Sufia 8.978216 0.993438 14.028347\n\n" }, { "code": null, "e": 3730, "s": 3706, "text": "Matplotlib Pyplot-class" }, { "code": null, "e": 3748, "s": 3730, "text": "Python-matplotlib" }, { "code": null, "e": 3755, "s": 3748, "text": "Python" } ]
What is Arch Linux?
06 Jul, 2022 Arch Linux is an independent Linux distribution that adheres to the principles of simplicity, modernity, pragmatism, user centrality, and versatility. It is a minimalist, lightweight, and bleeding edge distro targeting proficient GNU/Linux users over the idea of trying to be appealing to as many users as possible. Arch promotes the do-it-yourself (DIY) attitude among its users and thus provides you with the freedom to tweak your system according to your needs. Arch is bleeding-edge: Arch Linux follows a rolling release model, this essentially means that you get all the new features and updates as soon as they roll out. There is no need for versions when updating and upgrading your system boils down to a simple command mentioned below. pacman -Syu Arch is what you want it to be: Arch Linux offers absurd amounts of customizability to its users. A clean installation of Arch doesn’t even include a Desktop Environment or a Window Manager. The user builds their system from the ground up. This approach also makes Arch extremely lightweight because there is no preinstalled bloat on the system, you the user have full freedom of what you want and when you want it. The Arch User Repository (AUR): A unique feature that makes Arch stand out among other distros is the Arch User Repository (AUR). It is a community-driven repository for Arch users. It contains package descriptions (PKGBUILDs) that allow you to compile a package from source with makepkg and then install it via pacman. The AUR was created to organize and share new packages from the community and to help expedite popular packages’ inclusion into the community repository. AUR extends the software offerings of Arch’s official repository much further and beyond. The Holy Arch Wiki: Arch Linux is one of the, if not the most well documented Linux distros out there. The Arch wiki is the stuff of legends among the Linux enthusiasts. It is extremely well documented and massive. Its offerings extend beyond Arch Linux itself at times. If you run into some trouble with your system, the Arch Wiki probably has the solution already. It is a bridge: Package Manager (pacman), the package manager of Arch Linux is pretty unique in its own right. It is flexible enough to support the installation of binary packages from the Arch repository, as well as binaries compiled from source via makepkg. This makes Arch a bridge between the distros which allow the installation of binary packages via their package management systems and the distros which trade ease of users to allow their users to compile binaries from source with variable configurations. Improve your understanding of Linux: You won’t know how rewarding it is to get a clean installation of an Arch system unless you experience it yourself. The installation process is pretty complex since most of the things you will be doing won’t be GUI-assisted and you will be using CLI commands. Although this kind of complexity might sound scary to new users, it still has its own perks. The installation teaches you a lot about how Linux actually works, which you won’t bother learning because modern-day GUI installers take care of that for you. You are introduced to concepts like display managers, chroot, configuring networks, and much more during the installation itself. Note: Arch Linux still has GUI installers for new Linux users who are not ready to do it the hard way but where is the fun? Bonus: If you are into cybersecurity, you must have heard of Black Arch. The Black Arch repository contains a massive list of security tools for penetration testers and security researchers. The downside of installing Black Arch for some users might be its massive size as it comes with all the tools which include the ones you are never going to use. The good news is you can integrate the Black Arch repository in your Arch system and fetch tools you need on-demand from the repository. Other popular Linux distributions based on Arch: Manjaro Linux ArcoLinux EndeavourOS RebornOS It is an advanced distribution: Although, you might find Arch to be a very likely contender for your next distro hop, let me remind you that it is not at all a newbie-friendly distro. It is not recommended that an absolute Linux newbie tries out Arch. With the amount of customizability Arch offers in question, it is highly likely that a new user might potentially break their system trying to configure it in a totally wrong way. If you really want to try out Arch and you are not confident with your Linux skills, it is a much better idea to try out the installation in a virtual machine and then make the jump on a real system once you are confident enough. Smaller community compared to others. Cannot be fixed easily during any breaks. dasguptabhargav raj2002 Linux-Unix Operating Systems Operating Systems Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 53, "s": 25, "text": "\n06 Jul, 2022" }, { "code": null, "e": 519, "s": 53, "text": "Arch Linux is an independent Linux distribution that adheres to the principles of simplicity, modernity, pragmatism, user centrality, and versatility. It is a minimalist, lightweight, and bleeding edge distro targeting proficient GNU/Linux users over the idea of trying to be appealing to as many users as possible. Arch promotes the do-it-yourself (DIY) attitude among its users and thus provides you with the freedom to tweak your system according to your needs. " }, { "code": null, "e": 542, "s": 519, "text": "Arch is bleeding-edge:" }, { "code": null, "e": 799, "s": 542, "text": "Arch Linux follows a rolling release model, this essentially means that you get all the new features and updates as soon as they roll out. There is no need for versions when updating and upgrading your system boils down to a simple command mentioned below." }, { "code": null, "e": 811, "s": 799, "text": "pacman -Syu" }, { "code": null, "e": 843, "s": 811, "text": "Arch is what you want it to be:" }, { "code": null, "e": 1227, "s": 843, "text": "Arch Linux offers absurd amounts of customizability to its users. A clean installation of Arch doesn’t even include a Desktop Environment or a Window Manager. The user builds their system from the ground up. This approach also makes Arch extremely lightweight because there is no preinstalled bloat on the system, you the user have full freedom of what you want and when you want it." }, { "code": null, "e": 1259, "s": 1227, "text": "The Arch User Repository (AUR):" }, { "code": null, "e": 1791, "s": 1259, "text": "A unique feature that makes Arch stand out among other distros is the Arch User Repository (AUR). It is a community-driven repository for Arch users. It contains package descriptions (PKGBUILDs) that allow you to compile a package from source with makepkg and then install it via pacman. The AUR was created to organize and share new packages from the community and to help expedite popular packages’ inclusion into the community repository. AUR extends the software offerings of Arch’s official repository much further and beyond." }, { "code": null, "e": 1811, "s": 1791, "text": "The Holy Arch Wiki:" }, { "code": null, "e": 2158, "s": 1811, "text": "Arch Linux is one of the, if not the most well documented Linux distros out there. The Arch wiki is the stuff of legends among the Linux enthusiasts. It is extremely well documented and massive. Its offerings extend beyond Arch Linux itself at times. If you run into some trouble with your system, the Arch Wiki probably has the solution already." }, { "code": null, "e": 2174, "s": 2158, "text": "It is a bridge:" }, { "code": null, "e": 2674, "s": 2174, "text": "Package Manager (pacman), the package manager of Arch Linux is pretty unique in its own right. It is flexible enough to support the installation of binary packages from the Arch repository, as well as binaries compiled from source via makepkg. This makes Arch a bridge between the distros which allow the installation of binary packages via their package management systems and the distros which trade ease of users to allow their users to compile binaries from source with variable configurations. " }, { "code": null, "e": 2711, "s": 2674, "text": "Improve your understanding of Linux:" }, { "code": null, "e": 3355, "s": 2711, "text": "You won’t know how rewarding it is to get a clean installation of an Arch system unless you experience it yourself. The installation process is pretty complex since most of the things you will be doing won’t be GUI-assisted and you will be using CLI commands. Although this kind of complexity might sound scary to new users, it still has its own perks. The installation teaches you a lot about how Linux actually works, which you won’t bother learning because modern-day GUI installers take care of that for you. You are introduced to concepts like display managers, chroot, configuring networks, and much more during the installation itself. " }, { "code": null, "e": 3479, "s": 3355, "text": "Note: Arch Linux still has GUI installers for new Linux users who are not ready to do it the hard way but where is the fun?" }, { "code": null, "e": 3486, "s": 3479, "text": "Bonus:" }, { "code": null, "e": 3968, "s": 3486, "text": "If you are into cybersecurity, you must have heard of Black Arch. The Black Arch repository contains a massive list of security tools for penetration testers and security researchers. The downside of installing Black Arch for some users might be its massive size as it comes with all the tools which include the ones you are never going to use. The good news is you can integrate the Black Arch repository in your Arch system and fetch tools you need on-demand from the repository." }, { "code": null, "e": 4017, "s": 3968, "text": "Other popular Linux distributions based on Arch:" }, { "code": null, "e": 4031, "s": 4017, "text": "Manjaro Linux" }, { "code": null, "e": 4041, "s": 4031, "text": "ArcoLinux" }, { "code": null, "e": 4053, "s": 4041, "text": "EndeavourOS" }, { "code": null, "e": 4062, "s": 4053, "text": "RebornOS" }, { "code": null, "e": 4094, "s": 4062, "text": "It is an advanced distribution:" }, { "code": null, "e": 4724, "s": 4094, "text": "Although, you might find Arch to be a very likely contender for your next distro hop, let me remind you that it is not at all a newbie-friendly distro. It is not recommended that an absolute Linux newbie tries out Arch. With the amount of customizability Arch offers in question, it is highly likely that a new user might potentially break their system trying to configure it in a totally wrong way. If you really want to try out Arch and you are not confident with your Linux skills, it is a much better idea to try out the installation in a virtual machine and then make the jump on a real system once you are confident enough." }, { "code": null, "e": 4762, "s": 4724, "text": "Smaller community compared to others." }, { "code": null, "e": 4804, "s": 4762, "text": "Cannot be fixed easily during any breaks." }, { "code": null, "e": 4820, "s": 4804, "text": "dasguptabhargav" }, { "code": null, "e": 4828, "s": 4820, "text": "raj2002" }, { "code": null, "e": 4839, "s": 4828, "text": "Linux-Unix" }, { "code": null, "e": 4857, "s": 4839, "text": "Operating Systems" }, { "code": null, "e": 4875, "s": 4857, "text": "Operating Systems" } ]
How to create your own Avatar using Python ?
17 May, 2022 In this article, we will discuss how to create a custom avatar using Python. In order to perform this task. You don’t have to create it yourself on software or download it from some website, but a few lines of code will help you to generate an avatar of your choice. We will be using the py-avataaars package from which we will be creating those beautiful avatars. The basic syntax of this module is: from py_avataaars import PyAvataaar avatar = PyAvataaar() avatar.render_png_file('<output_file.png>') Here the PyAvataaar Class is in the __init__.py which is responsible for a number of functionalities, out of which the major one is setting the parameters of the avatar for eg: change in skin color, outfit, eyes, hairs, hair colors, moods etc. So, let’s begin... Step 1: Installation of some packages. First type pip install py-avataaars in your terminal to install the avatars package (Check: https://github.com/kebu/py-avataaars for more information) Then download and install this gtk file from here gtk3-runtime-3.24.24-2021-01-30-ts-win64.exe. Your antivirus will try to block it, but you should allow it to download for the code to run properly, trust me guys it’s a non-harmful file (Check: https://github.com/tschoonj/GTK-for-Windows-Runtime-Environment-Installer for more information) Step 2: Writing the python program. First, we will try to generate the default avatar by writing this code and see if this works properly or not Python3 # importing the require packagefrom py_avataaars import PyAvataaar # assigning various parameters to our avataravatar = PyAvataaar() # rendering the avatar in png formatavatar.render_png_file("AVATAR_1.png") Output: The above program will generate the AVATAR_1.png file in the folder where you’ve kept this python program. Once the above program is running properly, then we will generate the avatars according to our needs with this by using PyAvataaar() method. Syntax: PyAvataaar(style, skin_color, hair_color, facial_hair_type, top_type, mouth_type, eye_type, eyebrow_type, nose_type, accessories_type, clothe_type, clothe_graphic_type) Implementation: Python3 # Python program to create custom avatars # importing the require packageimport py_avataaars as pa # assigning various parameters to our avataravatar = pa.PyAvataaar(style=pa.AvatarStyle.CIRCLE, skin_color=pa.SkinColor.LIGHT, hair_color=pa.HairColor.AUBURN, facial_hair_type=pa.FacialHairType.MOUSTACHE_MAGNUM, top_type=pa.TopType.SHORT_HAIR_SHAGGY_MULLET, mouth_type=pa.MouthType.SCREAM_OPEN, eye_type=pa.EyesType.SQUINT, eyebrow_type=pa.EyebrowType.RAISED_EXCITED_NATURAL, nose_type=pa.NoseType.DEFAULT, accessories_type=pa.AccessoriesType.PRESCRIPTION_02, clothe_type=pa.ClotheType.HOODIE, clothe_graphic_type=pa.ClotheGraphicType.BAT,) # rendering the avatar in png formatavatar.render_png_file("AVATAR_2.png") Output: You can always change the parameters of the avatar accordingly by pressing the Ctrl button and hovering over the py_avataaars line, which will turn it blue and then you can click on it to see __init__.py file, where you can find all the parameters, each written in a different class. Demonstration: Python-projects python-utility Technical Scripter 2020 Python Technical Scripter Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 53, "s": 25, "text": "\n17 May, 2022" }, { "code": null, "e": 320, "s": 53, "text": "In this article, we will discuss how to create a custom avatar using Python. In order to perform this task. You don’t have to create it yourself on software or download it from some website, but a few lines of code will help you to generate an avatar of your choice." }, { "code": null, "e": 454, "s": 320, "text": "We will be using the py-avataaars package from which we will be creating those beautiful avatars. The basic syntax of this module is:" }, { "code": null, "e": 557, "s": 454, "text": "from py_avataaars import PyAvataaar\n\navatar = PyAvataaar()\navatar.render_png_file('<output_file.png>')" }, { "code": null, "e": 801, "s": 557, "text": "Here the PyAvataaar Class is in the __init__.py which is responsible for a number of functionalities, out of which the major one is setting the parameters of the avatar for eg: change in skin color, outfit, eyes, hairs, hair colors, moods etc." }, { "code": null, "e": 820, "s": 801, "text": "So, let’s begin..." }, { "code": null, "e": 860, "s": 820, "text": "Step 1: Installation of some packages. " }, { "code": null, "e": 1011, "s": 860, "text": "First type pip install py-avataaars in your terminal to install the avatars package (Check: https://github.com/kebu/py-avataaars for more information)" }, { "code": null, "e": 1353, "s": 1011, "text": "Then download and install this gtk file from here gtk3-runtime-3.24.24-2021-01-30-ts-win64.exe. Your antivirus will try to block it, but you should allow it to download for the code to run properly, trust me guys it’s a non-harmful file (Check: https://github.com/tschoonj/GTK-for-Windows-Runtime-Environment-Installer for more information)" }, { "code": null, "e": 1389, "s": 1353, "text": "Step 2: Writing the python program." }, { "code": null, "e": 1498, "s": 1389, "text": "First, we will try to generate the default avatar by writing this code and see if this works properly or not" }, { "code": null, "e": 1506, "s": 1498, "text": "Python3" }, { "code": "# importing the require packagefrom py_avataaars import PyAvataaar # assigning various parameters to our avataravatar = PyAvataaar() # rendering the avatar in png formatavatar.render_png_file(\"AVATAR_1.png\")", "e": 1718, "s": 1506, "text": null }, { "code": null, "e": 1726, "s": 1718, "text": "Output:" }, { "code": null, "e": 1974, "s": 1726, "text": "The above program will generate the AVATAR_1.png file in the folder where you’ve kept this python program. Once the above program is running properly, then we will generate the avatars according to our needs with this by using PyAvataaar() method." }, { "code": null, "e": 1982, "s": 1974, "text": "Syntax:" }, { "code": null, "e": 2151, "s": 1982, "text": "PyAvataaar(style, skin_color, hair_color, facial_hair_type, top_type, mouth_type, eye_type, eyebrow_type, nose_type, accessories_type, clothe_type, clothe_graphic_type)" }, { "code": null, "e": 2167, "s": 2151, "text": "Implementation:" }, { "code": null, "e": 2175, "s": 2167, "text": "Python3" }, { "code": "# Python program to create custom avatars # importing the require packageimport py_avataaars as pa # assigning various parameters to our avataravatar = pa.PyAvataaar(style=pa.AvatarStyle.CIRCLE, skin_color=pa.SkinColor.LIGHT, hair_color=pa.HairColor.AUBURN, facial_hair_type=pa.FacialHairType.MOUSTACHE_MAGNUM, top_type=pa.TopType.SHORT_HAIR_SHAGGY_MULLET, mouth_type=pa.MouthType.SCREAM_OPEN, eye_type=pa.EyesType.SQUINT, eyebrow_type=pa.EyebrowType.RAISED_EXCITED_NATURAL, nose_type=pa.NoseType.DEFAULT, accessories_type=pa.AccessoriesType.PRESCRIPTION_02, clothe_type=pa.ClotheType.HOODIE, clothe_graphic_type=pa.ClotheGraphicType.BAT,) # rendering the avatar in png formatavatar.render_png_file(\"AVATAR_2.png\")", "e": 3137, "s": 2175, "text": null }, { "code": null, "e": 3145, "s": 3137, "text": "Output:" }, { "code": null, "e": 3429, "s": 3145, "text": "You can always change the parameters of the avatar accordingly by pressing the Ctrl button and hovering over the py_avataaars line, which will turn it blue and then you can click on it to see __init__.py file, where you can find all the parameters, each written in a different class." }, { "code": null, "e": 3445, "s": 3429, "text": "Demonstration: " }, { "code": null, "e": 3461, "s": 3445, "text": "Python-projects" }, { "code": null, "e": 3476, "s": 3461, "text": "python-utility" }, { "code": null, "e": 3500, "s": 3476, "text": "Technical Scripter 2020" }, { "code": null, "e": 3507, "s": 3500, "text": "Python" }, { "code": null, "e": 3526, "s": 3507, "text": "Technical Scripter" } ]
Python – Sum of each List element occurrence in another
09 Mar, 2020 Sometimes, while working with Python, we can have a problem in which we need to get occurrence of 1 element in another. But as a modification of this, we can have a problem in which we need to count the occurrence of all elements of 1 list in another. Lets discuss certain ways in which this task can be performed. Method #1 : Using nested loopsThis is one of the way in which this task can be performed. This is brute force way in which this task can be performed. In this, we iterate one list and then target list, if element match, we increase the counter. # Python3 code to demonstrate # Sum of each List element occurrence in another# using nested loops # Initializing liststest_list1 = [1, 3, 4, 5, 1, 4, 4, 6, 7]test_list2 = [4, 6, 1] # printing original listsprint("The original list 1 is : " + str(test_list1))print("The original list 2 is : " + str(test_list2)) # Sum of each List element occurrence in another# using nested loopsres = 0for ele in test_list2: for ele1 in test_list1: if ele1 == ele: res = res + 1 # printing result print ("The occurrence count : " + str(res)) The original list 1 is : [1, 3, 4, 5, 1, 4, 4, 6, 7] The original list 2 is : [4, 6, 1] The occurrence count : 6 Method #2 : Using sum() + count()The combination of above methods can be used to perform this particular task. This is one liner alternative to the above method. In this counting is done using count() and accumulation using sum(). # Python3 code to demonstrate # Sum of each List element occurrence in another# using sum() + count() # Initializing liststest_list1 = [1, 3, 4, 5, 1, 4, 4, 6, 7]test_list2 = [4, 6, 1] # printing original listsprint("The original list 1 is : " + str(test_list1))print("The original list 2 is : " + str(test_list2)) # Sum of each List element occurrence in another# using sum() + count()res = sum(test_list1.count(idx) for idx in test_list2) # printing result print ("The occurrence count : " + str(res)) The original list 1 is : [1, 3, 4, 5, 1, 4, 4, 6, 7] The original list 2 is : [4, 6, 1] The occurrence count : 6 Python list-programs Python Python Programs 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 How to Install PIP on Windows ? Python program to convert a list to string Defaultdict in Python Python | Get dictionary keys as a list Python | Convert a list to dictionary Python Program for Fibonacci numbers
[ { "code": null, "e": 28, "s": 0, "text": "\n09 Mar, 2020" }, { "code": null, "e": 343, "s": 28, "text": "Sometimes, while working with Python, we can have a problem in which we need to get occurrence of 1 element in another. But as a modification of this, we can have a problem in which we need to count the occurrence of all elements of 1 list in another. Lets discuss certain ways in which this task can be performed." }, { "code": null, "e": 588, "s": 343, "text": "Method #1 : Using nested loopsThis is one of the way in which this task can be performed. This is brute force way in which this task can be performed. In this, we iterate one list and then target list, if element match, we increase the counter." }, { "code": "# Python3 code to demonstrate # Sum of each List element occurrence in another# using nested loops # Initializing liststest_list1 = [1, 3, 4, 5, 1, 4, 4, 6, 7]test_list2 = [4, 6, 1] # printing original listsprint(\"The original list 1 is : \" + str(test_list1))print(\"The original list 2 is : \" + str(test_list2)) # Sum of each List element occurrence in another# using nested loopsres = 0for ele in test_list2: for ele1 in test_list1: if ele1 == ele: res = res + 1 # printing result print (\"The occurrence count : \" + str(res))", "e": 1140, "s": 588, "text": null }, { "code": null, "e": 1254, "s": 1140, "text": "The original list 1 is : [1, 3, 4, 5, 1, 4, 4, 6, 7]\nThe original list 2 is : [4, 6, 1]\nThe occurrence count : 6\n" }, { "code": null, "e": 1487, "s": 1256, "text": "Method #2 : Using sum() + count()The combination of above methods can be used to perform this particular task. This is one liner alternative to the above method. In this counting is done using count() and accumulation using sum()." }, { "code": "# Python3 code to demonstrate # Sum of each List element occurrence in another# using sum() + count() # Initializing liststest_list1 = [1, 3, 4, 5, 1, 4, 4, 6, 7]test_list2 = [4, 6, 1] # printing original listsprint(\"The original list 1 is : \" + str(test_list1))print(\"The original list 2 is : \" + str(test_list2)) # Sum of each List element occurrence in another# using sum() + count()res = sum(test_list1.count(idx) for idx in test_list2) # printing result print (\"The occurrence count : \" + str(res))", "e": 1995, "s": 1487, "text": null }, { "code": null, "e": 2109, "s": 1995, "text": "The original list 1 is : [1, 3, 4, 5, 1, 4, 4, 6, 7]\nThe original list 2 is : [4, 6, 1]\nThe occurrence count : 6\n" }, { "code": null, "e": 2130, "s": 2109, "text": "Python list-programs" }, { "code": null, "e": 2137, "s": 2130, "text": "Python" }, { "code": null, "e": 2153, "s": 2137, "text": "Python Programs" }, { "code": null, "e": 2251, "s": 2153, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 2269, "s": 2251, "text": "Python Dictionary" }, { "code": null, "e": 2311, "s": 2269, "text": "Different ways to create Pandas Dataframe" }, { "code": null, "e": 2333, "s": 2311, "text": "Enumerate() in Python" }, { "code": null, "e": 2368, "s": 2333, "text": "Read a file line by line in Python" }, { "code": null, "e": 2400, "s": 2368, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 2443, "s": 2400, "text": "Python program to convert a list to string" }, { "code": null, "e": 2465, "s": 2443, "text": "Defaultdict in Python" }, { "code": null, "e": 2504, "s": 2465, "text": "Python | Get dictionary keys as a list" }, { "code": null, "e": 2542, "s": 2504, "text": "Python | Convert a list to dictionary" } ]
FittedBox in Flutter
14 Aug, 2020 Flutter is all about widgets. There are many widgets that are used for positioning and styling of text. In this article, we’ll learn about the FittedBox widget. FittedBox is a very useful widget that scales and positions its child within itself according to fit and alignment. Consider an app, in which, you have to take input from the user and in a certain scenario, the user enters a large input that overflows and scatters other widgets. As many of the widgets are dynamic, which means they can grow and shrink in size, according to their child widget’s size. So, in this case, the user interface wouldn’t be adaptive. In order to overcome this problem, we can use the FittedBox widget. FittedBox restricts its child widgets from growing its size beyond a certain limit. It re-scales them according to the size available. For instance, if the text is displayed inside a container, and the text is to be entered by the user. If the user enters a large string of text, then the container would grow beyond its allocated size. But, if we wrap it with FittedBox, then it would fit the text according to the size available. For large string, it would shrink its size, hence would fit in the container. Syntax: FittedBox({ Key key, BoxFit fit: BoxFit.contain, AlignmentGeometry alignment: Alignment.center, Widget child } ) 1. fit: This property is of type BoxFit. It is used to describe how a box is inscribed in another box. It caters to sizing semantics. Now, we’ll see it’s properties: contain: Using this property, we contain the source entirely in the target box, no matter how large it may be. cover: It makes the source as small as possible, while still covering the entire target box. fill: It fills the entire target box, impacting the source’s aspect ratio. fitHeight: It ensures that the full height of the source is shown, even if it overflows the target box horizontally. fitWidth: It ensures that the full width of the source is shown, even if it overflows the target box vertically. none: It aligns the source inside the target box and remove any extra portions from the source, if any, as it doesn’t resize the image. 2. alignment: This property is used to align the child widget in FittedBox. Various attributes for this property are bottomCenter, bottomLeft, bottomRight, center, centerLeft, centerRight, topCenter, topLeft, topRight. As the name suggests, the child widget is aligned according to one of these properties. You can also assign position co-ordinates to align the widgets. 3. child: This is the required property in FittedBox. The widget which we want to wrap in FittedBox is assigned as a child to FittedBox. It only takes one child widget. Any widget that displays something on-screen, most preferably text, can be wrapped with FittedBox. Example: Dart import 'package:flutter/material.dart'; void main() => runApp(MyApp()); class MyApp extends StatelessWidget { @override Widget build(BuildContext context) { return MaterialApp( home: Scaffold( appBar: AppBar( title: Text('GeeksforGeeks'), backgroundColor: Colors.green, ), body: Container( alignment: Alignment.center, child: Column( children: [ SizedBox(height: 10), // Without FittedBox Container( decoration: BoxDecoration( border: Border.all(width: 2, color: Colors.green ) ), child: Text('This is explanation'), width: 80, height: 20, ), SizedBox( height: 12, ), // With FittedBox Container( decoration: BoxDecoration( border: Border.all(width: 2, color: Colors.green), ), child: FittedBox( child: Text('This is explanation') ), width: 80, height: 20, ), SizedBox( height: 100, ), ], ), ), ), ); }} Output: In the above example, we have taken two containers to demonstrate the use of FittedBox. Both the containers have the same height and the same width. The first container is not wrapped in FittedBox and the text “This is Explanation” is given to it as a child. Since the container has limited height and width, so it can accommodate only partial text. But, in the second case, we have wrapped Text widget with FittedBox and the same constraints are also passed to this container. We here see that the whole text is accommodated in the container. It is because FittedBox scales down the text to fit in the Container. It is very useful in that scenario when you have to limit the widget from expanding or shrinking, but you also have to adjust child widgets according to that constraints, as it makes UI better. Flutter Dart Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 54, "s": 26, "text": "\n14 Aug, 2020" }, { "code": null, "e": 744, "s": 54, "text": "Flutter is all about widgets. There are many widgets that are used for positioning and styling of text. In this article, we’ll learn about the FittedBox widget. FittedBox is a very useful widget that scales and positions its child within itself according to fit and alignment. Consider an app, in which, you have to take input from the user and in a certain scenario, the user enters a large input that overflows and scatters other widgets. As many of the widgets are dynamic, which means they can grow and shrink in size, according to their child widget’s size. So, in this case, the user interface wouldn’t be adaptive. In order to overcome this problem, we can use the FittedBox widget." }, { "code": null, "e": 1255, "s": 744, "text": "FittedBox restricts its child widgets from growing its size beyond a certain limit. It re-scales them according to the size available. For instance, if the text is displayed inside a container, and the text is to be entered by the user. If the user enters a large string of text, then the container would grow beyond its allocated size. But, if we wrap it with FittedBox, then it would fit the text according to the size available. For large string, it would shrink its size, hence would fit in the container. " }, { "code": null, "e": 1399, "s": 1255, "text": "Syntax:\n\nFittedBox({\n Key key,\n BoxFit fit: BoxFit.contain,\n AlignmentGeometry alignment: Alignment.center,\n Widget child\n }\n)\n" }, { "code": null, "e": 1565, "s": 1399, "text": "1. fit: This property is of type BoxFit. It is used to describe how a box is inscribed in another box. It caters to sizing semantics. Now, we’ll see it’s properties:" }, { "code": null, "e": 1676, "s": 1565, "text": "contain: Using this property, we contain the source entirely in the target box, no matter how large it may be." }, { "code": null, "e": 1769, "s": 1676, "text": "cover: It makes the source as small as possible, while still covering the entire target box." }, { "code": null, "e": 1845, "s": 1769, "text": "fill: It fills the entire target box, impacting the source’s aspect ratio." }, { "code": null, "e": 1962, "s": 1845, "text": "fitHeight: It ensures that the full height of the source is shown, even if it overflows the target box horizontally." }, { "code": null, "e": 2075, "s": 1962, "text": "fitWidth: It ensures that the full width of the source is shown, even if it overflows the target box vertically." }, { "code": null, "e": 2211, "s": 2075, "text": "none: It aligns the source inside the target box and remove any extra portions from the source, if any, as it doesn’t resize the image." }, { "code": null, "e": 2582, "s": 2211, "text": "2. alignment: This property is used to align the child widget in FittedBox. Various attributes for this property are bottomCenter, bottomLeft, bottomRight, center, centerLeft, centerRight, topCenter, topLeft, topRight. As the name suggests, the child widget is aligned according to one of these properties. You can also assign position co-ordinates to align the widgets." }, { "code": null, "e": 2851, "s": 2582, "text": " 3. child: This is the required property in FittedBox. The widget which we want to wrap in FittedBox is assigned as a child to FittedBox. It only takes one child widget. Any widget that displays something on-screen, most preferably text, can be wrapped with FittedBox." }, { "code": null, "e": 2860, "s": 2851, "text": "Example:" }, { "code": null, "e": 2865, "s": 2860, "text": "Dart" }, { "code": "import 'package:flutter/material.dart'; void main() => runApp(MyApp()); class MyApp extends StatelessWidget { @override Widget build(BuildContext context) { return MaterialApp( home: Scaffold( appBar: AppBar( title: Text('GeeksforGeeks'), backgroundColor: Colors.green, ), body: Container( alignment: Alignment.center, child: Column( children: [ SizedBox(height: 10), // Without FittedBox Container( decoration: BoxDecoration( border: Border.all(width: 2, color: Colors.green ) ), child: Text('This is explanation'), width: 80, height: 20, ), SizedBox( height: 12, ), // With FittedBox Container( decoration: BoxDecoration( border: Border.all(width: 2, color: Colors.green), ), child: FittedBox( child: Text('This is explanation') ), width: 80, height: 20, ), SizedBox( height: 100, ), ], ), ), ), ); }}", "e": 4237, "s": 2865, "text": null }, { "code": null, "e": 4245, "s": 4237, "text": "Output:" }, { "code": null, "e": 4859, "s": 4245, "text": "In the above example, we have taken two containers to demonstrate the use of FittedBox. Both the containers have the same height and the same width. The first container is not wrapped in FittedBox and the text “This is Explanation” is given to it as a child. Since the container has limited height and width, so it can accommodate only partial text. But, in the second case, we have wrapped Text widget with FittedBox and the same constraints are also passed to this container. We here see that the whole text is accommodated in the container. It is because FittedBox scales down the text to fit in the Container." }, { "code": null, "e": 5053, "s": 4859, "text": "It is very useful in that scenario when you have to limit the widget from expanding or shrinking, but you also have to adjust child widgets according to that constraints, as it makes UI better." }, { "code": null, "e": 5061, "s": 5053, "text": "Flutter" }, { "code": null, "e": 5066, "s": 5061, "text": "Dart" } ]
Divide a Vector into Ranges in R Programming – cut() Function
12 Jun, 2020 cut() function in R Language is used to divide a numeric vector into different ranges. Syntax:cut.default(x, breaks, labels = NULL, include.lowest = FALSE, right = TRUE, dig.lab = 3) Parameters:x: Numeric Vectorbreak: break points of the vectorlabels: labels for levelsinclude.lowest: Boolean value to include lowest break valueright: Boolean value to close interval on the rightdig.lab: Used when labels are not provided Example 1: # R program to divide vector into ranges # Generating a vector with random numbers y <- rnorm(100) # the output factor is created by the division # of the range of variables into pi / 3*(-3:3) # 4 equal-length intervals table(cut(y, breaks = pi / 3*(-3:3))) Output: (-3.14, -2.09] (-2.09, -1.05] (-1.05, 0] (0, 1.05] (1.05, 2.09] 0 12 33 40 12 (2.09, 3.14] 2 Example 2: # R program to divide vector into ranges # Creating vectors age <- c(40, 49, 48, 40, 67, 52, 53) salary <- c(103200, 106200, 150200, 10606, 10390, 14070, 10220) gender <- c("male", "male", "transgender", "female", "male", "female", "transgender") # Creating data frame named employee employee<- data.frame(age, salary, gender) # Creating a factor corresponding to age with labels wfact = cut(employee$age, 3, labels = c('Young', 'Medium', 'Aged')) table(wfact) Output: wfact Young Medium Aged 4 2 1 R Vector-Function R Language Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n12 Jun, 2020" }, { "code": null, "e": 115, "s": 28, "text": "cut() function in R Language is used to divide a numeric vector into different ranges." }, { "code": null, "e": 211, "s": 115, "text": "Syntax:cut.default(x, breaks, labels = NULL, include.lowest = FALSE, right = TRUE, dig.lab = 3)" }, { "code": null, "e": 450, "s": 211, "text": "Parameters:x: Numeric Vectorbreak: break points of the vectorlabels: labels for levelsinclude.lowest: Boolean value to include lowest break valueright: Boolean value to close interval on the rightdig.lab: Used when labels are not provided" }, { "code": null, "e": 461, "s": 450, "text": "Example 1:" }, { "code": "# R program to divide vector into ranges # Generating a vector with random numbers y <- rnorm(100) # the output factor is created by the division # of the range of variables into pi / 3*(-3:3) # 4 equal-length intervals table(cut(y, breaks = pi / 3*(-3:3))) ", "e": 725, "s": 461, "text": null }, { "code": null, "e": 733, "s": 725, "text": "Output:" }, { "code": null, "e": 912, "s": 733, "text": "(-3.14, -2.09] (-2.09, -1.05] (-1.05, 0] (0, 1.05] (1.05, 2.09] \n 0 12 33 40 12 \n (2.09, 3.14] \n 2 \n" }, { "code": null, "e": 923, "s": 912, "text": "Example 2:" }, { "code": "# R program to divide vector into ranges # Creating vectors age <- c(40, 49, 48, 40, 67, 52, 53) salary <- c(103200, 106200, 150200, 10606, 10390, 14070, 10220) gender <- c(\"male\", \"male\", \"transgender\", \"female\", \"male\", \"female\", \"transgender\") # Creating data frame named employee employee<- data.frame(age, salary, gender) # Creating a factor corresponding to age with labels wfact = cut(employee$age, 3, labels = c('Young', 'Medium', 'Aged')) table(wfact) ", "e": 1410, "s": 923, "text": null }, { "code": null, "e": 1418, "s": 1410, "text": "Output:" }, { "code": null, "e": 1469, "s": 1418, "text": "wfact\n Young Medium Aged \n 4 2 1 \n" }, { "code": null, "e": 1487, "s": 1469, "text": "R Vector-Function" }, { "code": null, "e": 1498, "s": 1487, "text": "R Language" } ]
How to wait for a promise to finish before returning the variable of a function?
11 Oct, 2019 Here a promise is a returned object from an asynchronous function, to that callback methods can be added based on the previous function’s result. It is done for back-to-back execution of functions acting like a queue or chain of functions. So as the functions are in the queue, the functions following it must wait for the previous function’s result. To do that there is two popular way described below. Use of setTimeout() function Use of async or await() function Use of setTimeout() function: In order to wait for a promise to finish before returning the variable, the function can be set with setTimeout(), so that the function waits for a few milliseconds. Below program will illustrate the approach:Program : <script>const wait=ms=>new Promise(resolve => setTimeout(resolve, ms)); function failureCallback(){ console.log("This is failure callback");} wait(4*1000).then(() => { console.log("waited for 4 seconds"); throw new Error("error occurred");}).catch(() => { failureCallback();}); wait(2*1000).then(() => console.log("waited for 2 seconds")); </script> Output: waited for 2 seconds waited for 4 seconds This is failure callback Use of async or await() function: This method can be used if the exact time required in setTimeout() cannot be specified. The async keyword is used to create an asynchronous function that returns a promise that is either rejected or resolved. The promise is rejected when there is an uncaught exception thrown from that function or it is resolved otherwise. The await keyword is used inside an async function to pause its execution and wait for the promise. Below program will illustrate the approach:program : <script>//This function returns promise after 2 secondsvar first_function = function() {console.log("Entered first function");return new Promise(resolve => { setTimeout(function() { resolve("\t\t This is first promise"); console.log("Returned first promise"); }, 2000);});};//This function executes returns promise after 4 secondsvar second_function = function() {console.log("Entered second function");return new Promise(resolve => { setTimeout(function() { resolve("\t\t This is second promise"); console.log("Returned second promise"); }, 4000);});}; var async_function = async function() {console.log('async function called'); const first_promise= await first_function();console.log("After awaiting for 2 seconds," +"the promise returned from first function is:");console.log(first_promise); const second_promise= await second_function();console.log("After awaiting for 4 seconds, the" + "promise returned from second function is:");console.log(second_promise);} async_function(); </script> Output : async function called Entered first function Returned first promise After awaiting for 2 seconds, the promise returned from first function is: This is first promise Entered second function Returned second promise After awaiting for 4 seconds, the promise returned from second function is: This is second promise javascript-functions Picked JavaScript Technical Scripter Web Technologies Web technologies Questions Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 54, "s": 26, "text": "\n11 Oct, 2019" }, { "code": null, "e": 458, "s": 54, "text": "Here a promise is a returned object from an asynchronous function, to that callback methods can be added based on the previous function’s result. It is done for back-to-back execution of functions acting like a queue or chain of functions. So as the functions are in the queue, the functions following it must wait for the previous function’s result. To do that there is two popular way described below." }, { "code": null, "e": 487, "s": 458, "text": "Use of setTimeout() function" }, { "code": null, "e": 520, "s": 487, "text": "Use of async or await() function" }, { "code": null, "e": 716, "s": 520, "text": "Use of setTimeout() function: In order to wait for a promise to finish before returning the variable, the function can be set with setTimeout(), so that the function waits for a few milliseconds." }, { "code": null, "e": 769, "s": 716, "text": "Below program will illustrate the approach:Program :" }, { "code": "<script>const wait=ms=>new Promise(resolve => setTimeout(resolve, ms)); function failureCallback(){ console.log(\"This is failure callback\");} wait(4*1000).then(() => { console.log(\"waited for 4 seconds\"); throw new Error(\"error occurred\");}).catch(() => { failureCallback();}); wait(2*1000).then(() => console.log(\"waited for 2 seconds\")); </script>", "e": 1153, "s": 769, "text": null }, { "code": null, "e": 1161, "s": 1153, "text": "Output:" }, { "code": null, "e": 1229, "s": 1161, "text": "waited for 2 seconds\nwaited for 4 seconds\nThis is failure callback\n" }, { "code": null, "e": 1687, "s": 1229, "text": "Use of async or await() function: This method can be used if the exact time required in setTimeout() cannot be specified. The async keyword is used to create an asynchronous function that returns a promise that is either rejected or resolved. The promise is rejected when there is an uncaught exception thrown from that function or it is resolved otherwise. The await keyword is used inside an async function to pause its execution and wait for the promise." }, { "code": null, "e": 1740, "s": 1687, "text": "Below program will illustrate the approach:program :" }, { "code": "<script>//This function returns promise after 2 secondsvar first_function = function() {console.log(\"Entered first function\");return new Promise(resolve => { setTimeout(function() { resolve(\"\\t\\t This is first promise\"); console.log(\"Returned first promise\"); }, 2000);});};//This function executes returns promise after 4 secondsvar second_function = function() {console.log(\"Entered second function\");return new Promise(resolve => { setTimeout(function() { resolve(\"\\t\\t This is second promise\"); console.log(\"Returned second promise\"); }, 4000);});}; var async_function = async function() {console.log('async function called'); const first_promise= await first_function();console.log(\"After awaiting for 2 seconds,\" +\"the promise returned from first function is:\");console.log(first_promise); const second_promise= await second_function();console.log(\"After awaiting for 4 seconds, the\" + \"promise returned from second function is:\");console.log(second_promise);} async_function(); </script> ", "e": 2799, "s": 1740, "text": null }, { "code": null, "e": 2808, "s": 2799, "text": "Output :" }, { "code": null, "e": 3155, "s": 2808, "text": "async function called\nEntered first function\nReturned first promise\nAfter awaiting for 2 seconds, the promise returned from first function is:\n This is first promise\nEntered second function\nReturned second promise\nAfter awaiting for 4 seconds, the promise returned from second function is:\n This is second promise\n" }, { "code": null, "e": 3176, "s": 3155, "text": "javascript-functions" }, { "code": null, "e": 3183, "s": 3176, "text": "Picked" }, { "code": null, "e": 3194, "s": 3183, "text": "JavaScript" }, { "code": null, "e": 3213, "s": 3194, "text": "Technical Scripter" }, { "code": null, "e": 3230, "s": 3213, "text": "Web Technologies" }, { "code": null, "e": 3257, "s": 3230, "text": "Web technologies Questions" } ]
Excel – Working with DATE Functions With Examples
13 Dec, 2021 The DATE function is used to calculate dates in Excel. Excel provides different functions to work with dates & times such as TODAY, NOW, WEEKDAY, EOMONTH, etc. which we will discuss here with examples. The purpose of discussing DATE functions in Excel is to help different people to perform more complex and challenging tasks by combining several functions within one formula. It will return the date in serial number based on the year, month, or day value as provided. Syntax:DATE(year,month,day) Arguments: 1.Year:-This argument includes 1 to 4 digit value. Excel understand this year argument according to the date system of the local computer which we use. For example-Excel windows uses 1900 date system by default which means DATE(21,2,6) gives result as 06-02-1921. 2.Month:-This argument include positive or negative integer which represents the month of year from January to December. 3.Day:-This argument also include positive or negative integer representing day of the month from 1 to 31. Example 1: Example 2: It will return on the first day of the current year & month. Example 3: The TODAY() function name suggests it will return today’s date, and it has no arguments. Syntax: TODAY() Example1: Here we will print the current date and also add 10 days to the current date. Example 2: This function returns the current date as well as time & doesn’t have any arguments. Syntax: NOW() Example: It converts the date in text format to a serial number which can be represented as a date. Syntax: DATEVALUE(date_text) Arguments: 1. date_text:-This argument is a text that represents the date in Excel date format. Example: It converts any numeric value not only dates to a text string. Through this function, we can change the date to text strings in a variety of formats. Syntax: TEXT(value,format_text) Arguments: 1. value: The value that is to be converted. 2. format_text: The format in which you want to output the date value. These are the different formats used in the TEXT function to change dates to text strings. Example 1: Example 2: Example 3: It returns the day of a month i.e. integer from 1 to 31. Syntax: DAY(serial_number) Arguments: 1. serial_number: This value represents the day of the month you want to find. E.g: 5th day of june Example 1: Example 2: The DAY(TODAY()) function returns the day of today’s date as shown below: This function returns the month of the given date as an integer from 1 to 12 (January to December). Syntax: MONTH(serial_number) Arguments: 1. serial_number: This value represents the date for which you want to find the month. Example: The MONTH(TODAY()) function returns the month of today’s date. It returns the year of a specified date. Syntax: YEAR(serial_number) Arguments: 1. serial_number: The date to be specified. Example 1: Example 2: Example 3: This function returns the last day of the month after adding a specified number of months to a given date. Syntax: EOMONTH(start_date,months) Arguments: 1. start_date: In this argument, the date should be written in date format, not in the text. 2. months: In this argument, if a positive integer is given then corresponding months can be added to the start date & if a negative integer is given then corresponding months can be subtracted to the start date. Example 1: Example 2: Example 3: The EOMONTH(TODAY(),0) function returns the last day of the current month. This function returns the day of the week as a number from 1 to 7(Sunday to Saturday) according to the specified date. Syntax: WEEKDAY(serial_number,return_type) Arguments: 1. serial_number: It can be a date or the cell that contains the date. 2. return_type: It is optional as it specifies which day should be considered as the first day of week. NOTE:1st day of the week is by default Sunday. Example 1: Example 2: In the below example, 2 is given as return_type i.e. Monday is referred to as the first day of the week. Example 3: Here the day of todays(01-04-2021) date is the result & the default value (Sunday) is considered here because no return_type is given. This function calculates the difference between two dates in days, months, or years. For calculating the difference b/w dates which time interval should be used depends on the letter which we specify in our last argument i.e. at the unit. Syntax: DATEDIF(start_date,end_date,unit) Arguments: 1. start_date: The start date for evaluating the difference. 2. end_date: The end Date for evaluating the difference. Example 1: Example 2: Example 3: Here “m”,”y”,”d” means month, year & date. In the first example, the difference between dates is calculated by months, second by year & third by date. It returns the week number based on the specified date i.e. from 1 to 52 weeks of the year. Syntax: WEEKNUM(serial_number,firstday_ofweek) Arguments: 1. serial_number:This is the date for which we want the week number. 2. firstday_ofweek: This is optional arguments that specify which numbering system should be considered & which day of the week can be treated as start of the week,Default(omitted) is 1. The table below is the parameters that can be given in firstday_ofweek arguments. First Day of the Week Start Table Example 1: Example 2: Example 3: In the below example,21 is given as the second argument that means Monday is taken as the first day of the week & in the above example, the result shown is 15 but by taking 21 as the first_dayofweek means Monday as the first day the result is 14. This function adds or subtracts the specified month to a given date. Syntax: EDATE(start_date,months) Arguments: 1. start_date: This is an initial date on which the months are added or subtracted. 2. months: This is the number of months which is to be added or subtracted in the specified date. Example 1: Example 2: Example 3: This function returns the fraction of the year which represents the number of whole days between the start & end date. Syntax: YEARFRAC(start_date,end_date,[basis]) Arguments: 1. start_date: This is the start date in the serial number. 2. end_date: This is the end date in the serial number. 3. basis: This is the optional argument that specifies the day count method. Example 1: Using someday count methods. Example 2: Example 3: This function helps if we exactly know how many working days we have & want to find out the date when the number of working will skip. This function always includes working days & excludes weekend days. Syntax: WORKDAY(start_date,days,holidays) Arguments: 1. start_date: This argument is the date from which the counting of weekdays begins. Excel doesn't include start_date as a working day. 2. days: This is the number of working days. 3. holidays: This is an optional argument. If the days mentioned include any holidays then we need to make a list of holidays separately for this and mention it here. Example 1: 28 workdays from the start date, excluding holidays. Example 2: 28 workdays before the start date, excluding holidays Example 3: 28 workdays from the start date, no holidays. Example 4: 28 workdays from today’s date, no holidays. This is a modification of the WORKDAY function as it provides a custom weekend parameter which distinguishes this from the WORKDAY function. Syntax: WORKDAY.INTL(start_date,days,[weekends],holidays) Arguments: 1. start_date: This argument is the date from which the counting of weekdays begins. Excel doesn't include start_date as a working day. 2. days: This is the number of working days. 3. holidays: This is an optional argument. If the days mentioned include any holidays then we need to make a list of holidays separately for this and mention it here. 4. weekends: Through this argument we can specify which days of the week to be treated as non working days either by weekend number or specific character string. If this weekend argument is blank in this function then it will automatically take the combination of Saturday & Sunday. For instance: “0000011”-Saturday & Sunday are weekends(non-working days) “1000010”-Monday & Saturday are weekends(non-working days) Example 1: 30 days from the start date, excluding holidays & Sunday, Monday as weekends(by giving weekend number 2 as arguments). Example 2: 30 days from the start date, excluding holidays & Sunday, Monday as weekends(by giving weekend string “1000001” as arguments). Example 3: 20 days from the start date, no holidays & Monday, Saturday as weekends( by giving weekend string “1000010” as arguments). This function returns the number of working days between two dates excluding weekends & holidays is as optional arguments. Syntax: NETWORKDAYS(start_date,end_date,holidays) Arguments: 1. start_date: The initial date to start evaluation. 2. end_date: The last date to end the evaluation. 4. holidays: Used to specify holidays. Example 1: Example 2: This function also returns the number of working days between two dates but provides additional argument weekend to specify which days should be counted as weekend days. The structure of the weekend argument is the same as for WORKDAY.INTL i.e. we can use either weekend number or character string. Syntax: NETWORKDAYS.INTL(start_date,end_date,[weekend],holidays) Arguments: 1. start_date: The initial date to start evaluation. 2. end_date: The last date to end the evaluation. 3. weekend: Use to specify the weekends. 4. holidays: Used to specify holidays. Example 1: Here weekend argument is given in form of a number. Example 2: Here weekend argument is given in form of a character string of 0’s & 1’s. akshaysingh98088 surindertarika1234 Picked Excel Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to Delete Blank Columns in Excel? How to Normalize Data in Excel? How to Get Length of Array in Excel VBA? How to Use Solver in Excel? Macros in Excel How to Find the Last Used Row and Column in Excel VBA? How to Show Percentages in Stacked Column Chart in Excel? How to make a 3 Axis Graph using Excel? Introduction to Excel Spreadsheet How to Extract the Last Word From a Cell in Excel?
[ { "code": null, "e": 52, "s": 24, "text": "\n13 Dec, 2021" }, { "code": null, "e": 254, "s": 52, "text": "The DATE function is used to calculate dates in Excel. Excel provides different functions to work with dates & times such as TODAY, NOW, WEEKDAY, EOMONTH, etc. which we will discuss here with examples." }, { "code": null, "e": 429, "s": 254, "text": "The purpose of discussing DATE functions in Excel is to help different people to perform more complex and challenging tasks by combining several functions within one formula." }, { "code": null, "e": 522, "s": 429, "text": "It will return the date in serial number based on the year, month, or day value as provided." }, { "code": null, "e": 1100, "s": 522, "text": "Syntax:DATE(year,month,day)\n\nArguments:\n\n1.Year:-This argument includes 1 to 4 digit value. Excel understand this year argument\n according to the date system of the local computer which we use.\n For example-Excel windows uses 1900 date system by default which\n means DATE(21,2,6) gives result as 06-02-1921.\n2.Month:-This argument include positive or negative integer which represents the month\n of year from January to December.\n3.Day:-This argument also include positive or negative integer representing day of the month\n from 1 to 31." }, { "code": null, "e": 1111, "s": 1100, "text": "Example 1:" }, { "code": null, "e": 1183, "s": 1111, "text": "Example 2: It will return on the first day of the current year & month." }, { "code": null, "e": 1194, "s": 1183, "text": "Example 3:" }, { "code": null, "e": 1283, "s": 1194, "text": "The TODAY() function name suggests it will return today’s date, and it has no arguments." }, { "code": null, "e": 1299, "s": 1283, "text": "Syntax: TODAY()" }, { "code": null, "e": 1387, "s": 1299, "text": "Example1: Here we will print the current date and also add 10 days to the current date." }, { "code": null, "e": 1398, "s": 1387, "text": "Example 2:" }, { "code": null, "e": 1483, "s": 1398, "text": "This function returns the current date as well as time & doesn’t have any arguments." }, { "code": null, "e": 1497, "s": 1483, "text": "Syntax: NOW()" }, { "code": null, "e": 1506, "s": 1497, "text": "Example:" }, { "code": null, "e": 1597, "s": 1506, "text": "It converts the date in text format to a serial number which can be represented as a date." }, { "code": null, "e": 1723, "s": 1597, "text": "Syntax: DATEVALUE(date_text)\n\nArguments:\n1. date_text:-This argument is a text that represents the date in Excel date format." }, { "code": null, "e": 1732, "s": 1723, "text": "Example:" }, { "code": null, "e": 1882, "s": 1732, "text": "It converts any numeric value not only dates to a text string. Through this function, we can change the date to text strings in a variety of formats." }, { "code": null, "e": 2043, "s": 1882, "text": "Syntax: TEXT(value,format_text)\n\nArguments: \n1. value: The value that is to be converted.\n2. format_text: The format in which you want to output the date value." }, { "code": null, "e": 2134, "s": 2043, "text": "These are the different formats used in the TEXT function to change dates to text strings." }, { "code": null, "e": 2146, "s": 2134, "text": "Example 1: " }, { "code": null, "e": 2157, "s": 2146, "text": "Example 2:" }, { "code": null, "e": 2168, "s": 2157, "text": "Example 3:" }, { "code": null, "e": 2225, "s": 2168, "text": "It returns the day of a month i.e. integer from 1 to 31." }, { "code": null, "e": 2382, "s": 2225, "text": "Syntax: DAY(serial_number)\n\nArguments:\n1. serial_number: This value represents the day of the month you want to find.\n E.g: 5th day of june" }, { "code": null, "e": 2393, "s": 2382, "text": "Example 1:" }, { "code": null, "e": 2404, "s": 2393, "text": "Example 2:" }, { "code": null, "e": 2478, "s": 2404, "text": "The DAY(TODAY()) function returns the day of today’s date as shown below:" }, { "code": null, "e": 2578, "s": 2478, "text": "This function returns the month of the given date as an integer from 1 to 12 (January to December)." }, { "code": null, "e": 2707, "s": 2578, "text": "Syntax: MONTH(serial_number)\n\nArguments: \n1. serial_number: This value represents the date for which you want to find the month." }, { "code": null, "e": 2716, "s": 2707, "text": "Example:" }, { "code": null, "e": 2780, "s": 2716, "text": "The MONTH(TODAY()) function returns the month of today’s date." }, { "code": null, "e": 2821, "s": 2780, "text": "It returns the year of a specified date." }, { "code": null, "e": 2905, "s": 2821, "text": "Syntax: YEAR(serial_number)\n\nArguments:\n1. serial_number: The date to be specified." }, { "code": null, "e": 2916, "s": 2905, "text": "Example 1:" }, { "code": null, "e": 2927, "s": 2916, "text": "Example 2:" }, { "code": null, "e": 2938, "s": 2927, "text": "Example 3:" }, { "code": null, "e": 3045, "s": 2938, "text": "This function returns the last day of the month after adding a specified number of months to a given date." }, { "code": null, "e": 3420, "s": 3045, "text": "Syntax: EOMONTH(start_date,months)\n\nArguments:\n1. start_date: In this argument, the date should be written in date format, not in the text.\n2. months: In this argument, if a positive integer is given then corresponding months can be\n added to the start date & if a negative integer is given then corresponding months\n can be subtracted to the start date." }, { "code": null, "e": 3431, "s": 3420, "text": "Example 1:" }, { "code": null, "e": 3442, "s": 3431, "text": "Example 2:" }, { "code": null, "e": 3453, "s": 3442, "text": "Example 3:" }, { "code": null, "e": 3528, "s": 3453, "text": "The EOMONTH(TODAY(),0) function returns the last day of the current month." }, { "code": null, "e": 3648, "s": 3528, "text": "This function returns the day of the week as a number from 1 to 7(Sunday to Saturday) according to the specified date." }, { "code": null, "e": 3895, "s": 3648, "text": "Syntax: WEEKDAY(serial_number,return_type)\n \nArguments:\n1. serial_number: It can be a date or the cell that contains the date.\n2. return_type: It is optional as it specifies which day should be considered\n as the first day of week." }, { "code": null, "e": 3942, "s": 3895, "text": "NOTE:1st day of the week is by default Sunday." }, { "code": null, "e": 3953, "s": 3942, "text": "Example 1:" }, { "code": null, "e": 4069, "s": 3953, "text": "Example 2: In the below example, 2 is given as return_type i.e. Monday is referred to as the first day of the week." }, { "code": null, "e": 4080, "s": 4069, "text": "Example 3:" }, { "code": null, "e": 4215, "s": 4080, "text": "Here the day of todays(01-04-2021) date is the result & the default value (Sunday) is considered here because no return_type is given." }, { "code": null, "e": 4300, "s": 4215, "text": "This function calculates the difference between two dates in days, months, or years." }, { "code": null, "e": 4454, "s": 4300, "text": "For calculating the difference b/w dates which time interval should be used depends on the letter which we specify in our last argument i.e. at the unit." }, { "code": null, "e": 4626, "s": 4454, "text": "Syntax: DATEDIF(start_date,end_date,unit)\n\nArguments:\n1. start_date: The start date for evaluating the difference.\n2. end_date: The end Date for evaluating the difference." }, { "code": null, "e": 4637, "s": 4626, "text": "Example 1:" }, { "code": null, "e": 4648, "s": 4637, "text": "Example 2:" }, { "code": null, "e": 4659, "s": 4648, "text": "Example 3:" }, { "code": null, "e": 4810, "s": 4659, "text": "Here “m”,”y”,”d” means month, year & date. In the first example, the difference between dates is calculated by months, second by year & third by date." }, { "code": null, "e": 4902, "s": 4810, "text": "It returns the week number based on the specified date i.e. from 1 to 52 weeks of the year." }, { "code": null, "e": 5380, "s": 4902, "text": "Syntax: WEEKNUM(serial_number,firstday_ofweek)\n\nArguments: \n1. serial_number:This is the date for which we want the week number.\n2. firstday_ofweek: This is optional arguments that specify which numbering\n system should be considered & which day of the week can be\n treated as start of the week,Default(omitted) is 1.\n The table below is the parameters that can be given in\n firstday_ofweek arguments." }, { "code": null, "e": 5488, "s": 5380, "text": " First Day of the Week Start Table" }, { "code": null, "e": 5499, "s": 5488, "text": "Example 1:" }, { "code": null, "e": 5510, "s": 5499, "text": "Example 2:" }, { "code": null, "e": 5521, "s": 5510, "text": "Example 3:" }, { "code": null, "e": 5768, "s": 5521, "text": "In the below example,21 is given as the second argument that means Monday is taken as the first day of the week & in the above example, the result shown is 15 but by taking 21 as the first_dayofweek means Monday as the first day the result is 14." }, { "code": null, "e": 5837, "s": 5768, "text": "This function adds or subtracts the specified month to a given date." }, { "code": null, "e": 6064, "s": 5837, "text": "Syntax: EDATE(start_date,months)\n\nArguments:\n1. start_date: This is an initial date on which the months are added or subtracted.\n2. months: This is the number of months which is to be added or subtracted in the specified date." }, { "code": null, "e": 6075, "s": 6064, "text": "Example 1:" }, { "code": null, "e": 6086, "s": 6075, "text": "Example 2:" }, { "code": null, "e": 6097, "s": 6086, "text": "Example 3:" }, { "code": null, "e": 6216, "s": 6097, "text": "This function returns the fraction of the year which represents the number of whole days between the start & end date." }, { "code": null, "e": 6467, "s": 6216, "text": "Syntax: YEARFRAC(start_date,end_date,[basis])\n\nArguments:\n1. start_date: This is the start date in the serial number.\n2. end_date: This is the end date in the serial number.\n3. basis: This is the optional argument that specifies the day count method." }, { "code": null, "e": 6507, "s": 6467, "text": "Example 1: Using someday count methods." }, { "code": null, "e": 6518, "s": 6507, "text": "Example 2:" }, { "code": null, "e": 6529, "s": 6518, "text": "Example 3:" }, { "code": null, "e": 6732, "s": 6529, "text": "This function helps if we exactly know how many working days we have & want to find out the date when the number of working will skip. This function always includes working days & excludes weekend days." }, { "code": null, "e": 7176, "s": 6732, "text": "Syntax: WORKDAY(start_date,days,holidays)\n\nArguments:\n1. start_date: This argument is the date from which the counting of weekdays begins.\n Excel doesn't include start_date as a working day.\n2. days: This is the number of working days.\n3. holidays: This is an optional argument. If the days mentioned include any\n holidays then we need to make a list of holidays separately for\n this and mention it here." }, { "code": null, "e": 7240, "s": 7176, "text": "Example 1: 28 workdays from the start date, excluding holidays." }, { "code": null, "e": 7305, "s": 7240, "text": "Example 2: 28 workdays before the start date, excluding holidays" }, { "code": null, "e": 7362, "s": 7305, "text": "Example 3: 28 workdays from the start date, no holidays." }, { "code": null, "e": 7417, "s": 7362, "text": "Example 4: 28 workdays from today’s date, no holidays." }, { "code": null, "e": 7558, "s": 7417, "text": "This is a modification of the WORKDAY function as it provides a custom weekend parameter which distinguishes this from the WORKDAY function." }, { "code": null, "e": 8194, "s": 7558, "text": "Syntax: WORKDAY.INTL(start_date,days,[weekends],holidays)\n\nArguments:\n1. start_date: This argument is the date from which the counting of weekdays begins.\n Excel doesn't include start_date as a working day.\n2. days: This is the number of working days.\n3. holidays: This is an optional argument. If the days mentioned include any\n holidays then we need to make a list of holidays separately for\n this and mention it here.\n4. weekends: Through this argument we can specify which days of the week to be treated\n as non working days either by weekend number or specific character string." }, { "code": null, "e": 8315, "s": 8194, "text": "If this weekend argument is blank in this function then it will automatically take the combination of Saturday & Sunday." }, { "code": null, "e": 8329, "s": 8315, "text": "For instance:" }, { "code": null, "e": 8388, "s": 8329, "text": "“0000011”-Saturday & Sunday are weekends(non-working days)" }, { "code": null, "e": 8447, "s": 8388, "text": "“1000010”-Monday & Saturday are weekends(non-working days)" }, { "code": null, "e": 8577, "s": 8447, "text": "Example 1: 30 days from the start date, excluding holidays & Sunday, Monday as weekends(by giving weekend number 2 as arguments)." }, { "code": null, "e": 8715, "s": 8577, "text": "Example 2: 30 days from the start date, excluding holidays & Sunday, Monday as weekends(by giving weekend string “1000001” as arguments)." }, { "code": null, "e": 8849, "s": 8715, "text": "Example 3: 20 days from the start date, no holidays & Monday, Saturday as weekends( by giving weekend string “1000010” as arguments)." }, { "code": null, "e": 8972, "s": 8849, "text": "This function returns the number of working days between two dates excluding weekends & holidays is as optional arguments." }, { "code": null, "e": 9180, "s": 8972, "text": "Syntax: NETWORKDAYS(start_date,end_date,holidays)\n \nArguments:\n1. start_date: The initial date to start evaluation.\n2. end_date: The last date to end the evaluation.\n4. holidays: Used to specify holidays. " }, { "code": null, "e": 9191, "s": 9180, "text": "Example 1:" }, { "code": null, "e": 9202, "s": 9191, "text": "Example 2:" }, { "code": null, "e": 9372, "s": 9202, "text": "This function also returns the number of working days between two dates but provides additional argument weekend to specify which days should be counted as weekend days." }, { "code": null, "e": 9501, "s": 9372, "text": "The structure of the weekend argument is the same as for WORKDAY.INTL i.e. we can use either weekend number or character string." }, { "code": null, "e": 9763, "s": 9501, "text": "Syntax: NETWORKDAYS.INTL(start_date,end_date,[weekend],holidays)\n\nArguments:\n1. start_date: The initial date to start evaluation.\n2. end_date: The last date to end the evaluation.\n3. weekend: Use to specify the weekends.\n4. holidays: Used to specify holidays. " }, { "code": null, "e": 9826, "s": 9763, "text": "Example 1: Here weekend argument is given in form of a number." }, { "code": null, "e": 9912, "s": 9826, "text": "Example 2: Here weekend argument is given in form of a character string of 0’s & 1’s." }, { "code": null, "e": 9929, "s": 9912, "text": "akshaysingh98088" }, { "code": null, "e": 9948, "s": 9929, "text": "surindertarika1234" }, { "code": null, "e": 9955, "s": 9948, "text": "Picked" }, { "code": null, "e": 9961, "s": 9955, "text": "Excel" }, { "code": null, "e": 10059, "s": 9961, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 10097, "s": 10059, "text": "How to Delete Blank Columns in Excel?" }, { "code": null, "e": 10129, "s": 10097, "text": "How to Normalize Data in Excel?" }, { "code": null, "e": 10170, "s": 10129, "text": "How to Get Length of Array in Excel VBA?" }, { "code": null, "e": 10198, "s": 10170, "text": "How to Use Solver in Excel?" }, { "code": null, "e": 10214, "s": 10198, "text": "Macros in Excel" }, { "code": null, "e": 10269, "s": 10214, "text": "How to Find the Last Used Row and Column in Excel VBA?" }, { "code": null, "e": 10327, "s": 10269, "text": "How to Show Percentages in Stacked Column Chart in Excel?" }, { "code": null, "e": 10367, "s": 10327, "text": "How to make a 3 Axis Graph using Excel?" }, { "code": null, "e": 10401, "s": 10367, "text": "Introduction to Excel Spreadsheet" } ]
D3.js selection.append() Function
06 Sep, 2020 The selection.append() function is used to append a new element to the HTML tag name as given in the parameters to the end of the element. If the type that is given is a function then it must be evaluated for each element that is in the selection. Syntax: selection.append(type); Parameters: This function takes only one parameter which is given above and described below. type: This parameter takes a string that defines the type of the element. Return Value: This function must return an element to be appended at the end. Example 1: In the following example, elements are appended to each selected element. HTML <!DOCTYPE html><html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" path1tent="width=device-width, initial-scale=1.0"> <script src="https://d3js.org/d3.v4.min.js"> </script> <style> h1 { color: green; } p { background-color: #f2f2f2; padding: 10px; width: 300px; line-height: 5px; } p:hover { background-color: grey; padding: 10px; cursor: pointer; } div { width: 50px; height: 50px; background-color: green; margin: 10px; } </style></head> <body> <h1>GeeksforGeeks</h1> <h4>D3.js | selection.append() Function</h4> <p><b>Click me</b></p> <p><b>Click me</b></p> <script> function func() { // Selecting all p and // Appending a DIV to each p tag var chk = d3.selectAll("p") .append("div"); var div = document.querySelector("div"); console.log(div) } let btn = document.querySelector("p"); btn.addEventListener("click", func); </script></body> </html> Output: Before clicking the “click me” element: Before clicking the “click me” element: After clicking the “click me” element: After clicking the “click me” element: Example 2: In the following example elements are appended only to the first element. HTML <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" path1tent="width=device-width, initial-scale=1.0"> </head> <style> h1{ line-height: 5px; color: green; } h1, h2, p, h4, h5, h6{ background-color: #f2f2f2; padding:20px; width: 300px; line-height: 5px; } p:hover{ background-color: grey; cursor: pointer; } div{ width: 50px; height: 50px; background-color: green; margin:10px; }</style> <body> <h1>Geeks for geeks</h1> <p>Click me.</p> <p>Click me.</p> <script src = "https://d3js.org/d3.v4.min.js"> </script> <script> function func(){ // Selecting p and // Appending a DIV to the p tag // Only first p tag is effected var chk = d3.select("p") .append("b"); var b=document.querySelector("b"); b.innerText=" This <b> tag is appended." } let btn=document.querySelector("p"); btn.addEventListener("click", func); </script> </body> </html> Output: Before clicking the “click me” button: Before clicking the “click me” button: After clicking the “click me” button: After clicking the “click me” button: D3.js JavaScript Web Technologies Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n06 Sep, 2020" }, { "code": null, "e": 276, "s": 28, "text": "The selection.append() function is used to append a new element to the HTML tag name as given in the parameters to the end of the element. If the type that is given is a function then it must be evaluated for each element that is in the selection." }, { "code": null, "e": 284, "s": 276, "text": "Syntax:" }, { "code": null, "e": 310, "s": 284, "text": " selection.append(type);\n" }, { "code": null, "e": 403, "s": 310, "text": "Parameters: This function takes only one parameter which is given above and described below." }, { "code": null, "e": 477, "s": 403, "text": "type: This parameter takes a string that defines the type of the element." }, { "code": null, "e": 555, "s": 477, "text": "Return Value: This function must return an element to be appended at the end." }, { "code": null, "e": 640, "s": 555, "text": "Example 1: In the following example, elements are appended to each selected element." }, { "code": null, "e": 645, "s": 640, "text": "HTML" }, { "code": "<!DOCTYPE html><html lang=\"en\"> <head> <meta charset=\"UTF-8\"> <meta name=\"viewport\" path1tent=\"width=device-width, initial-scale=1.0\"> <script src=\"https://d3js.org/d3.v4.min.js\"> </script> <style> h1 { color: green; } p { background-color: #f2f2f2; padding: 10px; width: 300px; line-height: 5px; } p:hover { background-color: grey; padding: 10px; cursor: pointer; } div { width: 50px; height: 50px; background-color: green; margin: 10px; } </style></head> <body> <h1>GeeksforGeeks</h1> <h4>D3.js | selection.append() Function</h4> <p><b>Click me</b></p> <p><b>Click me</b></p> <script> function func() { // Selecting all p and // Appending a DIV to each p tag var chk = d3.selectAll(\"p\") .append(\"div\"); var div = document.querySelector(\"div\"); console.log(div) } let btn = document.querySelector(\"p\"); btn.addEventListener(\"click\", func); </script></body> </html>", "e": 1860, "s": 645, "text": null }, { "code": null, "e": 1868, "s": 1860, "text": "Output:" }, { "code": null, "e": 1908, "s": 1868, "text": "Before clicking the “click me” element:" }, { "code": null, "e": 1948, "s": 1908, "text": "Before clicking the “click me” element:" }, { "code": null, "e": 1987, "s": 1948, "text": "After clicking the “click me” element:" }, { "code": null, "e": 2026, "s": 1987, "text": "After clicking the “click me” element:" }, { "code": null, "e": 2111, "s": 2026, "text": "Example 2: In the following example elements are appended only to the first element." }, { "code": null, "e": 2116, "s": 2111, "text": "HTML" }, { "code": "<!DOCTYPE html> <html lang=\"en\"> <head> <meta charset=\"UTF-8\"> <meta name=\"viewport\" path1tent=\"width=device-width, initial-scale=1.0\"> </head> <style> h1{ line-height: 5px; color: green; } h1, h2, p, h4, h5, h6{ background-color: #f2f2f2; padding:20px; width: 300px; line-height: 5px; } p:hover{ background-color: grey; cursor: pointer; } div{ width: 50px; height: 50px; background-color: green; margin:10px; }</style> <body> <h1>Geeks for geeks</h1> <p>Click me.</p> <p>Click me.</p> <script src = \"https://d3js.org/d3.v4.min.js\"> </script> <script> function func(){ // Selecting p and // Appending a DIV to the p tag // Only first p tag is effected var chk = d3.select(\"p\") .append(\"b\"); var b=document.querySelector(\"b\"); b.innerText=\" This <b> tag is appended.\" } let btn=document.querySelector(\"p\"); btn.addEventListener(\"click\", func); </script> </body> </html>", "e": 3257, "s": 2116, "text": null }, { "code": null, "e": 3265, "s": 3257, "text": "Output:" }, { "code": null, "e": 3304, "s": 3265, "text": "Before clicking the “click me” button:" }, { "code": null, "e": 3343, "s": 3304, "text": "Before clicking the “click me” button:" }, { "code": null, "e": 3381, "s": 3343, "text": "After clicking the “click me” button:" }, { "code": null, "e": 3419, "s": 3381, "text": "After clicking the “click me” button:" }, { "code": null, "e": 3425, "s": 3419, "text": "D3.js" }, { "code": null, "e": 3436, "s": 3425, "text": "JavaScript" }, { "code": null, "e": 3453, "s": 3436, "text": "Web Technologies" } ]
Program to check if a number is divisible by any of its digits
23 Jun, 2022 Given an integer N where . The task is to check whether the number is not divisible by any of its digit. If the given number N is divisible by any of its digits then print “YES” else print “NO”. Examples: Input : N = 5115 Output : YES Explanation: 5115 is divisible by both 1 and 5. So print YES. Input : 27 Output : NO Explanation: 27 is not divisible by 2 or 7 Approach: The idea to solve the problem is to extract the digits of the number one by one and check if the number is divisible by any of its digit. If it is divisible by any of it’s digit then print YES otherwise print NO. Below is the implementation of above approach: C++ Java Python3 C# PHP Javascript // C++ implementation of above approach#include <bits/stdc++.h>using namespace std; // Function to check if given number is divisible// by any of its digitsstring isDivisible(long long int n){ long long int temp = n; // check if any of digit divides n while (n) { int k = n % 10; // check if K divides N if (temp % k == 0) return "YES"; n /= 10; } return "NO";} // Driver Codeint main(){ long long int n = 9876543; cout << isDivisible(n); return 0;} // Java implementation of above approach class GFG{ // Function to check if given number is divisible // by any of its digits static String isDivisible(int n) { int temp = n; // check if any of digit divides n while (n > 0) { int k = n % 10; // check if K divides N if (temp % k == 0) { return "YES"; } n /= 10; } return "NO"; } // Driver Code public static void main(String[] args) { int n = 9876543; System.out.println(isDivisible(n)); }} // This code is contributed by 29AjayKumar # Python program implementation of above approach # Function to check if given number is# divisible by any of its digitsdef isDivisible(n): temp = n # check if any of digit divides n while(n): k = n % 10 # check if K divides N if(temp % k == 0): return "YES" n /= 10; # Number is not divisible by # any of digits return "NO" # Driver Coden = 9876543print(isDivisible(n)) # This code is contributed by# Sanjit_Prasad // C# implementation of above approachusing System; class GFG{ // Function to check if given number is divisible // by any of its digits static String isDivisible(int n) { int temp = n; // check if any of digit divides n while (n > 0) { int k = n % 10; // check if K divides N if (temp % k == 0) { return "YES"; } n /= 10; } return "NO"; } // Driver Code public static void Main(String[] args) { int n = 9876543; Console.WriteLine(isDivisible(n)); }} // This code is contributed by PrinciRaj1992 <?php// PHP implementation of above approach // Function to check if given number// is divisible by any of its digitsfunction isDivisible($n){ $temp = $n; // check if any of digit divides n while ($n) { $k = $n % 10; // check if K divides N if ($temp % $k == 0) return "YES"; $n = floor($n / 10); } return "NO";} // Driver Code$n = 9876543; echo isDivisible($n); // This code is contributed by Ryuga?> <script> // Javascript implementation of above approach // Function to check if given number// is divisible by any of its digitsfunction isDivisible(n){ temp = n; // Check if any of digit divides n while (n) { k = n % 10; // Check if K divides N if (temp % k == 0) return "YES"; n = Math.floor(n / 10); } return "NO";} // Driver Codelet n = 9876543; document.write(isDivisible(n)); // This code is contributed by sravan kumar </script> YES Time Complexity: O(log(N)) Auxiliary Space: O(1), since no extra space has been required. We have to convert the given number to string by taking a new variable . Traverse the string , Convert character to integer(digit) Check if the number is divisible by any of it’s digit then print YES otherwise print NO. Below is the implementation of above approach: C++ Java Python3 C# Javascript //C++ implementation of above approach#include <bits/stdc++.h>using namespace std; string getResult(int n) { // Converting integer to string string st = to_string(n); // Traversing the string for (int i = 0; i < st.length(); i++) { //find the actual digit int d = st[i] - 48; // If the number is divisible by // digits then return yes if(n % d == 0) { return "Yes"; } } // If no digits are dividing the // number then return no return "No";} // Driver Codeint main(){int n = 9876543; // passing this number to get result functioncout<<getResult(n); } // this code is contributed by SoumiikMondal // JAva implementation of above approachimport java.io.*; class GFG{static String getResult(int n) { // Converting integer to string String st = Integer.toString(n); // Traversing the string for (int i = 0; i < st.length(); i++) { //find the actual digit int d = st.charAt(i) - 48; // If the number is divisible by // digits then return yes if(n % d == 0) { return "Yes"; } } // If no digits are dividing the // number then return no return "No";} // Driver Codepublic static void main(String[] args) {int n = 9876543; // passing this number to get result functionSystem.out.println(getResult(n));}} // this code is contributed by shivanisinghss2110 # Python implementation of above approachdef getResult(n): # Converting integer to string st = str(n) # Traversing the string for i in st: # If the number is divisible by # digits then return yes if(n % int(i) == 0): return 'Yes' # If no digits are dividing the # number then return no return 'No' # Driver Coden = 9876543 # passing this number to get result functionprint(getResult(n))# this code is contributed by vikkycirus // C# implementation of above approachusing System; public class GFG{static String getResult(int n) { // Converting integer to string string st = n.ToString(); // Traversing the string for (int i = 0; i < st.Length; i++) { //find the actual digit int d = st[i] - 48; // If the number is divisible by // digits then return yes if(n % d == 0) { return "Yes"; } } // If no digits are dividing the // number then return no return "No";} // Driver Codepublic static void Main(String[] args){ int n = 9876543; // passing this number to get result function Console.Write(getResult(n));}} // this code is contributed by shivanisinghss2110 <script> // JavaScript implementation of above approach function getResult(n){ // Converting integer to string let st = n.toString(); // Traversing the string for (let i = 0; i < st.length; i++) { //find the actual digit let d = st[i].charCodeAt(0) - 48; // If the number is divisible by // digits then return yes if(n % d == 0) { return "Yes"; } } // If no digits are dividing the // number then return no return "No";} // Driver Codelet n = 9876543; // passing this number to get result functiondocument.write(getResult(n)); // This code is contributed by unknown2108 </script> Yes Time Complexity: O(n) Auxiliary Space: O(n) Sanjit_Prasad ankthon 29AjayKumar princiraj1992 vikkycirus sravankumar8128 SoumikMondal unknown2108 shivanisinghss2110 sushmitamittal1329 number-digits Mathematical Mathematical Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Merge two sorted arrays Operators in C / C++ Find minimum number of coins that make a given value Program to find GCD or HCF of two numbers Minimum number of jumps to reach end Algorithm to solve Rubik's Cube Sieve of Eratosthenes Prime Numbers The Knight's tour problem | Backtracking-1 Program for Decimal to Binary Conversion
[ { "code": null, "e": 28, "s": 0, "text": "\n23 Jun, 2022" }, { "code": null, "e": 223, "s": 28, "text": "Given an integer N where . The task is to check whether the number is not divisible by any of its digit. If the given number N is divisible by any of its digits then print “YES” else print “NO”." }, { "code": null, "e": 234, "s": 223, "text": "Examples: " }, { "code": null, "e": 393, "s": 234, "text": "Input : N = 5115\nOutput : YES\nExplanation: 5115 is divisible by both 1 and 5.\nSo print YES.\n\nInput : 27\nOutput : NO\nExplanation: 27 is not divisible by 2 or 7" }, { "code": null, "e": 616, "s": 393, "text": "Approach: The idea to solve the problem is to extract the digits of the number one by one and check if the number is divisible by any of its digit. If it is divisible by any of it’s digit then print YES otherwise print NO." }, { "code": null, "e": 664, "s": 616, "text": "Below is the implementation of above approach: " }, { "code": null, "e": 668, "s": 664, "text": "C++" }, { "code": null, "e": 673, "s": 668, "text": "Java" }, { "code": null, "e": 681, "s": 673, "text": "Python3" }, { "code": null, "e": 684, "s": 681, "text": "C#" }, { "code": null, "e": 688, "s": 684, "text": "PHP" }, { "code": null, "e": 699, "s": 688, "text": "Javascript" }, { "code": "// C++ implementation of above approach#include <bits/stdc++.h>using namespace std; // Function to check if given number is divisible// by any of its digitsstring isDivisible(long long int n){ long long int temp = n; // check if any of digit divides n while (n) { int k = n % 10; // check if K divides N if (temp % k == 0) return \"YES\"; n /= 10; } return \"NO\";} // Driver Codeint main(){ long long int n = 9876543; cout << isDivisible(n); return 0;}", "e": 1218, "s": 699, "text": null }, { "code": "// Java implementation of above approach class GFG{ // Function to check if given number is divisible // by any of its digits static String isDivisible(int n) { int temp = n; // check if any of digit divides n while (n > 0) { int k = n % 10; // check if K divides N if (temp % k == 0) { return \"YES\"; } n /= 10; } return \"NO\"; } // Driver Code public static void main(String[] args) { int n = 9876543; System.out.println(isDivisible(n)); }} // This code is contributed by 29AjayKumar", "e": 1871, "s": 1218, "text": null }, { "code": "# Python program implementation of above approach # Function to check if given number is# divisible by any of its digitsdef isDivisible(n): temp = n # check if any of digit divides n while(n): k = n % 10 # check if K divides N if(temp % k == 0): return \"YES\" n /= 10; # Number is not divisible by # any of digits return \"NO\" # Driver Coden = 9876543print(isDivisible(n)) # This code is contributed by# Sanjit_Prasad", "e": 2348, "s": 1871, "text": null }, { "code": "// C# implementation of above approachusing System; class GFG{ // Function to check if given number is divisible // by any of its digits static String isDivisible(int n) { int temp = n; // check if any of digit divides n while (n > 0) { int k = n % 10; // check if K divides N if (temp % k == 0) { return \"YES\"; } n /= 10; } return \"NO\"; } // Driver Code public static void Main(String[] args) { int n = 9876543; Console.WriteLine(isDivisible(n)); }} // This code is contributed by PrinciRaj1992", "e": 3013, "s": 2348, "text": null }, { "code": "<?php// PHP implementation of above approach // Function to check if given number// is divisible by any of its digitsfunction isDivisible($n){ $temp = $n; // check if any of digit divides n while ($n) { $k = $n % 10; // check if K divides N if ($temp % $k == 0) return \"YES\"; $n = floor($n / 10); } return \"NO\";} // Driver Code$n = 9876543; echo isDivisible($n); // This code is contributed by Ryuga?>", "e": 3476, "s": 3013, "text": null }, { "code": "<script> // Javascript implementation of above approach // Function to check if given number// is divisible by any of its digitsfunction isDivisible(n){ temp = n; // Check if any of digit divides n while (n) { k = n % 10; // Check if K divides N if (temp % k == 0) return \"YES\"; n = Math.floor(n / 10); } return \"NO\";} // Driver Codelet n = 9876543; document.write(isDivisible(n)); // This code is contributed by sravan kumar </script>", "e": 3973, "s": 3476, "text": null }, { "code": null, "e": 3977, "s": 3973, "text": "YES" }, { "code": null, "e": 4069, "s": 3979, "text": "Time Complexity: O(log(N)) Auxiliary Space: O(1), since no extra space has been required." }, { "code": null, "e": 4142, "s": 4069, "text": "We have to convert the given number to string by taking a new variable ." }, { "code": null, "e": 4164, "s": 4142, "text": "Traverse the string ," }, { "code": null, "e": 4200, "s": 4164, "text": "Convert character to integer(digit)" }, { "code": null, "e": 4289, "s": 4200, "text": "Check if the number is divisible by any of it’s digit then print YES otherwise print NO." }, { "code": null, "e": 4336, "s": 4289, "text": "Below is the implementation of above approach:" }, { "code": null, "e": 4340, "s": 4336, "text": "C++" }, { "code": null, "e": 4345, "s": 4340, "text": "Java" }, { "code": null, "e": 4353, "s": 4345, "text": "Python3" }, { "code": null, "e": 4356, "s": 4353, "text": "C#" }, { "code": null, "e": 4367, "s": 4356, "text": "Javascript" }, { "code": "//C++ implementation of above approach#include <bits/stdc++.h>using namespace std; string getResult(int n) { // Converting integer to string string st = to_string(n); // Traversing the string for (int i = 0; i < st.length(); i++) { //find the actual digit int d = st[i] - 48; // If the number is divisible by // digits then return yes if(n % d == 0) { return \"Yes\"; } } // If no digits are dividing the // number then return no return \"No\";} // Driver Codeint main(){int n = 9876543; // passing this number to get result functioncout<<getResult(n); } // this code is contributed by SoumiikMondal", "e": 5086, "s": 4367, "text": null }, { "code": "// JAva implementation of above approachimport java.io.*; class GFG{static String getResult(int n) { // Converting integer to string String st = Integer.toString(n); // Traversing the string for (int i = 0; i < st.length(); i++) { //find the actual digit int d = st.charAt(i) - 48; // If the number is divisible by // digits then return yes if(n % d == 0) { return \"Yes\"; } } // If no digits are dividing the // number then return no return \"No\";} // Driver Codepublic static void main(String[] args) {int n = 9876543; // passing this number to get result functionSystem.out.println(getResult(n));}} // this code is contributed by shivanisinghss2110", "e": 5861, "s": 5086, "text": null }, { "code": "# Python implementation of above approachdef getResult(n): # Converting integer to string st = str(n) # Traversing the string for i in st: # If the number is divisible by # digits then return yes if(n % int(i) == 0): return 'Yes' # If no digits are dividing the # number then return no return 'No' # Driver Coden = 9876543 # passing this number to get result functionprint(getResult(n))# this code is contributed by vikkycirus", "e": 6368, "s": 5861, "text": null }, { "code": "// C# implementation of above approachusing System; public class GFG{static String getResult(int n) { // Converting integer to string string st = n.ToString(); // Traversing the string for (int i = 0; i < st.Length; i++) { //find the actual digit int d = st[i] - 48; // If the number is divisible by // digits then return yes if(n % d == 0) { return \"Yes\"; } } // If no digits are dividing the // number then return no return \"No\";} // Driver Codepublic static void Main(String[] args){ int n = 9876543; // passing this number to get result function Console.Write(getResult(n));}} // this code is contributed by shivanisinghss2110", "e": 7128, "s": 6368, "text": null }, { "code": "<script> // JavaScript implementation of above approach function getResult(n){ // Converting integer to string let st = n.toString(); // Traversing the string for (let i = 0; i < st.length; i++) { //find the actual digit let d = st[i].charCodeAt(0) - 48; // If the number is divisible by // digits then return yes if(n % d == 0) { return \"Yes\"; } } // If no digits are dividing the // number then return no return \"No\";} // Driver Codelet n = 9876543; // passing this number to get result functiondocument.write(getResult(n)); // This code is contributed by unknown2108 </script>", "e": 7833, "s": 7128, "text": null }, { "code": null, "e": 7837, "s": 7833, "text": "Yes" }, { "code": null, "e": 7859, "s": 7837, "text": "Time Complexity: O(n)" }, { "code": null, "e": 7881, "s": 7859, "text": "Auxiliary Space: O(n)" }, { "code": null, "e": 7895, "s": 7881, "text": "Sanjit_Prasad" }, { "code": null, "e": 7903, "s": 7895, "text": "ankthon" }, { "code": null, "e": 7915, "s": 7903, "text": "29AjayKumar" }, { "code": null, "e": 7929, "s": 7915, "text": "princiraj1992" }, { "code": null, "e": 7940, "s": 7929, "text": "vikkycirus" }, { "code": null, "e": 7956, "s": 7940, "text": "sravankumar8128" }, { "code": null, "e": 7969, "s": 7956, "text": "SoumikMondal" }, { "code": null, "e": 7981, "s": 7969, "text": "unknown2108" }, { "code": null, "e": 8000, "s": 7981, "text": "shivanisinghss2110" }, { "code": null, "e": 8019, "s": 8000, "text": "sushmitamittal1329" }, { "code": null, "e": 8033, "s": 8019, "text": "number-digits" }, { "code": null, "e": 8046, "s": 8033, "text": "Mathematical" }, { "code": null, "e": 8059, "s": 8046, "text": "Mathematical" }, { "code": null, "e": 8157, "s": 8059, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 8181, "s": 8157, "text": "Merge two sorted arrays" }, { "code": null, "e": 8202, "s": 8181, "text": "Operators in C / C++" }, { "code": null, "e": 8255, "s": 8202, "text": "Find minimum number of coins that make a given value" }, { "code": null, "e": 8297, "s": 8255, "text": "Program to find GCD or HCF of two numbers" }, { "code": null, "e": 8334, "s": 8297, "text": "Minimum number of jumps to reach end" }, { "code": null, "e": 8366, "s": 8334, "text": "Algorithm to solve Rubik's Cube" }, { "code": null, "e": 8388, "s": 8366, "text": "Sieve of Eratosthenes" }, { "code": null, "e": 8402, "s": 8388, "text": "Prime Numbers" }, { "code": null, "e": 8445, "s": 8402, "text": "The Knight's tour problem | Backtracking-1" } ]
Introduction to Priority Queues in Python | by Raivat Shah | Towards Data Science
What is a Priority Queue? A queue has FIFO (first-in-first-out) ordering where items are taken out or accessed on a first-come-first-served basis. Examples of queues include a queue at a movie ticket stand, as shown in the illustration above. But, what is a priority queue? A priority queue is an abstract data structure (a data structure defined by its behaviour) that is like a normal queue but where each item has a special “key” to quantify its “priority”. For example, if the movie cinema decides to serve loyal customers first, it will order them by their loyalty (points or number of tickets purchased). In such a case, the queue for tickets will no longer be first-come-first-served, but most-loyal-first-served. The customers will be the “items” of this priority queue while the “priority” or “key” will be their loyalty. Another example is of airlines that give luggage on the conveyer belt based on the status or ticket class of the passengers. Baggage tagged with “priority” or “business” or “first-class” usually arrives earlier than other non-tagged baggage. Implementing Priority Queues in Python Consider that we want to have a priority queue of customers based on their loyalty points. The higher the points, the more the priority. When it comes to implementing Priority Queues in Python, there are a number of options. We will explore three of them here. Using a list Using a list A very simple and straightforward way is to use the normal list but sort it every time an item is added. Here’s an example: customers = []customers.append((2, "Harry")) #no sort needed here because 1 item. customers.append((3, "Charles"))customers.sort(reverse=True) #Need to sort to maintain ordercustomers.append((1, "Riya"))customers.sort(reverse=True) #Need to sort to maintain ordercustomers.append((4, "Stacy"))customers.sort(reverse=True)while customers: print(customers.pop(0))#Will print names in the order: Stacy, Charles, Harry, Riya. However, it takes O(n log n) time to maintain the order when an item is added to the list. Thus, it is only efficient when we have to make few insertions. 2. Using heapq We can also use the heapq module in Python to implement our priority queue. This implementation has O(log n) time for insertion and extraction of the smallest element. Note that heapq only has a min heap implementation, but there are ways to use as a max heap (not covered in this article). Here’s an example: import heapqcustomers = []heapq.heappush(customers, (2, "Harry"))heapq.heappush(customers, (3, "Charles"))heapq.heappush(customers, (1, "Riya"))heapq.heappush(customers, (4, "Stacy"))while customers: print(heapq.heappop(q))#Will print names in the order: Riya, Harry, Charles, Stacy. 3. Using queue.PriorityQueue The PriorityQueue uses the same heapq implementation from 2) internally and thus has the same time complexity. However, it is different in two key ways. Firstly, it is synchronized, so it supports concurrent processes (you can read more about here). Secondly, it is a class interface instead of the function based interface of heapq . Thus, PriorityQueue is the classic OOP style of implementing and using Priority Queues. Let’s construct a priority queue for our movie buffs: from queue import PriorityQueuecustomers = PriorityQueue() #we initialise the PQ class instead of using a function to operate upon a list. customers.put((2, "Harry"))customers.put((3, "Charles"))customers.put((1, "Riya"))customers.put((4, "Stacy"))while customers: print(customers.get())#Will print names in the order: Riya, Harry, Charles, Stacy. And that’s how we can implement priority queues in Python! I hope this small article helps you get started with and understand the importance of PQs. Consider reading the references and further reading to know more! References and Further Reading
[ { "code": null, "e": 198, "s": 172, "text": "What is a Priority Queue?" }, { "code": null, "e": 446, "s": 198, "text": "A queue has FIFO (first-in-first-out) ordering where items are taken out or accessed on a first-come-first-served basis. Examples of queues include a queue at a movie ticket stand, as shown in the illustration above. But, what is a priority queue?" }, { "code": null, "e": 1003, "s": 446, "text": "A priority queue is an abstract data structure (a data structure defined by its behaviour) that is like a normal queue but where each item has a special “key” to quantify its “priority”. For example, if the movie cinema decides to serve loyal customers first, it will order them by their loyalty (points or number of tickets purchased). In such a case, the queue for tickets will no longer be first-come-first-served, but most-loyal-first-served. The customers will be the “items” of this priority queue while the “priority” or “key” will be their loyalty." }, { "code": null, "e": 1245, "s": 1003, "text": "Another example is of airlines that give luggage on the conveyer belt based on the status or ticket class of the passengers. Baggage tagged with “priority” or “business” or “first-class” usually arrives earlier than other non-tagged baggage." }, { "code": null, "e": 1284, "s": 1245, "text": "Implementing Priority Queues in Python" }, { "code": null, "e": 1545, "s": 1284, "text": "Consider that we want to have a priority queue of customers based on their loyalty points. The higher the points, the more the priority. When it comes to implementing Priority Queues in Python, there are a number of options. We will explore three of them here." }, { "code": null, "e": 1558, "s": 1545, "text": "Using a list" }, { "code": null, "e": 1571, "s": 1558, "text": "Using a list" }, { "code": null, "e": 1695, "s": 1571, "text": "A very simple and straightforward way is to use the normal list but sort it every time an item is added. Here’s an example:" }, { "code": null, "e": 2122, "s": 1695, "text": "customers = []customers.append((2, \"Harry\")) #no sort needed here because 1 item. customers.append((3, \"Charles\"))customers.sort(reverse=True) #Need to sort to maintain ordercustomers.append((1, \"Riya\"))customers.sort(reverse=True) #Need to sort to maintain ordercustomers.append((4, \"Stacy\"))customers.sort(reverse=True)while customers: print(customers.pop(0))#Will print names in the order: Stacy, Charles, Harry, Riya. " }, { "code": null, "e": 2277, "s": 2122, "text": "However, it takes O(n log n) time to maintain the order when an item is added to the list. Thus, it is only efficient when we have to make few insertions." }, { "code": null, "e": 2292, "s": 2277, "text": "2. Using heapq" }, { "code": null, "e": 2583, "s": 2292, "text": "We can also use the heapq module in Python to implement our priority queue. This implementation has O(log n) time for insertion and extraction of the smallest element. Note that heapq only has a min heap implementation, but there are ways to use as a max heap (not covered in this article)." }, { "code": null, "e": 2602, "s": 2583, "text": "Here’s an example:" }, { "code": null, "e": 2890, "s": 2602, "text": "import heapqcustomers = []heapq.heappush(customers, (2, \"Harry\"))heapq.heappush(customers, (3, \"Charles\"))heapq.heappush(customers, (1, \"Riya\"))heapq.heappush(customers, (4, \"Stacy\"))while customers: print(heapq.heappop(q))#Will print names in the order: Riya, Harry, Charles, Stacy." }, { "code": null, "e": 2919, "s": 2890, "text": "3. Using queue.PriorityQueue" }, { "code": null, "e": 3342, "s": 2919, "text": "The PriorityQueue uses the same heapq implementation from 2) internally and thus has the same time complexity. However, it is different in two key ways. Firstly, it is synchronized, so it supports concurrent processes (you can read more about here). Secondly, it is a class interface instead of the function based interface of heapq . Thus, PriorityQueue is the classic OOP style of implementing and using Priority Queues." }, { "code": null, "e": 3396, "s": 3342, "text": "Let’s construct a priority queue for our movie buffs:" }, { "code": null, "e": 3748, "s": 3396, "text": "from queue import PriorityQueuecustomers = PriorityQueue() #we initialise the PQ class instead of using a function to operate upon a list. customers.put((2, \"Harry\"))customers.put((3, \"Charles\"))customers.put((1, \"Riya\"))customers.put((4, \"Stacy\"))while customers: print(customers.get())#Will print names in the order: Riya, Harry, Charles, Stacy." }, { "code": null, "e": 3964, "s": 3748, "text": "And that’s how we can implement priority queues in Python! I hope this small article helps you get started with and understand the importance of PQs. Consider reading the references and further reading to know more!" } ]
PostgreSQL - Block Structure - GeeksforGeeks
28 Aug, 2020 PL/pgSQL is a block-structured language, therefore, a PL/pgSQL function or store procedure is organized into blocks. Syntax: [ <<label>> ] [ DECLARE declarations ] BEGIN statements; ... END [ label ]; Let’s analyze the above syntax: Each block has two sections: declaration and body. The declaration section is optional while the body section is required. The block is ended with a semicolon (;) after the END keyword. A block may have an optional label located at the beginning and at the end. You use the block label in case you want to specify it in the EXIT statement of the block body or if you want to qualify the names of variables declared in the block. The declaration section is where you declare all variables used within the body section. Each statement in the declaration section is terminated with a semicolon (;). The body section is where you place the code. Each statement in the body section is also terminated with a semicolon. Example: The following example illustrates a very simple block, also known as an anonymous block. DO $$ <<first_block>> DECLARE counter integer := 0; BEGIN counter := counter + 1; RAISE NOTICE 'The current value of counter is %', counter; END first_block $$; NOTICE: The current value of counter is 1 The pgAdmin execution of the above block can be done by clicking on the execute button on the interface as depicted below: Note: The DO statement does not belong to the block. It is used to execute an anonymous block. PostgreSQL introduced the DO statement since version 9.0. In the declaration section, we declared a variable counter and set its value to zero. Inside the body section, we increased the value of the counter to one and output its value using the RAISE NOTICE statement. The first_block label is just for demonstration purposes. Concept of Double Dollar($$): The double dollar ($$) is a substitution of a single quote (‘). When you develop a PL/pgSQL block, a function, or a stored procedure, you have to pass its body in the form of a string literal. In addition, you have to escape all single quote (‘) in the body as follows: DO '<<first_block>> DECLARE counter integer := 0; BEGIN counter := counter + 1; RAISE NOTICE ''The current value of counter is %'', counter; END first_block'; If you use the double dollar ($$) you can avoid quoting issues. You can also use a token between $$ like $function$ or $procedure$. PL/pgSQL Subblock: PL/pgSQL allows you to place a block inside the body of another block. This block nested inside another block is called subblock. The block that contains the subblock is referred to as an outer block. The subblocks are used for grouping statements so that a large block can be divided into smaller and more logical subblocks. The variables in the subblock can have the names as the ones in the outer block, even though it is not a good practice. When you declare a variable within a subblock with the same name as the one in the outer block, the variable in the outer block is hidden in the subblock. In case you want to access a variable in the outer block, you use a block label to qualify its name. Example: DO $$ <<outer_block>> DECLARE counter integer := 0; BEGIN counter := counter + 1; RAISE NOTICE 'The current value of counter is %', counter; DECLARE counter integer := 0; BEGIN counter := counter + 10; RAISE NOTICE 'The current value of counter in the subblock is %', counter; RAISE NOTICE 'The current value of counter in the outer block is %', outer_block.counter; END; RAISE NOTICE 'The current value of counter in the outer block is %', counter; END outer_block $$; Output: NOTICE: The current value of counter is 1 NOTICE: The current value of counter in the subblock is 10 NOTICE: The current value of counter in the outer block is 1 NOTICE: The current value of counter in the outer block is 1 Let’s analyze the above example: First, we declared a variable named counter in the outer_block. Then, before entering into the subblock, the value of the counter is one. In the subblock, we increased the value of the counter to ten and print it out. Notice that the change only affects the counter variable in the subblock. After that, we referred to the counter variable in the outer block using the block label to qualify its name outer_block.counter Finally, we printed out the value of the counter variable in the outer block, its value remains intact. postgreSQL-administration PostgreSQL Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments PostgreSQL - Change Column Type PostgreSQL - Psql commands PostgreSQL - For Loops PostgreSQL - Function Returning A Table PostgreSQL - Create Auto-increment Column using SERIAL How to use PostgreSQL Database in Django? PostgreSQL - DROP INDEX PostgreSQL - Copy Table PostgreSQL - Select Into PostgreSQL - LIMIT with OFFSET clause
[ { "code": null, "e": 27944, "s": 27916, "text": "\n28 Aug, 2020" }, { "code": null, "e": 28061, "s": 27944, "text": "PL/pgSQL is a block-structured language, therefore, a PL/pgSQL function or store procedure is organized into blocks." }, { "code": null, "e": 28158, "s": 28061, "text": "Syntax:\n[ <<label>> ]\n[ DECLARE\n declarations ]\nBEGIN\n statements;\n ...\nEND [ label ];\n" }, { "code": null, "e": 28190, "s": 28158, "text": "Let’s analyze the above syntax:" }, { "code": null, "e": 28376, "s": 28190, "text": "Each block has two sections: declaration and body. The declaration section is optional while the body section is required. The block is ended with a semicolon (;) after the END keyword." }, { "code": null, "e": 28619, "s": 28376, "text": "A block may have an optional label located at the beginning and at the end. You use the block label in case you want to specify it in the EXIT statement of the block body or if you want to qualify the names of variables declared in the block." }, { "code": null, "e": 28786, "s": 28619, "text": "The declaration section is where you declare all variables used within the body section. Each statement in the declaration section is terminated with a semicolon (;)." }, { "code": null, "e": 28904, "s": 28786, "text": "The body section is where you place the code. Each statement in the body section is also terminated with a semicolon." }, { "code": null, "e": 28913, "s": 28904, "text": "Example:" }, { "code": null, "e": 29003, "s": 28913, "text": "The following example illustrates a very simple block, also known as an anonymous block." }, { "code": null, "e": 29175, "s": 29003, "text": "DO $$ \n<<first_block>>\nDECLARE\n counter integer := 0;\nBEGIN \n counter := counter + 1;\n RAISE NOTICE 'The current value of counter is %', counter;\nEND first_block $$;\n" }, { "code": null, "e": 29219, "s": 29175, "text": "NOTICE: The current value of counter is 1\n" }, { "code": null, "e": 29342, "s": 29219, "text": "The pgAdmin execution of the above block can be done by clicking on the execute button on the interface as depicted below:" }, { "code": null, "e": 29495, "s": 29342, "text": "Note: The DO statement does not belong to the block. It is used to execute an anonymous block. PostgreSQL introduced the DO statement since version 9.0." }, { "code": null, "e": 29765, "s": 29495, "text": "In the declaration section, we declared a variable counter and set its value to zero. Inside the body section, we increased the value of the counter to one and output its value using the RAISE NOTICE statement. The first_block label is just for demonstration purposes. " }, { "code": null, "e": 29795, "s": 29765, "text": "Concept of Double Dollar($$):" }, { "code": null, "e": 30066, "s": 29795, "text": "The double dollar ($$) is a substitution of a single quote (‘). When you develop a PL/pgSQL block, a function, or a stored procedure, you have to pass its body in the form of a string literal. In addition, you have to escape all single quote (‘) in the body as follows:" }, { "code": null, "e": 30241, "s": 30066, "text": "DO\n'<<first_block>>\nDECLARE\n counter integer := 0;\nBEGIN \n \n counter := counter + 1;\n RAISE NOTICE ''The current value of counter is %'', counter;\n\nEND first_block';\n" }, { "code": null, "e": 30374, "s": 30241, "text": "If you use the double dollar ($$) you can avoid quoting issues. You can also use a token between $$ like $function$ or $procedure$." }, { "code": null, "e": 30393, "s": 30374, "text": "PL/pgSQL Subblock:" }, { "code": null, "e": 30594, "s": 30393, "text": "PL/pgSQL allows you to place a block inside the body of another block. This block nested inside another block is called subblock. The block that contains the subblock is referred to as an outer block." }, { "code": null, "e": 30839, "s": 30594, "text": "The subblocks are used for grouping statements so that a large block can be divided into smaller and more logical subblocks. The variables in the subblock can have the names as the ones in the outer block, even though it is not a good practice." }, { "code": null, "e": 31095, "s": 30839, "text": "When you declare a variable within a subblock with the same name as the one in the outer block, the variable in the outer block is hidden in the subblock. In case you want to access a variable in the outer block, you use a block label to qualify its name." }, { "code": null, "e": 31104, "s": 31095, "text": "Example:" }, { "code": null, "e": 31633, "s": 31104, "text": "DO $$ \n<<outer_block>>\nDECLARE\n counter integer := 0;\nBEGIN \n counter := counter + 1;\n RAISE NOTICE 'The current value of counter is %', counter;\n\n DECLARE \n counter integer := 0;\n BEGIN \n counter := counter + 10;\n RAISE NOTICE 'The current value of counter in the subblock is %', counter;\n RAISE NOTICE 'The current value of counter in the outer block is %', outer_block.counter;\n END;\n\n RAISE NOTICE 'The current value of counter in the outer block is %', counter;\n \nEND outer_block $$;\n" }, { "code": null, "e": 31641, "s": 31633, "text": "Output:" }, { "code": null, "e": 31869, "s": 31641, "text": "NOTICE: The current value of counter is 1\nNOTICE: The current value of counter in the subblock is 10\nNOTICE: The current value of counter in the outer block is 1\nNOTICE: The current value of counter in the outer block is 1\n" }, { "code": null, "e": 31902, "s": 31869, "text": "Let’s analyze the above example:" }, { "code": null, "e": 31966, "s": 31902, "text": "First, we declared a variable named counter in the outer_block." }, { "code": null, "e": 32194, "s": 31966, "text": "Then, before entering into the subblock, the value of the counter is one. In the subblock, we increased the value of the counter to ten and print it out. Notice that the change only affects the counter variable in the subblock." }, { "code": null, "e": 32323, "s": 32194, "text": "After that, we referred to the counter variable in the outer block using the block label to qualify its name outer_block.counter" }, { "code": null, "e": 32427, "s": 32323, "text": "Finally, we printed out the value of the counter variable in the outer block, its value remains intact." }, { "code": null, "e": 32453, "s": 32427, "text": "postgreSQL-administration" }, { "code": null, "e": 32464, "s": 32453, "text": "PostgreSQL" }, { "code": null, "e": 32562, "s": 32464, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 32571, "s": 32562, "text": "Comments" }, { "code": null, "e": 32584, "s": 32571, "text": "Old Comments" }, { "code": null, "e": 32616, "s": 32584, "text": "PostgreSQL - Change Column Type" }, { "code": null, "e": 32643, "s": 32616, "text": "PostgreSQL - Psql commands" }, { "code": null, "e": 32666, "s": 32643, "text": "PostgreSQL - For Loops" }, { "code": null, "e": 32706, "s": 32666, "text": "PostgreSQL - Function Returning A Table" }, { "code": null, "e": 32761, "s": 32706, "text": "PostgreSQL - Create Auto-increment Column using SERIAL" }, { "code": null, "e": 32803, "s": 32761, "text": "How to use PostgreSQL Database in Django?" }, { "code": null, "e": 32827, "s": 32803, "text": "PostgreSQL - DROP INDEX" }, { "code": null, "e": 32851, "s": 32827, "text": "PostgreSQL - Copy Table" }, { "code": null, "e": 32876, "s": 32851, "text": "PostgreSQL - Select Into" } ]
Perl ucfirst Function
This function returns the value of EXPR with only the first character uppercased. If EXPR is omitted, then uses $_. Following is the simple syntax for this function − ucfirst EXPR ucfirst This function returns String with first character in uppercase. Following is the example code showing its basic usage − #!/usr/bin/perl -w $string = 'the cat sat on the mat.'; $u_string = ucfirst($string); print "First String |$string|\n"; print "Second String |$u_string|\n"; When above code is executed, it produces the following result − First String |the cat sat on the mat.| Second String |The cat sat on the mat.| 46 Lectures 4.5 hours Devi Killada 11 Lectures 1.5 hours Harshit Srivastava 30 Lectures 6 hours TELCOMA Global 24 Lectures 2 hours Mohammad Nauman 68 Lectures 7 hours Stone River ELearning 58 Lectures 6.5 hours Stone River ELearning Print Add Notes Bookmark this page
[ { "code": null, "e": 2336, "s": 2220, "text": "This function returns the value of EXPR with only the first character uppercased. If EXPR is omitted, then uses $_." }, { "code": null, "e": 2387, "s": 2336, "text": "Following is the simple syntax for this function −" }, { "code": null, "e": 2410, "s": 2387, "text": "ucfirst EXPR\n\nucfirst\n" }, { "code": null, "e": 2474, "s": 2410, "text": "This function returns String with first character in uppercase." }, { "code": null, "e": 2530, "s": 2474, "text": "Following is the example code showing its basic usage −" }, { "code": null, "e": 2689, "s": 2530, "text": "#!/usr/bin/perl -w\n\n$string = 'the cat sat on the mat.';\n$u_string = ucfirst($string);\n\nprint \"First String |$string|\\n\";\nprint \"Second String |$u_string|\\n\";" }, { "code": null, "e": 2753, "s": 2689, "text": "When above code is executed, it produces the following result −" }, { "code": null, "e": 2833, "s": 2753, "text": "First String |the cat sat on the mat.|\nSecond String |The cat sat on the mat.|\n" }, { "code": null, "e": 2868, "s": 2833, "text": "\n 46 Lectures \n 4.5 hours \n" }, { "code": null, "e": 2882, "s": 2868, "text": " Devi Killada" }, { "code": null, "e": 2917, "s": 2882, "text": "\n 11 Lectures \n 1.5 hours \n" }, { "code": null, "e": 2937, "s": 2917, "text": " Harshit Srivastava" }, { "code": null, "e": 2970, "s": 2937, "text": "\n 30 Lectures \n 6 hours \n" }, { "code": null, "e": 2986, "s": 2970, "text": " TELCOMA Global" }, { "code": null, "e": 3019, "s": 2986, "text": "\n 24 Lectures \n 2 hours \n" }, { "code": null, "e": 3036, "s": 3019, "text": " Mohammad Nauman" }, { "code": null, "e": 3069, "s": 3036, "text": "\n 68 Lectures \n 7 hours \n" }, { "code": null, "e": 3092, "s": 3069, "text": " Stone River ELearning" }, { "code": null, "e": 3127, "s": 3092, "text": "\n 58 Lectures \n 6.5 hours \n" }, { "code": null, "e": 3150, "s": 3127, "text": " Stone River ELearning" }, { "code": null, "e": 3157, "s": 3150, "text": " Print" }, { "code": null, "e": 3168, "s": 3157, "text": " Add Notes" } ]
Display records after a particular date in MySQL
Let us first create a table − mysql> create table DemoTable708 ( CustomerName varchar(100), ShippingDate date ); Query OK, 0 rows affected (0.51 sec) Insert some records in the table using insert command − mysql> insert into DemoTable708 values('John','2019-01-21'); Query OK, 1 row affected (0.20 sec) mysql> insert into DemoTable708 values('Chris','2019-03-24'); Query OK, 1 row affected (0.15 sec) mysql> insert into DemoTable708 values('Robert','2019-04-26'); Query OK, 1 row affected (0.14 sec) mysql> insert into DemoTable708 values('David','2019-07-22'); Query OK, 1 row affected (0.17 sec) Display all records from the table using select statement − mysql> select *from DemoTable708; This will produce the following output - +--------------+--------------+ | CustomerName | ShippingDate | +--------------+--------------+ | John | 2019-01-21 | | Chris | 2019-03-24 | | Robert | 2019-04-26 | | David | 2019-07-22 | +--------------+--------------+ 4 rows in set (0.00 sec) Following is the query to display records after a particular date in MySQL − mysql> select *from DemoTable708 where ShippingDate >='2019-04-01'; This will produce the following output - +--------------+--------------+ | CustomerName | ShippingDate | +--------------+--------------+ | Robert | 2019-04-26 | | David | 2019-07-22 | +--------------+--------------+ 2 rows in set (0.00 sec)
[ { "code": null, "e": 1092, "s": 1062, "text": "Let us first create a table −" }, { "code": null, "e": 1218, "s": 1092, "text": "mysql> create table DemoTable708 (\n CustomerName varchar(100),\n ShippingDate date\n);\nQuery OK, 0 rows affected (0.51 sec)" }, { "code": null, "e": 1274, "s": 1218, "text": "Insert some records in the table using insert command −" }, { "code": null, "e": 1666, "s": 1274, "text": "mysql> insert into DemoTable708 values('John','2019-01-21');\nQuery OK, 1 row affected (0.20 sec)\nmysql> insert into DemoTable708 values('Chris','2019-03-24');\nQuery OK, 1 row affected (0.15 sec)\nmysql> insert into DemoTable708 values('Robert','2019-04-26');\nQuery OK, 1 row affected (0.14 sec)\nmysql> insert into DemoTable708 values('David','2019-07-22');\nQuery OK, 1 row affected (0.17 sec)" }, { "code": null, "e": 1726, "s": 1666, "text": "Display all records from the table using select statement −" }, { "code": null, "e": 1760, "s": 1726, "text": "mysql> select *from DemoTable708;" }, { "code": null, "e": 1801, "s": 1760, "text": "This will produce the following output -" }, { "code": null, "e": 2082, "s": 1801, "text": "+--------------+--------------+\n| CustomerName | ShippingDate |\n+--------------+--------------+\n| John | 2019-01-21 |\n| Chris | 2019-03-24 |\n| Robert | 2019-04-26 |\n| David | 2019-07-22 |\n+--------------+--------------+\n4 rows in set (0.00 sec)" }, { "code": null, "e": 2159, "s": 2082, "text": "Following is the query to display records after a particular date in MySQL −" }, { "code": null, "e": 2227, "s": 2159, "text": "mysql> select *from DemoTable708 where ShippingDate >='2019-04-01';" }, { "code": null, "e": 2268, "s": 2227, "text": "This will produce the following output -" }, { "code": null, "e": 2485, "s": 2268, "text": "+--------------+--------------+\n| CustomerName | ShippingDate |\n+--------------+--------------+\n| Robert | 2019-04-26 |\n| David | 2019-07-22 |\n+--------------+--------------+\n2 rows in set (0.00 sec)" } ]
AddressNet: How to build a robust street address parser using a Recurrent Neural Network | by Jason Rigby | Towards Data Science
Street addresses are complex beasts; they’re designed to be systematic and unambiguous to us human-folk, but end up a disaster for machines. Indeed, you’ll be paying US$5 per 1000 address lookups with Google, and Australia Post will point you to a selection of certified “solutions providers” while also offering discounts to those who pre-sort and barcode their mail (i.e. do the hard work). Maintaining structured address data has value beyond ye olde postage. The ability to reduce an address to geographic coordinates (geocoding) can yield answers to questions deceptively simple as “where do I make most of my sales?”, but it doesn’t take much imagination to see how all manner of correlations could be drawn from a person’s location, e.g. in public health (the industry in which I currently work). Now, of course it makes sense to collect this information in a structured manner from the outset, but what if you have a legacy dataset of manually entered and unvalidated address records? If you ask on StackOverflow the innocent question of... Looking for a quick and dirty way to parse Australian street addresses into its parts:3A/45 Jindabyne Rd, Oakleigh, VIC 3166 ... you will be quickly told that “you’re going to get data that’s completely useless,” and then you’ll be shown a regular expression like this: (?P<Unit_Number>\d*)\s*[\/,\,]\s*(?P<Street_Number>\d*)\s*(?P<Street_Name>[a-zA-Z\s]*),?\s*(?P<State>NSW|ACT|NT|QLD|SA|TAS|VIC|WA)\s*(?P<Post_Code>\d{4})| (?P<street_number>\d*)\s*(?P<street_name>[a-zA-Z\s]*),?\s*(?P<state>NSW|ACT|NT|QLD|SA|TAS|VIC|WA)\s*(?P<post_code>\d{4}) Dejected and saddened by the complex and unforgiving regular expression, you’ll slink away and lookup #ferrets on instagram because that’s really what the internet is for. I’m here to tell you to not be sad. I mean, watch the ferrets; they’re so cute, after all... and I wouldn’t want to rob you of such cuteness. But once you’re done, come back. I’ll show you how you can build your own address parsing machine. AddressNet, following the conventional neural network nomenclature of [Thing]+Net, is a nifty model that sorts out the bits of an address by labelling them any one of 22 possible components and is based on the GNAF database. It’s the product of about a week’s worth of work poking around TensorFlow (and de-rusting myself from a bit of a hiatus from machine learning) — I’m certain a more talented soul could produce this in a much shorter time (hash-tag-kids-these-days). The tl;dr: If you want a Python API to chop up your Australian street addresses, give AddressNet a go. >>> from addressnet.predict import predict_one>>> print(predict_one("3A/45 Jindabyne Rd, Oakleigh, VIC 3166")){'flat_number': '3', 'flat_number_suffix': 'A', 'number_first': '45', 'street_name': 'JINDABYNE', 'street_type': 'ROAD', 'locality_name': 'OAKLEIGH', 'state': 'VICTORIA', 'postcode': '3166'} Boom. So how does this trickery work? I’m sorry to say that I cannot do the theory justice; many smarter than I have written at length on these topics. So I’ll explain the process used in AddressNet at a high-level and link to my favourite authors whose elegant explanations deserve no reproduction here. At the heart of the AddressNet model is a Recurrent Neural Network (RNN) and they’re great at modelling sequential data (in this case, a sequence of letters). This kind of neural network is often shown diagramatically as: In the above diagram, x is an item from the input data sequence, y is some target estimation or output. The loopy arrow on the left, and the equivalently the horizontal arrows marked ‘h’ to the right, represent a “hidden state.” Each input is subscripted (t-1, t, t+1, etc.) indicating the point from which a particular sequence element originated, and this is often called referred to as the “time-step” (although this is often not time in the literal sense, but rather a “directional progression” through the elements). The big ol’ circular blobs in the middle contain all the matrix operations to produce the ys and hs, but be sure to note that each blob is identical; the exact same internal parameters are applied to each incoming h and x, thus making them recurrent. [Recommended reading: The Unreasonable Effectiveness of Recurrent Neural Networks] The way RNNs operate can be superficially explained like this: for each item of data in the sequence, transform it in some way using the hidden state of the previous step to both estimate a target output while also updating the hidden state to be handed off to the next step. This mysterious hidden state can be though of as “knowledge gleaned as the sequence is scanned,” and it functions as a memory of sorts. Many variations of RNN architecture centre around how the hidden state is managed, and the most common types are LSTM- and GRU-type RNNs (AddressNet uses the GRU-type of RNN). [Recommended reading: Understanding LSTM Networks; Understanding GRU networks] Being able to carry forward information from earlier in the sequence is the key strength of RNNs. In natural language processing, for example, grammatical concepts such as plurality and gender and the corresponding word conjugations often are linked over a long distance. Imagine an RNN designed to identify inappropriate verb forms; a simplistic grammar checker, if you will: Each x represents a word of the sentence, and each y yields a 0 if there is no mistake, and a 1 if there is a mistake. Here, the verb “is” should actually be “are” since the noun “diagrams” is plural. The ability to retain some memory of prior elements allows this hypothetical network to generate outcomes framed as “given what I have seen so far, what is the probability that the current element is a mistake?” RNNs can be extended to be multi-layer (outputs at each step are fed in as the inputs of another RNN), and they can also be paired with an equivalent RNN where the horizontal arrows are in the reverse direction, passing the hidden state backwards, effectively looking into the “future” to learn about the “past.” The latter is known as a bidirectional RNN. [Recommended reading: Bidirectional recurrent neural networks / PDF ] A multi-layer bidirectional RNN is used in AddressNet on a per-character basis. The bidirectionality is particularly important: consider the address “10 24–26 High Street Road, Mount Waverley” Assigning each character a class when only looking forward in time is almost impossible for the first character! Yes, maybe the unit/flat number is most frequently the first character, and perhaps there are more units than stand-alone properties overall, so we may statistically stand a chance, but it’s really just a stab in the dark. Similarly, the without any ability to look into the future, “Street” is probably indicating the type of street... but then we encounter “Road,” only to learn that we’ve made a mistake and the name is actually “High Street” of type “Road.” In the AddressNet implementation, one thing that differs from the diagrams above is that the output from the AddressNet RNN is not the predictions directly, but the forward and backwards pass are joined together and put through a final “fully connected” neural network — these are the standard textbook networks that are #1 in a Google Image search. If you want to see the exact implementation of this network, check out this part of the code. But how are characters represented in the first place? What is ‘A’? How can we shove ‘A’ — a letter — into a this magical bundle of mathematics? There are two main ways that textual data can be represented in neural networks: the “one-hot” vector approach, and the dense “embedding vector” approach. The former consists of a vector that is as long as our vocabulary (could be a list of words, characters, or even emoji 🤷‍♀️) containing a ‘1’ at the index corresponding to the item in our dictionary and zeros elsewhere, whereas the embedding vector approach is achieved through an arbitrarily long (but usually much shorter than the vocabulary) vector with parameters that are learnt by the model; that is, even the representations themselves are optimised as we train. Historically, embedding vectors have been used to derive semantic word relationships, but here I just use them for dimensionality reduction (and I generally like the idea of optimising the input parameters). AddressNet uses the embedding approach with short eight-unit vectors per character. [Recommended reading: TensorFlow docs, and anything on word embeddings (e.g. Mikolov’s word2vec paper)] Let’s talk training data. Alas I didn’t — and still don’t — have any labelled, curated, real-world address data. Instead, my approach was to synthetically generate as many random permutations (that were just shy of being unintelligible in some cases) that remain within the realms of plausible. There is a mish-mash of code that can be deciphered to understand the precise ways I butchered the GNAF dataset, but in essence the code makes the following decisions for each record in the GNAF dataset: Keep or drop the suburb?Keep or drop the state?Abbreviate the state? (e.g. changing “Victoria” to “VIC”)Keep or drop the postcode?Keep or drop the street number?Abbreviation the street type? (e.g. changing “Road” to “RD”)Keep or drop the unit type?Convert level numbers to ordinal or cardinal words? (e.g. changing “1” to “1st” or “first”) Keep or drop the suburb? Keep or drop the state? Abbreviate the state? (e.g. changing “Victoria” to “VIC”) Keep or drop the postcode? Keep or drop the street number? Abbreviation the street type? (e.g. changing “Road” to “RD”) Keep or drop the unit type? Convert level numbers to ordinal or cardinal words? (e.g. changing “1” to “1st” or “first”) The components are then shuffled in a special way (keeping thing like state and postcode nearer to the end, for example) and then each of the components is subjected to some random corruption that is designed to be somewhat like the typos a human might make. Typos include: Character substitution (using nearby characters on the keyboard)DeletionTranspositionDuplication Character substitution (using nearby characters on the keyboard) Deletion Transposition Duplication Then finally, each component is stitched together using some random delimiters. These might be spaces, dashes, slashes or full-stops (depending on the part of the address). But whyyyyy? Well there are two reasons: first, these are likely to actually occur in the real world and the model should be robust enough to handle these. Second, this extra noise is intended to function as a form of regularisation, which is a term for methods that reduce the likelihood that a model overfits. Properly mutating and corrupting the data was a high priority! While developing this model, I was acutely aware that I had no test data; there was no a priori way for me to know how well the model would perform in the real world. Ideally I would have a fully-labelled test set from manually entered addresses, however I am but one person working on a spare-time project. Thus it was key for me to ensure that there was so much variability in the input data that the model complexity could not start to “learn the noise.” Experience with the trained model suggests that I hit the mark, but I would love you, the reader, to give it a go and let me know how it goes. I know, I know, shame on me for having no test data 😔. Ready to try it out? I’m sure you said yes. Just pip install it and see what you think: https://github.com/jasonrig/address-net Contributions, feedback, corrections and suggestions are welcome. Let me know if you use AddressNet in, or adapt it for, your own project. May you never need a regular expression for your address data. 🙏
[ { "code": null, "e": 564, "s": 171, "text": "Street addresses are complex beasts; they’re designed to be systematic and unambiguous to us human-folk, but end up a disaster for machines. Indeed, you’ll be paying US$5 per 1000 address lookups with Google, and Australia Post will point you to a selection of certified “solutions providers” while also offering discounts to those who pre-sort and barcode their mail (i.e. do the hard work)." }, { "code": null, "e": 975, "s": 564, "text": "Maintaining structured address data has value beyond ye olde postage. The ability to reduce an address to geographic coordinates (geocoding) can yield answers to questions deceptively simple as “where do I make most of my sales?”, but it doesn’t take much imagination to see how all manner of correlations could be drawn from a person’s location, e.g. in public health (the industry in which I currently work)." }, { "code": null, "e": 1220, "s": 975, "text": "Now, of course it makes sense to collect this information in a structured manner from the outset, but what if you have a legacy dataset of manually entered and unvalidated address records? If you ask on StackOverflow the innocent question of..." }, { "code": null, "e": 1345, "s": 1220, "text": "Looking for a quick and dirty way to parse Australian street addresses into its parts:3A/45 Jindabyne Rd, Oakleigh, VIC 3166" }, { "code": null, "e": 1490, "s": 1345, "text": "... you will be quickly told that “you’re going to get data that’s completely useless,” and then you’ll be shown a regular expression like this:" }, { "code": null, "e": 1766, "s": 1490, "text": "(?P<Unit_Number>\\d*)\\s*[\\/,\\,]\\s*(?P<Street_Number>\\d*)\\s*(?P<Street_Name>[a-zA-Z\\s]*),?\\s*(?P<State>NSW|ACT|NT|QLD|SA|TAS|VIC|WA)\\s*(?P<Post_Code>\\d{4})| (?P<street_number>\\d*)\\s*(?P<street_name>[a-zA-Z\\s]*),?\\s*(?P<state>NSW|ACT|NT|QLD|SA|TAS|VIC|WA)\\s*(?P<post_code>\\d{4})" }, { "code": null, "e": 1938, "s": 1766, "text": "Dejected and saddened by the complex and unforgiving regular expression, you’ll slink away and lookup #ferrets on instagram because that’s really what the internet is for." }, { "code": null, "e": 2179, "s": 1938, "text": "I’m here to tell you to not be sad. I mean, watch the ferrets; they’re so cute, after all... and I wouldn’t want to rob you of such cuteness. But once you’re done, come back. I’ll show you how you can build your own address parsing machine." }, { "code": null, "e": 2652, "s": 2179, "text": "AddressNet, following the conventional neural network nomenclature of [Thing]+Net, is a nifty model that sorts out the bits of an address by labelling them any one of 22 possible components and is based on the GNAF database. It’s the product of about a week’s worth of work poking around TensorFlow (and de-rusting myself from a bit of a hiatus from machine learning) — I’m certain a more talented soul could produce this in a much shorter time (hash-tag-kids-these-days)." }, { "code": null, "e": 2755, "s": 2652, "text": "The tl;dr: If you want a Python API to chop up your Australian street addresses, give AddressNet a go." }, { "code": null, "e": 3056, "s": 2755, "text": ">>> from addressnet.predict import predict_one>>> print(predict_one(\"3A/45 Jindabyne Rd, Oakleigh, VIC 3166\")){'flat_number': '3', 'flat_number_suffix': 'A', 'number_first': '45', 'street_name': 'JINDABYNE', 'street_type': 'ROAD', 'locality_name': 'OAKLEIGH', 'state': 'VICTORIA', 'postcode': '3166'}" }, { "code": null, "e": 3062, "s": 3056, "text": "Boom." }, { "code": null, "e": 3361, "s": 3062, "text": "So how does this trickery work? I’m sorry to say that I cannot do the theory justice; many smarter than I have written at length on these topics. So I’ll explain the process used in AddressNet at a high-level and link to my favourite authors whose elegant explanations deserve no reproduction here." }, { "code": null, "e": 3583, "s": 3361, "text": "At the heart of the AddressNet model is a Recurrent Neural Network (RNN) and they’re great at modelling sequential data (in this case, a sequence of letters). This kind of neural network is often shown diagramatically as:" }, { "code": null, "e": 4356, "s": 3583, "text": "In the above diagram, x is an item from the input data sequence, y is some target estimation or output. The loopy arrow on the left, and the equivalently the horizontal arrows marked ‘h’ to the right, represent a “hidden state.” Each input is subscripted (t-1, t, t+1, etc.) indicating the point from which a particular sequence element originated, and this is often called referred to as the “time-step” (although this is often not time in the literal sense, but rather a “directional progression” through the elements). The big ol’ circular blobs in the middle contain all the matrix operations to produce the ys and hs, but be sure to note that each blob is identical; the exact same internal parameters are applied to each incoming h and x, thus making them recurrent." }, { "code": null, "e": 4439, "s": 4356, "text": "[Recommended reading: The Unreasonable Effectiveness of Recurrent Neural Networks]" }, { "code": null, "e": 5027, "s": 4439, "text": "The way RNNs operate can be superficially explained like this: for each item of data in the sequence, transform it in some way using the hidden state of the previous step to both estimate a target output while also updating the hidden state to be handed off to the next step. This mysterious hidden state can be though of as “knowledge gleaned as the sequence is scanned,” and it functions as a memory of sorts. Many variations of RNN architecture centre around how the hidden state is managed, and the most common types are LSTM- and GRU-type RNNs (AddressNet uses the GRU-type of RNN)." }, { "code": null, "e": 5106, "s": 5027, "text": "[Recommended reading: Understanding LSTM Networks; Understanding GRU networks]" }, { "code": null, "e": 5483, "s": 5106, "text": "Being able to carry forward information from earlier in the sequence is the key strength of RNNs. In natural language processing, for example, grammatical concepts such as plurality and gender and the corresponding word conjugations often are linked over a long distance. Imagine an RNN designed to identify inappropriate verb forms; a simplistic grammar checker, if you will:" }, { "code": null, "e": 5896, "s": 5483, "text": "Each x represents a word of the sentence, and each y yields a 0 if there is no mistake, and a 1 if there is a mistake. Here, the verb “is” should actually be “are” since the noun “diagrams” is plural. The ability to retain some memory of prior elements allows this hypothetical network to generate outcomes framed as “given what I have seen so far, what is the probability that the current element is a mistake?”" }, { "code": null, "e": 6253, "s": 5896, "text": "RNNs can be extended to be multi-layer (outputs at each step are fed in as the inputs of another RNN), and they can also be paired with an equivalent RNN where the horizontal arrows are in the reverse direction, passing the hidden state backwards, effectively looking into the “future” to learn about the “past.” The latter is known as a bidirectional RNN." }, { "code": null, "e": 6323, "s": 6253, "text": "[Recommended reading: Bidirectional recurrent neural networks / PDF ]" }, { "code": null, "e": 7535, "s": 6323, "text": "A multi-layer bidirectional RNN is used in AddressNet on a per-character basis. The bidirectionality is particularly important: consider the address “10 24–26 High Street Road, Mount Waverley” Assigning each character a class when only looking forward in time is almost impossible for the first character! Yes, maybe the unit/flat number is most frequently the first character, and perhaps there are more units than stand-alone properties overall, so we may statistically stand a chance, but it’s really just a stab in the dark. Similarly, the without any ability to look into the future, “Street” is probably indicating the type of street... but then we encounter “Road,” only to learn that we’ve made a mistake and the name is actually “High Street” of type “Road.” In the AddressNet implementation, one thing that differs from the diagrams above is that the output from the AddressNet RNN is not the predictions directly, but the forward and backwards pass are joined together and put through a final “fully connected” neural network — these are the standard textbook networks that are #1 in a Google Image search. If you want to see the exact implementation of this network, check out this part of the code." }, { "code": null, "e": 8597, "s": 7535, "text": "But how are characters represented in the first place? What is ‘A’? How can we shove ‘A’ — a letter — into a this magical bundle of mathematics? There are two main ways that textual data can be represented in neural networks: the “one-hot” vector approach, and the dense “embedding vector” approach. The former consists of a vector that is as long as our vocabulary (could be a list of words, characters, or even emoji 🤷‍♀️) containing a ‘1’ at the index corresponding to the item in our dictionary and zeros elsewhere, whereas the embedding vector approach is achieved through an arbitrarily long (but usually much shorter than the vocabulary) vector with parameters that are learnt by the model; that is, even the representations themselves are optimised as we train. Historically, embedding vectors have been used to derive semantic word relationships, but here I just use them for dimensionality reduction (and I generally like the idea of optimising the input parameters). AddressNet uses the embedding approach with short eight-unit vectors per character." }, { "code": null, "e": 8701, "s": 8597, "text": "[Recommended reading: TensorFlow docs, and anything on word embeddings (e.g. Mikolov’s word2vec paper)]" }, { "code": null, "e": 9200, "s": 8701, "text": "Let’s talk training data. Alas I didn’t — and still don’t — have any labelled, curated, real-world address data. Instead, my approach was to synthetically generate as many random permutations (that were just shy of being unintelligible in some cases) that remain within the realms of plausible. There is a mish-mash of code that can be deciphered to understand the precise ways I butchered the GNAF dataset, but in essence the code makes the following decisions for each record in the GNAF dataset:" }, { "code": null, "e": 9540, "s": 9200, "text": "Keep or drop the suburb?Keep or drop the state?Abbreviate the state? (e.g. changing “Victoria” to “VIC”)Keep or drop the postcode?Keep or drop the street number?Abbreviation the street type? (e.g. changing “Road” to “RD”)Keep or drop the unit type?Convert level numbers to ordinal or cardinal words? (e.g. changing “1” to “1st” or “first”)" }, { "code": null, "e": 9565, "s": 9540, "text": "Keep or drop the suburb?" }, { "code": null, "e": 9589, "s": 9565, "text": "Keep or drop the state?" }, { "code": null, "e": 9647, "s": 9589, "text": "Abbreviate the state? (e.g. changing “Victoria” to “VIC”)" }, { "code": null, "e": 9674, "s": 9647, "text": "Keep or drop the postcode?" }, { "code": null, "e": 9706, "s": 9674, "text": "Keep or drop the street number?" }, { "code": null, "e": 9767, "s": 9706, "text": "Abbreviation the street type? (e.g. changing “Road” to “RD”)" }, { "code": null, "e": 9795, "s": 9767, "text": "Keep or drop the unit type?" }, { "code": null, "e": 9887, "s": 9795, "text": "Convert level numbers to ordinal or cardinal words? (e.g. changing “1” to “1st” or “first”)" }, { "code": null, "e": 10161, "s": 9887, "text": "The components are then shuffled in a special way (keeping thing like state and postcode nearer to the end, for example) and then each of the components is subjected to some random corruption that is designed to be somewhat like the typos a human might make. Typos include:" }, { "code": null, "e": 10258, "s": 10161, "text": "Character substitution (using nearby characters on the keyboard)DeletionTranspositionDuplication" }, { "code": null, "e": 10323, "s": 10258, "text": "Character substitution (using nearby characters on the keyboard)" }, { "code": null, "e": 10332, "s": 10323, "text": "Deletion" }, { "code": null, "e": 10346, "s": 10332, "text": "Transposition" }, { "code": null, "e": 10358, "s": 10346, "text": "Duplication" }, { "code": null, "e": 10531, "s": 10358, "text": "Then finally, each component is stitched together using some random delimiters. These might be spaces, dashes, slashes or full-stops (depending on the part of the address)." }, { "code": null, "e": 10843, "s": 10531, "text": "But whyyyyy? Well there are two reasons: first, these are likely to actually occur in the real world and the model should be robust enough to handle these. Second, this extra noise is intended to function as a form of regularisation, which is a term for methods that reduce the likelihood that a model overfits." }, { "code": null, "e": 11562, "s": 10843, "text": "Properly mutating and corrupting the data was a high priority! While developing this model, I was acutely aware that I had no test data; there was no a priori way for me to know how well the model would perform in the real world. Ideally I would have a fully-labelled test set from manually entered addresses, however I am but one person working on a spare-time project. Thus it was key for me to ensure that there was so much variability in the input data that the model complexity could not start to “learn the noise.” Experience with the trained model suggests that I hit the mark, but I would love you, the reader, to give it a go and let me know how it goes. I know, I know, shame on me for having no test data 😔." }, { "code": null, "e": 11690, "s": 11562, "text": "Ready to try it out? I’m sure you said yes. Just pip install it and see what you think: https://github.com/jasonrig/address-net" } ]
Using Skip Connections To Enhance Denoising Autoencoder Algorithms | by Metika Sikka | Towards Data Science
The official Keras blog, calls autoencoders an example of ‘self-supervised’ algorithms as their targets are generated from the input data. Hence, they are used for tasks of image reconstruction. The main parts of an autoencoder are: Encoder, Bottleneck and Decoder. The Encoder is extracts image features at each step and in the process compresses the input data. The bottleneck constrains the input to its lowest dimensions known as compressed representations of the input data. The Decoder comes after this bottleneck and is used to reconstruct the input data. A loss measure is used to compare how close the generated or reconstructed date is to the input data. Data denoising images is a common application of autoencoders. Noise in images can be understood as a random variation in color or brightness of images, degrading their quality. Removing this noise is often a pre-processing step in various use-cases of image data. Convolutional autoencoders can be used for this purpose. The encoder learns to extract the features separating them from the noise in the image. Thereby compressing the image. The final compressed representations from the bottleneck are passed over to the decoder. The decoder finally decompresses the image minimizing the noise. We know that deep neural networks suffer from the degradation problem. Since Autoencoders have multiple convolutional and deconvolutional layers, they also suffer in performance when reconstructing images due to this information loss. Residual networks comprising of skip connections are a known solution to this problem. Hence, to improve the performance of the autoencoders such ‘skip connections’ can be added from the encoder to the decoder, i.e. across the bottleneck. These additional connections can directly send the feature maps from the an earlier layer of the encoder to a later layer of the decoder. This helps the decoder form more clearly defined decompressions of the input image. To see the advantage of these residual networks, let’s see the activation outputs at various stages of a convolutional autoencoder model. First we trained an autoencoder model without skip-connections across the bottleneck. Then we added them and train the model again on the same sample of images. A sample of 10K RGB images were taken from this data set of Flickr images on Kaggle. All the analysis was done using Google Colab’s GPU. We have used the Functional API of Keras to form the autoencoder model. The input images were resized to a smaller size (128,128,3) because of computational limitations. The image pixels were also standardized by a factor of 1/255. Further, the images were corrupted on purpose by applying a Gaussian noise matrix. These corrupted images formed the input of the autoencoder whereas the original images were used as targets while training the model. When building convolutional networks it is important to remember that, as we go deeper, the number of channels or filters increases whereas the size (height and width) of the input decreases. #Input input_img = Input(shape=(128, 128, 3))#Encoder y = Conv2D(32, (3, 3), padding='same',strides =(2,2))(input_img)y = LeakyReLU()(y)y = Conv2D(64, (3, 3), padding='same',strides =(2,2))(y)y = LeakyReLU()(y)y1 = Conv2D(128, (3, 3), padding='same',strides =(2,2))(y) # skip-1y = LeakyReLU()(y1)y = Conv2D(256, (3, 3), padding='same',strides =(2,2))(y)y = LeakyReLU()(y)y2 = Conv2D(256, (3, 3), padding='same',strides =(2,2))(y)# skip-2y = LeakyReLU()(y2)y = Conv2D(512, (3, 3), padding='same',strides =(2,2))(y)y = LeakyReLU()(y)y = Conv2D(1024, (3, 3), padding='same',strides =(2,2))(y)y = LeakyReLU()(y)#Flattening for the bottleneckvol = y.shapex = Flatten()(y)latent = Dense(128, activation='relu')(x) Below is code for the decoder. Transposed convolution or deconvolutional layers were used to build this decoder. Deconvolutional layers work roughly like a combination of convolutional and upsampling layers. Initially, we trained the model without the first and second skip connections. Then these connections were added from an earlier layer of the encoder to the later layer of the decoder using Add() from the layers API in Keras. The lrelu_bn() helper function was used to apply activations to these additions and pass the result through a batch normalization layer. # Helper function to apply activation and batch normalization to the # output added with output of residual connection from the encoderdef lrelu_bn(inputs): lrelu = LeakyReLU()(inputs) bn = BatchNormalization()(lrelu) return bn#Decodery = Dense(np.prod(vol[1:]), activation='relu')(latent)y = Reshape((vol[1], vol[2], vol[3]))(y)y = Conv2DTranspose(1024, (3,3), padding='same')(y)y = LeakyReLU()(y)y = Conv2DTranspose(512, (3,3), padding='same',strides=(2,2))(y)y = LeakyReLU()(y)y = Conv2DTranspose(256, (3,3), padding='same',strides=(2,2))(y)y= Add()([y2, y]) # second skip connection added herey = lrelu_bn(y)y = Conv2DTranspose(256, (3,3), padding='same',strides=(2,2))(y)y = LeakyReLU()(y)y = Conv2DTranspose(128, (3,3), padding='same',strides=(2,2))(y)y= Add()([y1, y]) # first skip connection added herey = lrelu_bn(y)y = Conv2DTranspose(64, (3,3), padding='same',strides=(2,2))(y)y = LeakyReLU()(y)y = Conv2DTranspose(32, (3,3), padding='same',strides=(2,2))(y)y = LeakyReLU()(y)y = Conv2DTranspose(3, (3,3), activation='sigmoid', padding='same',strides=(2,2))(y) Since the input images were standardized, their resulting pixel values were between 0 and 1. To get a comparable reconstructed image, “sigmoid” activation was used in the final layer. Out of the training set, 1k images were used as the validation set. Binary cross entropy was used as the loss function. Finally, both models were trained for 200 epochs with a mini-batch size of 32. The Adam optimizer with a learning rate of 0.001 gave the least training and validation loss at convergence. Let’s look at the activation outputs at various layers of the model for a test image. This will help us clearly see the encoder-decoder in action! The activation outputs were created using the keract package. We take a test image of the Columbia University campus. The test image was resized for the model and random noise was added. The ‘noisy’ image was used as the input for the model. Since the encoder was same for both the models, the activation outputs were also the same for this part. On examining the activation outputs of the first three convolutional layers, it can be seen that most of the image information is retained. This could also imply that the noise in the image is also retained at this stage of the model. However, as we go deeper in the model (see activation outputs of layers after the third convolutional layer), the information retained is quite abstract. The model starts to extract higher level features such as borders, corners & angles. It is interesting to note that the activation outputs of the decoder are in the exact opposite sequence as the encoder above. After the third de-convolutional layer, we still do not see any edges of the image being formed again. There is no clearly defined decompression of the image in the final layer of the decoder as seen below! As seen in the activation outputs of the encoder, its earlier layers retain the noise but the later layers extract higher representations of the image. Hence, skip connections are made from the third and fifth convolutional layers of the encoder to third and fifth deconvolutional layers of the decoder. The activation outputs of the first, second and third de-convolutional layers for this decoder are the same as the previous version of the decoder. However, after the third layer we see a difference in the activation outputs from those of the previous decoder. Below we can clearly see the image being formed again in the activation output of the sixth deconvolutional layer. The final layer of this decoder has given a clearly defined decompressed version of the test input image. Denoised image output from the first model: Denoised image output of the second model with skip connections across the bottleneck: We can clearly see the better performance the autoencoder model with skip connections across the bottleneck! This approach can be used for any image reconstruction application of autoencoders apart from denoising images. While the skip connections improve the performance of the autoencoder, the positions and number of these connections can be experimented with. The model can also be trained with different levels of noise factor for better generalization of results. The full code can be accessed here! J. Dong , XJ. Mao , C. Shen , YB. Yang, Learning Deep Representations Using Convolutional Auto-encoders with Symmetric Skip Connections (2017)
[ { "code": null, "e": 366, "s": 171, "text": "The official Keras blog, calls autoencoders an example of ‘self-supervised’ algorithms as their targets are generated from the input data. Hence, they are used for tasks of image reconstruction." }, { "code": null, "e": 836, "s": 366, "text": "The main parts of an autoencoder are: Encoder, Bottleneck and Decoder. The Encoder is extracts image features at each step and in the process compresses the input data. The bottleneck constrains the input to its lowest dimensions known as compressed representations of the input data. The Decoder comes after this bottleneck and is used to reconstruct the input data. A loss measure is used to compare how close the generated or reconstructed date is to the input data." }, { "code": null, "e": 1431, "s": 836, "text": "Data denoising images is a common application of autoencoders. Noise in images can be understood as a random variation in color or brightness of images, degrading their quality. Removing this noise is often a pre-processing step in various use-cases of image data. Convolutional autoencoders can be used for this purpose. The encoder learns to extract the features separating them from the noise in the image. Thereby compressing the image. The final compressed representations from the bottleneck are passed over to the decoder. The decoder finally decompresses the image minimizing the noise." }, { "code": null, "e": 2127, "s": 1431, "text": "We know that deep neural networks suffer from the degradation problem. Since Autoencoders have multiple convolutional and deconvolutional layers, they also suffer in performance when reconstructing images due to this information loss. Residual networks comprising of skip connections are a known solution to this problem. Hence, to improve the performance of the autoencoders such ‘skip connections’ can be added from the encoder to the decoder, i.e. across the bottleneck. These additional connections can directly send the feature maps from the an earlier layer of the encoder to a later layer of the decoder. This helps the decoder form more clearly defined decompressions of the input image." }, { "code": null, "e": 2426, "s": 2127, "text": "To see the advantage of these residual networks, let’s see the activation outputs at various stages of a convolutional autoencoder model. First we trained an autoencoder model without skip-connections across the bottleneck. Then we added them and train the model again on the same sample of images." }, { "code": null, "e": 2563, "s": 2426, "text": "A sample of 10K RGB images were taken from this data set of Flickr images on Kaggle. All the analysis was done using Google Colab’s GPU." }, { "code": null, "e": 3204, "s": 2563, "text": "We have used the Functional API of Keras to form the autoencoder model. The input images were resized to a smaller size (128,128,3) because of computational limitations. The image pixels were also standardized by a factor of 1/255. Further, the images were corrupted on purpose by applying a Gaussian noise matrix. These corrupted images formed the input of the autoencoder whereas the original images were used as targets while training the model. When building convolutional networks it is important to remember that, as we go deeper, the number of channels or filters increases whereas the size (height and width) of the input decreases." }, { "code": null, "e": 3913, "s": 3204, "text": "#Input input_img = Input(shape=(128, 128, 3))#Encoder y = Conv2D(32, (3, 3), padding='same',strides =(2,2))(input_img)y = LeakyReLU()(y)y = Conv2D(64, (3, 3), padding='same',strides =(2,2))(y)y = LeakyReLU()(y)y1 = Conv2D(128, (3, 3), padding='same',strides =(2,2))(y) # skip-1y = LeakyReLU()(y1)y = Conv2D(256, (3, 3), padding='same',strides =(2,2))(y)y = LeakyReLU()(y)y2 = Conv2D(256, (3, 3), padding='same',strides =(2,2))(y)# skip-2y = LeakyReLU()(y2)y = Conv2D(512, (3, 3), padding='same',strides =(2,2))(y)y = LeakyReLU()(y)y = Conv2D(1024, (3, 3), padding='same',strides =(2,2))(y)y = LeakyReLU()(y)#Flattening for the bottleneckvol = y.shapex = Flatten()(y)latent = Dense(128, activation='relu')(x) " }, { "code": null, "e": 4484, "s": 3913, "text": "Below is code for the decoder. Transposed convolution or deconvolutional layers were used to build this decoder. Deconvolutional layers work roughly like a combination of convolutional and upsampling layers. Initially, we trained the model without the first and second skip connections. Then these connections were added from an earlier layer of the encoder to the later layer of the decoder using Add() from the layers API in Keras. The lrelu_bn() helper function was used to apply activations to these additions and pass the result through a batch normalization layer." }, { "code": null, "e": 5562, "s": 4484, "text": "# Helper function to apply activation and batch normalization to the # output added with output of residual connection from the encoderdef lrelu_bn(inputs): lrelu = LeakyReLU()(inputs) bn = BatchNormalization()(lrelu) return bn#Decodery = Dense(np.prod(vol[1:]), activation='relu')(latent)y = Reshape((vol[1], vol[2], vol[3]))(y)y = Conv2DTranspose(1024, (3,3), padding='same')(y)y = LeakyReLU()(y)y = Conv2DTranspose(512, (3,3), padding='same',strides=(2,2))(y)y = LeakyReLU()(y)y = Conv2DTranspose(256, (3,3), padding='same',strides=(2,2))(y)y= Add()([y2, y]) # second skip connection added herey = lrelu_bn(y)y = Conv2DTranspose(256, (3,3), padding='same',strides=(2,2))(y)y = LeakyReLU()(y)y = Conv2DTranspose(128, (3,3), padding='same',strides=(2,2))(y)y= Add()([y1, y]) # first skip connection added herey = lrelu_bn(y)y = Conv2DTranspose(64, (3,3), padding='same',strides=(2,2))(y)y = LeakyReLU()(y)y = Conv2DTranspose(32, (3,3), padding='same',strides=(2,2))(y)y = LeakyReLU()(y)y = Conv2DTranspose(3, (3,3), activation='sigmoid', padding='same',strides=(2,2))(y)" }, { "code": null, "e": 6054, "s": 5562, "text": "Since the input images were standardized, their resulting pixel values were between 0 and 1. To get a comparable reconstructed image, “sigmoid” activation was used in the final layer. Out of the training set, 1k images were used as the validation set. Binary cross entropy was used as the loss function. Finally, both models were trained for 200 epochs with a mini-batch size of 32. The Adam optimizer with a learning rate of 0.001 gave the least training and validation loss at convergence." }, { "code": null, "e": 6201, "s": 6054, "text": "Let’s look at the activation outputs at various layers of the model for a test image. This will help us clearly see the encoder-decoder in action!" }, { "code": null, "e": 6263, "s": 6201, "text": "The activation outputs were created using the keract package." }, { "code": null, "e": 6443, "s": 6263, "text": "We take a test image of the Columbia University campus. The test image was resized for the model and random noise was added. The ‘noisy’ image was used as the input for the model." }, { "code": null, "e": 7022, "s": 6443, "text": "Since the encoder was same for both the models, the activation outputs were also the same for this part. On examining the activation outputs of the first three convolutional layers, it can be seen that most of the image information is retained. This could also imply that the noise in the image is also retained at this stage of the model. However, as we go deeper in the model (see activation outputs of layers after the third convolutional layer), the information retained is quite abstract. The model starts to extract higher level features such as borders, corners & angles." }, { "code": null, "e": 7148, "s": 7022, "text": "It is interesting to note that the activation outputs of the decoder are in the exact opposite sequence as the encoder above." }, { "code": null, "e": 7251, "s": 7148, "text": "After the third de-convolutional layer, we still do not see any edges of the image being formed again." }, { "code": null, "e": 7355, "s": 7251, "text": "There is no clearly defined decompression of the image in the final layer of the decoder as seen below!" }, { "code": null, "e": 8035, "s": 7355, "text": "As seen in the activation outputs of the encoder, its earlier layers retain the noise but the later layers extract higher representations of the image. Hence, skip connections are made from the third and fifth convolutional layers of the encoder to third and fifth deconvolutional layers of the decoder. The activation outputs of the first, second and third de-convolutional layers for this decoder are the same as the previous version of the decoder. However, after the third layer we see a difference in the activation outputs from those of the previous decoder. Below we can clearly see the image being formed again in the activation output of the sixth deconvolutional layer." }, { "code": null, "e": 8141, "s": 8035, "text": "The final layer of this decoder has given a clearly defined decompressed version of the test input image." }, { "code": null, "e": 8185, "s": 8141, "text": "Denoised image output from the first model:" }, { "code": null, "e": 8272, "s": 8185, "text": "Denoised image output of the second model with skip connections across the bottleneck:" }, { "code": null, "e": 8381, "s": 8272, "text": "We can clearly see the better performance the autoencoder model with skip connections across the bottleneck!" }, { "code": null, "e": 8778, "s": 8381, "text": "This approach can be used for any image reconstruction application of autoencoders apart from denoising images. While the skip connections improve the performance of the autoencoder, the positions and number of these connections can be experimented with. The model can also be trained with different levels of noise factor for better generalization of results. The full code can be accessed here!" } ]
How to Install Tkinter on Linux? - GeeksforGeeks
05 Oct, 2021 Tkinter is the most popular Python library used to create GUI-based applications. The name Tkinter comes from the Tk interface. In this article, we will look into the process of installing Tkinter in a Linux system. Note: Tkinter module comes in bundled with Python, so this article can be helpful for those who might face an error running Tkinter on their system. Follow the below step to install Tkinter on a Linux system: Step 1. Open up the Linux terminal and run the following command depending upon your version of Linux: For Debian-based Linux: sudo apt-get install python-tk For Arch-based Linux: sudo pacman -S tk For Fedora-based Linux: sudo dnf install python3-tkinter For RHEL, CentOS, Oracle Linux: sudo yum install -y tkinter tk-devel Installing Tkinter in debian based linux Step 2: After writing the above command hit the enter button and type your user password. After this, it will ask you to confirm the installation type “Y” in the terminal and hit enter. installing tkinter Step 3: To verify the Tkinter installation run the following command in the terminal. And you will see a pop-up window opened with two buttons showing the current version of Tkinter installed. python -m Tkinter Tkinter installed Note: The highlighted text shows the current version of the Tkinter i.e. 8.6 Blogathon-2021 how-to-install Picked Blogathon How To Installation Guide Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments How to Import JSON Data into SQL Server? How to Install Tkinter in Windows? SQL - Multiple Column Ordering How to pass data into table from a form using React Components How to Create a Table With Multiple Foreign Keys in SQL? How to Install PIP on Windows ? How to Find the Wi-Fi Password Using CMD in Windows? How to install Jupyter Notebook on Windows? How to Align Text in HTML? How to Install OpenCV for Python on Windows?
[ { "code": null, "e": 24421, "s": 24393, "text": "\n05 Oct, 2021" }, { "code": null, "e": 24637, "s": 24421, "text": "Tkinter is the most popular Python library used to create GUI-based applications. The name Tkinter comes from the Tk interface. In this article, we will look into the process of installing Tkinter in a Linux system." }, { "code": null, "e": 24786, "s": 24637, "text": "Note: Tkinter module comes in bundled with Python, so this article can be helpful for those who might face an error running Tkinter on their system." }, { "code": null, "e": 24846, "s": 24786, "text": "Follow the below step to install Tkinter on a Linux system:" }, { "code": null, "e": 24949, "s": 24846, "text": "Step 1. Open up the Linux terminal and run the following command depending upon your version of Linux:" }, { "code": null, "e": 24973, "s": 24949, "text": "For Debian-based Linux:" }, { "code": null, "e": 25004, "s": 24973, "text": "sudo apt-get install python-tk" }, { "code": null, "e": 25026, "s": 25004, "text": "For Arch-based Linux:" }, { "code": null, "e": 25044, "s": 25026, "text": "sudo pacman -S tk" }, { "code": null, "e": 25068, "s": 25044, "text": "For Fedora-based Linux:" }, { "code": null, "e": 25101, "s": 25068, "text": "sudo dnf install python3-tkinter" }, { "code": null, "e": 25133, "s": 25101, "text": "For RHEL, CentOS, Oracle Linux:" }, { "code": null, "e": 25170, "s": 25133, "text": "sudo yum install -y tkinter tk-devel" }, { "code": null, "e": 25211, "s": 25170, "text": "Installing Tkinter in debian based linux" }, { "code": null, "e": 25398, "s": 25211, "text": "Step 2: After writing the above command hit the enter button and type your user password. After this, it will ask you to confirm the installation type “Y” in the terminal and hit enter." }, { "code": null, "e": 25417, "s": 25398, "text": "installing tkinter" }, { "code": null, "e": 25610, "s": 25417, "text": "Step 3: To verify the Tkinter installation run the following command in the terminal. And you will see a pop-up window opened with two buttons showing the current version of Tkinter installed." }, { "code": null, "e": 25628, "s": 25610, "text": "python -m Tkinter" }, { "code": null, "e": 25646, "s": 25628, "text": "Tkinter installed" }, { "code": null, "e": 25723, "s": 25646, "text": "Note: The highlighted text shows the current version of the Tkinter i.e. 8.6" }, { "code": null, "e": 25738, "s": 25723, "text": "Blogathon-2021" }, { "code": null, "e": 25753, "s": 25738, "text": "how-to-install" }, { "code": null, "e": 25760, "s": 25753, "text": "Picked" }, { "code": null, "e": 25770, "s": 25760, "text": "Blogathon" }, { "code": null, "e": 25777, "s": 25770, "text": "How To" }, { "code": null, "e": 25796, "s": 25777, "text": "Installation Guide" }, { "code": null, "e": 25894, "s": 25796, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 25903, "s": 25894, "text": "Comments" }, { "code": null, "e": 25916, "s": 25903, "text": "Old Comments" }, { "code": null, "e": 25957, "s": 25916, "text": "How to Import JSON Data into SQL Server?" }, { "code": null, "e": 25992, "s": 25957, "text": "How to Install Tkinter in Windows?" }, { "code": null, "e": 26023, "s": 25992, "text": "SQL - Multiple Column Ordering" }, { "code": null, "e": 26086, "s": 26023, "text": "How to pass data into table from a form using React Components" }, { "code": null, "e": 26143, "s": 26086, "text": "How to Create a Table With Multiple Foreign Keys in SQL?" }, { "code": null, "e": 26175, "s": 26143, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 26228, "s": 26175, "text": "How to Find the Wi-Fi Password Using CMD in Windows?" }, { "code": null, "e": 26272, "s": 26228, "text": "How to install Jupyter Notebook on Windows?" }, { "code": null, "e": 26299, "s": 26272, "text": "How to Align Text in HTML?" } ]
Reading images in Python - GeeksforGeeks
19 Feb, 2022 Python supports very powerful tools when comes to image processing. Let’s see how to process the images using different libraries like ImageIO, OpenCV, Matplotlib, PIL, etc. Using ImageIO : Imageio is a Python library that provides an easy interface to read and write a wide range of image data, including animated images, video, volumetric data, and scientific formats. It is cross-platform, runs on Python 3.7+, and is easy to install. It is the recommended alternative to scipy.misc.imread and is used internally by libraries like scikit-image to load images. Using ImageIO : Imageio is a Python library that provides an easy interface to read and write a wide range of image data, including animated images, video, volumetric data, and scientific formats. It is cross-platform, runs on Python 3.7+, and is easy to install. It is the recommended alternative to scipy.misc.imread and is used internally by libraries like scikit-image to load images. Python3 # Python program to read an write an image import imageio as iio # read an imageimg = iio.imread("g4g.png") # write it in a new formatiio.imwrite("g4g.jpg", img) Output: Output: Output: Using OpenCV : OpenCV (Open Source Computer Vision) is a computer vision library that contains various functions to perform operations on pictures or videos. It was originally developed by Intel but was later maintained by Willow Garage and is now maintained by Itseez. This library is cross-platform that is it is available on multiple programming languages such as Python, C++ etc. Using OpenCV : OpenCV (Open Source Computer Vision) is a computer vision library that contains various functions to perform operations on pictures or videos. It was originally developed by Intel but was later maintained by Willow Garage and is now maintained by Itseez. This library is cross-platform that is it is available on multiple programming languages such as Python, C++ etc. Python3 # Python program to read image using OpenCV # importing OpenCV(cv2) moduleimport cv2 # Save image in set directory# Read RGB imageimg = cv2.imread('g4g.png') # Output img with window name as 'image'cv2.imshow('image', img) # Maintain output window utill# user presses a keycv2.waitKey(0) # Destroying present windows on screencv2.destroyAllWindows() Output : Output : Output : Using MatplotLib : Matplotlib is an amazing visualization library in Python for 2D plots of arrays. Matplotlib is a multi-platform data visualization library built on NumPy arrays and designed to work with the broader SciPy stack. It was introduced by John Hunter in the year 2002. Matplotlib comes with a wide variety of plots. Plots helps to understand trends, patterns, and to make correlations. They’re typically instruments for reasoning about quantitative information. Using MatplotLib : Matplotlib is an amazing visualization library in Python for 2D plots of arrays. Matplotlib is a multi-platform data visualization library built on NumPy arrays and designed to work with the broader SciPy stack. It was introduced by John Hunter in the year 2002. Matplotlib comes with a wide variety of plots. Plots helps to understand trends, patterns, and to make correlations. They’re typically instruments for reasoning about quantitative information. Python # Python program to read# image using matplotlib # importing matplotlib modulesimport matplotlib.image as mpimgimport matplotlib.pyplot as plt # Read Imagesimg = mpimg.imread('g4g.png') # Output Imagesplt.imshow(img) Output : Output : Using PIL : PIL is the Python Imaging Library which provides the python interpreter with image editing capabilities. It was developed by Fredrik Lundh and several other contributors. Pillow is the friendly PIL fork and an easy to use library developed by Alex Clark and other contributors. Using PIL : PIL is the Python Imaging Library which provides the python interpreter with image editing capabilities. It was developed by Fredrik Lundh and several other contributors. Pillow is the friendly PIL fork and an easy to use library developed by Alex Clark and other contributors. Python # Python program to read# image using PIL module # importing PILfrom PIL import Image # Read imageimg = Image.open('g4g.png') # Output Imagesimg.show() # prints format of imageprint(img.format) # prints mode of imageprint(img.mode) Output : Output : Output : PNG RGBA shubham_singh sebastian22 Image-Processing python-utility Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Python Dictionary How to Install PIP on Windows ? Enumerate() in Python Read a file line by line in Python Iterate over a list in Python Different ways to create Pandas Dataframe Reading and Writing to text files in Python Python OOPs Concepts Create a Pandas DataFrame from Lists *args and **kwargs in Python
[ { "code": null, "e": 24371, "s": 24343, "text": "\n19 Feb, 2022" }, { "code": null, "e": 24546, "s": 24371, "text": "Python supports very powerful tools when comes to image processing. Let’s see how to process the images using different libraries like ImageIO, OpenCV, Matplotlib, PIL, etc. " }, { "code": null, "e": 24935, "s": 24546, "text": "Using ImageIO : Imageio is a Python library that provides an easy interface to read and write a wide range of image data, including animated images, video, volumetric data, and scientific formats. It is cross-platform, runs on Python 3.7+, and is easy to install. It is the recommended alternative to scipy.misc.imread and is used internally by libraries like scikit-image to load images." }, { "code": null, "e": 25324, "s": 24935, "text": "Using ImageIO : Imageio is a Python library that provides an easy interface to read and write a wide range of image data, including animated images, video, volumetric data, and scientific formats. It is cross-platform, runs on Python 3.7+, and is easy to install. It is the recommended alternative to scipy.misc.imread and is used internally by libraries like scikit-image to load images." }, { "code": null, "e": 25332, "s": 25324, "text": "Python3" }, { "code": "# Python program to read an write an image import imageio as iio # read an imageimg = iio.imread(\"g4g.png\") # write it in a new formatiio.imwrite(\"g4g.jpg\", img)", "e": 25494, "s": 25332, "text": null }, { "code": null, "e": 25503, "s": 25494, "text": "Output: " }, { "code": null, "e": 25512, "s": 25503, "text": "Output: " }, { "code": null, "e": 25521, "s": 25512, "text": "Output: " }, { "code": null, "e": 25907, "s": 25521, "text": "Using OpenCV : OpenCV (Open Source Computer Vision) is a computer vision library that contains various functions to perform operations on pictures or videos. It was originally developed by Intel but was later maintained by Willow Garage and is now maintained by Itseez. This library is cross-platform that is it is available on multiple programming languages such as Python, C++ etc. " }, { "code": null, "e": 26293, "s": 25907, "text": "Using OpenCV : OpenCV (Open Source Computer Vision) is a computer vision library that contains various functions to perform operations on pictures or videos. It was originally developed by Intel but was later maintained by Willow Garage and is now maintained by Itseez. This library is cross-platform that is it is available on multiple programming languages such as Python, C++ etc. " }, { "code": null, "e": 26301, "s": 26293, "text": "Python3" }, { "code": "# Python program to read image using OpenCV # importing OpenCV(cv2) moduleimport cv2 # Save image in set directory# Read RGB imageimg = cv2.imread('g4g.png') # Output img with window name as 'image'cv2.imshow('image', img) # Maintain output window utill# user presses a keycv2.waitKey(0) # Destroying present windows on screencv2.destroyAllWindows()", "e": 26658, "s": 26301, "text": null }, { "code": null, "e": 26668, "s": 26658, "text": "Output : " }, { "code": null, "e": 26678, "s": 26668, "text": "Output : " }, { "code": null, "e": 26688, "s": 26678, "text": "Output : " }, { "code": null, "e": 27168, "s": 26688, "text": " Using MatplotLib : Matplotlib is an amazing visualization library in Python for 2D plots of arrays. Matplotlib is a multi-platform data visualization library built on NumPy arrays and designed to work with the broader SciPy stack. It was introduced by John Hunter in the year 2002. Matplotlib comes with a wide variety of plots. Plots helps to understand trends, patterns, and to make correlations. They’re typically instruments for reasoning about quantitative information. " }, { "code": null, "e": 27649, "s": 27172, "text": "Using MatplotLib : Matplotlib is an amazing visualization library in Python for 2D plots of arrays. Matplotlib is a multi-platform data visualization library built on NumPy arrays and designed to work with the broader SciPy stack. It was introduced by John Hunter in the year 2002. Matplotlib comes with a wide variety of plots. Plots helps to understand trends, patterns, and to make correlations. They’re typically instruments for reasoning about quantitative information. " }, { "code": null, "e": 27656, "s": 27649, "text": "Python" }, { "code": "# Python program to read# image using matplotlib # importing matplotlib modulesimport matplotlib.image as mpimgimport matplotlib.pyplot as plt # Read Imagesimg = mpimg.imread('g4g.png') # Output Imagesplt.imshow(img)", "e": 27873, "s": 27656, "text": null }, { "code": null, "e": 27883, "s": 27873, "text": "Output : " }, { "code": null, "e": 27893, "s": 27883, "text": "Output : " }, { "code": null, "e": 28188, "s": 27893, "text": " Using PIL : PIL is the Python Imaging Library which provides the python interpreter with image editing capabilities. It was developed by Fredrik Lundh and several other contributors. Pillow is the friendly PIL fork and an easy to use library developed by Alex Clark and other contributors. " }, { "code": null, "e": 28488, "s": 28196, "text": "Using PIL : PIL is the Python Imaging Library which provides the python interpreter with image editing capabilities. It was developed by Fredrik Lundh and several other contributors. Pillow is the friendly PIL fork and an easy to use library developed by Alex Clark and other contributors. " }, { "code": null, "e": 28495, "s": 28488, "text": "Python" }, { "code": "# Python program to read# image using PIL module # importing PILfrom PIL import Image # Read imageimg = Image.open('g4g.png') # Output Imagesimg.show() # prints format of imageprint(img.format) # prints mode of imageprint(img.mode)", "e": 28727, "s": 28495, "text": null }, { "code": null, "e": 28738, "s": 28727, "text": "Output : " }, { "code": null, "e": 28749, "s": 28738, "text": "Output : " }, { "code": null, "e": 28760, "s": 28749, "text": "Output : " }, { "code": null, "e": 28771, "s": 28760, "text": " \nPNG\nRGBA" }, { "code": null, "e": 28787, "s": 28773, "text": "shubham_singh" }, { "code": null, "e": 28799, "s": 28787, "text": "sebastian22" }, { "code": null, "e": 28816, "s": 28799, "text": "Image-Processing" }, { "code": null, "e": 28831, "s": 28816, "text": "python-utility" }, { "code": null, "e": 28838, "s": 28831, "text": "Python" }, { "code": null, "e": 28936, "s": 28838, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 28945, "s": 28936, "text": "Comments" }, { "code": null, "e": 28958, "s": 28945, "text": "Old Comments" }, { "code": null, "e": 28976, "s": 28958, "text": "Python Dictionary" }, { "code": null, "e": 29008, "s": 28976, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 29030, "s": 29008, "text": "Enumerate() in Python" }, { "code": null, "e": 29065, "s": 29030, "text": "Read a file line by line in Python" }, { "code": null, "e": 29095, "s": 29065, "text": "Iterate over a list in Python" }, { "code": null, "e": 29137, "s": 29095, "text": "Different ways to create Pandas Dataframe" }, { "code": null, "e": 29181, "s": 29137, "text": "Reading and Writing to text files in Python" }, { "code": null, "e": 29202, "s": 29181, "text": "Python OOPs Concepts" }, { "code": null, "e": 29239, "s": 29202, "text": "Create a Pandas DataFrame from Lists" } ]
How do you get a directory listing sorted by creation date in Python?
To get a directory listing sorted by creation date in Python, you can call os.listdir() to get a list of the filenames. Then call os.stat() for each one to get the creation time and finally sort against the creation time. import os import time import sys from stat import S_ISREG, ST_CTIME, ST_MODE dir_path = '.' # get all entries in the directory entries = (os.path.join(dir_path, file_name) for file_name in os.listdir(dir_path)) # Get their stats entries = ((os.stat(path), path) for path in entries) # leave only regular files, insert creation date entries = ((stat[ST_CTIME], path) for stat, path in entries if S_ISREG(stat[ST_MODE])) print(entries) Running the above code will give you listing sorted by creation date, for example, Mon Oct 23 18:01:25 2017 sorted_ls.py
[ { "code": null, "e": 1285, "s": 1062, "text": "To get a directory listing sorted by creation date in Python, you can call os.listdir() to get a list of the filenames. Then call os.stat() for each one to get the creation time and finally sort against the creation time. " }, { "code": null, "e": 1730, "s": 1285, "text": "import os\nimport time\nimport sys\nfrom stat import S_ISREG, ST_CTIME, ST_MODE\ndir_path = '.'\n# get all entries in the directory\nentries = (os.path.join(dir_path, file_name) for file_name in os.listdir(dir_path))\n# Get their stats\nentries = ((os.stat(path), path) for path in entries)\n# leave only regular files, insert creation date\nentries = ((stat[ST_CTIME], path)\n for stat, path in entries if S_ISREG(stat[ST_MODE]))\nprint(entries)" }, { "code": null, "e": 1813, "s": 1730, "text": "Running the above code will give you listing sorted by creation date, for example," }, { "code": null, "e": 1851, "s": 1813, "text": "Mon Oct 23 18:01:25 2017 sorted_ls.py" } ]
How to escape all special characters for regex in Python?
We use re.escape() to escape the special characters − The following code shows how all special characters in given string are escaped using re.escape() method >>> p = '5*(67).89?' >>> re.escape(p) '5\\*\\(67\\)\\.89\\?'
[ { "code": null, "e": 1116, "s": 1062, "text": "We use re.escape() to escape the special characters −" }, { "code": null, "e": 1221, "s": 1116, "text": "The following code shows how all special characters in given string are escaped using re.escape() method" }, { "code": null, "e": 1282, "s": 1221, "text": ">>> p = '5*(67).89?'\n>>> re.escape(p)\n'5\\\\*\\\\(67\\\\)\\\\.89\\\\?'" } ]
Point Cloud Data: Simple Approach | by Alex Simkiv | Towards Data Science
In recent years, there was great progress in the development of LIDAR detectors that resulted in huge amounts of raw data. LIDARs are now more accurate and provide a much higher resolution than even 10 years ago. Aerial-based LIDARs have become an efficient method for receiving information about the environment. Nevertheless, the data you get is in fact only a collection of sparse points that may provide some nice visualization but require extensive processing when it comes to more practical purposes. Unfortunately, as of now, the progress of computer vision mostly concerns structured two-dimensional data (photo, video). The current methods do not generalize to multidimensional sparse data like Point Cloud that we receive after a basic LIDAR data pre-processing. Extensive research is being done in the field. We should particularly mention PCL — a graf of libraries developed by a great international community to provide instruments for both 2D and 3D data for a wide variety of applications. Unfortunately, at the moment it is not an easy task to apply the library to some solution of interest. It often means that you have to dive into the library too deep. It makes sense for production-grade products that need high scalability. But it may be too costly for a PoC development. Therefore, I decided to try what can be done with point cloud data using a simple approach and pretty standard Python libraries (PCL can be used from Python but only so far, since only small subsets can be integrated seamlessly). As an example let’s use the data generated by an aerial-based LIDAR for the detection of power lines. Power lines are often clearly visible in point cloud visualization. However, mapping the points that belong to a power line requires a lot of manual efforts. On the other hand, simple geometrical consideration may provide us with means to greatly simplify or even automate such processing. The power line on the picture is actually a collection of points which form certain geometrical patterns. To simplify further categorization, I decided to check how we can form clusters out of these points. I will use NumPy, Sklearn, Laspy and SciPy libraries for the purpose of cluster formation and matplotlib for visualization. import laspyimport scipyimport numpy as npimport matplotlib.pyplot as pltfrom sklearn.cluster import DBSCANfrom sklearn import metricsfrom sklearn import preprocessingfrom mpl_toolkits.mplot3d import Axes3Dfrom matplotlib import path Laspy is great for handling point cloud data in Python. We read point cloud data from a las file and check the shape of the actual dataset. # Open a file in read mode:inFile = laspy.file.File(“./LAS/simple.las”)# Grab a numpy dataset of our clustering dimensions:dataset = np.vstack([inFile.x, inFile.y, inFile.z]).transpose()dataset.shape (5942479, 3) — our point cloud consists of 5942479 points. It is not enough if you want to get to small details. But the number is too big if you try to convert this DataFrame into a three-dimensional NumPy array, as in this case, we will get a huge 59424793 = 2.09*1020 array. It will use an enormous amount of RAM for the storage of really sparse data. The obvious thing to do is to use a NumPy sparse array. But as a matter of fact, a sparse array works great for 2D but fails with 3D data. Matrix manipulation functions are not fully compatible with sparse 3D matrices. We have to stick to working with a DataFrame instead of a NumPy array due to memory requirements. We need to find a method to eliminate those points that are not power lines. Power lines are placed high above the ground for safety reasons and to ensure their optimal performance. But for the rugged terrain, we have to take into account that some ground points can be higher than power lines in different parts of the image due to the ground incline. To avoid this let’s divide our point cloud to small vertical parts. %%timedef frange(start, stop, step): i = start while i < stop: yield i i += step#ground points grid filtern = 100 #grid stepdataset_Z_filtered = dataset[[0]]zfiltered = (dataset[:, 2].max() — dataset[:, 2].min())/10 #setting height filtered from groundprint(‘zfiltered =’, zfiltered)xstep = (dataset[:, 0].max() — dataset[:, 0].min())/nystep = (dataset[:, 1].max() — dataset[:, 1].min())/nfor x in frange (dataset[:, 0].min(), dataset[:, 0].max(), xstep): for y in frange (dataset[:, 1].min(), dataset[:, 1].max(), ystep): datasetfiltered = dataset[(dataset[:,0] > x) &(dataset[:, 0] < x+xstep) &(dataset[:, 1] > y) &(dataset[:, 1] < y+ystep)] if datasetfiltered.shape[0] > 0: datasetfiltered = datasetfiltered[datasetfiltered[:, 2] >(datasetfiltered[:, 2].min()+ zfiltered)] if datasetfiltered.shape[0] > 0: dataset_Z_filtered = np.concatenate((dataset_Z_filtered, datasetfiltered))print(‘dataset_Z_filtered shape’, dataset_Z_filtered.shape) With the help of this simple approach, we can greatly reduce the number of points in the cloud in no time even using moderate computing power. In our case, it was the reduction of the number of points by an order of magnitude in 3 minutes — not bad for a few lines of code, given that we made no real efforts for any optimization. dataset_Z_filtered shape (169862, 3)CPU times: user 3min 16s, sys: 7.14 ms, total: 3min 16sWall time: 3min 16s Now we’ll be using a much smaller filtered dataset. Let’s explore our data: print(“Examining Point Format: “)pointformat = inFile.point_formatfor spec in inFile.point_format:print(spec.name)Examining Point Format:XYZintensityflag_byteraw_classificationscan_angle_rankuser_datapt_src_idgps_time During my experiments, I try to use the 4D representation of data (X, Y, Z and intensity) but the results do not improve over 3D (X, Y, Z) so let’s stick to the latter subset of data. print(‘Z range =’, dataset[:, 2].max() — dataset[:, 2].min())print(‘Z max =’, dataset[:, 2].max(), ‘Z min =’, dataset[:, 2].min())print(‘Y range =’, dataset[:, 1].max() — dataset[:, 1].min())print(‘Y max =’, dataset[:, 1].max(), ‘Y min =’, dataset[:, 1].min())print(‘X range =’, dataset[:, 0].max() — dataset[:, 0].min())print(‘X max =’, dataset[:, 0].max(), ‘X min =’, dataset[:, 0].min())Z range = 149.81Z max = 181.78999908447264 Z min = 31.979999084472652Y range = 622.9700000002049Y max = 2576396.509974365 Y min = 2575773.539974365X range = 556.4400000000605X max = 711882.7199987792 X min = 711326.2799987792 As you can see, the values are in different ranges. For better results, we should normalize the dataset. dataset = preprocessing.normalize(dataset) Now we are ready to process our data. Our power lines are actually spatial clusters of points so it is natural to try a clustering algorithm. After a short investigation, I found that DBSCAN provided by the Sklearn library works best out-of-the-box. clustering = DBSCAN(eps=2, min_samples=5, leaf_size=30).fit(dataset) Now let’s visualize our results. core_samples_mask = np.zeros_like(clustering.labels_, dtype=bool)core_samples_mask[clustering.core_sample_indices_] = Truelabels = clustering.labels_# Number of clusters in labels, ignoring noise if present.n_clusters_ = len(set(labels)) — (1 if -1 in labels else 0)n_noise_ = list(labels).count(-1)print(‘Estimated number of clusters: %d’ % n_clusters_)print(‘Estimated number of noise points: %d’ % n_noise_)Estimated number of clusters: 501Estimated number of noise points: 1065 Most of our points were grouped into clusters. Let’s see what it looks like in practice: # Black removed and is used for noise instead.fig = plt.figure(figsize=[100, 50])ax = fig.add_subplot(111, projection=’3d’)unique_labels = set(labels)colors = [plt.cm.Spectral(each) for each in np.linspace(0, 1, len(unique_labels))]for k, col in zip(unique_labels, colors): if k == -1: # Black used for noise. col = [0, 0, 0, 1] class_member_mask = (labels == k) xyz = dataset[class_member_mask & core_samples_mask] ax.scatter(xyz[:, 0], xyz[:, 1], xyz[:, 2], c=col, marker=”.”)plt.title(‘Estimated number of cluster: %d’ % n_clusters_)plt.show() It is clear now that simple geometrical consideration and a pretty standard clustering method help us to simplify the point categorization using moderate computing resources. Each cluster of points can be categorized separately if needed. Our experiment showed that a combination of geometrical consideration and standard Python libraries can result in a significant reduction of efforts needed to categorize raw point cloud data for further usage. I want to thank my colleagues Andy Bosyi, Mykola Kozlenko, Volodymyr Sendetskyi for their discussions, cooperation, and helpful tips as well as the entire MindCraft.ai team for their constant support.
[ { "code": null, "e": 995, "s": 172, "text": "In recent years, there was great progress in the development of LIDAR detectors that resulted in huge amounts of raw data. LIDARs are now more accurate and provide a much higher resolution than even 10 years ago. Aerial-based LIDARs have become an efficient method for receiving information about the environment. Nevertheless, the data you get is in fact only a collection of sparse points that may provide some nice visualization but require extensive processing when it comes to more practical purposes. Unfortunately, as of now, the progress of computer vision mostly concerns structured two-dimensional data (photo, video). The current methods do not generalize to multidimensional sparse data like Point Cloud that we receive after a basic LIDAR data pre-processing. Extensive research is being done in the field. We" }, { "code": null, "e": 1695, "s": 995, "text": "should particularly mention PCL — a graf of libraries developed by a great international community to provide instruments for both 2D and 3D data for a wide variety of applications. Unfortunately, at the moment it is not an easy task to apply the library to some solution of interest. It often means that you have to dive into the library too deep. It makes sense for production-grade products that need high scalability. But it may be too costly for a PoC development. Therefore, I decided to try what can be done with point cloud data using a simple approach and pretty standard Python libraries (PCL can be used from Python but only so far, since only small subsets can be integrated seamlessly)." }, { "code": null, "e": 2087, "s": 1695, "text": "As an example let’s use the data generated by an aerial-based LIDAR for the detection of power lines. Power lines are often clearly visible in point cloud visualization. However, mapping the points that belong to a power line requires a lot of manual efforts. On the other hand, simple geometrical consideration may provide us with means to greatly simplify or even automate such processing." }, { "code": null, "e": 2294, "s": 2087, "text": "The power line on the picture is actually a collection of points which form certain geometrical patterns. To simplify further categorization, I decided to check how we can form clusters out of these points." }, { "code": null, "e": 2418, "s": 2294, "text": "I will use NumPy, Sklearn, Laspy and SciPy libraries for the purpose of cluster formation and matplotlib for visualization." }, { "code": null, "e": 2652, "s": 2418, "text": "import laspyimport scipyimport numpy as npimport matplotlib.pyplot as pltfrom sklearn.cluster import DBSCANfrom sklearn import metricsfrom sklearn import preprocessingfrom mpl_toolkits.mplot3d import Axes3Dfrom matplotlib import path" }, { "code": null, "e": 2792, "s": 2652, "text": "Laspy is great for handling point cloud data in Python. We read point cloud data from a las file and check the shape of the actual dataset." }, { "code": null, "e": 2992, "s": 2792, "text": "# Open a file in read mode:inFile = laspy.file.File(“./LAS/simple.las”)# Grab a numpy dataset of our clustering dimensions:dataset = np.vstack([inFile.x, inFile.y, inFile.z]).transpose()dataset.shape" }, { "code": null, "e": 3664, "s": 2992, "text": "(5942479, 3) — our point cloud consists of 5942479 points. It is not enough if you want to get to small details. But the number is too big if you try to convert this DataFrame into a three-dimensional NumPy array, as in this case, we will get a huge 59424793 = 2.09*1020 array. It will use an enormous amount of RAM for the storage of really sparse data. The obvious thing to do is to use a NumPy sparse array. But as a matter of fact, a sparse array works great for 2D but fails with 3D data. Matrix manipulation functions are not fully compatible with sparse 3D matrices. We have to stick to working with a DataFrame instead of a NumPy array due to memory requirements." }, { "code": null, "e": 4085, "s": 3664, "text": "We need to find a method to eliminate those points that are not power lines. Power lines are placed high above the ground for safety reasons and to ensure their optimal performance. But for the rugged terrain, we have to take into account that some ground points can be higher than power lines in different parts of the image due to the ground incline. To avoid this let’s divide our point cloud to small vertical parts." }, { "code": null, "e": 5211, "s": 4085, "text": "%%timedef frange(start, stop, step): i = start while i < stop: yield i i += step#ground points grid filtern = 100 #grid stepdataset_Z_filtered = dataset[[0]]zfiltered = (dataset[:, 2].max() — dataset[:, 2].min())/10 #setting height filtered from groundprint(‘zfiltered =’, zfiltered)xstep = (dataset[:, 0].max() — dataset[:, 0].min())/nystep = (dataset[:, 1].max() — dataset[:, 1].min())/nfor x in frange (dataset[:, 0].min(), dataset[:, 0].max(), xstep): for y in frange (dataset[:, 1].min(), dataset[:, 1].max(), ystep): datasetfiltered = dataset[(dataset[:,0] > x) &(dataset[:, 0] < x+xstep) &(dataset[:, 1] > y) &(dataset[:, 1] < y+ystep)] if datasetfiltered.shape[0] > 0: datasetfiltered = datasetfiltered[datasetfiltered[:, 2] >(datasetfiltered[:, 2].min()+ zfiltered)] if datasetfiltered.shape[0] > 0: dataset_Z_filtered = np.concatenate((dataset_Z_filtered, datasetfiltered))print(‘dataset_Z_filtered shape’, dataset_Z_filtered.shape)" }, { "code": null, "e": 5542, "s": 5211, "text": "With the help of this simple approach, we can greatly reduce the number of points in the cloud in no time even using moderate computing power. In our case, it was the reduction of the number of points by an order of magnitude in 3 minutes — not bad for a few lines of code, given that we made no real efforts for any optimization." }, { "code": null, "e": 5653, "s": 5542, "text": "dataset_Z_filtered shape (169862, 3)CPU times: user 3min 16s, sys: 7.14 ms, total: 3min 16sWall time: 3min 16s" }, { "code": null, "e": 5705, "s": 5653, "text": "Now we’ll be using a much smaller filtered dataset." }, { "code": null, "e": 5729, "s": 5705, "text": "Let’s explore our data:" }, { "code": null, "e": 5947, "s": 5729, "text": "print(“Examining Point Format: “)pointformat = inFile.point_formatfor spec in inFile.point_format:print(spec.name)Examining Point Format:XYZintensityflag_byteraw_classificationscan_angle_rankuser_datapt_src_idgps_time" }, { "code": null, "e": 6131, "s": 5947, "text": "During my experiments, I try to use the 4D representation of data (X, Y, Z and intensity) but the results do not improve over 3D (X, Y, Z) so let’s stick to the latter subset of data." }, { "code": null, "e": 6747, "s": 6131, "text": "print(‘Z range =’, dataset[:, 2].max() — dataset[:, 2].min())print(‘Z max =’, dataset[:, 2].max(), ‘Z min =’, dataset[:, 2].min())print(‘Y range =’, dataset[:, 1].max() — dataset[:, 1].min())print(‘Y max =’, dataset[:, 1].max(), ‘Y min =’, dataset[:, 1].min())print(‘X range =’, dataset[:, 0].max() — dataset[:, 0].min())print(‘X max =’, dataset[:, 0].max(), ‘X min =’, dataset[:, 0].min())Z range = 149.81Z max = 181.78999908447264 Z min = 31.979999084472652Y range = 622.9700000002049Y max = 2576396.509974365 Y min = 2575773.539974365X range = 556.4400000000605X max = 711882.7199987792 X min = 711326.2799987792" }, { "code": null, "e": 6852, "s": 6747, "text": "As you can see, the values are in different ranges. For better results, we should normalize the dataset." }, { "code": null, "e": 6895, "s": 6852, "text": "dataset = preprocessing.normalize(dataset)" }, { "code": null, "e": 7145, "s": 6895, "text": "Now we are ready to process our data. Our power lines are actually spatial clusters of points so it is natural to try a clustering algorithm. After a short investigation, I found that DBSCAN provided by the Sklearn library works best out-of-the-box." }, { "code": null, "e": 7214, "s": 7145, "text": "clustering = DBSCAN(eps=2, min_samples=5, leaf_size=30).fit(dataset)" }, { "code": null, "e": 7247, "s": 7214, "text": "Now let’s visualize our results." }, { "code": null, "e": 7729, "s": 7247, "text": "core_samples_mask = np.zeros_like(clustering.labels_, dtype=bool)core_samples_mask[clustering.core_sample_indices_] = Truelabels = clustering.labels_# Number of clusters in labels, ignoring noise if present.n_clusters_ = len(set(labels)) — (1 if -1 in labels else 0)n_noise_ = list(labels).count(-1)print(‘Estimated number of clusters: %d’ % n_clusters_)print(‘Estimated number of noise points: %d’ % n_noise_)Estimated number of clusters: 501Estimated number of noise points: 1065" }, { "code": null, "e": 7818, "s": 7729, "text": "Most of our points were grouped into clusters. Let’s see what it looks like in practice:" }, { "code": null, "e": 8376, "s": 7818, "text": "# Black removed and is used for noise instead.fig = plt.figure(figsize=[100, 50])ax = fig.add_subplot(111, projection=’3d’)unique_labels = set(labels)colors = [plt.cm.Spectral(each) for each in np.linspace(0, 1, len(unique_labels))]for k, col in zip(unique_labels, colors): if k == -1: # Black used for noise. col = [0, 0, 0, 1] class_member_mask = (labels == k) xyz = dataset[class_member_mask & core_samples_mask] ax.scatter(xyz[:, 0], xyz[:, 1], xyz[:, 2], c=col, marker=”.”)plt.title(‘Estimated number of cluster: %d’ % n_clusters_)plt.show()" }, { "code": null, "e": 8551, "s": 8376, "text": "It is clear now that simple geometrical consideration and a pretty standard clustering method help us to simplify the point categorization using moderate computing resources." }, { "code": null, "e": 8615, "s": 8551, "text": "Each cluster of points can be categorized separately if needed." }, { "code": null, "e": 8825, "s": 8615, "text": "Our experiment showed that a combination of geometrical consideration and standard Python libraries can result in a significant reduction of efforts needed to categorize raw point cloud data for further usage." } ]
How to show the title for the diagram of Seaborn pairplot() or PridGrid()? (Matplotlib)
To show the title for the diagram for Seaborn pairplot(), we can use pp.fig.suptitle() method. Set the figure size and adjust the padding between and around the subplots. Create a Pandas dataframe, i.e., a two-dimensional, size-mutable, potentially heterogeneous tabular data. Plot pairwise relationships in a dataset. Add a centered title to the figure. To display the figure, use show() method. import seaborn as sns import pandas as pd import numpy as np import matplotlib.pyplot as plt plt.rcParams["figure.figsize"] = [7.50, 3.50] plt.rcParams["figure.autolayout"] = True df = pd.DataFrame(np.random.random((5, 5)), columns=["a", "b", "c", "d", "e"]) pp = sns.pairplot(df, height=3.5) pp.fig.suptitle("My Pairplot") plt.show()
[ { "code": null, "e": 1157, "s": 1062, "text": "To show the title for the diagram for Seaborn pairplot(), we can use pp.fig.suptitle() method." }, { "code": null, "e": 1233, "s": 1157, "text": "Set the figure size and adjust the padding between and around the subplots." }, { "code": null, "e": 1339, "s": 1233, "text": "Create a Pandas dataframe, i.e., a two-dimensional, size-mutable, potentially heterogeneous tabular data." }, { "code": null, "e": 1381, "s": 1339, "text": "Plot pairwise relationships in a dataset." }, { "code": null, "e": 1417, "s": 1381, "text": "Add a centered title to the figure." }, { "code": null, "e": 1459, "s": 1417, "text": "To display the figure, use show() method." }, { "code": null, "e": 1816, "s": 1459, "text": "import seaborn as sns\nimport pandas as pd\nimport numpy as np\nimport matplotlib.pyplot as plt\n\nplt.rcParams[\"figure.figsize\"] = [7.50, 3.50]\nplt.rcParams[\"figure.autolayout\"] = True\n\ndf = pd.DataFrame(np.random.random((5, 5)),\n columns=[\"a\", \"b\", \"c\", \"d\", \"e\"])\n\npp = sns.pairplot(df, height=3.5)\npp.fig.suptitle(\"My Pairplot\")\n\nplt.show()" } ]
Complete Guide on Model Deployment with Flask and Heroku | by Tarek Ghanoum | Towards Data Science
I felt tears of joy running down my cheeks when I deployed my first Machine Learning model, and when I looked out the window, I saw a rainbow in the far distance. I took it as a sign that I will do great things in this world. That’s at least how I imagined it would be. In reality, I spent two days dealing with every type of error that Heroku could throw at me. When I finally deployed my model, I immediately shut the computer, drank my pre-workout, and hit the gym. This article aims to show you how to maneuver correctly when working with model deployment while showing you what to be aware of along the way. The final product can be seen here, while a more advanced deployment of the same model can be seen here (you might need some patience to visit the web apps since Heroku puts apps ‘to sleep’ after a period of inactivity — the app will ‘wake up’ with a delayed response of some seconds). The article is split into three parts which are: Building a Machine Learning modelSetting up a Flask web applicationDeployment on Heroku Building a Machine Learning model Setting up a Flask web application Deployment on Heroku The first step on our journey is to train a Machine Learning (ML) model, but given that my main focus is deployment, I will not put much effort into this part of the article. I will build an XGBoost model based on data from a bike-sharing scheme. The model will predict the number of bikes rented a given day based on three features; temperature, humidity, and windspeed. The focus at this stage is the methodology and not the model performance, so whether the model is XGBoost, RF, LG, or any other model is not important. The code below is all you need to train and save your model. Where to store the saved model will become more evident as we move along. At this stage, you should create an empty directory which I call ‘MyApp’, and store your model in it. I will be using Visual Studio Code (VSCode) to demonstrate the process, but you can use other methods. Contrary to a static website, where a user only reads the page content, we want the user to interact with our webpage. Websites with functionality and interactive element are referred to as web applications. In our case, a user will be met by three input fields, and by submitting some data, we want to give the user a prediction. Before we can do that, we need to understand that a browser interacts with other web pages by sending requests. A typical browser will send a GET request following a so-called HTTP protocol to visit a page and a POST request to send data through the web page. You will hopefully GET it along the way (pun intended)! As python programmers, we would usually have to write a bunch of code to handle user requests. Instead of writing repetitive code to handle requests, a dude (named Armin Ronacher) just put it in a library, as a joke, and called it flask. Flask is a web server framework because it requires our code to be organized in a certain way. Start by adding two folders called ‘Models’ and ‘Templates’ in your ‘MyApp’ directory. We will not be using the ‘Static’ folder for now, but feel free to add any optional CSS code. You should create a python file on the same root level as the folders and use the same naming convention as me ‘app.py’. Afterward, create an HTML file called index and place it in the templates directory. No worries that the app.py and index.html files are empty; focus on the framework at this stage. Your directory should look similar to the image below. Notice that I put our ML model in the model's folder. Before going through the files step-by-step, I will need you to create a virtual environment. Given that flask is simply a third-party library, we can easily install flask using pip (pip install Flask) and run our web application, but a problem occurs when the web application is dependent on specific versions of python and other third-party libraries. Imagine that your web application works perfectly, but all of a sudden, an update to a third-party library comes along the way and changes the name of certain functions. This will make your program stop functioning. To get around this problem, we can use a so-called virtual environment (virtualenv). Think of a virtual environment as a folder that is unaware of other libraries installed on your computer. Only libraries installed in the folder can be accessed. To create a virtual environment, we will need you to install virtualenv on your current Python installation. In other words, open a terminal (or command) line and type: pip install virtualenv To check whether you have it installed in your system, type the following command: virtualenv --version It is also possible to use pyvenv instead of virtualenv, but you will have to find another guide. Once virtualenv is installed, you can then create a virtual environment. The virtual environment files should be generated inside the ‘MyApp’ directory. You can either change your current directory using the command-line interface (using ls and cd) or right-click on your ‘MyApp’ folder and choose ‘New Terminal at folder’ (if you don't have that option — no worries, buy a Mac for 10.000$ or whatever they cost at the moment). Type the following command, use only one of the commands depending on whether you’re using Windows or Mac: python3 -m venv virtual (Mac)py -3 -m venv virtual (Windows) By doing this, you just used Python and the venv library to create a folder named ‘virtual’ with all the necessary virtual environment files. We will now have to activate the virtual environment by typing: . virtual/bin/activate (Mac)virtual\Scripts\activate (Windows) You can always do the opposite by simply typing deactivate. If all went well, you should see something similar to this in your command-line interface: (virtual) <user name> myapp % You can explore the new ‘virtual’ folder by opening and looking inside the ‘bin’ folder (or ‘Scripts’ on Windows). You should see pip and python in the folder pre-installed. Any new library installed will be found in the ‘bin’ folder. Now we can finally download the flask library: pip install Flask You should be able to easily locate flask in virtual/bin/ on Mac or virtual\Scripts\ on windows: You should find the nearest mirror at this stage and repeat the words: I can do anything if I set my mind to it. Let’s open the ‘app.py’ file and start inserting some code. The app file is the core of your web application which will run on Heroku. It will listen for user requests on specific ports and respond with specific functions depending on the type of request. The application can be separated into three parts. The first consists of importing libraries and initializing the flask app. We use the Flask(__name__) to tell flask where our app is located. Flask will locate templates and static files relative to the location of our app. from flask import Flask, render_template, requestimport pickleimport pandas as pd# Initialise the Flask appapp = Flask(__name__) Now we import our saved model using pickle from the /models directory and save it as ‘model’: # Use pickle to load in the pre-trained modelfilename = "models/model.sav"model = pickle.load(open(filename, "rb")) Our web application will only have a single page, which is referred to as the main or default page. The ‘/’ route is the home URL. This should, by default, point to the index.html file, i.e., the main page. We want to trigger a specific function when a user visits the main page. For that, I have created a function called main which will respond to user requests depending on whether the request is a GET or POST. A GET request is sent by the user when the purpose is to read or visit our main page. In this situation, I simply want to display the content of our index.html file, which we will create next. To do that, I use the render_template function which purpose is to look for a file in the templates directory and display its content. A POST request is sent by the user when information is being sent back to the webserver. We will allow the user to insert a specific temperature, humidity, and windspeed. I will retrieve this information from the index.html file by using the request.form.get function. I have given the input fields a specific name, so the functions know where to look. I then take the data and create a DataFrame from it using pandas and then feed the data to our ML model and store the result in a prediction variable before sending it back to the index.html file to display the result. Notice that the default app.route is configured to receive GET requests, so I added the methods=[“GET”, “POST”] in order to handle POST requests. # Set up the main route@app.route('/', methods=["GET", "POST"])def main(): if request.method == "POST": # Extract the input from the form temperature = request.form.get("temperature") humidity = request.form.get("humidity") windspeed = request.form.get("windspeed") # Create DataFrame based on input input_variables = pd.DataFrame([[temperature, humidity, windspeed]], columns=['temperature', 'humidity', 'windspeed'], dtype=float, index=['input']) # Get the model's prediction # Given that the prediction is stored in an array we simply extract by indexing prediction = model.predict(input_variables)[0] # We now pass on the input from the from and the prediction to the index page return render_template("index.html", original_input {'Temperature':temperature, 'Humidity':humidity, 'Windspeed':windspeed}, result=prediction) # If the request method is GET return render_template("index.html") The complete code is displayed below: Now we will create the default page, which the user will be met by. Let’s break the index.html code into three parts, as I did in the previous walk-through. Although, I would recommend watching a simple HTML tutorial video if you have never read or written HTML code. The first part of my index file simply consists of voluntary CSS code. As an alternative, I could have placed it in a stylesheet named ‘styles.css’ and store it in the static directory. I do this in the more advanced deployment (GitHub). <head> <!-- CSS code --> <style> form { margin: auto; width: 35%; } .result { margin: auto; width: 35%; border: 1px solid #ccc; } </style> <title>Bike Usage Model</title></head> The second part consists of a form with three input fields. Notice the ‘required’ attribute, which assures input from the user. The name attribute is used as a reference in the app.py file when I used the request.form.get function to get the data. <!-- Use the action attribute to call the 'main' function --><form action="{{ url_for('main') }}" method="POST"><fieldset> <legend>Input values:</legend> Temperature: <input name="temperature" type="number" required> <br> <br> Humidity: <input name="humidity" type="number" required> <br> <br> Windspeed: <input name="windspeed" type="number" required> <br> <br> <input type="submit"></fieldset></form> The above form, with the given CSS, gives us the following input fields and submit button: You might have noticed the {{ }} brackets above. Whenever you see these, you should immediately think: that dude is using Jinja. Flask supports Jinja, a templating language, which uses the {% %} and {{}} syntax to include placeholder blocks or other chunks of code. In this case, I wrote “{{ url_for(‘main’) }}” to trigger the ‘main’ function in the app.py file. Next up, I use an if condition and a for loop to display the prediction. The block is only showed or created if the condition is true. Remember that we stored the user input in a dictionary ‘original_input’ in the app.py file. Therefore, I iterate through the dictionary to print the user input, and last but not least, I display the prediction. <!-- Our 'result' is false until a prediction has been made -->{% if result %} <!-- Loop through dictionary and print key:value pair --> {% for variable in original_input %} <b>{{ variable }}:</b> {{ original_input[variable] }} {% endfor %} <br> <!-- Print prediction --> <br> Predicted number of bikes in use: <p style="font-size:50px">{{ result }}</p>{% endif %} The complete code is displayed below: Let’s celebrate your work so far by running our flask web application. You will need to install all libraries in your virtual environment (use either pip or conda to install pandas, xgboost, scikit-learn, and pickle-mixin). Afterward type: flask run This will run your application on a local address like http://127.0.0.1:5000/. By visiting the URL, you should be met by the index.html file. You can stop the server by typing ctrl+c. Notice that the command triggers the creation of a ‘__pycache__’ file. It’s the compiled version of our app.py. In order to make the application available for others, we still need a couple of minor steps. Let’s start by signing you up for a free account at GIT and Heroku. In order to interact with the two, we need to install GIT and the Heroku command-line interface known as Heroku-CLI. If you are using VSCode, then I would recommend installing the Heroku and Heroku-CLI extensions. Although flask is wonderful, it’s mainly used for local development. It isn’t designed to handle the requests that a normal web server receives. In order to handle a larger amount of requests, we need to install the gunicorn python library. pip install gunicorn Having installed gunicorn, we now need to tell Heroku to use it. We do that by creating a file called procfile without file extension (for example, Procfile.txt is not valid.). The file will specify which commands to execute on startup. Enter this line inside the empty Procfile file: web: gunicorn app:app The first ‘app’ represents the name of the python file that runs your application or the name of the module it is in (i.e., if you had an application called run.py, then it would be run:app). The second ‘app’ represents your app name (i.e. app = Flask(__name__)). Heroku needs to know which libraries to install to run your application. We can automate this process by running: pip freeze > requirements.txt This will generate a txt file called requirements.txt with the libraries used in your application. Although brilliant, it does not include all the necessary packages. The list below shows the content of my requirements file (notice that I have included scikit-learn since XGBClassifier object directly interacts with scikit-learn API): click==8.0.1Flask==2.0.1gunicorn==20.1.0itsdangerous==2.0.1Jinja2==3.0.1MarkupSafe==2.0.1Werkzeug==2.0.1pandasxgboostscikit-learnpickle-mixin I did not add specific versions of all my libraries but feel free to do that. Although not necessary, you can add a runtime.txt file if you wish to specify a specific python version. You can check which python version you're running by typing: python -V My runtime.txt file has the following: python-3.9.6 This is the final stage before deployment, and the MyApp directory should look similar to this: If all went well, you should start interacting with your Heroku account through the command line. Open your command line while you are inside the project folder and type: heroku login Use the email address and password used when creating your Heroku account. The command will open a browser window, but if you prefer to stay in the command line, just type: heroku login -i An example of a successful login: ########################################## A login might not be successful if you are in the wrong environment. In this scenario, the following command might be useful: conda deactivate ########################################## Before using the git commands to send our files to Heroku, you need to tell git who you are. This is important because every Git commit uses this information. To do that, type this in the command line: git config --global user.name "John Doe" Press enter and then type: git config --global user.email johndoe@example.com Make sure to replace your email address and your name appropriately in those lines keeping the double-quotes. You need to do this only once if you pass the — global option. Create a local git repository by typing: git init Add all your local files to the online repository by typing: git add . Make sure to include the dot after add. The dot means you are adding the entire directory to the repository. Commit your files with: git commit -m "First commit" The next steps consist of creating an empty app on Heroku and sending our local files to that app. And we will be sending the files using git. Create an empty Heroku app: heroku create <app-name-you-choose> Once the app has been created, you can enter your Heroku account to get an overview: The final steps consist of taking all our files, pushing them to Heroku, and then activating the app: git push heroku master Activate the app and set the number of dynos (anything more than one will cost): heroku ps:scale web=1 If all went well, then you should be able to access your app at: <app-name-you-choose>.herokuapp.com You can open it by simply following the URL above or typing: heroku open It might take some time to function, so have patience. If all went well, you should have an app running on the web. You should be proud of yourself. If you feel comfortable or want to see a different variation of the deployment, I can recommend visiting my advanced deployment. The files are made available on my git. The following commands have been great dealing with all the errors I saw along the way: heroku local Use this to open Heroku on a local server. Remember to install all required libraries. heroku logout It should be self-explanatory. heroku run 'ls -al' A copy of your dyno to have it list the directory contents. This is useful when you add more files and need to check that they have been added on Heroku. heroku logs --tail With this Heroku command, you can access information about your app’s performance once it’s up and running. heroku restart It should be self-explanatory. heroku apps:rename <newname> Rename your app. I hope you enjoyed this article as much as I have enjoyed writing it. Leave a comment if you have any difficulties understanding my code. The Data Science community has given me a lot, so I am always open to giving back. Feel free to connect with me on Linkedin and follow me on Medium to receive more articles.
[ { "code": null, "e": 397, "s": 171, "text": "I felt tears of joy running down my cheeks when I deployed my first Machine Learning model, and when I looked out the window, I saw a rainbow in the far distance. I took it as a sign that I will do great things in this world." }, { "code": null, "e": 640, "s": 397, "text": "That’s at least how I imagined it would be. In reality, I spent two days dealing with every type of error that Heroku could throw at me. When I finally deployed my model, I immediately shut the computer, drank my pre-workout, and hit the gym." }, { "code": null, "e": 1070, "s": 640, "text": "This article aims to show you how to maneuver correctly when working with model deployment while showing you what to be aware of along the way. The final product can be seen here, while a more advanced deployment of the same model can be seen here (you might need some patience to visit the web apps since Heroku puts apps ‘to sleep’ after a period of inactivity — the app will ‘wake up’ with a delayed response of some seconds)." }, { "code": null, "e": 1119, "s": 1070, "text": "The article is split into three parts which are:" }, { "code": null, "e": 1207, "s": 1119, "text": "Building a Machine Learning modelSetting up a Flask web applicationDeployment on Heroku" }, { "code": null, "e": 1241, "s": 1207, "text": "Building a Machine Learning model" }, { "code": null, "e": 1276, "s": 1241, "text": "Setting up a Flask web application" }, { "code": null, "e": 1297, "s": 1276, "text": "Deployment on Heroku" }, { "code": null, "e": 1472, "s": 1297, "text": "The first step on our journey is to train a Machine Learning (ML) model, but given that my main focus is deployment, I will not put much effort into this part of the article." }, { "code": null, "e": 1669, "s": 1472, "text": "I will build an XGBoost model based on data from a bike-sharing scheme. The model will predict the number of bikes rented a given day based on three features; temperature, humidity, and windspeed." }, { "code": null, "e": 1821, "s": 1669, "text": "The focus at this stage is the methodology and not the model performance, so whether the model is XGBoost, RF, LG, or any other model is not important." }, { "code": null, "e": 1956, "s": 1821, "text": "The code below is all you need to train and save your model. Where to store the saved model will become more evident as we move along." }, { "code": null, "e": 2161, "s": 1956, "text": "At this stage, you should create an empty directory which I call ‘MyApp’, and store your model in it. I will be using Visual Studio Code (VSCode) to demonstrate the process, but you can use other methods." }, { "code": null, "e": 2369, "s": 2161, "text": "Contrary to a static website, where a user only reads the page content, we want the user to interact with our webpage. Websites with functionality and interactive element are referred to as web applications." }, { "code": null, "e": 2808, "s": 2369, "text": "In our case, a user will be met by three input fields, and by submitting some data, we want to give the user a prediction. Before we can do that, we need to understand that a browser interacts with other web pages by sending requests. A typical browser will send a GET request following a so-called HTTP protocol to visit a page and a POST request to send data through the web page. You will hopefully GET it along the way (pun intended)!" }, { "code": null, "e": 3046, "s": 2808, "text": "As python programmers, we would usually have to write a bunch of code to handle user requests. Instead of writing repetitive code to handle requests, a dude (named Armin Ronacher) just put it in a library, as a joke, and called it flask." }, { "code": null, "e": 3625, "s": 3046, "text": "Flask is a web server framework because it requires our code to be organized in a certain way. Start by adding two folders called ‘Models’ and ‘Templates’ in your ‘MyApp’ directory. We will not be using the ‘Static’ folder for now, but feel free to add any optional CSS code. You should create a python file on the same root level as the folders and use the same naming convention as me ‘app.py’. Afterward, create an HTML file called index and place it in the templates directory. No worries that the app.py and index.html files are empty; focus on the framework at this stage." }, { "code": null, "e": 3734, "s": 3625, "text": "Your directory should look similar to the image below. Notice that I put our ML model in the model's folder." }, { "code": null, "e": 3828, "s": 3734, "text": "Before going through the files step-by-step, I will need you to create a virtual environment." }, { "code": null, "e": 4389, "s": 3828, "text": "Given that flask is simply a third-party library, we can easily install flask using pip (pip install Flask) and run our web application, but a problem occurs when the web application is dependent on specific versions of python and other third-party libraries. Imagine that your web application works perfectly, but all of a sudden, an update to a third-party library comes along the way and changes the name of certain functions. This will make your program stop functioning. To get around this problem, we can use a so-called virtual environment (virtualenv)." }, { "code": null, "e": 4551, "s": 4389, "text": "Think of a virtual environment as a folder that is unaware of other libraries installed on your computer. Only libraries installed in the folder can be accessed." }, { "code": null, "e": 4720, "s": 4551, "text": "To create a virtual environment, we will need you to install virtualenv on your current Python installation. In other words, open a terminal (or command) line and type:" }, { "code": null, "e": 4743, "s": 4720, "text": "pip install virtualenv" }, { "code": null, "e": 4826, "s": 4743, "text": "To check whether you have it installed in your system, type the following command:" }, { "code": null, "e": 4847, "s": 4826, "text": "virtualenv --version" }, { "code": null, "e": 4945, "s": 4847, "text": "It is also possible to use pyvenv instead of virtualenv, but you will have to find another guide." }, { "code": null, "e": 5373, "s": 4945, "text": "Once virtualenv is installed, you can then create a virtual environment. The virtual environment files should be generated inside the ‘MyApp’ directory. You can either change your current directory using the command-line interface (using ls and cd) or right-click on your ‘MyApp’ folder and choose ‘New Terminal at folder’ (if you don't have that option — no worries, buy a Mac for 10.000$ or whatever they cost at the moment)." }, { "code": null, "e": 5480, "s": 5373, "text": "Type the following command, use only one of the commands depending on whether you’re using Windows or Mac:" }, { "code": null, "e": 5541, "s": 5480, "text": "python3 -m venv virtual (Mac)py -3 -m venv virtual (Windows)" }, { "code": null, "e": 5683, "s": 5541, "text": "By doing this, you just used Python and the venv library to create a folder named ‘virtual’ with all the necessary virtual environment files." }, { "code": null, "e": 5747, "s": 5683, "text": "We will now have to activate the virtual environment by typing:" }, { "code": null, "e": 5810, "s": 5747, "text": ". virtual/bin/activate (Mac)virtual\\Scripts\\activate (Windows)" }, { "code": null, "e": 5961, "s": 5810, "text": "You can always do the opposite by simply typing deactivate. If all went well, you should see something similar to this in your command-line interface:" }, { "code": null, "e": 5991, "s": 5961, "text": "(virtual) <user name> myapp %" }, { "code": null, "e": 6226, "s": 5991, "text": "You can explore the new ‘virtual’ folder by opening and looking inside the ‘bin’ folder (or ‘Scripts’ on Windows). You should see pip and python in the folder pre-installed. Any new library installed will be found in the ‘bin’ folder." }, { "code": null, "e": 6273, "s": 6226, "text": "Now we can finally download the flask library:" }, { "code": null, "e": 6291, "s": 6273, "text": "pip install Flask" }, { "code": null, "e": 6388, "s": 6291, "text": "You should be able to easily locate flask in virtual/bin/ on Mac or virtual\\Scripts\\ on windows:" }, { "code": null, "e": 6501, "s": 6388, "text": "You should find the nearest mirror at this stage and repeat the words: I can do anything if I set my mind to it." }, { "code": null, "e": 6757, "s": 6501, "text": "Let’s open the ‘app.py’ file and start inserting some code. The app file is the core of your web application which will run on Heroku. It will listen for user requests on specific ports and respond with specific functions depending on the type of request." }, { "code": null, "e": 7031, "s": 6757, "text": "The application can be separated into three parts. The first consists of importing libraries and initializing the flask app. We use the Flask(__name__) to tell flask where our app is located. Flask will locate templates and static files relative to the location of our app." }, { "code": null, "e": 7160, "s": 7031, "text": "from flask import Flask, render_template, requestimport pickleimport pandas as pd# Initialise the Flask appapp = Flask(__name__)" }, { "code": null, "e": 7254, "s": 7160, "text": "Now we import our saved model using pickle from the /models directory and save it as ‘model’:" }, { "code": null, "e": 7370, "s": 7254, "text": "# Use pickle to load in the pre-trained modelfilename = \"models/model.sav\"model = pickle.load(open(filename, \"rb\"))" }, { "code": null, "e": 7577, "s": 7370, "text": "Our web application will only have a single page, which is referred to as the main or default page. The ‘/’ route is the home URL. This should, by default, point to the index.html file, i.e., the main page." }, { "code": null, "e": 7785, "s": 7577, "text": "We want to trigger a specific function when a user visits the main page. For that, I have created a function called main which will respond to user requests depending on whether the request is a GET or POST." }, { "code": null, "e": 8113, "s": 7785, "text": "A GET request is sent by the user when the purpose is to read or visit our main page. In this situation, I simply want to display the content of our index.html file, which we will create next. To do that, I use the render_template function which purpose is to look for a file in the templates directory and display its content." }, { "code": null, "e": 8685, "s": 8113, "text": "A POST request is sent by the user when information is being sent back to the webserver. We will allow the user to insert a specific temperature, humidity, and windspeed. I will retrieve this information from the index.html file by using the request.form.get function. I have given the input fields a specific name, so the functions know where to look. I then take the data and create a DataFrame from it using pandas and then feed the data to our ML model and store the result in a prediction variable before sending it back to the index.html file to display the result." }, { "code": null, "e": 8831, "s": 8685, "text": "Notice that the default app.route is configured to receive GET requests, so I added the methods=[“GET”, “POST”] in order to handle POST requests." }, { "code": null, "e": 9826, "s": 8831, "text": "# Set up the main route@app.route('/', methods=[\"GET\", \"POST\"])def main(): if request.method == \"POST\": # Extract the input from the form temperature = request.form.get(\"temperature\") humidity = request.form.get(\"humidity\") windspeed = request.form.get(\"windspeed\") # Create DataFrame based on input input_variables = pd.DataFrame([[temperature, humidity, windspeed]], columns=['temperature', 'humidity', 'windspeed'], dtype=float, index=['input']) # Get the model's prediction # Given that the prediction is stored in an array we simply extract by indexing prediction = model.predict(input_variables)[0] # We now pass on the input from the from and the prediction to the index page return render_template(\"index.html\", original_input {'Temperature':temperature, 'Humidity':humidity, 'Windspeed':windspeed}, result=prediction) # If the request method is GET return render_template(\"index.html\")" }, { "code": null, "e": 9864, "s": 9826, "text": "The complete code is displayed below:" }, { "code": null, "e": 10132, "s": 9864, "text": "Now we will create the default page, which the user will be met by. Let’s break the index.html code into three parts, as I did in the previous walk-through. Although, I would recommend watching a simple HTML tutorial video if you have never read or written HTML code." }, { "code": null, "e": 10370, "s": 10132, "text": "The first part of my index file simply consists of voluntary CSS code. As an alternative, I could have placed it in a stylesheet named ‘styles.css’ and store it in the static directory. I do this in the more advanced deployment (GitHub)." }, { "code": null, "e": 10632, "s": 10370, "text": "<head> <!-- CSS code --> <style> form { margin: auto; width: 35%; } .result { margin: auto; width: 35%; border: 1px solid #ccc; } </style> <title>Bike Usage Model</title></head>" }, { "code": null, "e": 10880, "s": 10632, "text": "The second part consists of a form with three input fields. Notice the ‘required’ attribute, which assures input from the user. The name attribute is used as a reference in the app.py file when I used the request.form.get function to get the data." }, { "code": null, "e": 11331, "s": 10880, "text": "<!-- Use the action attribute to call the 'main' function --><form action=\"{{ url_for('main') }}\" method=\"POST\"><fieldset> <legend>Input values:</legend> Temperature: <input name=\"temperature\" type=\"number\" required> <br> <br> Humidity: <input name=\"humidity\" type=\"number\" required> <br> <br> Windspeed: <input name=\"windspeed\" type=\"number\" required> <br> <br> <input type=\"submit\"></fieldset></form>" }, { "code": null, "e": 11422, "s": 11331, "text": "The above form, with the given CSS, gives us the following input fields and submit button:" }, { "code": null, "e": 11785, "s": 11422, "text": "You might have noticed the {{ }} brackets above. Whenever you see these, you should immediately think: that dude is using Jinja. Flask supports Jinja, a templating language, which uses the {% %} and {{}} syntax to include placeholder blocks or other chunks of code. In this case, I wrote “{{ url_for(‘main’) }}” to trigger the ‘main’ function in the app.py file." }, { "code": null, "e": 12131, "s": 11785, "text": "Next up, I use an if condition and a for loop to display the prediction. The block is only showed or created if the condition is true. Remember that we stored the user input in a dictionary ‘original_input’ in the app.py file. Therefore, I iterate through the dictionary to print the user input, and last but not least, I display the prediction." }, { "code": null, "e": 12532, "s": 12131, "text": "<!-- Our 'result' is false until a prediction has been made -->{% if result %} <!-- Loop through dictionary and print key:value pair --> {% for variable in original_input %} <b>{{ variable }}:</b> {{ original_input[variable] }} {% endfor %} <br> <!-- Print prediction --> <br> Predicted number of bikes in use: <p style=\"font-size:50px\">{{ result }}</p>{% endif %}" }, { "code": null, "e": 12570, "s": 12532, "text": "The complete code is displayed below:" }, { "code": null, "e": 12810, "s": 12570, "text": "Let’s celebrate your work so far by running our flask web application. You will need to install all libraries in your virtual environment (use either pip or conda to install pandas, xgboost, scikit-learn, and pickle-mixin). Afterward type:" }, { "code": null, "e": 12820, "s": 12810, "text": "flask run" }, { "code": null, "e": 13116, "s": 12820, "text": "This will run your application on a local address like http://127.0.0.1:5000/. By visiting the URL, you should be met by the index.html file. You can stop the server by typing ctrl+c. Notice that the command triggers the creation of a ‘__pycache__’ file. It’s the compiled version of our app.py." }, { "code": null, "e": 13492, "s": 13116, "text": "In order to make the application available for others, we still need a couple of minor steps. Let’s start by signing you up for a free account at GIT and Heroku. In order to interact with the two, we need to install GIT and the Heroku command-line interface known as Heroku-CLI. If you are using VSCode, then I would recommend installing the Heroku and Heroku-CLI extensions." }, { "code": null, "e": 13733, "s": 13492, "text": "Although flask is wonderful, it’s mainly used for local development. It isn’t designed to handle the requests that a normal web server receives. In order to handle a larger amount of requests, we need to install the gunicorn python library." }, { "code": null, "e": 13754, "s": 13733, "text": "pip install gunicorn" }, { "code": null, "e": 13991, "s": 13754, "text": "Having installed gunicorn, we now need to tell Heroku to use it. We do that by creating a file called procfile without file extension (for example, Procfile.txt is not valid.). The file will specify which commands to execute on startup." }, { "code": null, "e": 14039, "s": 13991, "text": "Enter this line inside the empty Procfile file:" }, { "code": null, "e": 14061, "s": 14039, "text": "web: gunicorn app:app" }, { "code": null, "e": 14253, "s": 14061, "text": "The first ‘app’ represents the name of the python file that runs your application or the name of the module it is in (i.e., if you had an application called run.py, then it would be run:app)." }, { "code": null, "e": 14325, "s": 14253, "text": "The second ‘app’ represents your app name (i.e. app = Flask(__name__))." }, { "code": null, "e": 14439, "s": 14325, "text": "Heroku needs to know which libraries to install to run your application. We can automate this process by running:" }, { "code": null, "e": 14469, "s": 14439, "text": "pip freeze > requirements.txt" }, { "code": null, "e": 14805, "s": 14469, "text": "This will generate a txt file called requirements.txt with the libraries used in your application. Although brilliant, it does not include all the necessary packages. The list below shows the content of my requirements file (notice that I have included scikit-learn since XGBClassifier object directly interacts with scikit-learn API):" }, { "code": null, "e": 14947, "s": 14805, "text": "click==8.0.1Flask==2.0.1gunicorn==20.1.0itsdangerous==2.0.1Jinja2==3.0.1MarkupSafe==2.0.1Werkzeug==2.0.1pandasxgboostscikit-learnpickle-mixin" }, { "code": null, "e": 15025, "s": 14947, "text": "I did not add specific versions of all my libraries but feel free to do that." }, { "code": null, "e": 15191, "s": 15025, "text": "Although not necessary, you can add a runtime.txt file if you wish to specify a specific python version. You can check which python version you're running by typing:" }, { "code": null, "e": 15201, "s": 15191, "text": "python -V" }, { "code": null, "e": 15240, "s": 15201, "text": "My runtime.txt file has the following:" }, { "code": null, "e": 15253, "s": 15240, "text": "python-3.9.6" }, { "code": null, "e": 15349, "s": 15253, "text": "This is the final stage before deployment, and the MyApp directory should look similar to this:" }, { "code": null, "e": 15520, "s": 15349, "text": "If all went well, you should start interacting with your Heroku account through the command line. Open your command line while you are inside the project folder and type:" }, { "code": null, "e": 15533, "s": 15520, "text": "heroku login" }, { "code": null, "e": 15706, "s": 15533, "text": "Use the email address and password used when creating your Heroku account. The command will open a browser window, but if you prefer to stay in the command line, just type:" }, { "code": null, "e": 15722, "s": 15706, "text": "heroku login -i" }, { "code": null, "e": 15756, "s": 15722, "text": "An example of a successful login:" }, { "code": null, "e": 15799, "s": 15756, "text": "##########################################" }, { "code": null, "e": 15942, "s": 15799, "text": "A login might not be successful if you are in the wrong environment. In this scenario, the following command might be useful: conda deactivate" }, { "code": null, "e": 15985, "s": 15942, "text": "##########################################" }, { "code": null, "e": 16144, "s": 15985, "text": "Before using the git commands to send our files to Heroku, you need to tell git who you are. This is important because every Git commit uses this information." }, { "code": null, "e": 16187, "s": 16144, "text": "To do that, type this in the command line:" }, { "code": null, "e": 16228, "s": 16187, "text": "git config --global user.name \"John Doe\"" }, { "code": null, "e": 16255, "s": 16228, "text": "Press enter and then type:" }, { "code": null, "e": 16306, "s": 16255, "text": "git config --global user.email johndoe@example.com" }, { "code": null, "e": 16479, "s": 16306, "text": "Make sure to replace your email address and your name appropriately in those lines keeping the double-quotes. You need to do this only once if you pass the — global option." }, { "code": null, "e": 16520, "s": 16479, "text": "Create a local git repository by typing:" }, { "code": null, "e": 16529, "s": 16520, "text": "git init" }, { "code": null, "e": 16590, "s": 16529, "text": "Add all your local files to the online repository by typing:" }, { "code": null, "e": 16600, "s": 16590, "text": "git add ." }, { "code": null, "e": 16709, "s": 16600, "text": "Make sure to include the dot after add. The dot means you are adding the entire directory to the repository." }, { "code": null, "e": 16733, "s": 16709, "text": "Commit your files with:" }, { "code": null, "e": 16762, "s": 16733, "text": "git commit -m \"First commit\"" }, { "code": null, "e": 16905, "s": 16762, "text": "The next steps consist of creating an empty app on Heroku and sending our local files to that app. And we will be sending the files using git." }, { "code": null, "e": 16933, "s": 16905, "text": "Create an empty Heroku app:" }, { "code": null, "e": 16969, "s": 16933, "text": "heroku create <app-name-you-choose>" }, { "code": null, "e": 17054, "s": 16969, "text": "Once the app has been created, you can enter your Heroku account to get an overview:" }, { "code": null, "e": 17156, "s": 17054, "text": "The final steps consist of taking all our files, pushing them to Heroku, and then activating the app:" }, { "code": null, "e": 17179, "s": 17156, "text": "git push heroku master" }, { "code": null, "e": 17260, "s": 17179, "text": "Activate the app and set the number of dynos (anything more than one will cost):" }, { "code": null, "e": 17282, "s": 17260, "text": "heroku ps:scale web=1" }, { "code": null, "e": 17347, "s": 17282, "text": "If all went well, then you should be able to access your app at:" }, { "code": null, "e": 17383, "s": 17347, "text": "<app-name-you-choose>.herokuapp.com" }, { "code": null, "e": 17444, "s": 17383, "text": "You can open it by simply following the URL above or typing:" }, { "code": null, "e": 17456, "s": 17444, "text": "heroku open" }, { "code": null, "e": 17605, "s": 17456, "text": "It might take some time to function, so have patience. If all went well, you should have an app running on the web. You should be proud of yourself." }, { "code": null, "e": 17774, "s": 17605, "text": "If you feel comfortable or want to see a different variation of the deployment, I can recommend visiting my advanced deployment. The files are made available on my git." }, { "code": null, "e": 17862, "s": 17774, "text": "The following commands have been great dealing with all the errors I saw along the way:" }, { "code": null, "e": 17962, "s": 17862, "text": "heroku local Use this to open Heroku on a local server. Remember to install all required libraries." }, { "code": null, "e": 18007, "s": 17962, "text": "heroku logout It should be self-explanatory." }, { "code": null, "e": 18181, "s": 18007, "text": "heroku run 'ls -al' A copy of your dyno to have it list the directory contents. This is useful when you add more files and need to check that they have been added on Heroku." }, { "code": null, "e": 18308, "s": 18181, "text": "heroku logs --tail With this Heroku command, you can access information about your app’s performance once it’s up and running." }, { "code": null, "e": 18354, "s": 18308, "text": "heroku restart It should be self-explanatory." }, { "code": null, "e": 18400, "s": 18354, "text": "heroku apps:rename <newname> Rename your app." }, { "code": null, "e": 18621, "s": 18400, "text": "I hope you enjoyed this article as much as I have enjoyed writing it. Leave a comment if you have any difficulties understanding my code. The Data Science community has given me a lot, so I am always open to giving back." } ]
Kotlin Syntax
In the previous chapter, we created a Kotlin file called Main.kt, and we used the following code to print "Hello World" to the screen: fun main() { println("Hello World") } The fun keyword is used to declare a function. A function is a block of code designed to perform a particular task. In the example above, it declares the main() function. The main() function is something you will see in every Kotlin program. This function is used to execute code. Any code inside the main() function's curly brackets {} will be executed. For example, the println() function is inside the main() function, meaning that this will be executed. The println() function is used to output/print text, and in our example it will output "Hello World". Good To Know: In Kotlin, code statements do not have to end with a semicolon (;) (which is often required for other programming languages, such as Java, C++, C#, etc.). Before Kotlin version 1.3, it was required to use the main() function with parameters, like: fun main(args : Array<String>). The example above had to be written like this to work: fun main(args : Array<String>) { println("Hello World") } Note: This is no longer required, and the program will run fine without it. However, it will not do any harm if you have been using it in the past, and will continue to use it. 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": 135, "s": 0, "text": "In the previous chapter, we created a Kotlin file called Main.kt, and we used the following code to print \"Hello World\" to the screen:" }, { "code": null, "e": 175, "s": 135, "text": "fun main() {\n println(\"Hello World\")\n}" }, { "code": null, "e": 346, "s": 175, "text": "The fun keyword is used to declare a function. A function is a block of code designed to perform a particular task. In the example above, it declares the main() function." }, { "code": null, "e": 531, "s": 346, "text": "The main() function is something you will \nsee in every Kotlin program. This function is used to execute code. Any code inside the main() function's curly brackets {} will be executed." }, { "code": null, "e": 736, "s": 531, "text": "For example, the println() function is inside the main() function, meaning that this will be executed. The println() function is used to output/print text, and in our example it will output \"Hello World\"." }, { "code": null, "e": 905, "s": 736, "text": "Good To Know: In Kotlin, code statements do not have to end with a semicolon (;) (which is often required for other programming languages, such as Java, C++, C#, etc.)." }, { "code": null, "e": 1086, "s": 905, "text": "Before Kotlin version 1.3, it was required to use the main() function with parameters, like: fun main(args : Array<String>). \nThe example above had to be written like this to work:" }, { "code": null, "e": 1146, "s": 1086, "text": "fun main(args : Array<String>) {\n println(\"Hello World\")\n}" }, { "code": null, "e": 1323, "s": 1146, "text": "Note: This is no longer required, and the program will run fine without it. However, it will not do any harm if you have been using it in the past, and will continue to use it." }, { "code": null, "e": 1356, "s": 1323, "text": "We just launchedW3Schools videos" }, { "code": null, "e": 1398, "s": 1356, "text": "Get certifiedby completinga course today!" }, { "code": null, "e": 1505, "s": 1398, "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": 1524, "s": 1505, "text": "help@w3schools.com" } ]
AutoML using H2o - GeeksforGeeks
18 Oct, 2021 Automated machine learning (AutoML) is the process of automating the end-to-end process of applying machine learning to real-world problems. AutoML automates most of the steps in an ML pipeline, with a minimum amount of human effort and without compromising on its performance. Automatic machine learning broadly includes the following steps: Data preparation and Ingestion: The real-world data can be raw data or just in any format. In this step, data needs to be converted into a format that can be processed easily. This also required to decide the data type of different columns in the dataset. We also required a clear knowledge about the task we need to perform on data (e.g classification, regression, etc.) Feature Engineering: This includes various steps that are required for cleaning the dataset such as dealing with NULL /missing values, selecting the most important features of the dataset, and removing the low-correlational features, dealing with the skewed dataset. Hyperparameter Optimization: To obtain the best results on any model, the AutoML need to carefully tune the hyperparameter values. Model Selection: H2O autoML trains with a large number of models in order to produce the best results. H2O AutoML also trains the data of different ensembles to get the best performance out of training data. H2O AutoML contains the cutting-edge and distributed implementation of many machine learning algorithms. These algorithms are available in Java, Python, Spark, Scala, and R. H2O also provide a web GUI that uses JSON to implement these algorithms. The models trained on H2O AutoML can be easily deployed on the Spark server, AWS, etc. The main advantage of H2O AutoML is that it automates the steps like basic data processing, model training and tuning, Ensemble and stacking of various models to provide the models with the best performance so that developers can focus on other steps like data collection, feature engineering and deployment of model. Functionalities of H2O AutoML H2O AutoML provides necessary data processing capabilities. These are also included in all of the H2O algorithms. Trains a Random grid of algorithms like GBMs, DNNs, GLMs, etc. using a carefully chosen hyper-parameter space. Individual models are tuned using cross-validation. Two Stacked Ensembles are trained. One ensemble contains all the models (optimized for model performance), and the other ensemble provides just the best performing model from each algorithm class/family (optimized for production use). Returns a sorted “Leaderboard” of all models. All models can be easily exported to production. Architecture: H2O AutoML uses H2O architecture. H2O architecture can be divided into different layers in which the top layer will be different APIs, and the bottom layer will be H2O JVM. H2O Software Stack H2O provides REST API clients for Python, R, Excel, Tableau, and Flow Web UI using socket connections. The bottom layer contains different components that will run on the H2O JVM process. An H2O cluster consists of one or more nodes. Each node is a single JVM process. Each JVM process is split into three layers: language, algorithms, and core infrastructure. The first layer in the bottom section is the language layer. The language layer consists of an expression evaluation engine for R and the Scala layer. The second layer is the algorithm layer. This layer contains an algorithms that are already provided in the H2O such as: XGBoost, GBM, Random Forest, K-Means etc. The third layer is the core infrastructure layer that deals with resource management such as Memory and CPU management. Implementation: In this code, we will be using California Housing Dataset which is easily available in colab. First, we need to import the necessary packages. Code: python3 # codeimport pandas as pdimport numpy as npimport matplotlib.pyplot as plt Now, we load the California Housing Dataset. This is already available in the sample data folder when we load the environment in colab. Code: python3 # codedf = pd.read_csv('sample_data / california_housing_train.csv') Let’s look at the dataset, we use the head function to list the first few rows of the dataset. Code: python3 # print first 5 rows of dataframe df.head() longitude latitude housing_median_age total_rooms total_bedrooms population households median_income median_house_value 0 -114.31 34.19 15.0 5612.0 1283.0 1015.0 472.0 1.4936 66900.0 1 -114.47 34.40 19.0 7650.0 1901.0 1129.0 463.0 1.8200 80100.0 2 -114.56 33.69 17.0 720.0 174.0 333.0 117.0 1.6509 85700.0 3 -114.57 33.64 14.0 1501.0 337.0 515.0 226.0 3.1917 73400.0 4 -114.57 33.57 20.0 1454.0 326.0 624.0 262.0 1.9250 65500.0 Now, let’s check for null values in the dataset. As we can see that there are no null values in the dataset. Code: python3 # calculate total null values in every columndf.isna().sum() longitude 0 latitude 0 housing_median_age 0 total_rooms 0 total_bedrooms 0 population 0 households 0 median_income 0 median_house_value 0 dtype: int64 Now we need to install the h2o, we can install it using pip. Note, if you are using the local environment for H2O, you need to install the Java Development Kit (JDK). After installing JDK and H2O, we will initialize it, if it works fine this will start an H2O instance on the localhost. There are many arguments which we can pass such as:nthreads: No of cores H2O server can use, by default it uses all cores of CPU.ip: IP address of the server where the H2O server will run. By default, it uses localhost.port: port on which the H2O server will run.max_mem_size: A character string specifying the maximum size, in bytes, of the memory allocation pool to H2O. This value must be a multiple of 1024 greater than 2MB. Append the letter m or M to indicate megabytes, or g or G to indicate gigabytes. Similarly, there is another parameter min_mem_size. For more details please look at H2O docs nthreads: No of cores H2O server can use, by default it uses all cores of CPU. ip: IP address of the server where the H2O server will run. By default, it uses localhost. port: port on which the H2O server will run. max_mem_size: A character string specifying the maximum size, in bytes, of the memory allocation pool to H2O. This value must be a multiple of 1024 greater than 2MB. Append the letter m or M to indicate megabytes, or g or G to indicate gigabytes. Similarly, there is another parameter min_mem_size. For more details please look at H2O docs Code: python3 # install and import H2o ! pip install h2oimport h2o# We will be using default parameter Here with H2O init methodh2o.init() Checking whether there is an H2O instance running at http://localhost:54321 ..... not found. Attempting to start a local H2O server... Java Version: openjdk version "11.0.7" 2020-04-14; OpenJDK Runtime Environment (build 11.0.7+10-post-Ubuntu-2ubuntu218.04); OpenJDK 64-Bit Server VM (build 11.0.7+10-post-Ubuntu-2ubuntu218.04, mixed mode, sharing) Starting server from /usr/local/lib/python3.6/dist-packages/h2o/backend/bin/h2o.jar Ice root: /tmp/tmpebz1_45i JVM stdout: /tmp/tmpebz1_45i/h2o_unknownUser_started_from_python.out JVM stderr: /tmp/tmpebz1_45i/h2o_unknownUser_started_from_python.err Server is running at http://127.0.0.1:54321 Connecting to H2O server at http://127.0.0.1:54321 ... successful. H2O_cluster_uptime: 03 secs H2O_cluster_timezone: Etc/UTC H2O_data_parsing_timezone: UTC H2O_cluster_version: 3.30.0.6 H2O_cluster_version_age: 13 days H2O_cluster_name: H2O_from_python_unknownUser_h4lj71 H2O_cluster_total_nodes: 1 H2O_cluster_free_memory: 3.180 Gb H2O_cluster_total_cores: 2 H2O_cluster_allowed_cores: 2 H2O_cluster_status: accepting new members, healthy H2O_connection_url: http://127.0.0.1:54321 H2O_connection_proxy: {"http": null, "https": null} H2O_internal_security: False H2O_API_Extensions: Amazon S3, XGBoost, Algos, AutoML, Core V3, TargetEncoder, Core V4 Python_version: 3.6.9 final The H2O instance can also be assessed from localhost: 54321, this instance provides a web GUI called FlowGUI. Now, we need to convert the train data frame into the H2O Dataframe. python3 # convert pandas DataFrame into H2O Frametrain_df = h2o.H2OFrame(df)# Describe the train h20Frametrain_df.describe() Parse progress: |?????????????????????????????????????????????????????????| 100% Rows:17000 Cols:9 longitude latitude housing_median_age total_rooms total_bedrooms population households median_income median_house_value type real real int int int int int real int mins -124.35 32.54 1.0 2.0 1.0 3.0 1.0 0.4999 14999.0 mean -119.5621082352941 35.62522470588239 28.589352941176436 2643.6644117647143 539.4108235294095 1429.573941176477 501.2219411764718 3.8835781000000016 207300.9123529415 maxs -114.31 41.95 52.0 37937.0 6445.0 35682.0 6082.0 15.0001 500001.0 sigma 2.0051664084260357 2.137339794657087 12.586936981660406 2179.9470714527765 421.4994515798648 1147.852959159527 384.52084085590155 1.9081565183791034 115983.76438720895 zeros 0 0 0 0 0 0 0 0 0 missing 0 0 0 0 0 0 0 0 0 0 -114.31 34.19 15.0 5612.0 1283.0 1015.0 472.0 1.4936 66900.0 1 -114.47 34.4 19.0 7650.0 1901.0 1129.0 463.0 1.82 80100.0 2 -114.56 33.69 17.0 720.0 174.0 333.0 117.0 1.6509 85700.0 3 -114.57 33.64 14.0 1501.0 337.0 515.0 226.0 3.1917 73400.0 4 -114.57 33.57 20.0 1454.0 326.0 624.0 262.0 1.925 65500.0 5 -114.58 33.63 29.0 1387.0 236.0 671.0 239.0 3.3438 74000.0 6 -114.58 33.61 25.0 2907.0 680.0 1841.0 633.0 2.6768 82400.0 7 -114.59 34.83 41.0 812.0 168.0 375.0 158.0 1.7083 48500.0 8 -114.59 33.61 34.0 4789.0 1175.0 3134.0 1056.0 2.1782 58400.0 9 -114.6 34.83 46.0 1497.0 309.0 787.0 271.0 2.1908 48100.0 Now, we load our test dataset into pandas DataFrame and convert it into the H2O Dataframe. Code: python3 # codetest = pd.read_csv('sample_data / california_housing_test.csv')test = h2o.H2OFrame(test)# selecting feature and label columns x = test.columnsy = 'median_house_value'# remove label classvariable from feature variablex.remove(y) Parse progress: |?????????????????????????????????????????????????????????| 100% Now, we run AutoML and start training. Code: python3 # import autoML from H2Ofrom h2o.automl import H2OAutoML# callh20automl functionaml = H2OAutoML(max_runtime_secs = 600, # exclude_algos =['DeepLearning'], seed = 1, # stopping_metric ='logloss', # sort_metric ='logloss', balance_classes = False, project_name ='Project 1')# train model and record time % timeaml.train(x = x, y = y, training_frame = train_df) AutoML progress: |????????????????????????????????????????????????????????| 100% CPU times: user 40 s, sys: 1.24 s, total: 41.2 s Wall time: 9min 39s In this step, we will look for the best performing model using the leaderboard and it will most probably be one of the two stacked ensemble models. python3 # View the H2O aml leaderboardlb = aml.leaderboard# Print all rows instead of 10 rowslb.head(rows = lb.nrows) model_id mean_residual_deviance rmse mse mae rmsle StackedEnsemble_AllModels_AutoML_20200714_173719 2.04045e+09 45171.3 2.04045e+09 29642.1 0.221447 StackedEnsemble_BestOfFamily_AutoML_20200714_173719 2.06576e+09 45450.6 2.06576e+09 29949.4 0.223522 GBM_3_AutoML_20200714_173719 2.15623e+09 46435.2 2.15623e+09 30763.8 0.227577 GBM_4_AutoML_20200714_173719 2.15913e+09 46466.4 2.15913e+09 30786.7 0.228627 XGBoost_grid__1_AutoML_20200714_173719_model_5 2.16562e+09 46536.2 2.16562e+09 31075.9 0.233288 GBM_2_AutoML_20200714_173719 2.17639e+09 46651.8 2.17639e+09 31014.8 0.229731 GBM_grid__1_AutoML_20200714_173719_model_2 2.2457e+09 47388.8 2.2457e+09 31717.9 0.236673 GBM_grid__1_AutoML_20200714_173719_model_4 2.24615e+09 47393.6 2.24615e+09 31533.6 0.235206 GBM_grid__1_AutoML_20200714_173719_model_5 2.30368e+09 47996.7 2.30368e+09 31888 0.234582 GBM_grid__1_AutoML_20200714_173719_model_3 2.31412e+09 48105.3 2.31412e+09 32428.7 0.241596 GBM_1_AutoML_20200714_173719 2.38155e+09 48801.2 2.38155e+09 32817.8 0.241261 GBM_5_AutoML_20200714_173719 2.38712e+09 48858.1 2.38712e+09 32730.3 0.238373 XGBoost_grid__1_AutoML_20200714_173719_model_2 2.41444e+09 49137 2.41444e+09 33359.3 nan XGBoost_grid__1_AutoML_20200714_173719_model_1 2.43811e+09 49377.2 2.43811e+09 33392.7 nan XGBoost_grid__1_AutoML_20200714_173719_model_6 2.44549e+09 49451.8 2.44549e+09 33620.7 nan XGBoost_grid__1_AutoML_20200714_173719_model_7 2.46672e+09 49666.1 2.46672e+09 33264.5 nan XGBoost_3_AutoML_20200714_173719 2.47346e+09 49733.9 2.47346e+09 33829 nan XGBoost_grid__1_AutoML_20200714_173719_model_3 2.53867e+09 50385.2 2.53867e+09 33713.1 0.252152 XGBoost_grid__1_AutoML_20200714_173719_model_4 2.61998e+09 51185.8 2.61998e+09 34084.3 nan GBM_grid__1_AutoML_20200714_173719_model_1 2.63332e+09 51315.9 2.63332e+09 35218.1 nan XGBoost_1_AutoML_20200714_173719 2.64565e+09 51435.9 2.64565e+09 34900.5 nan XGBoost_2_AutoML_20200714_173719 2.67031e+09 51675 2.67031e+09 35556.1 nan DRF_1_AutoML_20200714_173719 2.90447e+09 53893.1 2.90447e+09 36925.5 0.263639 XRT_1_AutoML_20200714_173719 2.92071e+09 54043.6 2.92071e+09 37116.6 0.264397 XGBoost_grid__1_AutoML_20200714_173719_model_8 4.32541e+09 65767.9 4.32541e+09 43502.3 0.287448 DeepLearning_1_AutoML_20200714_173719 5.06767e+09 71187.6 5.06767e+09 49467.4 nan DeepLearning_grid__2_AutoML_20200714_173719_model_1 6.01537e+09 77558.8 6.01537e+09 56478.1 0.386805 DeepLearning_grid__3_AutoML_20200714_173719_model_1 7.85515e+09 88629.3 7.85515e+09 64133.5 0.448841 GBM_grid__1_AutoML_20200714_173719_model_6 8.44986e+09 91923.1 8.44986e+09 71726.4 0.483173 DeepLearning_grid__1_AutoML_20200714_173719_model_2 8.72689e+09 93417.8 8.72689e+09 65346.1 nan DeepLearning_grid__1_AutoML_20200714_173719_model_1 8.9643e+09 94680 8.9643e+09 68862.6 nan GLM_1_AutoML_20200714_173719 1.34525e+10 115985 1.34525e+10 91648.3 0.592579 In this step, we explore the base learners of the stacked ensemble model and select the best performing base learning model. Code: python3 # Get the top model of leaderboardse = aml.leader # Get the metalearner model of top modelmetalearner = h2o.get_model(se.metalearner()['name'])) # list baselearner models :metalearner.varimp() [('XGBoost_grid__1_AutoML_20200714_173719_model_5', 36607.81502851827, 1.0, 0.3400955145231931), ('GBM_4_AutoML_20200714_173719', 33538.168782584005, 0.9161477885652846, 0.311577753531396), ('GBM_3_AutoML_20200714_173719', 27022.573640463357, 0.7381640674105295, 0.25104628830851705), ('XGBoost_grid__1_AutoML_20200714_173719_model_3', 7512.2319349954105, 0.2052084214570911, 0.06979046367994166), ('GBM_2_AutoML_20200714_173719', 1221.399944930078, 0.03336445903637191, 0.011347102862762904), ('XGBoost_grid__1_AutoML_20200714_173719_model_4', 897.9511180098376, 0.024528945999926915, 0.008342184510556763), ('XGBoost_grid__1_AutoML_20200714_173719_model_2', 839.6650323257486, 0.022936769967604773, 0.007800692583632669), ('GBM_grid__1_AutoML_20200714_173719_model_2', 0.0, 0.0, 0.0), ('GBM_grid__1_AutoML_20200714_173719_model_4', 0.0, 0.0, 0.0), ('GBM_grid__1_AutoML_20200714_173719_model_5', 0.0, 0.0, 0.0), ('GBM_grid__1_AutoML_20200714_173719_model_3', 0.0, 0.0, 0.0), ('GBM_1_AutoML_20200714_173719', 0.0, 0.0, 0.0), ('GBM_5_AutoML_20200714_173719', 0.0, 0.0, 0.0), ('XGBoost_grid__1_AutoML_20200714_173719_model_1', 0.0, 0.0, 0.0), ('XGBoost_grid__1_AutoML_20200714_173719_model_6', 0.0, 0.0, 0.0), ('XGBoost_grid__1_AutoML_20200714_173719_model_7', 0.0, 0.0, 0.0), ('XGBoost_3_AutoML_20200714_173719', 0.0, 0.0, 0.0), ('GBM_grid__1_AutoML_20200714_173719_model_1', 0.0, 0.0, 0.0), ('XGBoost_1_AutoML_20200714_173719', 0.0, 0.0, 0.0), ('XGBoost_2_AutoML_20200714_173719', 0.0, 0.0, 0.0), ('DRF_1_AutoML_20200714_173719', 0.0, 0.0, 0.0), ('XRT_1_AutoML_20200714_173719', 0.0, 0.0, 0.0), ('XGBoost_grid__1_AutoML_20200714_173719_model_8', 0.0, 0.0, 0.0), ('DeepLearning_1_AutoML_20200714_173719', 0.0, 0.0, 0.0), ('DeepLearning_grid__2_AutoML_20200714_173719_model_1', 0.0, 0.0, 0.0), ('DeepLearning_grid__3_AutoML_20200714_173719_model_1', 0.0, 0.0, 0.0), ('GBM_grid__1_AutoML_20200714_173719_model_6', 0.0, 0.0, 0.0), ('DeepLearning_grid__1_AutoML_20200714_173719_model_2', 0.0, 0.0, 0.0), ('DeepLearning_grid__1_AutoML_20200714_173719_model_1', 0.0, 0.0, 0.0), ('GLM_1_AutoML_20200714_173719', 0.0, 0.0, 0.0)] Now, we calculate error on this base learning model and plot the feature importance plot using this model. python3 # model performance on test datasetmodel = h2o.get_model('XGBoost_grid__1_AutoML_20200714_173719_model_5')model.model_performance(test) ModelMetricsRegression: xgboost ** Reported on test data. ** MSE: 2194912948.887177 RMSE: 46849.89806698812 MAE: 31039.50846508789 RMSLE: 0.24452804591616809 Mean Residual Deviance: 2194912948.887177 Code: python3 # plot the graph for variable importancemodel.varimp_plot(num_of_features = 9) Now, we can save this model using the model.save method, this model can be deployed on various platforms. Code: python3 # sAVE THE BASELEARNER MODELmodel_path = h2o.save_model(model = model, path ='sample_data/', force = True) References: H2O AI architecture doc H2O AutoML blog sagar0719kumar clintra singghakshay Machine Learning Machine Learning Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments ML | Linear Regression Search Algorithms in AI Elbow Method for optimal value of k in KMeans Support Vector Machine Algorithm Activation functions in Neural Networks ML | Underfitting and Overfitting Clustering in Machine Learning ML | Label Encoding of datasets in Python Python | Lemmatization with NLTK
[ { "code": null, "e": 24294, "s": 24266, "text": "\n18 Oct, 2021" }, { "code": null, "e": 24572, "s": 24294, "text": "Automated machine learning (AutoML) is the process of automating the end-to-end process of applying machine learning to real-world problems. AutoML automates most of the steps in an ML pipeline, with a minimum amount of human effort and without compromising on its performance." }, { "code": null, "e": 24637, "s": 24572, "text": "Automatic machine learning broadly includes the following steps:" }, { "code": null, "e": 25010, "s": 24637, "text": "Data preparation and Ingestion: The real-world data can be raw data or just in any format. In this step, data needs to be converted into a format that can be processed easily. This also required to decide the data type of different columns in the dataset. We also required a clear knowledge about the task we need to perform on data (e.g classification, regression, etc.)" }, { "code": null, "e": 25277, "s": 25010, "text": "Feature Engineering: This includes various steps that are required for cleaning the dataset such as dealing with NULL /missing values, selecting the most important features of the dataset, and removing the low-correlational features, dealing with the skewed dataset." }, { "code": null, "e": 25408, "s": 25277, "text": "Hyperparameter Optimization: To obtain the best results on any model, the AutoML need to carefully tune the hyperparameter values." }, { "code": null, "e": 25616, "s": 25408, "text": "Model Selection: H2O autoML trains with a large number of models in order to produce the best results. H2O AutoML also trains the data of different ensembles to get the best performance out of training data." }, { "code": null, "e": 25951, "s": 25616, "text": "H2O AutoML contains the cutting-edge and distributed implementation of many machine learning algorithms. These algorithms are available in Java, Python, Spark, Scala, and R. H2O also provide a web GUI that uses JSON to implement these algorithms. The models trained on H2O AutoML can be easily deployed on the Spark server, AWS, etc." }, { "code": null, "e": 26269, "s": 25951, "text": "The main advantage of H2O AutoML is that it automates the steps like basic data processing, model training and tuning, Ensemble and stacking of various models to provide the models with the best performance so that developers can focus on other steps like data collection, feature engineering and deployment of model." }, { "code": null, "e": 26299, "s": 26269, "text": "Functionalities of H2O AutoML" }, { "code": null, "e": 26413, "s": 26299, "text": "H2O AutoML provides necessary data processing capabilities. These are also included in all of the H2O algorithms." }, { "code": null, "e": 26524, "s": 26413, "text": "Trains a Random grid of algorithms like GBMs, DNNs, GLMs, etc. using a carefully chosen hyper-parameter space." }, { "code": null, "e": 26576, "s": 26524, "text": "Individual models are tuned using cross-validation." }, { "code": null, "e": 26811, "s": 26576, "text": "Two Stacked Ensembles are trained. One ensemble contains all the models (optimized for model performance), and the other ensemble provides just the best performing model from each algorithm class/family (optimized for production use)." }, { "code": null, "e": 26857, "s": 26811, "text": "Returns a sorted “Leaderboard” of all models." }, { "code": null, "e": 26906, "s": 26857, "text": "All models can be easily exported to production." }, { "code": null, "e": 26920, "s": 26906, "text": "Architecture:" }, { "code": null, "e": 27094, "s": 26920, "text": "H2O AutoML uses H2O architecture. H2O architecture can be divided into different layers in which the top layer will be different APIs, and the bottom layer will be H2O JVM." }, { "code": null, "e": 27113, "s": 27094, "text": "H2O Software Stack" }, { "code": null, "e": 27216, "s": 27113, "text": "H2O provides REST API clients for Python, R, Excel, Tableau, and Flow Web UI using socket connections." }, { "code": null, "e": 27302, "s": 27216, "text": "The bottom layer contains different components that will run on the H2O JVM process. " }, { "code": null, "e": 27476, "s": 27302, "text": "An H2O cluster consists of one or more nodes. Each node is a single JVM process. Each JVM process is split into three layers: language, algorithms, and core infrastructure. " }, { "code": null, "e": 27627, "s": 27476, "text": "The first layer in the bottom section is the language layer. The language layer consists of an expression evaluation engine for R and the Scala layer." }, { "code": null, "e": 27790, "s": 27627, "text": "The second layer is the algorithm layer. This layer contains an algorithms that are already provided in the H2O such as: XGBoost, GBM, Random Forest, K-Means etc." }, { "code": null, "e": 27910, "s": 27790, "text": "The third layer is the core infrastructure layer that deals with resource management such as Memory and CPU management." }, { "code": null, "e": 27926, "s": 27910, "text": "Implementation:" }, { "code": null, "e": 28069, "s": 27926, "text": "In this code, we will be using California Housing Dataset which is easily available in colab. First, we need to import the necessary packages." }, { "code": null, "e": 28076, "s": 28069, "text": "Code: " }, { "code": null, "e": 28084, "s": 28076, "text": "python3" }, { "code": "# codeimport pandas as pdimport numpy as npimport matplotlib.pyplot as plt", "e": 28159, "s": 28084, "text": null }, { "code": null, "e": 28295, "s": 28159, "text": "Now, we load the California Housing Dataset. This is already available in the sample data folder when we load the environment in colab." }, { "code": null, "e": 28302, "s": 28295, "text": "Code: " }, { "code": null, "e": 28310, "s": 28302, "text": "python3" }, { "code": "# codedf = pd.read_csv('sample_data / california_housing_train.csv')", "e": 28379, "s": 28310, "text": null }, { "code": null, "e": 28474, "s": 28379, "text": "Let’s look at the dataset, we use the head function to list the first few rows of the dataset." }, { "code": null, "e": 28481, "s": 28474, "text": "Code: " }, { "code": null, "e": 28489, "s": 28481, "text": "python3" }, { "code": "# print first 5 rows of dataframe df.head()", "e": 28533, "s": 28489, "text": null }, { "code": null, "e": 29120, "s": 28533, "text": "longitude latitude housing_median_age total_rooms total_bedrooms population households median_income median_house_value\n0 -114.31 34.19 15.0 5612.0 1283.0 1015.0 472.0 1.4936 66900.0\n1 -114.47 34.40 19.0 7650.0 1901.0 1129.0 463.0 1.8200 80100.0\n2 -114.56 33.69 17.0 720.0 174.0 333.0 117.0 1.6509 85700.0\n3 -114.57 33.64 14.0 1501.0 337.0 515.0 226.0 3.1917 73400.0\n4 -114.57 33.57 20.0 1454.0 326.0 624.0 262.0 1.9250 65500.0" }, { "code": null, "e": 29229, "s": 29120, "text": "Now, let’s check for null values in the dataset. As we can see that there are no null values in the dataset." }, { "code": null, "e": 29236, "s": 29229, "text": "Code: " }, { "code": null, "e": 29244, "s": 29236, "text": "python3" }, { "code": "# calculate total null values in every columndf.isna().sum()", "e": 29305, "s": 29244, "text": null }, { "code": null, "e": 29534, "s": 29305, "text": "longitude 0\nlatitude 0\nhousing_median_age 0\ntotal_rooms 0\ntotal_bedrooms 0\npopulation 0\nhouseholds 0\nmedian_income 0\nmedian_house_value 0\ndtype: int64" }, { "code": null, "e": 30425, "s": 29534, "text": "Now we need to install the h2o, we can install it using pip. Note, if you are using the local environment for H2O, you need to install the Java Development Kit (JDK). After installing JDK and H2O, we will initialize it, if it works fine this will start an H2O instance on the localhost. There are many arguments which we can pass such as:nthreads: No of cores H2O server can use, by default it uses all cores of CPU.ip: IP address of the server where the H2O server will run. By default, it uses localhost.port: port on which the H2O server will run.max_mem_size: A character string specifying the maximum size, in bytes, of the memory allocation pool to H2O. This value must be a multiple of 1024 greater than 2MB. Append the letter m or M to indicate megabytes, or g or G to indicate gigabytes. Similarly, there is another parameter min_mem_size. For more details please look at H2O docs" }, { "code": null, "e": 30505, "s": 30425, "text": "nthreads: No of cores H2O server can use, by default it uses all cores of CPU." }, { "code": null, "e": 30596, "s": 30505, "text": "ip: IP address of the server where the H2O server will run. By default, it uses localhost." }, { "code": null, "e": 30641, "s": 30596, "text": "port: port on which the H2O server will run." }, { "code": null, "e": 30981, "s": 30641, "text": "max_mem_size: A character string specifying the maximum size, in bytes, of the memory allocation pool to H2O. This value must be a multiple of 1024 greater than 2MB. Append the letter m or M to indicate megabytes, or g or G to indicate gigabytes. Similarly, there is another parameter min_mem_size. For more details please look at H2O docs" }, { "code": null, "e": 30988, "s": 30981, "text": "Code: " }, { "code": null, "e": 30996, "s": 30988, "text": "python3" }, { "code": "# install and import H2o ! pip install h2oimport h2o# We will be using default parameter Here with H2O init methodh2o.init()", "e": 31122, "s": 30996, "text": null }, { "code": null, "e": 32503, "s": 31122, "text": "Checking whether there is an H2O instance running at http://localhost:54321 ..... not found.\nAttempting to start a local H2O server...\n Java Version: openjdk version \"11.0.7\" 2020-04-14; OpenJDK Runtime Environment (build 11.0.7+10-post-Ubuntu-2ubuntu218.04); OpenJDK 64-Bit Server VM (build 11.0.7+10-post-Ubuntu-2ubuntu218.04, mixed mode, sharing)\n Starting server from /usr/local/lib/python3.6/dist-packages/h2o/backend/bin/h2o.jar\n Ice root: /tmp/tmpebz1_45i\n JVM stdout: /tmp/tmpebz1_45i/h2o_unknownUser_started_from_python.out\n JVM stderr: /tmp/tmpebz1_45i/h2o_unknownUser_started_from_python.err\n Server is running at http://127.0.0.1:54321\nConnecting to H2O server at http://127.0.0.1:54321 ... successful.\nH2O_cluster_uptime: 03 secs\nH2O_cluster_timezone: Etc/UTC\nH2O_data_parsing_timezone: UTC\nH2O_cluster_version: 3.30.0.6\nH2O_cluster_version_age: 13 days\nH2O_cluster_name: H2O_from_python_unknownUser_h4lj71\nH2O_cluster_total_nodes: 1\nH2O_cluster_free_memory: 3.180 Gb\nH2O_cluster_total_cores: 2\nH2O_cluster_allowed_cores: 2\nH2O_cluster_status: accepting new members, healthy\nH2O_connection_url: http://127.0.0.1:54321\nH2O_connection_proxy: {\"http\": null, \"https\": null}\nH2O_internal_security: False\nH2O_API_Extensions: Amazon S3, XGBoost, Algos, AutoML, Core V3, TargetEncoder, Core V4\nPython_version: 3.6.9 final" }, { "code": null, "e": 32682, "s": 32503, "text": "The H2O instance can also be assessed from localhost: 54321, this instance provides a web GUI called FlowGUI. Now, we need to convert the train data frame into the H2O Dataframe." }, { "code": null, "e": 32690, "s": 32682, "text": "python3" }, { "code": "# convert pandas DataFrame into H2O Frametrain_df = h2o.H2OFrame(df)# Describe the train h20Frametrain_df.describe()", "e": 32808, "s": 32690, "text": null }, { "code": null, "e": 34687, "s": 32808, "text": "Parse progress: |?????????????????????????????????????????????????????????| 100%\nRows:17000\nCols:9\n\n\nlongitude latitude housing_median_age total_rooms total_bedrooms population households median_income median_house_value\ntype real real int int int int int real int\nmins -124.35 32.54 1.0 2.0 1.0 3.0 1.0 0.4999 14999.0\nmean -119.5621082352941 35.62522470588239 28.589352941176436 2643.6644117647143 539.4108235294095 1429.573941176477 501.2219411764718 3.8835781000000016 207300.9123529415\nmaxs -114.31 41.95 52.0 37937.0 6445.0 35682.0 6082.0 15.0001 500001.0\nsigma 2.0051664084260357 2.137339794657087 12.586936981660406 2179.9470714527765 421.4994515798648 1147.852959159527 384.52084085590155 1.9081565183791034 115983.76438720895\nzeros 0 0 0 0 0 0 0 0 0\nmissing 0 0 0 0 0 0 0 0 0\n0 -114.31 34.19 15.0 5612.0 1283.0 1015.0 472.0 1.4936 66900.0\n1 -114.47 34.4 19.0 7650.0 1901.0 1129.0 463.0 1.82 80100.0\n2 -114.56 33.69 17.0 720.0 174.0 333.0 117.0 1.6509 85700.0\n3 -114.57 33.64 14.0 1501.0 337.0 515.0 226.0 3.1917 73400.0\n4 -114.57 33.57 20.0 1454.0 326.0 624.0 262.0 1.925 65500.0\n5 -114.58 33.63 29.0 1387.0 236.0 671.0 239.0 3.3438 74000.0\n6 -114.58 33.61 25.0 2907.0 680.0 1841.0 633.0 2.6768 82400.0\n7 -114.59 34.83 41.0 812.0 168.0 375.0 158.0 1.7083 48500.0\n8 -114.59 33.61 34.0 4789.0 1175.0 3134.0 1056.0 2.1782 58400.0\n9 -114.6 34.83 46.0 1497.0 309.0 787.0 271.0 2.1908 48100.0" }, { "code": null, "e": 34778, "s": 34687, "text": "Now, we load our test dataset into pandas DataFrame and convert it into the H2O Dataframe." }, { "code": null, "e": 34785, "s": 34778, "text": "Code: " }, { "code": null, "e": 34793, "s": 34785, "text": "python3" }, { "code": "# codetest = pd.read_csv('sample_data / california_housing_test.csv')test = h2o.H2OFrame(test)# selecting feature and label columns x = test.columnsy = 'median_house_value'# remove label classvariable from feature variablex.remove(y)", "e": 35027, "s": 34793, "text": null }, { "code": null, "e": 35108, "s": 35027, "text": "Parse progress: |?????????????????????????????????????????????????????????| 100%" }, { "code": null, "e": 35147, "s": 35108, "text": "Now, we run AutoML and start training." }, { "code": null, "e": 35154, "s": 35147, "text": "Code: " }, { "code": null, "e": 35162, "s": 35154, "text": "python3" }, { "code": "# import autoML from H2Ofrom h2o.automl import H2OAutoML# callh20automl functionaml = H2OAutoML(max_runtime_secs = 600, # exclude_algos =['DeepLearning'], seed = 1, # stopping_metric ='logloss', # sort_metric ='logloss', balance_classes = False, project_name ='Project 1')# train model and record time % timeaml.train(x = x, y = y, training_frame = train_df)", "e": 35612, "s": 35162, "text": null }, { "code": null, "e": 35762, "s": 35612, "text": "AutoML progress: |????????????????????????????????????????????????????????| 100%\nCPU times: user 40 s, sys: 1.24 s, total: 41.2 s\nWall time: 9min 39s" }, { "code": null, "e": 35910, "s": 35762, "text": "In this step, we will look for the best performing model using the leaderboard and it will most probably be one of the two stacked ensemble models." }, { "code": null, "e": 35918, "s": 35910, "text": "python3" }, { "code": "# View the H2O aml leaderboardlb = aml.leaderboard# Print all rows instead of 10 rowslb.head(rows = lb.nrows)", "e": 36028, "s": 35918, "text": null }, { "code": null, "e": 39379, "s": 36028, "text": "model_id mean_residual_deviance rmse mse mae rmsle\nStackedEnsemble_AllModels_AutoML_20200714_173719 2.04045e+09 45171.3 2.04045e+09 29642.1 0.221447\nStackedEnsemble_BestOfFamily_AutoML_20200714_173719 2.06576e+09 45450.6 2.06576e+09 29949.4 0.223522\nGBM_3_AutoML_20200714_173719 2.15623e+09 46435.2 2.15623e+09 30763.8 0.227577\nGBM_4_AutoML_20200714_173719 2.15913e+09 46466.4 2.15913e+09 30786.7 0.228627\nXGBoost_grid__1_AutoML_20200714_173719_model_5 2.16562e+09 46536.2 2.16562e+09 31075.9 0.233288\nGBM_2_AutoML_20200714_173719 2.17639e+09 46651.8 2.17639e+09 31014.8 0.229731\nGBM_grid__1_AutoML_20200714_173719_model_2 2.2457e+09 47388.8 2.2457e+09 31717.9 0.236673\nGBM_grid__1_AutoML_20200714_173719_model_4 2.24615e+09 47393.6 2.24615e+09 31533.6 0.235206\nGBM_grid__1_AutoML_20200714_173719_model_5 2.30368e+09 47996.7 2.30368e+09 31888 0.234582\nGBM_grid__1_AutoML_20200714_173719_model_3 2.31412e+09 48105.3 2.31412e+09 32428.7 0.241596\nGBM_1_AutoML_20200714_173719 2.38155e+09 48801.2 2.38155e+09 32817.8 0.241261\nGBM_5_AutoML_20200714_173719 2.38712e+09 48858.1 2.38712e+09 32730.3 0.238373\nXGBoost_grid__1_AutoML_20200714_173719_model_2 2.41444e+09 49137 2.41444e+09 33359.3 nan\nXGBoost_grid__1_AutoML_20200714_173719_model_1 2.43811e+09 49377.2 2.43811e+09 33392.7 nan\nXGBoost_grid__1_AutoML_20200714_173719_model_6 2.44549e+09 49451.8 2.44549e+09 33620.7 nan\nXGBoost_grid__1_AutoML_20200714_173719_model_7 2.46672e+09 49666.1 2.46672e+09 33264.5 nan\nXGBoost_3_AutoML_20200714_173719 2.47346e+09 49733.9 2.47346e+09 33829 nan\nXGBoost_grid__1_AutoML_20200714_173719_model_3 2.53867e+09 50385.2 2.53867e+09 33713.1 0.252152\nXGBoost_grid__1_AutoML_20200714_173719_model_4 2.61998e+09 51185.8 2.61998e+09 34084.3 nan\nGBM_grid__1_AutoML_20200714_173719_model_1 2.63332e+09 51315.9 2.63332e+09 35218.1 nan\nXGBoost_1_AutoML_20200714_173719 2.64565e+09 51435.9 2.64565e+09 34900.5 nan\nXGBoost_2_AutoML_20200714_173719 2.67031e+09 51675 2.67031e+09 35556.1 nan\nDRF_1_AutoML_20200714_173719 2.90447e+09 53893.1 2.90447e+09 36925.5 0.263639\nXRT_1_AutoML_20200714_173719 2.92071e+09 54043.6 2.92071e+09 37116.6 0.264397\nXGBoost_grid__1_AutoML_20200714_173719_model_8 4.32541e+09 65767.9 4.32541e+09 43502.3 0.287448\nDeepLearning_1_AutoML_20200714_173719 5.06767e+09 71187.6 5.06767e+09 49467.4 nan\nDeepLearning_grid__2_AutoML_20200714_173719_model_1 6.01537e+09 77558.8 6.01537e+09 56478.1 0.386805\nDeepLearning_grid__3_AutoML_20200714_173719_model_1 7.85515e+09 88629.3 7.85515e+09 64133.5 0.448841\nGBM_grid__1_AutoML_20200714_173719_model_6 8.44986e+09 91923.1 8.44986e+09 71726.4 0.483173\nDeepLearning_grid__1_AutoML_20200714_173719_model_2 8.72689e+09 93417.8 8.72689e+09 65346.1 nan\nDeepLearning_grid__1_AutoML_20200714_173719_model_1 8.9643e+09 94680 8.9643e+09 68862.6 nan\nGLM_1_AutoML_20200714_173719 1.34525e+10 115985 1.34525e+10 91648.3 0.592579" }, { "code": null, "e": 39504, "s": 39379, "text": "In this step, we explore the base learners of the stacked ensemble model and select the best performing base learning model." }, { "code": null, "e": 39511, "s": 39504, "text": "Code: " }, { "code": null, "e": 39519, "s": 39511, "text": "python3" }, { "code": "# Get the top model of leaderboardse = aml.leader # Get the metalearner model of top modelmetalearner = h2o.get_model(se.metalearner()['name'])) # list baselearner models :metalearner.varimp()", "e": 39712, "s": 39519, "text": null }, { "code": null, "e": 41903, "s": 39712, "text": "[('XGBoost_grid__1_AutoML_20200714_173719_model_5',\n 36607.81502851827,\n 1.0,\n 0.3400955145231931),\n ('GBM_4_AutoML_20200714_173719',\n 33538.168782584005,\n 0.9161477885652846,\n 0.311577753531396),\n ('GBM_3_AutoML_20200714_173719',\n 27022.573640463357,\n 0.7381640674105295,\n 0.25104628830851705),\n ('XGBoost_grid__1_AutoML_20200714_173719_model_3',\n 7512.2319349954105,\n 0.2052084214570911,\n 0.06979046367994166),\n ('GBM_2_AutoML_20200714_173719',\n 1221.399944930078,\n 0.03336445903637191,\n 0.011347102862762904),\n ('XGBoost_grid__1_AutoML_20200714_173719_model_4',\n 897.9511180098376,\n 0.024528945999926915,\n 0.008342184510556763),\n ('XGBoost_grid__1_AutoML_20200714_173719_model_2',\n 839.6650323257486,\n 0.022936769967604773,\n 0.007800692583632669),\n ('GBM_grid__1_AutoML_20200714_173719_model_2', 0.0, 0.0, 0.0),\n ('GBM_grid__1_AutoML_20200714_173719_model_4', 0.0, 0.0, 0.0),\n ('GBM_grid__1_AutoML_20200714_173719_model_5', 0.0, 0.0, 0.0),\n ('GBM_grid__1_AutoML_20200714_173719_model_3', 0.0, 0.0, 0.0),\n ('GBM_1_AutoML_20200714_173719', 0.0, 0.0, 0.0),\n ('GBM_5_AutoML_20200714_173719', 0.0, 0.0, 0.0),\n ('XGBoost_grid__1_AutoML_20200714_173719_model_1', 0.0, 0.0, 0.0),\n ('XGBoost_grid__1_AutoML_20200714_173719_model_6', 0.0, 0.0, 0.0),\n ('XGBoost_grid__1_AutoML_20200714_173719_model_7', 0.0, 0.0, 0.0),\n ('XGBoost_3_AutoML_20200714_173719', 0.0, 0.0, 0.0),\n ('GBM_grid__1_AutoML_20200714_173719_model_1', 0.0, 0.0, 0.0),\n ('XGBoost_1_AutoML_20200714_173719', 0.0, 0.0, 0.0),\n ('XGBoost_2_AutoML_20200714_173719', 0.0, 0.0, 0.0),\n ('DRF_1_AutoML_20200714_173719', 0.0, 0.0, 0.0),\n ('XRT_1_AutoML_20200714_173719', 0.0, 0.0, 0.0),\n ('XGBoost_grid__1_AutoML_20200714_173719_model_8', 0.0, 0.0, 0.0),\n ('DeepLearning_1_AutoML_20200714_173719', 0.0, 0.0, 0.0),\n ('DeepLearning_grid__2_AutoML_20200714_173719_model_1', 0.0, 0.0, 0.0),\n ('DeepLearning_grid__3_AutoML_20200714_173719_model_1', 0.0, 0.0, 0.0),\n ('GBM_grid__1_AutoML_20200714_173719_model_6', 0.0, 0.0, 0.0),\n ('DeepLearning_grid__1_AutoML_20200714_173719_model_2', 0.0, 0.0, 0.0),\n ('DeepLearning_grid__1_AutoML_20200714_173719_model_1', 0.0, 0.0, 0.0),\n ('GLM_1_AutoML_20200714_173719', 0.0, 0.0, 0.0)]" }, { "code": null, "e": 42010, "s": 41903, "text": "Now, we calculate error on this base learning model and plot the feature importance plot using this model." }, { "code": null, "e": 42018, "s": 42010, "text": "python3" }, { "code": "# model performance on test datasetmodel = h2o.get_model('XGBoost_grid__1_AutoML_20200714_173719_model_5')model.model_performance(test)", "e": 42154, "s": 42018, "text": null }, { "code": null, "e": 42355, "s": 42154, "text": "ModelMetricsRegression: xgboost\n** Reported on test data. **\n\nMSE: 2194912948.887177\nRMSE: 46849.89806698812\nMAE: 31039.50846508789\nRMSLE: 0.24452804591616809\nMean Residual Deviance: 2194912948.887177" }, { "code": null, "e": 42362, "s": 42355, "text": "Code: " }, { "code": null, "e": 42370, "s": 42362, "text": "python3" }, { "code": "# plot the graph for variable importancemodel.varimp_plot(num_of_features = 9)", "e": 42449, "s": 42370, "text": null }, { "code": null, "e": 42555, "s": 42449, "text": "Now, we can save this model using the model.save method, this model can be deployed on various platforms." }, { "code": null, "e": 42562, "s": 42555, "text": "Code: " }, { "code": null, "e": 42570, "s": 42562, "text": "python3" }, { "code": "# sAVE THE BASELEARNER MODELmodel_path = h2o.save_model(model = model, path ='sample_data/', force = True)", "e": 42677, "s": 42570, "text": null }, { "code": null, "e": 42689, "s": 42677, "text": "References:" }, { "code": null, "e": 42713, "s": 42689, "text": "H2O AI architecture doc" }, { "code": null, "e": 42729, "s": 42713, "text": "H2O AutoML blog" }, { "code": null, "e": 42744, "s": 42729, "text": "sagar0719kumar" }, { "code": null, "e": 42752, "s": 42744, "text": "clintra" }, { "code": null, "e": 42765, "s": 42752, "text": "singghakshay" }, { "code": null, "e": 42782, "s": 42765, "text": "Machine Learning" }, { "code": null, "e": 42799, "s": 42782, "text": "Machine Learning" }, { "code": null, "e": 42897, "s": 42799, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 42906, "s": 42897, "text": "Comments" }, { "code": null, "e": 42919, "s": 42906, "text": "Old Comments" }, { "code": null, "e": 42942, "s": 42919, "text": "ML | Linear Regression" }, { "code": null, "e": 42966, "s": 42942, "text": "Search Algorithms in AI" }, { "code": null, "e": 43012, "s": 42966, "text": "Elbow Method for optimal value of k in KMeans" }, { "code": null, "e": 43045, "s": 43012, "text": "Support Vector Machine Algorithm" }, { "code": null, "e": 43085, "s": 43045, "text": "Activation functions in Neural Networks" }, { "code": null, "e": 43119, "s": 43085, "text": "ML | Underfitting and Overfitting" }, { "code": null, "e": 43150, "s": 43119, "text": "Clustering in Machine Learning" }, { "code": null, "e": 43192, "s": 43150, "text": "ML | Label Encoding of datasets in Python" } ]
How to implement an Android notification action without opening the app?
This example demonstrate about How to implement an Android notification action without opening the app. Step 1 − Create a new project in Android Studio, go to File ⇒ New Project and fill all required details to create a new project. Step 2 − Add the following code to res/layout/activity_main.xml. <? xml version = "1.0" encoding = "utf-8" ?> <RelativeLayout xmlns:android = "http://schemas.android.com/apk/res/android" xmlns:tools = "http://schemas.android.com/tools" android:layout_width = "match_parent" android:layout_height = "match_parent" android:padding = "16dp" tools:context = ".MainActivity" > <Button android:onClick= "createNotification" android:text= "create notification" android:layout_centerInParent= "true" android:layout_width= "match_parent" android:layout_height= "wrap_content" /> </RelativeLayout> Step 3 − Add the following code to src/MainActivity. package app.tutorialspoint.com.notifyme ; import android.app.NotificationChannel ; import android.app.NotificationManager ; import android.app.PendingIntent ; import android.content.Intent ; import android.os.Bundle ; import android.support.v4.app.NotificationCompat ; import android.support.v7.app.AppCompatActivity ; import android.view.View ; public class MainActivity extends AppCompatActivity { public static final String NOTIFICATION_CHANNEL_ID = "10001" ; private final static String default_notification_channel_id = "default" ; @Override protected void onCreate (Bundle savedInstanceState) { super .onCreate(savedInstanceState) ; setContentView(R.layout. activity_main ) ; } public void createNotification (View view) { int NOTIFICATION_ID = ( int ) System. currentTimeMillis () ; PendingIntent pendingIntent = PendingIntent. getActivity ( this, 0 , new Intent() , 0 ) ; Intent buttonIntent = new Intent( this, NotificationBroadcastReceiver. class ) ; buttonIntent.putExtra( "notificationId" , NOTIFICATION_ID) ; PendingIntent btPendingIntent = PendingIntent. getBroadcast ( this, 0 , buttonIntent , 0 ) ; NotificationManager mNotificationManager = (NotificationManager) getSystemService( NOTIFICATION_SERVICE ) ; NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(getApplicationContext() , default_notification_channel_id ) ; mBuilder.setContentTitle( "My Notification" ) ; mBuilder.setContentIntent(pendingIntent) ; mBuilder.addAction(R.drawable. ic_launcher_foreground , "Cancel" , btPendingIntent) ; mBuilder.setContentText( "Notification Listener Service Example" ) ; mBuilder.setSmallIcon(R.drawable. ic_launcher_foreground ) ; mBuilder.setAutoCancel( true ) ; mBuilder.setDeleteIntent(getDeleteIntent()) ; if (android.os.Build.VERSION. SDK_INT >= android.os.Build.VERSION_CODES. O ) { int importance = NotificationManager. IMPORTANCE_HIGH ; NotificationChannel notificationChannel = new NotificationChannel( NOTIFICATION_CHANNEL_ID , "NOTIFICATION_CHANNEL_NAME" , importance) ; mBuilder.setChannelId( NOTIFICATION_CHANNEL_ID ) ; assert mNotificationManager != null; mNotificationManager.createNotificationChannel(notificationChannel) ; } assert mNotificationManager != null; mNotificationManager.notify(NOTIFICATION_ID , mBuilder.build()) ; } protected PendingIntent getDeleteIntent () { Intent intent = new Intent(MainActivity. this, NotificationBroadcastReceiver. class ) ; intent.setAction( "notification_cancelled" ) ; return PendingIntent. getBroadcast (MainActivity. this, 0 , intent , PendingIntent. FLAG_CANCEL_CURRENT ) ; } } Step 4 − Add the following code to src/NotificationBroadcastReceiver package app.tutorialspoint.com.notifyme ; import android.app.NotificationManager ; import android.content.BroadcastReceiver ; import android.content.Context ; import android.content.Intent ; public class NotificationBroadcastReceiver extends BroadcastReceiver { @Override public void onReceive (Context context , Intent intent) { int notificationId = intent.getIntExtra( "notificationId" , 0 ) ; // if you want cancel notification NotificationManager manager = (NotificationManager) context.getSystemService(Context. NOTIFICATION_SERVICE ) ; manager.cancel(notificationId) ; } } Step 5 − Add the following code to AndroidManifest.xml <? xml version = "1.0" encoding = "utf-8" ?> <manifest xmlns: android = "http://schemas.android.com/apk/res/android" package = "app.tutorialspoint.com.notifyme" > <uses-permission android :name = "android.permission.VIBRATE" /> <uses-permission android :name = "android.permission.RECEIVE_BOOT_COMPLETED" /> <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" > <receiver android :name = ".NotificationBroadcastReceiver" android :enabled = "true" android :exported = "true" > </receiver> <activity android :name = ".MainActivity" > <intent-filter> <action android :name = "android.intent.action.MAIN" /> <category android :name = "android.intent.category.LAUNCHER" /> </intent-filter> </activity> </application> </manifest> Let's try to run your application. I assume you have connected your actual Android Mobile device with your computer. To run the app from android studio, open one of your project's activity files and click Run icon from the toolbar. Select your mobile device as an option and then check your mobile device which will display your default screen Click here to download the project code
[ { "code": null, "e": 1166, "s": 1062, "text": "This example demonstrate about How to implement an Android notification action without opening the app." }, { "code": null, "e": 1295, "s": 1166, "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": 1360, "s": 1295, "text": "Step 2 − Add the following code to res/layout/activity_main.xml." }, { "code": null, "e": 1931, "s": 1360, "text": "<? xml version = \"1.0\" encoding = \"utf-8\" ?>\n<RelativeLayout xmlns:android = \"http://schemas.android.com/apk/res/android\"\n xmlns:tools = \"http://schemas.android.com/tools\"\n android:layout_width = \"match_parent\"\n android:layout_height = \"match_parent\"\n android:padding = \"16dp\"\n tools:context = \".MainActivity\" >\n <Button\n android:onClick= \"createNotification\"\n android:text= \"create notification\"\n android:layout_centerInParent= \"true\"\n android:layout_width= \"match_parent\"\n android:layout_height= \"wrap_content\" />\n</RelativeLayout>" }, { "code": null, "e": 1984, "s": 1931, "text": "Step 3 − Add the following code to src/MainActivity." }, { "code": null, "e": 4769, "s": 1984, "text": "package app.tutorialspoint.com.notifyme ;\nimport android.app.NotificationChannel ;\nimport android.app.NotificationManager ;\nimport android.app.PendingIntent ;\nimport android.content.Intent ;\nimport android.os.Bundle ;\nimport android.support.v4.app.NotificationCompat ;\nimport android.support.v7.app.AppCompatActivity ;\nimport android.view.View ;\npublic class MainActivity extends AppCompatActivity {\n public static final String NOTIFICATION_CHANNEL_ID = \"10001\" ;\n private final static String default_notification_channel_id = \"default\" ;\n @Override\n protected void onCreate (Bundle savedInstanceState) {\n super .onCreate(savedInstanceState) ;\n setContentView(R.layout. activity_main ) ;\n }\n public void createNotification (View view) {\n int NOTIFICATION_ID = ( int ) System. currentTimeMillis () ;\n PendingIntent pendingIntent = PendingIntent. getActivity ( this, 0 , new Intent() , 0 ) ;\n Intent buttonIntent = new Intent( this, NotificationBroadcastReceiver. class ) ;\n buttonIntent.putExtra( \"notificationId\" , NOTIFICATION_ID) ;\n PendingIntent btPendingIntent = PendingIntent. getBroadcast ( this, 0 , buttonIntent , 0 ) ;\n NotificationManager mNotificationManager = (NotificationManager) getSystemService( NOTIFICATION_SERVICE ) ;\n NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(getApplicationContext() , default_notification_channel_id ) ;\n mBuilder.setContentTitle( \"My Notification\" ) ;\n mBuilder.setContentIntent(pendingIntent) ;\n mBuilder.addAction(R.drawable. ic_launcher_foreground , \"Cancel\" , btPendingIntent) ;\n mBuilder.setContentText( \"Notification Listener Service Example\" ) ;\n mBuilder.setSmallIcon(R.drawable. ic_launcher_foreground ) ;\n mBuilder.setAutoCancel( true ) ;\n mBuilder.setDeleteIntent(getDeleteIntent()) ;\n if (android.os.Build.VERSION. SDK_INT >= android.os.Build.VERSION_CODES. O ) {\n int importance = NotificationManager. IMPORTANCE_HIGH ;\n NotificationChannel notificationChannel = new NotificationChannel( NOTIFICATION_CHANNEL_ID , \"NOTIFICATION_CHANNEL_NAME\" , importance) ;\n mBuilder.setChannelId( NOTIFICATION_CHANNEL_ID ) ;\n assert mNotificationManager != null;\n mNotificationManager.createNotificationChannel(notificationChannel) ;\n }\n assert mNotificationManager != null;\n mNotificationManager.notify(NOTIFICATION_ID , mBuilder.build()) ;\n }\n protected PendingIntent getDeleteIntent () {\n Intent intent = new Intent(MainActivity. this,\n NotificationBroadcastReceiver. class ) ;\n intent.setAction( \"notification_cancelled\" ) ;\n return PendingIntent. getBroadcast (MainActivity. this, 0 , intent , PendingIntent. FLAG_CANCEL_CURRENT ) ;\n }\n}" }, { "code": null, "e": 4838, "s": 4769, "text": "Step 4 − Add the following code to src/NotificationBroadcastReceiver" }, { "code": null, "e": 5450, "s": 4838, "text": "package app.tutorialspoint.com.notifyme ;\nimport android.app.NotificationManager ;\nimport android.content.BroadcastReceiver ;\nimport android.content.Context ;\nimport android.content.Intent ;\npublic class NotificationBroadcastReceiver extends BroadcastReceiver {\n @Override\n public void onReceive (Context context , Intent intent) {\n int notificationId = intent.getIntExtra( \"notificationId\" , 0 ) ;\n // if you want cancel notification\n NotificationManager manager = (NotificationManager) context.getSystemService(Context. NOTIFICATION_SERVICE ) ;\n manager.cancel(notificationId) ;\n }\n}" }, { "code": null, "e": 5505, "s": 5450, "text": "Step 5 − Add the following code to AndroidManifest.xml" }, { "code": null, "e": 6552, "s": 5505, "text": "<? xml version = \"1.0\" encoding = \"utf-8\" ?>\n<manifest xmlns: android = \"http://schemas.android.com/apk/res/android\"\n package = \"app.tutorialspoint.com.notifyme\" >\n <uses-permission android :name = \"android.permission.VIBRATE\" />\n <uses-permission android :name = \"android.permission.RECEIVE_BOOT_COMPLETED\" />\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 <receiver\n android :name = \".NotificationBroadcastReceiver\"\n android :enabled = \"true\"\n android :exported = \"true\" >\n </receiver>\n <activity android :name = \".MainActivity\" >\n <intent-filter>\n <action android :name = \"android.intent.action.MAIN\" />\n <category android :name = \"android.intent.category.LAUNCHER\" />\n </intent-filter>\n </activity>\n </application>\n</manifest>" }, { "code": null, "e": 6897, "s": 6552, "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": 6939, "s": 6897, "text": "Click here to download the project code" } ]
C program to sort names in alphabetical order
User has to enter number of names, and those names are required to be sorted in alphabetical order with the help of strcpy() function. An array of characters (or) collection of characters is called a string. Following is the declaration for an array − char stringname [size]; For example, char string[50]; string of length 50 characters. Using single character constant char string[10] = { ‘H’, ‘e’, ‘l’, ‘l’, ‘o’ ,‘\0’} Using string constants char string[10] = "Hello":; There is a control string "%s" used for accessing the string till it encounters ‘\0’ This function is used for copying source string into destination string. The length of the destination string is greater than or equal to the source string. The syntax for strcpy() function is as follows − strcpy (Destination string, Source String); For example, char a[50]; char a[50]; strcpy ("Hello",a); strcpy ( a,"hello"); output: error output: a= "Hello" The logic used to sort the names in alphabetical order is as follows − for(i=0;i<n;i++){ for(j=i+1;j<n;j++){ if(strcmp(str[i],str[j])>0){ strcpy(s,str[i]); strcpy(str[i],str[j]); strcpy(str[j],s); } } } Following is the C program to sort names in alphabetical order − #include<stdio.h> #include<string.h> main(){ int i,j,n; char str[100][100],s[100]; printf("Enter number of names :\n"); scanf("%d",&n); printf("Enter names in any order:\n"); for(i=0;i<n;i++){ scanf("%s",str[i]); } for(i=0;i<n;i++){ for(j=i+1;j<n;j++){ if(strcmp(str[i],str[j])>0){ strcpy(s,str[i]); strcpy(str[i],str[j]); strcpy(str[j],s); } } } printf("\nThe sorted order of names are:\n"); for(i=0;i<n;i++){ printf("%s\n",str[i]); } } When the above program is executed, it produces the following result − Enter number of names: 5 Enter names in any order: Pinky Lucky Ram Appu Bob The sorted order of names is: Appu Bob Lucky Pinky Ram
[ { "code": null, "e": 1197, "s": 1062, "text": "User has to enter number of names, and those names are required to be sorted in alphabetical order with the help of strcpy() function." }, { "code": null, "e": 1270, "s": 1197, "text": "An array of characters (or) collection of characters is called a string." }, { "code": null, "e": 1314, "s": 1270, "text": "Following is the declaration for an array −" }, { "code": null, "e": 1338, "s": 1314, "text": "char stringname [size];" }, { "code": null, "e": 1400, "s": 1338, "text": "For example, char string[50]; string of length 50 characters." }, { "code": null, "e": 1432, "s": 1400, "text": "Using single character constant" }, { "code": null, "e": 1483, "s": 1432, "text": "char string[10] = { ‘H’, ‘e’, ‘l’, ‘l’, ‘o’ ,‘\\0’}" }, { "code": null, "e": 1506, "s": 1483, "text": "Using string constants" }, { "code": null, "e": 1534, "s": 1506, "text": "char string[10] = \"Hello\":;" }, { "code": null, "e": 1619, "s": 1534, "text": "There is a control string \"%s\" used for accessing the string till it encounters ‘\\0’" }, { "code": null, "e": 1692, "s": 1619, "text": "This function is used for copying source string into destination string." }, { "code": null, "e": 1776, "s": 1692, "text": "The length of the destination string is greater than or equal to the source string." }, { "code": null, "e": 1825, "s": 1776, "text": "The syntax for strcpy() function is as follows −" }, { "code": null, "e": 1869, "s": 1825, "text": "strcpy (Destination string, Source String);" }, { "code": null, "e": 1882, "s": 1869, "text": "For example," }, { "code": null, "e": 2007, "s": 1882, "text": "char a[50]; char a[50];\nstrcpy (\"Hello\",a); strcpy ( a,\"hello\");\noutput: error output: a= \"Hello\"" }, { "code": null, "e": 2078, "s": 2007, "text": "The logic used to sort the names in alphabetical order is as follows −" }, { "code": null, "e": 2255, "s": 2078, "text": "for(i=0;i<n;i++){\n for(j=i+1;j<n;j++){\n if(strcmp(str[i],str[j])>0){\n strcpy(s,str[i]);\n strcpy(str[i],str[j]);\n strcpy(str[j],s);\n }\n }\n}" }, { "code": null, "e": 2320, "s": 2255, "text": "Following is the C program to sort names in alphabetical order −" }, { "code": null, "e": 2872, "s": 2320, "text": "#include<stdio.h>\n#include<string.h>\nmain(){\n int i,j,n;\n char str[100][100],s[100];\n printf(\"Enter number of names :\\n\");\n scanf(\"%d\",&n);\n printf(\"Enter names in any order:\\n\");\n for(i=0;i<n;i++){\n scanf(\"%s\",str[i]);\n }\n for(i=0;i<n;i++){\n for(j=i+1;j<n;j++){\n if(strcmp(str[i],str[j])>0){\n strcpy(s,str[i]);\n strcpy(str[i],str[j]);\n strcpy(str[j],s);\n }\n }\n }\n printf(\"\\nThe sorted order of names are:\\n\");\n for(i=0;i<n;i++){\n printf(\"%s\\n\",str[i]);\n }\n}" }, { "code": null, "e": 2943, "s": 2872, "text": "When the above program is executed, it produces the following result −" }, { "code": null, "e": 3074, "s": 2943, "text": "Enter number of names:\n5\nEnter names in any order:\nPinky\nLucky\nRam\nAppu\nBob\nThe sorted order of names is:\nAppu\nBob\nLucky\nPinky\nRam" } ]
Entity Framework - Track Changes
Entity Framework provides ability to track the changes made to entities and their relations, so the correct updates are made on the database when the SaveChanges method of context is called. This is a key feature of the Entity Framework. The Change Tracking tracks changes while adding new record(s) to the entity collection, modifying or removing existing entities. The Change Tracking tracks changes while adding new record(s) to the entity collection, modifying or removing existing entities. Then all the changes are kept by the DbContext level. Then all the changes are kept by the DbContext level. These track changes are lost if they are not saved before the DbContext object is destroyed. These track changes are lost if they are not saved before the DbContext object is destroyed. DbChangeTracker class gives you all the information about current entities being tracked by the context. DbChangeTracker class gives you all the information about current entities being tracked by the context. To track any entity by the context, it must have the primary key property. To track any entity by the context, it must have the primary key property. In Entity Framework, change tracking is enabled by default. You can also disable change tracking by setting the AutoDetectChangesEnabled property of DbContext to false. If this property is set to true then the Entity Framework maintains the state of entities. using (var context = new UniContextEntities()) { context.Configuration.AutoDetectChangesEnabled = true; } Let’s take a look at the following example in which the students and their enrollments are retrieved from the database. class Program { static void Main(string[] args) { using (var context = new UniContextEntities()) { context.Configuration.AutoDetectChangesEnabled = true; Console.WriteLine("Retrieve Student"); var student = (from s in context.Students where s.FirstMidName == "Ali" select s).FirstOrDefault<Student>(); string name = student.FirstMidName + " " + student.LastName; Console.WriteLine("ID: {0}, Name: {1}", student.ID, name); Console.WriteLine(); Console.WriteLine("Retrieve all related enrollments"); foreach (var enrollment in student.Enrollments) { Console.WriteLine("Enrollment ID: {0}, Course ID: {1}", enrollment.EnrollmentID, enrollment.CourseID); } Console.WriteLine(); Console.WriteLine("Context tracking changes of {0} entity.", context.ChangeTracker.Entries().Count()); var entries = context.ChangeTracker.Entries(); foreach (var entry in entries) { Console.WriteLine("Entity Name: {0}", entry.Entity.GetType().Name); Console.WriteLine("Status: {0}", entry.State); } Console.ReadKey(); } } } When the above example is compiled and executed you will receive the following output. Retrieve Student ID: 1, Name: Ali Alexander Retrieve all related enrollments Enrollment ID: 1, Course ID: 1050 Enrollment ID: 2, Course ID: 4022 Enrollment ID: 3, Course ID: 4041 Context tracking changes of 4 entity. Entity Name: Student Status: Unchanged Entity Name: Enrollment Status: Unchanged Entity Name: Enrollment Status: Unchanged Entity Name: Enrollment Status: Unchanged You can see that all data is only retrieved from the database that’s why the status is unchanged for all the entities. Let us now take a look at another simple example in which we will add one more enrollment and delete one student from the database. Following is the code in which new enrollment is added and one student is deleted. class Program { static void Main(string[] args) { using (var context = new UniContextEntities()) { context.Configuration.AutoDetectChangesEnabled = true; Enrollment enr = new Enrollment() { StudentID = 1, CourseID = 3141 }; Console.WriteLine("Adding New Enrollment"); context.Enrollments.Add(enr); Console.WriteLine("Delete Student"); var student = (from s in context.Students where s.ID == 23 select s).SingleOrDefault<Student>(); context.Students.Remove(student); Console.WriteLine(""); Console.WriteLine("Context tracking changes of {0} entity.", context.ChangeTracker.Entries().Count()); var entries = context.ChangeTracker.Entries(); foreach (var entry in entries) { Console.WriteLine("Entity Name: {0}", entry.Entity.GetType().Name); Console.WriteLine("Status: {0}", entry.State); } Console.ReadKey(); } } } When the above example is compiled and executed, you will receive the following output. Adding New Enrollment Delete Student Context tracking changes of 2 entity. Entity Name: Enrollment Status: Added Entity Name: Student Status: Deleted You can now see that the status of enrollment entity is set to added, and the status of student entity is deleted, because new enrollment has been added and one student is removed from the database. We recommend that you execute the above example in a step-by-step manner for better understanding. 19 Lectures 5 hours Trevoir Williams 33 Lectures 3.5 hours Nilay Mehta 21 Lectures 2.5 hours TELCOMA Global 89 Lectures 7.5 hours Mustafa Radaideh Print Add Notes Bookmark this page
[ { "code": null, "e": 3270, "s": 3032, "text": "Entity Framework provides ability to track the changes made to entities and their relations, so the correct updates are made on the database when the SaveChanges method of context is called. This is a key feature of the Entity Framework." }, { "code": null, "e": 3399, "s": 3270, "text": "The Change Tracking tracks changes while adding new record(s) to the entity collection, modifying or removing existing entities." }, { "code": null, "e": 3528, "s": 3399, "text": "The Change Tracking tracks changes while adding new record(s) to the entity collection, modifying or removing existing entities." }, { "code": null, "e": 3582, "s": 3528, "text": "Then all the changes are kept by the DbContext level." }, { "code": null, "e": 3636, "s": 3582, "text": "Then all the changes are kept by the DbContext level." }, { "code": null, "e": 3729, "s": 3636, "text": "These track changes are lost if they are not saved before the DbContext object is destroyed." }, { "code": null, "e": 3822, "s": 3729, "text": "These track changes are lost if they are not saved before the DbContext object is destroyed." }, { "code": null, "e": 3927, "s": 3822, "text": "DbChangeTracker class gives you all the information about current entities being tracked by the context." }, { "code": null, "e": 4032, "s": 3927, "text": "DbChangeTracker class gives you all the information about current entities being tracked by the context." }, { "code": null, "e": 4107, "s": 4032, "text": "To track any entity by the context, it must have the primary key property." }, { "code": null, "e": 4182, "s": 4107, "text": "To track any entity by the context, it must have the primary key property." }, { "code": null, "e": 4442, "s": 4182, "text": "In Entity Framework, change tracking is enabled by default. You can also disable change tracking by setting the AutoDetectChangesEnabled property of DbContext to false. If this property is set to true then the Entity Framework maintains the state of entities." }, { "code": null, "e": 4551, "s": 4442, "text": "using (var context = new UniContextEntities()) {\n context.Configuration.AutoDetectChangesEnabled = true;\n}" }, { "code": null, "e": 4671, "s": 4551, "text": "Let’s take a look at the following example in which the students and their enrollments are retrieved from the database." }, { "code": null, "e": 5912, "s": 4671, "text": "class Program {\n\n static void Main(string[] args) {\n\n using (var context = new UniContextEntities()) {\n\n context.Configuration.AutoDetectChangesEnabled = true;\n Console.WriteLine(\"Retrieve Student\");\n\n var student = (from s in context.Students where s.FirstMidName == \n \"Ali\" select s).FirstOrDefault<Student>();\n\n string name = student.FirstMidName + \" \" + student.LastName;\n Console.WriteLine(\"ID: {0}, Name: {1}\", student.ID, name);\n Console.WriteLine();\n Console.WriteLine(\"Retrieve all related enrollments\");\n\n foreach (var enrollment in student.Enrollments) {\n Console.WriteLine(\"Enrollment ID: {0}, Course ID: {1}\", \n enrollment.EnrollmentID, enrollment.CourseID);\n }\n\n Console.WriteLine();\n\n Console.WriteLine(\"Context tracking changes of {0} entity.\", \n context.ChangeTracker.Entries().Count());\n\n var entries = context.ChangeTracker.Entries();\n\n foreach (var entry in entries) {\n Console.WriteLine(\"Entity Name: {0}\", entry.Entity.GetType().Name);\n Console.WriteLine(\"Status: {0}\", entry.State);\n }\n\n Console.ReadKey();\n }\n }\n}" }, { "code": null, "e": 5999, "s": 5912, "text": "When the above example is compiled and executed you will receive the following output." }, { "code": null, "e": 6404, "s": 5999, "text": "Retrieve Student \nID: 1, Name: Ali Alexander\nRetrieve all related enrollments\n Enrollment ID: 1, Course ID: 1050\n Enrollment ID: 2, Course ID: 4022\n Enrollment ID: 3, Course ID: 4041\nContext tracking changes of 4 entity.\nEntity Name: Student\nStatus: Unchanged\nEntity Name: Enrollment\nStatus: Unchanged\nEntity Name: Enrollment\nStatus: Unchanged\nEntity Name: Enrollment\nStatus: Unchanged\n" }, { "code": null, "e": 6523, "s": 6404, "text": "You can see that all data is only retrieved from the database that’s why the status is unchanged for all the entities." }, { "code": null, "e": 6738, "s": 6523, "text": "Let us now take a look at another simple example in which we will add one more enrollment and delete one student from the database. Following is the code in which new enrollment is added and one student is deleted." }, { "code": null, "e": 7770, "s": 6738, "text": "class Program {\n\n static void Main(string[] args) {\n\n using (var context = new UniContextEntities()) {\n\n context.Configuration.AutoDetectChangesEnabled = true;\n\n Enrollment enr = new Enrollment() { \n StudentID = 1, CourseID = 3141 \n };\n\n Console.WriteLine(\"Adding New Enrollment\");\n context.Enrollments.Add(enr);\n Console.WriteLine(\"Delete Student\");\n\n var student = (from s in context.Students where s.ID == \n 23 select s).SingleOrDefault<Student>();\n\n context.Students.Remove(student);\n Console.WriteLine(\"\");\n\n Console.WriteLine(\"Context tracking changes of {0} entity.\", \n context.ChangeTracker.Entries().Count());\n var entries = context.ChangeTracker.Entries();\n\n foreach (var entry in entries) {\n Console.WriteLine(\"Entity Name: {0}\", entry.Entity.GetType().Name);\n Console.WriteLine(\"Status: {0}\", entry.State);\n }\n\n Console.ReadKey();\n }\n }\n}" }, { "code": null, "e": 7858, "s": 7770, "text": "When the above example is compiled and executed, you will receive the following output." }, { "code": null, "e": 8009, "s": 7858, "text": "Adding New Enrollment\nDelete Student\nContext tracking changes of 2 entity.\nEntity Name: Enrollment\nStatus: Added\nEntity Name: Student\nStatus: Deleted\n" }, { "code": null, "e": 8208, "s": 8009, "text": "You can now see that the status of enrollment entity is set to added, and the status of student entity is deleted, because new enrollment has been added and one student is removed from the database." }, { "code": null, "e": 8307, "s": 8208, "text": "We recommend that you execute the above example in a step-by-step manner for better understanding." }, { "code": null, "e": 8340, "s": 8307, "text": "\n 19 Lectures \n 5 hours \n" }, { "code": null, "e": 8358, "s": 8340, "text": " Trevoir Williams" }, { "code": null, "e": 8393, "s": 8358, "text": "\n 33 Lectures \n 3.5 hours \n" }, { "code": null, "e": 8406, "s": 8393, "text": " Nilay Mehta" }, { "code": null, "e": 8441, "s": 8406, "text": "\n 21 Lectures \n 2.5 hours \n" }, { "code": null, "e": 8457, "s": 8441, "text": " TELCOMA Global" }, { "code": null, "e": 8492, "s": 8457, "text": "\n 89 Lectures \n 7.5 hours \n" }, { "code": null, "e": 8510, "s": 8492, "text": " Mustafa Radaideh" }, { "code": null, "e": 8517, "s": 8510, "text": " Print" }, { "code": null, "e": 8528, "s": 8517, "text": " Add Notes" } ]
PARALLELPERIOD function
Returns a table that contains a column of dates that represents a period parallel to the dates in the specified dates column, in the current context, with the dates shifted a number of intervals either forward in time or back in time. PARALLELPERIOD (<dates>, <number_of_intervals>, <interval>) dates A column that contains dates. number_of_intervals An integer that specifies the number of intervals to add to or subtract from the dates. interval The interval by which to shift the dates. The value for interval can be one of the following − Year Quarter Month Day A table containing a single column of date values. DAX PARALLELPERIOD function takes the current set of dates in the column specified by dates, shifts the first date and the last date the specified number of intervals, and then returns all contiguous dates between the two shifted dates. If the interval is a partial range of month, quarter, or year, then any partial months in the result are also filled out to complete the entire interval. The dates parameter can be any of the following − A reference to a date/time column. A reference to a date/time column. A table expression that returns a single column of date/time values. A table expression that returns a single column of date/time values. A Boolean expression that defines a single-column table of date/time values. A Boolean expression that defines a single-column table of date/time values. Constraints on Boolean expressions − The expression cannot reference a calculated field. The expression cannot reference a calculated field. The expression cannot use CALCULATE function. The expression cannot use CALCULATE function. The expression cannot use any function that scans a table or returns a table, including aggregation functions. The expression cannot use any function that scans a table or returns a table, including aggregation functions. However, a Boolean expression can use any function that looks up a single value, or that calculates a scalar value. If the number specified for number_of_intervals parameter is positive, the dates are moved forward in time. If the number is negative, the dates are shifted back in time. The interval parameter is an enumeration, not a set of strings. Hence, the values for interval should not be enclosed in quotation marks. Also, the values: year, quarter, month, day should be spelled in full when using them. The result table includes only dates that are specified in the dates parameter. If the dates in the current context do not form a contiguous interval, the function returns an error. Previous Year Sales:= CALCULATE ( SUM (Sales[Sales Amount]), PARALLELPERIOD (Sales[Date], -1,YEAR) ) 53 Lectures 5.5 hours Abhay Gadiya 24 Lectures 2 hours Randy Minder 26 Lectures 4.5 hours Randy Minder Print Add Notes Bookmark this page
[ { "code": null, "e": 2236, "s": 2001, "text": "Returns a table that contains a column of dates that represents a period parallel to the dates in the specified dates column, in the current context, with the dates shifted a number of intervals either forward in time or back in time." }, { "code": null, "e": 2298, "s": 2236, "text": "PARALLELPERIOD (<dates>, <number_of_intervals>, <interval>) \n" }, { "code": null, "e": 2304, "s": 2298, "text": "dates" }, { "code": null, "e": 2334, "s": 2304, "text": "A column that contains dates." }, { "code": null, "e": 2354, "s": 2334, "text": "number_of_intervals" }, { "code": null, "e": 2442, "s": 2354, "text": "An integer that specifies the number of intervals to add to or subtract from the dates." }, { "code": null, "e": 2451, "s": 2442, "text": "interval" }, { "code": null, "e": 2493, "s": 2451, "text": "The interval by which to shift the dates." }, { "code": null, "e": 2546, "s": 2493, "text": "The value for interval can be one of the following −" }, { "code": null, "e": 2551, "s": 2546, "text": "Year" }, { "code": null, "e": 2559, "s": 2551, "text": "Quarter" }, { "code": null, "e": 2565, "s": 2559, "text": "Month" }, { "code": null, "e": 2569, "s": 2565, "text": "Day" }, { "code": null, "e": 2620, "s": 2569, "text": "A table containing a single column of date values." }, { "code": null, "e": 2857, "s": 2620, "text": "DAX PARALLELPERIOD function takes the current set of dates in the column specified by dates, shifts the first date and the last date the specified number of intervals, and then returns all contiguous dates between the two shifted dates." }, { "code": null, "e": 3011, "s": 2857, "text": "If the interval is a partial range of month, quarter, or year, then any partial months in the result are also filled out to complete the entire interval." }, { "code": null, "e": 3061, "s": 3011, "text": "The dates parameter can be any of the following −" }, { "code": null, "e": 3096, "s": 3061, "text": "A reference to a date/time column." }, { "code": null, "e": 3131, "s": 3096, "text": "A reference to a date/time column." }, { "code": null, "e": 3200, "s": 3131, "text": "A table expression that returns a single column of date/time values." }, { "code": null, "e": 3269, "s": 3200, "text": "A table expression that returns a single column of date/time values." }, { "code": null, "e": 3346, "s": 3269, "text": "A Boolean expression that defines a single-column table of date/time values." }, { "code": null, "e": 3423, "s": 3346, "text": "A Boolean expression that defines a single-column table of date/time values." }, { "code": null, "e": 3460, "s": 3423, "text": "Constraints on Boolean expressions −" }, { "code": null, "e": 3512, "s": 3460, "text": "The expression cannot reference a calculated field." }, { "code": null, "e": 3564, "s": 3512, "text": "The expression cannot reference a calculated field." }, { "code": null, "e": 3610, "s": 3564, "text": "The expression cannot use CALCULATE function." }, { "code": null, "e": 3656, "s": 3610, "text": "The expression cannot use CALCULATE function." }, { "code": null, "e": 3767, "s": 3656, "text": "The expression cannot use any function that scans a table or returns a table, including aggregation functions." }, { "code": null, "e": 3878, "s": 3767, "text": "The expression cannot use any function that scans a table or returns a table, including aggregation functions." }, { "code": null, "e": 3994, "s": 3878, "text": "However, a Boolean expression can use any function that looks up a single value, or that calculates a scalar value." }, { "code": null, "e": 4165, "s": 3994, "text": "If the number specified for number_of_intervals parameter is positive, the dates are moved forward in time. If the number is negative, the dates are shifted back in time." }, { "code": null, "e": 4390, "s": 4165, "text": "The interval parameter is an enumeration, not a set of strings. Hence, the values for interval should not be enclosed in quotation marks. Also, the values: year, quarter, month, day should be spelled in full when using them." }, { "code": null, "e": 4470, "s": 4390, "text": "The result table includes only dates that are specified in the dates parameter." }, { "code": null, "e": 4572, "s": 4470, "text": "If the dates in the current context do not form a contiguous interval, the function returns an error." }, { "code": null, "e": 4682, "s": 4572, "text": "Previous Year Sales:= CALCULATE ( \n SUM (Sales[Sales Amount]), \n PARALLELPERIOD (Sales[Date], -1,YEAR)\n) " }, { "code": null, "e": 4717, "s": 4682, "text": "\n 53 Lectures \n 5.5 hours \n" }, { "code": null, "e": 4731, "s": 4717, "text": " Abhay Gadiya" }, { "code": null, "e": 4764, "s": 4731, "text": "\n 24 Lectures \n 2 hours \n" }, { "code": null, "e": 4778, "s": 4764, "text": " Randy Minder" }, { "code": null, "e": 4813, "s": 4778, "text": "\n 26 Lectures \n 4.5 hours \n" }, { "code": null, "e": 4827, "s": 4813, "text": " Randy Minder" }, { "code": null, "e": 4834, "s": 4827, "text": " Print" }, { "code": null, "e": 4845, "s": 4834, "text": " Add Notes" } ]
Active Learning Tutorial with Python | Machine Learning | Towards Data Science
Active learning is a machine learning technique in which we use less labelled data and interactively label new data points to improve the performance of the model. Terminology: Train dataset = Labelled data pointsPool = Unlabelled data points We start with some labelled data points (train dataset). There is a large pool of unlabelled data points. These unlabelled data points have to be labelled and added to the train dataset to create the model. However, instead of labelling all the data points from the pool, we will label only a small number of them in active learning, but, still get a good performance. We create a model (classifier) and train it on the labelled data. Then, we go through all the data points in the pool and identify the points that are most ambiguous for the classifier and add these points to the train data (We may add just a single point each time). We repeat this process to improve model performance. This technique is generally used when the labelling cost is high. I will soon be uploading a video on YouTube, explaining in detail the concepts behind active learning. Here, we import the required libraries:pandas — to process the datasklearn — for the SVM modelnumpy — for matrix and array manipulationmatplotlib.pyplot — for graph plotsimageio — to make GIFsos — to create folders and check their contents from sklearn.svm import SVC, LinearSVCimport pandas as pdimport numpy as npimport matplotlib.pyplot as pltfrom sklearn.model_selection import train_test_splitimport imageio as ioimport os Here, we read the data from a CSV file. The data is available on Kaggle. origdata = pd.read_csv("Iris.csv")origdata[:10] This dataset contains data about 3 species/subspecies of the Iris flower. Each sample has the length of the sepal, width of the sepal, the length of the petal and the width of the petal, all in centimetres. Each sample is of one of these three species — Iris setosa, Iris versicolor and Iris virginica. We choose two of the attributes (columns) from the dataset for performing active learning. We have taken two columns because it is easy to visualize 2D data. However, note that taking only 2 columns may not be better than taking all the columns for machine learning or active learning. k1, k2 = 'PetalLengthCm', 'PetalWidthCm'data = origdata[[k1, k2, 'Species']].copy()data[:10] For the training data, we take the two columns chosen earlier. The species column are the labels. We change the labels to 0 (for Iris-setosa), 1 (for Iris-versicolor) and 2 (for Iris-virginica). X = data[[k1, k2]]y = data['Species']print('Classes:')print(y.unique(), '\n\n\n')y[y=='Iris-setosa'] = 0y[y=='Iris-versicolor'] = 1y[y=='Iris-virginica'] = 2 Output: Classes:['Iris-setosa' 'Iris-versicolor' 'Iris-virginica'] We plot the samples of versicolor and virginica on a 2D graph with versicolor in red and virginica in cyan. plt.figure()setosa = y == 0versicolor = y == 1virginica = y == 2plt.scatter(X[k1][versicolor], X[k2][versicolor], c='r')plt.scatter(X[k1][virginica], X[k2][virginica], c='c')plt.xlabel(k1)plt.ylabel(k2)plt.show() Output: We discard the samples of Iris-setosa. X1 = X[y != 0]y1 = y[y != 0]X1[:5] Output: Then, we reset the indexes of the dataframes. X1 = X1.reset_index(drop=True)y1 = y1.reset_index(drop=True)y1 -= 1print(y1.unique())X1[:5] Output:[0 1] We plot the data on a 2D graph and save the figure as ‘main.jpg’. fig = plt.figure()plt.scatter(X1[k1][y1==0], X1[k2][y1==0], c='r')plt.scatter(X1[k1][y1==1], X1[k2][y1==1], c='c')plt.xlabel(k1)plt.ylabel(k2)fig.savefig('main.jpg', dpi=100)plt.show() We train a Linear SVM kernel on the entire data to understand the SVM model that we would get when using all the data. Since this is a linear SVM model, the decision boundary (the boundary separating the two classes) will be a straight line. We look at the slope and the intercept of the decision boundary. y1 = y1.astype(dtype=np.uint8)clf0 = LinearSVC()clf0.fit(X1, y1)LinearSVC(C=1.0, class_weight=None, dual=True, fit_intercept=True, intercept_scaling=1, loss='squared_hinge', max_iter=1000, multi_class='ovr', penalty='l2', random_state=None, tol=0.0001, verbose=0)print(clf0.coef_)print(clf0.intercept_) Outputs [[0.2801542 1.70097577]][-4.17110884] Here, we plot the decision boundary along with all the data points. The decision boundary is a straight line in this case (because the model is a Linear SVM). clf0 is the trained classifier (SVM). We get the coefficients from the clf0.coef_ and clf0.intercept. a0, b0, c0 are the coefficients of the line (Line Equation: a0*x + b0*y + c0 = 0; y = -(a0*x + c0)/b0). We get 100 points on this line (lx0- has the x-corrdinates; ly0- has the y-coordinates) and plot them (a magenta line). Let us call this the ideal decision boundary (this may not be the ideal decision boundary for all SVMs when we use different kinds of SVM kernels, but, it will indeed be a good decision boundary).Then, we plot all points in the dataset in cyan and red as per their classes. xmin, xmax = X1[k1].min(), X1[k1].max()ymin, ymax = X1[k2].min(), X1[k2].max()stepx = (xmax - xmin)/99stepy = (ymax - ymin)/99a0, b0, c0 = clf0.coef_[0, 0], clf0.coef_[0, 1], clf0.intercept_# Formula for reference# a*x + b*y + c = 0# y = -(a*x + c)/blx0 = [xmin + stepx * i for i in range(100)]ly0 = [-(a0*lx0[i] + c0)/b0 for i in range(100)]plt.figure()plt.scatter(X1[k1][y1==0], X1[k2][y1==0], c='r')plt.scatter(X1[k1][y1==1], X1[k2][y1==1], c='c')plt.plot(lx0, ly0, c='m')plt.xlabel(k1)plt.ylabel(k2)plt.show() Now, we split the dataset into two parts — pool(80%) and test(20%). We use a random state of 1. The split of the dataset is dependent on the random state.(I have done simulations for 5 iterations of active learning after a random state of 1 and for 20 iterations of the active learning algorithm after a random state of 2). X_pool, X_test, y_pool, y_test = train_test_split(X1, y1, test_size=0.2, random_state=1)X_pool, X_test, y_pool, y_test = X_pool.reset_index(drop=True), X_test.reset_index(drop=True), y_pool.reset_index(drop=True), y_test.reset_index(drop=True)# random state 1 5 iterations# random state 2 20 iterations Let us apply the decision function of the SVM on two data points. Generally, for a two-class linear SVM, the decision function outputs positive values for one of the classes (one side of the decision boundary) and negative values for the other class (other side of the decision boundary) and zero on the decision boundary. For a linear SVM, the magnitude of decision function is equal to the distance of the data point from the decision function. This is because, if a point is close to the decision boundary, then, it may be an outlier from the class on the other side of the decision boundary. clf0.decision_function(X_pool.iloc[6:8]) Outputs array([-0.55706427, 0.26340314]) Here, we see that the decision function has a negative value for one of the points and a positive value for the other point. The function find_most_ambiguous gives the point that is the most ambiguous for the classifier. For an SVM classifier, if a data point is closer to the decision boundary and less ambiguous if the data point is farther from the decision boundary no matter which side of the decision boundary the point is on. Thus, find_most_ambiguous, gives the unlabelled point that is the closest to the decision boundary.clf- classifier (trained SVM model); unknown_indexes- indexes from the dataset that are the unlabelled/unknown pool def find_most_ambiguous(clf, unknown_indexes): ind = np.argmin(np.abs( list(clf0.decision_function(X_pool.iloc[unknown_indexes]) ) )) return unknown_indexes[ind] The function, plot_svm, is used to plot the following:SVM decision boundary, the data points from the train data according to their class, and the data points in the unknown pool of samples.clf- classifier (trained SVM model).train_indexes- Indexes of the dataset that are the train data points.unknown_indexes- Indexes of the dataset that are the unlabelled pool data points.title- The title of the plot.name- the name of the image file that when the plot is saved to a file.new_index- This is the index of the most ambiguous point in the unlabelled pool In this function, first, we get the train data (X_train, y_train)and the unlabelled data (X_unk, y_unk) from the train_indexes and unknown_indexes, respectively.We plot all the unlabelled points from the pool in black. Then, we plot all the points from the train data in different colours (red and cyan) as per their class labels. We get the coefficients of the decision boundary (straight line) from the clf.coef_ and clf.intercept. Using this and the formula of a straight line, we plot this line (dashed green line). We also have the ideal decision boundary calculated earlier. This line is also plotted (in magenta).Finally, we plot the new_index point, that is, the most ambiguous point (yellow star). def plot_svm(clf, train_indexes, unknown_indexes, new_index = False, title = False, name = False): X_train = X_pool.iloc[train_indexes] y_train = y_pool.iloc[train_indexes] X_unk = X_pool.iloc[unknown_indexes] if new_index: X_new = X_pool.iloc[new_index] a, b, c = clf.coef_[0, 0], clf.coef_[0, 1], clf.intercept_ # Straight Line Formula # a*x + b*y + c = 0 # y = -(a*x + c)/b lx = [xmin + stepx * i for i in range(100)] ly = [-(a*lx[i] + c)/b for i in range(100)] fig = plt.figure(figsize=(9,6)) # plt.scatter(x[k1][setosa], x[k2][setosa], c='r') plt.scatter(X_unk[k1], X_unk[k2], c='k', marker = '.') plt.scatter(X_train[k1][y_train==0], X_train[k2][y_train==0], c='r', marker = 'o') plt.scatter(X_train[k1][y_train==1], X_train[k2][y_train==1], c='c', marker = 'o') plt.plot(lx, ly, c='m') plt.plot(lx0, ly0, '--', c='g') if new_index: plt.scatter(X_new[k1], X_new[k2], c='y', marker="*", s=125) plt.scatter(X_new[k1], X_new[k2], c='y', marker="*", s=125) plt.scatter(X_new[k1], X_new[k2], c='y', marker="*", s=125) plt.scatter(X_new[k1], X_new[k2], c='y', marker="*", s=125) plt.scatter(X_new[k1], X_new[k2], c='y', marker="*", s=125) if title: plt.title(title) plt.xlabel(k1) plt.ylabel(k2) if name: fig.set_size_inches((9,6)) plt.savefig(name, dpi=100) plt.show() We take the first 10 indexes/data points of the pool as the initial train data and the rest 70 points as the unlabelled samples. We create the beginning plot with all the unlabelled samples, the ideal decision boundary and the 10 train data points.Then, we train an SVM on the train data, and we find the most ambiguous point and create a new plot (“Iteration 0”) with this point as a yellow star and also plot the decision boundary of the trained SVM. train_indexes = list(range(10))unknown_indexes = list(range(10, 80))X_train = X_pool.iloc[train_indexes]y_train = y_pool.iloc[train_indexes]clf = LinearSVC()clf.fit(X_train, y_train)# folder = "rs1it5/"folder = "rs2it20/"# folder = "rs1it20/"try: os.mkdir(folder)except: passfilenames = ["ActiveLearningTitleSlide2.jpg"] * 2title = "Beginning"# name = folder + ("rs1it5_0a.jpg")name = folder + ("rs2it20_0a.jpg")plot_svm(clf, train_indexes, unknown_indexes, False, title, name)filenames.append(name)n = find_most_ambiguous(clf, unknown_indexes)unknown_indexes.remove(n)title = "Iteration 0"name = folder + ("rs1it5_0b.jpg")# name = folder + ("rs2it20_0b.jpg")filenames.append(name)plot_svm(clf, train_indexes, unknown_indexes, n, title, name) Next, we run the active learning algorithm for 5 iterations. In each of them, we add the most ambiguous point to the training data and train an SVM, find the most unambiguous point at this stage and then create a plot all this. num = 5# num = 20t = []for i in range(num): train_indexes.append(n) X_train = X_pool.iloc[train_indexes] y_train = y_pool.iloc[train_indexes] clf = LinearSVC() clf.fit(X_train, y_train) title, name = "Iteration "+str(i+1), folder + ("rs1it5_%d.jpg" % (i+1)) # title, name = "Iteration "+str(i+1), folder + ("rs2it20_%d.jpg" % (i+1)) n = find_most_ambiguous(clf, unknown_indexes) unknown_indexes.remove(n) plot_svm(clf, train_indexes, unknown_indexes, n, title, name) filenames.append(name) images = []for filename in filenames: images.append(io.imread(filename))io.mimsave('rs1it5.gif', images, duration = 1)# io.mimsave('rs2it20.gif', images, duration = 1)# io.mimsave('rs1it20.gif', images, duration = 1)try: os.mkdir('rs1it5')# os.mkdir('rt2it20')except: passos.listdir('rs1it5') Outputs ['ActiveLearningTitleSlide2.jpg', 'ActiveLearningTitleSlide2.jpg', 'rs1it5/rs1it5_0a.jpg', 'rs1it5/rs1it5_0b.jpg', 'rs1it5/rs1it5_1.jpg', 'rs1it5/rs1it5_2.jpg', 'rs1it5/rs1it5_3.jpg', 'rs1it5/rs1it5_4.jpg', 'rs1it5/rs1it5_5.jpg'] Now, we display the GIF file with open('rs1it5.gif','rb') as f: display(Image(data=f.read(), format='gif')) Note that in the above GIF, the green line comes close to the ideal decision boundary as we add more points (number of iterations). Kindly note that in some of the above code blocks and in the below code blocks, there are some commented lines with the number 20. This is for running 20 iterations instead of 5 iterations. To run this, we have to comment all of the lines with 5 and uncomment all of the lines with 20.We get the below GIF when we run 20 iterations of the active learning algorithm. Note that for this, we have used 2 as the random state while splitting the data into test and pool.Note that as the number of iterations increases in the GIF below, the green line comes closer and closer to the ideal decision boundary. Note that active leaning can be used with other machine learning/deep learning models (not just SVMs). Also, the initial ActiveLearningTitleSlide2.jpg is a simple image that I created in Paint with the same aspect ratio as the rest of the images (900x600). We see that we have trained a good classifier, that is, a classifier that would perform close to the SVM trained with all the points, although we have used a very small number of points. This is how active learning can be used to create robust models with labelling fewer data points. The entire code is available on GitHub You can have a look at my YouTube channel for videos explaining AI and ML concepts. Some rights reserved
[ { "code": null, "e": 211, "s": 47, "text": "Active learning is a machine learning technique in which we use less labelled data and interactively label new data points to improve the performance of the model." }, { "code": null, "e": 290, "s": 211, "text": "Terminology: Train dataset = Labelled data pointsPool = Unlabelled data points" }, { "code": null, "e": 659, "s": 290, "text": "We start with some labelled data points (train dataset). There is a large pool of unlabelled data points. These unlabelled data points have to be labelled and added to the train dataset to create the model. However, instead of labelling all the data points from the pool, we will label only a small number of them in active learning, but, still get a good performance." }, { "code": null, "e": 1046, "s": 659, "text": "We create a model (classifier) and train it on the labelled data. Then, we go through all the data points in the pool and identify the points that are most ambiguous for the classifier and add these points to the train data (We may add just a single point each time). We repeat this process to improve model performance. This technique is generally used when the labelling cost is high." }, { "code": null, "e": 1149, "s": 1046, "text": "I will soon be uploading a video on YouTube, explaining in detail the concepts behind active learning." }, { "code": null, "e": 1389, "s": 1149, "text": "Here, we import the required libraries:pandas — to process the datasklearn — for the SVM modelnumpy — for matrix and array manipulationmatplotlib.pyplot — for graph plotsimageio — to make GIFsos — to create folders and check their contents" }, { "code": null, "e": 1577, "s": 1389, "text": "from sklearn.svm import SVC, LinearSVCimport pandas as pdimport numpy as npimport matplotlib.pyplot as pltfrom sklearn.model_selection import train_test_splitimport imageio as ioimport os" }, { "code": null, "e": 1650, "s": 1577, "text": "Here, we read the data from a CSV file. The data is available on Kaggle." }, { "code": null, "e": 1698, "s": 1650, "text": "origdata = pd.read_csv(\"Iris.csv\")origdata[:10]" }, { "code": null, "e": 2001, "s": 1698, "text": "This dataset contains data about 3 species/subspecies of the Iris flower. Each sample has the length of the sepal, width of the sepal, the length of the petal and the width of the petal, all in centimetres. Each sample is of one of these three species — Iris setosa, Iris versicolor and Iris virginica." }, { "code": null, "e": 2287, "s": 2001, "text": "We choose two of the attributes (columns) from the dataset for performing active learning. We have taken two columns because it is easy to visualize 2D data. However, note that taking only 2 columns may not be better than taking all the columns for machine learning or active learning." }, { "code": null, "e": 2380, "s": 2287, "text": "k1, k2 = 'PetalLengthCm', 'PetalWidthCm'data = origdata[[k1, k2, 'Species']].copy()data[:10]" }, { "code": null, "e": 2575, "s": 2380, "text": "For the training data, we take the two columns chosen earlier. The species column are the labels. We change the labels to 0 (for Iris-setosa), 1 (for Iris-versicolor) and 2 (for Iris-virginica)." }, { "code": null, "e": 2733, "s": 2575, "text": "X = data[[k1, k2]]y = data['Species']print('Classes:')print(y.unique(), '\\n\\n\\n')y[y=='Iris-setosa'] = 0y[y=='Iris-versicolor'] = 1y[y=='Iris-virginica'] = 2" }, { "code": null, "e": 2741, "s": 2733, "text": "Output:" }, { "code": null, "e": 2800, "s": 2741, "text": "Classes:['Iris-setosa' 'Iris-versicolor' 'Iris-virginica']" }, { "code": null, "e": 2908, "s": 2800, "text": "We plot the samples of versicolor and virginica on a 2D graph with versicolor in red and virginica in cyan." }, { "code": null, "e": 3121, "s": 2908, "text": "plt.figure()setosa = y == 0versicolor = y == 1virginica = y == 2plt.scatter(X[k1][versicolor], X[k2][versicolor], c='r')plt.scatter(X[k1][virginica], X[k2][virginica], c='c')plt.xlabel(k1)plt.ylabel(k2)plt.show()" }, { "code": null, "e": 3129, "s": 3121, "text": "Output:" }, { "code": null, "e": 3168, "s": 3129, "text": "We discard the samples of Iris-setosa." }, { "code": null, "e": 3203, "s": 3168, "text": "X1 = X[y != 0]y1 = y[y != 0]X1[:5]" }, { "code": null, "e": 3211, "s": 3203, "text": "Output:" }, { "code": null, "e": 3257, "s": 3211, "text": "Then, we reset the indexes of the dataframes." }, { "code": null, "e": 3349, "s": 3257, "text": "X1 = X1.reset_index(drop=True)y1 = y1.reset_index(drop=True)y1 -= 1print(y1.unique())X1[:5]" }, { "code": null, "e": 3362, "s": 3349, "text": "Output:[0 1]" }, { "code": null, "e": 3428, "s": 3362, "text": "We plot the data on a 2D graph and save the figure as ‘main.jpg’." }, { "code": null, "e": 3614, "s": 3428, "text": "fig = plt.figure()plt.scatter(X1[k1][y1==0], X1[k2][y1==0], c='r')plt.scatter(X1[k1][y1==1], X1[k2][y1==1], c='c')plt.xlabel(k1)plt.ylabel(k2)fig.savefig('main.jpg', dpi=100)plt.show() " }, { "code": null, "e": 3921, "s": 3614, "text": "We train a Linear SVM kernel on the entire data to understand the SVM model that we would get when using all the data. Since this is a linear SVM model, the decision boundary (the boundary separating the two classes) will be a straight line. We look at the slope and the intercept of the decision boundary." }, { "code": null, "e": 4251, "s": 3921, "text": "y1 = y1.astype(dtype=np.uint8)clf0 = LinearSVC()clf0.fit(X1, y1)LinearSVC(C=1.0, class_weight=None, dual=True, fit_intercept=True, intercept_scaling=1, loss='squared_hinge', max_iter=1000, multi_class='ovr', penalty='l2', random_state=None, tol=0.0001, verbose=0)print(clf0.coef_)print(clf0.intercept_)" }, { "code": null, "e": 4259, "s": 4251, "text": "Outputs" }, { "code": null, "e": 4298, "s": 4259, "text": "[[0.2801542 1.70097577]][-4.17110884]" }, { "code": null, "e": 5057, "s": 4298, "text": "Here, we plot the decision boundary along with all the data points. The decision boundary is a straight line in this case (because the model is a Linear SVM). clf0 is the trained classifier (SVM). We get the coefficients from the clf0.coef_ and clf0.intercept. a0, b0, c0 are the coefficients of the line (Line Equation: a0*x + b0*y + c0 = 0; y = -(a0*x + c0)/b0). We get 100 points on this line (lx0- has the x-corrdinates; ly0- has the y-coordinates) and plot them (a magenta line). Let us call this the ideal decision boundary (this may not be the ideal decision boundary for all SVMs when we use different kinds of SVM kernels, but, it will indeed be a good decision boundary).Then, we plot all points in the dataset in cyan and red as per their classes." }, { "code": null, "e": 5571, "s": 5057, "text": "xmin, xmax = X1[k1].min(), X1[k1].max()ymin, ymax = X1[k2].min(), X1[k2].max()stepx = (xmax - xmin)/99stepy = (ymax - ymin)/99a0, b0, c0 = clf0.coef_[0, 0], clf0.coef_[0, 1], clf0.intercept_# Formula for reference# a*x + b*y + c = 0# y = -(a*x + c)/blx0 = [xmin + stepx * i for i in range(100)]ly0 = [-(a0*lx0[i] + c0)/b0 for i in range(100)]plt.figure()plt.scatter(X1[k1][y1==0], X1[k2][y1==0], c='r')plt.scatter(X1[k1][y1==1], X1[k2][y1==1], c='c')plt.plot(lx0, ly0, c='m')plt.xlabel(k1)plt.ylabel(k2)plt.show()" }, { "code": null, "e": 5895, "s": 5571, "text": "Now, we split the dataset into two parts — pool(80%) and test(20%). We use a random state of 1. The split of the dataset is dependent on the random state.(I have done simulations for 5 iterations of active learning after a random state of 1 and for 20 iterations of the active learning algorithm after a random state of 2)." }, { "code": null, "e": 6198, "s": 5895, "text": "X_pool, X_test, y_pool, y_test = train_test_split(X1, y1, test_size=0.2, random_state=1)X_pool, X_test, y_pool, y_test = X_pool.reset_index(drop=True), X_test.reset_index(drop=True), y_pool.reset_index(drop=True), y_test.reset_index(drop=True)# random state 1 5 iterations# random state 2 20 iterations" }, { "code": null, "e": 6794, "s": 6198, "text": "Let us apply the decision function of the SVM on two data points. Generally, for a two-class linear SVM, the decision function outputs positive values for one of the classes (one side of the decision boundary) and negative values for the other class (other side of the decision boundary) and zero on the decision boundary. For a linear SVM, the magnitude of decision function is equal to the distance of the data point from the decision function. This is because, if a point is close to the decision boundary, then, it may be an outlier from the class on the other side of the decision boundary." }, { "code": null, "e": 6835, "s": 6794, "text": "clf0.decision_function(X_pool.iloc[6:8])" }, { "code": null, "e": 6843, "s": 6835, "text": "Outputs" }, { "code": null, "e": 6877, "s": 6843, "text": "array([-0.55706427, 0.26340314])" }, { "code": null, "e": 7002, "s": 6877, "text": "Here, we see that the decision function has a negative value for one of the points and a positive value for the other point." }, { "code": null, "e": 7525, "s": 7002, "text": "The function find_most_ambiguous gives the point that is the most ambiguous for the classifier. For an SVM classifier, if a data point is closer to the decision boundary and less ambiguous if the data point is farther from the decision boundary no matter which side of the decision boundary the point is on. Thus, find_most_ambiguous, gives the unlabelled point that is the closest to the decision boundary.clf- classifier (trained SVM model); unknown_indexes- indexes from the dataset that are the unlabelled/unknown pool" }, { "code": null, "e": 7712, "s": 7525, "text": "def find_most_ambiguous(clf, unknown_indexes): ind = np.argmin(np.abs( list(clf0.decision_function(X_pool.iloc[unknown_indexes]) ) )) return unknown_indexes[ind]" }, { "code": null, "e": 8268, "s": 7712, "text": "The function, plot_svm, is used to plot the following:SVM decision boundary, the data points from the train data according to their class, and the data points in the unknown pool of samples.clf- classifier (trained SVM model).train_indexes- Indexes of the dataset that are the train data points.unknown_indexes- Indexes of the dataset that are the unlabelled pool data points.title- The title of the plot.name- the name of the image file that when the plot is saved to a file.new_index- This is the index of the most ambiguous point in the unlabelled pool" }, { "code": null, "e": 8975, "s": 8268, "text": "In this function, first, we get the train data (X_train, y_train)and the unlabelled data (X_unk, y_unk) from the train_indexes and unknown_indexes, respectively.We plot all the unlabelled points from the pool in black. Then, we plot all the points from the train data in different colours (red and cyan) as per their class labels. We get the coefficients of the decision boundary (straight line) from the clf.coef_ and clf.intercept. Using this and the formula of a straight line, we plot this line (dashed green line). We also have the ideal decision boundary calculated earlier. This line is also plotted (in magenta).Finally, we plot the new_index point, that is, the most ambiguous point (yellow star)." }, { "code": null, "e": 10385, "s": 8975, "text": "def plot_svm(clf, train_indexes, unknown_indexes, new_index = False, title = False, name = False): X_train = X_pool.iloc[train_indexes] y_train = y_pool.iloc[train_indexes] X_unk = X_pool.iloc[unknown_indexes] if new_index: X_new = X_pool.iloc[new_index] a, b, c = clf.coef_[0, 0], clf.coef_[0, 1], clf.intercept_ # Straight Line Formula # a*x + b*y + c = 0 # y = -(a*x + c)/b lx = [xmin + stepx * i for i in range(100)] ly = [-(a*lx[i] + c)/b for i in range(100)] fig = plt.figure(figsize=(9,6)) # plt.scatter(x[k1][setosa], x[k2][setosa], c='r') plt.scatter(X_unk[k1], X_unk[k2], c='k', marker = '.') plt.scatter(X_train[k1][y_train==0], X_train[k2][y_train==0], c='r', marker = 'o') plt.scatter(X_train[k1][y_train==1], X_train[k2][y_train==1], c='c', marker = 'o') plt.plot(lx, ly, c='m') plt.plot(lx0, ly0, '--', c='g') if new_index: plt.scatter(X_new[k1], X_new[k2], c='y', marker=\"*\", s=125) plt.scatter(X_new[k1], X_new[k2], c='y', marker=\"*\", s=125) plt.scatter(X_new[k1], X_new[k2], c='y', marker=\"*\", s=125) plt.scatter(X_new[k1], X_new[k2], c='y', marker=\"*\", s=125) plt.scatter(X_new[k1], X_new[k2], c='y', marker=\"*\", s=125) if title: plt.title(title) plt.xlabel(k1) plt.ylabel(k2) if name: fig.set_size_inches((9,6)) plt.savefig(name, dpi=100) plt.show()" }, { "code": null, "e": 10838, "s": 10385, "text": "We take the first 10 indexes/data points of the pool as the initial train data and the rest 70 points as the unlabelled samples. We create the beginning plot with all the unlabelled samples, the ideal decision boundary and the 10 train data points.Then, we train an SVM on the train data, and we find the most ambiguous point and create a new plot (“Iteration 0”) with this point as a yellow star and also plot the decision boundary of the trained SVM." }, { "code": null, "e": 11587, "s": 10838, "text": "train_indexes = list(range(10))unknown_indexes = list(range(10, 80))X_train = X_pool.iloc[train_indexes]y_train = y_pool.iloc[train_indexes]clf = LinearSVC()clf.fit(X_train, y_train)# folder = \"rs1it5/\"folder = \"rs2it20/\"# folder = \"rs1it20/\"try: os.mkdir(folder)except: passfilenames = [\"ActiveLearningTitleSlide2.jpg\"] * 2title = \"Beginning\"# name = folder + (\"rs1it5_0a.jpg\")name = folder + (\"rs2it20_0a.jpg\")plot_svm(clf, train_indexes, unknown_indexes, False, title, name)filenames.append(name)n = find_most_ambiguous(clf, unknown_indexes)unknown_indexes.remove(n)title = \"Iteration 0\"name = folder + (\"rs1it5_0b.jpg\")# name = folder + (\"rs2it20_0b.jpg\")filenames.append(name)plot_svm(clf, train_indexes, unknown_indexes, n, title, name)" }, { "code": null, "e": 11815, "s": 11587, "text": "Next, we run the active learning algorithm for 5 iterations. In each of them, we add the most ambiguous point to the training data and train an SVM, find the most unambiguous point at this stage and then create a plot all this." }, { "code": null, "e": 12342, "s": 11815, "text": "num = 5# num = 20t = []for i in range(num): train_indexes.append(n) X_train = X_pool.iloc[train_indexes] y_train = y_pool.iloc[train_indexes] clf = LinearSVC() clf.fit(X_train, y_train) title, name = \"Iteration \"+str(i+1), folder + (\"rs1it5_%d.jpg\" % (i+1)) # title, name = \"Iteration \"+str(i+1), folder + (\"rs2it20_%d.jpg\" % (i+1)) n = find_most_ambiguous(clf, unknown_indexes) unknown_indexes.remove(n) plot_svm(clf, train_indexes, unknown_indexes, n, title, name) filenames.append(name)" }, { "code": null, "e": 12647, "s": 12342, "text": "images = []for filename in filenames: images.append(io.imread(filename))io.mimsave('rs1it5.gif', images, duration = 1)# io.mimsave('rs2it20.gif', images, duration = 1)# io.mimsave('rs1it20.gif', images, duration = 1)try: os.mkdir('rs1it5')# os.mkdir('rt2it20')except: passos.listdir('rs1it5')" }, { "code": null, "e": 12655, "s": 12647, "text": "Outputs" }, { "code": null, "e": 12885, "s": 12655, "text": "['ActiveLearningTitleSlide2.jpg', 'ActiveLearningTitleSlide2.jpg', 'rs1it5/rs1it5_0a.jpg', 'rs1it5/rs1it5_0b.jpg', 'rs1it5/rs1it5_1.jpg', 'rs1it5/rs1it5_2.jpg', 'rs1it5/rs1it5_3.jpg', 'rs1it5/rs1it5_4.jpg', 'rs1it5/rs1it5_5.jpg']" }, { "code": null, "e": 12914, "s": 12885, "text": "Now, we display the GIF file" }, { "code": null, "e": 12996, "s": 12914, "text": "with open('rs1it5.gif','rb') as f: display(Image(data=f.read(), format='gif'))" }, { "code": null, "e": 13128, "s": 12996, "text": "Note that in the above GIF, the green line comes close to the ideal decision boundary as we add more points (number of iterations)." }, { "code": null, "e": 13730, "s": 13128, "text": "Kindly note that in some of the above code blocks and in the below code blocks, there are some commented lines with the number 20. This is for running 20 iterations instead of 5 iterations. To run this, we have to comment all of the lines with 5 and uncomment all of the lines with 20.We get the below GIF when we run 20 iterations of the active learning algorithm. Note that for this, we have used 2 as the random state while splitting the data into test and pool.Note that as the number of iterations increases in the GIF below, the green line comes closer and closer to the ideal decision boundary." }, { "code": null, "e": 13987, "s": 13730, "text": "Note that active leaning can be used with other machine learning/deep learning models (not just SVMs). Also, the initial ActiveLearningTitleSlide2.jpg is a simple image that I created in Paint with the same aspect ratio as the rest of the images (900x600)." }, { "code": null, "e": 14272, "s": 13987, "text": "We see that we have trained a good classifier, that is, a classifier that would perform close to the SVM trained with all the points, although we have used a very small number of points. This is how active learning can be used to create robust models with labelling fewer data points." }, { "code": null, "e": 14311, "s": 14272, "text": "The entire code is available on GitHub" }, { "code": null, "e": 14395, "s": 14311, "text": "You can have a look at my YouTube channel for videos explaining AI and ML concepts." } ]
Java Program to Reverse a String using Stack - GeeksforGeeks
21 Oct, 2020 The Stack is a linear data structure that follows the LIFO(Last In First Out) principle, i.e, the element inserted at the last is the element to come out first. Approach: Push the character one by one into the Stack of datatype character.Pop the character one by one from the Stack until the stack becomes empty.Add a popped element to the character array.Convert character array to string.Return reversed string. Push the character one by one into the Stack of datatype character. Pop the character one by one from the Stack until the stack becomes empty. Add a popped element to the character array. Convert character array to string. Return reversed string. Below is the implementation of the above approach. Java // Java Program to Reverse a String using Stack import java.io.*;import java.util.*; class GFG { public static String ReverseString(String str) { char[] reverseString = new char[str.length()]; // Declare a stack of type Character Stack<Character> stack = new Stack<Character>(); // Traverse the String and push the character one by // one into the Stack for (int i = 0; i < str.length(); i++) { // push the character into the Stack stack.push(str.charAt(i)); } // Now Pop the Characters from the stack until it // becomes empty int i = 0; while (!stack.isEmpty()) { // popping element until // stack become empty // get the character from the top of the stack reverseString[i++] = stack.pop(); } // return string object return new String(reverseString); } // Driver code public static void main(String[] args) { String str1 = "GeeksForGeeks"; // call the function System.out.println(str1 + " <- Reverse -> " + ReverseString(str1)); String str2 = "Hello World"; // call the function System.out.println(str2 + " <- Reverse -> " + ReverseString(str2)); }} GeeksForGeeks <- Reverse -> skeeGroFskeeG Hello World <- Reverse -> dlroW olleH Time Complexity: O(n), where n is a number of characters in the stack. Auxiliary Space: O(n) for the stack. Java-String-Programs Java Java Programs Stack Stack Java Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Stream In Java Different ways of Reading a text file in Java Constructors in Java Exceptions in Java Functional Interfaces in Java Convert a String to Character array in Java Java Programming Examples Convert Double to Integer in Java Implementing a Linked List in Java using Class How to Iterate HashMap in Java?
[ { "code": null, "e": 24050, "s": 24022, "text": "\n21 Oct, 2020" }, { "code": null, "e": 24211, "s": 24050, "text": "The Stack is a linear data structure that follows the LIFO(Last In First Out) principle, i.e, the element inserted at the last is the element to come out first." }, { "code": null, "e": 24221, "s": 24211, "text": "Approach:" }, { "code": null, "e": 24464, "s": 24221, "text": "Push the character one by one into the Stack of datatype character.Pop the character one by one from the Stack until the stack becomes empty.Add a popped element to the character array.Convert character array to string.Return reversed string." }, { "code": null, "e": 24532, "s": 24464, "text": "Push the character one by one into the Stack of datatype character." }, { "code": null, "e": 24607, "s": 24532, "text": "Pop the character one by one from the Stack until the stack becomes empty." }, { "code": null, "e": 24652, "s": 24607, "text": "Add a popped element to the character array." }, { "code": null, "e": 24687, "s": 24652, "text": "Convert character array to string." }, { "code": null, "e": 24711, "s": 24687, "text": "Return reversed string." }, { "code": null, "e": 24762, "s": 24711, "text": "Below is the implementation of the above approach." }, { "code": null, "e": 24767, "s": 24762, "text": "Java" }, { "code": "// Java Program to Reverse a String using Stack import java.io.*;import java.util.*; class GFG { public static String ReverseString(String str) { char[] reverseString = new char[str.length()]; // Declare a stack of type Character Stack<Character> stack = new Stack<Character>(); // Traverse the String and push the character one by // one into the Stack for (int i = 0; i < str.length(); i++) { // push the character into the Stack stack.push(str.charAt(i)); } // Now Pop the Characters from the stack until it // becomes empty int i = 0; while (!stack.isEmpty()) { // popping element until // stack become empty // get the character from the top of the stack reverseString[i++] = stack.pop(); } // return string object return new String(reverseString); } // Driver code public static void main(String[] args) { String str1 = \"GeeksForGeeks\"; // call the function System.out.println(str1 + \" <- Reverse -> \" + ReverseString(str1)); String str2 = \"Hello World\"; // call the function System.out.println(str2 + \" <- Reverse -> \" + ReverseString(str2)); }}", "e": 26147, "s": 24767, "text": null }, { "code": null, "e": 26228, "s": 26147, "text": "GeeksForGeeks <- Reverse -> skeeGroFskeeG\nHello World <- Reverse -> dlroW olleH\n" }, { "code": null, "e": 26299, "s": 26228, "text": "Time Complexity: O(n), where n is a number of characters in the stack." }, { "code": null, "e": 26336, "s": 26299, "text": "Auxiliary Space: O(n) for the stack." }, { "code": null, "e": 26357, "s": 26336, "text": "Java-String-Programs" }, { "code": null, "e": 26362, "s": 26357, "text": "Java" }, { "code": null, "e": 26376, "s": 26362, "text": "Java Programs" }, { "code": null, "e": 26382, "s": 26376, "text": "Stack" }, { "code": null, "e": 26388, "s": 26382, "text": "Stack" }, { "code": null, "e": 26393, "s": 26388, "text": "Java" }, { "code": null, "e": 26491, "s": 26393, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 26506, "s": 26491, "text": "Stream In Java" }, { "code": null, "e": 26552, "s": 26506, "text": "Different ways of Reading a text file in Java" }, { "code": null, "e": 26573, "s": 26552, "text": "Constructors in Java" }, { "code": null, "e": 26592, "s": 26573, "text": "Exceptions in Java" }, { "code": null, "e": 26622, "s": 26592, "text": "Functional Interfaces in Java" }, { "code": null, "e": 26666, "s": 26622, "text": "Convert a String to Character array in Java" }, { "code": null, "e": 26692, "s": 26666, "text": "Java Programming Examples" }, { "code": null, "e": 26726, "s": 26692, "text": "Convert Double to Integer in Java" }, { "code": null, "e": 26773, "s": 26726, "text": "Implementing a Linked List in Java using Class" } ]
Sort elements by frequency | Set 1 - GeeksforGeeks
20 Jan, 2022 Print the elements of an array in the decreasing frequency if 2 numbers have same frequency then print the one which came first. Examples: Input: arr[] = {2, 5, 2, 8, 5, 6, 8, 8} Output: arr[] = {8, 8, 8, 2, 2, 5, 5, 6} Input: arr[] = {2, 5, 2, 6, -1, 9999999, 5, 8, 8, 8} Output: arr[] = {8, 8, 8, 2, 2, 5, 5, 6, -1, 9999999} METHOD 1 (Use Sorting) Use a sorting algorithm to sort the elements O(nlogn) Scan the sorted array and construct a 2D array of element and count O(n). Sort the 2D array according to count O(nlogn). Example: Input 2 5 2 8 5 6 8 8 After sorting we get 2 2 5 5 6 8 8 8 Now construct the 2D array as 2, 2 5, 2 6, 1 8, 3 Sort by count 8, 3 2, 2 5, 2 6, 1 How to maintain the order of elements if the frequency is the same? Chapters descriptions off, selected captions settings, opens captions settings dialog captions off, selected English This is a modal window. Beginning of dialog window. Escape will cancel and close the window. End of dialog window. The above approach doesn’t make sure order of elements if the frequency is the same. To handle this, we should use indexes in step 3, if two counts are same then we should first process(or print) the element with a lower index. In step 1, we should store the indexes instead of elements. Input 2 5 2 8 5 6 8 8 After sorting we get Element 2 2 5 5 6 8 8 8 Index 0 2 1 4 5 3 6 7 Now construct the 2D array as Index, Count 0, 2 1, 2 5, 1 3, 3 Sort by count (consider indexes in case of tie) 3, 3 0, 2 1, 2 5, 1 Print the elements using indexes in the above 2D array. Below is the implementation of above approach – CPP // Sort elements by frequency. If two elements have same// count, then put the elements that appears first#include <bits/stdc++.h>using namespace std; // Used for sortingstruct ele { int count, index, val;}; // Used for sorting by valuebool mycomp(struct ele a, struct ele b){ return (a.val < b.val);} // Used for sorting by frequency. And if frequency is same,// then by appearancebool mycomp2(struct ele a, struct ele b){ if (a.count != b.count) return (a.count < b.count); else return a.index > b.index;} void sortByFrequency(int arr[], int n){ struct ele element[n]; for (int i = 0; i < n; i++) { // Fill Indexes element[i].index = i; // Initialize counts as 0 element[i].count = 0; // Fill values in structure // elements element[i].val = arr[i]; } /* Sort the structure elements according to value, we used stable sort so relative order is maintained. */ stable_sort(element, element + n, mycomp); /* initialize count of first element as 1 */ element[0].count = 1; /* Count occurrences of remaining elements */ for (int i = 1; i < n; i++) { if (element[i].val == element[i - 1].val) { element[i].count += element[i - 1].count + 1; /* Set count of previous element as -1, we are doing this because we'll again sort on the basis of counts (if counts are equal than on the basis of index)*/ element[i - 1].count = -1; /* Retain the first index (Remember first index is always present in the first duplicate we used stable sort. */ element[i].index = element[i - 1].index; } /* Else If previous element is not equal to current so set the count to 1 */ else element[i].count = 1; } /* Now we have counts and first index for each element so now sort on the basis of count and in case of tie use index to sort.*/ stable_sort(element, element + n, mycomp2); for (int i = n - 1, index = 0; i >= 0; i--) if (element[i].count != -1) for (int j = 0; j < element[i].count; j++) arr[index++] = element[i].val;} // Driver programint main(){ int arr[] = { 2, 5, 2, 6, -1, 9999999, 5, 8, 8, 8 }; int n = sizeof(arr) / sizeof(arr[0]); sortByFrequency(arr, n); for (int i = 0; i < n; i++) cout << arr[i] << " "; return 0;} Output: 8 8 8 2 2 5 5 6 -1 9999999 Thanks to Gaurav Ahirwar for providing above implementation. METHOD 2 (Use Hashing and Sorting) Using a hashing mechanism, we can store the elements (also first index) and their counts in a hash. Finally, sort the hash elements according to their counts.Below is the implementation of above approach – CPP Java Python3 Javascript // CPP program for above approach#include <bits/stdc++.h>using namespace std; // Compare functionbool fcompare(pair<int, pair<int, int> > p, pair<int, pair<int, int> > p1){ if (p.second.second != p1.second.second) return (p.second.second > p1.second.second); else return (p.second.first < p1.second.first);}void sortByFrequency(int arr[], int n){ unordered_map<int, pair<int, int> > hash; // hash map for (int i = 0; i < n; i++) { if (hash.find(arr[i]) != hash.end()) hash[arr[i]].second++; else hash[arr[i]] = make_pair(i, 1); } // store the count of all the elements in the hashmap // Iterator to Traverse the Hashmap auto it = hash.begin(); // Vector to store the Final Sortted order vector<pair<int, pair<int, int> > > b; for (it; it != hash.end(); ++it) b.push_back(make_pair(it->first, it->second)); sort(b.begin(), b.end(), fcompare); // Printing the Sorted sequence for (int i = 0; i < b.size(); i++) { int count = b[i].second.second; while (count--) cout << b[i].first << " "; }} // Driver Functionint main(){ int arr[] = { 2, 5, 2, 6, -1, 9999999, 5, 8, 8, 8 }; int n = sizeof(arr) / sizeof(arr[0]); sortByFrequency(arr, n); return 0;} /*package whatever //do not write package name here */import java.util.Arrays;import java.util.Collections;import java.util.Comparator;import java.util.HashMap;import java.util.List;class GFG { static Integer[] arr = { 2, 5, 2, 8, 5, 6, 8, 8 }; // Driver Code public static void main(String[] args) { List<Integer> list = Arrays.asList(arr); sortBasedOnFrequencyAndValue(list); } // Compare Function public static void sortBasedOnFrequencyAndValue(List<Integer> list) { int n = arr.length; final HashMap<Integer, Integer> mapCount = new HashMap<Integer, Integer>(); final HashMap<Integer, Integer> mapIndex = new HashMap<Integer, Integer>(); for (int i = 0; i < n; i++) { if (mapCount.containsKey(arr[i])) { mapCount.put(arr[i], mapCount.get(arr[i]) + 1); } else { mapCount.put(arr[i],1); // Map to capture Count of elements mapIndex.put(arr[i],i); // Map to capture 1st occurrence of elements } } Collections.sort(list, new Comparator<Integer>() { public int compare(Integer n1, Integer n2) { int freq1 = mapCount.get(n1); int freq2 = mapCount.get(n2); if (freq1 != freq2) { return freq2 - freq1; } else { return mapIndex.get(n1) - mapIndex.get( n2); // Elements with Lesser // Index gets Higher // Priority } } }); System.out.println(list); }} # Python program for above approach from collections import defaultdict # Sort by Frequency def sortByFreq(arr, n): # arr -> Array to be sorted # n -> Length of Array # d is a hashmap(referred as dictionary in python) d = defaultdict(lambda: 0) for i in range(n): d[arr[i]] += 1 # Sorting the array 'arr' where key # is the function based on which # the array is sorted # While sorting we want to give # first priority to Frequency # Then to value of item arr.sort(key=lambda x: (-d[x], x)) return (arr) # Driver Functionif __name__ == "__main__": arr = [2, 5, 2, 6, -1, 9999999, 5, 8, 8, 8] n = len(arr) solution = sortByFreq(arr, n) print(*solution) <script> let arr=[2, 5, 2, 6, -1, 9999999, 5, 8, 8, 8]; // Compare Functionfunction sortBasedOnFrequencyAndValue(list){ let n = arr.length; let mapCount = new Map(); let mapIndex = new Map(); for (let i = 0; i < n; i++) { if (mapCount.has(arr[i])) { mapCount.set(arr[i], mapCount.get(arr[i]) + 1); } else { mapCount.set(arr[i],1); // Map to capture Count of elements mapIndex.set(arr[i],i); // Map to capture 1st occurrence of elements } } list.sort(function(n1,n2){ let freq1 = mapCount.get(n1); let freq2 = mapCount.get(n2); if (freq1 != freq2) { return freq2 - freq1; } else { return mapIndex.get(n1) - mapIndex.get( n2); // Elements with Lesser // Index gets Higher // Priority } }); document.write(list.join(" "));} // Driver CodesortBasedOnFrequencyAndValue(arr); // This code is contributed by patel2127</script> Output: 8 8 8 2 2 5 5 6 -1 9999999 This can also be solved by Using two maps, one for array element as an index and after this second map whose keys are frequency and value are array elements. METHOD 3(Use BST and Sorting) Insert elements in BST one by one and if an element is already present then increment the count of the node. Node of the Binary Search Tree (used in this approach) will be as follows. C Java C# struct tree { int element; int first_index /*To handle ties in counts*/ int count;} BST;</div> static class tree { int element; int first_index; /*To handle ties in counts*/ int count;}tree BST = new tree(); // This code is contributed by gauravrajput1 public class tree { public int element; public int first_index; /* To handle ties in counts */ public int count;}tree BST = new tree(); // This code is contributed by gauravrajput1 Store the first indexes and corresponding counts of BST in a 2D array. Sort the 2D array according to counts (and use indexes in case of tie). Time Complexity: O(nlogn) if a Self Balancing Binary Search Tree is used. This is implemented in Set 2. https://youtu.be/NBXf9vCksuM Set 2: Sort elements by frequency | Set 2Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above praveenjain6407 anumoluhemanth ahmadzaidju Koushik222 ayushagrawal99 shivagarg prithicogni89 patel2127 nisanth2590 GauravRajput1 Amazon Oracle Zoho Zycus Arrays Sorting Zoho Amazon Oracle Zycus Arrays Sorting Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Introduction to Arrays Multidimensional Arrays in Java Linked List vs Array Python | Using 2D arrays/lists the right way Search an element in a sorted and rotated array
[ { "code": null, "e": 25809, "s": 25781, "text": "\n20 Jan, 2022" }, { "code": null, "e": 25939, "s": 25809, "text": "Print the elements of an array in the decreasing frequency if 2 numbers have same frequency then print the one which came first. " }, { "code": null, "e": 25951, "s": 25939, "text": "Examples: " }, { "code": null, "e": 26141, "s": 25951, "text": "Input: arr[] = {2, 5, 2, 8, 5, 6, 8, 8}\nOutput: arr[] = {8, 8, 8, 2, 2, 5, 5, 6}\n\nInput: arr[] = {2, 5, 2, 6, -1, 9999999, 5, 8, 8, 8}\nOutput: arr[] = {8, 8, 8, 2, 2, 5, 5, 6, -1, 9999999}" }, { "code": null, "e": 26165, "s": 26141, "text": "METHOD 1 (Use Sorting) " }, { "code": null, "e": 26219, "s": 26165, "text": "Use a sorting algorithm to sort the elements O(nlogn)" }, { "code": null, "e": 26293, "s": 26219, "text": "Scan the sorted array and construct a 2D array of element and count O(n)." }, { "code": null, "e": 26340, "s": 26293, "text": "Sort the 2D array according to count O(nlogn)." }, { "code": null, "e": 26351, "s": 26340, "text": "Example: " }, { "code": null, "e": 26523, "s": 26351, "text": " Input 2 5 2 8 5 6 8 8\n\n After sorting we get\n 2 2 5 5 6 8 8 8\n\n Now construct the 2D array as\n 2, 2\n 5, 2\n 6, 1\n 8, 3\n\n Sort by count\n 8, 3\n 2, 2\n 5, 2\n 6, 1" }, { "code": null, "e": 26591, "s": 26523, "text": "How to maintain the order of elements if the frequency is the same?" }, { "code": null, "e": 26600, "s": 26591, "text": "Chapters" }, { "code": null, "e": 26627, "s": 26600, "text": "descriptions off, selected" }, { "code": null, "e": 26677, "s": 26627, "text": "captions settings, opens captions settings dialog" }, { "code": null, "e": 26700, "s": 26677, "text": "captions off, selected" }, { "code": null, "e": 26708, "s": 26700, "text": "English" }, { "code": null, "e": 26732, "s": 26708, "text": "This is a modal window." }, { "code": null, "e": 26801, "s": 26732, "text": "Beginning of dialog window. Escape will cancel and close the window." }, { "code": null, "e": 26823, "s": 26801, "text": "End of dialog window." }, { "code": null, "e": 27112, "s": 26823, "text": "The above approach doesn’t make sure order of elements if the frequency is the same. To handle this, we should use indexes in step 3, if two counts are same then we should first process(or print) the element with a lower index. In step 1, we should store the indexes instead of elements. " }, { "code": null, "e": 27457, "s": 27112, "text": " Input 2 5 2 8 5 6 8 8\n\n After sorting we get\n Element 2 2 5 5 6 8 8 8\n Index 0 2 1 4 5 3 6 7\n\n Now construct the 2D array as\n Index, Count\n 0, 2\n 1, 2\n 5, 1\n 3, 3\n\n Sort by count (consider indexes in case of tie)\n 3, 3\n 0, 2\n 1, 2\n 5, 1\n \n Print the elements using indexes in the above 2D array." }, { "code": null, "e": 27505, "s": 27457, "text": "Below is the implementation of above approach –" }, { "code": null, "e": 27509, "s": 27505, "text": "CPP" }, { "code": "// Sort elements by frequency. If two elements have same// count, then put the elements that appears first#include <bits/stdc++.h>using namespace std; // Used for sortingstruct ele { int count, index, val;}; // Used for sorting by valuebool mycomp(struct ele a, struct ele b){ return (a.val < b.val);} // Used for sorting by frequency. And if frequency is same,// then by appearancebool mycomp2(struct ele a, struct ele b){ if (a.count != b.count) return (a.count < b.count); else return a.index > b.index;} void sortByFrequency(int arr[], int n){ struct ele element[n]; for (int i = 0; i < n; i++) { // Fill Indexes element[i].index = i; // Initialize counts as 0 element[i].count = 0; // Fill values in structure // elements element[i].val = arr[i]; } /* Sort the structure elements according to value, we used stable sort so relative order is maintained. */ stable_sort(element, element + n, mycomp); /* initialize count of first element as 1 */ element[0].count = 1; /* Count occurrences of remaining elements */ for (int i = 1; i < n; i++) { if (element[i].val == element[i - 1].val) { element[i].count += element[i - 1].count + 1; /* Set count of previous element as -1, we are doing this because we'll again sort on the basis of counts (if counts are equal than on the basis of index)*/ element[i - 1].count = -1; /* Retain the first index (Remember first index is always present in the first duplicate we used stable sort. */ element[i].index = element[i - 1].index; } /* Else If previous element is not equal to current so set the count to 1 */ else element[i].count = 1; } /* Now we have counts and first index for each element so now sort on the basis of count and in case of tie use index to sort.*/ stable_sort(element, element + n, mycomp2); for (int i = n - 1, index = 0; i >= 0; i--) if (element[i].count != -1) for (int j = 0; j < element[i].count; j++) arr[index++] = element[i].val;} // Driver programint main(){ int arr[] = { 2, 5, 2, 6, -1, 9999999, 5, 8, 8, 8 }; int n = sizeof(arr) / sizeof(arr[0]); sortByFrequency(arr, n); for (int i = 0; i < n; i++) cout << arr[i] << \" \"; return 0;}", "e": 29996, "s": 27509, "text": null }, { "code": null, "e": 30005, "s": 29996, "text": "Output: " }, { "code": null, "e": 30032, "s": 30005, "text": "8 8 8 2 2 5 5 6 -1 9999999" }, { "code": null, "e": 30093, "s": 30032, "text": "Thanks to Gaurav Ahirwar for providing above implementation." }, { "code": null, "e": 30335, "s": 30093, "text": "METHOD 2 (Use Hashing and Sorting) Using a hashing mechanism, we can store the elements (also first index) and their counts in a hash. Finally, sort the hash elements according to their counts.Below is the implementation of above approach – " }, { "code": null, "e": 30339, "s": 30335, "text": "CPP" }, { "code": null, "e": 30344, "s": 30339, "text": "Java" }, { "code": null, "e": 30352, "s": 30344, "text": "Python3" }, { "code": null, "e": 30363, "s": 30352, "text": "Javascript" }, { "code": "// CPP program for above approach#include <bits/stdc++.h>using namespace std; // Compare functionbool fcompare(pair<int, pair<int, int> > p, pair<int, pair<int, int> > p1){ if (p.second.second != p1.second.second) return (p.second.second > p1.second.second); else return (p.second.first < p1.second.first);}void sortByFrequency(int arr[], int n){ unordered_map<int, pair<int, int> > hash; // hash map for (int i = 0; i < n; i++) { if (hash.find(arr[i]) != hash.end()) hash[arr[i]].second++; else hash[arr[i]] = make_pair(i, 1); } // store the count of all the elements in the hashmap // Iterator to Traverse the Hashmap auto it = hash.begin(); // Vector to store the Final Sortted order vector<pair<int, pair<int, int> > > b; for (it; it != hash.end(); ++it) b.push_back(make_pair(it->first, it->second)); sort(b.begin(), b.end(), fcompare); // Printing the Sorted sequence for (int i = 0; i < b.size(); i++) { int count = b[i].second.second; while (count--) cout << b[i].first << \" \"; }} // Driver Functionint main(){ int arr[] = { 2, 5, 2, 6, -1, 9999999, 5, 8, 8, 8 }; int n = sizeof(arr) / sizeof(arr[0]); sortByFrequency(arr, n); return 0;}", "e": 31664, "s": 30363, "text": null }, { "code": "/*package whatever //do not write package name here */import java.util.Arrays;import java.util.Collections;import java.util.Comparator;import java.util.HashMap;import java.util.List;class GFG { static Integer[] arr = { 2, 5, 2, 8, 5, 6, 8, 8 }; // Driver Code public static void main(String[] args) { List<Integer> list = Arrays.asList(arr); sortBasedOnFrequencyAndValue(list); } // Compare Function public static void sortBasedOnFrequencyAndValue(List<Integer> list) { int n = arr.length; final HashMap<Integer, Integer> mapCount = new HashMap<Integer, Integer>(); final HashMap<Integer, Integer> mapIndex = new HashMap<Integer, Integer>(); for (int i = 0; i < n; i++) { if (mapCount.containsKey(arr[i])) { mapCount.put(arr[i], mapCount.get(arr[i]) + 1); } else { mapCount.put(arr[i],1); // Map to capture Count of elements mapIndex.put(arr[i],i); // Map to capture 1st occurrence of elements } } Collections.sort(list, new Comparator<Integer>() { public int compare(Integer n1, Integer n2) { int freq1 = mapCount.get(n1); int freq2 = mapCount.get(n2); if (freq1 != freq2) { return freq2 - freq1; } else { return mapIndex.get(n1) - mapIndex.get( n2); // Elements with Lesser // Index gets Higher // Priority } } }); System.out.println(list); }}", "e": 33430, "s": 31664, "text": null }, { "code": "# Python program for above approach from collections import defaultdict # Sort by Frequency def sortByFreq(arr, n): # arr -> Array to be sorted # n -> Length of Array # d is a hashmap(referred as dictionary in python) d = defaultdict(lambda: 0) for i in range(n): d[arr[i]] += 1 # Sorting the array 'arr' where key # is the function based on which # the array is sorted # While sorting we want to give # first priority to Frequency # Then to value of item arr.sort(key=lambda x: (-d[x], x)) return (arr) # Driver Functionif __name__ == \"__main__\": arr = [2, 5, 2, 6, -1, 9999999, 5, 8, 8, 8] n = len(arr) solution = sortByFreq(arr, n) print(*solution)", "e": 34147, "s": 33430, "text": null }, { "code": "<script> let arr=[2, 5, 2, 6, -1, 9999999, 5, 8, 8, 8]; // Compare Functionfunction sortBasedOnFrequencyAndValue(list){ let n = arr.length; let mapCount = new Map(); let mapIndex = new Map(); for (let i = 0; i < n; i++) { if (mapCount.has(arr[i])) { mapCount.set(arr[i], mapCount.get(arr[i]) + 1); } else { mapCount.set(arr[i],1); // Map to capture Count of elements mapIndex.set(arr[i],i); // Map to capture 1st occurrence of elements } } list.sort(function(n1,n2){ let freq1 = mapCount.get(n1); let freq2 = mapCount.get(n2); if (freq1 != freq2) { return freq2 - freq1; } else { return mapIndex.get(n1) - mapIndex.get( n2); // Elements with Lesser // Index gets Higher // Priority } }); document.write(list.join(\" \"));} // Driver CodesortBasedOnFrequencyAndValue(arr); // This code is contributed by patel2127</script>", "e": 35430, "s": 34147, "text": null }, { "code": null, "e": 35439, "s": 35430, "text": "Output: " }, { "code": null, "e": 35466, "s": 35439, "text": "8 8 8 2 2 5 5 6 -1 9999999" }, { "code": null, "e": 35624, "s": 35466, "text": "This can also be solved by Using two maps, one for array element as an index and after this second map whose keys are frequency and value are array elements." }, { "code": null, "e": 35655, "s": 35624, "text": "METHOD 3(Use BST and Sorting) " }, { "code": null, "e": 35839, "s": 35655, "text": "Insert elements in BST one by one and if an element is already present then increment the count of the node. Node of the Binary Search Tree (used in this approach) will be as follows." }, { "code": null, "e": 35841, "s": 35839, "text": "C" }, { "code": null, "e": 35846, "s": 35841, "text": "Java" }, { "code": null, "e": 35849, "s": 35846, "text": "C#" }, { "code": "struct tree { int element; int first_index /*To handle ties in counts*/ int count;} BST;</div>", "e": 35957, "s": 35849, "text": null }, { "code": "static class tree { int element; int first_index; /*To handle ties in counts*/ int count;}tree BST = new tree(); // This code is contributed by gauravrajput1", "e": 36124, "s": 35957, "text": null }, { "code": "public class tree { public int element; public int first_index; /* To handle ties in counts */ public int count;}tree BST = new tree(); // This code is contributed by gauravrajput1", "e": 36314, "s": 36124, "text": null }, { "code": null, "e": 36385, "s": 36314, "text": "Store the first indexes and corresponding counts of BST in a 2D array." }, { "code": null, "e": 36457, "s": 36385, "text": "Sort the 2D array according to counts (and use indexes in case of tie)." }, { "code": null, "e": 36756, "s": 36457, "text": "Time Complexity: O(nlogn) if a Self Balancing Binary Search Tree is used. This is implemented in Set 2. https://youtu.be/NBXf9vCksuM Set 2: Sort elements by frequency | Set 2Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above " }, { "code": null, "e": 36772, "s": 36756, "text": "praveenjain6407" }, { "code": null, "e": 36787, "s": 36772, "text": "anumoluhemanth" }, { "code": null, "e": 36799, "s": 36787, "text": "ahmadzaidju" }, { "code": null, "e": 36810, "s": 36799, "text": "Koushik222" }, { "code": null, "e": 36825, "s": 36810, "text": "ayushagrawal99" }, { "code": null, "e": 36835, "s": 36825, "text": "shivagarg" }, { "code": null, "e": 36849, "s": 36835, "text": "prithicogni89" }, { "code": null, "e": 36859, "s": 36849, "text": "patel2127" }, { "code": null, "e": 36871, "s": 36859, "text": "nisanth2590" }, { "code": null, "e": 36885, "s": 36871, "text": "GauravRajput1" }, { "code": null, "e": 36892, "s": 36885, "text": "Amazon" }, { "code": null, "e": 36899, "s": 36892, "text": "Oracle" }, { "code": null, "e": 36904, "s": 36899, "text": "Zoho" }, { "code": null, "e": 36910, "s": 36904, "text": "Zycus" }, { "code": null, "e": 36917, "s": 36910, "text": "Arrays" }, { "code": null, "e": 36925, "s": 36917, "text": "Sorting" }, { "code": null, "e": 36930, "s": 36925, "text": "Zoho" }, { "code": null, "e": 36937, "s": 36930, "text": "Amazon" }, { "code": null, "e": 36944, "s": 36937, "text": "Oracle" }, { "code": null, "e": 36950, "s": 36944, "text": "Zycus" }, { "code": null, "e": 36957, "s": 36950, "text": "Arrays" }, { "code": null, "e": 36965, "s": 36957, "text": "Sorting" }, { "code": null, "e": 37063, "s": 36965, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 37086, "s": 37063, "text": "Introduction to Arrays" }, { "code": null, "e": 37118, "s": 37086, "text": "Multidimensional Arrays in Java" }, { "code": null, "e": 37139, "s": 37118, "text": "Linked List vs Array" }, { "code": null, "e": 37184, "s": 37139, "text": "Python | Using 2D arrays/lists the right way" } ]
Python Collections Module - GeeksforGeeks
27 Apr, 2022 The collection Module in Python provides different types of containers. A Container is an object that is used to store different objects and provide a way to access the contained objects and iterate over them. Some of the built-in containers are Tuple, List, Dictionary, etc. In this article, we will discuss the different containers provided by the collections module. Table of Content: Counters OrderedDict DefaultDict ChainMap NamedTuple DeQue UserDict UserList UserString Note: It is equivalent to bag or multiset of other languages. Syntax: class collections.Counter([iterable-or-mapping]) The counter object can be initialized using the counter() function and this function can be called in one of the following ways: With a sequence of items With a dictionary containing keys and counts With keyword arguments mapping string names to counts Example: Python3 # A Python program to show different # ways to create Counter from collections import Counter # With sequence of items print(Counter(['B','B','A','B','C','A','B', 'B','A','C'])) # with dictionary print(Counter({'A':3, 'B':5, 'C':2})) # with keyword arguments print(Counter(A=3, B=5, C=2)) Output: Counter({'B': 5, 'A': 3, 'C': 2}) Counter({'B': 5, 'A': 3, 'C': 2}) Counter({'B': 5, 'A': 3, 'C': 2}) Note: For more information, refer Counters in Python. An OrderedDict is also a sub-class of dictionary but unlike dictionary, it remembers the order in which the keys were inserted. Syntax: class collections.OrderDict() Example: Python3 # A Python program to demonstrate working# of OrderedDict from collections import OrderedDict print("This is a Dict:\n") d = {} d['a'] = 1d['b'] = 2d['c'] = 3d['d'] = 4 for key, value in d.items(): print(key, value) print("\nThis is an Ordered Dict:\n") od = OrderedDict() od['a'] = 1od['b'] = 2od['c'] = 3od['d'] = 4 for key, value in od.items(): print(key, value) Output: This is a Dict: a 1 b 2 c 3 d 4 This is an Ordered Dict: a 1 b 2 c 3 d 4 While deleting and re-inserting the same key will push the key to the last to maintain the order of insertion of the key. Example: Python3 # A Python program to demonstrate working# of OrderedDict from collections import OrderedDict od = OrderedDict() od['a'] = 1od['b'] = 2od['c'] = 3od['d'] = 4 print('Before Deleting')for key, value in od.items(): print(key, value) # deleting elementod.pop('a') # Re-inserting the sameod['a'] = 1 print('\nAfter re-inserting')for key, value in od.items(): print(key, value) Output: Before Deleting a 1 b 2 c 3 d 4 After re-inserting b 2 c 3 d 4 a 1 Note: for more information, refer OrderedDict in Python A DefaultDict is also a sub-class to dictionary. It is used to provide some default values for the key that does not exist and never raises a KeyError. Syntax: class collections.defaultdict(default_factory) default_factory is a function that provides the default value for the dictionary created. If this parameter is absent then the KeyError is raised. DefaultDict objects can be initialized using DefaultDict() method by passing the data type as an argument. Example: Python3 # Python program to demonstrate # defaultdict from collections import defaultdict # Defining the dict d = defaultdict(int) L = [1, 2, 3, 4, 2, 4, 1, 2] # Iterate through the list # for keeping the count for i in L: # The default value is 0 # so there is no need to # enter the key first d[i] += 1 print(d) Output: defaultdict(<class 'int'>, {1: 2, 2: 3, 3: 1, 4: 2}) Example 2: Python3 # Python program to demonstrate # defaultdict from collections import defaultdict # Defining a dict d = defaultdict(list) for i in range(5): d[i].append(i) print("Dictionary with values as list:") print(d) Output: Dictionary with values as list: defaultdict(<class ‘list’>, {0: [0], 1: [1], 2: [2], 3: [3], 4: [4]}) Note: For more information, refer Defaultdict in Python A ChainMap encapsulates many dictionaries into a single unit and returns a list of dictionaries. Syntax: class collections.ChainMap(dict1, dict2) Example: Python3 # Python program to demonstrate # ChainMap from collections import ChainMap d1 = {'a': 1, 'b': 2}d2 = {'c': 3, 'd': 4}d3 = {'e': 5, 'f': 6} # Defining the chainmap c = ChainMap(d1, d2, d3) print(c) Output: ChainMap({'a': 1, 'b': 2}, {'c': 3, 'd': 4}, {'e': 5, 'f': 6}) Values from ChainMap can be accessed using the key name. They can also be accessed by using the keys() and values() method. Example: Python3 # Python program to demonstrate # ChainMap from collections import ChainMap d1 = {'a': 1, 'b': 2}d2 = {'c': 3, 'd': 4}d3 = {'e': 5, 'f': 6} # Defining the chainmap c = ChainMap(d1, d2, d3) # Accessing Values using key nameprint(c['a']) # Accessing values using values()# methodprint(c.values()) # Accessing keys using keys()# methodprint(c.keys()) Output: 1 ValuesView(ChainMap({‘a’: 1, ‘b’: 2}, {‘c’: 3, ‘d’: 4}, {‘e’: 5, ‘f’: 6})) KeysView(ChainMap({‘a’: 1, ‘b’: 2}, {‘c’: 3, ‘d’: 4}, {‘e’: 5, ‘f’: 6})) A new dictionary can be added by using the new_child() method. The newly added dictionary is added at the beginning of the ChainMap. Example: Python3 # Python code to demonstrate ChainMap and # new_child() import collections # initializing dictionaries dic1 = { 'a' : 1, 'b' : 2 } dic2 = { 'b' : 3, 'c' : 4 } dic3 = { 'f' : 5 } # initializing ChainMap chain = collections.ChainMap(dic1, dic2) # printing chainMap print ("All the ChainMap contents are : ") print (chain) # using new_child() to add new dictionary chain1 = chain.new_child(dic3) # printing chainMapprint ("Displaying new ChainMap : ") print (chain1) Output: All the ChainMap contents are : ChainMap({'a': 1, 'b': 2}, {'b': 3, 'c': 4}) Displaying new ChainMap : ChainMap({'f': 5}, {'a': 1, 'b': 2}, {'b': 3, 'c': 4}) Note: For more information, refer ChainMap in Python A NamedTuple returns a tuple object with names for each position which the ordinary tuples lack. For example, consider a tuple names student where the first element represents fname, second represents lname and the third element represents the DOB. Suppose for calling fname instead of remembering the index position you can actually call the element by using the fname argument, then it will be really easy for accessing tuples element. This functionality is provided by the NamedTuple. Syntax: class collections.namedtuple(typename, field_names) Example: Python3 # Python code to demonstrate namedtuple() from collections import namedtuple # Declaring namedtuple() Student = namedtuple('Student',['name','age','DOB']) # Adding values S = Student('Nandini','19','2541997') # Access using index print ("The Student age using index is : ",end ="") print (S[1]) # Access using name print ("The Student name using keyname is : ",end ="") print (S.name) Output: The Student age using index is : 19 The Student name using keyname is : Nandini 1. _make(): This function is used to return a namedtuple() from the iterable passed as argument. 2. _asdict(): This function returns the OrdereDict() as constructed from the mapped values of namedtuple(). Example: Python3 # Python code to demonstrate namedtuple() and # _make(), _asdict() from collections import namedtuple # Declaring namedtuple() Student = namedtuple('Student',['name','age','DOB']) # Adding values S = Student('Nandini','19','2541997') # initializing iterable li = ['Manjeet', '19', '411997' ] # initializing dict di = { 'name' : "Nikhil", 'age' : 19 , 'DOB' : '1391997' } # using _make() to return namedtuple() print ("The namedtuple instance using iterable is : ") print (Student._make(li)) # using _asdict() to return an OrderedDict() print ("The OrderedDict instance using namedtuple is : ") print (S._asdict()) Output: The namedtuple instance using iterable is : Student(name='Manjeet', age='19', DOB='411997') The OrderedDict instance using namedtuple is : OrderedDict([('name', 'Nandini'), ('age', '19'), ('DOB', '2541997')]) Note: For more information, refer NamedTuple in Python Deque (Doubly Ended Queue) is the optimized list for quicker append and pop operations from both sides of the container. It provides O(1) time complexity for append and pop operations as compared to list with O(n) time complexity. Syntax: class collections.deque(list) This function takes the list as an argument. Example: Python3 # Python code to demonstrate deque from collections import deque # Declaring dequequeue = deque(['name','age','DOB']) print(queue) Output: deque(['name', 'age', 'DOB']) Elements in deque can be inserted from both ends. To insert the elements from right append() method is used and to insert the elements from the left appendleft() method is used. Example: Python3 # Python code to demonstrate working of # append(), appendleft() from collections import deque # initializing deque de = deque([1,2,3]) # using append() to insert element at right end # inserts 4 at the end of deque de.append(4) # printing modified deque print ("The deque after appending at right is : ") print (de) # using appendleft() to insert element at right end # inserts 6 at the beginning of deque de.appendleft(6) # printing modified deque print ("The deque after appending at left is : ") print (de) Output: The deque after appending at right is : deque([1, 2, 3, 4]) The deque after appending at left is : deque([6, 1, 2, 3, 4]) Elements can also be removed from the deque from both the ends. To remove elements from right use pop() method and to remove elements from the left use popleft() method. Example: Python3 # Python code to demonstrate working of # pop(), and popleft() from collections import deque # initializing deque de = deque([6, 1, 2, 3, 4]) # using pop() to delete element from right end # deletes 4 from the right end of deque de.pop() # printing modified deque print ("The deque after deleting from right is : ") print (de) # using popleft() to delete element from left end # deletes 6 from the left end of deque de.popleft() # printing modified deque print ("The deque after deleting from left is : ") print (de) Output: The deque after deleting from right is : deque([6, 1, 2, 3]) The deque after deleting from left is : deque([1, 2, 3]) Note: For more information, refer Deque in Python. UserDict is a dictionary-like container that acts as a wrapper around the dictionary objects. This container is used when someone wants to create their own dictionary with some modified or new functionality. Syntax: class collections.UserDict([initialdata]) Example: Python3 # Python program to demonstrate # userdict from collections import UserDict # Creating a Dictionary where # deletion is not allowed class MyDict(UserDict): # Function to stop deletion # from dictionary def __del__(self): raise RuntimeError("Deletion not allowed") # Function to stop pop from # dictionary def pop(self, s = None): raise RuntimeError("Deletion not allowed") # Function to stop popitem # from Dictionary def popitem(self, s = None): raise RuntimeError("Deletion not allowed") # Driver's code d = MyDict({'a':1, 'b': 2, 'c': 3}) d.pop(1) Output: Traceback (most recent call last): File "/home/f8db849e4cf1e58177983b2b6023c1a3.py", line 32, in <module> d.pop(1) File "/home/f8db849e4cf1e58177983b2b6023c1a3.py", line 20, in pop raise RuntimeError("Deletion not allowed") RuntimeError: Deletion not allowed Exception ignored in: <bound method MyDict.__del__ of {'a': 1, 'b': 2, 'c': 3}> Traceback (most recent call last): File "/home/f8db849e4cf1e58177983b2b6023c1a3.py", line 15, in __del__ RuntimeError: Deletion not allowed Note: For more information, refer UserDict in Python UserList is a list like container that acts as a wrapper around the list objects. This is useful when someone wants to create their own list with some modified or additional functionality. Syntax: class collections.UserList([list]) Example: Python3 # Python program to demonstrate # userlist from collections import UserList # Creating a List where # deletion is not allowed class MyList(UserList): # Function to stop deletion # from List def remove(self, s = None): raise RuntimeError("Deletion not allowed") # Function to stop pop from # List def pop(self, s = None): raise RuntimeError("Deletion not allowed") # Driver's code L = MyList([1, 2, 3, 4]) print("Original List") # Inserting to List" L.append(5) print("After Insertion") print(L) # Deleting From List L.remove() Output: Original List After Insertion [1, 2, 3, 4, 5] Traceback (most recent call last): File "/home/c90487eefa7474c0566435269f50a52a.py", line 33, in <module> L.remove() File "/home/c90487eefa7474c0566435269f50a52a.py", line 15, in remove raise RuntimeError("Deletion not allowed") RuntimeError: Deletion not allowed Note: For more information, refer UserList in Python UserString is a string like container and just like UserDict and UserList it acts as a wrapper around string objects. It is used when someone wants to create their own strings with some modified or additional functionality. Syntax: class collections.UserString(seq) Example: Python3 # Python program to demonstrate # userstring from collections import UserString # Creating a Mutable String class Mystring(UserString): # Function to append to # string def append(self, s): self.data += s # Function to remove from # string def remove(self, s): self.data = self.data.replace(s, "") # Driver's code s1 = Mystring("Geeks") print("Original String:", s1.data) # Appending to string s1.append("s") print("String After Appending:", s1.data) # Removing from string s1.remove("e") print("String after Removing:", s1.data) Output: Original String: Geeks String After Appending: Geekss String after Removing: Gkss Note: For more information, refer UserString in Python saurabh1990aror sooda367 varshagumber28 kapoorsagar226 Python collections-module Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Read JSON file using Python Adding new column to existing DataFrame in Pandas Python map() function How to get column names in Pandas dataframe 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()
[ { "code": null, "e": 42675, "s": 42647, "text": "\n27 Apr, 2022" }, { "code": null, "e": 43045, "s": 42675, "text": "The collection Module in Python provides different types of containers. A Container is an object that is used to store different objects and provide a way to access the contained objects and iterate over them. Some of the built-in containers are Tuple, List, Dictionary, etc. In this article, we will discuss the different containers provided by the collections module." }, { "code": null, "e": 43063, "s": 43045, "text": "Table of Content:" }, { "code": null, "e": 43072, "s": 43063, "text": "Counters" }, { "code": null, "e": 43084, "s": 43072, "text": "OrderedDict" }, { "code": null, "e": 43096, "s": 43084, "text": "DefaultDict" }, { "code": null, "e": 43105, "s": 43096, "text": "ChainMap" }, { "code": null, "e": 43116, "s": 43105, "text": "NamedTuple" }, { "code": null, "e": 43122, "s": 43116, "text": "DeQue" }, { "code": null, "e": 43131, "s": 43122, "text": "UserDict" }, { "code": null, "e": 43140, "s": 43131, "text": "UserList" }, { "code": null, "e": 43151, "s": 43140, "text": "UserString" }, { "code": null, "e": 43213, "s": 43151, "text": "Note: It is equivalent to bag or multiset of other languages." }, { "code": null, "e": 43221, "s": 43213, "text": "Syntax:" }, { "code": null, "e": 43270, "s": 43221, "text": "class collections.Counter([iterable-or-mapping])" }, { "code": null, "e": 43399, "s": 43270, "text": "The counter object can be initialized using the counter() function and this function can be called in one of the following ways:" }, { "code": null, "e": 43424, "s": 43399, "text": "With a sequence of items" }, { "code": null, "e": 43469, "s": 43424, "text": "With a dictionary containing keys and counts" }, { "code": null, "e": 43523, "s": 43469, "text": "With keyword arguments mapping string names to counts" }, { "code": null, "e": 43532, "s": 43523, "text": "Example:" }, { "code": null, "e": 43540, "s": 43532, "text": "Python3" }, { "code": "# A Python program to show different # ways to create Counter from collections import Counter # With sequence of items print(Counter(['B','B','A','B','C','A','B', 'B','A','C'])) # with dictionary print(Counter({'A':3, 'B':5, 'C':2})) # with keyword arguments print(Counter(A=3, B=5, C=2))", "e": 43854, "s": 43540, "text": null }, { "code": null, "e": 43862, "s": 43854, "text": "Output:" }, { "code": null, "e": 43964, "s": 43862, "text": "Counter({'B': 5, 'A': 3, 'C': 2})\nCounter({'B': 5, 'A': 3, 'C': 2})\nCounter({'B': 5, 'A': 3, 'C': 2})" }, { "code": null, "e": 44019, "s": 43964, "text": "Note: For more information, refer Counters in Python." }, { "code": null, "e": 44148, "s": 44019, "text": "An OrderedDict is also a sub-class of dictionary but unlike dictionary, it remembers the order in which the keys were inserted. " }, { "code": null, "e": 44156, "s": 44148, "text": "Syntax:" }, { "code": null, "e": 44186, "s": 44156, "text": "class collections.OrderDict()" }, { "code": null, "e": 44195, "s": 44186, "text": "Example:" }, { "code": null, "e": 44203, "s": 44195, "text": "Python3" }, { "code": "# A Python program to demonstrate working# of OrderedDict from collections import OrderedDict print(\"This is a Dict:\\n\") d = {} d['a'] = 1d['b'] = 2d['c'] = 3d['d'] = 4 for key, value in d.items(): print(key, value) print(\"\\nThis is an Ordered Dict:\\n\") od = OrderedDict() od['a'] = 1od['b'] = 2od['c'] = 3od['d'] = 4 for key, value in od.items(): print(key, value)", "e": 44593, "s": 44203, "text": null }, { "code": null, "e": 44601, "s": 44593, "text": "Output:" }, { "code": null, "e": 44677, "s": 44601, "text": "This is a Dict:\n\na 1\nb 2\nc 3\nd 4\n\nThis is an Ordered Dict:\n\na 1\nb 2\nc 3\nd 4" }, { "code": null, "e": 44799, "s": 44677, "text": "While deleting and re-inserting the same key will push the key to the last to maintain the order of insertion of the key." }, { "code": null, "e": 44808, "s": 44799, "text": "Example:" }, { "code": null, "e": 44816, "s": 44808, "text": "Python3" }, { "code": "# A Python program to demonstrate working# of OrderedDict from collections import OrderedDict od = OrderedDict() od['a'] = 1od['b'] = 2od['c'] = 3od['d'] = 4 print('Before Deleting')for key, value in od.items(): print(key, value) # deleting elementod.pop('a') # Re-inserting the sameod['a'] = 1 print('\\nAfter re-inserting')for key, value in od.items(): print(key, value)", "e": 45213, "s": 44816, "text": null }, { "code": null, "e": 45221, "s": 45213, "text": "Output:" }, { "code": null, "e": 45289, "s": 45221, "text": "Before Deleting\na 1\nb 2\nc 3\nd 4\n\nAfter re-inserting\nb 2\nc 3\nd 4\na 1" }, { "code": null, "e": 45345, "s": 45289, "text": "Note: for more information, refer OrderedDict in Python" }, { "code": null, "e": 45497, "s": 45345, "text": "A DefaultDict is also a sub-class to dictionary. It is used to provide some default values for the key that does not exist and never raises a KeyError." }, { "code": null, "e": 45505, "s": 45497, "text": "Syntax:" }, { "code": null, "e": 45552, "s": 45505, "text": "class collections.defaultdict(default_factory)" }, { "code": null, "e": 45699, "s": 45552, "text": "default_factory is a function that provides the default value for the dictionary created. If this parameter is absent then the KeyError is raised." }, { "code": null, "e": 45806, "s": 45699, "text": "DefaultDict objects can be initialized using DefaultDict() method by passing the data type as an argument." }, { "code": null, "e": 45815, "s": 45806, "text": "Example:" }, { "code": null, "e": 45823, "s": 45815, "text": "Python3" }, { "code": "# Python program to demonstrate # defaultdict from collections import defaultdict # Defining the dict d = defaultdict(int) L = [1, 2, 3, 4, 2, 4, 1, 2] # Iterate through the list # for keeping the count for i in L: # The default value is 0 # so there is no need to # enter the key first d[i] += 1 print(d)", "e": 46193, "s": 45823, "text": null }, { "code": null, "e": 46201, "s": 46193, "text": "Output:" }, { "code": null, "e": 46254, "s": 46201, "text": "defaultdict(<class 'int'>, {1: 2, 2: 3, 3: 1, 4: 2})" }, { "code": null, "e": 46265, "s": 46254, "text": "Example 2:" }, { "code": null, "e": 46273, "s": 46265, "text": "Python3" }, { "code": "# Python program to demonstrate # defaultdict from collections import defaultdict # Defining a dict d = defaultdict(list) for i in range(5): d[i].append(i) print(\"Dictionary with values as list:\") print(d)", "e": 46511, "s": 46273, "text": null }, { "code": null, "e": 46519, "s": 46511, "text": "Output:" }, { "code": null, "e": 46621, "s": 46519, "text": "Dictionary with values as list: defaultdict(<class ‘list’>, {0: [0], 1: [1], 2: [2], 3: [3], 4: [4]})" }, { "code": null, "e": 46677, "s": 46621, "text": "Note: For more information, refer Defaultdict in Python" }, { "code": null, "e": 46774, "s": 46677, "text": "A ChainMap encapsulates many dictionaries into a single unit and returns a list of dictionaries." }, { "code": null, "e": 46782, "s": 46774, "text": "Syntax:" }, { "code": null, "e": 46823, "s": 46782, "text": "class collections.ChainMap(dict1, dict2)" }, { "code": null, "e": 46832, "s": 46823, "text": "Example:" }, { "code": null, "e": 46840, "s": 46832, "text": "Python3" }, { "code": "# Python program to demonstrate # ChainMap from collections import ChainMap d1 = {'a': 1, 'b': 2}d2 = {'c': 3, 'd': 4}d3 = {'e': 5, 'f': 6} # Defining the chainmap c = ChainMap(d1, d2, d3) print(c)", "e": 47064, "s": 46840, "text": null }, { "code": null, "e": 47072, "s": 47064, "text": "Output:" }, { "code": null, "e": 47135, "s": 47072, "text": "ChainMap({'a': 1, 'b': 2}, {'c': 3, 'd': 4}, {'e': 5, 'f': 6})" }, { "code": null, "e": 47259, "s": 47135, "text": "Values from ChainMap can be accessed using the key name. They can also be accessed by using the keys() and values() method." }, { "code": null, "e": 47268, "s": 47259, "text": "Example:" }, { "code": null, "e": 47276, "s": 47268, "text": "Python3" }, { "code": "# Python program to demonstrate # ChainMap from collections import ChainMap d1 = {'a': 1, 'b': 2}d2 = {'c': 3, 'd': 4}d3 = {'e': 5, 'f': 6} # Defining the chainmap c = ChainMap(d1, d2, d3) # Accessing Values using key nameprint(c['a']) # Accessing values using values()# methodprint(c.values()) # Accessing keys using keys()# methodprint(c.keys())", "e": 47652, "s": 47276, "text": null }, { "code": null, "e": 47660, "s": 47652, "text": "Output:" }, { "code": null, "e": 47810, "s": 47660, "text": "1 ValuesView(ChainMap({‘a’: 1, ‘b’: 2}, {‘c’: 3, ‘d’: 4}, {‘e’: 5, ‘f’: 6})) KeysView(ChainMap({‘a’: 1, ‘b’: 2}, {‘c’: 3, ‘d’: 4}, {‘e’: 5, ‘f’: 6}))" }, { "code": null, "e": 47943, "s": 47810, "text": "A new dictionary can be added by using the new_child() method. The newly added dictionary is added at the beginning of the ChainMap." }, { "code": null, "e": 47952, "s": 47943, "text": "Example:" }, { "code": null, "e": 47960, "s": 47952, "text": "Python3" }, { "code": "# Python code to demonstrate ChainMap and # new_child() import collections # initializing dictionaries dic1 = { 'a' : 1, 'b' : 2 } dic2 = { 'b' : 3, 'c' : 4 } dic3 = { 'f' : 5 } # initializing ChainMap chain = collections.ChainMap(dic1, dic2) # printing chainMap print (\"All the ChainMap contents are : \") print (chain) # using new_child() to add new dictionary chain1 = chain.new_child(dic3) # printing chainMapprint (\"Displaying new ChainMap : \") print (chain1)", "e": 48448, "s": 47960, "text": null }, { "code": null, "e": 48456, "s": 48448, "text": "Output:" }, { "code": null, "e": 48616, "s": 48456, "text": "All the ChainMap contents are : \nChainMap({'a': 1, 'b': 2}, {'b': 3, 'c': 4})\nDisplaying new ChainMap : \nChainMap({'f': 5}, {'a': 1, 'b': 2}, {'b': 3, 'c': 4})" }, { "code": null, "e": 48669, "s": 48616, "text": "Note: For more information, refer ChainMap in Python" }, { "code": null, "e": 49157, "s": 48669, "text": "A NamedTuple returns a tuple object with names for each position which the ordinary tuples lack. For example, consider a tuple names student where the first element represents fname, second represents lname and the third element represents the DOB. Suppose for calling fname instead of remembering the index position you can actually call the element by using the fname argument, then it will be really easy for accessing tuples element. This functionality is provided by the NamedTuple." }, { "code": null, "e": 49165, "s": 49157, "text": "Syntax:" }, { "code": null, "e": 49217, "s": 49165, "text": "class collections.namedtuple(typename, field_names)" }, { "code": null, "e": 49226, "s": 49217, "text": "Example:" }, { "code": null, "e": 49234, "s": 49226, "text": "Python3" }, { "code": "# Python code to demonstrate namedtuple() from collections import namedtuple # Declaring namedtuple() Student = namedtuple('Student',['name','age','DOB']) # Adding values S = Student('Nandini','19','2541997') # Access using index print (\"The Student age using index is : \",end =\"\") print (S[1]) # Access using name print (\"The Student name using keyname is : \",end =\"\") print (S.name)", "e": 49638, "s": 49234, "text": null }, { "code": null, "e": 49646, "s": 49638, "text": "Output:" }, { "code": null, "e": 49726, "s": 49646, "text": "The Student age using index is : 19\nThe Student name using keyname is : Nandini" }, { "code": null, "e": 49823, "s": 49726, "text": "1. _make(): This function is used to return a namedtuple() from the iterable passed as argument." }, { "code": null, "e": 49931, "s": 49823, "text": "2. _asdict(): This function returns the OrdereDict() as constructed from the mapped values of namedtuple()." }, { "code": null, "e": 49940, "s": 49931, "text": "Example:" }, { "code": null, "e": 49948, "s": 49940, "text": "Python3" }, { "code": "# Python code to demonstrate namedtuple() and # _make(), _asdict() from collections import namedtuple # Declaring namedtuple() Student = namedtuple('Student',['name','age','DOB']) # Adding values S = Student('Nandini','19','2541997') # initializing iterable li = ['Manjeet', '19', '411997' ] # initializing dict di = { 'name' : \"Nikhil\", 'age' : 19 , 'DOB' : '1391997' } # using _make() to return namedtuple() print (\"The namedtuple instance using iterable is : \") print (Student._make(li)) # using _asdict() to return an OrderedDict() print (\"The OrderedDict instance using namedtuple is : \") print (S._asdict())", "e": 50593, "s": 49948, "text": null }, { "code": null, "e": 50601, "s": 50593, "text": "Output:" }, { "code": null, "e": 50814, "s": 50601, "text": "The namedtuple instance using iterable is : \nStudent(name='Manjeet', age='19', DOB='411997')\nThe OrderedDict instance using namedtuple is : \nOrderedDict([('name', 'Nandini'), ('age', '19'), ('DOB', '2541997')])" }, { "code": null, "e": 50870, "s": 50814, "text": "Note: For more information, refer NamedTuple in Python" }, { "code": null, "e": 51101, "s": 50870, "text": "Deque (Doubly Ended Queue) is the optimized list for quicker append and pop operations from both sides of the container. It provides O(1) time complexity for append and pop operations as compared to list with O(n) time complexity." }, { "code": null, "e": 51109, "s": 51101, "text": "Syntax:" }, { "code": null, "e": 51139, "s": 51109, "text": "class collections.deque(list)" }, { "code": null, "e": 51184, "s": 51139, "text": "This function takes the list as an argument." }, { "code": null, "e": 51193, "s": 51184, "text": "Example:" }, { "code": null, "e": 51201, "s": 51193, "text": "Python3" }, { "code": "# Python code to demonstrate deque from collections import deque # Declaring dequequeue = deque(['name','age','DOB']) print(queue)", "e": 51344, "s": 51201, "text": null }, { "code": null, "e": 51352, "s": 51344, "text": "Output:" }, { "code": null, "e": 51382, "s": 51352, "text": "deque(['name', 'age', 'DOB'])" }, { "code": null, "e": 51560, "s": 51382, "text": "Elements in deque can be inserted from both ends. To insert the elements from right append() method is used and to insert the elements from the left appendleft() method is used." }, { "code": null, "e": 51569, "s": 51560, "text": "Example:" }, { "code": null, "e": 51577, "s": 51569, "text": "Python3" }, { "code": "# Python code to demonstrate working of # append(), appendleft() from collections import deque # initializing deque de = deque([1,2,3]) # using append() to insert element at right end # inserts 4 at the end of deque de.append(4) # printing modified deque print (\"The deque after appending at right is : \") print (de) # using appendleft() to insert element at right end # inserts 6 at the beginning of deque de.appendleft(6) # printing modified deque print (\"The deque after appending at left is : \") print (de)", "e": 52116, "s": 51577, "text": null }, { "code": null, "e": 52124, "s": 52116, "text": "Output:" }, { "code": null, "e": 52248, "s": 52124, "text": "The deque after appending at right is : \ndeque([1, 2, 3, 4])\nThe deque after appending at left is : \ndeque([6, 1, 2, 3, 4])" }, { "code": null, "e": 52418, "s": 52248, "text": "Elements can also be removed from the deque from both the ends. To remove elements from right use pop() method and to remove elements from the left use popleft() method." }, { "code": null, "e": 52427, "s": 52418, "text": "Example:" }, { "code": null, "e": 52435, "s": 52427, "text": "Python3" }, { "code": "# Python code to demonstrate working of # pop(), and popleft() from collections import deque # initializing deque de = deque([6, 1, 2, 3, 4]) # using pop() to delete element from right end # deletes 4 from the right end of deque de.pop() # printing modified deque print (\"The deque after deleting from right is : \") print (de) # using popleft() to delete element from left end # deletes 6 from the left end of deque de.popleft() # printing modified deque print (\"The deque after deleting from left is : \") print (de)", "e": 52971, "s": 52435, "text": null }, { "code": null, "e": 52979, "s": 52971, "text": "Output:" }, { "code": null, "e": 53099, "s": 52979, "text": "The deque after deleting from right is : \ndeque([6, 1, 2, 3])\nThe deque after deleting from left is : \ndeque([1, 2, 3])" }, { "code": null, "e": 53150, "s": 53099, "text": "Note: For more information, refer Deque in Python." }, { "code": null, "e": 53359, "s": 53150, "text": "UserDict is a dictionary-like container that acts as a wrapper around the dictionary objects. This container is used when someone wants to create their own dictionary with some modified or new functionality. " }, { "code": null, "e": 53367, "s": 53359, "text": "Syntax:" }, { "code": null, "e": 53409, "s": 53367, "text": "class collections.UserDict([initialdata])" }, { "code": null, "e": 53418, "s": 53409, "text": "Example:" }, { "code": null, "e": 53426, "s": 53418, "text": "Python3" }, { "code": "# Python program to demonstrate # userdict from collections import UserDict # Creating a Dictionary where # deletion is not allowed class MyDict(UserDict): # Function to stop deletion # from dictionary def __del__(self): raise RuntimeError(\"Deletion not allowed\") # Function to stop pop from # dictionary def pop(self, s = None): raise RuntimeError(\"Deletion not allowed\") # Function to stop popitem # from Dictionary def popitem(self, s = None): raise RuntimeError(\"Deletion not allowed\") # Driver's code d = MyDict({'a':1, 'b': 2, 'c': 3}) d.pop(1)", "e": 54108, "s": 53426, "text": null }, { "code": null, "e": 54116, "s": 54108, "text": "Output:" }, { "code": null, "e": 54611, "s": 54116, "text": "Traceback (most recent call last):\n File \"/home/f8db849e4cf1e58177983b2b6023c1a3.py\", line 32, in <module>\n d.pop(1) \n File \"/home/f8db849e4cf1e58177983b2b6023c1a3.py\", line 20, in pop\n raise RuntimeError(\"Deletion not allowed\") \nRuntimeError: Deletion not allowed\nException ignored in: <bound method MyDict.__del__ of {'a': 1, 'b': 2, 'c': 3}>\nTraceback (most recent call last):\n File \"/home/f8db849e4cf1e58177983b2b6023c1a3.py\", line 15, in __del__\nRuntimeError: Deletion not allowed" }, { "code": null, "e": 54664, "s": 54611, "text": "Note: For more information, refer UserDict in Python" }, { "code": null, "e": 54853, "s": 54664, "text": "UserList is a list like container that acts as a wrapper around the list objects. This is useful when someone wants to create their own list with some modified or additional functionality." }, { "code": null, "e": 54861, "s": 54853, "text": "Syntax:" }, { "code": null, "e": 54896, "s": 54861, "text": "class collections.UserList([list])" }, { "code": null, "e": 54905, "s": 54896, "text": "Example:" }, { "code": null, "e": 54913, "s": 54905, "text": "Python3" }, { "code": "# Python program to demonstrate # userlist from collections import UserList # Creating a List where # deletion is not allowed class MyList(UserList): # Function to stop deletion # from List def remove(self, s = None): raise RuntimeError(\"Deletion not allowed\") # Function to stop pop from # List def pop(self, s = None): raise RuntimeError(\"Deletion not allowed\") # Driver's code L = MyList([1, 2, 3, 4]) print(\"Original List\") # Inserting to List\" L.append(5) print(\"After Insertion\") print(L) # Deleting From List L.remove()", "e": 55539, "s": 54913, "text": null }, { "code": null, "e": 55547, "s": 55539, "text": "Output:" }, { "code": null, "e": 55593, "s": 55547, "text": "Original List\nAfter Insertion\n[1, 2, 3, 4, 5]" }, { "code": null, "e": 55871, "s": 55593, "text": "Traceback (most recent call last):\n File \"/home/c90487eefa7474c0566435269f50a52a.py\", line 33, in <module>\n L.remove() \n File \"/home/c90487eefa7474c0566435269f50a52a.py\", line 15, in remove\n raise RuntimeError(\"Deletion not allowed\") \nRuntimeError: Deletion not allowed" }, { "code": null, "e": 55924, "s": 55871, "text": "Note: For more information, refer UserList in Python" }, { "code": null, "e": 56149, "s": 55924, "text": "UserString is a string like container and just like UserDict and UserList it acts as a wrapper around string objects. It is used when someone wants to create their own strings with some modified or additional functionality. " }, { "code": null, "e": 56157, "s": 56149, "text": "Syntax:" }, { "code": null, "e": 56191, "s": 56157, "text": "class collections.UserString(seq)" }, { "code": null, "e": 56200, "s": 56191, "text": "Example:" }, { "code": null, "e": 56208, "s": 56200, "text": "Python3" }, { "code": "# Python program to demonstrate # userstring from collections import UserString # Creating a Mutable String class Mystring(UserString): # Function to append to # string def append(self, s): self.data += s # Function to remove from # string def remove(self, s): self.data = self.data.replace(s, \"\") # Driver's code s1 = Mystring(\"Geeks\") print(\"Original String:\", s1.data) # Appending to string s1.append(\"s\") print(\"String After Appending:\", s1.data) # Removing from string s1.remove(\"e\") print(\"String after Removing:\", s1.data)", "e": 56833, "s": 56208, "text": null }, { "code": null, "e": 56841, "s": 56833, "text": "Output:" }, { "code": null, "e": 56923, "s": 56841, "text": "Original String: Geeks\nString After Appending: Geekss\nString after Removing: Gkss" }, { "code": null, "e": 56978, "s": 56923, "text": "Note: For more information, refer UserString in Python" }, { "code": null, "e": 56994, "s": 56978, "text": "saurabh1990aror" }, { "code": null, "e": 57003, "s": 56994, "text": "sooda367" }, { "code": null, "e": 57018, "s": 57003, "text": "varshagumber28" }, { "code": null, "e": 57033, "s": 57018, "text": "kapoorsagar226" }, { "code": null, "e": 57059, "s": 57033, "text": "Python collections-module" }, { "code": null, "e": 57066, "s": 57059, "text": "Python" }, { "code": null, "e": 57164, "s": 57066, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 57192, "s": 57164, "text": "Read JSON file using Python" }, { "code": null, "e": 57242, "s": 57192, "text": "Adding new column to existing DataFrame in Pandas" }, { "code": null, "e": 57264, "s": 57242, "text": "Python map() function" }, { "code": null, "e": 57308, "s": 57264, "text": "How to get column names in Pandas dataframe" }, { "code": null, "e": 57343, "s": 57308, "text": "Read a file line by line in Python" }, { "code": null, "e": 57375, "s": 57343, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 57397, "s": 57375, "text": "Enumerate() in Python" }, { "code": null, "e": 57439, "s": 57397, "text": "Different ways to create Pandas Dataframe" }, { "code": null, "e": 57469, "s": 57439, "text": "Iterate over a list in Python" } ]
C# | Math.Cos() Method - GeeksforGeeks
11 Jan, 2022 Math.Cos() is an inbuilt Math class method which returns the cosine of a given double value argument(specified angle).Syntax: public static double Cos(double num) Parameter: num: It is the angle(measured in radian) whose cosine is to be returned and the type of this parameter is System.Double. Return Value: Returns the cosine of num of type System.Double. If num is equal to NegativeInfinity, PositiveInfinity, or NaN, then this method returns NaN.Below are the programs to illustrate the Math.Cos() method.Program 1: To show the working of Math.Cos() method. CSharp // C# program to demonstrate working// Math.Cos() methodusing System; class Geeks { // Main Method public static void Main(String []args) { double a = 70; // converting value to radians double b = (a * (Math.PI)) / 180; // using method and displaying result Console.WriteLine(Math.Cos(b)); a = 50; // converting value to radians b = (a * (Math.PI)) / 180; // using method and displaying result Console.WriteLine(Math.Cos(b)); a = 73; // converting value to radians b = (a * (Math.PI)) / 180; // using method and displaying result Console.WriteLine(Math.Cos(b)); a = 77; // converting value to radians b = (a * (Math.PI)) / 180; // using method and displaying result Console.WriteLine(Math.Cos(b)); }} 0.342020143325669 0.642787609686539 0.292371704722737 0.224951054343865 Program 2: To show the working of Math.Cos() method when the argument is NaN or infinity. CSharp // C# program to demonstrate working// Math.Cos() method in infinity caseusing System; class Geeks { // Main Method public static void Main(String []args) { double positiveInfinity = Double.PositiveInfinity; double negativeInfinity = Double.NegativeInfinity; double nan = Double.NaN; double result; // Here argument is negative infinity, // output will be NaN result = Math.Cos(negativeInfinity); Console.WriteLine(result); // Here argument is positive infinity, // output will also be NaN result = Math.Cos(positiveInfinity); Console.WriteLine(result); // Here argument is NaN, output will be NaN result = Math.Cos(nan); Console.WriteLine(result); }} NaN NaN NaN adnanirshad158 CSharp-Math CSharp-method C# Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. C# Dictionary with examples C# | Delegates C# | Method Overriding C# | Abstract Classes Difference between Ref and Out keywords in C# Extension Method in C# C# | Class and Object C# | Constructors C# | String.IndexOf( ) Method | Set - 1 C# | Replace() Method
[ { "code": null, "e": 25555, "s": 25527, "text": "\n11 Jan, 2022" }, { "code": null, "e": 25683, "s": 25555, "text": "Math.Cos() is an inbuilt Math class method which returns the cosine of a given double value argument(specified angle).Syntax: " }, { "code": null, "e": 25720, "s": 25683, "text": "public static double Cos(double num)" }, { "code": null, "e": 25733, "s": 25720, "text": "Parameter: " }, { "code": null, "e": 25854, "s": 25733, "text": "num: It is the angle(measured in radian) whose cosine is to be returned and the type of this parameter is System.Double." }, { "code": null, "e": 26121, "s": 25854, "text": "Return Value: Returns the cosine of num of type System.Double. If num is equal to NegativeInfinity, PositiveInfinity, or NaN, then this method returns NaN.Below are the programs to illustrate the Math.Cos() method.Program 1: To show the working of Math.Cos() method." }, { "code": null, "e": 26128, "s": 26121, "text": "CSharp" }, { "code": "// C# program to demonstrate working// Math.Cos() methodusing System; class Geeks { // Main Method public static void Main(String []args) { double a = 70; // converting value to radians double b = (a * (Math.PI)) / 180; // using method and displaying result Console.WriteLine(Math.Cos(b)); a = 50; // converting value to radians b = (a * (Math.PI)) / 180; // using method and displaying result Console.WriteLine(Math.Cos(b)); a = 73; // converting value to radians b = (a * (Math.PI)) / 180; // using method and displaying result Console.WriteLine(Math.Cos(b)); a = 77; // converting value to radians b = (a * (Math.PI)) / 180; // using method and displaying result Console.WriteLine(Math.Cos(b)); }}", "e": 27031, "s": 26128, "text": null }, { "code": null, "e": 27103, "s": 27031, "text": "0.342020143325669\n0.642787609686539\n0.292371704722737\n0.224951054343865" }, { "code": null, "e": 27196, "s": 27105, "text": " Program 2: To show the working of Math.Cos() method when the argument is NaN or infinity." }, { "code": null, "e": 27203, "s": 27196, "text": "CSharp" }, { "code": "// C# program to demonstrate working// Math.Cos() method in infinity caseusing System; class Geeks { // Main Method public static void Main(String []args) { double positiveInfinity = Double.PositiveInfinity; double negativeInfinity = Double.NegativeInfinity; double nan = Double.NaN; double result; // Here argument is negative infinity, // output will be NaN result = Math.Cos(negativeInfinity); Console.WriteLine(result); // Here argument is positive infinity, // output will also be NaN result = Math.Cos(positiveInfinity); Console.WriteLine(result); // Here argument is NaN, output will be NaN result = Math.Cos(nan); Console.WriteLine(result); }}", "e": 28019, "s": 27203, "text": null }, { "code": null, "e": 28031, "s": 28019, "text": "NaN\nNaN\nNaN" }, { "code": null, "e": 28048, "s": 28033, "text": "adnanirshad158" }, { "code": null, "e": 28060, "s": 28048, "text": "CSharp-Math" }, { "code": null, "e": 28074, "s": 28060, "text": "CSharp-method" }, { "code": null, "e": 28077, "s": 28074, "text": "C#" }, { "code": null, "e": 28175, "s": 28077, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 28203, "s": 28175, "text": "C# Dictionary with examples" }, { "code": null, "e": 28218, "s": 28203, "text": "C# | Delegates" }, { "code": null, "e": 28241, "s": 28218, "text": "C# | Method Overriding" }, { "code": null, "e": 28263, "s": 28241, "text": "C# | Abstract Classes" }, { "code": null, "e": 28309, "s": 28263, "text": "Difference between Ref and Out keywords in C#" }, { "code": null, "e": 28332, "s": 28309, "text": "Extension Method in C#" }, { "code": null, "e": 28354, "s": 28332, "text": "C# | Class and Object" }, { "code": null, "e": 28372, "s": 28354, "text": "C# | Constructors" }, { "code": null, "e": 28412, "s": 28372, "text": "C# | String.IndexOf( ) Method | Set - 1" } ]
Minimum number of times A has to be repeated such that B is a substring of it - GeeksforGeeks
22 Feb, 2022 Given two strings A and B. The task is to find the minimum number of times A has to be repeated such that B is a substring of it. If no such solution exists, print -1. Examples: Input : A = “abcd”, B = “cdabcdab” Output : 3 Repeating A three times (“abcdabcdabcd”), B is a substring of it. B is not a substring of A when it is repeated less than 3 times. Input : A = “ab”, B = “cab” Output : -1 Approach : Imagine we wrote S = A+A+A+... If B is a substring of S, we only need to check whether some index 0 or 1 or .... length(A) -1 starts with B, as S is long enough to contain B, and S has a period of length(A).Now, suppose ans is the least number for which length(B) <= length(A * ans). We only need to check whether B is a substring of A * ans or A * (ans+1). If we try k < ans, then B has a larger length than A * ans and therefore can’t be a substring. When k = ans+1, A * k is already big enough to try all positions for B( A[i:i+length(B)] == B for i = 0, 1, ..., length(A) – 1). Below is the implementation of the above approach: C++14 Java Python3 C# Javascript // CPP program to find Minimum number of times A// has to be repeated such that B is a substring of it#include <bits/stdc++.h>using namespace std; // Function to check if a number// is a substring of other or notbool issubstring(string str2, string rep1){ int M = str2.length(); int N = rep1.length(); // Check for substring from starting // from i'th index of main string for (int i = 0; i <= N - M; i++) { int j; // For current index i, // check for pattern match for (j = 0; j < M; j++) if (rep1[i + j] != str2[j]) break; if (j == M) // pattern matched return true; } return false; // not a substring} // Function to find Minimum number of times A// has to be repeated such that B is a substring of itint Min_repetation(string A, string B){ // To store minimum number of repetitions int ans = 1; // To store repeated string string S = A; // Until size of S is less than B while(S.size() < B.size()) { S += A; ans++; } // ans times repetition makes required answer if (issubstring(B, S)) return ans; // Add one more string of A if (issubstring(B, S+A)) return ans + 1; // If no such solution exists return -1;} // Driver codeint main(){ string A = "abcd", B = "cdabcdab"; // Function call cout << Min_repetation(A, B); return 0;} // Java program to find minimum number// of times 'A' has to be repeated// such that 'B' is a substring of itclass GFG{ // Function to check if a number// is a substring of other or notstatic boolean issubstring(String str2, String rep1){ int M = str2.length(); int N = rep1.length(); // Check for substring from starting // from i'th index of main string for (int i = 0; i <= N - M; i++) { int j; // For current index i, // check for pattern match for (j = 0; j < M; j++) if (rep1.charAt(i + j) != str2.charAt(j)) break; if (j == M) // pattern matched return true; } return false; // not a substring} // Function to find Minimum number// of times 'A' has to be repeated// such that 'B' is a substring of itstatic int Min_repetation(String A, String B){ // To store minimum number of repetitions int ans = 1; // To store repeated string String S = A; // Until size of S is less than B while(S.length() < B.length()) { S += A; ans++; } // ans times repetition makes required answer if (issubstring(B, S)) return ans; // Add one more string of A if (issubstring(B, S + A)) return ans + 1; // If no such solution exists return -1;} // Driver codepublic static void main(String[] args){ String A = "abcd", B = "cdabcdab"; // Function call System.out.println(Min_repetation(A, B));}} // This code is contributed by PrinciRaj1992 # Python3 program to find minimum number# of times 'A' has to be repeated# such that 'B' is a substring of it # Method to find Minimum number# of times 'A' has to be repeated# such that 'B' is a substring of itdef min_repetitions(a, b): len_a = len(a) len_b = len(b) for i in range(0, len_a): if a[i] == b[0]: k = i count = 1 for j in range(0, len_b): # we are reiterating over A again and # again for each value of B # Resetting A pointer back to 0 as B # is not empty yet if k >= len_a: k = 0 count = count + 1 # Resetting A means count # needs to be increased if a[k] != b[j]: break k = k + 1 # k is iterating over A else: return count return -1 # Driver CodeA = 'abcd'B = 'cdabcdab'print(min_repetitions(A, B)) # This code is contributed by satycool // C# program to find minimum number// of times 'A' has to be repeated// such that 'B' is a substring of itusing System; class GFG{ // Function to check if a number// is a substring of other or notstatic Boolean issubstring(String str2, String rep1){ int M = str2.Length; int N = rep1.Length; // Check for substring from starting // from i'th index of main string for (int i = 0; i <= N - M; i++) { int j; // For current index i, // check for pattern match for (j = 0; j < M; j++) if (rep1[i + j] != str2[j]) break; if (j == M) // pattern matched return true; } return false; // not a substring} // Function to find Minimum number// of times 'A' has to be repeated// such that 'B' is a substring of itstatic int Min_repetation(String A, String B){ // To store minimum number of repetitions int ans = 1; // To store repeated string String S = A; // Until size of S is less than B while(S.Length < B.Length) { S += A; ans++; } // ans times repetition makes required answer if (issubstring(B, S)) return ans; // Add one more string of A if (issubstring(B, S + A)) return ans + 1; // If no such solution exists return -1;} // Driver codepublic static void Main(String[] args){ String A = "abcd", B = "cdabcdab"; // Function call Console.WriteLine(Min_repetation(A, B));}} // This code is contributed by 29AjayKumar <script> // Javascript program to find Minimum number of times A// has to be repeated such that B is a substring of it // Function to check if a number// is a substring of other or notfunction issubstring(str2, rep1){ var M = str2.length; var N = rep1.length; // Check for substring from starting // from i'th index of main string for (var i = 0; i <= N - M; i++) { var j; // For current index i, // check for pattern match for (j = 0; j < M; j++) if (rep1[i + j] != str2[j]) break; if (j == M) // pattern matched return true; } return false; // not a substring} // Function to find Minimum number of times A// has to be repeated such that B is a substring of itfunction Min_repetation(A, B){ // To store minimum number of repetitions var ans = 1; // To store repeated string var S = A; // Until size of S is less than B while(S.length < B.length) { S += A; ans++; } // ans times repetition makes required answer if (issubstring(B, S)) return ans; // Add one more string of A if (issubstring(B, S+A)) return ans + 1; // If no such solution exists return -1;} // Driver codevar A = "abcd", B = "cdabcdab"; // Function calldocument.write( Min_repetation(A, B)); </script> 3 Time Complexity: O(N * M) Auxiliary Space: O(1). Approach 2: Idea here is to try and find the string using a brute force string searching algorithm (n * m). The only difference here is to calculate the modulus (i % n) when the counter reaches the end of the string. C++ Java Python Javascript #include <bits/stdc++.h>using namespace std; int repeatedStringMatch(string A, string B){ int m = A.length(); int n = B.length(); int count; bool found = false; for (int i = 0; i < m; i++) { int j = i; int k = 0; count = 1; while (k < n && A[j] == B[k]) { if (k == n - 1) { found = true; break; } j = (j + 1) % m; if (j == 0) count++; k++; } if (found) return count; } return -1;}int main(){ string A = "abcd"; string B = "cdabcdab"; cout << repeatedStringMatch(A, B); return 0;} /*package whatever //do not write package name here */ import java.io.*; class GFG { static int repeatedStringMatch(String A, String B) { int m = A.length(); int n = B.length(); int count; boolean found = false; for (int i = 0; i < m; ++i) { int j = i; int k = 0; count = 1; while (k < n && A.charAt(j) == B.charAt(k)) { if (k == n - 1) { found = true; break; } j = (j + 1) % m; // if j = 0, it means we have repeated the // string if (j == 0) ++count; k += 1; } if (found) return count; } return -1; } public static void main(String[] args) { String A = "abcd", B = "cdabcdab"; // Function call System.out.println(repeatedStringMatch(A, B)); }} # Python implementation of this approachdef repeatedStringMatch(A, B): m = len(A) n = len(B) count = 0 found = False for i in range(m): j = i k = 0 count = 1 while k < n and A[j] == B[k] : if (k == n - 1) : found = True break j = (j + 1) % m if (j == 0): count = count + 1 k = k + 1 if (found): return count return -1 # Driver codeA = "abcd";B = "cdabcdab"; print(repeatedStringMatch(A, B)); # This code is contributed by shinjanpatra <script> // JavaScript implementation of this approach function repeatedStringMatch(A, B){ let m = A.length; let n = B.length; let count; let found = false; for (let i = 0; i < m; i++) { let j = i; let k = 0; count = 1; while (k < n && A[j] == B[k]) { if (k == n - 1) { found = true; break; } j = (j + 1) % m; if (j == 0) count++; k++; } if (found) return count; } return -1;} // Driver codelet A = "abcd";let B = "cdabcdab";document.write(repeatedStringMatch(A, B)); </script> // This code is contributed by shinjanpatra Time Complexity: O(N * M) Auxiliary Space: O(1). princiraj1992 29AjayKumar satycool sweetyty rutvik_56 pankajsharmagfg arorakashish0911 rushil ahuja 1 harshgupta597 shinjanpatra Google substring Data Structures Searching Strings Google Data Structures Searching Strings Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to Start Learning DSA? Introduction to Tree Data Structure Program to implement Singly Linked List in C++ using class Hash Functions and list/types of Hash functions What Should I Learn First: Data Structures or Algorithms? Binary Search Maximum and minimum of an array using minimum number of comparisons Linear Search Search an element in a sorted and rotated array Find the Missing Number
[ { "code": null, "e": 26299, "s": 26271, "text": "\n22 Feb, 2022" }, { "code": null, "e": 26467, "s": 26299, "text": "Given two strings A and B. The task is to find the minimum number of times A has to be repeated such that B is a substring of it. If no such solution exists, print -1." }, { "code": null, "e": 26478, "s": 26467, "text": "Examples: " }, { "code": null, "e": 26655, "s": 26478, "text": "Input : A = “abcd”, B = “cdabcdab” Output : 3 Repeating A three times (“abcdabcdabcd”), B is a substring of it. B is not a substring of A when it is repeated less than 3 times." }, { "code": null, "e": 26696, "s": 26655, "text": "Input : A = “ab”, B = “cab” Output : -1 " }, { "code": null, "e": 27289, "s": 26696, "text": "Approach : Imagine we wrote S = A+A+A+... If B is a substring of S, we only need to check whether some index 0 or 1 or .... length(A) -1 starts with B, as S is long enough to contain B, and S has a period of length(A).Now, suppose ans is the least number for which length(B) <= length(A * ans). We only need to check whether B is a substring of A * ans or A * (ans+1). If we try k < ans, then B has a larger length than A * ans and therefore can’t be a substring. When k = ans+1, A * k is already big enough to try all positions for B( A[i:i+length(B)] == B for i = 0, 1, ..., length(A) – 1)." }, { "code": null, "e": 27341, "s": 27289, "text": "Below is the implementation of the above approach: " }, { "code": null, "e": 27347, "s": 27341, "text": "C++14" }, { "code": null, "e": 27352, "s": 27347, "text": "Java" }, { "code": null, "e": 27360, "s": 27352, "text": "Python3" }, { "code": null, "e": 27363, "s": 27360, "text": "C#" }, { "code": null, "e": 27374, "s": 27363, "text": "Javascript" }, { "code": "// CPP program to find Minimum number of times A// has to be repeated such that B is a substring of it#include <bits/stdc++.h>using namespace std; // Function to check if a number// is a substring of other or notbool issubstring(string str2, string rep1){ int M = str2.length(); int N = rep1.length(); // Check for substring from starting // from i'th index of main string for (int i = 0; i <= N - M; i++) { int j; // For current index i, // check for pattern match for (j = 0; j < M; j++) if (rep1[i + j] != str2[j]) break; if (j == M) // pattern matched return true; } return false; // not a substring} // Function to find Minimum number of times A// has to be repeated such that B is a substring of itint Min_repetation(string A, string B){ // To store minimum number of repetitions int ans = 1; // To store repeated string string S = A; // Until size of S is less than B while(S.size() < B.size()) { S += A; ans++; } // ans times repetition makes required answer if (issubstring(B, S)) return ans; // Add one more string of A if (issubstring(B, S+A)) return ans + 1; // If no such solution exists return -1;} // Driver codeint main(){ string A = \"abcd\", B = \"cdabcdab\"; // Function call cout << Min_repetation(A, B); return 0;}", "e": 28822, "s": 27374, "text": null }, { "code": "// Java program to find minimum number// of times 'A' has to be repeated// such that 'B' is a substring of itclass GFG{ // Function to check if a number// is a substring of other or notstatic boolean issubstring(String str2, String rep1){ int M = str2.length(); int N = rep1.length(); // Check for substring from starting // from i'th index of main string for (int i = 0; i <= N - M; i++) { int j; // For current index i, // check for pattern match for (j = 0; j < M; j++) if (rep1.charAt(i + j) != str2.charAt(j)) break; if (j == M) // pattern matched return true; } return false; // not a substring} // Function to find Minimum number// of times 'A' has to be repeated// such that 'B' is a substring of itstatic int Min_repetation(String A, String B){ // To store minimum number of repetitions int ans = 1; // To store repeated string String S = A; // Until size of S is less than B while(S.length() < B.length()) { S += A; ans++; } // ans times repetition makes required answer if (issubstring(B, S)) return ans; // Add one more string of A if (issubstring(B, S + A)) return ans + 1; // If no such solution exists return -1;} // Driver codepublic static void main(String[] args){ String A = \"abcd\", B = \"cdabcdab\"; // Function call System.out.println(Min_repetation(A, B));}} // This code is contributed by PrinciRaj1992", "e": 30378, "s": 28822, "text": null }, { "code": "# Python3 program to find minimum number# of times 'A' has to be repeated# such that 'B' is a substring of it # Method to find Minimum number# of times 'A' has to be repeated# such that 'B' is a substring of itdef min_repetitions(a, b): len_a = len(a) len_b = len(b) for i in range(0, len_a): if a[i] == b[0]: k = i count = 1 for j in range(0, len_b): # we are reiterating over A again and # again for each value of B # Resetting A pointer back to 0 as B # is not empty yet if k >= len_a: k = 0 count = count + 1 # Resetting A means count # needs to be increased if a[k] != b[j]: break k = k + 1 # k is iterating over A else: return count return -1 # Driver CodeA = 'abcd'B = 'cdabcdab'print(min_repetitions(A, B)) # This code is contributed by satycool", "e": 31482, "s": 30378, "text": null }, { "code": "// C# program to find minimum number// of times 'A' has to be repeated// such that 'B' is a substring of itusing System; class GFG{ // Function to check if a number// is a substring of other or notstatic Boolean issubstring(String str2, String rep1){ int M = str2.Length; int N = rep1.Length; // Check for substring from starting // from i'th index of main string for (int i = 0; i <= N - M; i++) { int j; // For current index i, // check for pattern match for (j = 0; j < M; j++) if (rep1[i + j] != str2[j]) break; if (j == M) // pattern matched return true; } return false; // not a substring} // Function to find Minimum number// of times 'A' has to be repeated// such that 'B' is a substring of itstatic int Min_repetation(String A, String B){ // To store minimum number of repetitions int ans = 1; // To store repeated string String S = A; // Until size of S is less than B while(S.Length < B.Length) { S += A; ans++; } // ans times repetition makes required answer if (issubstring(B, S)) return ans; // Add one more string of A if (issubstring(B, S + A)) return ans + 1; // If no such solution exists return -1;} // Driver codepublic static void Main(String[] args){ String A = \"abcd\", B = \"cdabcdab\"; // Function call Console.WriteLine(Min_repetation(A, B));}} // This code is contributed by 29AjayKumar", "e": 33029, "s": 31482, "text": null }, { "code": "<script> // Javascript program to find Minimum number of times A// has to be repeated such that B is a substring of it // Function to check if a number// is a substring of other or notfunction issubstring(str2, rep1){ var M = str2.length; var N = rep1.length; // Check for substring from starting // from i'th index of main string for (var i = 0; i <= N - M; i++) { var j; // For current index i, // check for pattern match for (j = 0; j < M; j++) if (rep1[i + j] != str2[j]) break; if (j == M) // pattern matched return true; } return false; // not a substring} // Function to find Minimum number of times A// has to be repeated such that B is a substring of itfunction Min_repetation(A, B){ // To store minimum number of repetitions var ans = 1; // To store repeated string var S = A; // Until size of S is less than B while(S.length < B.length) { S += A; ans++; } // ans times repetition makes required answer if (issubstring(B, S)) return ans; // Add one more string of A if (issubstring(B, S+A)) return ans + 1; // If no such solution exists return -1;} // Driver codevar A = \"abcd\", B = \"cdabcdab\"; // Function calldocument.write( Min_repetation(A, B)); </script>", "e": 34401, "s": 33029, "text": null }, { "code": null, "e": 34403, "s": 34401, "text": "3" }, { "code": null, "e": 34456, "s": 34405, "text": "Time Complexity: O(N * M) Auxiliary Space: O(1). " }, { "code": null, "e": 34468, "s": 34456, "text": "Approach 2:" }, { "code": null, "e": 34673, "s": 34468, "text": "Idea here is to try and find the string using a brute force string searching algorithm (n * m). The only difference here is to calculate the modulus (i % n) when the counter reaches the end of the string." }, { "code": null, "e": 34677, "s": 34673, "text": "C++" }, { "code": null, "e": 34682, "s": 34677, "text": "Java" }, { "code": null, "e": 34689, "s": 34682, "text": "Python" }, { "code": null, "e": 34700, "s": 34689, "text": "Javascript" }, { "code": "#include <bits/stdc++.h>using namespace std; int repeatedStringMatch(string A, string B){ int m = A.length(); int n = B.length(); int count; bool found = false; for (int i = 0; i < m; i++) { int j = i; int k = 0; count = 1; while (k < n && A[j] == B[k]) { if (k == n - 1) { found = true; break; } j = (j + 1) % m; if (j == 0) count++; k++; } if (found) return count; } return -1;}int main(){ string A = \"abcd\"; string B = \"cdabcdab\"; cout << repeatedStringMatch(A, B); return 0;}", "e": 35372, "s": 34700, "text": null }, { "code": "/*package whatever //do not write package name here */ import java.io.*; class GFG { static int repeatedStringMatch(String A, String B) { int m = A.length(); int n = B.length(); int count; boolean found = false; for (int i = 0; i < m; ++i) { int j = i; int k = 0; count = 1; while (k < n && A.charAt(j) == B.charAt(k)) { if (k == n - 1) { found = true; break; } j = (j + 1) % m; // if j = 0, it means we have repeated the // string if (j == 0) ++count; k += 1; } if (found) return count; } return -1; } public static void main(String[] args) { String A = \"abcd\", B = \"cdabcdab\"; // Function call System.out.println(repeatedStringMatch(A, B)); }}", "e": 36362, "s": 35372, "text": null }, { "code": "# Python implementation of this approachdef repeatedStringMatch(A, B): m = len(A) n = len(B) count = 0 found = False for i in range(m): j = i k = 0 count = 1 while k < n and A[j] == B[k] : if (k == n - 1) : found = True break j = (j + 1) % m if (j == 0): count = count + 1 k = k + 1 if (found): return count return -1 # Driver codeA = \"abcd\";B = \"cdabcdab\"; print(repeatedStringMatch(A, B)); # This code is contributed by shinjanpatra", "e": 36978, "s": 36362, "text": null }, { "code": "<script> // JavaScript implementation of this approach function repeatedStringMatch(A, B){ let m = A.length; let n = B.length; let count; let found = false; for (let i = 0; i < m; i++) { let j = i; let k = 0; count = 1; while (k < n && A[j] == B[k]) { if (k == n - 1) { found = true; break; } j = (j + 1) % m; if (j == 0) count++; k++; } if (found) return count; } return -1;} // Driver codelet A = \"abcd\";let B = \"cdabcdab\";document.write(repeatedStringMatch(A, B)); </script> // This code is contributed by shinjanpatra", "e": 37679, "s": 36978, "text": null }, { "code": null, "e": 37707, "s": 37679, "text": " Time Complexity: O(N * M) " }, { "code": null, "e": 37731, "s": 37707, "text": "Auxiliary Space: O(1). " }, { "code": null, "e": 37745, "s": 37731, "text": "princiraj1992" }, { "code": null, "e": 37757, "s": 37745, "text": "29AjayKumar" }, { "code": null, "e": 37766, "s": 37757, "text": "satycool" }, { "code": null, "e": 37775, "s": 37766, "text": "sweetyty" }, { "code": null, "e": 37785, "s": 37775, "text": "rutvik_56" }, { "code": null, "e": 37801, "s": 37785, "text": "pankajsharmagfg" }, { "code": null, "e": 37818, "s": 37801, "text": "arorakashish0911" }, { "code": null, "e": 37833, "s": 37818, "text": "rushil ahuja 1" }, { "code": null, "e": 37847, "s": 37833, "text": "harshgupta597" }, { "code": null, "e": 37860, "s": 37847, "text": "shinjanpatra" }, { "code": null, "e": 37867, "s": 37860, "text": "Google" }, { "code": null, "e": 37877, "s": 37867, "text": "substring" }, { "code": null, "e": 37893, "s": 37877, "text": "Data Structures" }, { "code": null, "e": 37903, "s": 37893, "text": "Searching" }, { "code": null, "e": 37911, "s": 37903, "text": "Strings" }, { "code": null, "e": 37918, "s": 37911, "text": "Google" }, { "code": null, "e": 37934, "s": 37918, "text": "Data Structures" }, { "code": null, "e": 37944, "s": 37934, "text": "Searching" }, { "code": null, "e": 37952, "s": 37944, "text": "Strings" }, { "code": null, "e": 38050, "s": 37952, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 38077, "s": 38050, "text": "How to Start Learning DSA?" }, { "code": null, "e": 38113, "s": 38077, "text": "Introduction to Tree Data Structure" }, { "code": null, "e": 38172, "s": 38113, "text": "Program to implement Singly Linked List in C++ using class" }, { "code": null, "e": 38220, "s": 38172, "text": "Hash Functions and list/types of Hash functions" }, { "code": null, "e": 38278, "s": 38220, "text": "What Should I Learn First: Data Structures or Algorithms?" }, { "code": null, "e": 38292, "s": 38278, "text": "Binary Search" }, { "code": null, "e": 38360, "s": 38292, "text": "Maximum and minimum of an array using minimum number of comparisons" }, { "code": null, "e": 38374, "s": 38360, "text": "Linear Search" }, { "code": null, "e": 38422, "s": 38374, "text": "Search an element in a sorted and rotated array" } ]
RSA Digital Signature Scheme using Python - GeeksforGeeks
03 Aug, 2021 RSA algorithm is an asymmetric cryptography algorithm. Asymmetric actually means that it works on two different keys i.e. Public Key and Private Key. As the name describes that the Public Key is given to everyone and the Private key is kept private. An example of asymmetric cryptography : A client (for example browser) sends its public key to the server and requests for some data. The server encrypts the data using the client’s public key and sends the encrypted data. Client receives this data and decrypts it. Since this is asymmetric, nobody else except the browser can decrypt the data even if a third party has the public key of browser.Digital signatures are used to verify the authenticity of the message sent electronically. A digital signature algorithm uses a public key system. The intended transmitter signs his/her message with his/her private key and the intended receiver verifies it with the transmitter’s public key. A digital signature can provide message authentication, message integrity and non-repudiation services. RSA Key Generation: Choose two large prime numbers p and q Calculate n=p*q Select public key e such that it is not a factor of (p-1)*(q-1) Select private key d such that the following equation is true (d*e)mod(p-1)(q-1)=1 or d is inverse of E in modulo (p-1)*(q-1) RSA Digital Signature Scheme: In RSA, d is private; e and n are public. Alice creates her digital signature using S=M^d mod n where M is the message Alice sends Message M and Signature S to Bob Bob computes M1=S^e mod n If M1=M then Bob accepts the data sent by Alice. Below is the implementation. Python3 # Function to find gcd# of two numbersdef euclid(m, n): if n == 0: return m else: r = m % n return euclid(n, r) # Program to find# Multiplicative inversedef exteuclid(a, b): r1 = a r2 = b s1 = int(1) s2 = int(0) t1 = int(0) t2 = int(1) while r2 > 0: q = r1//r2 r = r1-q * r2 r1 = r2 r2 = r s = s1-q * s2 s1 = s2 s2 = s t = t1-q * t2 t1 = t2 t2 = t if t1 < 0: t1 = t1 % a return (r1, t1) # Enter two large prime# numbers p and qp = 823q = 953n = p * qPn = (p-1)*(q-1) # Generate encryption key# in range 1<e<Pnkey = [] for i in range(2, Pn): gcd = euclid(Pn, i) if gcd == 1: key.append(i) # Select an encryption key# from the above liste = int(313) # Obtain inverse of# encryption key in Z_Pnr, d = exteuclid(Pn, e)if r == 1: d = int(d) print("decryption key is: ", d) else: print("Multiplicative inverse for\ the given encryption key does not \ exist. Choose a different encryption key ") # Enter the message to be sentM = 19070 # Signature is created by AliceS = (M**d) % n # Alice sends M and S both to Bob# Bob generates message M1 using the# signature S, Alice's public key e# and product n.M1 = (S**e) % n # If M = M1 only then Bob accepts# the message sent by Alice. if M == M1: print("As M = M1, Accept the\ message sent by Alice")else: print("As M not equal to M1,\ Do not accept the message\ sent by Alice ") Output: decryption key is: 160009 As M = M1, Accept the message sent by Alice simmytarika5 Python-Miscellaneous 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 | Get unique values from a list Python | os.path.join() method Create a directory in Python Defaultdict in Python Python | Pandas dataframe.groupby()
[ { "code": null, "e": 25561, "s": 25533, "text": "\n03 Aug, 2021" }, { "code": null, "e": 25811, "s": 25561, "text": "RSA algorithm is an asymmetric cryptography algorithm. Asymmetric actually means that it works on two different keys i.e. Public Key and Private Key. As the name describes that the Public Key is given to everyone and the Private key is kept private." }, { "code": null, "e": 25851, "s": 25811, "text": "An example of asymmetric cryptography :" }, { "code": null, "e": 25946, "s": 25851, "text": "A client (for example browser) sends its public key to the server and requests for some data. " }, { "code": null, "e": 26036, "s": 25946, "text": "The server encrypts the data using the client’s public key and sends the encrypted data. " }, { "code": null, "e": 26080, "s": 26036, "text": "Client receives this data and decrypts it. " }, { "code": null, "e": 26608, "s": 26080, "text": "Since this is asymmetric, nobody else except the browser can decrypt the data even if a third party has the public key of browser.Digital signatures are used to verify the authenticity of the message sent electronically. A digital signature algorithm uses a public key system. The intended transmitter signs his/her message with his/her private key and the intended receiver verifies it with the transmitter’s public key. A digital signature can provide message authentication, message integrity and non-repudiation services. " }, { "code": null, "e": 26629, "s": 26608, "text": "RSA Key Generation: " }, { "code": null, "e": 26669, "s": 26629, "text": "Choose two large prime numbers p and q " }, { "code": null, "e": 26686, "s": 26669, "text": "Calculate n=p*q " }, { "code": null, "e": 26751, "s": 26686, "text": "Select public key e such that it is not a factor of (p-1)*(q-1) " }, { "code": null, "e": 26878, "s": 26751, "text": "Select private key d such that the following equation is true (d*e)mod(p-1)(q-1)=1 or d is inverse of E in modulo (p-1)*(q-1) " }, { "code": null, "e": 26952, "s": 26878, "text": "RSA Digital Signature Scheme: In RSA, d is private; e and n are public. " }, { "code": null, "e": 27030, "s": 26952, "text": "Alice creates her digital signature using S=M^d mod n where M is the message " }, { "code": null, "e": 27076, "s": 27030, "text": "Alice sends Message M and Signature S to Bob " }, { "code": null, "e": 27103, "s": 27076, "text": "Bob computes M1=S^e mod n " }, { "code": null, "e": 27153, "s": 27103, "text": "If M1=M then Bob accepts the data sent by Alice. " }, { "code": null, "e": 27183, "s": 27153, "text": "Below is the implementation. " }, { "code": null, "e": 27191, "s": 27183, "text": "Python3" }, { "code": "# Function to find gcd# of two numbersdef euclid(m, n): if n == 0: return m else: r = m % n return euclid(n, r) # Program to find# Multiplicative inversedef exteuclid(a, b): r1 = a r2 = b s1 = int(1) s2 = int(0) t1 = int(0) t2 = int(1) while r2 > 0: q = r1//r2 r = r1-q * r2 r1 = r2 r2 = r s = s1-q * s2 s1 = s2 s2 = s t = t1-q * t2 t1 = t2 t2 = t if t1 < 0: t1 = t1 % a return (r1, t1) # Enter two large prime# numbers p and qp = 823q = 953n = p * qPn = (p-1)*(q-1) # Generate encryption key# in range 1<e<Pnkey = [] for i in range(2, Pn): gcd = euclid(Pn, i) if gcd == 1: key.append(i) # Select an encryption key# from the above liste = int(313) # Obtain inverse of# encryption key in Z_Pnr, d = exteuclid(Pn, e)if r == 1: d = int(d) print(\"decryption key is: \", d) else: print(\"Multiplicative inverse for\\ the given encryption key does not \\ exist. Choose a different encryption key \") # Enter the message to be sentM = 19070 # Signature is created by AliceS = (M**d) % n # Alice sends M and S both to Bob# Bob generates message M1 using the# signature S, Alice's public key e# and product n.M1 = (S**e) % n # If M = M1 only then Bob accepts# the message sent by Alice. if M == M1: print(\"As M = M1, Accept the\\ message sent by Alice\")else: print(\"As M not equal to M1,\\ Do not accept the message\\ sent by Alice \")", "e": 28752, "s": 27191, "text": null }, { "code": null, "e": 28760, "s": 28752, "text": "Output:" }, { "code": null, "e": 28831, "s": 28760, "text": "decryption key is: 160009\nAs M = M1, Accept the message sent by Alice" }, { "code": null, "e": 28846, "s": 28833, "text": "simmytarika5" }, { "code": null, "e": 28867, "s": 28846, "text": "Python-Miscellaneous" }, { "code": null, "e": 28874, "s": 28867, "text": "Python" }, { "code": null, "e": 28972, "s": 28874, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 29004, "s": 28972, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 29046, "s": 29004, "text": "Check if element exists in list in Python" }, { "code": null, "e": 29088, "s": 29046, "text": "How To Convert Python Dictionary To JSON?" }, { "code": null, "e": 29144, "s": 29088, "text": "How to drop one or multiple columns in Pandas Dataframe" }, { "code": null, "e": 29171, "s": 29144, "text": "Python Classes and Objects" }, { "code": null, "e": 29210, "s": 29171, "text": "Python | Get unique values from a list" }, { "code": null, "e": 29241, "s": 29210, "text": "Python | os.path.join() method" }, { "code": null, "e": 29270, "s": 29241, "text": "Create a directory in Python" }, { "code": null, "e": 29292, "s": 29270, "text": "Defaultdict in Python" } ]
Python | sympy.Lambda() method - GeeksforGeeks
17 Jul, 2019 With the help of sympy.Lambda() method, we can perform any mathematical operation by just defining the formula and then pass the parameters with reference variable by using sympy.Lambda(). Syntax : sympy.Lambda()Return : Return the result of mathematical formula. Example #1 :In this example we can see that we are able to perform any mathematical operation by using sympy.Lambda() method. # import sympyfrom sympy import * # Use sympy.Lambda() methodx = symbols('x')gfg = Lambda(x, x + 1) print(gfg(9)) Output : 10 Example #2 : # import sympyfrom sympy import * # Use sympy.Lambda() methodx, y = symbols('x y')gfg = Lambda((x, y), x * y) print(gfg(9, 5)) Output : 45 SymPy 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 | Get unique values from a list Python | os.path.join() method Defaultdict in Python Create a directory in Python Python | Pandas dataframe.groupby()
[ { "code": null, "e": 25537, "s": 25509, "text": "\n17 Jul, 2019" }, { "code": null, "e": 25726, "s": 25537, "text": "With the help of sympy.Lambda() method, we can perform any mathematical operation by just defining the formula and then pass the parameters with reference variable by using sympy.Lambda()." }, { "code": null, "e": 25801, "s": 25726, "text": "Syntax : sympy.Lambda()Return : Return the result of mathematical formula." }, { "code": null, "e": 25927, "s": 25801, "text": "Example #1 :In this example we can see that we are able to perform any mathematical operation by using sympy.Lambda() method." }, { "code": "# import sympyfrom sympy import * # Use sympy.Lambda() methodx = symbols('x')gfg = Lambda(x, x + 1) print(gfg(9))", "e": 26043, "s": 25927, "text": null }, { "code": null, "e": 26052, "s": 26043, "text": "Output :" }, { "code": null, "e": 26055, "s": 26052, "text": "10" }, { "code": null, "e": 26068, "s": 26055, "text": "Example #2 :" }, { "code": "# import sympyfrom sympy import * # Use sympy.Lambda() methodx, y = symbols('x y')gfg = Lambda((x, y), x * y) print(gfg(9, 5))", "e": 26197, "s": 26068, "text": null }, { "code": null, "e": 26206, "s": 26197, "text": "Output :" }, { "code": null, "e": 26209, "s": 26206, "text": "45" }, { "code": null, "e": 26215, "s": 26209, "text": "SymPy" }, { "code": null, "e": 26222, "s": 26215, "text": "Python" }, { "code": null, "e": 26320, "s": 26222, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 26352, "s": 26320, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 26394, "s": 26352, "text": "Check if element exists in list in Python" }, { "code": null, "e": 26436, "s": 26394, "text": "How To Convert Python Dictionary To JSON?" }, { "code": null, "e": 26492, "s": 26436, "text": "How to drop one or multiple columns in Pandas Dataframe" }, { "code": null, "e": 26519, "s": 26492, "text": "Python Classes and Objects" }, { "code": null, "e": 26558, "s": 26519, "text": "Python | Get unique values from a list" }, { "code": null, "e": 26589, "s": 26558, "text": "Python | os.path.join() method" }, { "code": null, "e": 26611, "s": 26589, "text": "Defaultdict in Python" }, { "code": null, "e": 26640, "s": 26611, "text": "Create a directory in Python" } ]
How to get name of dataframe column in PySpark ? - GeeksforGeeks
11 Aug, 2021 In this article, we will discuss how to get the name of the Dataframe column in PySpark. To get the name of the columns present in the Dataframe we are using the columns function through this function we will get the list of all the column names present in the Dataframe. Syntax: df.columns We can also get the names of the columns from the list of StructFields then extract the name of the columns from the list of StructFields. Syntax: df.schema.fields Let’s create a sample dataframe given below: Python # importing necessary librariesfrom pyspark.sql import SparkSession # function to create new SparkSessiondef create_session(): spk = SparkSession.builder \ .master("local") \ .appName("Product_details.com") \ .getOrCreate() return spk def create_df(spark, data, schema): df1 = spark.createDataFrame(data, schema) return df1 if __name__ == "__main__": input_data = [("Uttar Pradesh", 122000, 89600, 12238), ("Maharashtra", 454000, 380000, 67985), ("Tamil Nadu", 115000, 102000, 13933), ("Karnataka", 147000, 111000, 15306), ("Kerala", 153000, 124000, 5259)] # calling function to create SparkSession spark = create_session() schema = ["State", "Cases", "Recovered", "Deaths"] # calling function to create dataframe df = create_df(spark, input_data, schema) # visualizing the dataframe df.show() Output: Example 1: Using df.columns In the example, we have created the Dataframe, then we’re getting the list of column names present in the Dataframe using df.columns then we have printed the list of column names. Python # getting the list of column namescol = df.columns # printingprint(f'List of column names: {col}') # visualizing the dataframedf.show() Output: Example 2: Using df.schema.fields In the example, we have created the Dataframe, then we are getting the list of StructFields that contains the name of the column, datatype of the column, and nullable flag. We have stored this list of StructFields in the variable named as ‘field’ then iterate the for loop of field and for getting the count of iteration we have taken the count of and used enumerate() function for getting the count from 1 onwards we have passed 1 after passing the field in the enumerate() function. Then print the count and names of the column simultaneously. Python # getting the list of StructFieldsfield = df.schema.fields # using for loop to iterate and enumerate# for indexing or numberingfor count, col_name in enumerate(field, 1): # printing the column names print(count, "-", col_name.name) # visualizing the dataframe df.show() Output: Example 3: Using df.printSchema() Another way of seeing or getting the names of the column present in the dataframe we can see the Schema of the Dataframe, this can be done by the function printSchema() this function is used to print the schema of the Dataframe from that scheme we can see all the column names. Python # printing Dataframe schema to# get the column namesdf.printSchema() # visualizing the dataframedf.show() Output: adnanirshad158 surinderdawra388 Picked Python-Pyspark Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to Install PIP on Windows ? 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 | Get unique values from a list Python | os.path.join() method Create a directory in Python Defaultdict in Python Python | Pandas dataframe.groupby()
[ { "code": null, "e": 25537, "s": 25509, "text": "\n11 Aug, 2021" }, { "code": null, "e": 25627, "s": 25537, "text": "In this article, we will discuss how to get the name of the Dataframe column in PySpark. " }, { "code": null, "e": 25810, "s": 25627, "text": "To get the name of the columns present in the Dataframe we are using the columns function through this function we will get the list of all the column names present in the Dataframe." }, { "code": null, "e": 25818, "s": 25810, "text": "Syntax:" }, { "code": null, "e": 25829, "s": 25818, "text": "df.columns" }, { "code": null, "e": 25968, "s": 25829, "text": "We can also get the names of the columns from the list of StructFields then extract the name of the columns from the list of StructFields." }, { "code": null, "e": 25976, "s": 25968, "text": "Syntax:" }, { "code": null, "e": 25993, "s": 25976, "text": "df.schema.fields" }, { "code": null, "e": 26038, "s": 25993, "text": "Let’s create a sample dataframe given below:" }, { "code": null, "e": 26045, "s": 26038, "text": "Python" }, { "code": "# importing necessary librariesfrom pyspark.sql import SparkSession # function to create new SparkSessiondef create_session(): spk = SparkSession.builder \\ .master(\"local\") \\ .appName(\"Product_details.com\") \\ .getOrCreate() return spk def create_df(spark, data, schema): df1 = spark.createDataFrame(data, schema) return df1 if __name__ == \"__main__\": input_data = [(\"Uttar Pradesh\", 122000, 89600, 12238), (\"Maharashtra\", 454000, 380000, 67985), (\"Tamil Nadu\", 115000, 102000, 13933), (\"Karnataka\", 147000, 111000, 15306), (\"Kerala\", 153000, 124000, 5259)] # calling function to create SparkSession spark = create_session() schema = [\"State\", \"Cases\", \"Recovered\", \"Deaths\"] # calling function to create dataframe df = create_df(spark, input_data, schema) # visualizing the dataframe df.show()", "e": 26971, "s": 26045, "text": null }, { "code": null, "e": 26979, "s": 26971, "text": "Output:" }, { "code": null, "e": 27007, "s": 26979, "text": "Example 1: Using df.columns" }, { "code": null, "e": 27187, "s": 27007, "text": "In the example, we have created the Dataframe, then we’re getting the list of column names present in the Dataframe using df.columns then we have printed the list of column names." }, { "code": null, "e": 27194, "s": 27187, "text": "Python" }, { "code": "# getting the list of column namescol = df.columns # printingprint(f'List of column names: {col}') # visualizing the dataframedf.show()", "e": 27330, "s": 27194, "text": null }, { "code": null, "e": 27341, "s": 27333, "text": "Output:" }, { "code": null, "e": 27378, "s": 27343, "text": "Example 2: Using df.schema.fields " }, { "code": null, "e": 27551, "s": 27378, "text": "In the example, we have created the Dataframe, then we are getting the list of StructFields that contains the name of the column, datatype of the column, and nullable flag." }, { "code": null, "e": 27925, "s": 27551, "text": "We have stored this list of StructFields in the variable named as ‘field’ then iterate the for loop of field and for getting the count of iteration we have taken the count of and used enumerate() function for getting the count from 1 onwards we have passed 1 after passing the field in the enumerate() function. Then print the count and names of the column simultaneously. " }, { "code": null, "e": 27932, "s": 27925, "text": "Python" }, { "code": "# getting the list of StructFieldsfield = df.schema.fields # using for loop to iterate and enumerate# for indexing or numberingfor count, col_name in enumerate(field, 1): # printing the column names print(count, \"-\", col_name.name) # visualizing the dataframe df.show()", "e": 28218, "s": 27932, "text": null }, { "code": null, "e": 28226, "s": 28218, "text": "Output:" }, { "code": null, "e": 28260, "s": 28226, "text": "Example 3: Using df.printSchema()" }, { "code": null, "e": 28539, "s": 28260, "text": "Another way of seeing or getting the names of the column present in the dataframe we can see the Schema of the Dataframe, this can be done by the function printSchema() this function is used to print the schema of the Dataframe from that scheme we can see all the column names. " }, { "code": null, "e": 28546, "s": 28539, "text": "Python" }, { "code": "# printing Dataframe schema to# get the column namesdf.printSchema() # visualizing the dataframedf.show()", "e": 28652, "s": 28546, "text": null }, { "code": null, "e": 28662, "s": 28652, "text": " Output:" }, { "code": null, "e": 28681, "s": 28666, "text": "adnanirshad158" }, { "code": null, "e": 28698, "s": 28681, "text": "surinderdawra388" }, { "code": null, "e": 28705, "s": 28698, "text": "Picked" }, { "code": null, "e": 28720, "s": 28705, "text": "Python-Pyspark" }, { "code": null, "e": 28727, "s": 28720, "text": "Python" }, { "code": null, "e": 28825, "s": 28727, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 28857, "s": 28825, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 28899, "s": 28857, "text": "Check if element exists in list in Python" }, { "code": null, "e": 28941, "s": 28899, "text": "How To Convert Python Dictionary To JSON?" }, { "code": null, "e": 28997, "s": 28941, "text": "How to drop one or multiple columns in Pandas Dataframe" }, { "code": null, "e": 29024, "s": 28997, "text": "Python Classes and Objects" }, { "code": null, "e": 29063, "s": 29024, "text": "Python | Get unique values from a list" }, { "code": null, "e": 29094, "s": 29063, "text": "Python | os.path.join() method" }, { "code": null, "e": 29123, "s": 29094, "text": "Create a directory in Python" }, { "code": null, "e": 29145, "s": 29123, "text": "Defaultdict in Python" } ]
Create a dictionary with list comprehension in Python - GeeksforGeeks
02 Dec, 2021 In this article, we will discuss how to create a dictionary with list comprehension in Python. Using dict() method we can convert list comprehension to the dictionary. Here we will pass the list_comprehension like a list of tuple values such that the first value act as a key in the dictionary and the second value act as the value in the dictionary. Syntax: dict(list_comprehension) Example 1: Python program to create a student list comprehension and convert it into a dictionary. Python3 # create a list comprehension with student agedata = [('sravan', 23), ('ojaswi', 15), ('rohith', 8), ('gnanesh', 4), ('bobby', 20)] # using dict methoddict(data) Output: {'bobby': 20, 'gnanesh': 4, 'ojaswi': 15, 'rohith': 8, 'sravan': 23} We can also use the following for loop inside the dict() method. Syntax: dict([(key,value) for key,value in data]) Example 2: Python3 # create a list comprehension with student agedata = [('sravan', 23), ('ojaswi', 15), ('rohith', 8), ('gnanesh', 4), ('bobby', 20)] # using dict method inside for loopdict([(key, value) for key, value in data]) Output: {'bobby': 20, 'gnanesh': 4, 'ojaswi': 15, 'rohith': 8, 'sravan': 23} Here in this method, we will create two lists such that values in the first list will be the keys and the second list values will be the values in the dictionary. Syntax: dict(zip(key_list,value_list)) Example 1: Python3 # create a list with student namename = ['sravan', 'ojaswi', 'rohith', 'gnanesh', 'bobby'] # create a list with student ageage = [23, 21, 32, 11, 23] # using dict method with zip()dict(zip(name, age)) Output: {'bobby': 23, 'gnanesh': 11, 'ojaswi': 21, 'rohith': 32, 'sravan': 23} Here we can iterate over the given date using iterable for loop. Syntax: {key: value for (key, value) in data} Example: Python3 # create a list comprehension with student agedata = [('sravan', 23), ('ojaswi', 15), ('rohith', 8), ('gnanesh', 4), ('bobby', 20)] # display using iterable method{key: value for (key, value) in data} Output: {'bobby': 20, 'gnanesh': 4, 'ojaswi': 15, 'rohith': 8, 'sravan': 23} We can add a filter to the iterable to a list comprehension to create a dictionary only for particular data based on condition. Filtering means adding values to dictionary-based on conditions. Syntax: {key: value for (key, value) in data condition} Example: Python3 # create a list comprehension with student agedata = [('sravan', 23), ('ojaswi', 15), ('rohith', 8), ('gnanesh', 4), ('bobby', 20)] # create a dictionary with list# comprehension if value is equal to 20print({key: value for (key, value) in data if value == 20}) # create a dictionary with list# comprehension if value is greater than to 10print({key: value for (key, value) in data if value > 10}) # create a dictionary with list# comprehension if key is sravanprint({key: value for (key, value) in data if key == 'sravan'}) Output: {'bobby': 20} {'sravan': 23, 'ojaswi': 15, 'bobby': 20} {'sravan': 23} sagar0719kumar sumitgumber28 Picked Python dictionary-programs python-dict Python Python Programs python-dict Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to Install PIP on Windows ? Check if element exists in list in Python How To Convert Python Dictionary To JSON? Python Classes and Objects How to drop one or multiple columns in Pandas Dataframe Defaultdict in Python Python | Get dictionary keys as a list Python | Split string into list of characters Python | Convert a list to dictionary How to print without newline in Python?
[ { "code": null, "e": 25537, "s": 25509, "text": "\n02 Dec, 2021" }, { "code": null, "e": 25632, "s": 25537, "text": "In this article, we will discuss how to create a dictionary with list comprehension in Python." }, { "code": null, "e": 25888, "s": 25632, "text": "Using dict() method we can convert list comprehension to the dictionary. Here we will pass the list_comprehension like a list of tuple values such that the first value act as a key in the dictionary and the second value act as the value in the dictionary." }, { "code": null, "e": 25921, "s": 25888, "text": "Syntax: dict(list_comprehension)" }, { "code": null, "e": 26020, "s": 25921, "text": "Example 1: Python program to create a student list comprehension and convert it into a dictionary." }, { "code": null, "e": 26028, "s": 26020, "text": "Python3" }, { "code": "# create a list comprehension with student agedata = [('sravan', 23), ('ojaswi', 15), ('rohith', 8), ('gnanesh', 4), ('bobby', 20)] # using dict methoddict(data)", "e": 26197, "s": 26028, "text": null }, { "code": null, "e": 26205, "s": 26197, "text": "Output:" }, { "code": null, "e": 26274, "s": 26205, "text": "{'bobby': 20, 'gnanesh': 4, 'ojaswi': 15, 'rohith': 8, 'sravan': 23}" }, { "code": null, "e": 26339, "s": 26274, "text": "We can also use the following for loop inside the dict() method." }, { "code": null, "e": 26414, "s": 26339, "text": "Syntax: dict([(key,value) for key,value in data]) " }, { "code": null, "e": 26425, "s": 26414, "text": "Example 2:" }, { "code": null, "e": 26433, "s": 26425, "text": "Python3" }, { "code": "# create a list comprehension with student agedata = [('sravan', 23), ('ojaswi', 15), ('rohith', 8), ('gnanesh', 4), ('bobby', 20)] # using dict method inside for loopdict([(key, value) for key, value in data])", "e": 26651, "s": 26433, "text": null }, { "code": null, "e": 26659, "s": 26651, "text": "Output:" }, { "code": null, "e": 26728, "s": 26659, "text": "{'bobby': 20, 'gnanesh': 4, 'ojaswi': 15, 'rohith': 8, 'sravan': 23}" }, { "code": null, "e": 26891, "s": 26728, "text": "Here in this method, we will create two lists such that values in the first list will be the keys and the second list values will be the values in the dictionary." }, { "code": null, "e": 26930, "s": 26891, "text": "Syntax: dict(zip(key_list,value_list))" }, { "code": null, "e": 26941, "s": 26930, "text": "Example 1:" }, { "code": null, "e": 26949, "s": 26941, "text": "Python3" }, { "code": "# create a list with student namename = ['sravan', 'ojaswi', 'rohith', 'gnanesh', 'bobby'] # create a list with student ageage = [23, 21, 32, 11, 23] # using dict method with zip()dict(zip(name, age))", "e": 27150, "s": 26949, "text": null }, { "code": null, "e": 27158, "s": 27150, "text": "Output:" }, { "code": null, "e": 27229, "s": 27158, "text": "{'bobby': 23, 'gnanesh': 11, 'ojaswi': 21, 'rohith': 32, 'sravan': 23}" }, { "code": null, "e": 27294, "s": 27229, "text": "Here we can iterate over the given date using iterable for loop." }, { "code": null, "e": 27340, "s": 27294, "text": "Syntax: {key: value for (key, value) in data}" }, { "code": null, "e": 27349, "s": 27340, "text": "Example:" }, { "code": null, "e": 27357, "s": 27349, "text": "Python3" }, { "code": "# create a list comprehension with student agedata = [('sravan', 23), ('ojaswi', 15), ('rohith', 8), ('gnanesh', 4), ('bobby', 20)] # display using iterable method{key: value for (key, value) in data}", "e": 27566, "s": 27357, "text": null }, { "code": null, "e": 27574, "s": 27566, "text": "Output:" }, { "code": null, "e": 27643, "s": 27574, "text": "{'bobby': 20, 'gnanesh': 4, 'ojaswi': 15, 'rohith': 8, 'sravan': 23}" }, { "code": null, "e": 27836, "s": 27643, "text": "We can add a filter to the iterable to a list comprehension to create a dictionary only for particular data based on condition. Filtering means adding values to dictionary-based on conditions." }, { "code": null, "e": 27892, "s": 27836, "text": "Syntax: {key: value for (key, value) in data condition}" }, { "code": null, "e": 27901, "s": 27892, "text": "Example:" }, { "code": null, "e": 27909, "s": 27901, "text": "Python3" }, { "code": "# create a list comprehension with student agedata = [('sravan', 23), ('ojaswi', 15), ('rohith', 8), ('gnanesh', 4), ('bobby', 20)] # create a dictionary with list# comprehension if value is equal to 20print({key: value for (key, value) in data if value == 20}) # create a dictionary with list# comprehension if value is greater than to 10print({key: value for (key, value) in data if value > 10}) # create a dictionary with list# comprehension if key is sravanprint({key: value for (key, value) in data if key == 'sravan'})", "e": 28443, "s": 27909, "text": null }, { "code": null, "e": 28451, "s": 28443, "text": "Output:" }, { "code": null, "e": 28522, "s": 28451, "text": "{'bobby': 20}\n{'sravan': 23, 'ojaswi': 15, 'bobby': 20}\n{'sravan': 23}" }, { "code": null, "e": 28537, "s": 28522, "text": "sagar0719kumar" }, { "code": null, "e": 28551, "s": 28537, "text": "sumitgumber28" }, { "code": null, "e": 28558, "s": 28551, "text": "Picked" }, { "code": null, "e": 28585, "s": 28558, "text": "Python dictionary-programs" }, { "code": null, "e": 28597, "s": 28585, "text": "python-dict" }, { "code": null, "e": 28604, "s": 28597, "text": "Python" }, { "code": null, "e": 28620, "s": 28604, "text": "Python Programs" }, { "code": null, "e": 28632, "s": 28620, "text": "python-dict" }, { "code": null, "e": 28730, "s": 28632, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 28762, "s": 28730, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 28804, "s": 28762, "text": "Check if element exists in list in Python" }, { "code": null, "e": 28846, "s": 28804, "text": "How To Convert Python Dictionary To JSON?" }, { "code": null, "e": 28873, "s": 28846, "text": "Python Classes and Objects" }, { "code": null, "e": 28929, "s": 28873, "text": "How to drop one or multiple columns in Pandas Dataframe" }, { "code": null, "e": 28951, "s": 28929, "text": "Defaultdict in Python" }, { "code": null, "e": 28990, "s": 28951, "text": "Python | Get dictionary keys as a list" }, { "code": null, "e": 29036, "s": 28990, "text": "Python | Split string into list of characters" }, { "code": null, "e": 29074, "s": 29036, "text": "Python | Convert a list to dictionary" } ]
CSS | Specificity - GeeksforGeeks
27 Jul, 2021 When more than one set of CSS rules apply to the same element, the browser will have to decide which specific set will be applied to the element. The rules the browser follows are collectively called Specificity Specificity Rules include: CSS style applied by referencing external stylesheet has lowest precedence and is overridden by Internal and inline CSS. Internal CSS is overridden by inline CSS. Inline CSS has highest priority and overrides all other selectors. Example: html <html> <head> <link rel="stylesheet" type="text/css" href="external.css"> <style type="text/css"> h1 { background-color: red; color: white; } h2 { color: blue; } </style></head> <body> <h1> Internal CSS overrides external CSS </h1> <h2 style="color: green;"> Inline CSS overrides internal CSS </h2></body> </html> “external.css” of Example-1: html h1{ background-color: lightgreen;}h2{ color: pink;} Output: inline internal and external css Specificity Hierarchy :Every element selector has a position in the Hierarchy. Inline style: Inline style has highest priority. Identifiers(ID): ID have the second highest priority. Classes, pseudo-classes and attributes: Classes, pseudo-classes and attributes are come next. Elements and pseudo-elements: Elements and pseudo-elements have lowest priority. Inline style: Inline style has highest priority. Identifiers(ID): ID have the second highest priority. Classes, pseudo-classes and attributes: Classes, pseudo-classes and attributes are come next. Elements and pseudo-elements: Elements and pseudo-elements have lowest priority. Example-2: html <html> <head> <style type="text/css"> h1 { background-color: red; color: white; } #second { background-color: black; color: white; } .third { background-color: pink; color: blue; } #second1 { color: blue; } .third1 { color: red; } </style></head> <body> <h1 id="second" class="third"> ID has highest priority. </h1> <h1> Element selectors has lowest priority. </h1> <h1 class="third"> Classes have higher priority than element selectors. </h1> <h2 style="color: green;" id="second1" class="third1"> Inline CSS has highest priority. </h2> </body> </html> Output: Specificity Hierarchy Note: When two or more selectors have equal specificity, the last(latest) one counts. Universal selectors like body and inherited selectors have least specificity. abhishek0719kadiyan Picked CSS Web Technologies Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to insert spaces/tabs in text using HTML/CSS? Top 10 Projects For Beginners To Practice HTML and CSS Skills How to update Node.js and NPM to next version ? How to create footer to stay at the bottom of a Web page? How to apply style to parent if it has child with CSS? Remove elements from a JavaScript Array Installation of Node.js on Linux Convert a string to an integer in JavaScript How to fetch data from an API in ReactJS ? How to insert spaces/tabs in text using HTML/CSS?
[ { "code": null, "e": 29316, "s": 29288, "text": "\n27 Jul, 2021" }, { "code": null, "e": 29529, "s": 29316, "text": "When more than one set of CSS rules apply to the same element, the browser will have to decide which specific set will be applied to the element. The rules the browser follows are collectively called Specificity " }, { "code": null, "e": 29558, "s": 29529, "text": "Specificity Rules include: " }, { "code": null, "e": 29679, "s": 29558, "text": "CSS style applied by referencing external stylesheet has lowest precedence and is overridden by Internal and inline CSS." }, { "code": null, "e": 29721, "s": 29679, "text": "Internal CSS is overridden by inline CSS." }, { "code": null, "e": 29788, "s": 29721, "text": "Inline CSS has highest priority and overrides all other selectors." }, { "code": null, "e": 29798, "s": 29788, "text": "Example: " }, { "code": null, "e": 29803, "s": 29798, "text": "html" }, { "code": "<html> <head> <link rel=\"stylesheet\" type=\"text/css\" href=\"external.css\"> <style type=\"text/css\"> h1 { background-color: red; color: white; } h2 { color: blue; } </style></head> <body> <h1> Internal CSS overrides external CSS </h1> <h2 style=\"color: green;\"> Inline CSS overrides internal CSS </h2></body> </html>", "e": 30222, "s": 29803, "text": null }, { "code": null, "e": 30253, "s": 30222, "text": "“external.css” of Example-1: " }, { "code": null, "e": 30258, "s": 30253, "text": "html" }, { "code": "h1{ background-color: lightgreen;}h2{ color: pink;}", "e": 30316, "s": 30258, "text": null }, { "code": null, "e": 30326, "s": 30316, "text": "Output: " }, { "code": null, "e": 30359, "s": 30326, "text": "inline internal and external css" }, { "code": null, "e": 30439, "s": 30359, "text": "Specificity Hierarchy :Every element selector has a position in the Hierarchy. " }, { "code": null, "e": 30722, "s": 30439, "text": "Inline style: Inline style has highest priority. Identifiers(ID): ID have the second highest priority. Classes, pseudo-classes and attributes: Classes, pseudo-classes and attributes are come next. Elements and pseudo-elements: Elements and pseudo-elements have lowest priority. " }, { "code": null, "e": 30773, "s": 30722, "text": "Inline style: Inline style has highest priority. " }, { "code": null, "e": 30829, "s": 30773, "text": "Identifiers(ID): ID have the second highest priority. " }, { "code": null, "e": 30925, "s": 30829, "text": "Classes, pseudo-classes and attributes: Classes, pseudo-classes and attributes are come next. " }, { "code": null, "e": 31008, "s": 30925, "text": "Elements and pseudo-elements: Elements and pseudo-elements have lowest priority. " }, { "code": null, "e": 31020, "s": 31008, "text": "Example-2: " }, { "code": null, "e": 31025, "s": 31020, "text": "html" }, { "code": "<html> <head> <style type=\"text/css\"> h1 { background-color: red; color: white; } #second { background-color: black; color: white; } .third { background-color: pink; color: blue; } #second1 { color: blue; } .third1 { color: red; } </style></head> <body> <h1 id=\"second\" class=\"third\"> ID has highest priority. </h1> <h1> Element selectors has lowest priority. </h1> <h1 class=\"third\"> Classes have higher priority than element selectors. </h1> <h2 style=\"color: green;\" id=\"second1\" class=\"third1\"> Inline CSS has highest priority. </h2> </body> </html>", "e": 31832, "s": 31025, "text": null }, { "code": null, "e": 31842, "s": 31832, "text": "Output: " }, { "code": null, "e": 31864, "s": 31842, "text": "Specificity Hierarchy" }, { "code": null, "e": 31871, "s": 31864, "text": "Note: " }, { "code": null, "e": 31951, "s": 31871, "text": "When two or more selectors have equal specificity, the last(latest) one counts." }, { "code": null, "e": 32029, "s": 31951, "text": "Universal selectors like body and inherited selectors have least specificity." }, { "code": null, "e": 32049, "s": 32029, "text": "abhishek0719kadiyan" }, { "code": null, "e": 32056, "s": 32049, "text": "Picked" }, { "code": null, "e": 32060, "s": 32056, "text": "CSS" }, { "code": null, "e": 32077, "s": 32060, "text": "Web Technologies" }, { "code": null, "e": 32175, "s": 32077, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 32225, "s": 32175, "text": "How to insert spaces/tabs in text using HTML/CSS?" }, { "code": null, "e": 32287, "s": 32225, "text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills" }, { "code": null, "e": 32335, "s": 32287, "text": "How to update Node.js and NPM to next version ?" }, { "code": null, "e": 32393, "s": 32335, "text": "How to create footer to stay at the bottom of a Web page?" }, { "code": null, "e": 32448, "s": 32393, "text": "How to apply style to parent if it has child with CSS?" }, { "code": null, "e": 32488, "s": 32448, "text": "Remove elements from a JavaScript Array" }, { "code": null, "e": 32521, "s": 32488, "text": "Installation of Node.js on Linux" }, { "code": null, "e": 32566, "s": 32521, "text": "Convert a string to an integer in JavaScript" }, { "code": null, "e": 32609, "s": 32566, "text": "How to fetch data from an API in ReactJS ?" } ]
Include all existing fields and add new fields to document in MongoDB?
You can achieve this with the help of $addFields operator. To understand the concept, let us create a collection with the document. The query to create a collection with a document is as follows − > db.addFieldDemo.insertOne({"EmployeeId":101,"EmployeeName":"Larry","EmployeeDetails":{ "EmployeeSalary":65000,"EmployeeCity":"New York","Message":"Hi"}}); { "acknowledged" : true, "insertedId" : ObjectId("5c7f654d8d10a061296a3c44") } Display all documents from a collection with the help of find() method. The query is as follows − > db.addFieldDemo.find().pretty(); The following is the output − { "_id" : ObjectId("5c7f654d8d10a061296a3c44"), "EmployeeId" : 101, "EmployeeName" : "Larry", "EmployeeDetails" : { "EmployeeSalary" : 65000, "EmployeeCity" : "New York", "Message" : "Hi" } } Here is the query to include all existing fields and add new fields to document in MongoDB − > db.addFieldDemo.aggregate([ { "$addFields": { "EmployeeBasicSalary":"$EmployeeDetails.EmployeeSalary" } } ]).pretty(); The following is the output − { "_id" : ObjectId("5c7f654d8d10a061296a3c44"), "EmployeeId" : 101, "EmployeeName" : "Larry", "EmployeeDetails" : { "EmployeeSalary" : 65000, "EmployeeCity" : "New York", "Message" : "Hi" }, "EmployeeBasicSalary" : 65000 } Look at the sample output, “EmployeeBasicSalary” has been added.
[ { "code": null, "e": 1259, "s": 1062, "text": "You can achieve this with the help of $addFields operator. To understand the concept, let us create a collection with the document. The query to create a collection with a document is as follows −" }, { "code": null, "e": 1504, "s": 1259, "text": "> db.addFieldDemo.insertOne({\"EmployeeId\":101,\"EmployeeName\":\"Larry\",\"EmployeeDetails\":{\n \"EmployeeSalary\":65000,\"EmployeeCity\":\"New York\",\"Message\":\"Hi\"}});\n{\n \"acknowledged\" : true,\n \"insertedId\" : ObjectId(\"5c7f654d8d10a061296a3c44\")\n}" }, { "code": null, "e": 1602, "s": 1504, "text": "Display all documents from a collection with the help of find() method. The query is as follows −" }, { "code": null, "e": 1637, "s": 1602, "text": "> db.addFieldDemo.find().pretty();" }, { "code": null, "e": 1667, "s": 1637, "text": "The following is the output −" }, { "code": null, "e": 1892, "s": 1667, "text": "{\n \"_id\" : ObjectId(\"5c7f654d8d10a061296a3c44\"),\n \"EmployeeId\" : 101,\n \"EmployeeName\" : \"Larry\",\n \"EmployeeDetails\" : {\n \"EmployeeSalary\" : 65000,\n \"EmployeeCity\" : \"New York\",\n \"Message\" : \"Hi\"\n }\n}" }, { "code": null, "e": 1985, "s": 1892, "text": "Here is the query to include all existing fields and add new fields to document in MongoDB −" }, { "code": null, "e": 2106, "s": 1985, "text": "> db.addFieldDemo.aggregate([ { \"$addFields\": { \"EmployeeBasicSalary\":\"$EmployeeDetails.EmployeeSalary\" } } ]).pretty();" }, { "code": null, "e": 2136, "s": 2106, "text": "The following is the output −" }, { "code": null, "e": 2395, "s": 2136, "text": "{\n \"_id\" : ObjectId(\"5c7f654d8d10a061296a3c44\"),\n \"EmployeeId\" : 101,\n \"EmployeeName\" : \"Larry\",\n \"EmployeeDetails\" : {\n \"EmployeeSalary\" : 65000,\n \"EmployeeCity\" : \"New York\",\n \"Message\" : \"Hi\"\n },\n \"EmployeeBasicSalary\" : 65000\n}" }, { "code": null, "e": 2460, "s": 2395, "text": "Look at the sample output, “EmployeeBasicSalary” has been added." } ]
p5.js mouseReleased() Function - GeeksforGeeks
04 Mar, 2021 The mouseReleased() function in p5.js works when mouse button released. The touchEnded() function is used instead of mouseReleased() function when mouseReleased() function is not defined. Syntax: mouseReleased(Event) Below programs illustrate the mouseReleased() function in p5.js: Example 1: This example uses mouseReleased() function to change the background color. function setup() { // Create Canvas createCanvas(500, 500);} let value = 0; function draw() { // Set the background color background(200); // Fill the color fill(value, value-50, value-100); // Create rectangle rect(25, 25, 460, 440); // Set the filled color fill('lightgreen'); // Set the font size textSize(15); // Display result text('Keep on Clicking the Mouse Across' + ' the page \nto change Canvas Color.', windowHeight/10, windowWidth/4);} function mouseReleased() { value = value + 5; if (value > 255) { value = 0; }} Output: Example 2: This example uses mouseReleased() function to change the mouse pointer color. let valueX;let valueY; function setup() { // Create Canvas createCanvas(500, 500);} function draw() { // Set background color background(200); // Fill the color fill('green'); // Set font size textSize(25); text('Drag mouse to change color', 30, 30); // Fill color according to mouseMoved() fill(valueX, 255-valueY, 255-valueX); // Draw ellipse ellipse(mouseX, mouseY, 115, 115);} function mouseReleased() { valueX = mouseX%255; valueY = mouseY%255;} Output: Reference: https://p5js.org/reference/#/p5/mouseReleased JavaScript-p5.js 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 Convert a string to an integer in JavaScript Differences between Functional Components and Class Components in React How to calculate the number of days between two dates in javascript? File uploading in React.js Top 10 Front End Developer Skills That You Need in 2022 Installation of Node.js on Linux Top 10 Projects For Beginners To Practice HTML and CSS Skills How to fetch data from an API in ReactJS ? How to insert spaces/tabs in text using HTML/CSS?
[ { "code": null, "e": 43301, "s": 43273, "text": "\n04 Mar, 2021" }, { "code": null, "e": 43489, "s": 43301, "text": "The mouseReleased() function in p5.js works when mouse button released. The touchEnded() function is used instead of mouseReleased() function when mouseReleased() function is not defined." }, { "code": null, "e": 43497, "s": 43489, "text": "Syntax:" }, { "code": null, "e": 43518, "s": 43497, "text": "mouseReleased(Event)" }, { "code": null, "e": 43583, "s": 43518, "text": "Below programs illustrate the mouseReleased() function in p5.js:" }, { "code": null, "e": 43669, "s": 43583, "text": "Example 1: This example uses mouseReleased() function to change the background color." }, { "code": "function setup() { // Create Canvas createCanvas(500, 500);} let value = 0; function draw() { // Set the background color background(200); // Fill the color fill(value, value-50, value-100); // Create rectangle rect(25, 25, 460, 440); // Set the filled color fill('lightgreen'); // Set the font size textSize(15); // Display result text('Keep on Clicking the Mouse Across' + ' the page \\nto change Canvas Color.', windowHeight/10, windowWidth/4);} function mouseReleased() { value = value + 5; if (value > 255) { value = 0; }}", "e": 44320, "s": 43669, "text": null }, { "code": null, "e": 44328, "s": 44320, "text": "Output:" }, { "code": null, "e": 44417, "s": 44328, "text": "Example 2: This example uses mouseReleased() function to change the mouse pointer color." }, { "code": "let valueX;let valueY; function setup() { // Create Canvas createCanvas(500, 500);} function draw() { // Set background color background(200); // Fill the color fill('green'); // Set font size textSize(25); text('Drag mouse to change color', 30, 30); // Fill color according to mouseMoved() fill(valueX, 255-valueY, 255-valueX); // Draw ellipse ellipse(mouseX, mouseY, 115, 115);} function mouseReleased() { valueX = mouseX%255; valueY = mouseY%255;}", "e": 44963, "s": 44417, "text": null }, { "code": null, "e": 44971, "s": 44963, "text": "Output:" }, { "code": null, "e": 45028, "s": 44971, "text": "Reference: https://p5js.org/reference/#/p5/mouseReleased" }, { "code": null, "e": 45045, "s": 45028, "text": "JavaScript-p5.js" }, { "code": null, "e": 45056, "s": 45045, "text": "JavaScript" }, { "code": null, "e": 45073, "s": 45056, "text": "Web Technologies" }, { "code": null, "e": 45171, "s": 45073, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 45180, "s": 45171, "text": "Comments" }, { "code": null, "e": 45193, "s": 45180, "text": "Old Comments" }, { "code": null, "e": 45254, "s": 45193, "text": "Difference between var, let and const keywords in JavaScript" }, { "code": null, "e": 45299, "s": 45254, "text": "Convert a string to an integer in JavaScript" }, { "code": null, "e": 45371, "s": 45299, "text": "Differences between Functional Components and Class Components in React" }, { "code": null, "e": 45440, "s": 45371, "text": "How to calculate the number of days between two dates in javascript?" }, { "code": null, "e": 45467, "s": 45440, "text": "File uploading in React.js" }, { "code": null, "e": 45523, "s": 45467, "text": "Top 10 Front End Developer Skills That You Need in 2022" }, { "code": null, "e": 45556, "s": 45523, "text": "Installation of Node.js on Linux" }, { "code": null, "e": 45618, "s": 45556, "text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills" }, { "code": null, "e": 45661, "s": 45618, "text": "How to fetch data from an API in ReactJS ?" } ]
Replace Character in a String in Java without using replace() method
To replace a character in a String, without using the replace() method, try the below logic. Let’s say the following is our string. String str = "The Haunting of Hill House!"; To replace character at a position with another character, use the substring() method login. Here, we are replacing 7th position with character ‘p’ int pos = 7; char rep = 'p'; String res = str.substring(0, pos) + rep + str.substring(pos + 1); The following is the complete example wherein a character at position 7 is replaced. Live Demo public class Demo { public static void main(String[] args) { String str = "The Haunting of Hill House!"; System.out.println("String: "+str); // replacing character at position 7 int pos = 7; char rep = 'p'; String res = str.substring(0, pos) + rep + str.substring(pos + 1); System.out.println("String after replacing a character: "+res); } } String: The Haunting of Hill House! String after replacing a character: The Haupting of Hill House!
[ { "code": null, "e": 1155, "s": 1062, "text": "To replace a character in a String, without using the replace() method, try the below logic." }, { "code": null, "e": 1194, "s": 1155, "text": "Let’s say the following is our string." }, { "code": null, "e": 1238, "s": 1194, "text": "String str = \"The Haunting of Hill House!\";" }, { "code": null, "e": 1386, "s": 1238, "text": "To replace character at a position with another character, use the substring() method login. Here, we are replacing 7th position with character ‘p’" }, { "code": null, "e": 1482, "s": 1386, "text": "int pos = 7;\nchar rep = 'p';\nString res = str.substring(0, pos) + rep + str.substring(pos + 1);" }, { "code": null, "e": 1567, "s": 1482, "text": "The following is the complete example wherein a character at position 7 is replaced." }, { "code": null, "e": 1578, "s": 1567, "text": " Live Demo" }, { "code": null, "e": 1977, "s": 1578, "text": "public class Demo {\n public static void main(String[] args) {\n String str = \"The Haunting of Hill House!\";\n System.out.println(\"String: \"+str);\n // replacing character at position 7\n int pos = 7;\n char rep = 'p';\n String res = str.substring(0, pos) + rep + str.substring(pos + 1);\n System.out.println(\"String after replacing a character: \"+res);\n }\n}" }, { "code": null, "e": 2077, "s": 1977, "text": "String: The Haunting of Hill House!\nString after replacing a character: The Haupting of Hill House!" } ]
Dart - Boolean - GeeksforGeeks
28 Feb, 2021 Dart language provides a pre-defined data type called boolean which can store two possible values, either true or false. To declare a boolean variable in Dart programming language, the keyword bool is used. Most commonly, boolean is used in decision-making statements. The syntax for declaring a boolean value is as follows: Syntax: bool variable_name = true/false; Example 1: The following example shows how we can assign boolean values in case of comparison of 2 predefined values. Dart main() { bool check; int val1=12; int val2=9; // Assigning variable check // value depending on condition check=(val1>val2); print(check);} Output: Example 2: The following example shows how we can use boolean values to check which of the two arguments passed is greater. Dart main(List<String> arguments) { // Taking values of arguments // inside variables val1 and val2 int val1=int.parse(arguments[0]); int val2=int.parse(arguments[1]); bool check; // Assigning variable check // value depending on condition check=(val1>val2); if(check){ print('First argument is greater'); }else{ print('Second argument is greater or both are equal'); } } Suppose we run this dart program named main.dart using : dart main.dart 12 9 Output: In the above example, as the value inside the first argument (12) is greater than the value of the second argument (9), the value inside the boolean variable check becomes true. Now, as if the condition is true the first statement is printed. Example 3: The following example shows how we can use boolean values to check which of the passed 2 strings is greater. Dart main(List<String> arguments) { //Taking values of lengths inside variables len1 and len2 int len1=arguments[0].length; int len2=arguments[1].length; bool check; //Assigning variable check value depending on condition check=(len1>len2); if(check){ print('First length is greater and its length is $len1'); }else{ print('Second length is greater or equal and its value is $len2'); } } Suppose we run this dart program named main.dart using : dart main.dart GeeksforGeeks Dart Output: In the above example, as the length of the first string (13) is greater than the length of the second string (4), the value inside the boolean variable check becomes true. Now, as if the condition is true the first statement is printed. Dart Data-types Picked Technical Scripter 2020 Dart Technical Scripter Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Flutter - Custom Bottom Navigation Bar ListView Class in Flutter Flutter - Stack Widget What is widgets in Flutter? Android Studio Setup for Flutter Development Flutter - Flexible Widget Flutter - BorderRadius Widget Simple Calculator App using Flutter Format Dates in Flutter Flutter - Positioned Widget
[ { "code": null, "e": 24010, "s": 23982, "text": "\n28 Feb, 2021" }, { "code": null, "e": 24279, "s": 24010, "text": "Dart language provides a pre-defined data type called boolean which can store two possible values, either true or false. To declare a boolean variable in Dart programming language, the keyword bool is used. Most commonly, boolean is used in decision-making statements." }, { "code": null, "e": 24335, "s": 24279, "text": "The syntax for declaring a boolean value is as follows:" }, { "code": null, "e": 24376, "s": 24335, "text": "Syntax: bool variable_name = true/false;" }, { "code": null, "e": 24387, "s": 24376, "text": "Example 1:" }, { "code": null, "e": 24494, "s": 24387, "text": "The following example shows how we can assign boolean values in case of comparison of 2 predefined values." }, { "code": null, "e": 24499, "s": 24494, "text": "Dart" }, { "code": "main() { bool check; int val1=12; int val2=9; // Assigning variable check // value depending on condition check=(val1>val2); print(check);}", "e": 24660, "s": 24499, "text": null }, { "code": null, "e": 24668, "s": 24660, "text": "Output:" }, { "code": null, "e": 24679, "s": 24668, "text": "Example 2:" }, { "code": null, "e": 24792, "s": 24679, "text": "The following example shows how we can use boolean values to check which of the two arguments passed is greater." }, { "code": null, "e": 24797, "s": 24792, "text": "Dart" }, { "code": "main(List<String> arguments) { // Taking values of arguments // inside variables val1 and val2 int val1=int.parse(arguments[0]); int val2=int.parse(arguments[1]); bool check; // Assigning variable check // value depending on condition check=(val1>val2); if(check){ print('First argument is greater'); }else{ print('Second argument is greater or both are equal'); } }", "e": 25213, "s": 24797, "text": null }, { "code": null, "e": 25271, "s": 25213, "text": "Suppose we run this dart program named main.dart using : " }, { "code": null, "e": 25291, "s": 25271, "text": "dart main.dart 12 9" }, { "code": null, "e": 25299, "s": 25291, "text": "Output:" }, { "code": null, "e": 25543, "s": 25299, "text": "In the above example, as the value inside the first argument (12) is greater than the value of the second argument (9), the value inside the boolean variable check becomes true. Now, as if the condition is true the first statement is printed. " }, { "code": null, "e": 25554, "s": 25543, "text": "Example 3:" }, { "code": null, "e": 25663, "s": 25554, "text": "The following example shows how we can use boolean values to check which of the passed 2 strings is greater." }, { "code": null, "e": 25668, "s": 25663, "text": "Dart" }, { "code": "main(List<String> arguments) { //Taking values of lengths inside variables len1 and len2 int len1=arguments[0].length; int len2=arguments[1].length; bool check; //Assigning variable check value depending on condition check=(len1>len2); if(check){ print('First length is greater and its length is $len1'); }else{ print('Second length is greater or equal and its value is $len2'); } }", "e": 26088, "s": 25668, "text": null }, { "code": null, "e": 26145, "s": 26088, "text": "Suppose we run this dart program named main.dart using :" }, { "code": null, "e": 26179, "s": 26145, "text": "dart main.dart GeeksforGeeks Dart" }, { "code": null, "e": 26187, "s": 26179, "text": "Output:" }, { "code": null, "e": 26425, "s": 26187, "text": "In the above example, as the length of the first string (13) is greater than the length of the second string (4), the value inside the boolean variable check becomes true. Now, as if the condition is true the first statement is printed. " }, { "code": null, "e": 26441, "s": 26425, "text": "Dart Data-types" }, { "code": null, "e": 26448, "s": 26441, "text": "Picked" }, { "code": null, "e": 26472, "s": 26448, "text": "Technical Scripter 2020" }, { "code": null, "e": 26477, "s": 26472, "text": "Dart" }, { "code": null, "e": 26496, "s": 26477, "text": "Technical Scripter" }, { "code": null, "e": 26594, "s": 26496, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 26633, "s": 26594, "text": "Flutter - Custom Bottom Navigation Bar" }, { "code": null, "e": 26659, "s": 26633, "text": "ListView Class in Flutter" }, { "code": null, "e": 26682, "s": 26659, "text": "Flutter - Stack Widget" }, { "code": null, "e": 26710, "s": 26682, "text": "What is widgets in Flutter?" }, { "code": null, "e": 26755, "s": 26710, "text": "Android Studio Setup for Flutter Development" }, { "code": null, "e": 26781, "s": 26755, "text": "Flutter - Flexible Widget" }, { "code": null, "e": 26811, "s": 26781, "text": "Flutter - BorderRadius Widget" }, { "code": null, "e": 26847, "s": 26811, "text": "Simple Calculator App using Flutter" }, { "code": null, "e": 26871, "s": 26847, "text": "Format Dates in Flutter" } ]
How to Write All of Your SQL Queries in Pandas | by Terence Shin | Towards Data Science
What makes SQL so amazing is that it’s so easy to learn — the reason why it’s so easy to learn is that the code syntax is so intuitive. Pandas on the other hand isn’t so intuitive, especially if you started out with SQL first like I did. Personally, what I found really helpful was thinking about how I would manipulate my data in SQL, and then replicate it in Pandas. And so, if you’re trying to be more proficient in Pandas, I highly recommend that you take this approach as well. Thus, this article serves as a cheatsheet, dictionary, a guide, whatever you want to call it so that you can refer to this when using Pandas. And with that said, let’s dive into it! Selecting RowsCombining tablesFiltering tablesSorting valuesAggregate functions Selecting Rows Combining tables Filtering tables Sorting values Aggregate functions If you want to select an entire table, simply call the name of the table: # SQLSELECT * FROM table_df# Pandastable_df If you want to select specific columns from a table, list the columns that you want in double brackets: # SQLSELECT column_a, column_b FROM table_df# Pandastable_df[['column_a', 'column_b']] Simply use .drop_duplicates() to get distinct values: # SQLSELECT DISTINCT column_a FROM table_df# Pandastable_df['column_a'].drop_duplicates() If you want to rename a column, use .rename(): # SQLSELECT column_a as Apple, column_b as Banana FROM table_df# Pandastable_df[['column_a', 'column_b']].rename(columns={'column_a':'Apple', 'column_b':'Banana'}) For the equivalent of SELECT CASE WHEN, you can use np.select() where you first specify your choices and the values for each choice. If you want to include multiple conditions per choice, check out this article. # SQLSELECT CASE WHEN column_a > 30 THEN "Large" WHEN column_a <= 30 THEN "Small" END AS SizeFROM table_df# Pandasconditions = [table_df['column_a']>30, table_df['column_b']<=30]choices = ['Large', 'Small']table_df['Size'] = np.select(conditions, choices) Simply use .merge() to join tables, You can specify whether you want it to be a LEFT, RIGHT, INNER, or OUTER join using the “how” parameter. # SQLSELECT * FROM table_1 t1 LEFT JOIN table_2 t1 on t1.lkey = t2.rkey # Pandastable_1.merge(table_2, left_on='lkey', right_on='rkey', how='left') Simply use pd.concat(): # SQLSELECT * FROM table_1UNION ALLSELECT * FROM table_2# Pandasfinal_table = pd.concat([table_1, table_2]) When filtering a DataFrame the same way you would use a WHERE clause in SQL, you simply need to define the criteria within square brackets: # SQLSELECT * FROM table_df WHERE column_a = 1# Pandastable_df[table_df['column_a'] == 1] When you want to select a certain column from a table and filter it with a different column, follow the format below (if you want to read more about it, check out this link): # SQLSELECT column_a FROM table_df WHERE column_b = 1# Pandastable_df[table_df['column_b']==1]['column_a'] If you want to filter by multiple criteria, simply wrap each condition in parenthesis and separate each condition using ‘&’. For more variations of this, check out this link. # SQLSELECT * FROM table_df WHERE column_a = 1 AND column_b = 2# Pandastable_df[(table_df['column_a']==1) & (table_df['column_b']==2)] The equivalent of LIKE in SQL is .str.contains(). If you want to apply case insensitivity, simply add case=False in the parameters (see here). # SQLSELECT * FROM table_df WHERE column_a LIKE '%ball%'# Pandastable_df[table_df['column_a'].str.contains('ball')] The equivalent of IN() in SQL is .isin(). # SQLSELECT * FROM table_df WHERE column_a IN('Canada', 'USA')# Pandastable_df[table_df['column_a'].isin(['Canada', 'USA'])] The equivalent of ORDER BY in SQL is .sort_values(). Use the ‘ascending’ parameter to specify whether you want to sort the values in ascending or descending order — the default is ascending just like SQL. # SQLSELECT * FROM table_df ORDER BY column_a DESC# Pandastable_df.sort_values('column_a', ascending=False) If you want to ORDER BY multiple columns, list the columns in brackets, and specify the direction of ordering in the ‘ascending’ parameter in brackets as well. Make sure that you follow the respective order of the columns that you list. # SQLSELECT * FROM table_df ORDER BY column_a DESC, column_b ASC# Pandastable_df.sort_values(['column_a', 'column_b'], ascending=[False, True]) You’ll notice a common pattern for aggregate functions. To replicate COUNT DISTINCT, simply use .groupby() and .nunique(). See here for more info: # SQLSELECT column_a, COUNT DISTINCT(ID) FROM table_dfGROUP BY column_a# Pandastable_df.groupby('column_a')['ID'].nunique() # SQLSELECT column_a, SUM(revenue) FROM table_dfGROUP BY column_a # Pandastable_df.groupby(['column_a', 'revenue']).sum() # SQLSELECT column_a, AVG(revenue) FROM table_dfGROUP BY column_a# Pandastable_df.groupby('column_a')['revenue'].mean() Hopefully, this serves as a useful guide when manipulating data with Pandas. Don’t feel like you have to memorize all of this either! This is something that I constantly come back to when I work with Pandas. Eventually, with enough practice, you’ll feel more comfortable with Pandas and will understand the underlying mechanics enough where you won’t need to rely on cheat sheets like this one. As always, I wish you the best in your endeavors! :) Not sure what to read next? I’ve picked another article for you: towardsdatascience.com If you enjoyed this, follow me on Medium for more Follow me on Kaggle for more content! Let’s connect on LinkedIn Interested in collaborating? Check out my website.
[ { "code": null, "e": 308, "s": 172, "text": "What makes SQL so amazing is that it’s so easy to learn — the reason why it’s so easy to learn is that the code syntax is so intuitive." }, { "code": null, "e": 410, "s": 308, "text": "Pandas on the other hand isn’t so intuitive, especially if you started out with SQL first like I did." }, { "code": null, "e": 655, "s": 410, "text": "Personally, what I found really helpful was thinking about how I would manipulate my data in SQL, and then replicate it in Pandas. And so, if you’re trying to be more proficient in Pandas, I highly recommend that you take this approach as well." }, { "code": null, "e": 797, "s": 655, "text": "Thus, this article serves as a cheatsheet, dictionary, a guide, whatever you want to call it so that you can refer to this when using Pandas." }, { "code": null, "e": 837, "s": 797, "text": "And with that said, let’s dive into it!" }, { "code": null, "e": 917, "s": 837, "text": "Selecting RowsCombining tablesFiltering tablesSorting valuesAggregate functions" }, { "code": null, "e": 932, "s": 917, "text": "Selecting Rows" }, { "code": null, "e": 949, "s": 932, "text": "Combining tables" }, { "code": null, "e": 966, "s": 949, "text": "Filtering tables" }, { "code": null, "e": 981, "s": 966, "text": "Sorting values" }, { "code": null, "e": 1001, "s": 981, "text": "Aggregate functions" }, { "code": null, "e": 1075, "s": 1001, "text": "If you want to select an entire table, simply call the name of the table:" }, { "code": null, "e": 1119, "s": 1075, "text": "# SQLSELECT * FROM table_df# Pandastable_df" }, { "code": null, "e": 1223, "s": 1119, "text": "If you want to select specific columns from a table, list the columns that you want in double brackets:" }, { "code": null, "e": 1310, "s": 1223, "text": "# SQLSELECT column_a, column_b FROM table_df# Pandastable_df[['column_a', 'column_b']]" }, { "code": null, "e": 1364, "s": 1310, "text": "Simply use .drop_duplicates() to get distinct values:" }, { "code": null, "e": 1454, "s": 1364, "text": "# SQLSELECT DISTINCT column_a FROM table_df# Pandastable_df['column_a'].drop_duplicates()" }, { "code": null, "e": 1501, "s": 1454, "text": "If you want to rename a column, use .rename():" }, { "code": null, "e": 1665, "s": 1501, "text": "# SQLSELECT column_a as Apple, column_b as Banana FROM table_df# Pandastable_df[['column_a', 'column_b']].rename(columns={'column_a':'Apple', 'column_b':'Banana'})" }, { "code": null, "e": 1798, "s": 1665, "text": "For the equivalent of SELECT CASE WHEN, you can use np.select() where you first specify your choices and the values for each choice." }, { "code": null, "e": 1877, "s": 1798, "text": "If you want to include multiple conditions per choice, check out this article." }, { "code": null, "e": 2155, "s": 1877, "text": "# SQLSELECT CASE WHEN column_a > 30 THEN \"Large\" WHEN column_a <= 30 THEN \"Small\" END AS SizeFROM table_df# Pandasconditions = [table_df['column_a']>30, table_df['column_b']<=30]choices = ['Large', 'Small']table_df['Size'] = np.select(conditions, choices)" }, { "code": null, "e": 2296, "s": 2155, "text": "Simply use .merge() to join tables, You can specify whether you want it to be a LEFT, RIGHT, INNER, or OUTER join using the “how” parameter." }, { "code": null, "e": 2452, "s": 2296, "text": "# SQLSELECT * FROM table_1 t1 LEFT JOIN table_2 t1 on t1.lkey = t2.rkey # Pandastable_1.merge(table_2, left_on='lkey', right_on='rkey', how='left')" }, { "code": null, "e": 2476, "s": 2452, "text": "Simply use pd.concat():" }, { "code": null, "e": 2584, "s": 2476, "text": "# SQLSELECT * FROM table_1UNION ALLSELECT * FROM table_2# Pandasfinal_table = pd.concat([table_1, table_2])" }, { "code": null, "e": 2724, "s": 2584, "text": "When filtering a DataFrame the same way you would use a WHERE clause in SQL, you simply need to define the criteria within square brackets:" }, { "code": null, "e": 2814, "s": 2724, "text": "# SQLSELECT * FROM table_df WHERE column_a = 1# Pandastable_df[table_df['column_a'] == 1]" }, { "code": null, "e": 2989, "s": 2814, "text": "When you want to select a certain column from a table and filter it with a different column, follow the format below (if you want to read more about it, check out this link):" }, { "code": null, "e": 3096, "s": 2989, "text": "# SQLSELECT column_a FROM table_df WHERE column_b = 1# Pandastable_df[table_df['column_b']==1]['column_a']" }, { "code": null, "e": 3271, "s": 3096, "text": "If you want to filter by multiple criteria, simply wrap each condition in parenthesis and separate each condition using ‘&’. For more variations of this, check out this link." }, { "code": null, "e": 3406, "s": 3271, "text": "# SQLSELECT * FROM table_df WHERE column_a = 1 AND column_b = 2# Pandastable_df[(table_df['column_a']==1) & (table_df['column_b']==2)]" }, { "code": null, "e": 3549, "s": 3406, "text": "The equivalent of LIKE in SQL is .str.contains(). If you want to apply case insensitivity, simply add case=False in the parameters (see here)." }, { "code": null, "e": 3665, "s": 3549, "text": "# SQLSELECT * FROM table_df WHERE column_a LIKE '%ball%'# Pandastable_df[table_df['column_a'].str.contains('ball')]" }, { "code": null, "e": 3707, "s": 3665, "text": "The equivalent of IN() in SQL is .isin()." }, { "code": null, "e": 3832, "s": 3707, "text": "# SQLSELECT * FROM table_df WHERE column_a IN('Canada', 'USA')# Pandastable_df[table_df['column_a'].isin(['Canada', 'USA'])]" }, { "code": null, "e": 4037, "s": 3832, "text": "The equivalent of ORDER BY in SQL is .sort_values(). Use the ‘ascending’ parameter to specify whether you want to sort the values in ascending or descending order — the default is ascending just like SQL." }, { "code": null, "e": 4145, "s": 4037, "text": "# SQLSELECT * FROM table_df ORDER BY column_a DESC# Pandastable_df.sort_values('column_a', ascending=False)" }, { "code": null, "e": 4382, "s": 4145, "text": "If you want to ORDER BY multiple columns, list the columns in brackets, and specify the direction of ordering in the ‘ascending’ parameter in brackets as well. Make sure that you follow the respective order of the columns that you list." }, { "code": null, "e": 4526, "s": 4382, "text": "# SQLSELECT * FROM table_df ORDER BY column_a DESC, column_b ASC# Pandastable_df.sort_values(['column_a', 'column_b'], ascending=[False, True])" }, { "code": null, "e": 4582, "s": 4526, "text": "You’ll notice a common pattern for aggregate functions." }, { "code": null, "e": 4673, "s": 4582, "text": "To replicate COUNT DISTINCT, simply use .groupby() and .nunique(). See here for more info:" }, { "code": null, "e": 4797, "s": 4673, "text": "# SQLSELECT column_a, COUNT DISTINCT(ID) FROM table_dfGROUP BY column_a# Pandastable_df.groupby('column_a')['ID'].nunique()" }, { "code": null, "e": 4919, "s": 4797, "text": "# SQLSELECT column_a, SUM(revenue) FROM table_dfGROUP BY column_a # Pandastable_df.groupby(['column_a', 'revenue']).sum()" }, { "code": null, "e": 5039, "s": 4919, "text": "# SQLSELECT column_a, AVG(revenue) FROM table_dfGROUP BY column_a# Pandastable_df.groupby('column_a')['revenue'].mean()" }, { "code": null, "e": 5247, "s": 5039, "text": "Hopefully, this serves as a useful guide when manipulating data with Pandas. Don’t feel like you have to memorize all of this either! This is something that I constantly come back to when I work with Pandas." }, { "code": null, "e": 5434, "s": 5247, "text": "Eventually, with enough practice, you’ll feel more comfortable with Pandas and will understand the underlying mechanics enough where you won’t need to rely on cheat sheets like this one." }, { "code": null, "e": 5487, "s": 5434, "text": "As always, I wish you the best in your endeavors! :)" }, { "code": null, "e": 5552, "s": 5487, "text": "Not sure what to read next? I’ve picked another article for you:" }, { "code": null, "e": 5575, "s": 5552, "text": "towardsdatascience.com" }, { "code": null, "e": 5625, "s": 5575, "text": "If you enjoyed this, follow me on Medium for more" }, { "code": null, "e": 5663, "s": 5625, "text": "Follow me on Kaggle for more content!" }, { "code": null, "e": 5689, "s": 5663, "text": "Let’s connect on LinkedIn" } ]
Counting number of lines in text file using java
We can read lines in a file using BufferedReader class of Java. See the example below − Consider the following text file in the classpath. test.txt This is Line 1 This is Line 2 This is Line 3 This is Line 4 This is Line 5 This is Line 6 This is Line 7 This is Line 8 This is Line 9 This is Line 10 Tester.java import java.io.BufferedReader; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.IOException; import java.io.InputStreamReader; public class Tester { private static final String FILE_PATH = "data.txt"; public static void main(String args[]) throws IOException { FileUtil fileUtil = new FileUtil(FILE_PATH); System.out.println("No. of lines in file: " + fileUtil.getLineCount()); } } class FileUtil { static BufferedReader reader = null; public FileUtil(String filePath) throws FileNotFoundException { File file = new File(filePath); FileInputStream fileStream = new FileInputStream(file); InputStreamReader input = new InputStreamReader(fileStream); reader = new BufferedReader(input); } public static int getLineCount() throws IOException { int lineCount = 0; String data; while((data = reader.readLine()) != null) { lineCount++; } return lineCount; } } This will produce the following result − No. of lines in file: 10
[ { "code": null, "e": 1150, "s": 1062, "text": "We can read lines in a file using BufferedReader class of Java. See the example below −" }, { "code": null, "e": 1201, "s": 1150, "text": "Consider the following text file in the classpath." }, { "code": null, "e": 1210, "s": 1201, "text": "test.txt" }, { "code": null, "e": 1361, "s": 1210, "text": "This is Line 1\nThis is Line 2\nThis is Line 3\nThis is Line 4\nThis is Line 5\nThis is Line 6\nThis is Line 7\nThis is Line 8\nThis is Line 9\nThis is Line 10" }, { "code": null, "e": 1373, "s": 1361, "text": "Tester.java" }, { "code": null, "e": 2429, "s": 1373, "text": "import java.io.BufferedReader;\nimport java.io.File;\nimport java.io.FileInputStream;\nimport java.io.FileNotFoundException;\nimport java.io.IOException;\nimport java.io.InputStreamReader;\n\npublic class Tester {\n\n private static final String FILE_PATH = \"data.txt\";\n public static void main(String args[]) throws IOException {\n FileUtil fileUtil = new FileUtil(FILE_PATH);\n System.out.println(\"No. of lines in file: \" + fileUtil.getLineCount());\n }\n}\n\nclass FileUtil {\n static BufferedReader reader = null; \n public FileUtil(String filePath) throws FileNotFoundException {\n File file = new File(filePath);\n FileInputStream fileStream = new FileInputStream(file);\n InputStreamReader input = new InputStreamReader(fileStream);\n reader = new BufferedReader(input);\n }\n\n public static int getLineCount() throws IOException {\n int lineCount = 0;\n String data; \n while((data = reader.readLine()) != null) {\n lineCount++; \n } \n return lineCount;\n }\n}" }, { "code": null, "e": 2470, "s": 2429, "text": "This will produce the following result −" }, { "code": null, "e": 2495, "s": 2470, "text": "No. of lines in file: 10" } ]
Python - Tkinter grid() Method
This geometry manager organizes widgets in a table-like structure in the parent widget. widget.grid( grid_options ) Here is the list of possible options − column − The column to put widget in; default 0 (leftmost column). column − The column to put widget in; default 0 (leftmost column). columnspan − How many columns widgetoccupies; default 1. columnspan − How many columns widgetoccupies; default 1. ipadx, ipady − How many pixels to pad widget, horizontally and vertically, inside widget's borders. ipadx, ipady − How many pixels to pad widget, horizontally and vertically, inside widget's borders. padx, pady − How many pixels to pad widget, horizontally and vertically, outside v's borders. padx, pady − How many pixels to pad widget, horizontally and vertically, outside v's borders. row − The row to put widget in; default the first row that is still empty. row − The row to put widget in; default the first row that is still empty. rowspan − How many rowswidget occupies; default 1. rowspan − How many rowswidget occupies; default 1. sticky − What to do if the cell is larger than widget. By default, with sticky='', widget is centered in its cell. sticky may be the string concatenation of zero or more of N, E, S, W, NE, NW, SE, and SW, compass directions indicating the sides and corners of the cell to which widget sticks. sticky − What to do if the cell is larger than widget. By default, with sticky='', widget is centered in its cell. sticky may be the string concatenation of zero or more of N, E, S, W, NE, NW, SE, and SW, compass directions indicating the sides and corners of the cell to which widget sticks. Try the following example by moving cursor on different buttons − import Tkinter root = Tkinter.Tk( ) for r in range(3): for c in range(4): Tkinter.Label(root, text='R%s/C%s'%(r,c), borderwidth=1 ).grid(row=r,column=c) root.mainloop( ) This would produce the following result displaying 12 labels arrayed in a 3 × 4 grid − 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": 2332, "s": 2244, "text": "This geometry manager organizes widgets in a table-like structure in the parent widget." }, { "code": null, "e": 2361, "s": 2332, "text": "widget.grid( grid_options )\n" }, { "code": null, "e": 2400, "s": 2361, "text": "Here is the list of possible options −" }, { "code": null, "e": 2467, "s": 2400, "text": "column − The column to put widget in; default 0 (leftmost column)." }, { "code": null, "e": 2534, "s": 2467, "text": "column − The column to put widget in; default 0 (leftmost column)." }, { "code": null, "e": 2591, "s": 2534, "text": "columnspan − How many columns widgetoccupies; default 1." }, { "code": null, "e": 2648, "s": 2591, "text": "columnspan − How many columns widgetoccupies; default 1." }, { "code": null, "e": 2748, "s": 2648, "text": "ipadx, ipady − How many pixels to pad widget, horizontally and vertically, inside widget's borders." }, { "code": null, "e": 2848, "s": 2748, "text": "ipadx, ipady − How many pixels to pad widget, horizontally and vertically, inside widget's borders." }, { "code": null, "e": 2942, "s": 2848, "text": "padx, pady − How many pixels to pad widget, horizontally and vertically, outside v's borders." }, { "code": null, "e": 3036, "s": 2942, "text": "padx, pady − How many pixels to pad widget, horizontally and vertically, outside v's borders." }, { "code": null, "e": 3111, "s": 3036, "text": "row − The row to put widget in; default the first row that is still empty." }, { "code": null, "e": 3186, "s": 3111, "text": "row − The row to put widget in; default the first row that is still empty." }, { "code": null, "e": 3237, "s": 3186, "text": "rowspan − How many rowswidget occupies; default 1." }, { "code": null, "e": 3288, "s": 3237, "text": "rowspan − How many rowswidget occupies; default 1." }, { "code": null, "e": 3581, "s": 3288, "text": "sticky − What to do if the cell is larger than widget. By default, with sticky='', widget is centered in its cell. sticky may be the string concatenation of zero or more of N, E, S, W, NE, NW, SE, and SW, compass directions indicating the sides and corners of the cell to which widget sticks." }, { "code": null, "e": 3874, "s": 3581, "text": "sticky − What to do if the cell is larger than widget. By default, with sticky='', widget is centered in its cell. sticky may be the string concatenation of zero or more of N, E, S, W, NE, NW, SE, and SW, compass directions indicating the sides and corners of the cell to which widget sticks." }, { "code": null, "e": 3940, "s": 3874, "text": "Try the following example by moving cursor on different buttons −" }, { "code": null, "e": 4130, "s": 3940, "text": "import Tkinter\nroot = Tkinter.Tk( )\nfor r in range(3):\n for c in range(4):\n Tkinter.Label(root, text='R%s/C%s'%(r,c),\n borderwidth=1 ).grid(row=r,column=c)\nroot.mainloop( )" }, { "code": null, "e": 4217, "s": 4130, "text": "This would produce the following result displaying 12 labels arrayed in a 3 × 4 grid −" }, { "code": null, "e": 4254, "s": 4217, "text": "\n 187 Lectures \n 17.5 hours \n" }, { "code": null, "e": 4270, "s": 4254, "text": " Malhar Lathkar" }, { "code": null, "e": 4303, "s": 4270, "text": "\n 55 Lectures \n 8 hours \n" }, { "code": null, "e": 4322, "s": 4303, "text": " Arnab Chakraborty" }, { "code": null, "e": 4357, "s": 4322, "text": "\n 136 Lectures \n 11 hours \n" }, { "code": null, "e": 4379, "s": 4357, "text": " In28Minutes Official" }, { "code": null, "e": 4413, "s": 4379, "text": "\n 75 Lectures \n 13 hours \n" }, { "code": null, "e": 4441, "s": 4413, "text": " Eduonix Learning Solutions" }, { "code": null, "e": 4476, "s": 4441, "text": "\n 70 Lectures \n 8.5 hours \n" }, { "code": null, "e": 4490, "s": 4476, "text": " Lets Kode It" }, { "code": null, "e": 4523, "s": 4490, "text": "\n 63 Lectures \n 6 hours \n" }, { "code": null, "e": 4540, "s": 4523, "text": " Abhilash Nelson" }, { "code": null, "e": 4547, "s": 4540, "text": " Print" }, { "code": null, "e": 4558, "s": 4547, "text": " Add Notes" } ]
The Initializer Block in Java
The Initializer block is used to declare constructors’ common parts. Let us see an example − Live Demo import java.io.*; public class Demo{ { System.out.println("The common constructor has been invoked"); } public Demo(){ System.out.println("The default constructor has been invoked"); } public Demo(int x){ System.out.println("The parametrized constructor has been invoked"); } public static void main(String arr[]){ Demo my_obj_1, my_obj_2; System.out.println("The Demo objects have been created."); my_obj_1 = new Demo(); my_obj_2 = new Demo(89); } } The Demo objects have been created. The common constructor has been invoked The default constructor has been invoked The common constructor has been invoked The parametrized constructor has been invoked A class named Demo contains a constructor without a parameter, a parameterized constructor, and the main function. Inside the main function, an instance of the Demo class is created, one with parameter, and one without parameter.
[ { "code": null, "e": 1155, "s": 1062, "text": "The Initializer block is used to declare constructors’ common parts. Let us see an example −" }, { "code": null, "e": 1166, "s": 1155, "text": " Live Demo" }, { "code": null, "e": 1683, "s": 1166, "text": "import java.io.*;\npublic class Demo{\n {\n System.out.println(\"The common constructor has been invoked\");\n }\n public Demo(){\n System.out.println(\"The default constructor has been invoked\");\n }\n public Demo(int x){\n System.out.println(\"The parametrized constructor has been invoked\");\n }\n public static void main(String arr[]){\n Demo my_obj_1, my_obj_2;\n System.out.println(\"The Demo objects have been created.\");\n my_obj_1 = new Demo();\n my_obj_2 = new Demo(89);\n }\n}" }, { "code": null, "e": 1886, "s": 1683, "text": "The Demo objects have been created.\nThe common constructor has been invoked\nThe default constructor has been invoked\nThe common constructor has been invoked\nThe parametrized constructor has been invoked" }, { "code": null, "e": 2116, "s": 1886, "text": "A class named Demo contains a constructor without a parameter, a parameterized constructor, and\nthe main function. Inside the main function, an instance of the Demo class is created, one with\nparameter, and one without parameter." } ]
Create New Column Based on Other Columns in Pandas | Towards Data Science
As part of data processing or feature engineering, we usually need to create additional columns out of existing ones. In today’s short guide, we will explore how to perform such operations in pandas. Specifically, we will explore how to do so in a few different ways, using apply() method numpy.select() method (for a vectorised approach) loc property First, let’s create an example DataFrame that we’ll reference throughout the article in order to demonstrate a few concepts and showcase how to create new columns based on values from existing ones. import pandas as pddf = pd.DataFrame( [ (1, 'Hello', 158, True, 12.8), (2, 'Hey', 567, False, 74.2), (3, 'Hi', 123, False, 1.1), (4, 'Howdy', 578, True, 45.8), (5, 'Hello', 418, True, 21.1), (6, 'Hi', 98, False, 98.1), ], columns=['colA', 'colB', 'colC', 'colD', 'colE'])print(df) colA colB colC colD colE0 1 Hello 158 True 12.81 2 Hey 567 False 74.22 3 Hi 123 False 1.13 4 Howdy 578 True 45.84 5 Hello 418 True 21.15 6 Hi 98 False 98.1 If you need to apply a method over an existing column in order to compute some values that will eventually be added as a new column in the existing DataFrame, then pandas.DataFrame.apply() method should do the trick. For example, you can define your own method and then pass it to the apply() method. Let’s suppose we want to create a new column called colF that will be created based on the values of the column colC using the categorise() method defined below: def categorise(row): if row['colC'] > 0 and row['colC'] <= 99: return 'A' elif row['colC'] > 100 and row['colC'] <= 199: return 'B' elif row['colC'] > 200 and row['colC'] <= 299: return 'C' return 'D' All you need to do is to pass the above method to apply() as a lambda expression: df['colF'] = df.apply(lambda row: categorise(row), axis=1)print(df) colA colB colC colD colE colF0 1 Hello 158 True 12.8 B1 2 Hey 567 False 74.2 D2 3 Hi 123 False 1.1 B3 4 Howdy 578 True 45.8 D4 5 Hello 418 True 21.1 D5 6 Hi 98 False 98.1 A For more simple operations, you can specify the lambda expressions directly to the apply() method. For instance, let’s suppose we want to create another column called colG that will add together the values of columns colC and colE. The following should do the trick: df['colG'] = df.apply(lambda row: row.colC + row.colE, axis=1)print(df) colA colB colC colD colE colF colG0 1 Hello 158 True 12.8 B 170.81 2 Hey 567 False 74.2 D 641.22 3 Hi 123 False 1.1 B 124.13 4 Howdy 578 True 45.8 D 623.84 5 Hello 418 True 21.1 D 439.15 6 Hi 98 False 98.1 A 196.1 Now a more vectorised approach (and potentially better in terms of performance) is to use NumPy’s select() method as described below. Again, let’s suppose we want to create a new column called colF that will be created based on the values of the column colC. This time, instead of defining a function we will instead create a list containing the desired conditions. import numpy as npconditions = [ np.logical_and(df['colC'].gt(0), np.less_equal(df['colC'], 99)), np.logical_and(df['colC'].gt(100), np.less_equal(df['colC'],199)), np.logical_and(df['colC'].gt(200), np.less_equal(df['colC'],299)),] Then we define an additional list containing the corresponding values that the new column will contain. Note that in the list below we do not include the default value D. outputs = ['A', 'B', 'C'] And finally, we use the select() method to apply the conditions and also specify the default value that will be used whenever none of the specified conditions is met. df['colF'] = pd.Series(np.select(conditions, outputs, 'D'))print(df) colA colB colC colD colE colF0 1 Hello 158 True 12.8 B1 2 Hey 567 False 74.2 D2 3 Hi 123 False 1.1 B3 4 Howdy 578 True 45.8 D4 5 Hello 418 True 21.1 D5 6 Hi 98 False 98.1 A Finally, another option is the loc property that in some occasions might be more efficient compared to apply() method. Note that this approach may also be a little bit more verbose compared to the solutions we discussed previously. df.loc[ np.logical_and(df['colC'].gt(0), np.less_equal(df['colC'], 99)), 'colF'] = 'A'df.loc[ np.logical_and(df['colC'].gt(100), np.less_equal(df['colC'], 199)),'colF'] = 'B'df.loc[ np.logical_and(df['colC'].gt(200), np.less_equal(df['colC'], 299)),'colF'] = 'C'df['colF'].fillna('D', inplace=True)print(df) colA colB colC colD colE colF0 1 Hello 158 True 12.8 B1 2 Hey 567 False 74.2 D2 3 Hi 123 False 1.1 B3 4 Howdy 578 True 45.8 D4 5 Hello 418 True 21.1 D5 6 Hi 98 False 98.1 A In today’s short guide we discussed to add new columns in pandas DataFrames based on the values of existing columns. Specifically, we showcased how to do so using apply() method and loc[] property in pandas, as well as using NumPy’s select() method in case you are interested into a more vectorised approach. Become a member and read every story on Medium. Your membership fee directly supports me and other writers you read. You’ll also get full access to every story on Medium. You may also like
[ { "code": null, "e": 372, "s": 172, "text": "As part of data processing or feature engineering, we usually need to create additional columns out of existing ones. In today’s short guide, we will explore how to perform such operations in pandas." }, { "code": null, "e": 446, "s": 372, "text": "Specifically, we will explore how to do so in a few different ways, using" }, { "code": null, "e": 461, "s": 446, "text": "apply() method" }, { "code": null, "e": 511, "s": 461, "text": "numpy.select() method (for a vectorised approach)" }, { "code": null, "e": 524, "s": 511, "text": "loc property" }, { "code": null, "e": 723, "s": 524, "text": "First, let’s create an example DataFrame that we’ll reference throughout the article in order to demonstrate a few concepts and showcase how to create new columns based on values from existing ones." }, { "code": null, "e": 1286, "s": 723, "text": "import pandas as pddf = pd.DataFrame( [ (1, 'Hello', 158, True, 12.8), (2, 'Hey', 567, False, 74.2), (3, 'Hi', 123, False, 1.1), (4, 'Howdy', 578, True, 45.8), (5, 'Hello', 418, True, 21.1), (6, 'Hi', 98, False, 98.1), ], columns=['colA', 'colB', 'colC', 'colD', 'colE'])print(df) colA colB colC colD colE0 1 Hello 158 True 12.81 2 Hey 567 False 74.22 3 Hi 123 False 1.13 4 Howdy 578 True 45.84 5 Hello 418 True 21.15 6 Hi 98 False 98.1" }, { "code": null, "e": 1503, "s": 1286, "text": "If you need to apply a method over an existing column in order to compute some values that will eventually be added as a new column in the existing DataFrame, then pandas.DataFrame.apply() method should do the trick." }, { "code": null, "e": 1749, "s": 1503, "text": "For example, you can define your own method and then pass it to the apply() method. Let’s suppose we want to create a new column called colF that will be created based on the values of the column colC using the categorise() method defined below:" }, { "code": null, "e": 1986, "s": 1749, "text": "def categorise(row): if row['colC'] > 0 and row['colC'] <= 99: return 'A' elif row['colC'] > 100 and row['colC'] <= 199: return 'B' elif row['colC'] > 200 and row['colC'] <= 299: return 'C' return 'D'" }, { "code": null, "e": 2068, "s": 1986, "text": "All you need to do is to pass the above method to apply() as a lambda expression:" }, { "code": null, "e": 2402, "s": 2068, "text": "df['colF'] = df.apply(lambda row: categorise(row), axis=1)print(df) colA colB colC colD colE colF0 1 Hello 158 True 12.8 B1 2 Hey 567 False 74.2 D2 3 Hi 123 False 1.1 B3 4 Howdy 578 True 45.8 D4 5 Hello 418 True 21.1 D5 6 Hi 98 False 98.1 A" }, { "code": null, "e": 2669, "s": 2402, "text": "For more simple operations, you can specify the lambda expressions directly to the apply() method. For instance, let’s suppose we want to create another column called colG that will add together the values of columns colC and colE. The following should do the trick:" }, { "code": null, "e": 3056, "s": 2669, "text": "df['colG'] = df.apply(lambda row: row.colC + row.colE, axis=1)print(df) colA colB colC colD colE colF colG0 1 Hello 158 True 12.8 B 170.81 2 Hey 567 False 74.2 D 641.22 3 Hi 123 False 1.1 B 124.13 4 Howdy 578 True 45.8 D 623.84 5 Hello 418 True 21.1 D 439.15 6 Hi 98 False 98.1 A 196.1" }, { "code": null, "e": 3190, "s": 3056, "text": "Now a more vectorised approach (and potentially better in terms of performance) is to use NumPy’s select() method as described below." }, { "code": null, "e": 3422, "s": 3190, "text": "Again, let’s suppose we want to create a new column called colF that will be created based on the values of the column colC. This time, instead of defining a function we will instead create a list containing the desired conditions." }, { "code": null, "e": 3658, "s": 3422, "text": "import numpy as npconditions = [ np.logical_and(df['colC'].gt(0), np.less_equal(df['colC'], 99)), np.logical_and(df['colC'].gt(100), np.less_equal(df['colC'],199)), np.logical_and(df['colC'].gt(200), np.less_equal(df['colC'],299)),]" }, { "code": null, "e": 3829, "s": 3658, "text": "Then we define an additional list containing the corresponding values that the new column will contain. Note that in the list below we do not include the default value D." }, { "code": null, "e": 3855, "s": 3829, "text": "outputs = ['A', 'B', 'C']" }, { "code": null, "e": 4022, "s": 3855, "text": "And finally, we use the select() method to apply the conditions and also specify the default value that will be used whenever none of the specified conditions is met." }, { "code": null, "e": 4358, "s": 4022, "text": "df['colF'] = pd.Series(np.select(conditions, outputs, 'D'))print(df) colA colB colC colD colE colF0 1 Hello 158 True 12.8 B1 2 Hey 567 False 74.2 D2 3 Hi 123 False 1.1 B3 4 Howdy 578 True 45.8 D4 5 Hello 418 True 21.1 D5 6 Hi 98 False 98.1 A" }, { "code": null, "e": 4590, "s": 4358, "text": "Finally, another option is the loc property that in some occasions might be more efficient compared to apply() method. Note that this approach may also be a little bit more verbose compared to the solutions we discussed previously." }, { "code": null, "e": 5165, "s": 4590, "text": "df.loc[ np.logical_and(df['colC'].gt(0), np.less_equal(df['colC'], 99)), 'colF'] = 'A'df.loc[ np.logical_and(df['colC'].gt(100), np.less_equal(df['colC'], 199)),'colF'] = 'B'df.loc[ np.logical_and(df['colC'].gt(200), np.less_equal(df['colC'], 299)),'colF'] = 'C'df['colF'].fillna('D', inplace=True)print(df) colA colB colC colD colE colF0 1 Hello 158 True 12.8 B1 2 Hey 567 False 74.2 D2 3 Hi 123 False 1.1 B3 4 Howdy 578 True 45.8 D4 5 Hello 418 True 21.1 D5 6 Hi 98 False 98.1 A" }, { "code": null, "e": 5474, "s": 5165, "text": "In today’s short guide we discussed to add new columns in pandas DataFrames based on the values of existing columns. Specifically, we showcased how to do so using apply() method and loc[] property in pandas, as well as using NumPy’s select() method in case you are interested into a more vectorised approach." }, { "code": null, "e": 5645, "s": 5474, "text": "Become a member and read every story on Medium. Your membership fee directly supports me and other writers you read. You’ll also get full access to every story on Medium." } ]
HTML | <div> align Attribute - GeeksforGeeks
22 Feb, 2022 The HTML div align Attribute is used to specify the alignment of the <div> element or the content present inside the div Element. Note : This attribute is not supported by HTML5. Syntax: <div align="left | right | center | justify";> Attribute Values: left: It sets the content to the left-align. right: It sets the content to the right-align. center: I sets the div element to the center. By default, it is set to center. justify: It sets the content to the justify position. Example: <!DOCTYPE html><html> <head> <title>gfg</title> <style type=text/css> p { background-color: gray; margin: 10px; } div { color: white; background-color: 009900; margin: 2px; font-size: 25px; } body { text-align: center; } </style> </head> <body> <h1>GeeksForGeeks</h1> <h2><div>align Attribute</h2> <div align="center"> div align="center" </div> <div align="left"> div align="left" </div> <div align="right"> div align="right" </div> <div align="justify"> div align="justify" </div> </body> </html> Output : Supported Browsers: The browsers supported by HTML div align Attribute are listed below: Google Chrome Internet Explorer Firefox Apple Safari Opera HTML is the foundation of webpages, is used for webpage development by structuring websites and web apps.You can learn HTML from the ground up by following this HTML Tutorial and HTML Examples. Attention reader! Don’t stop learning now. Get hold of all the important HTML concepts with the Web Design for Beginners | HTML course. chhabradhanvi hritikbhatnagar2182 HTML-Attributes HTML Web Technologies HTML Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. REST API (Introduction) How to Insert Form Data into Database using PHP ? HTML Cheat Sheet - A Basic Guide to HTML Form validation using HTML and JavaScript Design a web page using HTML and CSS Remove elements from a JavaScript Array Installation of Node.js on Linux Convert a string to an integer in JavaScript How to fetch data from an API in ReactJS ? Difference between var, let and const keywords in JavaScript
[ { "code": null, "e": 26565, "s": 26537, "text": "\n22 Feb, 2022" }, { "code": null, "e": 26695, "s": 26565, "text": "The HTML div align Attribute is used to specify the alignment of the <div> element or the content present inside the div Element." }, { "code": null, "e": 26744, "s": 26695, "text": "Note : This attribute is not supported by HTML5." }, { "code": null, "e": 26752, "s": 26744, "text": "Syntax:" }, { "code": null, "e": 26799, "s": 26752, "text": "<div align=\"left | right | center | justify\";>" }, { "code": null, "e": 26817, "s": 26799, "text": "Attribute Values:" }, { "code": null, "e": 26862, "s": 26817, "text": "left: It sets the content to the left-align." }, { "code": null, "e": 26909, "s": 26862, "text": "right: It sets the content to the right-align." }, { "code": null, "e": 26988, "s": 26909, "text": "center: I sets the div element to the center. By default, it is set to center." }, { "code": null, "e": 27042, "s": 26988, "text": "justify: It sets the content to the justify position." }, { "code": null, "e": 27051, "s": 27042, "text": "Example:" }, { "code": "<!DOCTYPE html><html> <head> <title>gfg</title> <style type=text/css> p { background-color: gray; margin: 10px; } div { color: white; background-color: 009900; margin: 2px; font-size: 25px; } body { text-align: center; } </style> </head> <body> <h1>GeeksForGeeks</h1> <h2><div>align Attribute</h2> <div align=\"center\"> div align=\"center\" </div> <div align=\"left\"> div align=\"left\" </div> <div align=\"right\"> div align=\"right\" </div> <div align=\"justify\"> div align=\"justify\" </div> </body> </html>", "e": 27748, "s": 27051, "text": null }, { "code": null, "e": 27757, "s": 27748, "text": "Output :" }, { "code": null, "e": 27846, "s": 27757, "text": "Supported Browsers: The browsers supported by HTML div align Attribute are listed below:" }, { "code": null, "e": 27860, "s": 27846, "text": "Google Chrome" }, { "code": null, "e": 27878, "s": 27860, "text": "Internet Explorer" }, { "code": null, "e": 27886, "s": 27878, "text": "Firefox" }, { "code": null, "e": 27899, "s": 27886, "text": "Apple Safari" }, { "code": null, "e": 27905, "s": 27899, "text": "Opera" }, { "code": null, "e": 28099, "s": 27905, "text": "HTML is the foundation of webpages, is used for webpage development by structuring websites and web apps.You can learn HTML from the ground up by following this HTML Tutorial and HTML Examples." }, { "code": null, "e": 28236, "s": 28099, "text": "Attention reader! Don’t stop learning now. Get hold of all the important HTML concepts with the Web Design for Beginners | HTML course." }, { "code": null, "e": 28250, "s": 28236, "text": "chhabradhanvi" }, { "code": null, "e": 28270, "s": 28250, "text": "hritikbhatnagar2182" }, { "code": null, "e": 28286, "s": 28270, "text": "HTML-Attributes" }, { "code": null, "e": 28291, "s": 28286, "text": "HTML" }, { "code": null, "e": 28308, "s": 28291, "text": "Web Technologies" }, { "code": null, "e": 28313, "s": 28308, "text": "HTML" }, { "code": null, "e": 28411, "s": 28313, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 28435, "s": 28411, "text": "REST API (Introduction)" }, { "code": null, "e": 28485, "s": 28435, "text": "How to Insert Form Data into Database using PHP ?" }, { "code": null, "e": 28526, "s": 28485, "text": "HTML Cheat Sheet - A Basic Guide to HTML" }, { "code": null, "e": 28568, "s": 28526, "text": "Form validation using HTML and JavaScript" }, { "code": null, "e": 28605, "s": 28568, "text": "Design a web page using HTML and CSS" }, { "code": null, "e": 28645, "s": 28605, "text": "Remove elements from a JavaScript Array" }, { "code": null, "e": 28678, "s": 28645, "text": "Installation of Node.js on Linux" }, { "code": null, "e": 28723, "s": 28678, "text": "Convert a string to an integer in JavaScript" }, { "code": null, "e": 28766, "s": 28723, "text": "How to fetch data from an API in ReactJS ?" } ]
Calibration Curves - GeeksforGeeks
14 Sep, 2021 Generally, for any classification problem, we predict the class value that has the highest probability of being the true class label. However, sometimes, we want to predict the probabilities of a data instance belonging to each class label. For example, say we are building a model to classify fruits and we have three class labels: apples, oranges, and bananas (each fruit is one of these). For any fruit, we want the probabilities of the fruit being an apple, an orange, or a banana. This is very useful for the evaluation of a classification model. It can help us understand how ‘sure’ a model is while predicting a class label and may help us interpret how decisive a classification model is. Generally, classifiers that have a linear probability of predicting each class’s labels are called calibrated. The problem is, not all classification models are calibrated. Some models can give poor estimates of class probabilities and some do not even support probability prediction. Calibration Curves: Calibration curves are used to evaluate how calibrated a classifier is i.e., how the probabilities of predicting each class label differ. The x-axis represents the average predicted probability in each bin. The y-axis is the ratio of positives (the proportion of positive predictions). The curve of the ideal calibrated model is a linear straight line from (0, 0) moving linearly. Plotting Calibration Curves in Python3: For this example, we will use a binary dataset. We will use the popular diabetes dataset. You can learn more about this dataset here. Code: Implementing a Support Vector Machine’s calibration curve and compare it with a perfectly calibrated model’s curve. Python3 # Importing required modules from sklearn.datasets import load_breast_cancerfrom sklearn.svm import SVCfrom sklearn.model_selection import train_test_splitfrom sklearn.calibration import calibration_curveimport matplotlib.pyplot as plt # Loading datasetdataset = load_breast_cancer()X = dataset.datay = dataset.target # Splitting dataset into training and testing setsX_train, X_test, y_train, y_test = train_test_split(X, y, test_size = 0.1, random_state = 13) # Creating and fitting modelmodel = SVC()model.fit(X_train, y_train) # Predict Probabilitiesprob = model.decision_function(X_test) # Creating Calibration Curvex, y = calibration_curve(y_test, prob, n_bins = 10, normalize = True) # Plot calibration curve # Plot perfectly calibratedplt.plot([0, 1], [0, 1], linestyle = '--', label = 'Ideally Calibrated') # Plot model's calibration curveplt.plot(y, x, marker = '.', label = 'Support Vector Classifier') leg = plt.legend(loc = 'upper left')plt.xlabel('Average Predicted Probability in each bin')plt.ylabel('Ratio of positives')plt.show() Output: From the graph, we can clearly see that the Support Vector classifier is nor very well calibrated. The closes a model’s curve is to the perfect calibrated model’s curve (dotted curve), the better calibrated it is. Conclusion: Now that you know what calibration is in terms of Machine Learning and how to plot a calibration curve, next time you classifier gives unpredictable results and you can’t find the cause, try plotting the calibration curve and check if the model is well-calibrated. anikakapoor Machine Learning Python Machine Learning Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Introduction to Recurrent Neural Network Support Vector Machine Algorithm Intuition of Adam Optimizer CNN | Introduction to Pooling Layer Convolutional Neural Network (CNN) in Machine Learning Read JSON file using Python Adding new column to existing DataFrame in Pandas Python map() function How to get column names in Pandas dataframe
[ { "code": null, "e": 25589, "s": 25561, "text": "\n14 Sep, 2021" }, { "code": null, "e": 26572, "s": 25589, "text": "Generally, for any classification problem, we predict the class value that has the highest probability of being the true class label. However, sometimes, we want to predict the probabilities of a data instance belonging to each class label. For example, say we are building a model to classify fruits and we have three class labels: apples, oranges, and bananas (each fruit is one of these). For any fruit, we want the probabilities of the fruit being an apple, an orange, or a banana. This is very useful for the evaluation of a classification model. It can help us understand how ‘sure’ a model is while predicting a class label and may help us interpret how decisive a classification model is. Generally, classifiers that have a linear probability of predicting each class’s labels are called calibrated. The problem is, not all classification models are calibrated. Some models can give poor estimates of class probabilities and some do not even support probability prediction. " }, { "code": null, "e": 26974, "s": 26572, "text": "Calibration Curves: Calibration curves are used to evaluate how calibrated a classifier is i.e., how the probabilities of predicting each class label differ. The x-axis represents the average predicted probability in each bin. The y-axis is the ratio of positives (the proportion of positive predictions). The curve of the ideal calibrated model is a linear straight line from (0, 0) moving linearly. " }, { "code": null, "e": 27149, "s": 26974, "text": "Plotting Calibration Curves in Python3: For this example, we will use a binary dataset. We will use the popular diabetes dataset. You can learn more about this dataset here. " }, { "code": null, "e": 27273, "s": 27149, "text": "Code: Implementing a Support Vector Machine’s calibration curve and compare it with a perfectly calibrated model’s curve. " }, { "code": null, "e": 27281, "s": 27273, "text": "Python3" }, { "code": "# Importing required modules from sklearn.datasets import load_breast_cancerfrom sklearn.svm import SVCfrom sklearn.model_selection import train_test_splitfrom sklearn.calibration import calibration_curveimport matplotlib.pyplot as plt # Loading datasetdataset = load_breast_cancer()X = dataset.datay = dataset.target # Splitting dataset into training and testing setsX_train, X_test, y_train, y_test = train_test_split(X, y, test_size = 0.1, random_state = 13) # Creating and fitting modelmodel = SVC()model.fit(X_train, y_train) # Predict Probabilitiesprob = model.decision_function(X_test) # Creating Calibration Curvex, y = calibration_curve(y_test, prob, n_bins = 10, normalize = True) # Plot calibration curve # Plot perfectly calibratedplt.plot([0, 1], [0, 1], linestyle = '--', label = 'Ideally Calibrated') # Plot model's calibration curveplt.plot(y, x, marker = '.', label = 'Support Vector Classifier') leg = plt.legend(loc = 'upper left')plt.xlabel('Average Predicted Probability in each bin')plt.ylabel('Ratio of positives')plt.show()", "e": 28349, "s": 27281, "text": null }, { "code": null, "e": 28358, "s": 28349, "text": "Output: " }, { "code": null, "e": 28573, "s": 28358, "text": "From the graph, we can clearly see that the Support Vector classifier is nor very well calibrated. The closes a model’s curve is to the perfect calibrated model’s curve (dotted curve), the better calibrated it is. " }, { "code": null, "e": 28852, "s": 28573, "text": "Conclusion: Now that you know what calibration is in terms of Machine Learning and how to plot a calibration curve, next time you classifier gives unpredictable results and you can’t find the cause, try plotting the calibration curve and check if the model is well-calibrated. " }, { "code": null, "e": 28864, "s": 28852, "text": "anikakapoor" }, { "code": null, "e": 28881, "s": 28864, "text": "Machine Learning" }, { "code": null, "e": 28888, "s": 28881, "text": "Python" }, { "code": null, "e": 28905, "s": 28888, "text": "Machine Learning" }, { "code": null, "e": 29003, "s": 28905, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 29044, "s": 29003, "text": "Introduction to Recurrent Neural Network" }, { "code": null, "e": 29077, "s": 29044, "text": "Support Vector Machine Algorithm" }, { "code": null, "e": 29105, "s": 29077, "text": "Intuition of Adam Optimizer" }, { "code": null, "e": 29141, "s": 29105, "text": "CNN | Introduction to Pooling Layer" }, { "code": null, "e": 29196, "s": 29141, "text": "Convolutional Neural Network (CNN) in Machine Learning" }, { "code": null, "e": 29224, "s": 29196, "text": "Read JSON file using Python" }, { "code": null, "e": 29274, "s": 29224, "text": "Adding new column to existing DataFrame in Pandas" }, { "code": null, "e": 29296, "s": 29274, "text": "Python map() function" } ]
Array getDouble() Method in Java - GeeksforGeeks
30 Nov, 2018 The java.lang.reflect.Array.getDouble() is an inbuilt method of Array class in Java and is used to return the element present at the given index from the specified Array as Double. Syntax: Array.getDouble(Object []array, int index) Parameters: This method accepts two mandatory parameters: array: The object array whose index is to be returned. index: The particular index of the given array. The element at ‘index’ in the given array is returned. Return Value: This method returns the element of the array as byte. Exceptions: This method throws following exceptions: NullPointerException – when the array is null. IllegalArgumentException – when the given object array is not an Array. ArrayIndexOutOfBoundsException – if the given index is not in the range of the size of the array. Note: Typecast isn’t necessary as the return type is double. Below programs illustrate the getDouble() method of Array class. Program 1: // Java code to demonstrate getDouble() method of Array classimport java.lang.reflect.Array;public class GfG { // main method public static void main(String[] args) { // Declaring and defining a double array double a[] = { 1.0, 2.0, 3.0 }; // Traversing the array for (int i = 0; i < 3; i++) { // Array.getDouble() method double x = Array.getDouble(a, i); // Printing the values System.out.print(x + " "); } }} 1.0 2.0 3.0 Program 2: // Java code to demonstrate getDouble() method of Array classimport java.lang.reflect.Array;public class GfG { // main method public static void main(String[] args) { // Declaring and defining a double array double a[] = { 1.0, 2.0, 3.0 }; try { double x = Array.getDouble(a, 4); } catch (Exception e) { System.out.println("Exception : " + e); } }} Exception : java.lang.ArrayIndexOutOfBoundsException Program 3: // Java code to demonstrate getDouble() method of Array classimport java.lang.reflect.Array;public class GfG { // main method public static void main(String[] args) { // Declaring and defining a double array as null double a[] = null; try { double x = Array.getDouble(a, 4); } catch (Exception e) { System.out.println("Exception : " + e); } }} Exception : java.lang.NullPointerException Program 4: // Java code to demonstrate getDouble() method of Array classimport java.lang.reflect.Array;public class GfG { // main method public static void main(String[] args) { // Declaring and defining a double variable double a = 1.0f; try { double x = Array.getDouble(a, 4); } catch (Exception e) { System.out.println("Exception : " + e); } }} Exception : java.lang.IllegalArgumentException: Argument is not an array Program 5: // Java code to demonstrate getDouble() method of Array classimport java.lang.reflect.Array;public class GfG { // main method public static void main(String[] args) { // Declaring and defining a String array String s[] = { "Geeks", "for", "Geeks" }; try { double x = Array.getDouble(s, 4); } catch (Exception e) { System.out.println("Exception : " + e); } }} Exception : java.lang.IllegalArgumentException: Argument is not an array Java - util package Java-Arrays Java-Collections Java-Functions java-lang-reflect-package java-reflection-array Java Java Java-Collections Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Object Oriented Programming (OOPs) Concept in Java HashMap in Java with Examples Interfaces in Java Stream In Java How to iterate any Map in Java ArrayList in Java Initialize an ArrayList in Java Stack Class in Java Multidimensional Arrays in Java Singleton Class in Java
[ { "code": null, "e": 25711, "s": 25683, "text": "\n30 Nov, 2018" }, { "code": null, "e": 25892, "s": 25711, "text": "The java.lang.reflect.Array.getDouble() is an inbuilt method of Array class in Java and is used to return the element present at the given index from the specified Array as Double." }, { "code": null, "e": 25900, "s": 25892, "text": "Syntax:" }, { "code": null, "e": 25944, "s": 25900, "text": "Array.getDouble(Object []array, int index)\n" }, { "code": null, "e": 26002, "s": 25944, "text": "Parameters: This method accepts two mandatory parameters:" }, { "code": null, "e": 26057, "s": 26002, "text": "array: The object array whose index is to be returned." }, { "code": null, "e": 26160, "s": 26057, "text": "index: The particular index of the given array. The element at ‘index’ in the given array is returned." }, { "code": null, "e": 26228, "s": 26160, "text": "Return Value: This method returns the element of the array as byte." }, { "code": null, "e": 26281, "s": 26228, "text": "Exceptions: This method throws following exceptions:" }, { "code": null, "e": 26328, "s": 26281, "text": "NullPointerException – when the array is null." }, { "code": null, "e": 26400, "s": 26328, "text": "IllegalArgumentException – when the given object array is not an Array." }, { "code": null, "e": 26498, "s": 26400, "text": "ArrayIndexOutOfBoundsException – if the given index is not in the range of the size of the array." }, { "code": null, "e": 26559, "s": 26498, "text": "Note: Typecast isn’t necessary as the return type is double." }, { "code": null, "e": 26624, "s": 26559, "text": "Below programs illustrate the getDouble() method of Array class." }, { "code": null, "e": 26635, "s": 26624, "text": "Program 1:" }, { "code": "// Java code to demonstrate getDouble() method of Array classimport java.lang.reflect.Array;public class GfG { // main method public static void main(String[] args) { // Declaring and defining a double array double a[] = { 1.0, 2.0, 3.0 }; // Traversing the array for (int i = 0; i < 3; i++) { // Array.getDouble() method double x = Array.getDouble(a, i); // Printing the values System.out.print(x + \" \"); } }}", "e": 27145, "s": 26635, "text": null }, { "code": null, "e": 27158, "s": 27145, "text": "1.0 2.0 3.0\n" }, { "code": null, "e": 27169, "s": 27158, "text": "Program 2:" }, { "code": "// Java code to demonstrate getDouble() method of Array classimport java.lang.reflect.Array;public class GfG { // main method public static void main(String[] args) { // Declaring and defining a double array double a[] = { 1.0, 2.0, 3.0 }; try { double x = Array.getDouble(a, 4); } catch (Exception e) { System.out.println(\"Exception : \" + e); } }}", "e": 27598, "s": 27169, "text": null }, { "code": null, "e": 27652, "s": 27598, "text": "Exception : java.lang.ArrayIndexOutOfBoundsException\n" }, { "code": null, "e": 27663, "s": 27652, "text": "Program 3:" }, { "code": "// Java code to demonstrate getDouble() method of Array classimport java.lang.reflect.Array;public class GfG { // main method public static void main(String[] args) { // Declaring and defining a double array as null double a[] = null; try { double x = Array.getDouble(a, 4); } catch (Exception e) { System.out.println(\"Exception : \" + e); } }}", "e": 28087, "s": 27663, "text": null }, { "code": null, "e": 28131, "s": 28087, "text": "Exception : java.lang.NullPointerException\n" }, { "code": null, "e": 28142, "s": 28131, "text": "Program 4:" }, { "code": "// Java code to demonstrate getDouble() method of Array classimport java.lang.reflect.Array;public class GfG { // main method public static void main(String[] args) { // Declaring and defining a double variable double a = 1.0f; try { double x = Array.getDouble(a, 4); } catch (Exception e) { System.out.println(\"Exception : \" + e); } }}", "e": 28559, "s": 28142, "text": null }, { "code": null, "e": 28633, "s": 28559, "text": "Exception : java.lang.IllegalArgumentException: Argument is not an array\n" }, { "code": null, "e": 28644, "s": 28633, "text": "Program 5:" }, { "code": "// Java code to demonstrate getDouble() method of Array classimport java.lang.reflect.Array;public class GfG { // main method public static void main(String[] args) { // Declaring and defining a String array String s[] = { \"Geeks\", \"for\", \"Geeks\" }; try { double x = Array.getDouble(s, 4); } catch (Exception e) { System.out.println(\"Exception : \" + e); } }}", "e": 29083, "s": 28644, "text": null }, { "code": null, "e": 29157, "s": 29083, "text": "Exception : java.lang.IllegalArgumentException: Argument is not an array\n" }, { "code": null, "e": 29177, "s": 29157, "text": "Java - util package" }, { "code": null, "e": 29189, "s": 29177, "text": "Java-Arrays" }, { "code": null, "e": 29206, "s": 29189, "text": "Java-Collections" }, { "code": null, "e": 29221, "s": 29206, "text": "Java-Functions" }, { "code": null, "e": 29247, "s": 29221, "text": "java-lang-reflect-package" }, { "code": null, "e": 29269, "s": 29247, "text": "java-reflection-array" }, { "code": null, "e": 29274, "s": 29269, "text": "Java" }, { "code": null, "e": 29279, "s": 29274, "text": "Java" }, { "code": null, "e": 29296, "s": 29279, "text": "Java-Collections" }, { "code": null, "e": 29394, "s": 29296, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 29445, "s": 29394, "text": "Object Oriented Programming (OOPs) Concept in Java" }, { "code": null, "e": 29475, "s": 29445, "text": "HashMap in Java with Examples" }, { "code": null, "e": 29494, "s": 29475, "text": "Interfaces in Java" }, { "code": null, "e": 29509, "s": 29494, "text": "Stream In Java" }, { "code": null, "e": 29540, "s": 29509, "text": "How to iterate any Map in Java" }, { "code": null, "e": 29558, "s": 29540, "text": "ArrayList in Java" }, { "code": null, "e": 29590, "s": 29558, "text": "Initialize an ArrayList in Java" }, { "code": null, "e": 29610, "s": 29590, "text": "Stack Class in Java" }, { "code": null, "e": 29642, "s": 29610, "text": "Multidimensional Arrays in Java" } ]
OFFSET Function in Excel With Examples - GeeksforGeeks
27 May, 2021 Excel contains many useful formulas and functions that make it more and more useful and at the same time user-friendly. Such a function is the OFFSET() function. In many cases, this function is also used inside another function. This function basically returns a reference of a single cell or a range of cells depending on the input. With the help of this function, we can traverse from one cell to another cell. Moreover, the user can specify the number of rows and columns to be returned. This function is a volatile function that also works according to its name. It returns a reference of the desired element(s) that is(are) ‘offset’ of some distance from the given starting point. This can be used within some functions to make tasks easier. Syntax: OFFSET(reference, rows, cols, [height], [width]) -->Here the [height] and [width] are optional. This function takes a valid reference, rows, and columns(To know how much distance the function will traverse), and height and width(that describes the height and width of output reference) as its arguments and returns the desired reference of the cell or the range of cells. These arguments are discussed below elaborately. Arguments: reference (Required): This is the reference of the starting point or the base of the OFFSET() function and this reference must be provided by the user. The reference must be valid i.e. a reference of a single cell or a reference to a range of adjacent cells. rows (Required): This argument contains the number of rows(up or down) that are used by the OFFSET() function to traverse up or down. Again this argument must be provided by the user. This value may be negative or positive. A negative value denotes that the function has to traverse upwards and a positive value denotes traversing downwards. cols (Required): This argument contains the number of columns provided by the user. With the help of this argument OFFSET(), function traverse left or right of the starting point. This value may also be negative or positive. A negative value means traversing to the left and a positive value means traversing to the right. [height] (Optional): This is the height of the reference to be returned by the OFFSET() function. Basically, this value denotes the number of rows of the returned reference. This value must be a positive number. But this is an optional argument. If this argument is omitted, OFFSET() returns a reference of the same height as the ‘reference’(starting point). [width] (Optional): This is the width of the reference to be returned by the OFFSET() function. Basically, this value denotes the number of columns of the returned reference. This value must also be a positive number. But again this is an optional argument. If this argument is omitted, OFFSET() returns a reference of the same width as the ‘reference’(starting point). Note: The number of rows and columns must not exceed the height and width of the worksheet. Return Value: This function naturally returns a reference to a range of cells(sometimes a single cell depending on the input arguments) of a certain height and width either same as the ‘reference’ argument or as the user has provided. Example: An Excel sheet has been taken as an example and the OFFSET function has been used in several formats. OFFSET function has been applied to the above table. OFFSET function traverses 2 rows down and 2 columns left, and returns the reference of cell A6. Output: Picked Excel Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to Use Solver in Excel? How to Find the Last Used Row and Column in Excel VBA? How to Get Length of Array in Excel VBA? Using CHOOSE Function along with VLOOKUP in Excel Macros in Excel Introduction to Excel Spreadsheet How to Extract the Last Word From a Cell in Excel? How to Show Percentages in Stacked Column Chart in Excel? How to Remove Duplicates From Array Using VBA in Excel? How to Sum Values Based on Criteria in Another Column in Excel?
[ { "code": null, "e": 26289, "s": 26261, "text": "\n27 May, 2021" }, { "code": null, "e": 26780, "s": 26289, "text": "Excel contains many useful formulas and functions that make it more and more useful and at the same time user-friendly. Such a function is the OFFSET() function. In many cases, this function is also used inside another function. This function basically returns a reference of a single cell or a range of cells depending on the input. With the help of this function, we can traverse from one cell to another cell. Moreover, the user can specify the number of rows and columns to be returned." }, { "code": null, "e": 27037, "s": 26780, "text": "This function is a volatile function that also works according to its name. It returns a reference of the desired element(s) that is(are) ‘offset’ of some distance from the given starting point. This can be used within some functions to make tasks easier. " }, { "code": null, "e": 27045, "s": 27037, "text": "Syntax:" }, { "code": null, "e": 27142, "s": 27045, "text": "OFFSET(reference, rows, cols, [height], [width])\n\n-->Here the [height] and [width] are optional." }, { "code": null, "e": 27467, "s": 27142, "text": "This function takes a valid reference, rows, and columns(To know how much distance the function will traverse), and height and width(that describes the height and width of output reference) as its arguments and returns the desired reference of the cell or the range of cells. These arguments are discussed below elaborately." }, { "code": null, "e": 27478, "s": 27467, "text": "Arguments:" }, { "code": null, "e": 27737, "s": 27478, "text": "reference (Required): This is the reference of the starting point or the base of the OFFSET() function and this reference must be provided by the user. The reference must be valid i.e. a reference of a single cell or a reference to a range of adjacent cells." }, { "code": null, "e": 28079, "s": 27737, "text": "rows (Required): This argument contains the number of rows(up or down) that are used by the OFFSET() function to traverse up or down. Again this argument must be provided by the user. This value may be negative or positive. A negative value denotes that the function has to traverse upwards and a positive value denotes traversing downwards." }, { "code": null, "e": 28402, "s": 28079, "text": "cols (Required): This argument contains the number of columns provided by the user. With the help of this argument OFFSET(), function traverse left or right of the starting point. This value may also be negative or positive. A negative value means traversing to the left and a positive value means traversing to the right." }, { "code": null, "e": 28761, "s": 28402, "text": "[height] (Optional): This is the height of the reference to be returned by the OFFSET() function. Basically, this value denotes the number of rows of the returned reference. This value must be a positive number. But this is an optional argument. If this argument is omitted, OFFSET() returns a reference of the same height as the ‘reference’(starting point)." }, { "code": null, "e": 29131, "s": 28761, "text": "[width] (Optional): This is the width of the reference to be returned by the OFFSET() function. Basically, this value denotes the number of columns of the returned reference. This value must also be a positive number. But again this is an optional argument. If this argument is omitted, OFFSET() returns a reference of the same width as the ‘reference’(starting point)." }, { "code": null, "e": 29223, "s": 29131, "text": "Note: The number of rows and columns must not exceed the height and width of the worksheet." }, { "code": null, "e": 29459, "s": 29223, "text": "Return Value: This function naturally returns a reference to a range of cells(sometimes a single cell depending on the input arguments) of a certain height and width either same as the ‘reference’ argument or as the user has provided. " }, { "code": null, "e": 29468, "s": 29459, "text": "Example:" }, { "code": null, "e": 29570, "s": 29468, "text": "An Excel sheet has been taken as an example and the OFFSET function has been used in several formats." }, { "code": null, "e": 29623, "s": 29570, "text": "OFFSET function has been applied to the above table." }, { "code": null, "e": 29682, "s": 29623, "text": "OFFSET function traverses 2 rows down and 2 columns left, " }, { "code": null, "e": 29720, "s": 29682, "text": "and returns the reference of cell A6." }, { "code": null, "e": 29728, "s": 29720, "text": "Output:" }, { "code": null, "e": 29735, "s": 29728, "text": "Picked" }, { "code": null, "e": 29741, "s": 29735, "text": "Excel" }, { "code": null, "e": 29839, "s": 29741, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 29867, "s": 29839, "text": "How to Use Solver in Excel?" }, { "code": null, "e": 29922, "s": 29867, "text": "How to Find the Last Used Row and Column in Excel VBA?" }, { "code": null, "e": 29963, "s": 29922, "text": "How to Get Length of Array in Excel VBA?" }, { "code": null, "e": 30013, "s": 29963, "text": "Using CHOOSE Function along with VLOOKUP in Excel" }, { "code": null, "e": 30029, "s": 30013, "text": "Macros in Excel" }, { "code": null, "e": 30063, "s": 30029, "text": "Introduction to Excel Spreadsheet" }, { "code": null, "e": 30114, "s": 30063, "text": "How to Extract the Last Word From a Cell in Excel?" }, { "code": null, "e": 30172, "s": 30114, "text": "How to Show Percentages in Stacked Column Chart in Excel?" }, { "code": null, "e": 30228, "s": 30172, "text": "How to Remove Duplicates From Array Using VBA in Excel?" } ]
Subset Sum Problem | Practice | GeeksforGeeks
Given an array of non-negative integers, and a value sum, determine if there is a subset of the given set with sum equal to given sum. Example 1: Input: N = 6 arr[] = {3, 34, 4, 12, 5, 2} sum = 9 Output: 1 Explanation: Here there exists a subset with sum = 9, 4+3+2 = 9. Example 2: Input: N = 6 arr[] = {3, 34, 4, 12, 5, 2} sum = 30 Output: 0 Explanation: There is no subset with sum 30. Your Task: You don't need to read input or print anything. Your task is to complete the function isSubsetSum() which takes the array arr[], its size N and an integer sum as input parameters and returns boolean value true if there exists a subset with given sum and false otherwise. The driver code itself prints 1, if returned value is true and prints 0 if returned value is false. Expected Time Complexity: O(sum*N) Expected Auxiliary Space: O(sum*N) Constraints: 1 <= N <= 100 1<= arr[i] <= 100 1<= sum <= 105 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": 374, "s": 238, "text": "Given an array of non-negative integers, and a value sum, determine if there is a subset of the given set with sum equal to given sum. " }, { "code": null, "e": 386, "s": 374, "text": "\nExample 1:" }, { "code": null, "e": 513, "s": 386, "text": "Input:\nN = 6\narr[] = {3, 34, 4, 12, 5, 2}\nsum = 9\nOutput: 1 \nExplanation: Here there exists a subset with\nsum = 9, 4+3+2 = 9.\n" }, { "code": null, "e": 524, "s": 513, "text": "Example 2:" }, { "code": null, "e": 631, "s": 524, "text": "Input:\nN = 6\narr[] = {3, 34, 4, 12, 5, 2}\nsum = 30\nOutput: 0 \nExplanation: There is no subset with sum 30." }, { "code": null, "e": 1018, "s": 631, "text": "\nYour Task: \nYou don't need to read input or print anything. Your task is to complete the function isSubsetSum() which takes the array arr[], its size N and an integer sum as input parameters and returns boolean value true if there exists a subset with given sum and false otherwise.\nThe driver code itself prints 1, if returned value is true and prints 0 if returned value is false.\n " }, { "code": null, "e": 1090, "s": 1018, "text": "Expected Time Complexity: O(sum*N)\nExpected Auxiliary Space: O(sum*N)\n " }, { "code": null, "e": 1150, "s": 1090, "text": "Constraints:\n1 <= N <= 100\n1<= arr[i] <= 100\n1<= sum <= 105" }, { "code": null, "e": 1296, "s": 1150, "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": 1332, "s": 1296, "text": " Login to access your submissions. " }, { "code": null, "e": 1342, "s": 1332, "text": "\nProblem\n" }, { "code": null, "e": 1352, "s": 1342, "text": "\nContest\n" }, { "code": null, "e": 1415, "s": 1352, "text": "Reset the IDE using the second button on the top right corner." }, { "code": null, "e": 1563, "s": 1415, "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": 1771, "s": 1563, "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": 1877, "s": 1771, "text": "You can access the hints to get an idea about what is expected of you as well as the final solution code." } ]
Minimal moves to form a string by adding characters or appending string itself - GeeksforGeeks
24 Aug, 2020 Given a string S, we need to write a program to check if it is possible to construct the given string S by performing any of the below operations any number of times. In each step, we can: Add any character at the end of the string. or, append the string to the string itself. The above steps can be applied any number of times. We need to write a program to print the minimum steps required to form the string. Examples: Input : aaaaaaaa Output : 4 Explanation: move 1: add 'a' to form "a" move 2: add 'a' to form "aa" move 3: append "aa" to form "aaaa" move 4: append "aaaa" to form "aaaaaaaa" Input: aaaaaa Output: 4 Explanation: move 1: add 'a' to form "a" move 2: add 'a' to form "aa" move 3: add 'a' to form "aaa" move 4: append "aaa" to form "aaaaaa" Input: abcabca Output: 5 The idea to solve this problem is to use Dynamic Programming to count the minimum number of moves. Create an array named dp of size n, where n is the length of the input string. dp[i] stores the minimum number of moves that are required to make substring (0...i). According to the question there are two moves that are possible: dp[i] = min(dp[i], dp[i-1] + 1) which signifies addition of characters.dp[i*2+1] = min(dp[i]+1, dp[i*2+1]), appending of string is done if s[0...i]==s[i+1..i*2+1]The answer will be stored in dp[n-1] as we need to form the string(0..n-1) index-wise.Below is the implementation of above idea:C++JavaPython3C#PHPC++// CPP program to print the// Minimal moves to form a string// by appending string and adding characters#include <bits/stdc++.h>using namespace std; // function to return the minimal number of movesint minimalSteps(string s, int n){ int dp[n]; // initializing dp[i] to INT_MAX for (int i = 0; i < n; i++) dp[i] = INT_MAX; // initialize both strings to null string s1 = "", s2 = ""; // base case dp[0] = 1; s1 += s[0]; for (int i = 1; i < n; i++) { s1 += s[i]; // check if it can be appended s2 = s.substr(i + 1, i + 1); // addition of character takes one step dp[i] = min(dp[i], dp[i - 1] + 1); // appending takes 1 step, and we directly // reach index i*2+1 after appending // so the number of steps is stord in i*2+1 if (s1 == s2) dp[i * 2 + 1] = min(dp[i] + 1, dp[i * 2 + 1]); } return dp[n - 1];} // Driver Codeint main(){ string s = "aaaaaaaa"; int n = s.length(); // function call to return minimal number of moves cout << minimalSteps(s, n); return 0;}Java// Java program to print the// Minimal moves to form a string// by appending string and adding charactersimport java.util.*; class GFG{ // function to return the minimal number of movesstatic int minimalSteps(String s, int n){ int []dp = new int[n]; // initializing dp[i] to INT_MAX for (int i = 0; i < n; i++) dp[i] = Integer.MAX_VALUE; // initialize both strings to null String s1 = "", s2 = ""; // base case dp[0] = 1; s1 += s.charAt(0); for (int i = 1; i < n; i++) { s1 += s.charAt(i); // check if it can be appended s2 = s.substring(i + 1, i + 1); // addition of character takes one step dp[i] = Math.min(dp[i], dp[i - 1] + 1); // appending takes 1 step, and we directly // reach index i*2+1 after appending // so the number of steps is stord in i*2+1 if (s1 == s2) dp[i * 2 + 1] = Math.min(dp[i] + 1, dp[i * 2 + 1]); } return dp[n - 1];} // Driver Codepublic static void main(String args[]){ String s = "aaaaaaaa"; int n = s.length(); // function call to return minimal number of moves System.out.println(minimalSteps(s, n)/2);}} // This code is contributed by // Shashank_SharmaPython3# Python program to print the # Minimal moves to form a string # by appending string and adding characters INT_MAX = 100000000 # function to return the # minimal number of moves def minimalSteps(s, n): dp = [INT_MAX for i in range(n)] # initialize both strings to null s1 = "" s2 = "" # base case dp[0] = 1 s1 += s[0] for i in range(1, n): s1 += s[i] # check if it can be appended s2 = s[i + 1: i + 1 + i + 1] # addition of character # takes one step dp[i] = min(dp[i], dp[i - 1] + 1) # appending takes 1 step, and # we directly reach index i*2+1 # after appending so the number # of steps is stord in i*2+1 if (s1 == s2): dp[i * 2 + 1] = min(dp[i] + 1, dp[i * 2 + 1]) return dp[n - 1] # Driver Code s = "aaaaaaaa"n =len(s) # function call to return # minimal number of moves print( minimalSteps(s, n) ) # This code is contributed # by sahilshelangiaC#// C# program to print the// Minimal moves to form a string// by appending string and adding charactersusing System; class GFG{ // function to return the minimal number of movesstatic int minimalSteps(String s, int n){ int []dp = new int[n]; // initializing dp[i] to INT_MAX for (int i = 0; i < n; i++) dp[i] = int.MaxValue; // initialize both strings to null String s1 = "", s2 = ""; // base case dp[0] = 1; s1 += s[0]; for (int i = 1; i < n; i++) { s1 += s[i]; // check if it can be appended s2 = s.Substring(i , 1); // addition of character takes one step dp[i] = Math.Min(dp[i], dp[i - 1] + 1); // appending takes 1 step, and we directly // reach index i*2+1 after appending // so the number of steps is stord in i*2+1 if (s1 == s2) dp[i * 2 + 1] = Math.Min(dp[i] + 1, dp[i * 2 + 1]); } return dp[n - 1];} // Driver Codepublic static void Main(String []args){ String s = "aaaaaaaa"; int n = s.Length; // function call to return minimal number of moves Console.Write(minimalSteps(s, n)/2);}} // This code has been contributed by 29AjayKumarPHP<?php// php program to print the// Minimal moves to form a // string by appending string// and adding characters // function to return the// minimal number of movesfunction minimalSteps($s,$n){ // initializing dp[i] to INT_MAX for ($i = 0; $i < $n; $i++) $dp[$i] = PHP_INT_MAX; // initialize both // strings to null $s1 = ""; $s2 = ""; // base case $dp[0] = 1; $s1=$s1.$s[0]; for ($i = 1; $i < $n; $i++) { $s1 = $s1.$s[$i]; // check if it can // be appended $s2 = substr($s, $i + 1, $i + 1); // addition of character // takes one step $dp[$i] = min($dp[$i], $dp[$i - 1] + 1); // appending takes 1 step, // and we directly // reach index i*2+1 // after appending // so the number of steps // is stord in i*2+1 if ($s1 == $s2) $dp[$i * 2 + 1] = min($dp[$i] + 1, $dp[$i * 2 + 1]); } return $dp[$n - 1];} // Driver Code $s = "aaaaaaaa"; $n = strlen($s); // function call to return //minimal number of moves echo minimalSteps($s, $n); // This code is contributed by mits ?>Output:4 Time Complexity : O(n2), where n is the length of input string.My Personal Notes arrow_drop_upSave dp[i] = min(dp[i], dp[i-1] + 1) which signifies addition of characters. dp[i*2+1] = min(dp[i]+1, dp[i*2+1]), appending of string is done if s[0...i]==s[i+1..i*2+1]The answer will be stored in dp[n-1] as we need to form the string(0..n-1) index-wise.Below is the implementation of above idea:C++JavaPython3C#PHPC++// CPP program to print the// Minimal moves to form a string// by appending string and adding characters#include <bits/stdc++.h>using namespace std; // function to return the minimal number of movesint minimalSteps(string s, int n){ int dp[n]; // initializing dp[i] to INT_MAX for (int i = 0; i < n; i++) dp[i] = INT_MAX; // initialize both strings to null string s1 = "", s2 = ""; // base case dp[0] = 1; s1 += s[0]; for (int i = 1; i < n; i++) { s1 += s[i]; // check if it can be appended s2 = s.substr(i + 1, i + 1); // addition of character takes one step dp[i] = min(dp[i], dp[i - 1] + 1); // appending takes 1 step, and we directly // reach index i*2+1 after appending // so the number of steps is stord in i*2+1 if (s1 == s2) dp[i * 2 + 1] = min(dp[i] + 1, dp[i * 2 + 1]); } return dp[n - 1];} // Driver Codeint main(){ string s = "aaaaaaaa"; int n = s.length(); // function call to return minimal number of moves cout << minimalSteps(s, n); return 0;}Java// Java program to print the// Minimal moves to form a string// by appending string and adding charactersimport java.util.*; class GFG{ // function to return the minimal number of movesstatic int minimalSteps(String s, int n){ int []dp = new int[n]; // initializing dp[i] to INT_MAX for (int i = 0; i < n; i++) dp[i] = Integer.MAX_VALUE; // initialize both strings to null String s1 = "", s2 = ""; // base case dp[0] = 1; s1 += s.charAt(0); for (int i = 1; i < n; i++) { s1 += s.charAt(i); // check if it can be appended s2 = s.substring(i + 1, i + 1); // addition of character takes one step dp[i] = Math.min(dp[i], dp[i - 1] + 1); // appending takes 1 step, and we directly // reach index i*2+1 after appending // so the number of steps is stord in i*2+1 if (s1 == s2) dp[i * 2 + 1] = Math.min(dp[i] + 1, dp[i * 2 + 1]); } return dp[n - 1];} // Driver Codepublic static void main(String args[]){ String s = "aaaaaaaa"; int n = s.length(); // function call to return minimal number of moves System.out.println(minimalSteps(s, n)/2);}} // This code is contributed by // Shashank_SharmaPython3# Python program to print the # Minimal moves to form a string # by appending string and adding characters INT_MAX = 100000000 # function to return the # minimal number of moves def minimalSteps(s, n): dp = [INT_MAX for i in range(n)] # initialize both strings to null s1 = "" s2 = "" # base case dp[0] = 1 s1 += s[0] for i in range(1, n): s1 += s[i] # check if it can be appended s2 = s[i + 1: i + 1 + i + 1] # addition of character # takes one step dp[i] = min(dp[i], dp[i - 1] + 1) # appending takes 1 step, and # we directly reach index i*2+1 # after appending so the number # of steps is stord in i*2+1 if (s1 == s2): dp[i * 2 + 1] = min(dp[i] + 1, dp[i * 2 + 1]) return dp[n - 1] # Driver Code s = "aaaaaaaa"n =len(s) # function call to return # minimal number of moves print( minimalSteps(s, n) ) # This code is contributed # by sahilshelangiaC#// C# program to print the// Minimal moves to form a string// by appending string and adding charactersusing System; class GFG{ // function to return the minimal number of movesstatic int minimalSteps(String s, int n){ int []dp = new int[n]; // initializing dp[i] to INT_MAX for (int i = 0; i < n; i++) dp[i] = int.MaxValue; // initialize both strings to null String s1 = "", s2 = ""; // base case dp[0] = 1; s1 += s[0]; for (int i = 1; i < n; i++) { s1 += s[i]; // check if it can be appended s2 = s.Substring(i , 1); // addition of character takes one step dp[i] = Math.Min(dp[i], dp[i - 1] + 1); // appending takes 1 step, and we directly // reach index i*2+1 after appending // so the number of steps is stord in i*2+1 if (s1 == s2) dp[i * 2 + 1] = Math.Min(dp[i] + 1, dp[i * 2 + 1]); } return dp[n - 1];} // Driver Codepublic static void Main(String []args){ String s = "aaaaaaaa"; int n = s.Length; // function call to return minimal number of moves Console.Write(minimalSteps(s, n)/2);}} // This code has been contributed by 29AjayKumarPHP<?php// php program to print the// Minimal moves to form a // string by appending string// and adding characters // function to return the// minimal number of movesfunction minimalSteps($s,$n){ // initializing dp[i] to INT_MAX for ($i = 0; $i < $n; $i++) $dp[$i] = PHP_INT_MAX; // initialize both // strings to null $s1 = ""; $s2 = ""; // base case $dp[0] = 1; $s1=$s1.$s[0]; for ($i = 1; $i < $n; $i++) { $s1 = $s1.$s[$i]; // check if it can // be appended $s2 = substr($s, $i + 1, $i + 1); // addition of character // takes one step $dp[$i] = min($dp[$i], $dp[$i - 1] + 1); // appending takes 1 step, // and we directly // reach index i*2+1 // after appending // so the number of steps // is stord in i*2+1 if ($s1 == $s2) $dp[$i * 2 + 1] = min($dp[$i] + 1, $dp[$i * 2 + 1]); } return $dp[$n - 1];} // Driver Code $s = "aaaaaaaa"; $n = strlen($s); // function call to return //minimal number of moves echo minimalSteps($s, $n); // This code is contributed by mits ?>Output:4 Time Complexity : O(n2), where n is the length of input string.My Personal Notes arrow_drop_upSave The answer will be stored in dp[n-1] as we need to form the string(0..n-1) index-wise. Below is the implementation of above idea: C++ Java Python3 C# PHP // CPP program to print the// Minimal moves to form a string// by appending string and adding characters#include <bits/stdc++.h>using namespace std; // function to return the minimal number of movesint minimalSteps(string s, int n){ int dp[n]; // initializing dp[i] to INT_MAX for (int i = 0; i < n; i++) dp[i] = INT_MAX; // initialize both strings to null string s1 = "", s2 = ""; // base case dp[0] = 1; s1 += s[0]; for (int i = 1; i < n; i++) { s1 += s[i]; // check if it can be appended s2 = s.substr(i + 1, i + 1); // addition of character takes one step dp[i] = min(dp[i], dp[i - 1] + 1); // appending takes 1 step, and we directly // reach index i*2+1 after appending // so the number of steps is stord in i*2+1 if (s1 == s2) dp[i * 2 + 1] = min(dp[i] + 1, dp[i * 2 + 1]); } return dp[n - 1];} // Driver Codeint main(){ string s = "aaaaaaaa"; int n = s.length(); // function call to return minimal number of moves cout << minimalSteps(s, n); return 0;} // Java program to print the// Minimal moves to form a string// by appending string and adding charactersimport java.util.*; class GFG{ // function to return the minimal number of movesstatic int minimalSteps(String s, int n){ int []dp = new int[n]; // initializing dp[i] to INT_MAX for (int i = 0; i < n; i++) dp[i] = Integer.MAX_VALUE; // initialize both strings to null String s1 = "", s2 = ""; // base case dp[0] = 1; s1 += s.charAt(0); for (int i = 1; i < n; i++) { s1 += s.charAt(i); // check if it can be appended s2 = s.substring(i + 1, i + 1); // addition of character takes one step dp[i] = Math.min(dp[i], dp[i - 1] + 1); // appending takes 1 step, and we directly // reach index i*2+1 after appending // so the number of steps is stord in i*2+1 if (s1 == s2) dp[i * 2 + 1] = Math.min(dp[i] + 1, dp[i * 2 + 1]); } return dp[n - 1];} // Driver Codepublic static void main(String args[]){ String s = "aaaaaaaa"; int n = s.length(); // function call to return minimal number of moves System.out.println(minimalSteps(s, n)/2);}} // This code is contributed by // Shashank_Sharma # Python program to print the # Minimal moves to form a string # by appending string and adding characters INT_MAX = 100000000 # function to return the # minimal number of moves def minimalSteps(s, n): dp = [INT_MAX for i in range(n)] # initialize both strings to null s1 = "" s2 = "" # base case dp[0] = 1 s1 += s[0] for i in range(1, n): s1 += s[i] # check if it can be appended s2 = s[i + 1: i + 1 + i + 1] # addition of character # takes one step dp[i] = min(dp[i], dp[i - 1] + 1) # appending takes 1 step, and # we directly reach index i*2+1 # after appending so the number # of steps is stord in i*2+1 if (s1 == s2): dp[i * 2 + 1] = min(dp[i] + 1, dp[i * 2 + 1]) return dp[n - 1] # Driver Code s = "aaaaaaaa"n =len(s) # function call to return # minimal number of moves print( minimalSteps(s, n) ) # This code is contributed # by sahilshelangia // C# program to print the// Minimal moves to form a string// by appending string and adding charactersusing System; class GFG{ // function to return the minimal number of movesstatic int minimalSteps(String s, int n){ int []dp = new int[n]; // initializing dp[i] to INT_MAX for (int i = 0; i < n; i++) dp[i] = int.MaxValue; // initialize both strings to null String s1 = "", s2 = ""; // base case dp[0] = 1; s1 += s[0]; for (int i = 1; i < n; i++) { s1 += s[i]; // check if it can be appended s2 = s.Substring(i , 1); // addition of character takes one step dp[i] = Math.Min(dp[i], dp[i - 1] + 1); // appending takes 1 step, and we directly // reach index i*2+1 after appending // so the number of steps is stord in i*2+1 if (s1 == s2) dp[i * 2 + 1] = Math.Min(dp[i] + 1, dp[i * 2 + 1]); } return dp[n - 1];} // Driver Codepublic static void Main(String []args){ String s = "aaaaaaaa"; int n = s.Length; // function call to return minimal number of moves Console.Write(minimalSteps(s, n)/2);}} // This code has been contributed by 29AjayKumar <?php// php program to print the// Minimal moves to form a // string by appending string// and adding characters // function to return the// minimal number of movesfunction minimalSteps($s,$n){ // initializing dp[i] to INT_MAX for ($i = 0; $i < $n; $i++) $dp[$i] = PHP_INT_MAX; // initialize both // strings to null $s1 = ""; $s2 = ""; // base case $dp[0] = 1; $s1=$s1.$s[0]; for ($i = 1; $i < $n; $i++) { $s1 = $s1.$s[$i]; // check if it can // be appended $s2 = substr($s, $i + 1, $i + 1); // addition of character // takes one step $dp[$i] = min($dp[$i], $dp[$i - 1] + 1); // appending takes 1 step, // and we directly // reach index i*2+1 // after appending // so the number of steps // is stord in i*2+1 if ($s1 == $s2) $dp[$i * 2 + 1] = min($dp[$i] + 1, $dp[$i * 2 + 1]); } return $dp[$n - 1];} // Driver Code $s = "aaaaaaaa"; $n = strlen($s); // function call to return //minimal number of moves echo minimalSteps($s, $n); // This code is contributed by mits ?> 4 Time Complexity : O(n2), where n is the length of input string. Mithun Kumar sahilshelangia Shashank_Sharma 29AjayKumar Akanksha_Rai C-String-Question Dynamic Programming Strings Strings Dynamic Programming Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Bellman–Ford Algorithm | DP-23 Floyd Warshall Algorithm | DP-16 Travelling Salesman Problem | Set 1 (Naive and Dynamic Programming) Edit Distance | DP-5 Sieve of Eratosthenes Write a program to reverse an array or string Reverse a string in Java Write a program to print all permutations of a given string C++ Data Types Check for Balanced Brackets in an expression (well-formedness) using Stack
[ { "code": null, "e": 26613, "s": 26585, "text": "\n24 Aug, 2020" }, { "code": null, "e": 26802, "s": 26613, "text": "Given a string S, we need to write a program to check if it is possible to construct the given string S by performing any of the below operations any number of times. In each step, we can:" }, { "code": null, "e": 26846, "s": 26802, "text": "Add any character at the end of the string." }, { "code": null, "e": 26890, "s": 26846, "text": "or, append the string to the string itself." }, { "code": null, "e": 27025, "s": 26890, "text": "The above steps can be applied any number of times. We need to write a program to print the minimum steps required to form the string." }, { "code": null, "e": 27035, "s": 27025, "text": "Examples:" }, { "code": null, "e": 27407, "s": 27035, "text": "Input : aaaaaaaa\nOutput : 4 \nExplanation: move 1: add 'a' to form \"a\"\nmove 2: add 'a' to form \"aa\"\nmove 3: append \"aa\" to form \"aaaa\" \nmove 4: append \"aaaa\" to form \"aaaaaaaa\" \n\nInput: aaaaaa\nOutput: 4 \nExplanation: move 1: add 'a' to form \"a\"\nmove 2: add 'a' to form \"aa\"\nmove 3: add 'a' to form \"aaa\" \nmove 4: append \"aaa\" to form \"aaaaaa\" \n\nInput: abcabca\nOutput: 5 \n" }, { "code": null, "e": 27736, "s": 27407, "text": "The idea to solve this problem is to use Dynamic Programming to count the minimum number of moves. Create an array named dp of size n, where n is the length of the input string. dp[i] stores the minimum number of moves that are required to make substring (0...i). According to the question there are two moves that are possible:" }, { "code": null, "e": 34094, "s": 27736, "text": "dp[i] = min(dp[i], dp[i-1] + 1) which signifies addition of characters.dp[i*2+1] = min(dp[i]+1, dp[i*2+1]), appending of string is done if s[0...i]==s[i+1..i*2+1]The answer will be stored in dp[n-1] as we need to form the string(0..n-1) index-wise.Below is the implementation of above idea:C++JavaPython3C#PHPC++// CPP program to print the// Minimal moves to form a string// by appending string and adding characters#include <bits/stdc++.h>using namespace std; // function to return the minimal number of movesint minimalSteps(string s, int n){ int dp[n]; // initializing dp[i] to INT_MAX for (int i = 0; i < n; i++) dp[i] = INT_MAX; // initialize both strings to null string s1 = \"\", s2 = \"\"; // base case dp[0] = 1; s1 += s[0]; for (int i = 1; i < n; i++) { s1 += s[i]; // check if it can be appended s2 = s.substr(i + 1, i + 1); // addition of character takes one step dp[i] = min(dp[i], dp[i - 1] + 1); // appending takes 1 step, and we directly // reach index i*2+1 after appending // so the number of steps is stord in i*2+1 if (s1 == s2) dp[i * 2 + 1] = min(dp[i] + 1, dp[i * 2 + 1]); } return dp[n - 1];} // Driver Codeint main(){ string s = \"aaaaaaaa\"; int n = s.length(); // function call to return minimal number of moves cout << minimalSteps(s, n); return 0;}Java// Java program to print the// Minimal moves to form a string// by appending string and adding charactersimport java.util.*; class GFG{ // function to return the minimal number of movesstatic int minimalSteps(String s, int n){ int []dp = new int[n]; // initializing dp[i] to INT_MAX for (int i = 0; i < n; i++) dp[i] = Integer.MAX_VALUE; // initialize both strings to null String s1 = \"\", s2 = \"\"; // base case dp[0] = 1; s1 += s.charAt(0); for (int i = 1; i < n; i++) { s1 += s.charAt(i); // check if it can be appended s2 = s.substring(i + 1, i + 1); // addition of character takes one step dp[i] = Math.min(dp[i], dp[i - 1] + 1); // appending takes 1 step, and we directly // reach index i*2+1 after appending // so the number of steps is stord in i*2+1 if (s1 == s2) dp[i * 2 + 1] = Math.min(dp[i] + 1, dp[i * 2 + 1]); } return dp[n - 1];} // Driver Codepublic static void main(String args[]){ String s = \"aaaaaaaa\"; int n = s.length(); // function call to return minimal number of moves System.out.println(minimalSteps(s, n)/2);}} // This code is contributed by // Shashank_SharmaPython3# Python program to print the # Minimal moves to form a string # by appending string and adding characters INT_MAX = 100000000 # function to return the # minimal number of moves def minimalSteps(s, n): dp = [INT_MAX for i in range(n)] # initialize both strings to null s1 = \"\" s2 = \"\" # base case dp[0] = 1 s1 += s[0] for i in range(1, n): s1 += s[i] # check if it can be appended s2 = s[i + 1: i + 1 + i + 1] # addition of character # takes one step dp[i] = min(dp[i], dp[i - 1] + 1) # appending takes 1 step, and # we directly reach index i*2+1 # after appending so the number # of steps is stord in i*2+1 if (s1 == s2): dp[i * 2 + 1] = min(dp[i] + 1, dp[i * 2 + 1]) return dp[n - 1] # Driver Code s = \"aaaaaaaa\"n =len(s) # function call to return # minimal number of moves print( minimalSteps(s, n) ) # This code is contributed # by sahilshelangiaC#// C# program to print the// Minimal moves to form a string// by appending string and adding charactersusing System; class GFG{ // function to return the minimal number of movesstatic int minimalSteps(String s, int n){ int []dp = new int[n]; // initializing dp[i] to INT_MAX for (int i = 0; i < n; i++) dp[i] = int.MaxValue; // initialize both strings to null String s1 = \"\", s2 = \"\"; // base case dp[0] = 1; s1 += s[0]; for (int i = 1; i < n; i++) { s1 += s[i]; // check if it can be appended s2 = s.Substring(i , 1); // addition of character takes one step dp[i] = Math.Min(dp[i], dp[i - 1] + 1); // appending takes 1 step, and we directly // reach index i*2+1 after appending // so the number of steps is stord in i*2+1 if (s1 == s2) dp[i * 2 + 1] = Math.Min(dp[i] + 1, dp[i * 2 + 1]); } return dp[n - 1];} // Driver Codepublic static void Main(String []args){ String s = \"aaaaaaaa\"; int n = s.Length; // function call to return minimal number of moves Console.Write(minimalSteps(s, n)/2);}} // This code has been contributed by 29AjayKumarPHP<?php// php program to print the// Minimal moves to form a // string by appending string// and adding characters // function to return the// minimal number of movesfunction minimalSteps($s,$n){ // initializing dp[i] to INT_MAX for ($i = 0; $i < $n; $i++) $dp[$i] = PHP_INT_MAX; // initialize both // strings to null $s1 = \"\"; $s2 = \"\"; // base case $dp[0] = 1; $s1=$s1.$s[0]; for ($i = 1; $i < $n; $i++) { $s1 = $s1.$s[$i]; // check if it can // be appended $s2 = substr($s, $i + 1, $i + 1); // addition of character // takes one step $dp[$i] = min($dp[$i], $dp[$i - 1] + 1); // appending takes 1 step, // and we directly // reach index i*2+1 // after appending // so the number of steps // is stord in i*2+1 if ($s1 == $s2) $dp[$i * 2 + 1] = min($dp[$i] + 1, $dp[$i * 2 + 1]); } return $dp[$n - 1];} // Driver Code $s = \"aaaaaaaa\"; $n = strlen($s); // function call to return //minimal number of moves echo minimalSteps($s, $n); // This code is contributed by mits ?>Output:4\nTime Complexity : O(n2), where n is the length of input string.My Personal Notes\narrow_drop_upSave" }, { "code": null, "e": 34166, "s": 34094, "text": "dp[i] = min(dp[i], dp[i-1] + 1) which signifies addition of characters." }, { "code": null, "e": 40453, "s": 34166, "text": "dp[i*2+1] = min(dp[i]+1, dp[i*2+1]), appending of string is done if s[0...i]==s[i+1..i*2+1]The answer will be stored in dp[n-1] as we need to form the string(0..n-1) index-wise.Below is the implementation of above idea:C++JavaPython3C#PHPC++// CPP program to print the// Minimal moves to form a string// by appending string and adding characters#include <bits/stdc++.h>using namespace std; // function to return the minimal number of movesint minimalSteps(string s, int n){ int dp[n]; // initializing dp[i] to INT_MAX for (int i = 0; i < n; i++) dp[i] = INT_MAX; // initialize both strings to null string s1 = \"\", s2 = \"\"; // base case dp[0] = 1; s1 += s[0]; for (int i = 1; i < n; i++) { s1 += s[i]; // check if it can be appended s2 = s.substr(i + 1, i + 1); // addition of character takes one step dp[i] = min(dp[i], dp[i - 1] + 1); // appending takes 1 step, and we directly // reach index i*2+1 after appending // so the number of steps is stord in i*2+1 if (s1 == s2) dp[i * 2 + 1] = min(dp[i] + 1, dp[i * 2 + 1]); } return dp[n - 1];} // Driver Codeint main(){ string s = \"aaaaaaaa\"; int n = s.length(); // function call to return minimal number of moves cout << minimalSteps(s, n); return 0;}Java// Java program to print the// Minimal moves to form a string// by appending string and adding charactersimport java.util.*; class GFG{ // function to return the minimal number of movesstatic int minimalSteps(String s, int n){ int []dp = new int[n]; // initializing dp[i] to INT_MAX for (int i = 0; i < n; i++) dp[i] = Integer.MAX_VALUE; // initialize both strings to null String s1 = \"\", s2 = \"\"; // base case dp[0] = 1; s1 += s.charAt(0); for (int i = 1; i < n; i++) { s1 += s.charAt(i); // check if it can be appended s2 = s.substring(i + 1, i + 1); // addition of character takes one step dp[i] = Math.min(dp[i], dp[i - 1] + 1); // appending takes 1 step, and we directly // reach index i*2+1 after appending // so the number of steps is stord in i*2+1 if (s1 == s2) dp[i * 2 + 1] = Math.min(dp[i] + 1, dp[i * 2 + 1]); } return dp[n - 1];} // Driver Codepublic static void main(String args[]){ String s = \"aaaaaaaa\"; int n = s.length(); // function call to return minimal number of moves System.out.println(minimalSteps(s, n)/2);}} // This code is contributed by // Shashank_SharmaPython3# Python program to print the # Minimal moves to form a string # by appending string and adding characters INT_MAX = 100000000 # function to return the # minimal number of moves def minimalSteps(s, n): dp = [INT_MAX for i in range(n)] # initialize both strings to null s1 = \"\" s2 = \"\" # base case dp[0] = 1 s1 += s[0] for i in range(1, n): s1 += s[i] # check if it can be appended s2 = s[i + 1: i + 1 + i + 1] # addition of character # takes one step dp[i] = min(dp[i], dp[i - 1] + 1) # appending takes 1 step, and # we directly reach index i*2+1 # after appending so the number # of steps is stord in i*2+1 if (s1 == s2): dp[i * 2 + 1] = min(dp[i] + 1, dp[i * 2 + 1]) return dp[n - 1] # Driver Code s = \"aaaaaaaa\"n =len(s) # function call to return # minimal number of moves print( minimalSteps(s, n) ) # This code is contributed # by sahilshelangiaC#// C# program to print the// Minimal moves to form a string// by appending string and adding charactersusing System; class GFG{ // function to return the minimal number of movesstatic int minimalSteps(String s, int n){ int []dp = new int[n]; // initializing dp[i] to INT_MAX for (int i = 0; i < n; i++) dp[i] = int.MaxValue; // initialize both strings to null String s1 = \"\", s2 = \"\"; // base case dp[0] = 1; s1 += s[0]; for (int i = 1; i < n; i++) { s1 += s[i]; // check if it can be appended s2 = s.Substring(i , 1); // addition of character takes one step dp[i] = Math.Min(dp[i], dp[i - 1] + 1); // appending takes 1 step, and we directly // reach index i*2+1 after appending // so the number of steps is stord in i*2+1 if (s1 == s2) dp[i * 2 + 1] = Math.Min(dp[i] + 1, dp[i * 2 + 1]); } return dp[n - 1];} // Driver Codepublic static void Main(String []args){ String s = \"aaaaaaaa\"; int n = s.Length; // function call to return minimal number of moves Console.Write(minimalSteps(s, n)/2);}} // This code has been contributed by 29AjayKumarPHP<?php// php program to print the// Minimal moves to form a // string by appending string// and adding characters // function to return the// minimal number of movesfunction minimalSteps($s,$n){ // initializing dp[i] to INT_MAX for ($i = 0; $i < $n; $i++) $dp[$i] = PHP_INT_MAX; // initialize both // strings to null $s1 = \"\"; $s2 = \"\"; // base case $dp[0] = 1; $s1=$s1.$s[0]; for ($i = 1; $i < $n; $i++) { $s1 = $s1.$s[$i]; // check if it can // be appended $s2 = substr($s, $i + 1, $i + 1); // addition of character // takes one step $dp[$i] = min($dp[$i], $dp[$i - 1] + 1); // appending takes 1 step, // and we directly // reach index i*2+1 // after appending // so the number of steps // is stord in i*2+1 if ($s1 == $s2) $dp[$i * 2 + 1] = min($dp[$i] + 1, $dp[$i * 2 + 1]); } return $dp[$n - 1];} // Driver Code $s = \"aaaaaaaa\"; $n = strlen($s); // function call to return //minimal number of moves echo minimalSteps($s, $n); // This code is contributed by mits ?>Output:4\nTime Complexity : O(n2), where n is the length of input string.My Personal Notes\narrow_drop_upSave" }, { "code": null, "e": 40540, "s": 40453, "text": "The answer will be stored in dp[n-1] as we need to form the string(0..n-1) index-wise." }, { "code": null, "e": 40583, "s": 40540, "text": "Below is the implementation of above idea:" }, { "code": null, "e": 40587, "s": 40583, "text": "C++" }, { "code": null, "e": 40592, "s": 40587, "text": "Java" }, { "code": null, "e": 40600, "s": 40592, "text": "Python3" }, { "code": null, "e": 40603, "s": 40600, "text": "C#" }, { "code": null, "e": 40607, "s": 40603, "text": "PHP" }, { "code": "// CPP program to print the// Minimal moves to form a string// by appending string and adding characters#include <bits/stdc++.h>using namespace std; // function to return the minimal number of movesint minimalSteps(string s, int n){ int dp[n]; // initializing dp[i] to INT_MAX for (int i = 0; i < n; i++) dp[i] = INT_MAX; // initialize both strings to null string s1 = \"\", s2 = \"\"; // base case dp[0] = 1; s1 += s[0]; for (int i = 1; i < n; i++) { s1 += s[i]; // check if it can be appended s2 = s.substr(i + 1, i + 1); // addition of character takes one step dp[i] = min(dp[i], dp[i - 1] + 1); // appending takes 1 step, and we directly // reach index i*2+1 after appending // so the number of steps is stord in i*2+1 if (s1 == s2) dp[i * 2 + 1] = min(dp[i] + 1, dp[i * 2 + 1]); } return dp[n - 1];} // Driver Codeint main(){ string s = \"aaaaaaaa\"; int n = s.length(); // function call to return minimal number of moves cout << minimalSteps(s, n); return 0;}", "e": 41728, "s": 40607, "text": null }, { "code": "// Java program to print the// Minimal moves to form a string// by appending string and adding charactersimport java.util.*; class GFG{ // function to return the minimal number of movesstatic int minimalSteps(String s, int n){ int []dp = new int[n]; // initializing dp[i] to INT_MAX for (int i = 0; i < n; i++) dp[i] = Integer.MAX_VALUE; // initialize both strings to null String s1 = \"\", s2 = \"\"; // base case dp[0] = 1; s1 += s.charAt(0); for (int i = 1; i < n; i++) { s1 += s.charAt(i); // check if it can be appended s2 = s.substring(i + 1, i + 1); // addition of character takes one step dp[i] = Math.min(dp[i], dp[i - 1] + 1); // appending takes 1 step, and we directly // reach index i*2+1 after appending // so the number of steps is stord in i*2+1 if (s1 == s2) dp[i * 2 + 1] = Math.min(dp[i] + 1, dp[i * 2 + 1]); } return dp[n - 1];} // Driver Codepublic static void main(String args[]){ String s = \"aaaaaaaa\"; int n = s.length(); // function call to return minimal number of moves System.out.println(minimalSteps(s, n)/2);}} // This code is contributed by // Shashank_Sharma", "e": 43012, "s": 41728, "text": null }, { "code": "# Python program to print the # Minimal moves to form a string # by appending string and adding characters INT_MAX = 100000000 # function to return the # minimal number of moves def minimalSteps(s, n): dp = [INT_MAX for i in range(n)] # initialize both strings to null s1 = \"\" s2 = \"\" # base case dp[0] = 1 s1 += s[0] for i in range(1, n): s1 += s[i] # check if it can be appended s2 = s[i + 1: i + 1 + i + 1] # addition of character # takes one step dp[i] = min(dp[i], dp[i - 1] + 1) # appending takes 1 step, and # we directly reach index i*2+1 # after appending so the number # of steps is stord in i*2+1 if (s1 == s2): dp[i * 2 + 1] = min(dp[i] + 1, dp[i * 2 + 1]) return dp[n - 1] # Driver Code s = \"aaaaaaaa\"n =len(s) # function call to return # minimal number of moves print( minimalSteps(s, n) ) # This code is contributed # by sahilshelangia", "e": 44069, "s": 43012, "text": null }, { "code": "// C# program to print the// Minimal moves to form a string// by appending string and adding charactersusing System; class GFG{ // function to return the minimal number of movesstatic int minimalSteps(String s, int n){ int []dp = new int[n]; // initializing dp[i] to INT_MAX for (int i = 0; i < n; i++) dp[i] = int.MaxValue; // initialize both strings to null String s1 = \"\", s2 = \"\"; // base case dp[0] = 1; s1 += s[0]; for (int i = 1; i < n; i++) { s1 += s[i]; // check if it can be appended s2 = s.Substring(i , 1); // addition of character takes one step dp[i] = Math.Min(dp[i], dp[i - 1] + 1); // appending takes 1 step, and we directly // reach index i*2+1 after appending // so the number of steps is stord in i*2+1 if (s1 == s2) dp[i * 2 + 1] = Math.Min(dp[i] + 1, dp[i * 2 + 1]); } return dp[n - 1];} // Driver Codepublic static void Main(String []args){ String s = \"aaaaaaaa\"; int n = s.Length; // function call to return minimal number of moves Console.Write(minimalSteps(s, n)/2);}} // This code has been contributed by 29AjayKumar", "e": 45312, "s": 44069, "text": null }, { "code": "<?php// php program to print the// Minimal moves to form a // string by appending string// and adding characters // function to return the// minimal number of movesfunction minimalSteps($s,$n){ // initializing dp[i] to INT_MAX for ($i = 0; $i < $n; $i++) $dp[$i] = PHP_INT_MAX; // initialize both // strings to null $s1 = \"\"; $s2 = \"\"; // base case $dp[0] = 1; $s1=$s1.$s[0]; for ($i = 1; $i < $n; $i++) { $s1 = $s1.$s[$i]; // check if it can // be appended $s2 = substr($s, $i + 1, $i + 1); // addition of character // takes one step $dp[$i] = min($dp[$i], $dp[$i - 1] + 1); // appending takes 1 step, // and we directly // reach index i*2+1 // after appending // so the number of steps // is stord in i*2+1 if ($s1 == $s2) $dp[$i * 2 + 1] = min($dp[$i] + 1, $dp[$i * 2 + 1]); } return $dp[$n - 1];} // Driver Code $s = \"aaaaaaaa\"; $n = strlen($s); // function call to return //minimal number of moves echo minimalSteps($s, $n); // This code is contributed by mits ?>", "e": 46534, "s": 45312, "text": null }, { "code": null, "e": 46537, "s": 46534, "text": "4\n" }, { "code": null, "e": 46601, "s": 46537, "text": "Time Complexity : O(n2), where n is the length of input string." }, { "code": null, "e": 46614, "s": 46601, "text": "Mithun Kumar" }, { "code": null, "e": 46629, "s": 46614, "text": "sahilshelangia" }, { "code": null, "e": 46645, "s": 46629, "text": "Shashank_Sharma" }, { "code": null, "e": 46657, "s": 46645, "text": "29AjayKumar" }, { "code": null, "e": 46670, "s": 46657, "text": "Akanksha_Rai" }, { "code": null, "e": 46688, "s": 46670, "text": "C-String-Question" }, { "code": null, "e": 46708, "s": 46688, "text": "Dynamic Programming" }, { "code": null, "e": 46716, "s": 46708, "text": "Strings" }, { "code": null, "e": 46724, "s": 46716, "text": "Strings" }, { "code": null, "e": 46744, "s": 46724, "text": "Dynamic Programming" }, { "code": null, "e": 46842, "s": 46744, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 46873, "s": 46842, "text": "Bellman–Ford Algorithm | DP-23" }, { "code": null, "e": 46906, "s": 46873, "text": "Floyd Warshall Algorithm | DP-16" }, { "code": null, "e": 46974, "s": 46906, "text": "Travelling Salesman Problem | Set 1 (Naive and Dynamic Programming)" }, { "code": null, "e": 46995, "s": 46974, "text": "Edit Distance | DP-5" }, { "code": null, "e": 47017, "s": 46995, "text": "Sieve of Eratosthenes" }, { "code": null, "e": 47063, "s": 47017, "text": "Write a program to reverse an array or string" }, { "code": null, "e": 47088, "s": 47063, "text": "Reverse a string in Java" }, { "code": null, "e": 47148, "s": 47088, "text": "Write a program to print all permutations of a given string" }, { "code": null, "e": 47163, "s": 47148, "text": "C++ Data Types" } ]
Python | Find the closest Key in dictionary - GeeksforGeeks
19 Jul, 2019 The search of keys in dictionary in python has been discussed many times. But sometimes, we may have a problem in which we require to fetch the key which is the nearest one of the given keys. Let’s discuss certain ways in which this task can be performed. Method #1 : Using list comprehension + keys() + lambdaThe combination of above functions can be used to perform the particular task of finding the closest key in the dictionary. The keys function can be used to access the keys from the dictionary, lambda function can be used to formulate the logic and list comprehension to apply that all to whole list. # Python3 code to demonstrate working of# Closest key in dictionary# Using list comprehension + keys() + lambda # initializing dictionarytest_dict = {13 : 'Hi', 15 : 'Hello', 16 : 'Gfg'} # initializing nearest keysearch_key = 15.6 # printing original dictionaryprint("The original dictionary is : " + str(test_dict)) # Using list comprehension + keys() + lambda# Closest key in dictionaryres = test_dict.get(search_key) or test_dict[ min(test_dict.keys(), key = lambda key: abs(key-search_key))] # printing result print("The value to the closest key : " + str(res)) The original dictionary is : {16: 'Gfg', 13: 'Hi', 15: 'Hello'} The value to the closest key : Gfg Method #2 : Using bisect_left() + OrderedDict()This method generally uses the binary search method of finding the nearest number. While being fast, it changes the ordering and also returns 2 potential candidates for nearest values, current and the next key’s value in sequence. And just returns position of key. # Python3 code to demonstrate working of# Closest key in dictionary# Using bisect_left() + OrderedDict()import collectionsimport bisect # initializing dictionarytest_dict = collections.OrderedDict()test_dict = {13 : 'Hi', 15 : 'Hello', 16 : 'Gfg'} # initializing nearest keysearch_key = 15.6 # printing original dictionaryprint("The original dictionary is : " + str(test_dict)) # Using bisect_left() + OrderedDict()# Closest key in dictionaryres = bisect.bisect_left(list(test_dict.keys()), 15.6) # printing result print("The position of closest key : " + str(res)) The original dictionary is : {16: 'Gfg', 13: 'Hi', 15: 'Hello'} The position of closest key : 3 Python dictionary-programs Python Python Programs Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Enumerate() in Python Python Dictionary Defaultdict in Python sum() function in Python Python String | replace() Defaultdict in Python Python program to convert a list to string Python | Split string into list of characters Python | Convert a list into a tuple Python Program for Binary Search (Recursive and Iterative)
[ { "code": null, "e": 26121, "s": 26093, "text": "\n19 Jul, 2019" }, { "code": null, "e": 26377, "s": 26121, "text": "The search of keys in dictionary in python has been discussed many times. But sometimes, we may have a problem in which we require to fetch the key which is the nearest one of the given keys. Let’s discuss certain ways in which this task can be performed." }, { "code": null, "e": 26732, "s": 26377, "text": "Method #1 : Using list comprehension + keys() + lambdaThe combination of above functions can be used to perform the particular task of finding the closest key in the dictionary. The keys function can be used to access the keys from the dictionary, lambda function can be used to formulate the logic and list comprehension to apply that all to whole list." }, { "code": "# Python3 code to demonstrate working of# Closest key in dictionary# Using list comprehension + keys() + lambda # initializing dictionarytest_dict = {13 : 'Hi', 15 : 'Hello', 16 : 'Gfg'} # initializing nearest keysearch_key = 15.6 # printing original dictionaryprint(\"The original dictionary is : \" + str(test_dict)) # Using list comprehension + keys() + lambda# Closest key in dictionaryres = test_dict.get(search_key) or test_dict[ min(test_dict.keys(), key = lambda key: abs(key-search_key))] # printing result print(\"The value to the closest key : \" + str(res))", "e": 27309, "s": 26732, "text": null }, { "code": null, "e": 27409, "s": 27309, "text": "The original dictionary is : {16: 'Gfg', 13: 'Hi', 15: 'Hello'}\nThe value to the closest key : Gfg\n" }, { "code": null, "e": 27723, "s": 27411, "text": "Method #2 : Using bisect_left() + OrderedDict()This method generally uses the binary search method of finding the nearest number. While being fast, it changes the ordering and also returns 2 potential candidates for nearest values, current and the next key’s value in sequence. And just returns position of key." }, { "code": "# Python3 code to demonstrate working of# Closest key in dictionary# Using bisect_left() + OrderedDict()import collectionsimport bisect # initializing dictionarytest_dict = collections.OrderedDict()test_dict = {13 : 'Hi', 15 : 'Hello', 16 : 'Gfg'} # initializing nearest keysearch_key = 15.6 # printing original dictionaryprint(\"The original dictionary is : \" + str(test_dict)) # Using bisect_left() + OrderedDict()# Closest key in dictionaryres = bisect.bisect_left(list(test_dict.keys()), 15.6) # printing result print(\"The position of closest key : \" + str(res))", "e": 28295, "s": 27723, "text": null }, { "code": null, "e": 28392, "s": 28295, "text": "The original dictionary is : {16: 'Gfg', 13: 'Hi', 15: 'Hello'}\nThe position of closest key : 3\n" }, { "code": null, "e": 28419, "s": 28392, "text": "Python dictionary-programs" }, { "code": null, "e": 28426, "s": 28419, "text": "Python" }, { "code": null, "e": 28442, "s": 28426, "text": "Python Programs" }, { "code": null, "e": 28540, "s": 28442, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 28562, "s": 28540, "text": "Enumerate() in Python" }, { "code": null, "e": 28580, "s": 28562, "text": "Python Dictionary" }, { "code": null, "e": 28602, "s": 28580, "text": "Defaultdict in Python" }, { "code": null, "e": 28627, "s": 28602, "text": "sum() function in Python" }, { "code": null, "e": 28653, "s": 28627, "text": "Python String | replace()" }, { "code": null, "e": 28675, "s": 28653, "text": "Defaultdict in Python" }, { "code": null, "e": 28718, "s": 28675, "text": "Python program to convert a list to string" }, { "code": null, "e": 28764, "s": 28718, "text": "Python | Split string into list of characters" }, { "code": null, "e": 28801, "s": 28764, "text": "Python | Convert a list into a tuple" } ]
HTML Doctypes - GeeksforGeeks
04 Feb, 2021 Doctype: A doctype or document type declaration is an instruction that tells the web browser about the markup language in which the current page is written. The Doctype is not an element or tag, it lets the browser know about the version of or standard of HTML or any other markup language that is being used in the document. Declaration of a Doctype: A DOCTYPE declaration appears at the top of a web page before all other elements. According to the HTML specification or standards, every HTML document requires a document type declaration to ensure that the pages are displayed in the way they are intended to be displayed. The DOCTYPE for HTML5 is case-insensitive and can be written as shown below: < !DOCTYPE html > Doctype Usage: In the version, HTML 4.01, the usage of DOCTYPE declaration was to create a reference to a document type definition (DTD), since the version HTML 4.01 was completely based on a Standard Generalized Markup Language(SGML).The document type definition (DTD) is responsible for specifying the rules for the Standard Generalized Markup Language(SGML) so that the browser processes the content correctly. But in the HTML version, HTML 5 there isn’t any need for a reference to a document type definition (DTD) because HTML 5 is not based on a Standard Generalized Markup Language(SGML). In HTML 5, the DOCTYPE declaration is only required for enabling the standard mode for writing documents.Below is a sample HTML program with doctype declaration: Example: html <!DOCTYPE html><html> <body> <h1>GeeksforGeeks</h1> <h2>This is HTML5 Doctype Tag</h2></body> </html> Output: Below is the list of some common doctype declaration for different version of HTML and XHTML: HTML 5 htmlhtml<!DOCTYPE html>HTML 4.01 Strict: In HTML 4.01 Strict document type definition (DTD) all those elements and attributes are included that do not appear in frameset documents or that have not been deprecated.htmlhtml<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd"> HTML 4.01 Transitional: In HTML 4.01 Transitional document type definition (DTD) allows some older PUBLIC and attributes that have been deprecated. htmlhtml<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">HTML 4.01 Frameset: In HTML 4.01 Frameset document type definition (DTD),Frames can be used.htmlhtml<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Frameset//EN" "http://www.w3.org/TR/html4/frameset.dtd">XHTML 1.0 Strict: In XHTML 1.0 Strict document type definition (DTD), deprecated tags are not supported and the code must be written according to the XML Specification.htmlhtml<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">XHTML 1.0 Transitional: In XHTML 1.0 Transitional document type definition (DTD), deprecated elements are allowed.htmlhtml<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">XHTML 1.0 Frameset: In XHTML 1.0 Frameset document type definition (DTD), framesets can be used.htmlhtml<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Frameset//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-frameset.dtd">XHTML 1.1: In XHTML 1.1 document type definition (DTD), allows the addition of modules.htmlhtml<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN" "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd"> HTML 5 htmlhtml<!DOCTYPE html> HTML 5 html <!DOCTYPE html> HTML 4.01 Strict: In HTML 4.01 Strict document type definition (DTD) all those elements and attributes are included that do not appear in frameset documents or that have not been deprecated.htmlhtml<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd"> HTML 4.01 Strict: In HTML 4.01 Strict document type definition (DTD) all those elements and attributes are included that do not appear in frameset documents or that have not been deprecated. html <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd"> HTML 4.01 Transitional: In HTML 4.01 Transitional document type definition (DTD) allows some older PUBLIC and attributes that have been deprecated. htmlhtml<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> HTML 4.01 Transitional: In HTML 4.01 Transitional document type definition (DTD) allows some older PUBLIC and attributes that have been deprecated. html <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> HTML 4.01 Frameset: In HTML 4.01 Frameset document type definition (DTD),Frames can be used.htmlhtml<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Frameset//EN" "http://www.w3.org/TR/html4/frameset.dtd"> HTML 4.01 Frameset: In HTML 4.01 Frameset document type definition (DTD),Frames can be used. html <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Frameset//EN" "http://www.w3.org/TR/html4/frameset.dtd"> XHTML 1.0 Strict: In XHTML 1.0 Strict document type definition (DTD), deprecated tags are not supported and the code must be written according to the XML Specification.htmlhtml<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"> XHTML 1.0 Strict: In XHTML 1.0 Strict document type definition (DTD), deprecated tags are not supported and the code must be written according to the XML Specification. html <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"> XHTML 1.0 Transitional: In XHTML 1.0 Transitional document type definition (DTD), deprecated elements are allowed.htmlhtml<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> XHTML 1.0 Transitional: In XHTML 1.0 Transitional document type definition (DTD), deprecated elements are allowed. html <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> XHTML 1.0 Frameset: In XHTML 1.0 Frameset document type definition (DTD), framesets can be used.htmlhtml<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Frameset//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-frameset.dtd"> XHTML 1.0 Frameset: In XHTML 1.0 Frameset document type definition (DTD), framesets can be used. html <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Frameset//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-frameset.dtd"> XHTML 1.1: In XHTML 1.1 document type definition (DTD), allows the addition of modules.htmlhtml<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN" "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd"> XHTML 1.1: In XHTML 1.1 document type definition (DTD), allows the addition of modules. html <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN" "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd"> Supported Browsers: Google Chrome Internet Explorer Firefox Opera Safari Attention reader! Don’t stop learning now. Get hold of all the important HTML concepts with the Web Design for Beginners | HTML course. nidhi_biet shubhamyadav4 HTML-Basics HTML Web Technologies HTML Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to insert spaces/tabs in text using HTML/CSS? Top 10 Projects For Beginners To Practice HTML and CSS Skills How to update Node.js and NPM to next version ? How to set the default value for an HTML <select> element ? Hide or show elements in HTML using display property Remove elements from a JavaScript Array Installation of Node.js on Linux Convert a string to an integer in JavaScript How to fetch data from an API in ReactJS ? Difference between var, let and const keywords in JavaScript
[ { "code": null, "e": 31646, "s": 31618, "text": "\n04 Feb, 2021" }, { "code": null, "e": 31972, "s": 31646, "text": "Doctype: A doctype or document type declaration is an instruction that tells the web browser about the markup language in which the current page is written. The Doctype is not an element or tag, it lets the browser know about the version of or standard of HTML or any other markup language that is being used in the document." }, { "code": null, "e": 32272, "s": 31972, "text": "Declaration of a Doctype: A DOCTYPE declaration appears at the top of a web page before all other elements. According to the HTML specification or standards, every HTML document requires a document type declaration to ensure that the pages are displayed in the way they are intended to be displayed." }, { "code": null, "e": 32349, "s": 32272, "text": "The DOCTYPE for HTML5 is case-insensitive and can be written as shown below:" }, { "code": null, "e": 32367, "s": 32349, "text": "< !DOCTYPE html >" }, { "code": null, "e": 32963, "s": 32367, "text": "Doctype Usage: In the version, HTML 4.01, the usage of DOCTYPE declaration was to create a reference to a document type definition (DTD), since the version HTML 4.01 was completely based on a Standard Generalized Markup Language(SGML).The document type definition (DTD) is responsible for specifying the rules for the Standard Generalized Markup Language(SGML) so that the browser processes the content correctly. But in the HTML version, HTML 5 there isn’t any need for a reference to a document type definition (DTD) because HTML 5 is not based on a Standard Generalized Markup Language(SGML)." }, { "code": null, "e": 33125, "s": 32963, "text": "In HTML 5, the DOCTYPE declaration is only required for enabling the standard mode for writing documents.Below is a sample HTML program with doctype declaration:" }, { "code": null, "e": 33134, "s": 33125, "text": "Example:" }, { "code": null, "e": 33139, "s": 33134, "text": "html" }, { "code": "<!DOCTYPE html><html> <body> <h1>GeeksforGeeks</h1> <h2>This is HTML5 Doctype Tag</h2></body> </html>", "e": 33249, "s": 33139, "text": null }, { "code": null, "e": 33259, "s": 33249, "text": "Output: " }, { "code": null, "e": 33355, "s": 33259, "text": "Below is the list of some common doctype declaration for different version of HTML and XHTML: " }, { "code": null, "e": 35077, "s": 33355, "text": "HTML 5 htmlhtml<!DOCTYPE html>HTML 4.01 Strict: In HTML 4.01 Strict document type definition (DTD) all those elements and attributes are included that do not appear in frameset documents or that have not been deprecated.htmlhtml<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.01//EN\" \"http://www.w3.org/TR/html4/strict.dtd\"> HTML 4.01 Transitional: In HTML 4.01 Transitional document type definition (DTD) allows some older PUBLIC and attributes that have been deprecated. htmlhtml<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.01 Transitional//EN\" \"http://www.w3.org/TR/html4/loose.dtd\">HTML 4.01 Frameset: In HTML 4.01 Frameset document type definition (DTD),Frames can be used.htmlhtml<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.01 Frameset//EN\" \"http://www.w3.org/TR/html4/frameset.dtd\">XHTML 1.0 Strict: In XHTML 1.0 Strict document type definition (DTD), deprecated tags are not supported and the code must be written according to the XML Specification.htmlhtml<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Strict//EN\" \"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd\">XHTML 1.0 Transitional: In XHTML 1.0 Transitional document type definition (DTD), deprecated elements are allowed.htmlhtml<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Transitional//EN\" \"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd\">XHTML 1.0 Frameset: In XHTML 1.0 Frameset document type definition (DTD), framesets can be used.htmlhtml<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Frameset//EN\" \"http://www.w3.org/TR/xhtml1/DTD/xhtml1-frameset.dtd\">XHTML 1.1: In XHTML 1.1 document type definition (DTD), allows the addition of modules.htmlhtml<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.1//EN\" \"http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd\">" }, { "code": null, "e": 35108, "s": 35077, "text": "HTML 5 htmlhtml<!DOCTYPE html>" }, { "code": null, "e": 35116, "s": 35108, "text": "HTML 5 " }, { "code": null, "e": 35121, "s": 35116, "text": "html" }, { "code": "<!DOCTYPE html>", "e": 35137, "s": 35121, "text": null }, { "code": null, "e": 35429, "s": 35137, "text": "HTML 4.01 Strict: In HTML 4.01 Strict document type definition (DTD) all those elements and attributes are included that do not appear in frameset documents or that have not been deprecated.htmlhtml<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.01//EN\" \"http://www.w3.org/TR/html4/strict.dtd\"> " }, { "code": null, "e": 35620, "s": 35429, "text": "HTML 4.01 Strict: In HTML 4.01 Strict document type definition (DTD) all those elements and attributes are included that do not appear in frameset documents or that have not been deprecated." }, { "code": null, "e": 35625, "s": 35620, "text": "html" }, { "code": "<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.01//EN\" \"http://www.w3.org/TR/html4/strict.dtd\">", "e": 35718, "s": 35625, "text": null }, { "code": null, "e": 35981, "s": 35720, "text": "HTML 4.01 Transitional: In HTML 4.01 Transitional document type definition (DTD) allows some older PUBLIC and attributes that have been deprecated. htmlhtml<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.01 Transitional//EN\" \"http://www.w3.org/TR/html4/loose.dtd\">" }, { "code": null, "e": 36130, "s": 35981, "text": "HTML 4.01 Transitional: In HTML 4.01 Transitional document type definition (DTD) allows some older PUBLIC and attributes that have been deprecated. " }, { "code": null, "e": 36135, "s": 36130, "text": "html" }, { "code": "<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.01 Transitional//EN\" \"http://www.w3.org/TR/html4/loose.dtd\">", "e": 36240, "s": 36135, "text": null }, { "code": null, "e": 36444, "s": 36240, "text": "HTML 4.01 Frameset: In HTML 4.01 Frameset document type definition (DTD),Frames can be used.htmlhtml<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.01 Frameset//EN\" \"http://www.w3.org/TR/html4/frameset.dtd\">" }, { "code": null, "e": 36537, "s": 36444, "text": "HTML 4.01 Frameset: In HTML 4.01 Frameset document type definition (DTD),Frames can be used." }, { "code": null, "e": 36542, "s": 36537, "text": "html" }, { "code": "<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.01 Frameset//EN\" \"http://www.w3.org/TR/html4/frameset.dtd\">", "e": 36646, "s": 36542, "text": null }, { "code": null, "e": 36932, "s": 36646, "text": "XHTML 1.0 Strict: In XHTML 1.0 Strict document type definition (DTD), deprecated tags are not supported and the code must be written according to the XML Specification.htmlhtml<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Strict//EN\" \"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd\">" }, { "code": null, "e": 37101, "s": 36932, "text": "XHTML 1.0 Strict: In XHTML 1.0 Strict document type definition (DTD), deprecated tags are not supported and the code must be written according to the XML Specification." }, { "code": null, "e": 37106, "s": 37101, "text": "html" }, { "code": "<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Strict//EN\" \"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd\">", "e": 37216, "s": 37106, "text": null }, { "code": null, "e": 37460, "s": 37216, "text": "XHTML 1.0 Transitional: In XHTML 1.0 Transitional document type definition (DTD), deprecated elements are allowed.htmlhtml<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Transitional//EN\" \"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd\">" }, { "code": null, "e": 37575, "s": 37460, "text": "XHTML 1.0 Transitional: In XHTML 1.0 Transitional document type definition (DTD), deprecated elements are allowed." }, { "code": null, "e": 37580, "s": 37575, "text": "html" }, { "code": "<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Transitional//EN\" \"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd\">", "e": 37702, "s": 37580, "text": null }, { "code": null, "e": 37920, "s": 37702, "text": "XHTML 1.0 Frameset: In XHTML 1.0 Frameset document type definition (DTD), framesets can be used.htmlhtml<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Frameset//EN\" \"http://www.w3.org/TR/xhtml1/DTD/xhtml1-frameset.dtd\">" }, { "code": null, "e": 38017, "s": 37920, "text": "XHTML 1.0 Frameset: In XHTML 1.0 Frameset document type definition (DTD), framesets can be used." }, { "code": null, "e": 38022, "s": 38017, "text": "html" }, { "code": "<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Frameset//EN\" \"http://www.w3.org/TR/xhtml1/DTD/xhtml1-frameset.dtd\">", "e": 38136, "s": 38022, "text": null }, { "code": null, "e": 38329, "s": 38136, "text": "XHTML 1.1: In XHTML 1.1 document type definition (DTD), allows the addition of modules.htmlhtml<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.1//EN\" \"http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd\">" }, { "code": null, "e": 38417, "s": 38329, "text": "XHTML 1.1: In XHTML 1.1 document type definition (DTD), allows the addition of modules." }, { "code": null, "e": 38422, "s": 38417, "text": "html" }, { "code": "<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.1//EN\" \"http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd\">", "e": 38520, "s": 38422, "text": null }, { "code": null, "e": 38541, "s": 38520, "text": "Supported Browsers: " }, { "code": null, "e": 38555, "s": 38541, "text": "Google Chrome" }, { "code": null, "e": 38573, "s": 38555, "text": "Internet Explorer" }, { "code": null, "e": 38581, "s": 38573, "text": "Firefox" }, { "code": null, "e": 38587, "s": 38581, "text": "Opera" }, { "code": null, "e": 38594, "s": 38587, "text": "Safari" }, { "code": null, "e": 38731, "s": 38594, "text": "Attention reader! Don’t stop learning now. Get hold of all the important HTML concepts with the Web Design for Beginners | HTML course." }, { "code": null, "e": 38742, "s": 38731, "text": "nidhi_biet" }, { "code": null, "e": 38756, "s": 38742, "text": "shubhamyadav4" }, { "code": null, "e": 38768, "s": 38756, "text": "HTML-Basics" }, { "code": null, "e": 38773, "s": 38768, "text": "HTML" }, { "code": null, "e": 38790, "s": 38773, "text": "Web Technologies" }, { "code": null, "e": 38795, "s": 38790, "text": "HTML" }, { "code": null, "e": 38893, "s": 38795, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 38943, "s": 38893, "text": "How to insert spaces/tabs in text using HTML/CSS?" }, { "code": null, "e": 39005, "s": 38943, "text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills" }, { "code": null, "e": 39053, "s": 39005, "text": "How to update Node.js and NPM to next version ?" }, { "code": null, "e": 39113, "s": 39053, "text": "How to set the default value for an HTML <select> element ?" }, { "code": null, "e": 39166, "s": 39113, "text": "Hide or show elements in HTML using display property" }, { "code": null, "e": 39206, "s": 39166, "text": "Remove elements from a JavaScript Array" }, { "code": null, "e": 39239, "s": 39206, "text": "Installation of Node.js on Linux" }, { "code": null, "e": 39284, "s": 39239, "text": "Convert a string to an integer in JavaScript" }, { "code": null, "e": 39327, "s": 39284, "text": "How to fetch data from an API in ReactJS ?" } ]
Plot 2-D Histogram in Python using Matplotlib - GeeksforGeeks
03 May, 2020 2D Histogram is used to analyze the relationship among two data variables which has wide range of values. A 2D histogram is very similar like 1D histogram. The class intervals of the data set are plotted on both x and y axis. Unlike 1D histogram, it drawn by including the total number of combinations of the values which occur in intervals of x and y, and marking the densities. It is useful when there is a large amount of data in a discrete distribution, and simplifies it by visualizing the points where the frequencies if variables are dense. Matplotlib library provides an inbuilt function matplotlib.pyplot.hist2d() which is used to create 2D histogram.Below is the syntax of the function: matplotlib.pyplot.hist2d(x, y, bins=(nx, ny), range=None, density=False, weights=None, cmin=None, cmax=None, cmap=value) Here (x, y) specify the coordinates of the data variables, the length of the X data and Y variables should be same.The number of bins can be specified by the attribute bins=(nx, ny) where nx and ny is the number of bins to be used in the horizontal and vertical directions respectively.cmap=value is used to set the color scale.The range=None is an optional parameter used to set rectangular area in which data values are counted for plot.density=value is optional parameter accepting boolean values used to normalize histogram.The code below code creates a simple 2D histogram using matplotlib.pyplot.hist2d() function having some random values of x and y: # Import librariesimport numpy as npimport matplotlib.pyplot as pltimport random # Creating datasetn = 100x = np.random.standard_normal(n)y = 3.0 * x fig = plt.subplots(figsize =(10, 7))# Creating plotplot.hist2d(x, y)plot.title("Simple 2D Histogram") # show plotplot.show() Output: The matplotlib.pyplot.hist2d() function has a wide range of methods which we can use to customize and create the plot for better view and understanding. # Import librariesimport numpy as npimport matplotlib.pyplot as pltimport random # Creating datasetx = np.random.normal(size = 500000)y = x * 3 + 4 * np.random.normal(size = 500000) fig = plt.subplots(figsize =(10, 7))# Creating plotplot.hist2d(x, y)plot.title("Simple 2D Histogram") # show plotplot.show() Output: # Import librariesimport numpy as npimport matplotlib.pyplot as pltimport random # Creating datasetx = np.random.normal(size = 500000)y = x * 3 + 4 * np.random.normal(size = 500000) # Creating binsx_min = np.min(x)x_max = np.max(x) y_min = np.min(y)y_max = np.max(y) x_bins = np.linspace(x_min, x_max, 50)y_bins = np.linspace(y_min, y_max, 20) fig, ax = plt.subplots(figsize =(10, 7))# Creating plotplt.hist2d(x, y, bins =[x_bins, y_bins])plt.title("Changing the bin scale") ax.set_xlabel('X-axis') ax.set_ylabel('X-axis') # show plotplt.tight_layout() plot.show() Output: # Import librariesimport numpy as npimport matplotlib.pyplot as pltimport random # Creating datasetx = np.random.normal(size = 500000)y = x * 3 + 4 * np.random.normal(size = 500000) # Creating binsx_min = np.min(x)x_max = np.max(x) y_min = np.min(y)y_max = np.max(y) x_bins = np.linspace(x_min, x_max, 50)y_bins = np.linspace(y_min, y_max, 20) fig, ax = plt.subplots(figsize =(10, 7))# Creating plotplt.hist2d(x, y, bins =[x_bins, y_bins], cmap = plt.cm.nipy_spectral)plt.title("Changing the color scale and adding color bar") # Adding color barplt.colorbar() ax.set_xlabel('X-axis') ax.set_ylabel('X-axis') # show plotplt.tight_layout() plot.show() Output: # Import librariesimport numpy as npimport matplotlib.pyplot as pltimport random # Creating datasetx = np.random.normal(size = 500000)y = x * 3 + 4 * np.random.normal(size = 500000) # Creating binsx_min = np.min(x)x_max = np.max(x) y_min = np.min(y)y_max = np.max(y) x_bins = np.linspace(x_min, x_max, 50)y_bins = np.linspace(y_min, y_max, 20) # Creating data filterdata = np.c_[x, y] for i in range(10000): x_idx = random.randint(0, 500000) data[x_idx, 0] = -9999 data = data[data[:, 0]!=-9999] fig, ax = plt.subplots(figsize =(10, 7))# Creating plotplt.hist2d(data[:, 0], data[:, 1], bins =[x_bins, y_bins])plt.title("Filtering data") ax.set_xlabel('X-axis') ax.set_ylabel('X-axis') # show plotplt.tight_layout() plot.show() Output: # Import librariesimport numpy as npimport matplotlib.pyplot as pltimport random # Creating datasetx = np.random.normal(size = 500000)y = x * 3 + 4 * np.random.normal(size = 500000) fig, ax = plt.subplots(figsize =(10, 7))# Creating plotplt.title("Using matplotlib hexbin function")plt.hexbin(x, y, bins = 50) ax.set_xlabel('X-axis') ax.set_ylabel('Y-axis') # show plotplt.tight_layout() plot.show() Output: Picked 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() *args and **kwargs in Python Reading and Writing to text files in Python Create a Pandas DataFrame from Lists
[ { "code": null, "e": 26125, "s": 26097, "text": "\n03 May, 2020" }, { "code": null, "e": 26673, "s": 26125, "text": "2D Histogram is used to analyze the relationship among two data variables which has wide range of values. A 2D histogram is very similar like 1D histogram. The class intervals of the data set are plotted on both x and y axis. Unlike 1D histogram, it drawn by including the total number of combinations of the values which occur in intervals of x and y, and marking the densities. It is useful when there is a large amount of data in a discrete distribution, and simplifies it by visualizing the points where the frequencies if variables are dense." }, { "code": null, "e": 26822, "s": 26673, "text": "Matplotlib library provides an inbuilt function matplotlib.pyplot.hist2d() which is used to create 2D histogram.Below is the syntax of the function:" }, { "code": null, "e": 26943, "s": 26822, "text": "matplotlib.pyplot.hist2d(x, y, bins=(nx, ny), range=None, density=False, weights=None, cmin=None, cmax=None, cmap=value)" }, { "code": null, "e": 27601, "s": 26943, "text": "Here (x, y) specify the coordinates of the data variables, the length of the X data and Y variables should be same.The number of bins can be specified by the attribute bins=(nx, ny) where nx and ny is the number of bins to be used in the horizontal and vertical directions respectively.cmap=value is used to set the color scale.The range=None is an optional parameter used to set rectangular area in which data values are counted for plot.density=value is optional parameter accepting boolean values used to normalize histogram.The code below code creates a simple 2D histogram using matplotlib.pyplot.hist2d() function having some random values of x and y:" }, { "code": "# Import librariesimport numpy as npimport matplotlib.pyplot as pltimport random # Creating datasetn = 100x = np.random.standard_normal(n)y = 3.0 * x fig = plt.subplots(figsize =(10, 7))# Creating plotplot.hist2d(x, y)plot.title(\"Simple 2D Histogram\") # show plotplot.show()", "e": 27880, "s": 27601, "text": null }, { "code": null, "e": 27888, "s": 27880, "text": "Output:" }, { "code": null, "e": 28041, "s": 27888, "text": "The matplotlib.pyplot.hist2d() function has a wide range of methods which we can use to customize and create the plot for better view and understanding." }, { "code": "# Import librariesimport numpy as npimport matplotlib.pyplot as pltimport random # Creating datasetx = np.random.normal(size = 500000)y = x * 3 + 4 * np.random.normal(size = 500000) fig = plt.subplots(figsize =(10, 7))# Creating plotplot.hist2d(x, y)plot.title(\"Simple 2D Histogram\") # show plotplot.show()", "e": 28351, "s": 28041, "text": null }, { "code": null, "e": 28359, "s": 28351, "text": "Output:" }, { "code": "# Import librariesimport numpy as npimport matplotlib.pyplot as pltimport random # Creating datasetx = np.random.normal(size = 500000)y = x * 3 + 4 * np.random.normal(size = 500000) # Creating binsx_min = np.min(x)x_max = np.max(x) y_min = np.min(y)y_max = np.max(y) x_bins = np.linspace(x_min, x_max, 50)y_bins = np.linspace(y_min, y_max, 20) fig, ax = plt.subplots(figsize =(10, 7))# Creating plotplt.hist2d(x, y, bins =[x_bins, y_bins])plt.title(\"Changing the bin scale\") ax.set_xlabel('X-axis') ax.set_ylabel('X-axis') # show plotplt.tight_layout() plot.show()", "e": 28932, "s": 28359, "text": null }, { "code": null, "e": 28940, "s": 28932, "text": "Output:" }, { "code": "# Import librariesimport numpy as npimport matplotlib.pyplot as pltimport random # Creating datasetx = np.random.normal(size = 500000)y = x * 3 + 4 * np.random.normal(size = 500000) # Creating binsx_min = np.min(x)x_max = np.max(x) y_min = np.min(y)y_max = np.max(y) x_bins = np.linspace(x_min, x_max, 50)y_bins = np.linspace(y_min, y_max, 20) fig, ax = plt.subplots(figsize =(10, 7))# Creating plotplt.hist2d(x, y, bins =[x_bins, y_bins], cmap = plt.cm.nipy_spectral)plt.title(\"Changing the color scale and adding color bar\") # Adding color barplt.colorbar() ax.set_xlabel('X-axis') ax.set_ylabel('X-axis') # show plotplt.tight_layout() plot.show()", "e": 29599, "s": 28940, "text": null }, { "code": null, "e": 29607, "s": 29599, "text": "Output:" }, { "code": "# Import librariesimport numpy as npimport matplotlib.pyplot as pltimport random # Creating datasetx = np.random.normal(size = 500000)y = x * 3 + 4 * np.random.normal(size = 500000) # Creating binsx_min = np.min(x)x_max = np.max(x) y_min = np.min(y)y_max = np.max(y) x_bins = np.linspace(x_min, x_max, 50)y_bins = np.linspace(y_min, y_max, 20) # Creating data filterdata = np.c_[x, y] for i in range(10000): x_idx = random.randint(0, 500000) data[x_idx, 0] = -9999 data = data[data[:, 0]!=-9999] fig, ax = plt.subplots(figsize =(10, 7))# Creating plotplt.hist2d(data[:, 0], data[:, 1], bins =[x_bins, y_bins])plt.title(\"Filtering data\") ax.set_xlabel('X-axis') ax.set_ylabel('X-axis') # show plotplt.tight_layout() plot.show()", "e": 30351, "s": 29607, "text": null }, { "code": null, "e": 30359, "s": 30351, "text": "Output:" }, { "code": "# Import librariesimport numpy as npimport matplotlib.pyplot as pltimport random # Creating datasetx = np.random.normal(size = 500000)y = x * 3 + 4 * np.random.normal(size = 500000) fig, ax = plt.subplots(figsize =(10, 7))# Creating plotplt.title(\"Using matplotlib hexbin function\")plt.hexbin(x, y, bins = 50) ax.set_xlabel('X-axis') ax.set_ylabel('Y-axis') # show plotplt.tight_layout() plot.show()", "e": 30764, "s": 30359, "text": null }, { "code": null, "e": 30772, "s": 30764, "text": "Output:" }, { "code": null, "e": 30779, "s": 30772, "text": "Picked" }, { "code": null, "e": 30797, "s": 30779, "text": "Python-matplotlib" }, { "code": null, "e": 30804, "s": 30797, "text": "Python" }, { "code": null, "e": 30902, "s": 30804, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 30920, "s": 30902, "text": "Python Dictionary" }, { "code": null, "e": 30955, "s": 30920, "text": "Read a file line by line in Python" }, { "code": null, "e": 30987, "s": 30955, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 31009, "s": 30987, "text": "Enumerate() in Python" }, { "code": null, "e": 31051, "s": 31009, "text": "Different ways to create Pandas Dataframe" }, { "code": null, "e": 31081, "s": 31051, "text": "Iterate over a list in Python" }, { "code": null, "e": 31107, "s": 31081, "text": "Python String | replace()" }, { "code": null, "e": 31136, "s": 31107, "text": "*args and **kwargs in Python" }, { "code": null, "e": 31180, "s": 31136, "text": "Reading and Writing to text files in Python" } ]
Scala | Reduce, fold or scan - GeeksforGeeks
29 Mar, 2019 In this tutorial we will learn about Reduce, Fold and Scan functions in Scala. Reduce : Reduce function is applied on collection data structure in scala that contains lists, sets, maps, sequence and tuples. Parameter in the reduce function is a binary operation which merges all the elements from the collection and returns a single value. The first two values is combined with the binary operation and the resultant of that operation combines with the next value of the collection and atlast we obtain a single value.This code implements the Sum of elements in a sequence using reduce function.Example :// Scala program sum of elements // using reduce function // Creating objectobject geeks{ // Main method def main(arg:Array[String]) { // initialize a sequence of elements val seq_elements: Seq[Double] = Seq(3.5, 5.0, 1.5) println(s"Elements = $seq_elements") // find the sum of the elements // using reduce function val sum: Double = seq_elements.reduce((a, b) => a + b) println(s"Sum of elements = $sum") } }Output:Elements = List(3.5, 5.0, 1.5) Sum of elements = 10.0 This code finds the maximum and minimum element in the sequence using reduce functionExample :// Scala program to find maximum and minimum // using reduce function // Creating objectobject geeks{ // Main method def main(arg:Array[String]) { // initialize a sequence of elements val seq_elements : Seq[Double] = Seq(3.5, 5.0, 1.5) println(s"Elements = $seq_elements") // find the maximum element using reduce function val maximum : Double = seq_elements.reduce(_ max _) println(s"Maximum element = $maximum") // find the minimum element using reduce function val minimum : Double = seq_elements.reduce(_ min _) println(s"Minimum element = $minimum") }}Output:Elements = List(3.5, 5.0, 1.5) Maximum element = 5.0 Minimum element = 1.5 Fold : Like reduce fold also takes a binary operation which merges all the elements from the collection and returns a single value. The difference is that fold allows us to define an initial value. Due to this property, fold can also manage empty collections. If the collection is empty, the value initialized becomes the final answer. Due to this we can also return a different value from the set of collection using initial value of some other datatype. Reduce can only return the value of the same type because its initial value is the first value from the collection.This code implements the Sum of elements in a sequence using fold function. Here initial value is taken as 0.0 as the sequence is in datatype Double.Example :// Scala program sum of elements // using fold function // Creating objectobject geeks{ // Main method def main(arg:Array[String]) { // initialize a sequence of elements val seq_elements: Seq[Double] = Seq(3.5, 5.0, 1.5) println(s"Elements = $seq_elements") // find the sum of the elements using fold function val sum: Double = seq_elements.fold(0.0)((a, b) => a + b) println(s"Sum of elements = $sum") }}Output:Elements = List(3.5, 5.0, 1.5) Sum of elements = 10.0 This code concatenate the strings with hyphen. We use initial value as empty string. So our fold method will apply the operator on empty string as well where as with reduce we would not get the hyphen before the first value of the collection.Example :// Scala program concatenate string // using fold function // Creating objectobject geeks{ // Main method def main(arg:Array[String]) { // initialize a sequence of strings val str_elements: Seq[String] = Seq("hello", "Geeks", "For", "Geeks") println(s"Elements = $str_elements") // Concatenate strings with fold function val concat: String = str_elements.fold("")( (a, b) => a + "-" + b) println(s"After concatenation = $concat") }} Output:Elements = List(hello, Geeks, For, Geeks) After concatenation = -hello-Geeks-For-Geeks Scan : Scan function takes the binary operation as parameter and returns the value for each element in collection for that operation. It returns each iteration for that binary operator in the collection. In scan also we can define the initial value.This code implements iterations of sum of all elements using scan function.Example :// Scala program sum of elements // using scan function // Creating objectobject geeks{ // Main method def main(arg:Array[String]) { //initialize a sequence of numbers val numbers: Seq[Int] = Seq(4, 2, 1, 6, 9) println(s"Elements of numbers = $numbers") //find the sum of the elements using scan function val iterations: Seq[Int] = numbers.scan(0)(_ + _) println("Running total of all elements" + s"in the collection = $iterations") }} Output:Elements of numbers = List(4, 2, 1, 6, 9) Running total of all elements in the collection = List(0, 4, 6, 7, 13, 22) This is the implementation of concatenation of the strings with hyphen and shows the iterations.Example :// Scala program concatenate string // using scan function // Creating objectobject geeks{ // Main method def main(arg:Array[String]) { // initialize a sequence of strings val str_elements : Seq[String] = Seq("hello", "Geeks", "For", "Geeks") println(s"Elements = $str_elements") // Concatenate strings with scan function val concat : Seq[String] = str_elements.scan("")((a, b) => a + "-" + b) println(s"After concatenation = $concat") }} Output:Elements = List(hello, Geeks, For, Geeks)After concatenation = List(, -hello, -hello-Geeks, -hello-Geeks-For, -hello-Geeks-For-Geeks) Reduce : Reduce function is applied on collection data structure in scala that contains lists, sets, maps, sequence and tuples. Parameter in the reduce function is a binary operation which merges all the elements from the collection and returns a single value. The first two values is combined with the binary operation and the resultant of that operation combines with the next value of the collection and atlast we obtain a single value.This code implements the Sum of elements in a sequence using reduce function.Example :// Scala program sum of elements // using reduce function // Creating objectobject geeks{ // Main method def main(arg:Array[String]) { // initialize a sequence of elements val seq_elements: Seq[Double] = Seq(3.5, 5.0, 1.5) println(s"Elements = $seq_elements") // find the sum of the elements // using reduce function val sum: Double = seq_elements.reduce((a, b) => a + b) println(s"Sum of elements = $sum") } }Output:Elements = List(3.5, 5.0, 1.5) Sum of elements = 10.0 This code finds the maximum and minimum element in the sequence using reduce functionExample :// Scala program to find maximum and minimum // using reduce function // Creating objectobject geeks{ // Main method def main(arg:Array[String]) { // initialize a sequence of elements val seq_elements : Seq[Double] = Seq(3.5, 5.0, 1.5) println(s"Elements = $seq_elements") // find the maximum element using reduce function val maximum : Double = seq_elements.reduce(_ max _) println(s"Maximum element = $maximum") // find the minimum element using reduce function val minimum : Double = seq_elements.reduce(_ min _) println(s"Minimum element = $minimum") }}Output:Elements = List(3.5, 5.0, 1.5) Maximum element = 5.0 Minimum element = 1.5 This code implements the Sum of elements in a sequence using reduce function.Example : // Scala program sum of elements // using reduce function // Creating objectobject geeks{ // Main method def main(arg:Array[String]) { // initialize a sequence of elements val seq_elements: Seq[Double] = Seq(3.5, 5.0, 1.5) println(s"Elements = $seq_elements") // find the sum of the elements // using reduce function val sum: Double = seq_elements.reduce((a, b) => a + b) println(s"Sum of elements = $sum") } } Output: Elements = List(3.5, 5.0, 1.5) Sum of elements = 10.0 This code finds the maximum and minimum element in the sequence using reduce functionExample : // Scala program to find maximum and minimum // using reduce function // Creating objectobject geeks{ // Main method def main(arg:Array[String]) { // initialize a sequence of elements val seq_elements : Seq[Double] = Seq(3.5, 5.0, 1.5) println(s"Elements = $seq_elements") // find the maximum element using reduce function val maximum : Double = seq_elements.reduce(_ max _) println(s"Maximum element = $maximum") // find the minimum element using reduce function val minimum : Double = seq_elements.reduce(_ min _) println(s"Minimum element = $minimum") }} Output: Elements = List(3.5, 5.0, 1.5) Maximum element = 5.0 Minimum element = 1.5 Fold : Like reduce fold also takes a binary operation which merges all the elements from the collection and returns a single value. The difference is that fold allows us to define an initial value. Due to this property, fold can also manage empty collections. If the collection is empty, the value initialized becomes the final answer. Due to this we can also return a different value from the set of collection using initial value of some other datatype. Reduce can only return the value of the same type because its initial value is the first value from the collection.This code implements the Sum of elements in a sequence using fold function. Here initial value is taken as 0.0 as the sequence is in datatype Double.Example :// Scala program sum of elements // using fold function // Creating objectobject geeks{ // Main method def main(arg:Array[String]) { // initialize a sequence of elements val seq_elements: Seq[Double] = Seq(3.5, 5.0, 1.5) println(s"Elements = $seq_elements") // find the sum of the elements using fold function val sum: Double = seq_elements.fold(0.0)((a, b) => a + b) println(s"Sum of elements = $sum") }}Output:Elements = List(3.5, 5.0, 1.5) Sum of elements = 10.0 This code concatenate the strings with hyphen. We use initial value as empty string. So our fold method will apply the operator on empty string as well where as with reduce we would not get the hyphen before the first value of the collection.Example :// Scala program concatenate string // using fold function // Creating objectobject geeks{ // Main method def main(arg:Array[String]) { // initialize a sequence of strings val str_elements: Seq[String] = Seq("hello", "Geeks", "For", "Geeks") println(s"Elements = $str_elements") // Concatenate strings with fold function val concat: String = str_elements.fold("")( (a, b) => a + "-" + b) println(s"After concatenation = $concat") }} Output:Elements = List(hello, Geeks, For, Geeks) After concatenation = -hello-Geeks-For-Geeks This code implements the Sum of elements in a sequence using fold function. Here initial value is taken as 0.0 as the sequence is in datatype Double.Example : // Scala program sum of elements // using fold function // Creating objectobject geeks{ // Main method def main(arg:Array[String]) { // initialize a sequence of elements val seq_elements: Seq[Double] = Seq(3.5, 5.0, 1.5) println(s"Elements = $seq_elements") // find the sum of the elements using fold function val sum: Double = seq_elements.fold(0.0)((a, b) => a + b) println(s"Sum of elements = $sum") }} Output: Elements = List(3.5, 5.0, 1.5) Sum of elements = 10.0 This code concatenate the strings with hyphen. We use initial value as empty string. So our fold method will apply the operator on empty string as well where as with reduce we would not get the hyphen before the first value of the collection.Example : // Scala program concatenate string // using fold function // Creating objectobject geeks{ // Main method def main(arg:Array[String]) { // initialize a sequence of strings val str_elements: Seq[String] = Seq("hello", "Geeks", "For", "Geeks") println(s"Elements = $str_elements") // Concatenate strings with fold function val concat: String = str_elements.fold("")( (a, b) => a + "-" + b) println(s"After concatenation = $concat") }} Output: Elements = List(hello, Geeks, For, Geeks) After concatenation = -hello-Geeks-For-Geeks Scan : Scan function takes the binary operation as parameter and returns the value for each element in collection for that operation. It returns each iteration for that binary operator in the collection. In scan also we can define the initial value.This code implements iterations of sum of all elements using scan function.Example :// Scala program sum of elements // using scan function // Creating objectobject geeks{ // Main method def main(arg:Array[String]) { //initialize a sequence of numbers val numbers: Seq[Int] = Seq(4, 2, 1, 6, 9) println(s"Elements of numbers = $numbers") //find the sum of the elements using scan function val iterations: Seq[Int] = numbers.scan(0)(_ + _) println("Running total of all elements" + s"in the collection = $iterations") }} Output:Elements of numbers = List(4, 2, 1, 6, 9) Running total of all elements in the collection = List(0, 4, 6, 7, 13, 22) This is the implementation of concatenation of the strings with hyphen and shows the iterations.Example :// Scala program concatenate string // using scan function // Creating objectobject geeks{ // Main method def main(arg:Array[String]) { // initialize a sequence of strings val str_elements : Seq[String] = Seq("hello", "Geeks", "For", "Geeks") println(s"Elements = $str_elements") // Concatenate strings with scan function val concat : Seq[String] = str_elements.scan("")((a, b) => a + "-" + b) println(s"After concatenation = $concat") }} Output:Elements = List(hello, Geeks, For, Geeks)After concatenation = List(, -hello, -hello-Geeks, -hello-Geeks-For, -hello-Geeks-For-Geeks) This code implements iterations of sum of all elements using scan function.Example : // Scala program sum of elements // using scan function // Creating objectobject geeks{ // Main method def main(arg:Array[String]) { //initialize a sequence of numbers val numbers: Seq[Int] = Seq(4, 2, 1, 6, 9) println(s"Elements of numbers = $numbers") //find the sum of the elements using scan function val iterations: Seq[Int] = numbers.scan(0)(_ + _) println("Running total of all elements" + s"in the collection = $iterations") }} Output: Elements of numbers = List(4, 2, 1, 6, 9) Running total of all elements in the collection = List(0, 4, 6, 7, 13, 22) This is the implementation of concatenation of the strings with hyphen and shows the iterations.Example : // Scala program concatenate string // using scan function // Creating objectobject geeks{ // Main method def main(arg:Array[String]) { // initialize a sequence of strings val str_elements : Seq[String] = Seq("hello", "Geeks", "For", "Geeks") println(s"Elements = $str_elements") // Concatenate strings with scan function val concat : Seq[String] = str_elements.scan("")((a, b) => a + "-" + b) println(s"After concatenation = $concat") }} Output: Elements = List(hello, Geeks, For, Geeks)After concatenation = List(, -hello, -hello-Geeks, -hello-Geeks-For, -hello-Geeks-For-Geeks) Picked Scala Scala-Method Scala Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Class and Object in Scala Scala Lists Scala Tutorial – Learn Scala with Step By Step Guide Operators in Scala Scala Constructors Inheritance in Scala Scala | Arrays How to get the first element of List in Scala Scala String replace() method with example Break statement in Scala
[ { "code": null, "e": 25152, "s": 25124, "text": "\n29 Mar, 2019" }, { "code": null, "e": 25231, "s": 25152, "text": "In this tutorial we will learn about Reduce, Fold and Scan functions in Scala." }, { "code": null, "e": 31024, "s": 25231, "text": "Reduce : Reduce function is applied on collection data structure in scala that contains lists, sets, maps, sequence and tuples. Parameter in the reduce function is a binary operation which merges all the elements from the collection and returns a single value. The first two values is combined with the binary operation and the resultant of that operation combines with the next value of the collection and atlast we obtain a single value.This code implements the Sum of elements in a sequence using reduce function.Example :// Scala program sum of elements // using reduce function // Creating objectobject geeks{ // Main method def main(arg:Array[String]) { // initialize a sequence of elements val seq_elements: Seq[Double] = Seq(3.5, 5.0, 1.5) println(s\"Elements = $seq_elements\") // find the sum of the elements // using reduce function val sum: Double = seq_elements.reduce((a, b) => a + b) println(s\"Sum of elements = $sum\") } }Output:Elements = List(3.5, 5.0, 1.5)\nSum of elements = 10.0\nThis code finds the maximum and minimum element in the sequence using reduce functionExample :// Scala program to find maximum and minimum // using reduce function // Creating objectobject geeks{ // Main method def main(arg:Array[String]) { // initialize a sequence of elements val seq_elements : Seq[Double] = Seq(3.5, 5.0, 1.5) println(s\"Elements = $seq_elements\") // find the maximum element using reduce function val maximum : Double = seq_elements.reduce(_ max _) println(s\"Maximum element = $maximum\") // find the minimum element using reduce function val minimum : Double = seq_elements.reduce(_ min _) println(s\"Minimum element = $minimum\") }}Output:Elements = List(3.5, 5.0, 1.5)\nMaximum element = 5.0\nMinimum element = 1.5\nFold : Like reduce fold also takes a binary operation which merges all the elements from the collection and returns a single value. The difference is that fold allows us to define an initial value. Due to this property, fold can also manage empty collections. If the collection is empty, the value initialized becomes the final answer. Due to this we can also return a different value from the set of collection using initial value of some other datatype. Reduce can only return the value of the same type because its initial value is the first value from the collection.This code implements the Sum of elements in a sequence using fold function. Here initial value is taken as 0.0 as the sequence is in datatype Double.Example :// Scala program sum of elements // using fold function // Creating objectobject geeks{ // Main method def main(arg:Array[String]) { // initialize a sequence of elements val seq_elements: Seq[Double] = Seq(3.5, 5.0, 1.5) println(s\"Elements = $seq_elements\") // find the sum of the elements using fold function val sum: Double = seq_elements.fold(0.0)((a, b) => a + b) println(s\"Sum of elements = $sum\") }}Output:Elements = List(3.5, 5.0, 1.5)\nSum of elements = 10.0\nThis code concatenate the strings with hyphen. We use initial value as empty string. So our fold method will apply the operator on empty string as well where as with reduce we would not get the hyphen before the first value of the collection.Example :// Scala program concatenate string // using fold function // Creating objectobject geeks{ // Main method def main(arg:Array[String]) { // initialize a sequence of strings val str_elements: Seq[String] = Seq(\"hello\", \"Geeks\", \"For\", \"Geeks\") println(s\"Elements = $str_elements\") // Concatenate strings with fold function val concat: String = str_elements.fold(\"\")( (a, b) => a + \"-\" + b) println(s\"After concatenation = $concat\") }} Output:Elements = List(hello, Geeks, For, Geeks)\nAfter concatenation = -hello-Geeks-For-Geeks\nScan : Scan function takes the binary operation as parameter and returns the value for each element in collection for that operation. It returns each iteration for that binary operator in the collection. In scan also we can define the initial value.This code implements iterations of sum of all elements using scan function.Example :// Scala program sum of elements // using scan function // Creating objectobject geeks{ // Main method def main(arg:Array[String]) { //initialize a sequence of numbers val numbers: Seq[Int] = Seq(4, 2, 1, 6, 9) println(s\"Elements of numbers = $numbers\") //find the sum of the elements using scan function val iterations: Seq[Int] = numbers.scan(0)(_ + _) println(\"Running total of all elements\" + s\"in the collection = $iterations\") }} Output:Elements of numbers = List(4, 2, 1, 6, 9)\nRunning total of all elements in the collection = List(0, 4, 6, 7, 13, 22)\nThis is the implementation of concatenation of the strings with hyphen and shows the iterations.Example :// Scala program concatenate string // using scan function // Creating objectobject geeks{ // Main method def main(arg:Array[String]) { // initialize a sequence of strings val str_elements : Seq[String] = Seq(\"hello\", \"Geeks\", \"For\", \"Geeks\") println(s\"Elements = $str_elements\") // Concatenate strings with scan function val concat : Seq[String] = str_elements.scan(\"\")((a, b) => a + \"-\" + b) println(s\"After concatenation = $concat\") }} Output:Elements = List(hello, Geeks, For, Geeks)After concatenation = List(, -hello, -hello-Geeks, -hello-Geeks-For, -hello-Geeks-For-Geeks)" }, { "code": null, "e": 32904, "s": 31024, "text": "Reduce : Reduce function is applied on collection data structure in scala that contains lists, sets, maps, sequence and tuples. Parameter in the reduce function is a binary operation which merges all the elements from the collection and returns a single value. The first two values is combined with the binary operation and the resultant of that operation combines with the next value of the collection and atlast we obtain a single value.This code implements the Sum of elements in a sequence using reduce function.Example :// Scala program sum of elements // using reduce function // Creating objectobject geeks{ // Main method def main(arg:Array[String]) { // initialize a sequence of elements val seq_elements: Seq[Double] = Seq(3.5, 5.0, 1.5) println(s\"Elements = $seq_elements\") // find the sum of the elements // using reduce function val sum: Double = seq_elements.reduce((a, b) => a + b) println(s\"Sum of elements = $sum\") } }Output:Elements = List(3.5, 5.0, 1.5)\nSum of elements = 10.0\nThis code finds the maximum and minimum element in the sequence using reduce functionExample :// Scala program to find maximum and minimum // using reduce function // Creating objectobject geeks{ // Main method def main(arg:Array[String]) { // initialize a sequence of elements val seq_elements : Seq[Double] = Seq(3.5, 5.0, 1.5) println(s\"Elements = $seq_elements\") // find the maximum element using reduce function val maximum : Double = seq_elements.reduce(_ max _) println(s\"Maximum element = $maximum\") // find the minimum element using reduce function val minimum : Double = seq_elements.reduce(_ min _) println(s\"Minimum element = $minimum\") }}Output:Elements = List(3.5, 5.0, 1.5)\nMaximum element = 5.0\nMinimum element = 1.5\n" }, { "code": null, "e": 32991, "s": 32904, "text": "This code implements the Sum of elements in a sequence using reduce function.Example :" }, { "code": "// Scala program sum of elements // using reduce function // Creating objectobject geeks{ // Main method def main(arg:Array[String]) { // initialize a sequence of elements val seq_elements: Seq[Double] = Seq(3.5, 5.0, 1.5) println(s\"Elements = $seq_elements\") // find the sum of the elements // using reduce function val sum: Double = seq_elements.reduce((a, b) => a + b) println(s\"Sum of elements = $sum\") } }", "e": 33470, "s": 32991, "text": null }, { "code": null, "e": 33478, "s": 33470, "text": "Output:" }, { "code": null, "e": 33534, "s": 33478, "text": "Elements = List(3.5, 5.0, 1.5)\nSum of elements = 10.0\n" }, { "code": null, "e": 33629, "s": 33534, "text": "This code finds the maximum and minimum element in the sequence using reduce functionExample :" }, { "code": "// Scala program to find maximum and minimum // using reduce function // Creating objectobject geeks{ // Main method def main(arg:Array[String]) { // initialize a sequence of elements val seq_elements : Seq[Double] = Seq(3.5, 5.0, 1.5) println(s\"Elements = $seq_elements\") // find the maximum element using reduce function val maximum : Double = seq_elements.reduce(_ max _) println(s\"Maximum element = $maximum\") // find the minimum element using reduce function val minimum : Double = seq_elements.reduce(_ min _) println(s\"Minimum element = $minimum\") }}", "e": 34268, "s": 33629, "text": null }, { "code": null, "e": 34276, "s": 34268, "text": "Output:" }, { "code": null, "e": 34352, "s": 34276, "text": "Elements = List(3.5, 5.0, 1.5)\nMaximum element = 5.0\nMinimum element = 1.5\n" }, { "code": null, "e": 36505, "s": 34352, "text": "Fold : Like reduce fold also takes a binary operation which merges all the elements from the collection and returns a single value. The difference is that fold allows us to define an initial value. Due to this property, fold can also manage empty collections. If the collection is empty, the value initialized becomes the final answer. Due to this we can also return a different value from the set of collection using initial value of some other datatype. Reduce can only return the value of the same type because its initial value is the first value from the collection.This code implements the Sum of elements in a sequence using fold function. Here initial value is taken as 0.0 as the sequence is in datatype Double.Example :// Scala program sum of elements // using fold function // Creating objectobject geeks{ // Main method def main(arg:Array[String]) { // initialize a sequence of elements val seq_elements: Seq[Double] = Seq(3.5, 5.0, 1.5) println(s\"Elements = $seq_elements\") // find the sum of the elements using fold function val sum: Double = seq_elements.fold(0.0)((a, b) => a + b) println(s\"Sum of elements = $sum\") }}Output:Elements = List(3.5, 5.0, 1.5)\nSum of elements = 10.0\nThis code concatenate the strings with hyphen. We use initial value as empty string. So our fold method will apply the operator on empty string as well where as with reduce we would not get the hyphen before the first value of the collection.Example :// Scala program concatenate string // using fold function // Creating objectobject geeks{ // Main method def main(arg:Array[String]) { // initialize a sequence of strings val str_elements: Seq[String] = Seq(\"hello\", \"Geeks\", \"For\", \"Geeks\") println(s\"Elements = $str_elements\") // Concatenate strings with fold function val concat: String = str_elements.fold(\"\")( (a, b) => a + \"-\" + b) println(s\"After concatenation = $concat\") }} Output:Elements = List(hello, Geeks, For, Geeks)\nAfter concatenation = -hello-Geeks-For-Geeks\n" }, { "code": null, "e": 36664, "s": 36505, "text": "This code implements the Sum of elements in a sequence using fold function. Here initial value is taken as 0.0 as the sequence is in datatype Double.Example :" }, { "code": "// Scala program sum of elements // using fold function // Creating objectobject geeks{ // Main method def main(arg:Array[String]) { // initialize a sequence of elements val seq_elements: Seq[Double] = Seq(3.5, 5.0, 1.5) println(s\"Elements = $seq_elements\") // find the sum of the elements using fold function val sum: Double = seq_elements.fold(0.0)((a, b) => a + b) println(s\"Sum of elements = $sum\") }}", "e": 37129, "s": 36664, "text": null }, { "code": null, "e": 37137, "s": 37129, "text": "Output:" }, { "code": null, "e": 37192, "s": 37137, "text": "Elements = List(3.5, 5.0, 1.5)\nSum of elements = 10.0\n" }, { "code": null, "e": 37444, "s": 37192, "text": "This code concatenate the strings with hyphen. We use initial value as empty string. So our fold method will apply the operator on empty string as well where as with reduce we would not get the hyphen before the first value of the collection.Example :" }, { "code": "// Scala program concatenate string // using fold function // Creating objectobject geeks{ // Main method def main(arg:Array[String]) { // initialize a sequence of strings val str_elements: Seq[String] = Seq(\"hello\", \"Geeks\", \"For\", \"Geeks\") println(s\"Elements = $str_elements\") // Concatenate strings with fold function val concat: String = str_elements.fold(\"\")( (a, b) => a + \"-\" + b) println(s\"After concatenation = $concat\") }} ", "e": 37998, "s": 37444, "text": null }, { "code": null, "e": 38006, "s": 37998, "text": "Output:" }, { "code": null, "e": 38094, "s": 38006, "text": "Elements = List(hello, Geeks, For, Geeks)\nAfter concatenation = -hello-Geeks-For-Geeks\n" }, { "code": null, "e": 39856, "s": 38094, "text": "Scan : Scan function takes the binary operation as parameter and returns the value for each element in collection for that operation. It returns each iteration for that binary operator in the collection. In scan also we can define the initial value.This code implements iterations of sum of all elements using scan function.Example :// Scala program sum of elements // using scan function // Creating objectobject geeks{ // Main method def main(arg:Array[String]) { //initialize a sequence of numbers val numbers: Seq[Int] = Seq(4, 2, 1, 6, 9) println(s\"Elements of numbers = $numbers\") //find the sum of the elements using scan function val iterations: Seq[Int] = numbers.scan(0)(_ + _) println(\"Running total of all elements\" + s\"in the collection = $iterations\") }} Output:Elements of numbers = List(4, 2, 1, 6, 9)\nRunning total of all elements in the collection = List(0, 4, 6, 7, 13, 22)\nThis is the implementation of concatenation of the strings with hyphen and shows the iterations.Example :// Scala program concatenate string // using scan function // Creating objectobject geeks{ // Main method def main(arg:Array[String]) { // initialize a sequence of strings val str_elements : Seq[String] = Seq(\"hello\", \"Geeks\", \"For\", \"Geeks\") println(s\"Elements = $str_elements\") // Concatenate strings with scan function val concat : Seq[String] = str_elements.scan(\"\")((a, b) => a + \"-\" + b) println(s\"After concatenation = $concat\") }} Output:Elements = List(hello, Geeks, For, Geeks)After concatenation = List(, -hello, -hello-Geeks, -hello-Geeks-For, -hello-Geeks-For-Geeks)" }, { "code": null, "e": 39941, "s": 39856, "text": "This code implements iterations of sum of all elements using scan function.Example :" }, { "code": "// Scala program sum of elements // using scan function // Creating objectobject geeks{ // Main method def main(arg:Array[String]) { //initialize a sequence of numbers val numbers: Seq[Int] = Seq(4, 2, 1, 6, 9) println(s\"Elements of numbers = $numbers\") //find the sum of the elements using scan function val iterations: Seq[Int] = numbers.scan(0)(_ + _) println(\"Running total of all elements\" + s\"in the collection = $iterations\") }} ", "e": 40454, "s": 39941, "text": null }, { "code": null, "e": 40462, "s": 40454, "text": "Output:" }, { "code": null, "e": 40580, "s": 40462, "text": "Elements of numbers = List(4, 2, 1, 6, 9)\nRunning total of all elements in the collection = List(0, 4, 6, 7, 13, 22)\n" }, { "code": null, "e": 40686, "s": 40580, "text": "This is the implementation of concatenation of the strings with hyphen and shows the iterations.Example :" }, { "code": "// Scala program concatenate string // using scan function // Creating objectobject geeks{ // Main method def main(arg:Array[String]) { // initialize a sequence of strings val str_elements : Seq[String] = Seq(\"hello\", \"Geeks\", \"For\", \"Geeks\") println(s\"Elements = $str_elements\") // Concatenate strings with scan function val concat : Seq[String] = str_elements.scan(\"\")((a, b) => a + \"-\" + b) println(s\"After concatenation = $concat\") }} ", "e": 41234, "s": 40686, "text": null }, { "code": null, "e": 41242, "s": 41234, "text": "Output:" }, { "code": null, "e": 41376, "s": 41242, "text": "Elements = List(hello, Geeks, For, Geeks)After concatenation = List(, -hello, -hello-Geeks, -hello-Geeks-For, -hello-Geeks-For-Geeks)" }, { "code": null, "e": 41383, "s": 41376, "text": "Picked" }, { "code": null, "e": 41389, "s": 41383, "text": "Scala" }, { "code": null, "e": 41402, "s": 41389, "text": "Scala-Method" }, { "code": null, "e": 41408, "s": 41402, "text": "Scala" }, { "code": null, "e": 41506, "s": 41408, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 41532, "s": 41506, "text": "Class and Object in Scala" }, { "code": null, "e": 41544, "s": 41532, "text": "Scala Lists" }, { "code": null, "e": 41597, "s": 41544, "text": "Scala Tutorial – Learn Scala with Step By Step Guide" }, { "code": null, "e": 41616, "s": 41597, "text": "Operators in Scala" }, { "code": null, "e": 41635, "s": 41616, "text": "Scala Constructors" }, { "code": null, "e": 41656, "s": 41635, "text": "Inheritance in Scala" }, { "code": null, "e": 41671, "s": 41656, "text": "Scala | Arrays" }, { "code": null, "e": 41717, "s": 41671, "text": "How to get the first element of List in Scala" }, { "code": null, "e": 41760, "s": 41717, "text": "Scala String replace() method with example" } ]
Detect loop in a linked list - GeeksforGeeks
12 Apr, 2022 Given a linked list, check if the linked list has loop or not. Below diagram shows a linked list with a loop. The following are different ways of doing this. Solution 1: Hashing Approach: Traverse the list one by one and keep putting the node addresses in a Hash Table. At any point, if NULL is reached then return false, and if the next of the current nodes points to any of the previously stored nodes in Hash then return true. C++ Java Python3 C# Javascript // C++ program to detect loop in a linked list#include <bits/stdc++.h>using namespace std; /* Link list node */struct Node { int data; struct Node* next;}; void push(struct Node** head_ref, int new_data){ /* allocate node */ struct Node* new_node = new Node; /* put in the data */ new_node->data = new_data; /* link the old list off the new node */ new_node->next = (*head_ref); /* move the head to point to the new node */ (*head_ref) = new_node;} // Returns true if there is a loop in linked list// else returns false.bool detectLoop(struct Node* h){ unordered_set<Node*> s; while (h != NULL) { // If this node is already present // in hashmap it means there is a cycle // (Because you will be encountering the // node for the second time). if (s.find(h) != s.end()) return true; // If we are seeing the node for // the first time, insert it in hash s.insert(h); h = h->next; } return false;} /* Driver program to test above function*/int main(){ /* Start with the empty list */ struct Node* head = NULL; push(&head, 20); push(&head, 4); push(&head, 15); push(&head, 10); /* Create a loop for testing */ head->next->next->next->next = head; if (detectLoop(head)) cout << "Loop found"; else cout << "No Loop"; return 0;}// This code is contributed by Geetanjali // Java program to detect loop in a linked listimport java.util.*; public class LinkedList { static Node head; // head of list /* Linked list Node*/ static class Node { int data; Node next; Node(int d) { data = d; next = null; } } /* Inserts a new Node at front of the list. */ static public void push(int new_data) { /* 1 & 2: Allocate the Node & Put in the data*/ Node new_node = new Node(new_data); /* 3. Make next of new Node as head */ new_node.next = head; /* 4. Move the head to point to new Node */ head = new_node; } // Returns true if there is a loop in linked // list else returns false. static boolean detectLoop(Node h) { HashSet<Node> s = new HashSet<Node>(); while (h != null) { // If we have already has this node // in hashmap it means their is a cycle // (Because you we encountering the // node second time). if (s.contains(h)) return true; // If we are seeing the node for // the first time, insert it in hash s.add(h); h = h.next; } return false; } /* Driver program to test above function */ public static void main(String[] args) { LinkedList llist = new LinkedList(); llist.push(20); llist.push(4); llist.push(15); llist.push(10); /*Create loop for testing */ llist.head.next.next.next.next = llist.head; if (detectLoop(head)) System.out.println("Loop found"); else System.out.println("No Loop"); }} // This code is contributed by Arnav Kr. Mandal. # Python3 program to detect loop# in the linked list # Node class class Node: # Constructor to initialize # the node object def __init__(self, data): self.data = data self.next = None class LinkedList: # Function to initialize head def __init__(self): self.head = None # Function to insert a new # node at the beginning def push(self, new_data): new_node = Node(new_data) new_node.next = self.head self.head = new_node # Utility function to print it # the linked LinkedList def printList(self): temp = self.head while(temp): print(temp.data, end=" ") temp = temp.next def detectLoop(self): s = set() temp = self.head while (temp): # If we have already has # this node in hashmap it # means their is a cycle # (Because you we encountering # the node second time). if (temp in s): return True # If we are seeing the node for # the first time, insert it in hash s.add(temp) temp = temp.next return False # Driver program for testingllist = LinkedList()llist.push(20)llist.push(4)llist.push(15)llist.push(10) # Create a loop for testingllist.head.next.next.next.next = llist.head if(llist.detectLoop()): print("Loop found")else: print("No Loop ") # This code is contributed by Gitanjali. // C# program to detect loop in a linked listusing System;using System.Collections.Generic; class LinkedList { // head of list public Node head; /* Linked list Node*/ public class Node { public int data; public Node next; public Node(int d) { data = d; next = null; } } /* Inserts a new Node at front of the list. */ public void push(int new_data) { /* 1 & 2: Allocate the Node & Put in the data*/ Node new_node = new Node(new_data); /* 3. Make next of new Node as head */ new_node.next = head; /* 4. Move the head to point to new Node */ head = new_node; } // Returns true if there is a loop in linked // list else returns false. public static bool detectLoop(Node h) { HashSet<Node> s = new HashSet<Node>(); while (h != null) { // If we have already has this node // in hashmap it means their is a cycle // (Because you we encountering the // node second time). if (s.Contains(h)) return true; // If we are seeing the node for // the first time, insert it in hash s.Add(h); h = h.next; } return false; } /* Driver code*/ public static void Main(String[] args) { LinkedList llist = new LinkedList(); llist.push(20); llist.push(4); llist.push(15); llist.push(10); /*Create loop for testing */ llist.head.next.next.next.next = llist.head; if (detectLoop(llist.head)) Console.WriteLine("Loop found"); else Console.WriteLine("No Loop"); }} // This code has been contributed by 29AjayKumar <script> // JavaScript program to detect loop in a linked list var head; // head of list /* Linked list Node */ class Node { constructor(val) { this.data = val; this.next = null; } } /* Inserts a new Node at front of the list. */ function push(new_data) { /* * 1 & 2: Allocate the Node & Put in the data */var new_node = new Node(new_data); /* 3. Make next of new Node as head */ new_node.next = head; /* 4. Move the head to point to new Node */ head = new_node; } // Returns true if there is a loop in linked // list else returns false. function detectLoop(h) { var s = new Set(); while (h != null) { // If we have already has this node // in hashmap it means their is a cycle // (Because you we encountering the // node second time). if (s.has(h)) return true; // If we are seeing the node for // the first time, insert it in hash s.add(h); h = h.next; } return false; } /* Driver program to test above function */ push(20); push(4); push(15); push(10); /* Create loop for testing */ head.next.next.next.next = head; if (detectLoop(head)) document.write("Loop found"); else document.write("No Loop"); // This code is contributed by todaysgaurav </script> Loop found Complexity Analysis: Time complexity: O(n). Only one traversal of the loop is needed. Auxiliary Space: O(n). n is the space required to store the value in hashmap. Solution 2: This problem can be solved without hashmap by modifying the linked list data structure. Approach: This solution requires modifications to the basic linked list data structure. Have a visited flag with each node. Traverse the linked list and keep marking visited nodes. If you see a visited node again then there is a loop. This solution works in O(n) but requires additional information with each node. A variation of this solution that doesn’t require modification to basic data structure can be implemented using a hash, just store the addresses of visited nodes in a hash and if you see an address that already exists in hash then there is a loop. C++ C Java Python3 C# Javascript // C++ program to detect loop in a linked list#include <bits/stdc++.h>using namespace std; /* Link list node */struct Node { int data; struct Node* next; int flag;}; void push(struct Node** head_ref, int new_data){ /* allocate node */ struct Node* new_node = new Node; /* put in the data */ new_node->data = new_data; new_node->flag = 0; /* link the old list off the new node */ new_node->next = (*head_ref); /* move the head to point to the new node */ (*head_ref) = new_node;} // Returns true if there is a loop in linked list// else returns false.bool detectLoop(struct Node* h){ while (h != NULL) { // If this node is already traverse // it means there is a cycle // (Because you we encountering the // node for the second time). if (h->flag == 1) return true; // If we are seeing the node for // the first time, mark its flag as 1 h->flag = 1; h = h->next; } return false;} /* Driver program to test above function*/int main(){ /* Start with the empty list */ struct Node* head = NULL; push(&head, 20); push(&head, 4); push(&head, 15); push(&head, 10); /* Create a loop for testing */ head->next->next->next->next = head; if (detectLoop(head)) cout << "Loop found"; else cout << "No Loop"; return 0;}// This code is contributed by Geetanjali // C program to detect loop in a linked list#include <stdbool.h>#include <stdio.h>#include <stdlib.h> /* Link list node */typedef struct Node { int data; struct Node* next; int flag;} Node; void push(struct Node** head_ref, int new_data){ /* allocate node */ struct Node* new_node = (Node*)malloc(sizeof(Node)); /* put in the data */ new_node->data = new_data; new_node->flag = 0; /* link the old list off the new node */ new_node->next = (*head_ref); /* move the head to point to the new node */ (*head_ref) = new_node;} // Returns true if there is a loop in linked list// else returns false.bool detectLoop(struct Node* h){ while (h != NULL) { // If this node is already traverse // it means there is a cycle // (Because you we encountering the // node for the second time). if (h->flag == 1) return true; // If we are seeing the node for // the first time, mark its flag as 1 h->flag = 1; h = h->next; } return false;} /* Driver program to test above function*/int main(){ /* Start with the empty list */ struct Node* head = NULL; push(&head, 20); push(&head, 4); push(&head, 15); push(&head, 10); /* Create a loop for testing */ head->next->next->next->next = head; if (detectLoop(head)) printf("Loop found"); else printf("No Loop"); return 0;} // This code is contributed by Aditya Kumar (adityakumar129) // Java program to detect loop in a linked listimport java.util.*; class GFG{ // Link list nodestatic class Node{ int data; Node next; int flag;}; static Node push(Node head_ref, int new_data){ // Allocate node Node new_node = new Node(); // Put in the data new_node.data = new_data; new_node.flag = 0; // Link the old list off the new node new_node.next = head_ref; // Move the head to point to the new node head_ref = new_node; return head_ref;} // Returns true if there is a loop in linked// list else returns false.static boolean detectLoop(Node h){ while (h != null) { // If this node is already traverse // it means there is a cycle // (Because you we encountering the // node for the second time). if (h.flag == 1) return true; // If we are seeing the node for // the first time, mark its flag as 1 h.flag = 1; h = h.next; } return false;} // Driver codepublic static void main(String[] args){ // Start with the empty list Node head = null; head = push(head, 20); head = push(head, 4); head = push(head, 15); head = push(head, 10); // Create a loop for testing head.next.next.next.next = head; if (detectLoop(head)) System.out.print("Loop found"); else System.out.print("No Loop");}} // This code is contributed by Rajput-Ji # Python3 program to detect loop in a linked list ''' Link list node '''class Node: def __init__(self): self.data = 0 self.next = None self.flag = 0 def push(head_ref, new_data): ''' allocate node ''' new_node = Node(); ''' put in the data ''' new_node.data = new_data; new_node.flag = 0; ''' link the old list off the new node ''' new_node.next = (head_ref); ''' move the head to point to the new node ''' (head_ref) = new_node; return head_ref # Returns true if there is a loop in linked list# else returns false.def detectLoop(h): while (h != None): # If this node is already traverse # it means there is a cycle # (Because you we encountering the # node for the second time). if (h.flag == 1): return True; # If we are seeing the node for # the first time, mark its flag as 1 h.flag = 1; h = h.next; return False; ''' Driver program to test above function'''if __name__=='__main__': ''' Start with the empty list ''' head = None; head = push(head, 20); head = push(head, 4); head = push(head, 15); head = push( head, 10) ''' Create a loop for testing ''' head.next.next.next.next = head; if (detectLoop(head)): print("Loop found") else: print("No Loop") # This code is contributed by rutvik_56 // C# program to detect loop in a linked listusing System; class GFG{ // Link list nodeclass Node{ public int data; public Node next; public int flag;}; static Node push(Node head_ref, int new_data){ // Allocate node Node new_node = new Node(); // Put in the data new_node.data = new_data; new_node.flag = 0; // Link the old list off the new node new_node.next = head_ref; // Move the head to point to the new node head_ref = new_node; return head_ref;} // Returns true if there is a loop in linked// list else returns false.static bool detectLoop(Node h){ while (h != null) { // If this node is already traverse // it means there is a cycle // (Because you we encountering the // node for the second time). if (h.flag == 1) return true; // If we are seeing the node for // the first time, mark its flag as 1 h.flag = 1; h = h.next; } return false;} // Driver codepublic static void Main(string[] args){ // Start with the empty list Node head = null; head = push(head, 20); head = push(head, 4); head = push(head, 15); head = push(head, 10); // Create a loop for testing head.next.next.next.next = head; if (detectLoop(head)) Console.Write("Loop found"); else Console.Write("No Loop");}} // This code is contributed by pratham76 <script> // JavaScript program to detect loop in a linked list // Link list nodeclass Node{ constructor() { let data; let next; let flag; }} function push( head_ref, new_data){ // Allocate node let new_node = new Node(); // Put in the data new_node.data = new_data; new_node.flag = 0; // Link the old list off the new node new_node.next = head_ref; // Move the head to point to the new node head_ref = new_node; return head_ref;} // Returns true if there is a loop in linked// list else returns false. function detectLoop(h){ while (h != null) { // If this node is already traverse // it means there is a cycle // (Because you we encountering the // node for the second time). if (h.flag == 1) return true; // If we are seeing the node for // the first time, mark its flag as 1 h.flag = 1; h = h.next; } return false;} // Driver code // Start with the empty list let head = null; head = push(head, 20); head = push(head, 4); head = push(head, 15); head = push(head, 10); // Create a loop for testing head.next.next.next.next = head; if (detectLoop(head)) document.write("Loop found"); else document.write("No Loop"); // This code is contributed by rag2127 </script> Loop found Complexity Analysis: Time complexity:O(n). Only one traversal of the loop is needed. Auxiliary Space:O(1). No extra space is needed. Solution 3: Floyd’s Cycle-Finding Algorithm Approach: This is the fastest method and has been described below: Traverse linked list using two pointers. Move one pointer(slow_p) by one and another pointer(fast_p) by two. If these pointers meet at the same node then there is a loop. If pointers do not meet then linked list doesn’t have a loop. The below image shows how the detectloop function works in the code: Implementation of Floyd’s Cycle-Finding Algorithm: C++ C Java Python C# Javascript // C++ program to detect loop in a linked list#include <bits/stdc++.h>using namespace std; /* Link list node */class Node {public: int data; Node* next;}; void push(Node** head_ref, int new_data){ /* allocate node */ Node* new_node = new Node(); /* put in the data */ new_node->data = new_data; /* link the old list off the new node */ new_node->next = (*head_ref); /* move the head to point to the new node */ (*head_ref) = new_node;} int detectLoop(Node* list){ Node *slow_p = list, *fast_p = list; while (slow_p && fast_p && fast_p->next) { slow_p = slow_p->next; fast_p = fast_p->next->next; if (slow_p == fast_p) { return 1; } } return 0;} /* Driver code*/int main(){ /* Start with the empty list */ Node* head = NULL; push(&head, 20); push(&head, 4); push(&head, 15); push(&head, 10); /* Create a loop for testing */ head->next->next->next->next = head; if (detectLoop(head)) cout << "Loop found"; else cout << "No Loop"; return 0;} // This is code is contributed by rathbhupendra // C program to detect loop in a linked list#include <stdio.h>#include <stdlib.h> /* Link list node */struct Node { int data; struct Node* next;}; void push(struct Node** head_ref, int new_data){ /* allocate node */ struct Node* new_node = (struct Node*)malloc(sizeof(struct Node)); /* put in the data */ new_node->data = new_data; /* link the old list off the new node */ new_node->next = (*head_ref); /* move the head to point to the new node */ (*head_ref) = new_node;} int detectLoop(struct Node* list){ struct Node *slow_p = list, *fast_p = list; while (slow_p && fast_p && fast_p->next) { slow_p = slow_p->next; fast_p = fast_p->next->next; if (slow_p == fast_p) { return 1; } } return 0;} /* Driver program to test above function*/int main(){ /* Start with the empty list */ struct Node* head = NULL; push(&head, 20); push(&head, 4); push(&head, 15); push(&head, 10); /* Create a loop for testing */ head->next->next->next->next = head; if (detectLoop(head)) printf("Loop found"); else printf("No Loop"); return 0;} // Java program to detect loop in a linked listclass LinkedList { Node head; // head of list /* Linked list Node*/ class Node { int data; Node next; Node(int d) { data = d; next = null; } } /* Inserts a new Node at front of the list. */ public void push(int new_data) { /* 1 & 2: Allocate the Node & Put in the data*/ Node new_node = new Node(new_data); /* 3. Make next of new Node as head */ new_node.next = head; /* 4. Move the head to point to new Node */ head = new_node; } void detectLoop() { Node slow_p = head, fast_p = head; int flag = 0; while (slow_p != null && fast_p != null && fast_p.next != null) { slow_p = slow_p.next; fast_p = fast_p.next.next; if (slow_p == fast_p) { flag = 1; break; } } if (flag == 1) System.out.println("Loop found"); else System.out.println("Loop not found"); } /* Driver program to test above functions */ public static void main(String args[]) { LinkedList llist = new LinkedList(); llist.push(20); llist.push(4); llist.push(15); llist.push(10); /*Create loop for testing */ llist.head.next.next.next.next = llist.head; llist.detectLoop(); }}/* This code is contributed by Rajat Mishra. */ # Python program to detect loop in the linked list # Node class class Node: # Constructor to initialize the node object def __init__(self, data): self.data = data self.next = None class LinkedList: # Function to initialize head def __init__(self): self.head = None # Function to insert a new node at the beginning def push(self, new_data): new_node = Node(new_data) new_node.next = self.head self.head = new_node # Utility function to print it the linked LinkedList def printList(self): temp = self.head while(temp): print temp.data, temp = temp.next def detectLoop(self): slow_p = self.head fast_p = self.head while(slow_p and fast_p and fast_p.next): slow_p = slow_p.next fast_p = fast_p.next.next if slow_p == fast_p: return # Driver program for testingllist = LinkedList()llist.push(20)llist.push(4)llist.push(15)llist.push(10) # Create a loop for testingllist.head.next.next.next.next = llist.headif(llist.detectLoop()): print "Found Loop"else: print "No Loop" # This code is contributed by Nikhil Kumar Singh(nickzuck_007) // C# program to detect loop in a linked listusing System; public class LinkedList { Node head; // head of list /* Linked list Node*/ public class Node { public int data; public Node next; public Node(int d) { data = d; next = null; } } /* Inserts a new Node at front of the list. */ public void push(int new_data) { /* 1 & 2: Allocate the Node & Put in the data*/ Node new_node = new Node(new_data); /* 3. Make next of new Node as head */ new_node.next = head; /* 4. Move the head to point to new Node */ head = new_node; } Boolean detectLoop() { Node slow_p = head, fast_p = head; while (slow_p != null && fast_p != null && fast_p.next != null) { slow_p = slow_p.next; fast_p = fast_p.next.next; if (slow_p == fast_p) { return true; } } return false; } /* Driver code */ public static void Main(String[] args) { LinkedList llist = new LinkedList(); llist.push(20); llist.push(4); llist.push(15); llist.push(10); /*Create loop for testing */ llist.head.next.next.next.next = llist.head; Boolean found = llist.detectLoop(); if (found) { Console.WriteLine("Loop Found"); } else { Console.WriteLine("No Loop"); } }} // This code is contributed by Princi Singh <script> // Javascript program to detect loop in a linked listlet head; // head of list /* Linked list Node*/class Node{ constructor(d) { this.data = d; this.next = null; }} /* Inserts a new Node at front of the list. */function push(new_data){ /* 1 & 2: Allocate the Node & Put in the data*/ let new_node = new Node(new_data); /* 3. Make next of new Node as head */ new_node.next = head; /* 4. Move the head to point to new Node */ head = new_node;} function detectLoop(){ let slow_p = head, fast_p = head; let flag = 0; while (slow_p != null && fast_p != null && fast_p.next != null) { slow_p = slow_p.next; fast_p = fast_p.next.next; if (slow_p == fast_p) { flag = 1; break; } } if (flag == 1) document.write("Loop found<br>"); else document.write("Loop not found<br>");} // Driver codepush(20);push(4);push(15);push(10); // Create loop for testinghead.next.next.next.next = head; detectLoop(); // This code is contributed by avanitrachhadiya2155 </script> Loop found Complexity Analysis: Time complexity: O(n). Only one traversal of the loop is needed. Auxiliary Space:O(1). There is no space required. How does above algorithm work? Please See : How does Floyd’s slow and fast pointers approach work?https://www.youtube.com/watch?v=Aup0kOWoMVg Solution 4: Marking visited nodes without modifying the linked list data structure In this method, a temporary node is created. The next pointer of each node that is traversed is made to point to this temporary node. This way we are using the next pointer of a node as a flag to indicate whether the node has been traversed or not. Every node is checked to see if the next is pointing to a temporary node or not. In the case of the first node of the loop, the second time we traverse it this condition will be true, hence we find that loop exists. If we come across a node that points to null then the loop doesn’t exist. Below is the implementation of the above approach: C++ Java Python3 C# Javascript // C++ program to return first node of loop#include <bits/stdc++.h>using namespace std; struct Node { int key; struct Node* next;}; Node* newNode(int key){ Node* temp = new Node; temp->key = key; temp->next = NULL; return temp;} // A utility function to print a linked listvoid printList(Node* head){ while (head != NULL) { cout << head->key << " "; head = head->next; } cout << endl;} // Function to detect first node of loop// in a linked list that may contain loopbool detectLoop(Node* head){ // Create a temporary node Node* temp = new Node; while (head != NULL) { // This condition is for the case // when there is no loop if (head->next == NULL) { return false; } // Check if next is already // pointing to temp if (head->next == temp) { return true; } // Store the pointer to the next node // in order to get to it in the next step Node* next = head->next; // Make next point to temp head->next = temp; // Get to the next node in the list head = nex; } return false;} /* Driver program to test above function*/int main(){ Node* head = newNode(1); head->next = newNode(2); head->next->next = newNode(3); head->next->next->next = newNode(4); head->next->next->next->next = newNode(5); /* Create a loop for testing(5 is pointing to 3) */ head->next->next->next->next->next = head->next->next; bool found = detectLoop(head); if (found) cout << "Loop Found"; else cout << "No Loop"; return 0;} // Java program to return first node of loopclass GFG { static class Node { int key; Node next; }; static Node newNode(int key) { Node temp = new Node(); temp.key = key; temp.next = null; return temp; } // A utility function to print a linked list static void printList(Node head) { while (head != null) { System.out.print(head.key + " "); head = head.next; } System.out.println(); } // Function to detect first node of loop // in a linked list that may contain loop static boolean detectLoop(Node head) { // Create a temporary node Node temp = new Node(); while (head != null) { // This condition is for the case // when there is no loop if (head.next == null) { return false; } // Check if next is already // pointing to temp if (head.next == temp) { return true; } // Store the pointer to the next node // in order to get to it in the next step Node next = head.next; // Make next point to temp head.next = temp; // Get to the next node in the list head = nex; } return false; } // Driver code public static void main(String args[]) { Node head = newNode(1); head.next = newNode(2); head.next.next = newNode(3); head.next.next.next = newNode(4); head.next.next.next.next = newNode(5); // Create a loop for testing(5 is pointing to 3) / head.next.next.next.next.next = head.next.next; boolean found = detectLoop(head); if (found) System.out.println("Loop Found"); else System.out.println("No Loop"); }} // This code is contributed by Arnab Kundu # Python3 program to return first node of loop # A binary tree node has data, pointer to# left child and a pointer to right child# Helper function that allocates a new node# with the given data and None left and# right pointers class newNode: def __init__(self, key): self.key = key self.left = None self.right = None # A utility function to print a linked list def printList(head): while (head != None): print(head.key, end=" ") head = head.next print() # Function to detect first node of loop# in a linked list that may contain loop def detectLoop(head): # Create a temporary node temp = "" while (head != None): # This condition is for the case # when there is no loop if (head.next == None): return False # Check if next is already # pointing to temp if (head.next == temp): return True # Store the pointer to the next node # in order to get to it in the next step next = head.next # Make next point to temp head.next = temp # Get to the next node in the list head = nex return False # Driver Codehead = newNode(1)head.next = newNode(2)head.next.next = newNode(3)head.next.next.next = newNode(4)head.next.next.next.next = newNode(5) # Create a loop for testing(5 is pointing to 3)head.next.next.next.next.next = head.next.next found = detectLoop(head)if (found): print("Loop Found")else: print("No Loop") # This code is contributed by SHUBHAMSINGH10 // C# program to return first node of loopusing System;public class GFG { public class Node { public int key; public Node next; }; static Node newNode(int key) { Node temp = new Node(); temp.key = key; temp.next = null; return temp; } // A utility function to print a linked list static void printList(Node head) { while (head != null) { Console.Write(head.key + " "); head = head.next; } Console.WriteLine(); } // Function to detect first node of loop // in a linked list that may contain loop static Boolean detectLoop(Node head) { // Create a temporary node Node temp = new Node(); while (head != null) { // This condition is for the case // when there is no loop if (head.next == null) { return false; } // Check if next is already // pointing to temp if (head.next == temp) { return true; } // Store the pointer to the next node // in order to get to it in the next step Node next = head.next; // Make next point to temp head.next = temp; // Get to the next node in the list head = nex; } return false; } // Driver code public static void Main(String[] args) { Node head = newNode(1); head.next = newNode(2); head.next.next = newNode(3); head.next.next.next = newNode(4); head.next.next.next.next = newNode(5); // Create a loop for testing(5 is pointing to 3) head.next.next.next.next.next = head.next.next; Boolean found = detectLoop(head); if (found) { Console.WriteLine("Loop Found"); } else { Console.WriteLine("No Loop"); } }} // This code is contributed by Princi Singh <script> // Javascript program to return first node of loopclass Node{ constructor(key) { this.key = key; this.next = null; }} // A utility function to print a linked listfunction printList(head){ while (head != null) { document.write(head.key + " "); head = head.next; } document.write("<br>");} // Function to detect first node of loop// in a linked list that may contain loopfunction detectLoop(head){ // Create a temporary node let temp = new Node(); while (head != null) { // This condition is for the case // when there is no loop if (head.next == null) { return false; } // Check if next is already // pointing to temp if (head.next == temp) { return true; } // Store the pointer to the next node // in order to get to it in the next step let next = head.next; // Make next point to temp head.next = temp; // Get to the next node in the list head = nex; } return false;} // Driver codelet head = new Node(1);head.next = new Node(2);head.next.next = new Node(3);head.next.next.next = new Node(4);head.next.next.next.next = new Node(5); // Create a loop for testing(5 is pointing to 3) /head.next.next.next.next.next = head.next.next; let found = detectLoop(head);if (found) document.write("Loop Found");else document.write("No Loop"); // This code is contributed by ab2127 </script> Loop Found Complexity Analysis: Time complexity: O(n). Only one traversal of the loop is needed. Auxiliary Space: O(1). There is no space required. Solution 5: Store length In this method, two pointers are created, first (always points to head) and last. Each time the last pointer moves we calculate no of nodes in between first and last and check whether the current no of nodes > previous no of nodes, if yes we proceed by moving last pointer else it means we’ve reached the end of the loop, so we return output accordingly. C++ Java Python3 C# Javascript // C++ program to return first node of loop#include <bits/stdc++.h>using namespace std; struct Node { int key; struct Node* next;}; Node* newNode(int key){ Node* temp = new Node; temp->key = key; temp->next = NULL; return temp;} // A utility function to print a linked listvoid printList(Node* head){ while (head != NULL) { cout << head->key << " "; head = head->next; } cout << endl;} /*returns distance between first and last node every time * last node moves forwards*/int distance(Node* first, Node* last){ /*counts no of nodes between first and last*/ int counter = 0; Node* curr; curr = first; while (curr != last) { counter += 1; curr = curr->next; } return counter + 1;} // Function to detect first node of loop// in a linked list that may contain loopbool detectLoop(Node* head){ // Create a temporary node Node* temp = new Node; Node *first, *last; /*first always points to head*/ first = head; /*last pointer initially points to head*/ last = head; /*current_length stores no of nodes between current * position of first and last*/ int current_length = 0; /*prev_length stores no of nodes between previous * position of first and last*/ int prev_length = -1; while (current_length > prev_length && last != NULL) { // set prev_length to current length then update the // current length prev_length = current_length; // distance is calculated current_length = distance(first, last); // last node points the next node last = last->next; } if (last == NULL) { return false; } else { return true; }} /* Driver program to test above function*/int main(){ Node* head = newNode(1); head->next = newNode(2); head->next->next = newNode(3); head->next->next->next = newNode(4); head->next->next->next->next = newNode(5); /* Create a loop for testing(5 is pointing to 3) */ head->next->next->next->next->next = head->next->next; bool found = detectLoop(head); if (found) cout << "Loop Found"; else cout << "No Loop Found"; return 0;} // Java program to return first node of loopimport java.util.*;class GFG{static class Node{ int key; Node next;}; static Node newNode(int key){ Node temp = new Node(); temp.key = key; temp.next = null; return temp;} // A utility function to print a linked liststatic void printList(Node head){ while (head != null) { System.out.print(head.key + " "); head = head.next; } System.out.println();} /*returns distance between first and last node every time * last node moves forwards*/static int distance(Node first, Node last){ /*counts no of nodes between first and last*/ int counter = 0; Node curr; curr = first; while (curr != last) { counter += 1; curr = curr.next; } return counter + 1;} // Function to detect first node of loop// in a linked list that may contain loopstatic boolean detectLoop(Node head){ // Create a temporary node Node temp = new Node(); Node first, last; /*first always points to head*/ first = head; /*last pointer initially points to head*/ last = head; /*current_length stores no of nodes between current * position of first and last*/ int current_length = 0; /*current_length stores no of nodes between previous * position of first and last*/ int prev_length = -1; while (current_length > prev_length && last != null) { // set prev_length to current length then update the // current length prev_length = current_length; // distance is calculated current_length = distance(first, last); // last node points the next node last = last.next; } if (last == null) { return false; } else { return true; }} /* Driver program to test above function*/public static void main(String[] args){ Node head = newNode(1); head.next = newNode(2); head.next.next = newNode(3); head.next.next.next = newNode(4); head.next.next.next.next = newNode(5); /* Create a loop for testing(5 is pointing to 3) */ head.next.next.next.next.next = head.next.next; boolean found = detectLoop(head); if (found) System.out.print("Loop Found"); else System.out.print("No Loop Found");}} // This code is contributed by gauravrajput1 # Python program to return first node of loopclass newNode: def __init__(self, key): self.key = key self.left = None self.right = None # A utility function to print a linked listdef printList(head): while (head != None) : print(head.key, end=" ") head = head.next; print() # returns distance between first and last node every time# last node moves forwardsdef distance(first, last): # counts no of nodes between first and last counter = 0 curr = first while (curr != last): counter = counter + 1 curr = curr.next return counter + 1 # Function to detect first node of loop# in a linked list that may contain loopdef detectLoop(head): # Create a temporary node temp = "" # first always points to head first = head; # last pointer initially points to head last = head; # current_length stores no of nodes between current # position of first and last current_length = 0 #current_length stores no of nodes between previous # position of first and last*/ prev_length = -1 while (current_length > prev_length and last != None) : # set prev_length to current length then update the # current length prev_length = current_length # distance is calculated current_length = distance(first, last) # last node points the next node last = last.next; if (last == None) : return False else : return True # Driver program to test above function head = newNode(1);head.next = newNode(2);head.next.next = newNode(3);head.next.next.next = newNode(4);head.next.next.next.next = newNode(5); # Create a loop for testing(5 is pointing to 3)head.next.next.next.next.next = head.next.next; found = detectLoop(head)if (found) : print("Loop Found")else : print("No Loop Found") # This code is contributed by ihritik // C# program to return first node of loopusing System; public class GFG{ public class Node { public int key; public Node next; }; static Node newNode(int key) { Node temp = new Node(); temp.key = key; temp.next = null; return temp; } // A utility function to print a linked list static void printList(Node head) { while (head != null) { Console.Write(head.key + " "); head = head.next; } Console.WriteLine(); } /*returns distance between first and last node every time * last node moves forwards*/ static int distance(Node first, Node last) { /*counts no of nodes between first and last*/ int counter = 0; Node curr; curr = first; while (curr != last) { counter += 1; curr = curr.next; } return counter + 1; } // Function to detect first node of loop // in a linked list that may contain loop static bool detectLoop(Node head) { // Create a temporary node Node temp = new Node(); Node first, last; /*first always points to head*/ first = head; /*last pointer initially points to head*/ last = head; /*current_length stores no of nodes between current * position of first and last*/ int current_length = 0; /*current_length stores no of nodes between previous * position of first and last*/ int prev_length = -1; while (current_length > prev_length && last != null) { // set prev_length to current length then update the // current length prev_length = current_length; // distance is calculated current_length = distance(first, last); // last node points the next node last = last.next; } if (last == null) { return false; } else { return true; } } /* Driver program to test above function*/ public static void Main(String[] args) { Node head = newNode(1); head.next = newNode(2); head.next.next = newNode(3); head.next.next.next = newNode(4); head.next.next.next.next = newNode(5); /* Create a loop for testing(5 is pointing to 3) */ head.next.next.next.next.next = head.next.next; bool found = detectLoop(head); if (found) Console.Write("Loop Found"); else Console.Write("No Loop Found"); }} // This code is contributed by gauravrajput1 <script> // Javascript program to return first node of loopclass Node{ constructor(key) { this.key = key; this.next = null; }} function newNode(key){ let temp = new Node(key); return temp;} // A utility function to print a linked listfunction printList(head){ while (head != null) { document.write(head.key + " "); head = head.next; } document.write("</br>");} /*returns distance between first and lastnode every time last node moves forwards*/function distance(first, last){ /*counts no of nodes between first and last*/ let counter = 0; let curr; curr = first; while (curr != last) { counter += 1; curr = curr.next; } return counter + 1;} // Function to detect first node of loop// in a linked list that may contain loopfunction detectLoop(head){ // Create a temporary node let temp = new Node(); let first, last; /*first always points to head*/ first = head; /*last pointer initially points to head*/ last = head; /*current_length stores no of nodes between current position of first and last*/ let current_length = 0; /*current_length stores no of nodes between previous position of first and last*/ let prev_length = -1; while (current_length > prev_length && last != null) { // Set prev_length to current length // then update the current length prev_length = current_length; // Distance is calculated current_length = distance(first, last); // Last node points the next node last = last.next; } if (last == null) { return false; } else { return true; }} // Driver codelet head = newNode(1);head.next = newNode(2);head.next.next = newNode(3);head.next.next.next = newNode(4);head.next.next.next.next = newNode(5); /* Create a loop for testing(5 is pointing to 3) */head.next.next.next.next.next = head.next.next;let found = detectLoop(head);if (found) document.write("Loop Found");else document.write("No Loop Found"); // This code is contributed by divyeshrabadiya07 </script> Loop Found Complexity Analysis: Time complexity: O(n2) Auxiliary Space: O(1) This is the simplest approach of the given problem, the only thing we have to do is to assign a new value to each data of node in the linked list which is not in the range given.Example suppose (1 <= Data on Node <= 10^3) then after visiting node assign the data as -1 as it is out of the given range. This is the simplest approach of the given problem, the only thing we have to do is to assign a new value to each data of node in the linked list which is not in the range given. Example suppose (1 <= Data on Node <= 10^3) then after visiting node assign the data as -1 as it is out of the given range. Follow the code given below for a better understanding: C++ Java Python3 C# Javascript // C++ program to return first node of loop#include <bits/stdc++.h>using namespace std; struct Node { int key; struct Node* next;}; Node* newNode(int key){ Node* temp = new Node; temp->key = key; temp->next = NULL; return temp;} // Function to detect first node of loop// in a linked list that may contain loopbool detectLoop(Node* head){ // If the head is null we will return false if (!head) return 0; else { // Traversing the linked list // for detecting loop while (head) { // If loop found if (head->key == -1) { return true; } // Changing the data of visited node to any // value which is outside th given range here it // is supposed the given range is (1 <= Data on // Node <= 10^3) else { head->key = -1; head = head->next; } } // If loop not found return false return 0; }} /* Driver program to test above function*/int main(){ Node* head = newNode(1); head->next = newNode(2); head->next->next = newNode(3); head->next->next->next = newNode(4); head->next->next->next->next = newNode(5); /* Create a loop for testing(5 is pointing to 3) */ head->next->next->next->next->next = head->next->next; bool found = detectLoop(head); cout << found << endl; return 0;} // Java program to return first node of loopimport java.util.*; class LinkedList{ // Head of liststatic Node head; // Linked list Nodestatic class Node{ int data; Node next; Node(int d) { data = d; next = null; }} /* Inserts a new Node at front of the list. */static public void push(int new_data){ /* 1 & 2: Allocate the Node & Put in the data*/ Node new_node = new Node(new_data); /* 3. Make next of new Node as head */ new_node.next = head; /* 4. Move the head to point to new Node */ head = new_node;} // Function to detect first node of loop// in a linked list that may contain loopstatic boolean detectLoop(Node h){ // If the head is null we will return false if (head == null) return false; else { // Traversing the linked list // for detecting loop while (head != null) { // If loop found if (head.data == -1) { return true; } // Changing the data of visited node to any // value which is outside th given range // here it is supposed the given range is (1 // <= Data on Node <= 10^3) else { head.data = -1; head = head.next; } } // If loop not found return false return false; }} // Driver Codepublic static void main(String[] args){ LinkedList llist = new LinkedList(); llist.push(1); llist.push(2); llist.push(3); llist.push(4); llist.push(5); /* Create a loop for testing */ llist.head.next.next.next.next.next = llist.head.next.next; if (detectLoop(llist.head)) System.out.println("1"); else System.out.println("0");}} // This code is contributed by RohitOberoi # Python program to return first node of loopclass Node: def __init__(self,d): self.data = d self.next = None head = Nonedef push(new_data): global head new_node = Node(new_data) new_node.next = head head=new_node def detectLoop(h): global head if (head == None): return False else: while (head != None): if (head.data == -1): return True else: head.data = -1 head = head.next return False push(1);push(2);push(3);push(4);push(5); head.next.next.next.next.next = head.next.next if (detectLoop(head)): print("1")else: print("0") # This code is contributed by patel2127. // C# program to return first node of loop using System; public class Node{ public int data; public Node next; public Node(int d) { data = d; next = null; }} public class GFG{ // Head of liststatic Node head; /* Inserts a new Node at front of the list. */static public void push(int new_data){ /* 1 & 2: Allocate the Node & Put in the data*/ Node new_node = new Node(new_data); /* 3. Make next of new Node as head */ new_node.next = head; /* 4. Move the head to point to new Node */ head = new_node;} // Function to detect first node of loop// in a linked list that may contain loopstatic bool detectLoop(Node h){ // If the head is null we will return false if (head == null) return false; else { // Traversing the linked list // for detecting loop while (head != null) { // If loop found if (head.data == -1) { return true; } // Changing the data of visited node to any // value which is outside th given range // here it is supposed the given range is (1 // <= Data on Node <= 10^3) else { head.data = -1; head = head.next; } } // If loop not found return false return false; }} // Driver Code static public void Main (){ push(1); push(2); push(3); push(4); push(5); /* Create a loop for testing */ head.next.next.next.next.next = head.next.next; if (detectLoop(head)) Console.WriteLine("1"); else Console.WriteLine("0"); }} <script>// Javascript program to return first node of loop// Linked list Nodeclass Node{ constructor(d) { this.data = d; this.next = null; }} // Head of listlet head; /* Inserts a new Node at front of the list. */function push(new_data){ /* 1 & 2: Allocate the Node & Put in the data*/ let new_node = new Node(new_data); /* 3. Make next of new Node as head */ new_node.next = head; /* 4. Move the head to point to new Node */ head = new_node;} // Function to detect first node of loop// in a linked list that may contain loopfunction detectLoop(h){ // If the head is null we will return false if (head == null) return false; else { // Traversing the linked list // for detecting loop while (head != null) { // If loop found if (head.data == -1) { return true; } // Changing the data of visited node to any // value which is outside th given range // here it is supposed the given range is (1 // <= Data on Node <= 10^3) else { head.data = -1; head = head.next; } } // If loop not found return false return false; }} // Driver Codepush(1);push(2);push(3);push(4);push(5); /* Create a loop for testing */head.next.next.next.next.next = head.next.next; if (detectLoop(head)) document.write("1");else document.write("0"); // This code is contributed by unknown2108</script> 1 Time Complexity: O(N) Auxiliary Space: O(1) Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. PrasadPawar ashwinvivek purnasrivatsa96 29AjayKumar rathbhupendra andrew1234 Akanksha_Rai princi singh SHUBHAMSINGH10 nidhi_biet prakhar7 rgndunes nesher123 rutvik_56 Rajput-Ji pratham76 GauravRajput1 us19018 RohitOberoi todaysgaurav rag2127 avanitrachhadiya2155 ab2127 divyeshrabadiya07 unknown2108 patel2127 simranarora5sos ihritik arn0dian parthc2002 surinderdawra388 sumitgumber28 adityakumar129 Accolite Amazon Linked Lists loop MAQ Software Samsung Tortoise-Hare-Approach Linked List Accolite Amazon Samsung MAQ Software Linked List Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Delete a Linked List node at a given position Implement a stack using singly linked list Queue - Linked List Implementation Implementing a Linked List in Java using Class Circular Linked List | Set 1 (Introduction and Applications) Remove duplicates from a sorted linked list Function to check if a singly linked list is palindrome Top 20 Linked List Interview Question Find Length of a Linked List (Iterative and Recursive) Remove duplicates from an unsorted linked list
[ { "code": null, "e": 25867, "s": 25839, "text": "\n12 Apr, 2022" }, { "code": null, "e": 25979, "s": 25867, "text": "Given a linked list, check if the linked list has loop or not. Below diagram shows a linked list with a loop. " }, { "code": null, "e": 26030, "s": 25981, "text": "The following are different ways of doing this. " }, { "code": null, "e": 26060, "s": 26030, "text": "Solution 1: Hashing Approach:" }, { "code": null, "e": 26303, "s": 26060, "text": "Traverse the list one by one and keep putting the node addresses in a Hash Table. At any point, if NULL is reached then return false, and if the next of the current nodes points to any of the previously stored nodes in Hash then return true." }, { "code": null, "e": 26307, "s": 26303, "text": "C++" }, { "code": null, "e": 26312, "s": 26307, "text": "Java" }, { "code": null, "e": 26320, "s": 26312, "text": "Python3" }, { "code": null, "e": 26323, "s": 26320, "text": "C#" }, { "code": null, "e": 26334, "s": 26323, "text": "Javascript" }, { "code": "// C++ program to detect loop in a linked list#include <bits/stdc++.h>using namespace std; /* Link list node */struct Node { int data; struct Node* next;}; void push(struct Node** head_ref, int new_data){ /* allocate node */ struct Node* new_node = new Node; /* put in the data */ new_node->data = new_data; /* link the old list off the new node */ new_node->next = (*head_ref); /* move the head to point to the new node */ (*head_ref) = new_node;} // Returns true if there is a loop in linked list// else returns false.bool detectLoop(struct Node* h){ unordered_set<Node*> s; while (h != NULL) { // If this node is already present // in hashmap it means there is a cycle // (Because you will be encountering the // node for the second time). if (s.find(h) != s.end()) return true; // If we are seeing the node for // the first time, insert it in hash s.insert(h); h = h->next; } return false;} /* Driver program to test above function*/int main(){ /* Start with the empty list */ struct Node* head = NULL; push(&head, 20); push(&head, 4); push(&head, 15); push(&head, 10); /* Create a loop for testing */ head->next->next->next->next = head; if (detectLoop(head)) cout << \"Loop found\"; else cout << \"No Loop\"; return 0;}// This code is contributed by Geetanjali", "e": 27771, "s": 26334, "text": null }, { "code": "// Java program to detect loop in a linked listimport java.util.*; public class LinkedList { static Node head; // head of list /* Linked list Node*/ static class Node { int data; Node next; Node(int d) { data = d; next = null; } } /* Inserts a new Node at front of the list. */ static public void push(int new_data) { /* 1 & 2: Allocate the Node & Put in the data*/ Node new_node = new Node(new_data); /* 3. Make next of new Node as head */ new_node.next = head; /* 4. Move the head to point to new Node */ head = new_node; } // Returns true if there is a loop in linked // list else returns false. static boolean detectLoop(Node h) { HashSet<Node> s = new HashSet<Node>(); while (h != null) { // If we have already has this node // in hashmap it means their is a cycle // (Because you we encountering the // node second time). if (s.contains(h)) return true; // If we are seeing the node for // the first time, insert it in hash s.add(h); h = h.next; } return false; } /* Driver program to test above function */ public static void main(String[] args) { LinkedList llist = new LinkedList(); llist.push(20); llist.push(4); llist.push(15); llist.push(10); /*Create loop for testing */ llist.head.next.next.next.next = llist.head; if (detectLoop(head)) System.out.println(\"Loop found\"); else System.out.println(\"No Loop\"); }} // This code is contributed by Arnav Kr. Mandal.", "e": 29551, "s": 27771, "text": null }, { "code": "# Python3 program to detect loop# in the linked list # Node class class Node: # Constructor to initialize # the node object def __init__(self, data): self.data = data self.next = None class LinkedList: # Function to initialize head def __init__(self): self.head = None # Function to insert a new # node at the beginning def push(self, new_data): new_node = Node(new_data) new_node.next = self.head self.head = new_node # Utility function to print it # the linked LinkedList def printList(self): temp = self.head while(temp): print(temp.data, end=\" \") temp = temp.next def detectLoop(self): s = set() temp = self.head while (temp): # If we have already has # this node in hashmap it # means their is a cycle # (Because you we encountering # the node second time). if (temp in s): return True # If we are seeing the node for # the first time, insert it in hash s.add(temp) temp = temp.next return False # Driver program for testingllist = LinkedList()llist.push(20)llist.push(4)llist.push(15)llist.push(10) # Create a loop for testingllist.head.next.next.next.next = llist.head if(llist.detectLoop()): print(\"Loop found\")else: print(\"No Loop \") # This code is contributed by Gitanjali.", "e": 31020, "s": 29551, "text": null }, { "code": "// C# program to detect loop in a linked listusing System;using System.Collections.Generic; class LinkedList { // head of list public Node head; /* Linked list Node*/ public class Node { public int data; public Node next; public Node(int d) { data = d; next = null; } } /* Inserts a new Node at front of the list. */ public void push(int new_data) { /* 1 & 2: Allocate the Node & Put in the data*/ Node new_node = new Node(new_data); /* 3. Make next of new Node as head */ new_node.next = head; /* 4. Move the head to point to new Node */ head = new_node; } // Returns true if there is a loop in linked // list else returns false. public static bool detectLoop(Node h) { HashSet<Node> s = new HashSet<Node>(); while (h != null) { // If we have already has this node // in hashmap it means their is a cycle // (Because you we encountering the // node second time). if (s.Contains(h)) return true; // If we are seeing the node for // the first time, insert it in hash s.Add(h); h = h.next; } return false; } /* Driver code*/ public static void Main(String[] args) { LinkedList llist = new LinkedList(); llist.push(20); llist.push(4); llist.push(15); llist.push(10); /*Create loop for testing */ llist.head.next.next.next.next = llist.head; if (detectLoop(llist.head)) Console.WriteLine(\"Loop found\"); else Console.WriteLine(\"No Loop\"); }} // This code has been contributed by 29AjayKumar", "e": 32814, "s": 31020, "text": null }, { "code": "<script> // JavaScript program to detect loop in a linked list var head; // head of list /* Linked list Node */ class Node { constructor(val) { this.data = val; this.next = null; } } /* Inserts a new Node at front of the list. */ function push(new_data) { /* * 1 & 2: Allocate the Node & Put in the data */var new_node = new Node(new_data); /* 3. Make next of new Node as head */ new_node.next = head; /* 4. Move the head to point to new Node */ head = new_node; } // Returns true if there is a loop in linked // list else returns false. function detectLoop(h) { var s = new Set(); while (h != null) { // If we have already has this node // in hashmap it means their is a cycle // (Because you we encountering the // node second time). if (s.has(h)) return true; // If we are seeing the node for // the first time, insert it in hash s.add(h); h = h.next; } return false; } /* Driver program to test above function */ push(20); push(4); push(15); push(10); /* Create loop for testing */ head.next.next.next.next = head; if (detectLoop(head)) document.write(\"Loop found\"); else document.write(\"No Loop\"); // This code is contributed by todaysgaurav </script>", "e": 34332, "s": 32814, "text": null }, { "code": null, "e": 34343, "s": 34332, "text": "Loop found" }, { "code": null, "e": 34366, "s": 34343, "text": "Complexity Analysis: " }, { "code": null, "e": 34431, "s": 34366, "text": "Time complexity: O(n). Only one traversal of the loop is needed." }, { "code": null, "e": 34509, "s": 34431, "text": "Auxiliary Space: O(n). n is the space required to store the value in hashmap." }, { "code": null, "e": 34698, "s": 34509, "text": "Solution 2: This problem can be solved without hashmap by modifying the linked list data structure. Approach: This solution requires modifications to the basic linked list data structure. " }, { "code": null, "e": 34734, "s": 34698, "text": "Have a visited flag with each node." }, { "code": null, "e": 34791, "s": 34734, "text": "Traverse the linked list and keep marking visited nodes." }, { "code": null, "e": 34925, "s": 34791, "text": "If you see a visited node again then there is a loop. This solution works in O(n) but requires additional information with each node." }, { "code": null, "e": 35173, "s": 34925, "text": "A variation of this solution that doesn’t require modification to basic data structure can be implemented using a hash, just store the addresses of visited nodes in a hash and if you see an address that already exists in hash then there is a loop." }, { "code": null, "e": 35177, "s": 35173, "text": "C++" }, { "code": null, "e": 35179, "s": 35177, "text": "C" }, { "code": null, "e": 35184, "s": 35179, "text": "Java" }, { "code": null, "e": 35192, "s": 35184, "text": "Python3" }, { "code": null, "e": 35195, "s": 35192, "text": "C#" }, { "code": null, "e": 35206, "s": 35195, "text": "Javascript" }, { "code": "// C++ program to detect loop in a linked list#include <bits/stdc++.h>using namespace std; /* Link list node */struct Node { int data; struct Node* next; int flag;}; void push(struct Node** head_ref, int new_data){ /* allocate node */ struct Node* new_node = new Node; /* put in the data */ new_node->data = new_data; new_node->flag = 0; /* link the old list off the new node */ new_node->next = (*head_ref); /* move the head to point to the new node */ (*head_ref) = new_node;} // Returns true if there is a loop in linked list// else returns false.bool detectLoop(struct Node* h){ while (h != NULL) { // If this node is already traverse // it means there is a cycle // (Because you we encountering the // node for the second time). if (h->flag == 1) return true; // If we are seeing the node for // the first time, mark its flag as 1 h->flag = 1; h = h->next; } return false;} /* Driver program to test above function*/int main(){ /* Start with the empty list */ struct Node* head = NULL; push(&head, 20); push(&head, 4); push(&head, 15); push(&head, 10); /* Create a loop for testing */ head->next->next->next->next = head; if (detectLoop(head)) cout << \"Loop found\"; else cout << \"No Loop\"; return 0;}// This code is contributed by Geetanjali", "e": 36630, "s": 35206, "text": null }, { "code": "// C program to detect loop in a linked list#include <stdbool.h>#include <stdio.h>#include <stdlib.h> /* Link list node */typedef struct Node { int data; struct Node* next; int flag;} Node; void push(struct Node** head_ref, int new_data){ /* allocate node */ struct Node* new_node = (Node*)malloc(sizeof(Node)); /* put in the data */ new_node->data = new_data; new_node->flag = 0; /* link the old list off the new node */ new_node->next = (*head_ref); /* move the head to point to the new node */ (*head_ref) = new_node;} // Returns true if there is a loop in linked list// else returns false.bool detectLoop(struct Node* h){ while (h != NULL) { // If this node is already traverse // it means there is a cycle // (Because you we encountering the // node for the second time). if (h->flag == 1) return true; // If we are seeing the node for // the first time, mark its flag as 1 h->flag = 1; h = h->next; } return false;} /* Driver program to test above function*/int main(){ /* Start with the empty list */ struct Node* head = NULL; push(&head, 20); push(&head, 4); push(&head, 15); push(&head, 10); /* Create a loop for testing */ head->next->next->next->next = head; if (detectLoop(head)) printf(\"Loop found\"); else printf(\"No Loop\"); return 0;} // This code is contributed by Aditya Kumar (adityakumar129)", "e": 38117, "s": 36630, "text": null }, { "code": "// Java program to detect loop in a linked listimport java.util.*; class GFG{ // Link list nodestatic class Node{ int data; Node next; int flag;}; static Node push(Node head_ref, int new_data){ // Allocate node Node new_node = new Node(); // Put in the data new_node.data = new_data; new_node.flag = 0; // Link the old list off the new node new_node.next = head_ref; // Move the head to point to the new node head_ref = new_node; return head_ref;} // Returns true if there is a loop in linked// list else returns false.static boolean detectLoop(Node h){ while (h != null) { // If this node is already traverse // it means there is a cycle // (Because you we encountering the // node for the second time). if (h.flag == 1) return true; // If we are seeing the node for // the first time, mark its flag as 1 h.flag = 1; h = h.next; } return false;} // Driver codepublic static void main(String[] args){ // Start with the empty list Node head = null; head = push(head, 20); head = push(head, 4); head = push(head, 15); head = push(head, 10); // Create a loop for testing head.next.next.next.next = head; if (detectLoop(head)) System.out.print(\"Loop found\"); else System.out.print(\"No Loop\");}} // This code is contributed by Rajput-Ji", "e": 39546, "s": 38117, "text": null }, { "code": "# Python3 program to detect loop in a linked list ''' Link list node '''class Node: def __init__(self): self.data = 0 self.next = None self.flag = 0 def push(head_ref, new_data): ''' allocate node ''' new_node = Node(); ''' put in the data ''' new_node.data = new_data; new_node.flag = 0; ''' link the old list off the new node ''' new_node.next = (head_ref); ''' move the head to point to the new node ''' (head_ref) = new_node; return head_ref # Returns true if there is a loop in linked list# else returns false.def detectLoop(h): while (h != None): # If this node is already traverse # it means there is a cycle # (Because you we encountering the # node for the second time). if (h.flag == 1): return True; # If we are seeing the node for # the first time, mark its flag as 1 h.flag = 1; h = h.next; return False; ''' Driver program to test above function'''if __name__=='__main__': ''' Start with the empty list ''' head = None; head = push(head, 20); head = push(head, 4); head = push(head, 15); head = push( head, 10) ''' Create a loop for testing ''' head.next.next.next.next = head; if (detectLoop(head)): print(\"Loop found\") else: print(\"No Loop\") # This code is contributed by rutvik_56", "e": 40961, "s": 39546, "text": null }, { "code": "// C# program to detect loop in a linked listusing System; class GFG{ // Link list nodeclass Node{ public int data; public Node next; public int flag;}; static Node push(Node head_ref, int new_data){ // Allocate node Node new_node = new Node(); // Put in the data new_node.data = new_data; new_node.flag = 0; // Link the old list off the new node new_node.next = head_ref; // Move the head to point to the new node head_ref = new_node; return head_ref;} // Returns true if there is a loop in linked// list else returns false.static bool detectLoop(Node h){ while (h != null) { // If this node is already traverse // it means there is a cycle // (Because you we encountering the // node for the second time). if (h.flag == 1) return true; // If we are seeing the node for // the first time, mark its flag as 1 h.flag = 1; h = h.next; } return false;} // Driver codepublic static void Main(string[] args){ // Start with the empty list Node head = null; head = push(head, 20); head = push(head, 4); head = push(head, 15); head = push(head, 10); // Create a loop for testing head.next.next.next.next = head; if (detectLoop(head)) Console.Write(\"Loop found\"); else Console.Write(\"No Loop\");}} // This code is contributed by pratham76", "e": 42387, "s": 40961, "text": null }, { "code": "<script> // JavaScript program to detect loop in a linked list // Link list nodeclass Node{ constructor() { let data; let next; let flag; }} function push( head_ref, new_data){ // Allocate node let new_node = new Node(); // Put in the data new_node.data = new_data; new_node.flag = 0; // Link the old list off the new node new_node.next = head_ref; // Move the head to point to the new node head_ref = new_node; return head_ref;} // Returns true if there is a loop in linked// list else returns false. function detectLoop(h){ while (h != null) { // If this node is already traverse // it means there is a cycle // (Because you we encountering the // node for the second time). if (h.flag == 1) return true; // If we are seeing the node for // the first time, mark its flag as 1 h.flag = 1; h = h.next; } return false;} // Driver code // Start with the empty list let head = null; head = push(head, 20); head = push(head, 4); head = push(head, 15); head = push(head, 10); // Create a loop for testing head.next.next.next.next = head; if (detectLoop(head)) document.write(\"Loop found\"); else document.write(\"No Loop\"); // This code is contributed by rag2127 </script>", "e": 43772, "s": 42387, "text": null }, { "code": null, "e": 43783, "s": 43772, "text": "Loop found" }, { "code": null, "e": 43806, "s": 43783, "text": "Complexity Analysis: " }, { "code": null, "e": 43870, "s": 43806, "text": "Time complexity:O(n). Only one traversal of the loop is needed." }, { "code": null, "e": 43918, "s": 43870, "text": "Auxiliary Space:O(1). No extra space is needed." }, { "code": null, "e": 44033, "s": 43920, "text": "Solution 3: Floyd’s Cycle-Finding Algorithm Approach: This is the fastest method and has been described below: " }, { "code": null, "e": 44074, "s": 44033, "text": "Traverse linked list using two pointers." }, { "code": null, "e": 44142, "s": 44074, "text": "Move one pointer(slow_p) by one and another pointer(fast_p) by two." }, { "code": null, "e": 44266, "s": 44142, "text": "If these pointers meet at the same node then there is a loop. If pointers do not meet then linked list doesn’t have a loop." }, { "code": null, "e": 44335, "s": 44266, "text": "The below image shows how the detectloop function works in the code:" }, { "code": null, "e": 44388, "s": 44335, "text": "Implementation of Floyd’s Cycle-Finding Algorithm: " }, { "code": null, "e": 44392, "s": 44388, "text": "C++" }, { "code": null, "e": 44394, "s": 44392, "text": "C" }, { "code": null, "e": 44399, "s": 44394, "text": "Java" }, { "code": null, "e": 44406, "s": 44399, "text": "Python" }, { "code": null, "e": 44409, "s": 44406, "text": "C#" }, { "code": null, "e": 44420, "s": 44409, "text": "Javascript" }, { "code": "// C++ program to detect loop in a linked list#include <bits/stdc++.h>using namespace std; /* Link list node */class Node {public: int data; Node* next;}; void push(Node** head_ref, int new_data){ /* allocate node */ Node* new_node = new Node(); /* put in the data */ new_node->data = new_data; /* link the old list off the new node */ new_node->next = (*head_ref); /* move the head to point to the new node */ (*head_ref) = new_node;} int detectLoop(Node* list){ Node *slow_p = list, *fast_p = list; while (slow_p && fast_p && fast_p->next) { slow_p = slow_p->next; fast_p = fast_p->next->next; if (slow_p == fast_p) { return 1; } } return 0;} /* Driver code*/int main(){ /* Start with the empty list */ Node* head = NULL; push(&head, 20); push(&head, 4); push(&head, 15); push(&head, 10); /* Create a loop for testing */ head->next->next->next->next = head; if (detectLoop(head)) cout << \"Loop found\"; else cout << \"No Loop\"; return 0;} // This is code is contributed by rathbhupendra", "e": 45541, "s": 44420, "text": null }, { "code": "// C program to detect loop in a linked list#include <stdio.h>#include <stdlib.h> /* Link list node */struct Node { int data; struct Node* next;}; void push(struct Node** head_ref, int new_data){ /* allocate node */ struct Node* new_node = (struct Node*)malloc(sizeof(struct Node)); /* put in the data */ new_node->data = new_data; /* link the old list off the new node */ new_node->next = (*head_ref); /* move the head to point to the new node */ (*head_ref) = new_node;} int detectLoop(struct Node* list){ struct Node *slow_p = list, *fast_p = list; while (slow_p && fast_p && fast_p->next) { slow_p = slow_p->next; fast_p = fast_p->next->next; if (slow_p == fast_p) { return 1; } } return 0;} /* Driver program to test above function*/int main(){ /* Start with the empty list */ struct Node* head = NULL; push(&head, 20); push(&head, 4); push(&head, 15); push(&head, 10); /* Create a loop for testing */ head->next->next->next->next = head; if (detectLoop(head)) printf(\"Loop found\"); else printf(\"No Loop\"); return 0;}", "e": 46707, "s": 45541, "text": null }, { "code": "// Java program to detect loop in a linked listclass LinkedList { Node head; // head of list /* Linked list Node*/ class Node { int data; Node next; Node(int d) { data = d; next = null; } } /* Inserts a new Node at front of the list. */ public void push(int new_data) { /* 1 & 2: Allocate the Node & Put in the data*/ Node new_node = new Node(new_data); /* 3. Make next of new Node as head */ new_node.next = head; /* 4. Move the head to point to new Node */ head = new_node; } void detectLoop() { Node slow_p = head, fast_p = head; int flag = 0; while (slow_p != null && fast_p != null && fast_p.next != null) { slow_p = slow_p.next; fast_p = fast_p.next.next; if (slow_p == fast_p) { flag = 1; break; } } if (flag == 1) System.out.println(\"Loop found\"); else System.out.println(\"Loop not found\"); } /* Driver program to test above functions */ public static void main(String args[]) { LinkedList llist = new LinkedList(); llist.push(20); llist.push(4); llist.push(15); llist.push(10); /*Create loop for testing */ llist.head.next.next.next.next = llist.head; llist.detectLoop(); }}/* This code is contributed by Rajat Mishra. */", "e": 48214, "s": 46707, "text": null }, { "code": "# Python program to detect loop in the linked list # Node class class Node: # Constructor to initialize the node object def __init__(self, data): self.data = data self.next = None class LinkedList: # Function to initialize head def __init__(self): self.head = None # Function to insert a new node at the beginning def push(self, new_data): new_node = Node(new_data) new_node.next = self.head self.head = new_node # Utility function to print it the linked LinkedList def printList(self): temp = self.head while(temp): print temp.data, temp = temp.next def detectLoop(self): slow_p = self.head fast_p = self.head while(slow_p and fast_p and fast_p.next): slow_p = slow_p.next fast_p = fast_p.next.next if slow_p == fast_p: return # Driver program for testingllist = LinkedList()llist.push(20)llist.push(4)llist.push(15)llist.push(10) # Create a loop for testingllist.head.next.next.next.next = llist.headif(llist.detectLoop()): print \"Found Loop\"else: print \"No Loop\" # This code is contributed by Nikhil Kumar Singh(nickzuck_007)", "e": 49431, "s": 48214, "text": null }, { "code": "// C# program to detect loop in a linked listusing System; public class LinkedList { Node head; // head of list /* Linked list Node*/ public class Node { public int data; public Node next; public Node(int d) { data = d; next = null; } } /* Inserts a new Node at front of the list. */ public void push(int new_data) { /* 1 & 2: Allocate the Node & Put in the data*/ Node new_node = new Node(new_data); /* 3. Make next of new Node as head */ new_node.next = head; /* 4. Move the head to point to new Node */ head = new_node; } Boolean detectLoop() { Node slow_p = head, fast_p = head; while (slow_p != null && fast_p != null && fast_p.next != null) { slow_p = slow_p.next; fast_p = fast_p.next.next; if (slow_p == fast_p) { return true; } } return false; } /* Driver code */ public static void Main(String[] args) { LinkedList llist = new LinkedList(); llist.push(20); llist.push(4); llist.push(15); llist.push(10); /*Create loop for testing */ llist.head.next.next.next.next = llist.head; Boolean found = llist.detectLoop(); if (found) { Console.WriteLine(\"Loop Found\"); } else { Console.WriteLine(\"No Loop\"); } }} // This code is contributed by Princi Singh", "e": 50963, "s": 49431, "text": null }, { "code": "<script> // Javascript program to detect loop in a linked listlet head; // head of list /* Linked list Node*/class Node{ constructor(d) { this.data = d; this.next = null; }} /* Inserts a new Node at front of the list. */function push(new_data){ /* 1 & 2: Allocate the Node & Put in the data*/ let new_node = new Node(new_data); /* 3. Make next of new Node as head */ new_node.next = head; /* 4. Move the head to point to new Node */ head = new_node;} function detectLoop(){ let slow_p = head, fast_p = head; let flag = 0; while (slow_p != null && fast_p != null && fast_p.next != null) { slow_p = slow_p.next; fast_p = fast_p.next.next; if (slow_p == fast_p) { flag = 1; break; } } if (flag == 1) document.write(\"Loop found<br>\"); else document.write(\"Loop not found<br>\");} // Driver codepush(20);push(4);push(15);push(10); // Create loop for testinghead.next.next.next.next = head; detectLoop(); // This code is contributed by avanitrachhadiya2155 </script>", "e": 52089, "s": 50963, "text": null }, { "code": null, "e": 52100, "s": 52089, "text": "Loop found" }, { "code": null, "e": 52123, "s": 52100, "text": "Complexity Analysis: " }, { "code": null, "e": 52188, "s": 52123, "text": "Time complexity: O(n). Only one traversal of the loop is needed." }, { "code": null, "e": 52238, "s": 52188, "text": "Auxiliary Space:O(1). There is no space required." }, { "code": null, "e": 52381, "s": 52238, "text": "How does above algorithm work? Please See : How does Floyd’s slow and fast pointers approach work?https://www.youtube.com/watch?v=Aup0kOWoMVg " }, { "code": null, "e": 53003, "s": 52381, "text": "Solution 4: Marking visited nodes without modifying the linked list data structure In this method, a temporary node is created. The next pointer of each node that is traversed is made to point to this temporary node. This way we are using the next pointer of a node as a flag to indicate whether the node has been traversed or not. Every node is checked to see if the next is pointing to a temporary node or not. In the case of the first node of the loop, the second time we traverse it this condition will be true, hence we find that loop exists. If we come across a node that points to null then the loop doesn’t exist." }, { "code": null, "e": 53054, "s": 53003, "text": "Below is the implementation of the above approach:" }, { "code": null, "e": 53058, "s": 53054, "text": "C++" }, { "code": null, "e": 53063, "s": 53058, "text": "Java" }, { "code": null, "e": 53071, "s": 53063, "text": "Python3" }, { "code": null, "e": 53074, "s": 53071, "text": "C#" }, { "code": null, "e": 53085, "s": 53074, "text": "Javascript" }, { "code": "// C++ program to return first node of loop#include <bits/stdc++.h>using namespace std; struct Node { int key; struct Node* next;}; Node* newNode(int key){ Node* temp = new Node; temp->key = key; temp->next = NULL; return temp;} // A utility function to print a linked listvoid printList(Node* head){ while (head != NULL) { cout << head->key << \" \"; head = head->next; } cout << endl;} // Function to detect first node of loop// in a linked list that may contain loopbool detectLoop(Node* head){ // Create a temporary node Node* temp = new Node; while (head != NULL) { // This condition is for the case // when there is no loop if (head->next == NULL) { return false; } // Check if next is already // pointing to temp if (head->next == temp) { return true; } // Store the pointer to the next node // in order to get to it in the next step Node* next = head->next; // Make next point to temp head->next = temp; // Get to the next node in the list head = nex; } return false;} /* Driver program to test above function*/int main(){ Node* head = newNode(1); head->next = newNode(2); head->next->next = newNode(3); head->next->next->next = newNode(4); head->next->next->next->next = newNode(5); /* Create a loop for testing(5 is pointing to 3) */ head->next->next->next->next->next = head->next->next; bool found = detectLoop(head); if (found) cout << \"Loop Found\"; else cout << \"No Loop\"; return 0;}", "e": 54721, "s": 53085, "text": null }, { "code": "// Java program to return first node of loopclass GFG { static class Node { int key; Node next; }; static Node newNode(int key) { Node temp = new Node(); temp.key = key; temp.next = null; return temp; } // A utility function to print a linked list static void printList(Node head) { while (head != null) { System.out.print(head.key + \" \"); head = head.next; } System.out.println(); } // Function to detect first node of loop // in a linked list that may contain loop static boolean detectLoop(Node head) { // Create a temporary node Node temp = new Node(); while (head != null) { // This condition is for the case // when there is no loop if (head.next == null) { return false; } // Check if next is already // pointing to temp if (head.next == temp) { return true; } // Store the pointer to the next node // in order to get to it in the next step Node next = head.next; // Make next point to temp head.next = temp; // Get to the next node in the list head = nex; } return false; } // Driver code public static void main(String args[]) { Node head = newNode(1); head.next = newNode(2); head.next.next = newNode(3); head.next.next.next = newNode(4); head.next.next.next.next = newNode(5); // Create a loop for testing(5 is pointing to 3) / head.next.next.next.next.next = head.next.next; boolean found = detectLoop(head); if (found) System.out.println(\"Loop Found\"); else System.out.println(\"No Loop\"); }} // This code is contributed by Arnab Kundu", "e": 56644, "s": 54721, "text": null }, { "code": "# Python3 program to return first node of loop # A binary tree node has data, pointer to# left child and a pointer to right child# Helper function that allocates a new node# with the given data and None left and# right pointers class newNode: def __init__(self, key): self.key = key self.left = None self.right = None # A utility function to print a linked list def printList(head): while (head != None): print(head.key, end=\" \") head = head.next print() # Function to detect first node of loop# in a linked list that may contain loop def detectLoop(head): # Create a temporary node temp = \"\" while (head != None): # This condition is for the case # when there is no loop if (head.next == None): return False # Check if next is already # pointing to temp if (head.next == temp): return True # Store the pointer to the next node # in order to get to it in the next step next = head.next # Make next point to temp head.next = temp # Get to the next node in the list head = nex return False # Driver Codehead = newNode(1)head.next = newNode(2)head.next.next = newNode(3)head.next.next.next = newNode(4)head.next.next.next.next = newNode(5) # Create a loop for testing(5 is pointing to 3)head.next.next.next.next.next = head.next.next found = detectLoop(head)if (found): print(\"Loop Found\")else: print(\"No Loop\") # This code is contributed by SHUBHAMSINGH10", "e": 58185, "s": 56644, "text": null }, { "code": "// C# program to return first node of loopusing System;public class GFG { public class Node { public int key; public Node next; }; static Node newNode(int key) { Node temp = new Node(); temp.key = key; temp.next = null; return temp; } // A utility function to print a linked list static void printList(Node head) { while (head != null) { Console.Write(head.key + \" \"); head = head.next; } Console.WriteLine(); } // Function to detect first node of loop // in a linked list that may contain loop static Boolean detectLoop(Node head) { // Create a temporary node Node temp = new Node(); while (head != null) { // This condition is for the case // when there is no loop if (head.next == null) { return false; } // Check if next is already // pointing to temp if (head.next == temp) { return true; } // Store the pointer to the next node // in order to get to it in the next step Node next = head.next; // Make next point to temp head.next = temp; // Get to the next node in the list head = nex; } return false; } // Driver code public static void Main(String[] args) { Node head = newNode(1); head.next = newNode(2); head.next.next = newNode(3); head.next.next.next = newNode(4); head.next.next.next.next = newNode(5); // Create a loop for testing(5 is pointing to 3) head.next.next.next.next.next = head.next.next; Boolean found = detectLoop(head); if (found) { Console.WriteLine(\"Loop Found\"); } else { Console.WriteLine(\"No Loop\"); } }} // This code is contributed by Princi Singh", "e": 60155, "s": 58185, "text": null }, { "code": "<script> // Javascript program to return first node of loopclass Node{ constructor(key) { this.key = key; this.next = null; }} // A utility function to print a linked listfunction printList(head){ while (head != null) { document.write(head.key + \" \"); head = head.next; } document.write(\"<br>\");} // Function to detect first node of loop// in a linked list that may contain loopfunction detectLoop(head){ // Create a temporary node let temp = new Node(); while (head != null) { // This condition is for the case // when there is no loop if (head.next == null) { return false; } // Check if next is already // pointing to temp if (head.next == temp) { return true; } // Store the pointer to the next node // in order to get to it in the next step let next = head.next; // Make next point to temp head.next = temp; // Get to the next node in the list head = nex; } return false;} // Driver codelet head = new Node(1);head.next = new Node(2);head.next.next = new Node(3);head.next.next.next = new Node(4);head.next.next.next.next = new Node(5); // Create a loop for testing(5 is pointing to 3) /head.next.next.next.next.next = head.next.next; let found = detectLoop(head);if (found) document.write(\"Loop Found\");else document.write(\"No Loop\"); // This code is contributed by ab2127 </script>", "e": 61678, "s": 60155, "text": null }, { "code": null, "e": 61689, "s": 61678, "text": "Loop Found" }, { "code": null, "e": 61712, "s": 61689, "text": "Complexity Analysis: " }, { "code": null, "e": 61777, "s": 61712, "text": "Time complexity: O(n). Only one traversal of the loop is needed." }, { "code": null, "e": 61828, "s": 61777, "text": "Auxiliary Space: O(1). There is no space required." }, { "code": null, "e": 61853, "s": 61828, "text": "Solution 5: Store length" }, { "code": null, "e": 62208, "s": 61853, "text": "In this method, two pointers are created, first (always points to head) and last. Each time the last pointer moves we calculate no of nodes in between first and last and check whether the current no of nodes > previous no of nodes, if yes we proceed by moving last pointer else it means we’ve reached the end of the loop, so we return output accordingly." }, { "code": null, "e": 62212, "s": 62208, "text": "C++" }, { "code": null, "e": 62217, "s": 62212, "text": "Java" }, { "code": null, "e": 62225, "s": 62217, "text": "Python3" }, { "code": null, "e": 62228, "s": 62225, "text": "C#" }, { "code": null, "e": 62239, "s": 62228, "text": "Javascript" }, { "code": "// C++ program to return first node of loop#include <bits/stdc++.h>using namespace std; struct Node { int key; struct Node* next;}; Node* newNode(int key){ Node* temp = new Node; temp->key = key; temp->next = NULL; return temp;} // A utility function to print a linked listvoid printList(Node* head){ while (head != NULL) { cout << head->key << \" \"; head = head->next; } cout << endl;} /*returns distance between first and last node every time * last node moves forwards*/int distance(Node* first, Node* last){ /*counts no of nodes between first and last*/ int counter = 0; Node* curr; curr = first; while (curr != last) { counter += 1; curr = curr->next; } return counter + 1;} // Function to detect first node of loop// in a linked list that may contain loopbool detectLoop(Node* head){ // Create a temporary node Node* temp = new Node; Node *first, *last; /*first always points to head*/ first = head; /*last pointer initially points to head*/ last = head; /*current_length stores no of nodes between current * position of first and last*/ int current_length = 0; /*prev_length stores no of nodes between previous * position of first and last*/ int prev_length = -1; while (current_length > prev_length && last != NULL) { // set prev_length to current length then update the // current length prev_length = current_length; // distance is calculated current_length = distance(first, last); // last node points the next node last = last->next; } if (last == NULL) { return false; } else { return true; }} /* Driver program to test above function*/int main(){ Node* head = newNode(1); head->next = newNode(2); head->next->next = newNode(3); head->next->next->next = newNode(4); head->next->next->next->next = newNode(5); /* Create a loop for testing(5 is pointing to 3) */ head->next->next->next->next->next = head->next->next; bool found = detectLoop(head); if (found) cout << \"Loop Found\"; else cout << \"No Loop Found\"; return 0;}", "e": 64436, "s": 62239, "text": null }, { "code": "// Java program to return first node of loopimport java.util.*;class GFG{static class Node{ int key; Node next;}; static Node newNode(int key){ Node temp = new Node(); temp.key = key; temp.next = null; return temp;} // A utility function to print a linked liststatic void printList(Node head){ while (head != null) { System.out.print(head.key + \" \"); head = head.next; } System.out.println();} /*returns distance between first and last node every time * last node moves forwards*/static int distance(Node first, Node last){ /*counts no of nodes between first and last*/ int counter = 0; Node curr; curr = first; while (curr != last) { counter += 1; curr = curr.next; } return counter + 1;} // Function to detect first node of loop// in a linked list that may contain loopstatic boolean detectLoop(Node head){ // Create a temporary node Node temp = new Node(); Node first, last; /*first always points to head*/ first = head; /*last pointer initially points to head*/ last = head; /*current_length stores no of nodes between current * position of first and last*/ int current_length = 0; /*current_length stores no of nodes between previous * position of first and last*/ int prev_length = -1; while (current_length > prev_length && last != null) { // set prev_length to current length then update the // current length prev_length = current_length; // distance is calculated current_length = distance(first, last); // last node points the next node last = last.next; } if (last == null) { return false; } else { return true; }} /* Driver program to test above function*/public static void main(String[] args){ Node head = newNode(1); head.next = newNode(2); head.next.next = newNode(3); head.next.next.next = newNode(4); head.next.next.next.next = newNode(5); /* Create a loop for testing(5 is pointing to 3) */ head.next.next.next.next.next = head.next.next; boolean found = detectLoop(head); if (found) System.out.print(\"Loop Found\"); else System.out.print(\"No Loop Found\");}} // This code is contributed by gauravrajput1", "e": 66755, "s": 64436, "text": null }, { "code": "# Python program to return first node of loopclass newNode: def __init__(self, key): self.key = key self.left = None self.right = None # A utility function to print a linked listdef printList(head): while (head != None) : print(head.key, end=\" \") head = head.next; print() # returns distance between first and last node every time# last node moves forwardsdef distance(first, last): # counts no of nodes between first and last counter = 0 curr = first while (curr != last): counter = counter + 1 curr = curr.next return counter + 1 # Function to detect first node of loop# in a linked list that may contain loopdef detectLoop(head): # Create a temporary node temp = \"\" # first always points to head first = head; # last pointer initially points to head last = head; # current_length stores no of nodes between current # position of first and last current_length = 0 #current_length stores no of nodes between previous # position of first and last*/ prev_length = -1 while (current_length > prev_length and last != None) : # set prev_length to current length then update the # current length prev_length = current_length # distance is calculated current_length = distance(first, last) # last node points the next node last = last.next; if (last == None) : return False else : return True # Driver program to test above function head = newNode(1);head.next = newNode(2);head.next.next = newNode(3);head.next.next.next = newNode(4);head.next.next.next.next = newNode(5); # Create a loop for testing(5 is pointing to 3)head.next.next.next.next.next = head.next.next; found = detectLoop(head)if (found) : print(\"Loop Found\")else : print(\"No Loop Found\") # This code is contributed by ihritik", "e": 68679, "s": 66755, "text": null }, { "code": "// C# program to return first node of loopusing System; public class GFG{ public class Node { public int key; public Node next; }; static Node newNode(int key) { Node temp = new Node(); temp.key = key; temp.next = null; return temp; } // A utility function to print a linked list static void printList(Node head) { while (head != null) { Console.Write(head.key + \" \"); head = head.next; } Console.WriteLine(); } /*returns distance between first and last node every time * last node moves forwards*/ static int distance(Node first, Node last) { /*counts no of nodes between first and last*/ int counter = 0; Node curr; curr = first; while (curr != last) { counter += 1; curr = curr.next; } return counter + 1; } // Function to detect first node of loop // in a linked list that may contain loop static bool detectLoop(Node head) { // Create a temporary node Node temp = new Node(); Node first, last; /*first always points to head*/ first = head; /*last pointer initially points to head*/ last = head; /*current_length stores no of nodes between current * position of first and last*/ int current_length = 0; /*current_length stores no of nodes between previous * position of first and last*/ int prev_length = -1; while (current_length > prev_length && last != null) { // set prev_length to current length then update the // current length prev_length = current_length; // distance is calculated current_length = distance(first, last); // last node points the next node last = last.next; } if (last == null) { return false; } else { return true; } } /* Driver program to test above function*/ public static void Main(String[] args) { Node head = newNode(1); head.next = newNode(2); head.next.next = newNode(3); head.next.next.next = newNode(4); head.next.next.next.next = newNode(5); /* Create a loop for testing(5 is pointing to 3) */ head.next.next.next.next.next = head.next.next; bool found = detectLoop(head); if (found) Console.Write(\"Loop Found\"); else Console.Write(\"No Loop Found\"); }} // This code is contributed by gauravrajput1", "e": 71009, "s": 68679, "text": null }, { "code": "<script> // Javascript program to return first node of loopclass Node{ constructor(key) { this.key = key; this.next = null; }} function newNode(key){ let temp = new Node(key); return temp;} // A utility function to print a linked listfunction printList(head){ while (head != null) { document.write(head.key + \" \"); head = head.next; } document.write(\"</br>\");} /*returns distance between first and lastnode every time last node moves forwards*/function distance(first, last){ /*counts no of nodes between first and last*/ let counter = 0; let curr; curr = first; while (curr != last) { counter += 1; curr = curr.next; } return counter + 1;} // Function to detect first node of loop// in a linked list that may contain loopfunction detectLoop(head){ // Create a temporary node let temp = new Node(); let first, last; /*first always points to head*/ first = head; /*last pointer initially points to head*/ last = head; /*current_length stores no of nodes between current position of first and last*/ let current_length = 0; /*current_length stores no of nodes between previous position of first and last*/ let prev_length = -1; while (current_length > prev_length && last != null) { // Set prev_length to current length // then update the current length prev_length = current_length; // Distance is calculated current_length = distance(first, last); // Last node points the next node last = last.next; } if (last == null) { return false; } else { return true; }} // Driver codelet head = newNode(1);head.next = newNode(2);head.next.next = newNode(3);head.next.next.next = newNode(4);head.next.next.next.next = newNode(5); /* Create a loop for testing(5 is pointing to 3) */head.next.next.next.next.next = head.next.next;let found = detectLoop(head);if (found) document.write(\"Loop Found\");else document.write(\"No Loop Found\"); // This code is contributed by divyeshrabadiya07 </script>", "e": 73195, "s": 71009, "text": null }, { "code": null, "e": 73206, "s": 73195, "text": "Loop Found" }, { "code": null, "e": 73230, "s": 73206, "text": " Complexity Analysis: " }, { "code": null, "e": 73253, "s": 73230, "text": "Time complexity: O(n2)" }, { "code": null, "e": 73275, "s": 73253, "text": "Auxiliary Space: O(1)" }, { "code": null, "e": 73577, "s": 73275, "text": "This is the simplest approach of the given problem, the only thing we have to do is to assign a new value to each data of node in the linked list which is not in the range given.Example suppose (1 <= Data on Node <= 10^3) then after visiting node assign the data as -1 as it is out of the given range." }, { "code": null, "e": 73756, "s": 73577, "text": "This is the simplest approach of the given problem, the only thing we have to do is to assign a new value to each data of node in the linked list which is not in the range given." }, { "code": null, "e": 73880, "s": 73756, "text": "Example suppose (1 <= Data on Node <= 10^3) then after visiting node assign the data as -1 as it is out of the given range." }, { "code": null, "e": 73936, "s": 73880, "text": "Follow the code given below for a better understanding:" }, { "code": null, "e": 73940, "s": 73936, "text": "C++" }, { "code": null, "e": 73945, "s": 73940, "text": "Java" }, { "code": null, "e": 73953, "s": 73945, "text": "Python3" }, { "code": null, "e": 73956, "s": 73953, "text": "C#" }, { "code": null, "e": 73967, "s": 73956, "text": "Javascript" }, { "code": "// C++ program to return first node of loop#include <bits/stdc++.h>using namespace std; struct Node { int key; struct Node* next;}; Node* newNode(int key){ Node* temp = new Node; temp->key = key; temp->next = NULL; return temp;} // Function to detect first node of loop// in a linked list that may contain loopbool detectLoop(Node* head){ // If the head is null we will return false if (!head) return 0; else { // Traversing the linked list // for detecting loop while (head) { // If loop found if (head->key == -1) { return true; } // Changing the data of visited node to any // value which is outside th given range here it // is supposed the given range is (1 <= Data on // Node <= 10^3) else { head->key = -1; head = head->next; } } // If loop not found return false return 0; }} /* Driver program to test above function*/int main(){ Node* head = newNode(1); head->next = newNode(2); head->next->next = newNode(3); head->next->next->next = newNode(4); head->next->next->next->next = newNode(5); /* Create a loop for testing(5 is pointing to 3) */ head->next->next->next->next->next = head->next->next; bool found = detectLoop(head); cout << found << endl; return 0;}", "e": 75416, "s": 73967, "text": null }, { "code": "// Java program to return first node of loopimport java.util.*; class LinkedList{ // Head of liststatic Node head; // Linked list Nodestatic class Node{ int data; Node next; Node(int d) { data = d; next = null; }} /* Inserts a new Node at front of the list. */static public void push(int new_data){ /* 1 & 2: Allocate the Node & Put in the data*/ Node new_node = new Node(new_data); /* 3. Make next of new Node as head */ new_node.next = head; /* 4. Move the head to point to new Node */ head = new_node;} // Function to detect first node of loop// in a linked list that may contain loopstatic boolean detectLoop(Node h){ // If the head is null we will return false if (head == null) return false; else { // Traversing the linked list // for detecting loop while (head != null) { // If loop found if (head.data == -1) { return true; } // Changing the data of visited node to any // value which is outside th given range // here it is supposed the given range is (1 // <= Data on Node <= 10^3) else { head.data = -1; head = head.next; } } // If loop not found return false return false; }} // Driver Codepublic static void main(String[] args){ LinkedList llist = new LinkedList(); llist.push(1); llist.push(2); llist.push(3); llist.push(4); llist.push(5); /* Create a loop for testing */ llist.head.next.next.next.next.next = llist.head.next.next; if (detectLoop(llist.head)) System.out.println(\"1\"); else System.out.println(\"0\");}} // This code is contributed by RohitOberoi", "e": 77292, "s": 75416, "text": null }, { "code": "# Python program to return first node of loopclass Node: def __init__(self,d): self.data = d self.next = None head = Nonedef push(new_data): global head new_node = Node(new_data) new_node.next = head head=new_node def detectLoop(h): global head if (head == None): return False else: while (head != None): if (head.data == -1): return True else: head.data = -1 head = head.next return False push(1);push(2);push(3);push(4);push(5); head.next.next.next.next.next = head.next.next if (detectLoop(head)): print(\"1\")else: print(\"0\") # This code is contributed by patel2127.", "e": 78024, "s": 77292, "text": null }, { "code": "// C# program to return first node of loop using System; public class Node{ public int data; public Node next; public Node(int d) { data = d; next = null; }} public class GFG{ // Head of liststatic Node head; /* Inserts a new Node at front of the list. */static public void push(int new_data){ /* 1 & 2: Allocate the Node & Put in the data*/ Node new_node = new Node(new_data); /* 3. Make next of new Node as head */ new_node.next = head; /* 4. Move the head to point to new Node */ head = new_node;} // Function to detect first node of loop// in a linked list that may contain loopstatic bool detectLoop(Node h){ // If the head is null we will return false if (head == null) return false; else { // Traversing the linked list // for detecting loop while (head != null) { // If loop found if (head.data == -1) { return true; } // Changing the data of visited node to any // value which is outside th given range // here it is supposed the given range is (1 // <= Data on Node <= 10^3) else { head.data = -1; head = head.next; } } // If loop not found return false return false; }} // Driver Code static public void Main (){ push(1); push(2); push(3); push(4); push(5); /* Create a loop for testing */ head.next.next.next.next.next = head.next.next; if (detectLoop(head)) Console.WriteLine(\"1\"); else Console.WriteLine(\"0\"); }}", "e": 79815, "s": 78024, "text": null }, { "code": "<script>// Javascript program to return first node of loop// Linked list Nodeclass Node{ constructor(d) { this.data = d; this.next = null; }} // Head of listlet head; /* Inserts a new Node at front of the list. */function push(new_data){ /* 1 & 2: Allocate the Node & Put in the data*/ let new_node = new Node(new_data); /* 3. Make next of new Node as head */ new_node.next = head; /* 4. Move the head to point to new Node */ head = new_node;} // Function to detect first node of loop// in a linked list that may contain loopfunction detectLoop(h){ // If the head is null we will return false if (head == null) return false; else { // Traversing the linked list // for detecting loop while (head != null) { // If loop found if (head.data == -1) { return true; } // Changing the data of visited node to any // value which is outside th given range // here it is supposed the given range is (1 // <= Data on Node <= 10^3) else { head.data = -1; head = head.next; } } // If loop not found return false return false; }} // Driver Codepush(1);push(2);push(3);push(4);push(5); /* Create a loop for testing */head.next.next.next.next.next = head.next.next; if (detectLoop(head)) document.write(\"1\");else document.write(\"0\"); // This code is contributed by unknown2108</script>", "e": 81422, "s": 79815, "text": null }, { "code": null, "e": 81424, "s": 81422, "text": "1" }, { "code": null, "e": 81446, "s": 81424, "text": "Time Complexity: O(N)" }, { "code": null, "e": 81468, "s": 81446, "text": "Auxiliary Space: O(1)" }, { "code": null, "e": 81593, "s": 81468, "text": "Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above." }, { "code": null, "e": 81605, "s": 81593, "text": "PrasadPawar" }, { "code": null, "e": 81617, "s": 81605, "text": "ashwinvivek" }, { "code": null, "e": 81633, "s": 81617, "text": "purnasrivatsa96" }, { "code": null, "e": 81645, "s": 81633, "text": "29AjayKumar" }, { "code": null, "e": 81659, "s": 81645, "text": "rathbhupendra" }, { "code": null, "e": 81670, "s": 81659, "text": "andrew1234" }, { "code": null, "e": 81683, "s": 81670, "text": "Akanksha_Rai" }, { "code": null, "e": 81696, "s": 81683, "text": "princi singh" }, { "code": null, "e": 81711, "s": 81696, "text": "SHUBHAMSINGH10" }, { "code": null, "e": 81722, "s": 81711, "text": "nidhi_biet" }, { "code": null, "e": 81731, "s": 81722, "text": "prakhar7" }, { "code": null, "e": 81740, "s": 81731, "text": "rgndunes" }, { "code": null, "e": 81750, "s": 81740, "text": "nesher123" }, { "code": null, "e": 81760, "s": 81750, "text": "rutvik_56" }, { "code": null, "e": 81770, "s": 81760, "text": "Rajput-Ji" }, { "code": null, "e": 81780, "s": 81770, "text": "pratham76" }, { "code": null, "e": 81794, "s": 81780, "text": "GauravRajput1" }, { "code": null, "e": 81802, "s": 81794, "text": "us19018" }, { "code": null, "e": 81814, "s": 81802, "text": "RohitOberoi" }, { "code": null, "e": 81827, "s": 81814, "text": "todaysgaurav" }, { "code": null, "e": 81835, "s": 81827, "text": "rag2127" }, { "code": null, "e": 81856, "s": 81835, "text": "avanitrachhadiya2155" }, { "code": null, "e": 81863, "s": 81856, "text": "ab2127" }, { "code": null, "e": 81881, "s": 81863, "text": "divyeshrabadiya07" }, { "code": null, "e": 81893, "s": 81881, "text": "unknown2108" }, { "code": null, "e": 81903, "s": 81893, "text": "patel2127" }, { "code": null, "e": 81919, "s": 81903, "text": "simranarora5sos" }, { "code": null, "e": 81927, "s": 81919, "text": "ihritik" }, { "code": null, "e": 81936, "s": 81927, "text": "arn0dian" }, { "code": null, "e": 81947, "s": 81936, "text": "parthc2002" }, { "code": null, "e": 81964, "s": 81947, "text": "surinderdawra388" }, { "code": null, "e": 81978, "s": 81964, "text": "sumitgumber28" }, { "code": null, "e": 81993, "s": 81978, "text": "adityakumar129" }, { "code": null, "e": 82002, "s": 81993, "text": "Accolite" }, { "code": null, "e": 82009, "s": 82002, "text": "Amazon" }, { "code": null, "e": 82022, "s": 82009, "text": "Linked Lists" }, { "code": null, "e": 82027, "s": 82022, "text": "loop" }, { "code": null, "e": 82040, "s": 82027, "text": "MAQ Software" }, { "code": null, "e": 82048, "s": 82040, "text": "Samsung" }, { "code": null, "e": 82071, "s": 82048, "text": "Tortoise-Hare-Approach" }, { "code": null, "e": 82083, "s": 82071, "text": "Linked List" }, { "code": null, "e": 82092, "s": 82083, "text": "Accolite" }, { "code": null, "e": 82099, "s": 82092, "text": "Amazon" }, { "code": null, "e": 82107, "s": 82099, "text": "Samsung" }, { "code": null, "e": 82120, "s": 82107, "text": "MAQ Software" }, { "code": null, "e": 82132, "s": 82120, "text": "Linked List" }, { "code": null, "e": 82230, "s": 82132, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 82276, "s": 82230, "text": "Delete a Linked List node at a given position" }, { "code": null, "e": 82319, "s": 82276, "text": "Implement a stack using singly linked list" }, { "code": null, "e": 82354, "s": 82319, "text": "Queue - Linked List Implementation" }, { "code": null, "e": 82401, "s": 82354, "text": "Implementing a Linked List in Java using Class" }, { "code": null, "e": 82462, "s": 82401, "text": "Circular Linked List | Set 1 (Introduction and Applications)" }, { "code": null, "e": 82506, "s": 82462, "text": "Remove duplicates from a sorted linked list" }, { "code": null, "e": 82562, "s": 82506, "text": "Function to check if a singly linked list is palindrome" }, { "code": null, "e": 82600, "s": 82562, "text": "Top 20 Linked List Interview Question" }, { "code": null, "e": 82655, "s": 82600, "text": "Find Length of a Linked List (Iterative and Recursive)" } ]
Date manipulating functions in SQL - GeeksforGeeks
21 Oct, 2020 To manipulate and fetch date values from the table, oracle has inbuilt date functions. Here, we are going to coverDate manipulating functions in SQL. ADD_MONTHS :It will add the total number of months specified in n to the date parameter and Returns date.Syntax :ADD_MONTHS(d, n)Example –Select ADD_MONTHS(SYSDATE, 4) "Add months" from dual; Output :Add Months 01-NOV-04 LAST_DAY :In the LAST_DAY function, It will return the last date of the month, and for the specified month like if the system date is 1 Nov then it will return 30 Nov.Syntax :LAST_DAY(date)Example-Select SYSDATE, LAST_DAY(SYSDATE) "Last Day" from dual; Output :SYSDATE Last Day 01-NOV-04 30-NOV-04 MONTHS_BETWEEN :Returns number of months between date1 and date2.Syntax :MONTHS_BETWEEN(date1, date2)Example –Select MONTHS_BETWEEN('02-FEB-00', '01-JAN-00') "Months" from dual; Output :Months 1 NEXT_DAY :It will return the date of the first weekday that comes after the date specified in date parameter. char specified should be someday of the week.Syntax :NEXT_DAY(date, char)Example –SELECT NEXT_DAY('06-JUL-02', 'saturday') "Next day" from dual; here it returns the date of next saturday.Output :Next day 13-JUL-02 NEW_TIME :Returns the date after converting it from time zone 1 to a date in time zone 2.Syntax :NEW_TIME(date, zone1, zone2)ValueDescriptionValueDescriptionASTAtlantic Standard TimeADTAtlantic Daylight TimeBSTBering Standard TimeBDTBering daylight TimeCSTCentral Standard TimeCDTCentral daylightTimeGMTGreenwich Mean TimeNSTNewfoundland standard timeHDTAlaska -Hawaii daylight TimeHSTAlaska -Hawaii standard TimeMDTMountain daylight TimeMSTMountain standard TimePSTpacific standard TimePDTpacific daylight TimeExample –Select NEW_TIME(To_date('2004/07/01 01:45', 'yyyy/mm/dd HH24:MI'), 'AST', 'MST') "MST" from dual; Output :MST 30-JUN-04 This converts an Atlantic standard time into mountain standard time. ADD_MONTHS :It will add the total number of months specified in n to the date parameter and Returns date.Syntax :ADD_MONTHS(d, n)Example –Select ADD_MONTHS(SYSDATE, 4) "Add months" from dual; Output :Add Months 01-NOV-04 Syntax : ADD_MONTHS(d, n) Example – Select ADD_MONTHS(SYSDATE, 4) "Add months" from dual; Output : Add Months 01-NOV-04 LAST_DAY :In the LAST_DAY function, It will return the last date of the month, and for the specified month like if the system date is 1 Nov then it will return 30 Nov.Syntax :LAST_DAY(date)Example-Select SYSDATE, LAST_DAY(SYSDATE) "Last Day" from dual; Output :SYSDATE Last Day 01-NOV-04 30-NOV-04 Syntax : LAST_DAY(date) Example- Select SYSDATE, LAST_DAY(SYSDATE) "Last Day" from dual; Output : SYSDATE Last Day 01-NOV-04 30-NOV-04 MONTHS_BETWEEN :Returns number of months between date1 and date2.Syntax :MONTHS_BETWEEN(date1, date2)Example –Select MONTHS_BETWEEN('02-FEB-00', '01-JAN-00') "Months" from dual; Output :Months 1 Syntax : MONTHS_BETWEEN(date1, date2) Example – Select MONTHS_BETWEEN('02-FEB-00', '01-JAN-00') "Months" from dual; Output : Months 1 NEXT_DAY :It will return the date of the first weekday that comes after the date specified in date parameter. char specified should be someday of the week.Syntax :NEXT_DAY(date, char)Example –SELECT NEXT_DAY('06-JUL-02', 'saturday') "Next day" from dual; here it returns the date of next saturday.Output :Next day 13-JUL-02 Syntax : NEXT_DAY(date, char) Example – SELECT NEXT_DAY('06-JUL-02', 'saturday') "Next day" from dual; here it returns the date of next saturday.Output : Next day 13-JUL-02 NEW_TIME :Returns the date after converting it from time zone 1 to a date in time zone 2.Syntax :NEW_TIME(date, zone1, zone2)ValueDescriptionValueDescriptionASTAtlantic Standard TimeADTAtlantic Daylight TimeBSTBering Standard TimeBDTBering daylight TimeCSTCentral Standard TimeCDTCentral daylightTimeGMTGreenwich Mean TimeNSTNewfoundland standard timeHDTAlaska -Hawaii daylight TimeHSTAlaska -Hawaii standard TimeMDTMountain daylight TimeMSTMountain standard TimePSTpacific standard TimePDTpacific daylight TimeExample –Select NEW_TIME(To_date('2004/07/01 01:45', 'yyyy/mm/dd HH24:MI'), 'AST', 'MST') "MST" from dual; Output :MST 30-JUN-04 This converts an Atlantic standard time into mountain standard time. Syntax : NEW_TIME(date, zone1, zone2) Example – Select NEW_TIME(To_date('2004/07/01 01:45', 'yyyy/mm/dd HH24:MI'), 'AST', 'MST') "MST" from dual; Output : MST 30-JUN-04 This converts an Atlantic standard time into mountain standard time. DBMS-SQL SQL SQL Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to Update Multiple Columns in Single Update Statement in SQL? SQL | Subquery How to Create a Table With Multiple Foreign Keys in SQL? What is Temporary Table in SQL? SQL Query to Find the Name of a Person Whose Name Starts with Specific Letter SQL using Python SQL Query to Convert VARCHAR to INT How to Write a SQL Query For a Specific Date Range and Date Time? How to Select Data Between Two Dates and Times in SQL Server? SQL Query to Compare Two Dates
[ { "code": null, "e": 25513, "s": 25485, "text": "\n21 Oct, 2020" }, { "code": null, "e": 25663, "s": 25513, "text": "To manipulate and fetch date values from the table, oracle has inbuilt date functions. Here, we are going to coverDate manipulating functions in SQL." }, { "code": null, "e": 27444, "s": 25663, "text": "ADD_MONTHS :It will add the total number of months specified in n to the date parameter and Returns date.Syntax :ADD_MONTHS(d, n)Example –Select ADD_MONTHS(SYSDATE, 4) \n\"Add months\" from dual;\nOutput :Add Months\n01-NOV-04\nLAST_DAY :In the LAST_DAY function, It will return the last date of the month, and for the specified month like if the system date is 1 Nov then it will return 30 Nov.Syntax :LAST_DAY(date)Example-Select SYSDATE, LAST_DAY(SYSDATE) \n\"Last Day\" from dual;\nOutput :SYSDATE Last Day\n01-NOV-04 30-NOV-04\nMONTHS_BETWEEN :Returns number of months between date1 and date2.Syntax :MONTHS_BETWEEN(date1, date2)Example –Select MONTHS_BETWEEN('02-FEB-00', '01-JAN-00') \n\"Months\" from dual;\nOutput :Months\n 1\nNEXT_DAY :It will return the date of the first weekday that comes after the date specified in date parameter. char specified should be someday of the week.Syntax :NEXT_DAY(date, char)Example –SELECT NEXT_DAY('06-JUL-02', 'saturday') \n\"Next day\" from dual;\nhere it returns the date of next saturday.Output :Next day\n13-JUL-02\nNEW_TIME :Returns the date after converting it from time zone 1 to a date in time zone 2.Syntax :NEW_TIME(date, zone1, zone2)ValueDescriptionValueDescriptionASTAtlantic Standard TimeADTAtlantic Daylight TimeBSTBering Standard TimeBDTBering daylight TimeCSTCentral Standard TimeCDTCentral daylightTimeGMTGreenwich Mean TimeNSTNewfoundland standard timeHDTAlaska -Hawaii daylight TimeHSTAlaska -Hawaii standard TimeMDTMountain daylight TimeMSTMountain standard TimePSTpacific standard TimePDTpacific daylight TimeExample –Select NEW_TIME(To_date('2004/07/01 01:45', 'yyyy/mm/dd HH24:MI'), \n'AST', 'MST') \"MST\" from dual;\nOutput :MST\n30-JUN-04\nThis converts an Atlantic standard time into mountain standard time." }, { "code": null, "e": 27667, "s": 27444, "text": "ADD_MONTHS :It will add the total number of months specified in n to the date parameter and Returns date.Syntax :ADD_MONTHS(d, n)Example –Select ADD_MONTHS(SYSDATE, 4) \n\"Add months\" from dual;\nOutput :Add Months\n01-NOV-04\n" }, { "code": null, "e": 27676, "s": 27667, "text": "Syntax :" }, { "code": null, "e": 27693, "s": 27676, "text": "ADD_MONTHS(d, n)" }, { "code": null, "e": 27703, "s": 27693, "text": "Example –" }, { "code": null, "e": 27759, "s": 27703, "text": "Select ADD_MONTHS(SYSDATE, 4) \n\"Add months\" from dual;\n" }, { "code": null, "e": 27768, "s": 27759, "text": "Output :" }, { "code": null, "e": 27790, "s": 27768, "text": "Add Months\n01-NOV-04\n" }, { "code": null, "e": 28117, "s": 27790, "text": "LAST_DAY :In the LAST_DAY function, It will return the last date of the month, and for the specified month like if the system date is 1 Nov then it will return 30 Nov.Syntax :LAST_DAY(date)Example-Select SYSDATE, LAST_DAY(SYSDATE) \n\"Last Day\" from dual;\nOutput :SYSDATE Last Day\n01-NOV-04 30-NOV-04\n" }, { "code": null, "e": 28126, "s": 28117, "text": "Syntax :" }, { "code": null, "e": 28141, "s": 28126, "text": "LAST_DAY(date)" }, { "code": null, "e": 28150, "s": 28141, "text": "Example-" }, { "code": null, "e": 28208, "s": 28150, "text": "Select SYSDATE, LAST_DAY(SYSDATE) \n\"Last Day\" from dual;\n" }, { "code": null, "e": 28217, "s": 28208, "text": "Output :" }, { "code": null, "e": 28282, "s": 28217, "text": "SYSDATE Last Day\n01-NOV-04 30-NOV-04\n" }, { "code": null, "e": 28481, "s": 28282, "text": "MONTHS_BETWEEN :Returns number of months between date1 and date2.Syntax :MONTHS_BETWEEN(date1, date2)Example –Select MONTHS_BETWEEN('02-FEB-00', '01-JAN-00') \n\"Months\" from dual;\nOutput :Months\n 1\n" }, { "code": null, "e": 28490, "s": 28481, "text": "Syntax :" }, { "code": null, "e": 28519, "s": 28490, "text": "MONTHS_BETWEEN(date1, date2)" }, { "code": null, "e": 28529, "s": 28519, "text": "Example –" }, { "code": null, "e": 28599, "s": 28529, "text": "Select MONTHS_BETWEEN('02-FEB-00', '01-JAN-00') \n\"Months\" from dual;\n" }, { "code": null, "e": 28608, "s": 28599, "text": "Output :" }, { "code": null, "e": 28620, "s": 28608, "text": "Months\n 1\n" }, { "code": null, "e": 28946, "s": 28620, "text": "NEXT_DAY :It will return the date of the first weekday that comes after the date specified in date parameter. char specified should be someday of the week.Syntax :NEXT_DAY(date, char)Example –SELECT NEXT_DAY('06-JUL-02', 'saturday') \n\"Next day\" from dual;\nhere it returns the date of next saturday.Output :Next day\n13-JUL-02\n" }, { "code": null, "e": 28955, "s": 28946, "text": "Syntax :" }, { "code": null, "e": 28976, "s": 28955, "text": "NEXT_DAY(date, char)" }, { "code": null, "e": 28986, "s": 28976, "text": "Example –" }, { "code": null, "e": 29051, "s": 28986, "text": "SELECT NEXT_DAY('06-JUL-02', 'saturday') \n\"Next day\" from dual;\n" }, { "code": null, "e": 29102, "s": 29051, "text": "here it returns the date of next saturday.Output :" }, { "code": null, "e": 29122, "s": 29102, "text": "Next day\n13-JUL-02\n" }, { "code": null, "e": 29832, "s": 29122, "text": "NEW_TIME :Returns the date after converting it from time zone 1 to a date in time zone 2.Syntax :NEW_TIME(date, zone1, zone2)ValueDescriptionValueDescriptionASTAtlantic Standard TimeADTAtlantic Daylight TimeBSTBering Standard TimeBDTBering daylight TimeCSTCentral Standard TimeCDTCentral daylightTimeGMTGreenwich Mean TimeNSTNewfoundland standard timeHDTAlaska -Hawaii daylight TimeHSTAlaska -Hawaii standard TimeMDTMountain daylight TimeMSTMountain standard TimePSTpacific standard TimePDTpacific daylight TimeExample –Select NEW_TIME(To_date('2004/07/01 01:45', 'yyyy/mm/dd HH24:MI'), \n'AST', 'MST') \"MST\" from dual;\nOutput :MST\n30-JUN-04\nThis converts an Atlantic standard time into mountain standard time." }, { "code": null, "e": 29841, "s": 29832, "text": "Syntax :" }, { "code": null, "e": 29870, "s": 29841, "text": "NEW_TIME(date, zone1, zone2)" }, { "code": null, "e": 29880, "s": 29870, "text": "Example –" }, { "code": null, "e": 29980, "s": 29880, "text": "Select NEW_TIME(To_date('2004/07/01 01:45', 'yyyy/mm/dd HH24:MI'), \n'AST', 'MST') \"MST\" from dual;\n" }, { "code": null, "e": 29989, "s": 29980, "text": "Output :" }, { "code": null, "e": 30004, "s": 29989, "text": "MST\n30-JUN-04\n" }, { "code": null, "e": 30073, "s": 30004, "text": "This converts an Atlantic standard time into mountain standard time." }, { "code": null, "e": 30082, "s": 30073, "text": "DBMS-SQL" }, { "code": null, "e": 30086, "s": 30082, "text": "SQL" }, { "code": null, "e": 30090, "s": 30086, "text": "SQL" }, { "code": null, "e": 30188, "s": 30090, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 30254, "s": 30188, "text": "How to Update Multiple Columns in Single Update Statement in SQL?" }, { "code": null, "e": 30269, "s": 30254, "text": "SQL | Subquery" }, { "code": null, "e": 30326, "s": 30269, "text": "How to Create a Table With Multiple Foreign Keys in SQL?" }, { "code": null, "e": 30358, "s": 30326, "text": "What is Temporary Table in SQL?" }, { "code": null, "e": 30436, "s": 30358, "text": "SQL Query to Find the Name of a Person Whose Name Starts with Specific Letter" }, { "code": null, "e": 30453, "s": 30436, "text": "SQL using Python" }, { "code": null, "e": 30489, "s": 30453, "text": "SQL Query to Convert VARCHAR to INT" }, { "code": null, "e": 30555, "s": 30489, "text": "How to Write a SQL Query For a Specific Date Range and Date Time?" }, { "code": null, "e": 30617, "s": 30555, "text": "How to Select Data Between Two Dates and Times in SQL Server?" } ]
System Bus Design - GeeksforGeeks
22 Mar, 2021 Definition: The electrically conducting path along which data is transmitted inside any digital electronic device. A Computer bus consists of a set of parallel conductors, which may be conventional wires, copper tracks on a PRINTED CIRCUIT BOARD, or microscopic aluminum trails on the surface of a silicon chip. Each wire carries just one bit, so the number of wires determines the largest data WORD the bus can transmit: a bus with eight wires can carry only 8- bit data words, and hence defines the device as an 8-bit device. The bus is a communication channel. The characteristic of the bus is shared transmission media. The limitation of a bus is only one transmission at a time. A bus which is used to provide communication between the major components of a computer is called a System bus. Computer: System bus contains 3 categories of lines used to provide the communication between the CPU, memory and IO named as: 1. Address lines (AL) 2. Data lines (DL) 3. Control lines (CL) 1. Address Lines: Used to carry the address to memory and IO. Unidirectional. Based on width of a address bus we can determine the capacity of a main memory Example: 2. Data Lines: Used to carry the binary data between the CPU, memory and IO. Bidirectional. Based on the width of a data bus we can determine the word length of a CPU. Based on the word length we can determine the performance of a CPU. Example: 3. Control Lines: Used to carry the control signals and timing signals Control signals indicates type of operation. Timing Signals used to synchronize the memory and IO operations with a CPU clock. toshnaw2 chauhandeepakdc9 Computer Organization & Architecture GATE CS Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Logical and Physical Address in Operating System Computer Organization and Architecture | Pipelining | Set 1 (Execution, Stages and Throughput) Memory Hierarchy Design and its Characteristics Computer Organization | RISC and CISC Direct Access Media (DMA) Controller in Computer Architecture Layers of OSI Model ACID Properties in DBMS TCP/IP Model Types of Operating Systems Normal Forms in DBMS
[ { "code": null, "e": 25868, "s": 25840, "text": "\n22 Mar, 2021" }, { "code": null, "e": 25881, "s": 25868, "text": "Definition: " }, { "code": null, "e": 26398, "s": 25881, "text": "The electrically conducting path along which data is transmitted inside any digital electronic device. A Computer bus consists of a set of parallel conductors, which may be conventional wires, copper tracks on a PRINTED CIRCUIT BOARD, or microscopic aluminum trails on the surface of a silicon chip. Each wire carries just one bit, so the number of wires determines the largest data WORD the bus can transmit: a bus with eight wires can carry only 8- bit data words, and hence defines the device as an 8-bit device. " }, { "code": null, "e": 26434, "s": 26398, "text": "The bus is a communication channel." }, { "code": null, "e": 26494, "s": 26434, "text": "The characteristic of the bus is shared transmission media." }, { "code": null, "e": 26554, "s": 26494, "text": "The limitation of a bus is only one transmission at a time." }, { "code": null, "e": 26666, "s": 26554, "text": "A bus which is used to provide communication between the major components of a computer is called a System bus." }, { "code": null, "e": 26677, "s": 26666, "text": "Computer: " }, { "code": null, "e": 26798, "s": 26679, "text": "System bus contains 3 categories of lines used to provide the communication between the CPU, memory and IO named as: " }, { "code": null, "e": 26862, "s": 26798, "text": "1. Address lines (AL)\n2. Data lines (DL)\n3. Control lines (CL) " }, { "code": null, "e": 26882, "s": 26862, "text": "1. Address Lines: " }, { "code": null, "e": 26926, "s": 26882, "text": "Used to carry the address to memory and IO." }, { "code": null, "e": 26942, "s": 26926, "text": "Unidirectional." }, { "code": null, "e": 27021, "s": 26942, "text": "Based on width of a address bus we can determine the capacity of a main memory" }, { "code": null, "e": 27031, "s": 27021, "text": "Example: " }, { "code": null, "e": 27052, "s": 27035, "text": "2. Data Lines: " }, { "code": null, "e": 27114, "s": 27052, "text": "Used to carry the binary data between the CPU, memory and IO." }, { "code": null, "e": 27129, "s": 27114, "text": "Bidirectional." }, { "code": null, "e": 27205, "s": 27129, "text": "Based on the width of a data bus we can determine the word length of a CPU." }, { "code": null, "e": 27273, "s": 27205, "text": "Based on the word length we can determine the performance of a CPU." }, { "code": null, "e": 27283, "s": 27273, "text": "Example: " }, { "code": null, "e": 27307, "s": 27287, "text": "3. Control Lines: " }, { "code": null, "e": 27360, "s": 27307, "text": "Used to carry the control signals and timing signals" }, { "code": null, "e": 27405, "s": 27360, "text": "Control signals indicates type of operation." }, { "code": null, "e": 27487, "s": 27405, "text": "Timing Signals used to synchronize the memory and IO operations with a CPU clock." }, { "code": null, "e": 27498, "s": 27489, "text": "toshnaw2" }, { "code": null, "e": 27515, "s": 27498, "text": "chauhandeepakdc9" }, { "code": null, "e": 27552, "s": 27515, "text": "Computer Organization & Architecture" }, { "code": null, "e": 27560, "s": 27552, "text": "GATE CS" }, { "code": null, "e": 27658, "s": 27560, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 27707, "s": 27658, "text": "Logical and Physical Address in Operating System" }, { "code": null, "e": 27802, "s": 27707, "text": "Computer Organization and Architecture | Pipelining | Set 1 (Execution, Stages and Throughput)" }, { "code": null, "e": 27850, "s": 27802, "text": "Memory Hierarchy Design and its Characteristics" }, { "code": null, "e": 27888, "s": 27850, "text": "Computer Organization | RISC and CISC" }, { "code": null, "e": 27950, "s": 27888, "text": "Direct Access Media (DMA) Controller in Computer Architecture" }, { "code": null, "e": 27970, "s": 27950, "text": "Layers of OSI Model" }, { "code": null, "e": 27994, "s": 27970, "text": "ACID Properties in DBMS" }, { "code": null, "e": 28007, "s": 27994, "text": "TCP/IP Model" }, { "code": null, "e": 28034, "s": 28007, "text": "Types of Operating Systems" } ]
std::adjacent_find in C++ - GeeksforGeeks
20 Aug, 2021 Searches the range [first, last) for the first occurrence of two consecutive elements that match, and returns an iterator to the first of these two elements, or last if no such pair is found. Elements are compared using the given binary predicate p or using ==. There are two possible implementations of the function as given below: 1. Without binary predicate: ForwardIt adjacent_find( ForwardIt first, ForwardIt last ); first, last : the range of elements to examine Example : Given a sorted array of n elements containing all unique elements but one, the task is to find the repeating element in the array. Examples: Input : arr[] = { 1, 2, 3, 4, 4} Output : 4 Input : arr[] = { 1, 1, 2, 3, 4} Output : 1 We have discussed this problem with other approaches here. C++ // C++ Program to find the only// repeating element in sorted array// using std :: adjacent_find// without predicate#include <iostream>#include <algorithm> int main(){ // Sorted Array with a repeated element int A[] = { 10, 13, 16, 16, 18 }; // Size of the array int n = sizeof(A) / sizeof(A[0]); // Iterator pointer which points to the address of the repeated element int* it = std::adjacent_find(A, A + n); // Printing the result std::cout << *it;} Output: 16 2. With binary predicate: ForwardIt adjacent_find( ForwardIt first, ForwardIt last, BinaryPredicate p ); first, last : the range of elements to examine p : binary predicate which returns true if the elements should be treated as equal. Return value : An iterator to the first of the first pair of identical elements, ' that is, the first iterator it such that *it == *(it+1) for the first version or p(*it, *(it + 1)) != false for the second version. If no such elements are found, last is returned. Example: Given a container of size n, and a range between [0 ... n], write a program to check if it is sorted in ascending order or not. Equal values are allowed in array and two consecutive equal values are considered sorted. Input : 2 5 9 4 // Range = 3 Output : Sorted in given range. Input : 3 5 1 9 // Range = 3 Output : Not sorted in given range. C++ // CPP program to illustrate// std :: adjacent_find'// with binary predicate#include <algorithm>#include <iostream>#include <vector> int main(){ std::vector<int> vec{ 0, 1, 2, 5, 40, 40, 41, 41, 5 }; // Index 0 to 4 int range1 = 5; // Index 0 to 8 int range2 = 9; std::vector<int>::iterator it; // Iterating from 0 to range1, // till we get a decreasing element it = std::adjacent_find(vec.begin(), vec.begin() + range1, std::greater<int>()); if (it == vec.begin() + range1) { std::cout << "Sorted in the range : " << range1 << std::endl; } else { std::cout << "Not sorted in the range : " << range1 << std::endl; } // Iterating from 0 to range2, // till we get a decreasing element it = std::adjacent_find(vec.begin(), vec.begin() + range2, std::greater<int>()); if (it == vec.begin() + range2) { std::cout << "Sorted in the range : " << range2 << std::endl; } else { std::cout << "Not sorted in the range : " << range2 << std::endl; }} Output: Sorted in the range : 5 Not sorted in the range : 9 This article is contributed by Rohit Thapliyal. 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. arorakashish0911 cpp-algorithm-library STL C++ STL CPP Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Inheritance in C++ Map in C++ Standard Template Library (STL) Bitwise Operators in C/C++ C++ Classes and Objects Virtual Function in C++ Operator Overloading in C++ Templates in C++ with Examples Constructors in C++ vector erase() and clear() in C++ Socket Programming in C/C++
[ { "code": null, "e": 25645, "s": 25617, "text": "\n20 Aug, 2021" }, { "code": null, "e": 25979, "s": 25645, "text": "Searches the range [first, last) for the first occurrence of two consecutive elements that match, and returns an iterator to the first of these two elements, or last if no such pair is found. Elements are compared using the given binary predicate p or using ==. There are two possible implementations of the function as given below: " }, { "code": null, "e": 26009, "s": 25979, "text": "1. Without binary predicate: " }, { "code": null, "e": 26116, "s": 26009, "text": "ForwardIt adjacent_find( ForwardIt first, ForwardIt last );\nfirst, last : the range of elements to examine" }, { "code": null, "e": 26258, "s": 26116, "text": "Example : Given a sorted array of n elements containing all unique elements but one, the task is to find the repeating element in the array. " }, { "code": null, "e": 26269, "s": 26258, "text": "Examples: " }, { "code": null, "e": 26362, "s": 26269, "text": "Input : arr[] = { 1, 2, 3, 4, 4}\nOutput : 4\n\nInput : arr[] = { 1, 1, 2, 3, 4}\nOutput : 1" }, { "code": null, "e": 26421, "s": 26362, "text": "We have discussed this problem with other approaches here." }, { "code": null, "e": 26425, "s": 26421, "text": "C++" }, { "code": "// C++ Program to find the only// repeating element in sorted array// using std :: adjacent_find// without predicate#include <iostream>#include <algorithm> int main(){ // Sorted Array with a repeated element int A[] = { 10, 13, 16, 16, 18 }; // Size of the array int n = sizeof(A) / sizeof(A[0]); // Iterator pointer which points to the address of the repeated element int* it = std::adjacent_find(A, A + n); // Printing the result std::cout << *it;}", "e": 26903, "s": 26425, "text": null }, { "code": null, "e": 26912, "s": 26903, "text": "Output: " }, { "code": null, "e": 26915, "s": 26912, "text": "16" }, { "code": null, "e": 26942, "s": 26915, "text": "2. With binary predicate: " }, { "code": null, "e": 27421, "s": 26942, "text": "ForwardIt adjacent_find( ForwardIt first, ForwardIt last, BinaryPredicate p );\nfirst, last : the range of elements to examine\np : binary predicate which returns true \nif the elements should be treated as equal. \n\nReturn value :\nAn iterator to the first of the first pair of identical elements, '\nthat is, the first iterator it such that *it == *(it+1) for the first \nversion or p(*it, *(it + 1)) != false for the second version.\nIf no such elements are found, last is returned." }, { "code": null, "e": 27649, "s": 27421, "text": "Example: Given a container of size n, and a range between [0 ... n], write a program to check if it is sorted in ascending order or not. Equal values are allowed in array and two consecutive equal values are considered sorted. " }, { "code": null, "e": 27785, "s": 27649, "text": "Input : 2 5 9 4 // Range = 3\nOutput : Sorted in given range.\n\nInput : 3 5 1 9 // Range = 3\nOutput : Not sorted in given range." }, { "code": null, "e": 27789, "s": 27785, "text": "C++" }, { "code": "// CPP program to illustrate// std :: adjacent_find'// with binary predicate#include <algorithm>#include <iostream>#include <vector> int main(){ std::vector<int> vec{ 0, 1, 2, 5, 40, 40, 41, 41, 5 }; // Index 0 to 4 int range1 = 5; // Index 0 to 8 int range2 = 9; std::vector<int>::iterator it; // Iterating from 0 to range1, // till we get a decreasing element it = std::adjacent_find(vec.begin(), vec.begin() + range1, std::greater<int>()); if (it == vec.begin() + range1) { std::cout << \"Sorted in the range : \" << range1 << std::endl; } else { std::cout << \"Not sorted in the range : \" << range1 << std::endl; } // Iterating from 0 to range2, // till we get a decreasing element it = std::adjacent_find(vec.begin(), vec.begin() + range2, std::greater<int>()); if (it == vec.begin() + range2) { std::cout << \"Sorted in the range : \" << range2 << std::endl; } else { std::cout << \"Not sorted in the range : \" << range2 << std::endl; }}", "e": 28890, "s": 27789, "text": null }, { "code": null, "e": 28899, "s": 28890, "text": "Output: " }, { "code": null, "e": 28951, "s": 28899, "text": "Sorted in the range : 5\nNot sorted in the range : 9" }, { "code": null, "e": 29375, "s": 28951, "text": "This article is contributed by Rohit Thapliyal. 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": 29392, "s": 29375, "text": "arorakashish0911" }, { "code": null, "e": 29414, "s": 29392, "text": "cpp-algorithm-library" }, { "code": null, "e": 29418, "s": 29414, "text": "STL" }, { "code": null, "e": 29422, "s": 29418, "text": "C++" }, { "code": null, "e": 29426, "s": 29422, "text": "STL" }, { "code": null, "e": 29430, "s": 29426, "text": "CPP" }, { "code": null, "e": 29528, "s": 29430, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 29547, "s": 29528, "text": "Inheritance in C++" }, { "code": null, "e": 29590, "s": 29547, "text": "Map in C++ Standard Template Library (STL)" }, { "code": null, "e": 29617, "s": 29590, "text": "Bitwise Operators in C/C++" }, { "code": null, "e": 29641, "s": 29617, "text": "C++ Classes and Objects" }, { "code": null, "e": 29665, "s": 29641, "text": "Virtual Function in C++" }, { "code": null, "e": 29693, "s": 29665, "text": "Operator Overloading in C++" }, { "code": null, "e": 29724, "s": 29693, "text": "Templates in C++ with Examples" }, { "code": null, "e": 29744, "s": 29724, "text": "Constructors in C++" }, { "code": null, "e": 29778, "s": 29744, "text": "vector erase() and clear() in C++" } ]
Artificial Intelligence - Temporal Logic - GeeksforGeeks
12 Jan, 2022 The phrase temporal logic refers to any system that uses rules and symbolism for representing and reasoning about propositions that are time-limited. Tense logic is a term that is occasionally used to describe it. More precisely, temporal logic is concerned with tense and employs modal operators in relation to temporal concepts such as sometimes, always, precedes, succeeds, and so on. Arthur Prior introduced a special modal logic-system of temporal logic in the 1960s. In addition to the normal logical operators, temporal logic contains four modal operators with the following intended meanings: In order to create a propositional tense logic, the operators G and F are used to refer to the future, whereas the operators H and P are used to refer to the past. The operators P & F are known as the weak tense operators, while the operators H and G are known as strong tense operators. By reason of equivalence, the two pairings are commonly viewed as inter definable. Assume Q is some closed formula in conventional Logic. The 2 axioms govern the interaction between the past and future operators : FQ ≅ ~G~Q PQ ≅ ~H~Q NOTE: If a variable appears in quantification or is inside the scope of quantification of that variable, it is bound. Otherwise, the variable is free. A closed formula is one that has no free variables; otherwise, it is an open formula. Arthur employed the operators to create formulas that could express the concepts of time that had been taken as axioms of a formal system based on these intended meanings. The distribution axioms are : G(Q -> R) -> (GQ -> GR) interpreted as: If it will always be the case that Q implies R, then if Q will always be the case,then R will be always be so. H ( Q->R) -> (HQ -> HR) interpreted as: If Q has implies R, then if Q has always been the case,then R will be always be so. Depending on the assumptions we make about the structure of time, further axioms can be added to temporal logic. A set of commonly adopted axioms is : GQ -> FQ and HQ -> PQ Certain combinations of past & future tense operators may be used to express complex tense in English. Example: FPQ corresponds to a sentence Q in the future perfect tense. PPQ expresses past perfect tense.The useful axioms in Temporal Logic :(i) It has always been the case that Q is true is equivalent to It is not in the past that Q was false. HQ ≅ ~P~Q (ii) It will always be the case that Q will be true is equivalent to It is not in the future that Q will be false. GQ ≅ ~F~Q (iii) It will always be the case in future that Q will be true is equivalent to It will not be always that Q will be false. FQ ≅ ~G~Q (iv) It was the case that Q was true is equivalent to It has not always been the case in past that Q was false. PQ ≅ ~H~Q (v) It will not always be the case that Q will be true is equivalent to It will be the case in the future that Q will be false. ~GQ ≅ F~Q (vi) It has not always been the case in the past that Q was true is equivalent to It was the case in the past that Q was false. ~HQ ≅ P~Q Inference Rules in Temporal Logic : Following inference rules in Temporal Logic can be used to infer new information from existing knowledge : If it is true in future that Q will be true in the future, then we infer that Q will be true in the future. FFQ -> FQIf Q is true now, then we infer that in the future it will be the case that Q was true in the past. Q -> FPQIf Q has always been true in the past, then we infer that Q is true HQ -> QIf Q will be always true in future then we infer that Q is true. GQ -> QDistribution Axioms : – G(Q -> R) -> (GQ -> GR) interpreted as If it will always be the case that Q implies R, then if Q will always be the case, always be then R will always be so.– H ( Q->R) -> (HQ -> HR) interpreted as If Q has implied R, then if Q has always been the case, then R will be always be so. If it is true in future that Q will be true in the future, then we infer that Q will be true in the future. FFQ -> FQ If Q is true now, then we infer that in the future it will be the case that Q was true in the past. Q -> FPQ If Q has always been true in the past, then we infer that Q is true HQ -> Q If Q will be always true in future then we infer that Q is true. GQ -> Q Distribution Axioms : – G(Q -> R) -> (GQ -> GR) interpreted as If it will always be the case that Q implies R, then if Q will always be the case, always be then R will always be so.– H ( Q->R) -> (HQ -> HR) interpreted as If Q has implied R, then if Q has always been the case, then R will be always be so. sumitgumber28 Advanced Computer Subject Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Copying Files to and from Docker Containers Markov Decision Process Fuzzy Logic | Introduction Q-Learning in Python Principal Component Analysis with Python Basics of API Testing Using Postman ML | What is Machine Learning ? OpenCV - Overview Getting Started with System Design Deep Learning | Introduction to Long Short Term Memory
[ { "code": null, "e": 25493, "s": 25465, "text": "\n12 Jan, 2022" }, { "code": null, "e": 26095, "s": 25493, "text": "The phrase temporal logic refers to any system that uses rules and symbolism for representing and reasoning about propositions that are time-limited. Tense logic is a term that is occasionally used to describe it. More precisely, temporal logic is concerned with tense and employs modal operators in relation to temporal concepts such as sometimes, always, precedes, succeeds, and so on. Arthur Prior introduced a special modal logic-system of temporal logic in the 1960s. In addition to the normal logical operators, temporal logic contains four modal operators with the following intended meanings: " }, { "code": null, "e": 26597, "s": 26095, "text": "In order to create a propositional tense logic, the operators G and F are used to refer to the future, whereas the operators H and P are used to refer to the past. The operators P & F are known as the weak tense operators, while the operators H and G are known as strong tense operators. By reason of equivalence, the two pairings are commonly viewed as inter definable. Assume Q is some closed formula in conventional Logic. The 2 axioms govern the interaction between the past and future operators :" }, { "code": null, "e": 26617, "s": 26597, "text": "FQ ≅ ~G~Q\nPQ ≅ ~H~Q" }, { "code": null, "e": 26855, "s": 26617, "text": "NOTE: If a variable appears in quantification or is inside the scope of quantification of that variable, it is bound. Otherwise, the variable is free. A closed formula is one that has no free variables; otherwise, it is an open formula. " }, { "code": null, "e": 27027, "s": 26855, "text": "Arthur employed the operators to create formulas that could express the concepts of time that had been taken as axioms of a formal system based on these intended meanings." }, { "code": null, "e": 27057, "s": 27027, "text": "The distribution axioms are :" }, { "code": null, "e": 27333, "s": 27057, "text": "G(Q -> R) -> (GQ -> GR) interpreted as:\nIf it will always be the case that Q implies R, then\nif Q will always be the case,then R will be always be so.\n\nH ( Q->R) -> (HQ -> HR) interpreted as:\nIf Q has implies R, then\nif Q has always been the case,then R will be always be so." }, { "code": null, "e": 27484, "s": 27333, "text": "Depending on the assumptions we make about the structure of time, further axioms can be added to temporal logic. A set of commonly adopted axioms is :" }, { "code": null, "e": 27506, "s": 27484, "text": "GQ -> FQ and HQ -> PQ" }, { "code": null, "e": 27853, "s": 27506, "text": "Certain combinations of past & future tense operators may be used to express complex tense in English. Example: FPQ corresponds to a sentence Q in the future perfect tense. PPQ expresses past perfect tense.The useful axioms in Temporal Logic :(i) It has always been the case that Q is true is equivalent to It is not in the past that Q was false." }, { "code": null, "e": 27863, "s": 27853, "text": "HQ ≅ ~P~Q" }, { "code": null, "e": 27978, "s": 27863, "text": "(ii) It will always be the case that Q will be true is equivalent to It is not in the future that Q will be false." }, { "code": null, "e": 27988, "s": 27978, "text": "GQ ≅ ~F~Q" }, { "code": null, "e": 28112, "s": 27988, "text": "(iii) It will always be the case in future that Q will be true is equivalent to It will not be always that Q will be false." }, { "code": null, "e": 28122, "s": 28112, "text": "FQ ≅ ~G~Q" }, { "code": null, "e": 28234, "s": 28122, "text": "(iv) It was the case that Q was true is equivalent to It has not always been the case in past that Q was false." }, { "code": null, "e": 28244, "s": 28234, "text": "PQ ≅ ~H~Q" }, { "code": null, "e": 28372, "s": 28244, "text": "(v) It will not always be the case that Q will be true is equivalent to It will be the case in the future that Q will be false." }, { "code": null, "e": 28382, "s": 28372, "text": "~GQ ≅ F~Q" }, { "code": null, "e": 28510, "s": 28382, "text": "(vi) It has not always been the case in the past that Q was true is equivalent to It was the case in the past that Q was false." }, { "code": null, "e": 28520, "s": 28510, "text": "~HQ ≅ P~Q" }, { "code": null, "e": 28556, "s": 28520, "text": "Inference Rules in Temporal Logic :" }, { "code": null, "e": 28663, "s": 28556, "text": "Following inference rules in Temporal Logic can be used to infer new information from existing knowledge :" }, { "code": null, "e": 29342, "s": 28663, "text": "If it is true in future that Q will be true in the future, then we infer that Q will be true in the future. FFQ -> FQIf Q is true now, then we infer that in the future it will be the case that Q was true in the past. Q -> FPQIf Q has always been true in the past, then we infer that Q is true HQ -> QIf Q will be always true in future then we infer that Q is true. GQ -> QDistribution Axioms : – G(Q -> R) -> (GQ -> GR) interpreted as If it will always be the case that Q implies R, then if Q will always be the case, always be then R will always be so.– H ( Q->R) -> (HQ -> HR) interpreted as If Q has implied R, then if Q has always been the case, then R will be always be so." }, { "code": null, "e": 29460, "s": 29342, "text": "If it is true in future that Q will be true in the future, then we infer that Q will be true in the future. FFQ -> FQ" }, { "code": null, "e": 29569, "s": 29460, "text": "If Q is true now, then we infer that in the future it will be the case that Q was true in the past. Q -> FPQ" }, { "code": null, "e": 29645, "s": 29569, "text": "If Q has always been true in the past, then we infer that Q is true HQ -> Q" }, { "code": null, "e": 29718, "s": 29645, "text": "If Q will be always true in future then we infer that Q is true. GQ -> Q" }, { "code": null, "e": 30025, "s": 29718, "text": "Distribution Axioms : – G(Q -> R) -> (GQ -> GR) interpreted as If it will always be the case that Q implies R, then if Q will always be the case, always be then R will always be so.– H ( Q->R) -> (HQ -> HR) interpreted as If Q has implied R, then if Q has always been the case, then R will be always be so." }, { "code": null, "e": 30039, "s": 30025, "text": "sumitgumber28" }, { "code": null, "e": 30065, "s": 30039, "text": "Advanced Computer Subject" }, { "code": null, "e": 30163, "s": 30065, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 30207, "s": 30163, "text": "Copying Files to and from Docker Containers" }, { "code": null, "e": 30231, "s": 30207, "text": "Markov Decision Process" }, { "code": null, "e": 30258, "s": 30231, "text": "Fuzzy Logic | Introduction" }, { "code": null, "e": 30279, "s": 30258, "text": "Q-Learning in Python" }, { "code": null, "e": 30320, "s": 30279, "text": "Principal Component Analysis with Python" }, { "code": null, "e": 30356, "s": 30320, "text": "Basics of API Testing Using Postman" }, { "code": null, "e": 30388, "s": 30356, "text": "ML | What is Machine Learning ?" }, { "code": null, "e": 30406, "s": 30388, "text": "OpenCV - Overview" }, { "code": null, "e": 30441, "s": 30406, "text": "Getting Started with System Design" } ]
How to use pandas cut() and qcut()? - GeeksforGeeks
13 Jul, 2021 Pandas is an open-source library that is made mainly for working with relational or labeled data both easily and intuitively. It provides various data structures and operations for manipulating numerical data and time series. In this tutorial, we’ll look at pandas’ intelligent cut and qcut functions. Basically, we use cut and qcut to convert a numerical column into a categorical one, perhaps to make it better suited for a machine learning model (in case of a fairly skewed numerical column), or just for better analyzing the data at hand. Now, rather than blurting out technical definitions of cut and qcut, we’d be better off seeing what both these functions are good at and how to use them. We’ll first import the necessary data manipulating libraries. Python3 import pandas as pdimport numpy as npimport matplotlib.pyplot as plt We’ll be using the CarDekho dataset, containing data about used cars listed on the platform. You can find the dataset here: ‘Year’ is the year in which the car was purchased. ‘Selling_Price’ is the price the owner wants to sell the car at. ‘Present_Price’ is the current ex-showroom price of the car. ‘Owner’ defines the number of owners the car has previously had, before this car was put up on the platform. Rest of the columns are pretty self explanatory. Python3 df = pd.read_csv('cardekho.csv')df.head() Output: Python3 # no missing values in the datasetdf.info() We’ll infuse a missing value to better demonstrate how cut and qcut would handle an ‘imperfect’ dataset. Python3 df.loc[0, 'Year'] = np.nan # these are the 'unique' years in# the datanp.array(sorted(df.Year.unique())) Output: We can use the ‘cut’ function in broadly 2 ways: by specifying the number of bins directly and let pandas do the work of calculating equal-sized bins for us, or we can manually specify the bin edges as we desire. Python3 # right = True, by defaultpd.cut(df.Year, bins=3, right=True).head() Output: When we specified bins=3, pandas saw that the year range in the data is 2003 to 2018, hence appropriately cut it into 3 equal-width bins of 5 years each: [(2002.985, 2008.0] < (2008.0, 2013.0] < (2013.0, 2018.0]. Note that pandas automatically took the lower bound value of the the first category (2002.985) to be a fraction less that the least value in the ‘Year’ column (2003), to include the year 2003 in the results as well, because you see, the lower bounds of the bins are open ended, while the upper bounds are closed ended (as right=True) Note: Did you notice that the NaN values are kept as NaNs in the output result as well? When we specify right=False, the left bounds are now closed ended, while right bounds get open ended. Python3 pd.cut(df.Year, bins=3, right=False).head() Output: Instead of getting the intervals back, we can specify the ‘labels’ parameter as a list for better analysis. Python3 pd.cut(df.Year, bins=3, labels=['old', 'medium', 'new']).head() Output: We will assign this series back to the original dataframe: Python3 df['Yr_cut'] = pd.cut(df.Year, bins=3, labels=['old', 'medium', 'new'])df.head() Output: If we specify labels=False, instead of bin labels, we will get numeric representation of the bins: Here, 0 represents old, 1 is medium and 2 is new. Python3 pd.cut(df.Year, bins=3, labels=False).head() Output: Just to see how many values fall in each bin: Python3 df['Yr_cut'].value_counts() Output: And just because drawing a graph pleases more people than offends.. Python3 df['Yr_cut'].value_counts().plot(kind='barh')plt.show() Output: Now, if we need the bin intervals along with the discretized series at one go, we specify retbins=True. Pandas will give us back a tuple containing 2 elements: the series, and the bin intervals. We will use tuple unpacking to grab both outputs. Python3 cut_series, cut_intervals = pd.cut(df.Year, bins=3, retbins=True) print("Cut series:")print(cut_series.head())print()print("Cut intervals: ", cut_intervals) Output: As mentioned earlier, we can also specify bin edges manually by passing in a list: Python3 pd.cut(df.Year, bins=[2003, 2007, 2010, 2015, 2018], include_lowest=True).head() Output: Here, we had to mention include_lowest=True. Can you guess why? Because by default ‘include_lowest’ parameter is set to False, and hence when pandas sees the list that we passed, it will exclude 2003 from calculations. For the eagle-eyed, we could have used any value less than 2003 as well, like 1999 or 2002 or 2002.255 etc and gone ahead with the default setting of include_lowest=False. Qcut (quantile-cut) differs from cut in the sense that, in qcut, the number of elements in each bin will be roughly the same, but this will come at the cost of differently sized interval widths. On the other hand, in cut, the bin edges were equal sized (when we specified bins=3) with uneven number of elements in each bin or group. Also, cut is useful when you know for sure the interval ranges and the bins, For example, if binning an ‘age’ column, we know infants are between 0 and 1 years old, 1-12 years are kids, 13-19 are teenagers, 20-60 are working class grownups, and 60+ senior citizens. So we can appropriately set bins=[0, 1, 12, 19, 60, 140] and labels=[‘infant’, ‘kid’, ‘teenager’, ‘grownup’, ‘senior citizen’]. In qcut, when we specify q=5, we are telling pandas to cut the Year column into 5 equal quantiles, i.e. 0-20%, 20-40%, 40-60%, 60-80% and 80-100% buckets/bins. Python3 pd.qcut(df.Year, q=5).head(7) Output: We’ll assign this series to the dataframe. Python3 df['Yr_qcut'] = pd.qcut(df.Year, q=5, labels=['oldest', 'not so old', 'medium', 'newer', 'latest'])df.head() df['Yr_qcut'].value_counts().plot(kind='barh')plt.show() qcut_series, qcut_intervals = pd.qcut(df.Year, q=5, labels=['oldest', 'not so old', 'medium', 'newer', 'latest'], retbins=True) qcut_series.value_counts() Output: Now just to highlight the fact that q=5 indeed implies splitting values into 5 equal quantiles of 20% each, we’ll manually specify the quantiles, and get the same bin distributions as above. Python3 pd.qcut(df.Year, q=[0, 0.2, 0.4, 0.6, 0.8, 1.0], labels=['oldest', 'not so old', 'medium', 'newer', 'latest']).value_counts() Output: We’ll now see the qcut intervals array we got using tuple unpacking: Python3 qcut_intervals Output: You see? Here in qcut, the bin edges are of unequal widths, because it is accommodating 20% of the values in each bucket, and hence it is calculating the bin widths on its own to achieve that objective. Python3 # demonstrating with some random quantilespd.qcut(df.Year, q=[0,0.15,0.35, 0.51,0.78,1]).head() Output: Now it is binning the data into our custom made list of quantiles of 0-15%, 15-35%, 35-51%, 51-78% and 78-100%.With qcut, we’re answering the question of “which data points lie in the first 15% of the data, or in the 51-78 percentile range etc. Additionally, we can also use pandas’ interval_range, or numpy’s linspace and arange to generate a list of interval ranges and feed it to cut and qcut as the bins and q parameter respectively. Python3 pd.cut(df.Year, bins=pd.interval_range(start=2002.99, end=2018, periods=3)).head() Output: Using linspace: Python3 # basically dividing data into 3# quantilespd.qcut(df.Kms_Driven, q=np.linspace(0,1,4)).head() Output: Using arange: Python3 pd.qcut(df.Selling_Price, q=np.arange(0, 1.01, 0.25), labels=['inexpensive', 'average', 'high cost', 'over budget']).head() Output: Sometimes when we ask pandas to calculate the bin edges for us, you may run into an error which looks like: ValueError: Bin edges must be unique error. This implies that while calculating the bin intervals, pandas found that some bin edges were the same on both ends, like an interval of (2014, 2014] and hence it raised that error. This usually happens when the number of bins is large and the value range of the particular column is small. You can silence this error by passing the argument of duplicates=’drop’. abhishek0719kadiyan Python-pandas 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() *args and **kwargs in Python Reading and Writing to text files in Python Create a Pandas DataFrame from Lists
[ { "code": null, "e": 25491, "s": 25463, "text": "\n13 Jul, 2021" }, { "code": null, "e": 25717, "s": 25491, "text": "Pandas is an open-source library that is made mainly for working with relational or labeled data both easily and intuitively. It provides various data structures and operations for manipulating numerical data and time series." }, { "code": null, "e": 26188, "s": 25717, "text": "In this tutorial, we’ll look at pandas’ intelligent cut and qcut functions. Basically, we use cut and qcut to convert a numerical column into a categorical one, perhaps to make it better suited for a machine learning model (in case of a fairly skewed numerical column), or just for better analyzing the data at hand. Now, rather than blurting out technical definitions of cut and qcut, we’d be better off seeing what both these functions are good at and how to use them." }, { "code": null, "e": 26252, "s": 26188, "text": "We’ll first import the necessary data manipulating libraries. " }, { "code": null, "e": 26260, "s": 26252, "text": "Python3" }, { "code": "import pandas as pdimport numpy as npimport matplotlib.pyplot as plt", "e": 26329, "s": 26260, "text": null }, { "code": null, "e": 26458, "s": 26333, "text": "We’ll be using the CarDekho dataset, containing data about used cars listed on the platform. You can find the dataset here: " }, { "code": null, "e": 26511, "s": 26460, "text": "‘Year’ is the year in which the car was purchased." }, { "code": null, "e": 26576, "s": 26511, "text": "‘Selling_Price’ is the price the owner wants to sell the car at." }, { "code": null, "e": 26637, "s": 26576, "text": "‘Present_Price’ is the current ex-showroom price of the car." }, { "code": null, "e": 26746, "s": 26637, "text": "‘Owner’ defines the number of owners the car has previously had, before this car was put up on the platform." }, { "code": null, "e": 26798, "s": 26748, "text": "Rest of the columns are pretty self explanatory. " }, { "code": null, "e": 26808, "s": 26800, "text": "Python3" }, { "code": "df = pd.read_csv('cardekho.csv')df.head()", "e": 26850, "s": 26808, "text": null }, { "code": null, "e": 26862, "s": 26854, "text": "Output:" }, { "code": null, "e": 26874, "s": 26866, "text": "Python3" }, { "code": "# no missing values in the datasetdf.info()", "e": 26918, "s": 26874, "text": null }, { "code": null, "e": 27024, "s": 26918, "text": "We’ll infuse a missing value to better demonstrate how cut and qcut would handle an ‘imperfect’ dataset. " }, { "code": null, "e": 27032, "s": 27024, "text": "Python3" }, { "code": "df.loc[0, 'Year'] = np.nan # these are the 'unique' years in# the datanp.array(sorted(df.Year.unique()))", "e": 27137, "s": 27032, "text": null }, { "code": null, "e": 27145, "s": 27137, "text": "Output:" }, { "code": null, "e": 27359, "s": 27145, "text": "We can use the ‘cut’ function in broadly 2 ways: by specifying the number of bins directly and let pandas do the work of calculating equal-sized bins for us, or we can manually specify the bin edges as we desire. " }, { "code": null, "e": 27367, "s": 27359, "text": "Python3" }, { "code": "# right = True, by defaultpd.cut(df.Year, bins=3, right=True).head()", "e": 27436, "s": 27367, "text": null }, { "code": null, "e": 27444, "s": 27436, "text": "Output:" }, { "code": null, "e": 27992, "s": 27444, "text": "When we specified bins=3, pandas saw that the year range in the data is 2003 to 2018, hence appropriately cut it into 3 equal-width bins of 5 years each: [(2002.985, 2008.0] < (2008.0, 2013.0] < (2013.0, 2018.0]. Note that pandas automatically took the lower bound value of the the first category (2002.985) to be a fraction less that the least value in the ‘Year’ column (2003), to include the year 2003 in the results as well, because you see, the lower bounds of the bins are open ended, while the upper bounds are closed ended (as right=True) " }, { "code": null, "e": 28183, "s": 27992, "text": "Note: Did you notice that the NaN values are kept as NaNs in the output result as well? When we specify right=False, the left bounds are now closed ended, while right bounds get open ended. " }, { "code": null, "e": 28191, "s": 28183, "text": "Python3" }, { "code": "pd.cut(df.Year, bins=3, right=False).head()", "e": 28235, "s": 28191, "text": null }, { "code": null, "e": 28247, "s": 28239, "text": "Output:" }, { "code": null, "e": 28360, "s": 28251, "text": "Instead of getting the intervals back, we can specify the ‘labels’ parameter as a list for better analysis. " }, { "code": null, "e": 28370, "s": 28362, "text": "Python3" }, { "code": "pd.cut(df.Year, bins=3, labels=['old', 'medium', 'new']).head()", "e": 28440, "s": 28370, "text": null }, { "code": null, "e": 28452, "s": 28444, "text": "Output:" }, { "code": null, "e": 28516, "s": 28456, "text": "We will assign this series back to the original dataframe: " }, { "code": null, "e": 28526, "s": 28518, "text": "Python3" }, { "code": "df['Yr_cut'] = pd.cut(df.Year, bins=3, labels=['old', 'medium', 'new'])df.head()", "e": 28628, "s": 28526, "text": null }, { "code": null, "e": 28640, "s": 28632, "text": "Output:" }, { "code": null, "e": 28794, "s": 28644, "text": "If we specify labels=False, instead of bin labels, we will get numeric representation of the bins: Here, 0 represents old, 1 is medium and 2 is new. " }, { "code": null, "e": 28804, "s": 28796, "text": "Python3" }, { "code": "pd.cut(df.Year, bins=3, labels=False).head()", "e": 28849, "s": 28804, "text": null }, { "code": null, "e": 28861, "s": 28853, "text": "Output:" }, { "code": null, "e": 28912, "s": 28865, "text": "Just to see how many values fall in each bin: " }, { "code": null, "e": 28922, "s": 28914, "text": "Python3" }, { "code": "df['Yr_cut'].value_counts()", "e": 28950, "s": 28922, "text": null }, { "code": null, "e": 28962, "s": 28954, "text": "Output:" }, { "code": null, "e": 29035, "s": 28966, "text": "And just because drawing a graph pleases more people than offends.. " }, { "code": null, "e": 29045, "s": 29037, "text": "Python3" }, { "code": "df['Yr_cut'].value_counts().plot(kind='barh')plt.show()", "e": 29101, "s": 29045, "text": null }, { "code": null, "e": 29113, "s": 29105, "text": "Output:" }, { "code": null, "e": 29363, "s": 29117, "text": "Now, if we need the bin intervals along with the discretized series at one go, we specify retbins=True. Pandas will give us back a tuple containing 2 elements: the series, and the bin intervals. We will use tuple unpacking to grab both outputs. " }, { "code": null, "e": 29373, "s": 29365, "text": "Python3" }, { "code": "cut_series, cut_intervals = pd.cut(df.Year, bins=3, retbins=True) print(\"Cut series:\")print(cut_series.head())print()print(\"Cut intervals: \", cut_intervals)", "e": 29598, "s": 29373, "text": null }, { "code": null, "e": 29610, "s": 29602, "text": "Output:" }, { "code": null, "e": 29698, "s": 29614, "text": "As mentioned earlier, we can also specify bin edges manually by passing in a list: " }, { "code": null, "e": 29708, "s": 29700, "text": "Python3" }, { "code": "pd.cut(df.Year, bins=[2003, 2007, 2010, 2015, 2018], include_lowest=True).head()", "e": 29879, "s": 29708, "text": null }, { "code": null, "e": 29891, "s": 29883, "text": "Output:" }, { "code": null, "e": 30287, "s": 29895, "text": "Here, we had to mention include_lowest=True. Can you guess why? Because by default ‘include_lowest’ parameter is set to False, and hence when pandas sees the list that we passed, it will exclude 2003 from calculations. For the eagle-eyed, we could have used any value less than 2003 as well, like 1999 or 2002 or 2002.255 etc and gone ahead with the default setting of include_lowest=False. " }, { "code": null, "e": 30702, "s": 30291, "text": "Qcut (quantile-cut) differs from cut in the sense that, in qcut, the number of elements in each bin will be roughly the same, but this will come at the cost of differently sized interval widths. On the other hand, in cut, the bin edges were equal sized (when we specified bins=3) with uneven number of elements in each bin or group. Also, cut is useful when you know for sure the interval ranges and the bins, " }, { "code": null, "e": 31182, "s": 30704, "text": "For example, if binning an ‘age’ column, we know infants are between 0 and 1 years old, 1-12 years are kids, 13-19 are teenagers, 20-60 are working class grownups, and 60+ senior citizens. So we can appropriately set bins=[0, 1, 12, 19, 60, 140] and labels=[‘infant’, ‘kid’, ‘teenager’, ‘grownup’, ‘senior citizen’]. In qcut, when we specify q=5, we are telling pandas to cut the Year column into 5 equal quantiles, i.e. 0-20%, 20-40%, 40-60%, 60-80% and 80-100% buckets/bins. " }, { "code": null, "e": 31192, "s": 31184, "text": "Python3" }, { "code": "pd.qcut(df.Year, q=5).head(7)", "e": 31222, "s": 31192, "text": null }, { "code": null, "e": 31234, "s": 31226, "text": "Output:" }, { "code": null, "e": 31282, "s": 31238, "text": "We’ll assign this series to the dataframe. " }, { "code": null, "e": 31292, "s": 31284, "text": "Python3" }, { "code": "df['Yr_qcut'] = pd.qcut(df.Year, q=5, labels=['oldest', 'not so old', 'medium', 'newer', 'latest'])df.head() df['Yr_qcut'].value_counts().plot(kind='barh')plt.show() qcut_series, qcut_intervals = pd.qcut(df.Year, q=5, labels=['oldest', 'not so old', 'medium', 'newer', 'latest'], retbins=True) qcut_series.value_counts()", "e": 32014, "s": 31292, "text": null }, { "code": null, "e": 32026, "s": 32018, "text": "Output:" }, { "code": null, "e": 32222, "s": 32030, "text": "Now just to highlight the fact that q=5 indeed implies splitting values into 5 equal quantiles of 20% each, we’ll manually specify the quantiles, and get the same bin distributions as above. " }, { "code": null, "e": 32232, "s": 32224, "text": "Python3" }, { "code": "pd.qcut(df.Year, q=[0, 0.2, 0.4, 0.6, 0.8, 1.0], labels=['oldest', 'not so old', 'medium', 'newer', 'latest']).value_counts()", "e": 32442, "s": 32232, "text": null }, { "code": null, "e": 32454, "s": 32446, "text": "Output:" }, { "code": null, "e": 32529, "s": 32458, "text": "We’ll now see the qcut intervals array we got using tuple unpacking: " }, { "code": null, "e": 32539, "s": 32531, "text": "Python3" }, { "code": "qcut_intervals", "e": 32554, "s": 32539, "text": null }, { "code": null, "e": 32566, "s": 32558, "text": "Output:" }, { "code": null, "e": 32774, "s": 32570, "text": "You see? Here in qcut, the bin edges are of unequal widths, because it is accommodating 20% of the values in each bucket, and hence it is calculating the bin widths on its own to achieve that objective. " }, { "code": null, "e": 32784, "s": 32776, "text": "Python3" }, { "code": "# demonstrating with some random quantilespd.qcut(df.Year, q=[0,0.15,0.35, 0.51,0.78,1]).head()", "e": 32899, "s": 32784, "text": null }, { "code": null, "e": 32911, "s": 32903, "text": "Output:" }, { "code": null, "e": 33354, "s": 32915, "text": "Now it is binning the data into our custom made list of quantiles of 0-15%, 15-35%, 35-51%, 51-78% and 78-100%.With qcut, we’re answering the question of “which data points lie in the first 15% of the data, or in the 51-78 percentile range etc. Additionally, we can also use pandas’ interval_range, or numpy’s linspace and arange to generate a list of interval ranges and feed it to cut and qcut as the bins and q parameter respectively. " }, { "code": null, "e": 33364, "s": 33356, "text": "Python3" }, { "code": "pd.cut(df.Year, bins=pd.interval_range(start=2002.99, end=2018, periods=3)).head()", "e": 33511, "s": 33364, "text": null }, { "code": null, "e": 33523, "s": 33515, "text": "Output:" }, { "code": null, "e": 33545, "s": 33527, "text": "Using linspace: " }, { "code": null, "e": 33555, "s": 33547, "text": "Python3" }, { "code": "# basically dividing data into 3# quantilespd.qcut(df.Kms_Driven, q=np.linspace(0,1,4)).head()", "e": 33657, "s": 33555, "text": null }, { "code": null, "e": 33665, "s": 33657, "text": "Output:" }, { "code": null, "e": 33679, "s": 33665, "text": "Using arange:" }, { "code": null, "e": 33687, "s": 33679, "text": "Python3" }, { "code": "pd.qcut(df.Selling_Price, q=np.arange(0, 1.01, 0.25), labels=['inexpensive', 'average', 'high cost', 'over budget']).head()", "e": 33870, "s": 33687, "text": null }, { "code": null, "e": 33882, "s": 33874, "text": "Output:" }, { "code": null, "e": 34402, "s": 33886, "text": "Sometimes when we ask pandas to calculate the bin edges for us, you may run into an error which looks like: ValueError: Bin edges must be unique error. This implies that while calculating the bin intervals, pandas found that some bin edges were the same on both ends, like an interval of (2014, 2014] and hence it raised that error. This usually happens when the number of bins is large and the value range of the particular column is small. You can silence this error by passing the argument of duplicates=’drop’. " }, { "code": null, "e": 34424, "s": 34404, "text": "abhishek0719kadiyan" }, { "code": null, "e": 34438, "s": 34424, "text": "Python-pandas" }, { "code": null, "e": 34445, "s": 34438, "text": "Python" }, { "code": null, "e": 34543, "s": 34445, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 34561, "s": 34543, "text": "Python Dictionary" }, { "code": null, "e": 34596, "s": 34561, "text": "Read a file line by line in Python" }, { "code": null, "e": 34628, "s": 34596, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 34650, "s": 34628, "text": "Enumerate() in Python" }, { "code": null, "e": 34692, "s": 34650, "text": "Different ways to create Pandas Dataframe" }, { "code": null, "e": 34722, "s": 34692, "text": "Iterate over a list in Python" }, { "code": null, "e": 34748, "s": 34722, "text": "Python String | replace()" }, { "code": null, "e": 34777, "s": 34748, "text": "*args and **kwargs in Python" }, { "code": null, "e": 34821, "s": 34777, "text": "Reading and Writing to text files in Python" } ]
How To Use Images as Backgrounds in Tkinter? - GeeksforGeeks
02 Dec, 2020 Prerequisite: Python GUI – tkinter , Frame In this article, We are going to write a program use image in the background. In Tkinter, there is no in-built function for images, so that it can be used as a background image. It can be done with various methods: Method 1: Using photoimage methods. When it comes to GUI based application, images play a vital role. From the application icon to animation, it’s useful. To display images in labels, buttons, canvases, and text widgets, the PhotoImage class is used, which is present in Tkinter package. Code: Python3 # Import module from tkinter import * # Create object root = Tk() # Adjust size root.geometry("400x400") # Add image filebg = PhotoImage(file = "Your_image.png") # Show image using labellabel1 = Label( root, image = bg)label1.place(x = 0, y = 0) label2 = Label( root, text = "Welcome")label2.pack(pady = 50) # Create Frameframe1 = Frame(root)frame1.pack(pady = 20 ) # Add buttonsbutton1 = Button(frame1,text="Exit")button1.pack(pady=20) button2 = Button( frame1, text = "Start")button2.pack(pady = 20) button3 = Button( frame1, text = "Reset")button3.pack(pady = 20) # Execute tkinterroot.mainloop() Output: As you can see the background color of buttons and labels have different from the image color. The solution is to set the background color of buttons and label it as the color of the image with this color “#88cffa” . Python3 # Import module from tkinter import * # Create object root = Tk() # Adjust size root.geometry("400x400") # Add image filebg = PhotoImage( file = "Your_img.png") # Show image using labellabel1 = Label( root, image = bg)label1.place(x = 0,y = 0) # Add textlabel2 = Label( root, text = "Welcome", bg = "#88cffa") label2.pack(pady = 50) # Create Frameframe1 = Frame( root, bg = "#88cffa")frame1.pack(pady = 20) # Add buttonsbutton1 = Button( frame1, text = "Exit")button1.pack(pady = 20) button2 = Button( frame1, text = "Start")button2.pack(pady = 20) button3 = Button( frame1, text = "Reset")button3.pack(pady = 20) # Execute tkinterroot.mainloop() Output: Note: This method will not work for multiple colors in image. Method 2: Using Canvas methods. Approach: Same as above implementation. Add Image file. Create Canvas and set width and height. Display image using create_image. Set text using create_text. Create buttons. Final step add button using create_window. Code: Python3 # Import module from tkinter import * # Create object root = Tk() # Adjust size root.geometry("400x400") # Add image filebg = PhotoImage(file = "Your_img.png") # Create Canvascanvas1 = Canvas( root, width = 400, height = 400) canvas1.pack(fill = "both", expand = True) # Display imagecanvas1.create_image( 0, 0, image = bg, anchor = "nw") # Add Textcanvas1.create_text( 200, 250, text = "Welcome") # Create Buttonsbutton1 = Button( root, text = "Exit")button3 = Button( root, text = "Start")button2 = Button( root, text = "Reset") # Display Buttonsbutton1_canvas = canvas1.create_window( 100, 10, anchor = "nw", window = button1) button2_canvas = canvas1.create_window( 100, 40, anchor = "nw", window = button2) button3_canvas = canvas1.create_window( 100, 70, anchor = "nw", window = button3) # Execute tkinterroot.mainloop() Output: Python Tkinter-exercises Python-tkinter Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Python Dictionary How to Install PIP on Windows ? Different ways to create Pandas Dataframe Python String | replace() *args and **kwargs in Python Reading and Writing to text files in Python Create a Pandas DataFrame from Lists Convert integer to string in Python Check if element exists in list in Python How To Convert Python Dictionary To JSON?
[ { "code": null, "e": 25597, "s": 25569, "text": "\n02 Dec, 2020" }, { "code": null, "e": 25640, "s": 25597, "text": "Prerequisite: Python GUI – tkinter , Frame" }, { "code": null, "e": 25855, "s": 25640, "text": "In this article, We are going to write a program use image in the background. In Tkinter, there is no in-built function for images, so that it can be used as a background image. It can be done with various methods:" }, { "code": null, "e": 25891, "s": 25855, "text": "Method 1: Using photoimage methods." }, { "code": null, "e": 26010, "s": 25891, "text": "When it comes to GUI based application, images play a vital role. From the application icon to animation, it’s useful." }, { "code": null, "e": 26143, "s": 26010, "text": "To display images in labels, buttons, canvases, and text widgets, the PhotoImage class is used, which is present in Tkinter package." }, { "code": null, "e": 26149, "s": 26143, "text": "Code:" }, { "code": null, "e": 26157, "s": 26149, "text": "Python3" }, { "code": "# Import module from tkinter import * # Create object root = Tk() # Adjust size root.geometry(\"400x400\") # Add image filebg = PhotoImage(file = \"Your_image.png\") # Show image using labellabel1 = Label( root, image = bg)label1.place(x = 0, y = 0) label2 = Label( root, text = \"Welcome\")label2.pack(pady = 50) # Create Frameframe1 = Frame(root)frame1.pack(pady = 20 ) # Add buttonsbutton1 = Button(frame1,text=\"Exit\")button1.pack(pady=20) button2 = Button( frame1, text = \"Start\")button2.pack(pady = 20) button3 = Button( frame1, text = \"Reset\")button3.pack(pady = 20) # Execute tkinterroot.mainloop()", "e": 26767, "s": 26157, "text": null }, { "code": null, "e": 26775, "s": 26767, "text": "Output:" }, { "code": null, "e": 26870, "s": 26775, "text": "As you can see the background color of buttons and labels have different from the image color." }, { "code": null, "e": 26993, "s": 26870, "text": "The solution is to set the background color of buttons and label it as the color of the image with this color “#88cffa” ." }, { "code": null, "e": 27001, "s": 26993, "text": "Python3" }, { "code": "# Import module from tkinter import * # Create object root = Tk() # Adjust size root.geometry(\"400x400\") # Add image filebg = PhotoImage( file = \"Your_img.png\") # Show image using labellabel1 = Label( root, image = bg)label1.place(x = 0,y = 0) # Add textlabel2 = Label( root, text = \"Welcome\", bg = \"#88cffa\") label2.pack(pady = 50) # Create Frameframe1 = Frame( root, bg = \"#88cffa\")frame1.pack(pady = 20) # Add buttonsbutton1 = Button( frame1, text = \"Exit\")button1.pack(pady = 20) button2 = Button( frame1, text = \"Start\")button2.pack(pady = 20) button3 = Button( frame1, text = \"Reset\")button3.pack(pady = 20) # Execute tkinterroot.mainloop()", "e": 27673, "s": 27001, "text": null }, { "code": null, "e": 27681, "s": 27673, "text": "Output:" }, { "code": null, "e": 27743, "s": 27681, "text": "Note: This method will not work for multiple colors in image." }, { "code": null, "e": 27775, "s": 27743, "text": "Method 2: Using Canvas methods." }, { "code": null, "e": 27785, "s": 27775, "text": "Approach:" }, { "code": null, "e": 27815, "s": 27785, "text": "Same as above implementation." }, { "code": null, "e": 27831, "s": 27815, "text": "Add Image file." }, { "code": null, "e": 27871, "s": 27831, "text": "Create Canvas and set width and height." }, { "code": null, "e": 27905, "s": 27871, "text": "Display image using create_image." }, { "code": null, "e": 27933, "s": 27905, "text": "Set text using create_text." }, { "code": null, "e": 27949, "s": 27933, "text": "Create buttons." }, { "code": null, "e": 27992, "s": 27949, "text": "Final step add button using create_window." }, { "code": null, "e": 27998, "s": 27992, "text": "Code:" }, { "code": null, "e": 28006, "s": 27998, "text": "Python3" }, { "code": "# Import module from tkinter import * # Create object root = Tk() # Adjust size root.geometry(\"400x400\") # Add image filebg = PhotoImage(file = \"Your_img.png\") # Create Canvascanvas1 = Canvas( root, width = 400, height = 400) canvas1.pack(fill = \"both\", expand = True) # Display imagecanvas1.create_image( 0, 0, image = bg, anchor = \"nw\") # Add Textcanvas1.create_text( 200, 250, text = \"Welcome\") # Create Buttonsbutton1 = Button( root, text = \"Exit\")button3 = Button( root, text = \"Start\")button2 = Button( root, text = \"Reset\") # Display Buttonsbutton1_canvas = canvas1.create_window( 100, 10, anchor = \"nw\", window = button1) button2_canvas = canvas1.create_window( 100, 40, anchor = \"nw\", window = button2) button3_canvas = canvas1.create_window( 100, 70, anchor = \"nw\", window = button3) # Execute tkinterroot.mainloop()", "e": 29073, "s": 28006, "text": null }, { "code": null, "e": 29081, "s": 29073, "text": "Output:" }, { "code": null, "e": 29106, "s": 29081, "text": "Python Tkinter-exercises" }, { "code": null, "e": 29121, "s": 29106, "text": "Python-tkinter" }, { "code": null, "e": 29128, "s": 29121, "text": "Python" }, { "code": null, "e": 29226, "s": 29128, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 29244, "s": 29226, "text": "Python Dictionary" }, { "code": null, "e": 29276, "s": 29244, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 29318, "s": 29276, "text": "Different ways to create Pandas Dataframe" }, { "code": null, "e": 29344, "s": 29318, "text": "Python String | replace()" }, { "code": null, "e": 29373, "s": 29344, "text": "*args and **kwargs in Python" }, { "code": null, "e": 29417, "s": 29373, "text": "Reading and Writing to text files in Python" }, { "code": null, "e": 29454, "s": 29417, "text": "Create a Pandas DataFrame from Lists" }, { "code": null, "e": 29490, "s": 29454, "text": "Convert integer to string in Python" }, { "code": null, "e": 29532, "s": 29490, "text": "Check if element exists in list in Python" } ]
Cross Product of Vectors in R Programming - GeeksforGeeks
25 Aug, 2020 In mathematics, the cross product or also known as the vector product is a binary operation on two vectors in three-dimensional space and is denoted by the symbol ‘X‘. Given two linearly independent vectors a and b, the cross product, a × b is a vector that is perpendicular to both a and b and thus normal to the plane containing them. Let we have given two vectors, and, where, i: the unit vector along the x directions j: the unit vector along the y directions k: the unit vector along the z directions Then the cross product is calculated as: where, are the coefficient of unit vector along i, j and k directions. Example: Given two vectors A and B as, A = 3i + 5j + 4k, and B = 2i + 7j + 5k Cross Product = (5 ? 5 – 4 ? 7)i + (4 ? 2 – 3 ? 5)j + (3 ? 7 – 5 ? 2)k = (?3)i + (?7)j + (11)k R language provides a very efficient method to calculate the cross product of two vectors. By using cross() method which is available in the pracma library. This function computes the cross or vector product of vectors in 3 dimensions. In the case of matrices, it takes the first dimension of length 3 and computes the cross product between corresponding columns or rows. Syntax: cross(x, y) Parameters: x: numeric vector or matrix y: numeric vector or matrix # Taking Input as Vectors Example 1: R # R Program illustrating# cross product of two vectors # Import the required librarylibrary(pracma) # Taking two vectorsa = c(3, 5, 4)b = c(2, 7, 5) # Calculating cross product using cross()print(cross(a, b)) Output: [1] -3 -7 11 Example 2: R # R Program illustrating# cross product of two vectors # Import the required librarylibrary(pracma) # Taking two vectorsa = c(23, 15, 49)b = c(28, 17, 25) # Calculating cross product using cross()print(cross(a, b)) Output: [1] -458 797 -29 # Taking Input as Matrix Example 1: R # R Program illustrating# cross product of two vectors # Import the required librarylibrary(pracma) # Taking two matricesa = matrix( c(1, 2, 3, 4, 5, 6, 7, 8, 9), nrow = 3, ncol = 3, byrow = TRUE ) b = matrix( c(5, 2, 1, 4, 6, 6, 3, 2, 9), nrow = 3, ncol = 3, byrow = TRUE ) # Calculating cross product using cross()print(cross(a, b)) Output: [, 1] [, 2] [, 3] [1, ] -4 14 -8 [2, ] -6 0 4 [3, ] 54 -36 -10 Example 2: R # R Program illustrating# cross product of two vectors # Import the required librarylibrary(pracma) # Taking two matricesa = matrix( c(11, 2, 31, 4, 52, 64, 7, 8, 9), nrow = 3, ncol = 3, byrow = TRUE ) b = matrix( c(85, 21, 1, 4, 61, 6, 32, 2, 9), nrow = 3, ncol = 3, byrow = TRUE ) # Calculating cross product using cross()print(cross(a, b)) Output: [, 1] [, 2] [, 3] [1, ] -649 2624 61 [2, ] -3592 232 36 [3, ] 54 225 -242 R Vector-Function R-Vectors R Language Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to Replace specific values in column in R DataFrame ? Filter data by multiple conditions in R using Dplyr Loops in R (for, while, repeat) How to change Row Names of DataFrame in R ? Change Color of Bars in Barchart using ggplot2 in R Group by function in R using Dplyr How to Change Axis Scales in R Plots? How to Split Column Into Multiple Columns in R DataFrame? K-Means Clustering in R Programming Creating a Data Frame from Vectors in R Programming
[ { "code": null, "e": 26141, "s": 26113, "text": "\n25 Aug, 2020" }, { "code": null, "e": 26478, "s": 26141, "text": "In mathematics, the cross product or also known as the vector product is a binary operation on two vectors in three-dimensional space and is denoted by the symbol ‘X‘. Given two linearly independent vectors a and b, the cross product, a × b is a vector that is perpendicular to both a and b and thus normal to the plane containing them." }, { "code": null, "e": 26509, "s": 26478, "text": "Let we have given two vectors," }, { "code": null, "e": 26514, "s": 26509, "text": "and," }, { "code": null, "e": 26521, "s": 26514, "text": "where," }, { "code": null, "e": 26563, "s": 26521, "text": "i: the unit vector along the x directions" }, { "code": null, "e": 26605, "s": 26563, "text": "j: the unit vector along the y directions" }, { "code": null, "e": 26647, "s": 26605, "text": "k: the unit vector along the z directions" }, { "code": null, "e": 26688, "s": 26647, "text": "Then the cross product is calculated as:" }, { "code": null, "e": 26695, "s": 26688, "text": "where," }, { "code": null, "e": 26759, "s": 26695, "text": "are the coefficient of unit vector along i, j and k directions." }, { "code": null, "e": 26768, "s": 26759, "text": "Example:" }, { "code": null, "e": 26798, "s": 26768, "text": "Given two vectors A and B as," }, { "code": null, "e": 26816, "s": 26798, "text": "A = 3i + 5j + 4k," }, { "code": null, "e": 26820, "s": 26816, "text": "and" }, { "code": null, "e": 26837, "s": 26820, "text": "B = 2i + 7j + 5k" }, { "code": null, "e": 26910, "s": 26837, "text": "Cross Product = (5 ? 5 – 4 ? 7)i + (4 ? 2 – 3 ? 5)j + (3 ? 7 – 5 ? 2)k " }, { "code": null, "e": 26956, "s": 26910, "text": " = (?3)i + (?7)j + (11)k" }, { "code": null, "e": 27328, "s": 26956, "text": "R language provides a very efficient method to calculate the cross product of two vectors. By using cross() method which is available in the pracma library. This function computes the cross or vector product of vectors in 3 dimensions. In the case of matrices, it takes the first dimension of length 3 and computes the cross product between corresponding columns or rows." }, { "code": null, "e": 27348, "s": 27328, "text": "Syntax: cross(x, y)" }, { "code": null, "e": 27360, "s": 27348, "text": "Parameters:" }, { "code": null, "e": 27388, "s": 27360, "text": "x: numeric vector or matrix" }, { "code": null, "e": 27416, "s": 27388, "text": "y: numeric vector or matrix" }, { "code": null, "e": 27442, "s": 27416, "text": "# Taking Input as Vectors" }, { "code": null, "e": 27453, "s": 27442, "text": "Example 1:" }, { "code": null, "e": 27455, "s": 27453, "text": "R" }, { "code": "# R Program illustrating# cross product of two vectors # Import the required librarylibrary(pracma) # Taking two vectorsa = c(3, 5, 4)b = c(2, 7, 5) # Calculating cross product using cross()print(cross(a, b))", "e": 27667, "s": 27455, "text": null }, { "code": null, "e": 27675, "s": 27667, "text": "Output:" }, { "code": null, "e": 27689, "s": 27675, "text": "[1] -3 -7 11\n" }, { "code": null, "e": 27700, "s": 27689, "text": "Example 2:" }, { "code": null, "e": 27702, "s": 27700, "text": "R" }, { "code": "# R Program illustrating# cross product of two vectors # Import the required librarylibrary(pracma) # Taking two vectorsa = c(23, 15, 49)b = c(28, 17, 25) # Calculating cross product using cross()print(cross(a, b))", "e": 27920, "s": 27702, "text": null }, { "code": null, "e": 27928, "s": 27920, "text": "Output:" }, { "code": null, "e": 27948, "s": 27928, "text": "[1] -458 797 -29\n" }, { "code": null, "e": 27975, "s": 27950, "text": "# Taking Input as Matrix" }, { "code": null, "e": 27986, "s": 27975, "text": "Example 1:" }, { "code": null, "e": 27988, "s": 27986, "text": "R" }, { "code": "# R Program illustrating# cross product of two vectors # Import the required librarylibrary(pracma) # Taking two matricesa = matrix( c(1, 2, 3, 4, 5, 6, 7, 8, 9), nrow = 3, ncol = 3, byrow = TRUE ) b = matrix( c(5, 2, 1, 4, 6, 6, 3, 2, 9), nrow = 3, ncol = 3, byrow = TRUE ) # Calculating cross product using cross()print(cross(a, b))", "e": 28417, "s": 27988, "text": null }, { "code": null, "e": 28425, "s": 28417, "text": "Output:" }, { "code": null, "e": 28513, "s": 28425, "text": " [, 1] [, 2] [, 3]\n[1, ] -4 14 -8\n[2, ] -6 0 4\n[3, ] 54 -36 -10\n" }, { "code": null, "e": 28524, "s": 28513, "text": "Example 2:" }, { "code": null, "e": 28526, "s": 28524, "text": "R" }, { "code": "# R Program illustrating# cross product of two vectors # Import the required librarylibrary(pracma) # Taking two matricesa = matrix( c(11, 2, 31, 4, 52, 64, 7, 8, 9), nrow = 3, ncol = 3, byrow = TRUE ) b = matrix( c(85, 21, 1, 4, 61, 6, 32, 2, 9), nrow = 3, ncol = 3, byrow = TRUE ) # Calculating cross product using cross()print(cross(a, b))", "e": 28963, "s": 28526, "text": null }, { "code": null, "e": 28971, "s": 28963, "text": "Output:" }, { "code": null, "e": 29062, "s": 28971, "text": " [, 1] [, 2] [, 3]\n[1, ] -649 2624 61\n[2, ] -3592 232 36\n[3, ] 54 225 -242\n" }, { "code": null, "e": 29080, "s": 29062, "text": "R Vector-Function" }, { "code": null, "e": 29090, "s": 29080, "text": "R-Vectors" }, { "code": null, "e": 29101, "s": 29090, "text": "R Language" }, { "code": null, "e": 29199, "s": 29101, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 29257, "s": 29199, "text": "How to Replace specific values in column in R DataFrame ?" }, { "code": null, "e": 29309, "s": 29257, "text": "Filter data by multiple conditions in R using Dplyr" }, { "code": null, "e": 29341, "s": 29309, "text": "Loops in R (for, while, repeat)" }, { "code": null, "e": 29385, "s": 29341, "text": "How to change Row Names of DataFrame in R ?" }, { "code": null, "e": 29437, "s": 29385, "text": "Change Color of Bars in Barchart using ggplot2 in R" }, { "code": null, "e": 29472, "s": 29437, "text": "Group by function in R using Dplyr" }, { "code": null, "e": 29510, "s": 29472, "text": "How to Change Axis Scales in R Plots?" }, { "code": null, "e": 29568, "s": 29510, "text": "How to Split Column Into Multiple Columns in R DataFrame?" }, { "code": null, "e": 29604, "s": 29568, "text": "K-Means Clustering in R Programming" } ]
How to set the Font of the Content present in the RichTextBox in C#? - GeeksforGeeks
17 Jul, 2019 In C#, RichTextBox control is a textbox which gives you rich text editing controls and advanced formatting features also includes a loading rich text format (RTF) files. Or in other words, RichTextBox controls allows you to display or edit flow content, including paragraphs, images, tables, etc. In RichTextBox, you are allowed to set the font of the content present in the RichTextBox control. You can set this property in two different ways: 1. Design-Time: It is the easiest way to set the font of the content present in the RichTextBox as shown in the following steps: Step 1: Create a windows form as shown in the below image:Visual Studio -> File -> New -> Project -> WindowsFormApp Step 2: Drag the RichTextBox control from the ToolBox and drop it on the windows form. You are allowed to place a RichTextBox control anywhere on the windows form according to your need. Step 3: After drag and drop you will go to the properties of the RichTextBox control set the font of the content present in the RichTextBox control.Output: Output: 2. Run-Time: It is a little bit trickier than the above method. In this method, you can set the font of the content present in the RichTextBox control programmatically with the help of given syntax: public virtual System.Drawing.Font Font { get; set; } Here, the Font is the type of font applied to the RichTextBox content. The following steps show how to set the Font property of the RichTextBox dynamically: Step 1: Create a RichTextBox using the RichTextBox() constructor is provided by the RichTextBox class.// Creating RichTextBox using RichTextBox class constructor RichTextBox rbox = new RichTextBox(); // Creating RichTextBox using RichTextBox class constructor RichTextBox rbox = new RichTextBox(); Step 2: After creating RichTextBox, set the Font property of the RichTextBox provided by the RichTextBox class.// Setting the font rbox.Font = new Font("Castellar", 8); // Setting the font rbox.Font = new Font("Castellar", 8); Step 3: And last add this RichTextBox control to the form using Add() method.// Add this RichTextBox to the form this.Controls.Add(rbox); Example:using System;using System.Collections.Generic;using System.ComponentModel;using System.Data;using System.Drawing;using System.Linq;using System.Text;using System.Threading.Tasks;using System.Windows.Forms; namespace WindowsFormsApp30 { public partial class Form1 : Form { public Form1() { InitializeComponent(); } private void Form1_Load(object sender, EventArgs e) { // Creating and setting the // properties of the label Label lb = new Label(); lb.Location = new Point(251, 70); lb.Text = "Enter Text"; // Adding this label in the form this.Controls.Add(lb); // Creating and setting the // properties of the RichTextBox RichTextBox rbox = new RichTextBox(); rbox.Location = new Point(236, 97); rbox.ForeColor = Color.Red; rbox.Font = new Font("Castellar", 8); rbox.Text = "!..Welcome to GeeksforGeeks..!"; // Adding this RichTextBox in the form this.Controls.Add(rbox); }}}Output: // Add this RichTextBox to the form this.Controls.Add(rbox); Example: using System;using System.Collections.Generic;using System.ComponentModel;using System.Data;using System.Drawing;using System.Linq;using System.Text;using System.Threading.Tasks;using System.Windows.Forms; namespace WindowsFormsApp30 { public partial class Form1 : Form { public Form1() { InitializeComponent(); } private void Form1_Load(object sender, EventArgs e) { // Creating and setting the // properties of the label Label lb = new Label(); lb.Location = new Point(251, 70); lb.Text = "Enter Text"; // Adding this label in the form this.Controls.Add(lb); // Creating and setting the // properties of the RichTextBox RichTextBox rbox = new RichTextBox(); rbox.Location = new Point(236, 97); rbox.ForeColor = Color.Red; rbox.Font = new Font("Castellar", 8); rbox.Text = "!..Welcome to GeeksforGeeks..!"; // Adding this RichTextBox in the form this.Controls.Add(rbox); }}} Output: C# Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. C# | How to insert an element in an Array? HashSet in C# with Examples Convert String to Character Array in C# Console.ReadLine() Method in C# Program to Print a New Line in C# Different ways to create an Object in C# C# | Interface C# | Abstraction C# | Optional Parameters ref in C#
[ { "code": null, "e": 25547, "s": 25519, "text": "\n17 Jul, 2019" }, { "code": null, "e": 25992, "s": 25547, "text": "In C#, RichTextBox control is a textbox which gives you rich text editing controls and advanced formatting features also includes a loading rich text format (RTF) files. Or in other words, RichTextBox controls allows you to display or edit flow content, including paragraphs, images, tables, etc. In RichTextBox, you are allowed to set the font of the content present in the RichTextBox control. You can set this property in two different ways:" }, { "code": null, "e": 26121, "s": 25992, "text": "1. Design-Time: It is the easiest way to set the font of the content present in the RichTextBox as shown in the following steps:" }, { "code": null, "e": 26237, "s": 26121, "text": "Step 1: Create a windows form as shown in the below image:Visual Studio -> File -> New -> Project -> WindowsFormApp" }, { "code": null, "e": 26424, "s": 26237, "text": "Step 2: Drag the RichTextBox control from the ToolBox and drop it on the windows form. You are allowed to place a RichTextBox control anywhere on the windows form according to your need." }, { "code": null, "e": 26580, "s": 26424, "text": "Step 3: After drag and drop you will go to the properties of the RichTextBox control set the font of the content present in the RichTextBox control.Output:" }, { "code": null, "e": 26588, "s": 26580, "text": "Output:" }, { "code": null, "e": 26787, "s": 26588, "text": "2. Run-Time: It is a little bit trickier than the above method. In this method, you can set the font of the content present in the RichTextBox control programmatically with the help of given syntax:" }, { "code": null, "e": 26841, "s": 26787, "text": "public virtual System.Drawing.Font Font { get; set; }" }, { "code": null, "e": 26998, "s": 26841, "text": "Here, the Font is the type of font applied to the RichTextBox content. The following steps show how to set the Font property of the RichTextBox dynamically:" }, { "code": null, "e": 27199, "s": 26998, "text": "Step 1: Create a RichTextBox using the RichTextBox() constructor is provided by the RichTextBox class.// Creating RichTextBox using RichTextBox class constructor\nRichTextBox rbox = new RichTextBox();\n" }, { "code": null, "e": 27298, "s": 27199, "text": "// Creating RichTextBox using RichTextBox class constructor\nRichTextBox rbox = new RichTextBox();\n" }, { "code": null, "e": 27468, "s": 27298, "text": "Step 2: After creating RichTextBox, set the Font property of the RichTextBox provided by the RichTextBox class.// Setting the font\nrbox.Font = new Font(\"Castellar\", 8);\n" }, { "code": null, "e": 27527, "s": 27468, "text": "// Setting the font\nrbox.Font = new Font(\"Castellar\", 8);\n" }, { "code": null, "e": 28707, "s": 27527, "text": "Step 3: And last add this RichTextBox control to the form using Add() method.// Add this RichTextBox to the form\nthis.Controls.Add(rbox);\nExample:using System;using System.Collections.Generic;using System.ComponentModel;using System.Data;using System.Drawing;using System.Linq;using System.Text;using System.Threading.Tasks;using System.Windows.Forms; namespace WindowsFormsApp30 { public partial class Form1 : Form { public Form1() { InitializeComponent(); } private void Form1_Load(object sender, EventArgs e) { // Creating and setting the // properties of the label Label lb = new Label(); lb.Location = new Point(251, 70); lb.Text = \"Enter Text\"; // Adding this label in the form this.Controls.Add(lb); // Creating and setting the // properties of the RichTextBox RichTextBox rbox = new RichTextBox(); rbox.Location = new Point(236, 97); rbox.ForeColor = Color.Red; rbox.Font = new Font(\"Castellar\", 8); rbox.Text = \"!..Welcome to GeeksforGeeks..!\"; // Adding this RichTextBox in the form this.Controls.Add(rbox); }}}Output:" }, { "code": null, "e": 28769, "s": 28707, "text": "// Add this RichTextBox to the form\nthis.Controls.Add(rbox);\n" }, { "code": null, "e": 28778, "s": 28769, "text": "Example:" }, { "code": "using System;using System.Collections.Generic;using System.ComponentModel;using System.Data;using System.Drawing;using System.Linq;using System.Text;using System.Threading.Tasks;using System.Windows.Forms; namespace WindowsFormsApp30 { public partial class Form1 : Form { public Form1() { InitializeComponent(); } private void Form1_Load(object sender, EventArgs e) { // Creating and setting the // properties of the label Label lb = new Label(); lb.Location = new Point(251, 70); lb.Text = \"Enter Text\"; // Adding this label in the form this.Controls.Add(lb); // Creating and setting the // properties of the RichTextBox RichTextBox rbox = new RichTextBox(); rbox.Location = new Point(236, 97); rbox.ForeColor = Color.Red; rbox.Font = new Font(\"Castellar\", 8); rbox.Text = \"!..Welcome to GeeksforGeeks..!\"; // Adding this RichTextBox in the form this.Controls.Add(rbox); }}}", "e": 29805, "s": 28778, "text": null }, { "code": null, "e": 29813, "s": 29805, "text": "Output:" }, { "code": null, "e": 29816, "s": 29813, "text": "C#" }, { "code": null, "e": 29914, "s": 29816, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 29957, "s": 29914, "text": "C# | How to insert an element in an Array?" }, { "code": null, "e": 29985, "s": 29957, "text": "HashSet in C# with Examples" }, { "code": null, "e": 30025, "s": 29985, "text": "Convert String to Character Array in C#" }, { "code": null, "e": 30057, "s": 30025, "text": "Console.ReadLine() Method in C#" }, { "code": null, "e": 30091, "s": 30057, "text": "Program to Print a New Line in C#" }, { "code": null, "e": 30132, "s": 30091, "text": "Different ways to create an Object in C#" }, { "code": null, "e": 30147, "s": 30132, "text": "C# | Interface" }, { "code": null, "e": 30164, "s": 30147, "text": "C# | Abstraction" }, { "code": null, "e": 30189, "s": 30164, "text": "C# | Optional Parameters" } ]
Tryit Editor v3.7
Tryit: HTML table cells
[]
Power Of Numbers | Practice | GeeksforGeeks
Given a number and its reverse. Find that number raised to the power of its own reverse. Note: As answers can be very large, print the result modulo 109 + 7. Example 1: Input: N = 2 Output: 4 Explanation: The reverse of 2 is 2 and after raising power of 2 by 2 we get 4 which gives remainder as 4 by dividing 1000000007. Example 2: Input: N = 12 Output: 864354781 Explanation: The reverse of 12 is 21 and 1221 , when divided by 1000000007 gives remainder as 864354781. Your Task: You don't need to read input or print anything. You just need to complete the function pow() that takes two parameters N and R denoting the input number and its reverse and returns power of (N to R)mod(109 + 7). Expected Time Complexity: O(LogN). Expected Auxiliary Space: O(LogN). Constraints: 1 <= N <= 109 0 aashishkumar09111 week ago whats the error in this code can anyone please help long long power(int N,int R) { //Your code here const int m=1e+7; long long ans=1; while(R>0){ if(R&1) ans=(ans*N)%m; N=(N*N)%m; R>>=1; } return ans; } 0 ugamthakkar2 weeks ago class Solution{ public: const long long m = 1e9+7; long long count(int n, int r){ long res=1; while(r>0){ if(r&1){ res = (res* n%m)%m; } n = (n%m * n%m)%m; r = r>>1; } return res; } //You need to complete this fucntion long long power(int N,int R) { //Your code here return count(N,R); } }; 0 arjunnigam17132 weeks ago class Solution: #Complete this function def power(self,N,R): #Your code here if R==0: return 1 temp = self.power(N,R//2) if R%2==0: return (temp*temp)%(1000000007) else: return (N*temp*temp)%(1000000007) -6 sharankushal03 weeks ago C++ all test cases pass🎉 long long power(long long int N,int R) { static long long int m=1000000007; if(R==0) return 1; if(R==1) return N; if(R%2==0) return power((N*N)%m, R/2)%m; else return (N%m)*power((N*N)%m, (R-1)/2)%m; } -1 moaslam8263 weeks ago c++ soln const long long m=1e9+7; long long fun(int n,int r){ if(r==1){ return n; } if(r==0){ return 1; } long long ans=fun(n,r/2); if(r&1){ return n*1LL*ans%m *ans%m; } return ans%m*1LL*ans%m; } long long power(int N,int R) { return fun(N,R); } 0 akkeshri140420011 month ago long long power(int N,int R) { //Your code here if(R==0){ return 1; } if(R==1){ return N; } long long know=power(N,R/2)%mod; long long ans=1; if(R%2){ ans=(ans*N)%mod; } return ans*((know*know)%mod)%mod; } 0 velspace011 month ago Java Solution.Works for all test Cases static long m=1000000007; long power(long N,long R) { long ans; if(R==0){ return 1; } if(R==1){ return N; } if(R%2==0){ ans=power((N*N)%m,R/2); }else{ ans=(N%m)*power((N*N)%m,R/2); } return ans%m; } +1 anukoolsrivastava1 month ago Python Solution. Works for all test cases. def power(self,N,R): self.N=N if R==0: return 1 ans=self.power(self.N,R//2) if R%2==0: return (ans*ans)%(1000000007) else: return self.N*ans*ans%(1000000007) 0 salonitayal1 month ago Can anybody tell why this is wrong? long long power(int N,int R) { if(R==0)return 1; if(R&1) { return (N%1000000007)*(power(N, R/2)%1000000007*power(N, R/2)%1000000007); } else { return ((power(N, R/2)%1000000007)*(power(N, R/2)%1000000007))%1000000007; } } +1 joker381 month ago whats wrong with this code? class Solution{ private: long long powerFunction(int a,int b) { if(b==0) { return 1; } if(b==1) { return a; } long long ans=powerFunction(a,b/2); if(b%2==0) { return ans*ans; } else { return a*ans*ans; } } public: //You need to complete this fucntion long long power(int N,int R) { //Your code here long long int m= 1000000007; long long ans= powerFunction(N,R)%m; return ans; } }; We strongly recommend solving this problem on your own before viewing its editorial. Do you still want to view the editorial? Login to access your submissions. Problem Contest Reset the IDE using the second button on the top right corner. Avoid using static/global variables in your code as your code is tested against multiple test cases and these tend to retain their previous values. Passing the Sample/Custom Test cases does not guarantee the correctness of code. On submission, your code is tested against multiple test cases consisting of all possible corner cases and stress constraints. You can access the hints to get an idea about what is expected of you as well as the final solution code. You can view the solutions submitted by other users from the submission tab.
[ { "code": null, "e": 396, "s": 238, "text": "Given a number and its reverse. Find that number raised to the power of its own reverse.\nNote: As answers can be very large, print the result modulo 109 + 7." }, { "code": null, "e": 407, "s": 396, "text": "Example 1:" }, { "code": null, "e": 561, "s": 407, "text": "Input:\nN = 2\nOutput: 4\nExplanation: The reverse of 2 is 2\nand after raising power of 2 by 2 \nwe get 4 which gives remainder as \n4 by dividing 1000000007." }, { "code": null, "e": 572, "s": 561, "text": "Example 2:" }, { "code": null, "e": 710, "s": 572, "text": "Input:\nN = 12\nOutput: 864354781\nExplanation: The reverse of 12 is 21\nand 1221 , when divided by 1000000007 \ngives remainder as 864354781." }, { "code": null, "e": 933, "s": 710, "text": "Your Task:\nYou don't need to read input or print anything. You just need to complete the function pow() that takes two parameters N and R denoting the input number and its reverse and returns power of (N to R)mod(109 + 7)." }, { "code": null, "e": 1003, "s": 933, "text": "Expected Time Complexity: O(LogN).\nExpected Auxiliary Space: O(LogN)." }, { "code": null, "e": 1030, "s": 1003, "text": "Constraints:\n1 <= N <= 109" }, { "code": null, "e": 1034, "s": 1032, "text": "0" }, { "code": null, "e": 1061, "s": 1034, "text": "aashishkumar09111 week ago" }, { "code": null, "e": 1113, "s": 1061, "text": "whats the error in this code can anyone please help" }, { "code": null, "e": 1341, "s": 1115, "text": "long long power(int N,int R) { //Your code here const int m=1e+7; long long ans=1; while(R>0){ if(R&1) ans=(ans*N)%m; N=(N*N)%m; R>>=1; } return ans; }" }, { "code": null, "e": 1343, "s": 1341, "text": "0" }, { "code": null, "e": 1366, "s": 1343, "text": "ugamthakkar2 weeks ago" }, { "code": null, "e": 1780, "s": 1366, "text": "class Solution{ public: const long long m = 1e9+7; long long count(int n, int r){ long res=1; while(r>0){ if(r&1){ res = (res* n%m)%m; } n = (n%m * n%m)%m; r = r>>1; } return res; } //You need to complete this fucntion long long power(int N,int R) { //Your code here return count(N,R); }" }, { "code": null, "e": 1783, "s": 1780, "text": "};" }, { "code": null, "e": 1785, "s": 1783, "text": "0" }, { "code": null, "e": 1811, "s": 1785, "text": "arjunnigam17132 weeks ago" }, { "code": null, "e": 2117, "s": 1811, "text": "class Solution:\n #Complete this function\n def power(self,N,R):\n #Your code here\n \n if R==0:\n return 1\n \n temp = self.power(N,R//2)\n if R%2==0:\n return (temp*temp)%(1000000007)\n else:\n return (N*temp*temp)%(1000000007)" }, { "code": null, "e": 2120, "s": 2117, "text": "-6" }, { "code": null, "e": 2145, "s": 2120, "text": "sharankushal03 weeks ago" }, { "code": null, "e": 2170, "s": 2145, "text": "C++ all test cases pass🎉" }, { "code": null, "e": 2376, "s": 2170, "text": "long long power(long long int N,int R)\n{\nstatic long long int m=1000000007;\nif(R==0)\n\treturn 1;\nif(R==1)\n\treturn N;\nif(R%2==0)\n\treturn power((N*N)%m, R/2)%m;\nelse\n\treturn (N%m)*power((N*N)%m, (R-1)/2)%m;\n}" }, { "code": null, "e": 2381, "s": 2378, "text": "-1" }, { "code": null, "e": 2403, "s": 2381, "text": "moaslam8263 weeks ago" }, { "code": null, "e": 2412, "s": 2403, "text": "c++ soln" }, { "code": null, "e": 2799, "s": 2412, "text": "const long long m=1e9+7;\n long long fun(int n,int r){\n if(r==1){\n return n;\n }\n if(r==0){\n return 1;\n }\n long long ans=fun(n,r/2);\n if(r&1){\n return n*1LL*ans%m *ans%m;\n }\n return ans%m*1LL*ans%m;\n }\n long long power(int N,int R)\n {\n \n \n return fun(N,R);\n \n \n }" }, { "code": null, "e": 2801, "s": 2799, "text": "0" }, { "code": null, "e": 2829, "s": 2801, "text": "akkeshri140420011 month ago" }, { "code": null, "e": 3139, "s": 2829, "text": "long long power(int N,int R)\n {\n //Your code here\n if(R==0){\n return 1;\n }\n if(R==1){\n return N;\n }\n long long know=power(N,R/2)%mod;\n long long ans=1;\n if(R%2){\n ans=(ans*N)%mod;\n }\n return ans*((know*know)%mod)%mod;\n \n }" }, { "code": null, "e": 3141, "s": 3139, "text": "0" }, { "code": null, "e": 3163, "s": 3141, "text": "velspace011 month ago" }, { "code": null, "e": 3546, "s": 3163, "text": "Java Solution.Works for all test Cases\nstatic long m=1000000007; \n long power(long N,long R)\n {\n long ans;\n if(R==0){\n return 1;\n }\n if(R==1){\n return N;\n }\n if(R%2==0){\n ans=power((N*N)%m,R/2);\n }else{\n ans=(N%m)*power((N*N)%m,R/2);\n }\n return ans%m;\n \n }" }, { "code": null, "e": 3549, "s": 3546, "text": "+1" }, { "code": null, "e": 3578, "s": 3549, "text": "anukoolsrivastava1 month ago" }, { "code": null, "e": 3866, "s": 3578, "text": "Python Solution. Works for all test cases.\n \n def power(self,N,R):\n self.N=N\n if R==0:\n return 1\n ans=self.power(self.N,R//2)\n if R%2==0:\n return (ans*ans)%(1000000007)\n else:\n return self.N*ans*ans%(1000000007)" }, { "code": null, "e": 3868, "s": 3866, "text": "0" }, { "code": null, "e": 3891, "s": 3868, "text": "salonitayal1 month ago" }, { "code": null, "e": 3927, "s": 3891, "text": "Can anybody tell why this is wrong?" }, { "code": null, "e": 4232, "s": 3929, "text": "long long power(int N,int R)\n {\n if(R==0)return 1;\n if(R&1)\n {\n return (N%1000000007)*(power(N, R/2)%1000000007*power(N, R/2)%1000000007);\n }\n else \n {\n return ((power(N, R/2)%1000000007)*(power(N, R/2)%1000000007))%1000000007;\n }\n }\n" }, { "code": null, "e": 4235, "s": 4232, "text": "+1" }, { "code": null, "e": 4254, "s": 4235, "text": "joker381 month ago" }, { "code": null, "e": 4282, "s": 4254, "text": "whats wrong with this code?" }, { "code": null, "e": 4827, "s": 4282, "text": "class Solution{ private: long long powerFunction(int a,int b) { if(b==0) { return 1; } if(b==1) { return a; } long long ans=powerFunction(a,b/2); if(b%2==0) { return ans*ans; } else { return a*ans*ans; } } public: //You need to complete this fucntion long long power(int N,int R) { //Your code here long long int m= 1000000007; long long ans= powerFunction(N,R)%m; return ans; }" }, { "code": null, "e": 4830, "s": 4827, "text": "};" }, { "code": null, "e": 4976, "s": 4830, "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": 5012, "s": 4976, "text": " Login to access your submissions. " }, { "code": null, "e": 5022, "s": 5012, "text": "\nProblem\n" }, { "code": null, "e": 5032, "s": 5022, "text": "\nContest\n" }, { "code": null, "e": 5095, "s": 5032, "text": "Reset the IDE using the second button on the top right corner." }, { "code": null, "e": 5243, "s": 5095, "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": 5451, "s": 5243, "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": 5557, "s": 5451, "text": "You can access the hints to get an idea about what is expected of you as well as the final solution code." } ]
Generating Synthetic Patient Data | by Akash Kaul | Towards Data Science
Using healthcare data for research can be tricky, and there can be many legal and financial hoops to jump through in order to use certain data. This is especially true when dealing with the information of specific patients. But, these hurdles can be avoided with synthetic data created using Synthea, an open-source patient generator. Synthea creates realistic data that can be used without restriction. Best of all, it’s extremely user-friendly. Before you start creating your own patients, make sure you have the latest version of JDK (JDK 14). If you don’t already have it, you can follow this installation guide. Be sure you install JDK 14, and NOT JRE 14. The next step is to install Synthea. If you are just looking to run Synthea without much flexibility and customizability, you can install the basic version using the link here. Alternatively, you can create a local copy of the Github repository if you want more freedom to play around with the code. I’ll walk through using the basic version, and I’ll leave exploring the more expansive version to you (follow these instructions). Once Synthea is installed, open up your terminal and change to the directory where the file was downloaded. For me, that’s the “Downloads” folder. cd /directory/with/downloaded/file Once you’re in the directory, you can run Synthea with JUST ONE COMMAND! All you need to do is open the JAR file. java -jar synthea-with-dependencies.jar You should see a bunch of text pop up in the terminal. Just like that, you’ve successfully created a synthetic patient; but, that’s just the surface of what Synthea has to offer. There are several different parameters that you can use to customize the patients you create. For a full list of parameters, check out the Synthea wiki. Let’s take a look at some useful ones. -p size — Generate a population of the specified size (The size specifies the number of alive members of the population, so the total population size will likely be bigger) -g gender— Generate a population of one gender (M for male, F for female) -a ageRange — Generate a population within a range of ages (i.e. 30–40) -m module — Generate a population using a specific ailment (i.e. Asthma, Dermatitis, Lupus, etc.) A full list of modules can be found here. State City — Generate a population within a specific area (i.e. Minnesota, Texas Dallas, etc.) The city is optional. Only 1 state can be run at a time; if nothing is specified, the default state is Massachusetts. --exporter.csv.export true — Exports the data as a CSV file. The default format is FHIR. The patient information is split up into multiple CSV files based on different data like “medications”, “encounters”, “providers”, and many others. You can also choose from lots of other output formats. The full list can be found here. With these parameters, we can generate some pretty meaningful data. These parameters can all be combined, and the more parameters you use, the more specific the data you generate will be. Let’s look at a couple of examples. java -jar synthea-with-dependencies.jar -p 500 -a 20–50 Minnesota This generates a list of patients between the ages of 20 and 50 who live in Minnesota. The list will have 500 alive patients and some number of dead patients. java -jar synthea-with-dependencies.jar -p 100 -g F -m Asthma --exporter.csv.export true This generates a list of at least 100 female patients using only the asthma module and exports the data as a CSV file. There are lots of ways that you can combine different parameters to create very different data sets. I encourage you to experiment, try different parameters, and see what you get. Or, if you’re feeling comfortable with the basic model, you can install the full repository and explore everything Synthea has to offer. I hope you enjoyed this short introduction to Synthea, and I hope I showed you how easy-to-use and powerful this tool really is. Whether you’re working on a large-scale project, or you’re just experimenting on your laptop, the possibilities are truly endless.
[ { "code": null, "e": 619, "s": 172, "text": "Using healthcare data for research can be tricky, and there can be many legal and financial hoops to jump through in order to use certain data. This is especially true when dealing with the information of specific patients. But, these hurdles can be avoided with synthetic data created using Synthea, an open-source patient generator. Synthea creates realistic data that can be used without restriction. Best of all, it’s extremely user-friendly." }, { "code": null, "e": 833, "s": 619, "text": "Before you start creating your own patients, make sure you have the latest version of JDK (JDK 14). If you don’t already have it, you can follow this installation guide. Be sure you install JDK 14, and NOT JRE 14." }, { "code": null, "e": 1264, "s": 833, "text": "The next step is to install Synthea. If you are just looking to run Synthea without much flexibility and customizability, you can install the basic version using the link here. Alternatively, you can create a local copy of the Github repository if you want more freedom to play around with the code. I’ll walk through using the basic version, and I’ll leave exploring the more expansive version to you (follow these instructions)." }, { "code": null, "e": 1411, "s": 1264, "text": "Once Synthea is installed, open up your terminal and change to the directory where the file was downloaded. For me, that’s the “Downloads” folder." }, { "code": null, "e": 1446, "s": 1411, "text": "cd /directory/with/downloaded/file" }, { "code": null, "e": 1560, "s": 1446, "text": "Once you’re in the directory, you can run Synthea with JUST ONE COMMAND! All you need to do is open the JAR file." }, { "code": null, "e": 1600, "s": 1560, "text": "java -jar synthea-with-dependencies.jar" }, { "code": null, "e": 1655, "s": 1600, "text": "You should see a bunch of text pop up in the terminal." }, { "code": null, "e": 1779, "s": 1655, "text": "Just like that, you’ve successfully created a synthetic patient; but, that’s just the surface of what Synthea has to offer." }, { "code": null, "e": 1932, "s": 1779, "text": "There are several different parameters that you can use to customize the patients you create. For a full list of parameters, check out the Synthea wiki." }, { "code": null, "e": 1971, "s": 1932, "text": "Let’s take a look at some useful ones." }, { "code": null, "e": 2144, "s": 1971, "text": "-p size — Generate a population of the specified size (The size specifies the number of alive members of the population, so the total population size will likely be bigger)" }, { "code": null, "e": 2218, "s": 2144, "text": "-g gender— Generate a population of one gender (M for male, F for female)" }, { "code": null, "e": 2290, "s": 2218, "text": "-a ageRange — Generate a population within a range of ages (i.e. 30–40)" }, { "code": null, "e": 2430, "s": 2290, "text": "-m module — Generate a population using a specific ailment (i.e. Asthma, Dermatitis, Lupus, etc.) A full list of modules can be found here." }, { "code": null, "e": 2643, "s": 2430, "text": "State City — Generate a population within a specific area (i.e. Minnesota, Texas Dallas, etc.) The city is optional. Only 1 state can be run at a time; if nothing is specified, the default state is Massachusetts." }, { "code": null, "e": 2968, "s": 2643, "text": "--exporter.csv.export true — Exports the data as a CSV file. The default format is FHIR. The patient information is split up into multiple CSV files based on different data like “medications”, “encounters”, “providers”, and many others. You can also choose from lots of other output formats. The full list can be found here." }, { "code": null, "e": 3192, "s": 2968, "text": "With these parameters, we can generate some pretty meaningful data. These parameters can all be combined, and the more parameters you use, the more specific the data you generate will be. Let’s look at a couple of examples." }, { "code": null, "e": 3258, "s": 3192, "text": "java -jar synthea-with-dependencies.jar -p 500 -a 20–50 Minnesota" }, { "code": null, "e": 3417, "s": 3258, "text": "This generates a list of patients between the ages of 20 and 50 who live in Minnesota. The list will have 500 alive patients and some number of dead patients." }, { "code": null, "e": 3506, "s": 3417, "text": "java -jar synthea-with-dependencies.jar -p 100 -g F -m Asthma --exporter.csv.export true" }, { "code": null, "e": 3625, "s": 3506, "text": "This generates a list of at least 100 female patients using only the asthma module and exports the data as a CSV file." }, { "code": null, "e": 3942, "s": 3625, "text": "There are lots of ways that you can combine different parameters to create very different data sets. I encourage you to experiment, try different parameters, and see what you get. Or, if you’re feeling comfortable with the basic model, you can install the full repository and explore everything Synthea has to offer." } ]
DataTables searchDelay Option - GeeksforGeeks
13 Jul, 2021 DataTables is a jQuery plugin that can be used for adding interactive and advanced controls to HTML tables for the webpage. This also allows the data in the table to be searched, sorted, and filtered according to the needs of the user. The DataTable also exposes a powerful API that can be further used to modify how the data is displayed. The searchDelay option is used to specify the number of milliseconds after which the term entered the search box is searched in the table. This can be useful to reduce the number of redraws of the table and save processing power on slower systems. It accepts an integer value that denotes the number of milliseconds of the delay. The default value for client-side search is 0ms, which means that the value is searched and the results are displayed immediately. On the server-side, the delay is set to a default of 400ms to reduce the number of calls to the server. Note: This affects only the global search box of the DataTable. The API methods like search() are not affected by changing this option. Syntax: { searchDelay: value } Parameters: This option has a single value as mentioned above and described below. value: This is an integer value that specifies the number of milliseconds after which the search is executed. The example below illustrates the use of this option. Example 1: In this example, we set the search delay to 2000 milliseconds. HTML <!DOCTYPE html><html> <head> <!-- jQuery --> <script type="text/javascript" src="https://code.jquery.com/jquery-3.5.1.js"> </script> <!-- DataTables CSS --> <link rel="stylesheet" href="https://cdn.datatables.net/1.10.23/css/jquery.dataTables.min.css"> <!-- DataTables JS --> <script src="https://cdn.datatables.net/1.10.23/js/jquery.dataTables.min.js"> </script></head> <body> <h1 style="color: green;"> GeeksForGeeks </h1> <h3>DataTables searchDelay Option</h3> <!-- HTML table with random data --> <table id="tableID" class="display nowrap"> <thead> <tr> <th>Day</th> <th>Name</th> <th>Age</th> </tr> </thead> <tbody> <tr> <td>2</td> <td>Patricia</td> <td>22</td> </tr> <tr> <td>2</td> <td>Caleb</td> <td>47</td> </tr> <tr> <td>1</td> <td>Abigail</td> <td>48</td> </tr> <tr> <td>5</td> <td>Rahim</td> <td>44</td> </tr> <tr> <td>5</td> <td>Sheila</td> <td>22</td> </tr> <tr> <td>2</td> <td>Lance</td> <td>48</td> </tr> <tr> <td>5</td> <td>Erin</td> <td>48</td> </tr> <tr> <td>1</td> <td>Christopher</td> <td>28</td> </tr> <tr> <td>2</td> <td>Roary</td> <td>35</td> </tr> <tr> <td>2</td> <td>Astra</td> <td>37</td> </tr> </tbody> </table> <script> // Initialize the DataTable $(document).ready(function () { $('#tableID').DataTable({ // Enable delaying of the search // to the given number of milliseconds searchDelay: 2000 }); }); </script></body> </html> Output: Example 2: In this example, we set the search delay to 0 milliseconds, which means that a search is instant. HTML <!DOCTYPE html><html> <head> <!-- jQuery --> <script type="text/javascript" src="https://code.jquery.com/jquery-3.5.1.js"> </script> <!-- DataTables CSS --> <link rel="stylesheet" href="https://cdn.datatables.net/1.10.23/css/jquery.dataTables.min.css"> <!-- DataTables JS --> <script src= "https://cdn.datatables.net/1.10.23/js/jquery.dataTables.min.js"> </script></head> <body> <h1 style="color: green;"> GeeksForGeeks </h1> <h3>DataTables searchDelay Option</h3> <!-- HTML table with random data --> <table id="tableID" class="display nowrap"> <thead> <tr> <th>Day</th> <th>Name</th> <th>Age</th> </tr> </thead> <tbody> <tr> <td>2</td> <td>Patricia</td> <td>22</td> </tr> <tr> <td>2</td> <td>Caleb</td> <td>47</td> </tr> <tr> <td>1</td> <td>Abigail</td> <td>48</td> </tr> <tr> <td>5</td> <td>Rahim</td> <td>44</td> </tr> <tr> <td>5</td> <td>Sheila</td> <td>22</td> </tr> <tr> <td>2</td> <td>Lance</td> <td>48</td> </tr> <tr> <td>5</td> <td>Erin</td> <td>48</td> </tr> <tr> <td>1</td> <td>Christopher</td> <td>28</td> </tr> <tr> <td>2</td> <td>Roary</td> <td>35</td> </tr> <tr> <td>2</td> <td>Astra</td> <td>37</td> </tr> </tbody> </table> <script> // Initialize the DataTable $(document).ready(function () { $('#tableID').DataTable({ // Prevent any delay of the search // by setting the value to 0 searchDelay: 0 }); }); </script></body> </html> Output: Reference link: https://datatables.net/reference/option/searchDelay jQuery-DataTables JQuery Web Technologies Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments How to prevent Body from scrolling when a modal is opened using jQuery ? jQuery | ajax() Method Difference Between JavaScript and jQuery How to get the value in an input text box using jQuery ? QR Code Generator using HTML, CSS and jQuery Top 10 Front End Developer Skills That You Need in 2022 Installation of Node.js on Linux Top 10 Projects For Beginners To Practice HTML and CSS Skills How to fetch data from an API in ReactJS ? How to insert spaces/tabs in text using HTML/CSS?
[ { "code": null, "e": 25364, "s": 25336, "text": "\n13 Jul, 2021" }, { "code": null, "e": 25704, "s": 25364, "text": "DataTables is a jQuery plugin that can be used for adding interactive and advanced controls to HTML tables for the webpage. This also allows the data in the table to be searched, sorted, and filtered according to the needs of the user. The DataTable also exposes a powerful API that can be further used to modify how the data is displayed." }, { "code": null, "e": 26269, "s": 25704, "text": "The searchDelay option is used to specify the number of milliseconds after which the term entered the search box is searched in the table. This can be useful to reduce the number of redraws of the table and save processing power on slower systems. It accepts an integer value that denotes the number of milliseconds of the delay. The default value for client-side search is 0ms, which means that the value is searched and the results are displayed immediately. On the server-side, the delay is set to a default of 400ms to reduce the number of calls to the server." }, { "code": null, "e": 26405, "s": 26269, "text": "Note: This affects only the global search box of the DataTable. The API methods like search() are not affected by changing this option." }, { "code": null, "e": 26413, "s": 26405, "text": "Syntax:" }, { "code": null, "e": 26436, "s": 26413, "text": "{ searchDelay: value }" }, { "code": null, "e": 26521, "s": 26438, "text": "Parameters: This option has a single value as mentioned above and described below." }, { "code": null, "e": 26631, "s": 26521, "text": "value: This is an integer value that specifies the number of milliseconds after which the search is executed." }, { "code": null, "e": 26685, "s": 26631, "text": "The example below illustrates the use of this option." }, { "code": null, "e": 26759, "s": 26685, "text": "Example 1: In this example, we set the search delay to 2000 milliseconds." }, { "code": null, "e": 26764, "s": 26759, "text": "HTML" }, { "code": "<!DOCTYPE html><html> <head> <!-- jQuery --> <script type=\"text/javascript\" src=\"https://code.jquery.com/jquery-3.5.1.js\"> </script> <!-- DataTables CSS --> <link rel=\"stylesheet\" href=\"https://cdn.datatables.net/1.10.23/css/jquery.dataTables.min.css\"> <!-- DataTables JS --> <script src=\"https://cdn.datatables.net/1.10.23/js/jquery.dataTables.min.js\"> </script></head> <body> <h1 style=\"color: green;\"> GeeksForGeeks </h1> <h3>DataTables searchDelay Option</h3> <!-- HTML table with random data --> <table id=\"tableID\" class=\"display nowrap\"> <thead> <tr> <th>Day</th> <th>Name</th> <th>Age</th> </tr> </thead> <tbody> <tr> <td>2</td> <td>Patricia</td> <td>22</td> </tr> <tr> <td>2</td> <td>Caleb</td> <td>47</td> </tr> <tr> <td>1</td> <td>Abigail</td> <td>48</td> </tr> <tr> <td>5</td> <td>Rahim</td> <td>44</td> </tr> <tr> <td>5</td> <td>Sheila</td> <td>22</td> </tr> <tr> <td>2</td> <td>Lance</td> <td>48</td> </tr> <tr> <td>5</td> <td>Erin</td> <td>48</td> </tr> <tr> <td>1</td> <td>Christopher</td> <td>28</td> </tr> <tr> <td>2</td> <td>Roary</td> <td>35</td> </tr> <tr> <td>2</td> <td>Astra</td> <td>37</td> </tr> </tbody> </table> <script> // Initialize the DataTable $(document).ready(function () { $('#tableID').DataTable({ // Enable delaying of the search // to the given number of milliseconds searchDelay: 2000 }); }); </script></body> </html>", "e": 28565, "s": 26764, "text": null }, { "code": null, "e": 28573, "s": 28565, "text": "Output:" }, { "code": null, "e": 28682, "s": 28573, "text": "Example 2: In this example, we set the search delay to 0 milliseconds, which means that a search is instant." }, { "code": null, "e": 28687, "s": 28682, "text": "HTML" }, { "code": "<!DOCTYPE html><html> <head> <!-- jQuery --> <script type=\"text/javascript\" src=\"https://code.jquery.com/jquery-3.5.1.js\"> </script> <!-- DataTables CSS --> <link rel=\"stylesheet\" href=\"https://cdn.datatables.net/1.10.23/css/jquery.dataTables.min.css\"> <!-- DataTables JS --> <script src= \"https://cdn.datatables.net/1.10.23/js/jquery.dataTables.min.js\"> </script></head> <body> <h1 style=\"color: green;\"> GeeksForGeeks </h1> <h3>DataTables searchDelay Option</h3> <!-- HTML table with random data --> <table id=\"tableID\" class=\"display nowrap\"> <thead> <tr> <th>Day</th> <th>Name</th> <th>Age</th> </tr> </thead> <tbody> <tr> <td>2</td> <td>Patricia</td> <td>22</td> </tr> <tr> <td>2</td> <td>Caleb</td> <td>47</td> </tr> <tr> <td>1</td> <td>Abigail</td> <td>48</td> </tr> <tr> <td>5</td> <td>Rahim</td> <td>44</td> </tr> <tr> <td>5</td> <td>Sheila</td> <td>22</td> </tr> <tr> <td>2</td> <td>Lance</td> <td>48</td> </tr> <tr> <td>5</td> <td>Erin</td> <td>48</td> </tr> <tr> <td>1</td> <td>Christopher</td> <td>28</td> </tr> <tr> <td>2</td> <td>Roary</td> <td>35</td> </tr> <tr> <td>2</td> <td>Astra</td> <td>37</td> </tr> </tbody> </table> <script> // Initialize the DataTable $(document).ready(function () { $('#tableID').DataTable({ // Prevent any delay of the search // by setting the value to 0 searchDelay: 0 }); }); </script></body> </html>", "e": 30489, "s": 28687, "text": null }, { "code": null, "e": 30497, "s": 30489, "text": "Output:" }, { "code": null, "e": 30565, "s": 30497, "text": "Reference link: https://datatables.net/reference/option/searchDelay" }, { "code": null, "e": 30583, "s": 30565, "text": "jQuery-DataTables" }, { "code": null, "e": 30590, "s": 30583, "text": "JQuery" }, { "code": null, "e": 30607, "s": 30590, "text": "Web Technologies" }, { "code": null, "e": 30705, "s": 30607, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 30714, "s": 30705, "text": "Comments" }, { "code": null, "e": 30727, "s": 30714, "text": "Old Comments" }, { "code": null, "e": 30800, "s": 30727, "text": "How to prevent Body from scrolling when a modal is opened using jQuery ?" }, { "code": null, "e": 30823, "s": 30800, "text": "jQuery | ajax() Method" }, { "code": null, "e": 30864, "s": 30823, "text": "Difference Between JavaScript and jQuery" }, { "code": null, "e": 30921, "s": 30864, "text": "How to get the value in an input text box using jQuery ?" }, { "code": null, "e": 30966, "s": 30921, "text": "QR Code Generator using HTML, CSS and jQuery" }, { "code": null, "e": 31022, "s": 30966, "text": "Top 10 Front End Developer Skills That You Need in 2022" }, { "code": null, "e": 31055, "s": 31022, "text": "Installation of Node.js on Linux" }, { "code": null, "e": 31117, "s": 31055, "text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills" }, { "code": null, "e": 31160, "s": 31117, "text": "How to fetch data from an API in ReactJS ?" } ]
Check if edit distance between two strings is one - GeeksforGeeks
20 Jan, 2022 An edit between two strings is one of the following changes. Add a characterDelete a characterChange a character Add a character Delete a character Change a character Given two string s1 and s2, find if s1 can be converted to s2 with exactly one edit. Expected time complexity is O(m+n) where m and n are lengths of two strings. Examples: Input: s1 = "geeks", s2 = "geek" Output: yes Number of edits is 1 Input: s1 = "geeks", s2 = "geeks" Output: no Number of edits is 0 Input: s1 = "geaks", s2 = "geeks" Output: yes Number of edits is 1 Input: s1 = "peaks", s2 = "geeks" Output: no Number of edits is 2 A Simple Solution is to find Edit Distance using Dynamic programming. If distance is 1, then return true, else return false. Time complexity of this solution is O(n2)An Efficient Solution is to simultaneously traverse both strings and keep track of count of different characters. Below is complete algorithm. Let the input strings be s1 and s2 and lengths of input strings be m and n respectively. 1) If difference between m an n is more than 1, return false. 2) Initialize count of edits as 0. 3) Start traversing both strings from first character. a) If current characters don't match, then (i) Increment count of edits (ii) If count becomes more than 1, return false (iii) If length of one string is more, then only possible edit is to remove a character. Therefore, move ahead in larger string. (iv) If length is same, then only possible edit is to change a character. Therefore, move ahead in both strings. b) Else, move ahead in both strings. Below is the implementation of the above idea : C++ Java Python3 C# PHP Javascript // C++ program to check if given two strings are// at distance one.#include <bits/stdc++.h>using namespace std; // Returns true if edit distance between s1 and// s2 is one, else falsebool isEditDistanceOne(string s1, string s2){ // Find lengths of given strings int m = s1.length(), n = s2.length(); // If difference between lengths is more than // 1, then strings can't be at one distance if (abs(m - n) > 1) return false; int count = 0; // Count of edits int i = 0, j = 0; while (i < m && j < n) { // If current characters don't match if (s1[i] != s2[j]) { if (count == 1) return false; // If length of one string is // more, then only possible edit // is to remove a character if (m > n) i++; else if (m< n) j++; else //Iflengths of both strings is same { i++; j++; } // Increment count of edits count++; } else // If current characters match { i++; j++; } } // If last character is extra in any string if (i < m || j < n) count++; return count == 1;} // Driver programint main(){ string s1 = "gfg"; string s2 = "gf"; isEditDistanceOne(s1, s2)? cout << "Yes": cout << "No"; return 0;} // Java program to check if given// two strings are at distance one.class GFG{// Returns true if edit distance// between s1 and s2 is one, else falsestatic boolean isEditDistanceOne(String s1, String s2){ // Find lengths of given strings int m = s1.length(), n = s2.length(); // If difference between lengths is // more than 1, then strings can't // be at one distance if (Math.abs(m - n) > 1) return false; int count = 0; // Count of edits int i = 0, j = 0; while (i < m && j < n) { // If current characters don't match if (s1.charAt(i) != s2.charAt(j)) { if (count == 1) return false; // If length of one string is // more, then only possible edit // is to remove a character if (m > n) i++; else if (m< n) j++; else // Iflengths of both strings // is same { i++; j++; } // Increment count of edits count++; } else // If current characters match { i++; j++; } } // If last character is extra // in any string if (i < m || j < n) count++; return count == 1;} // driver codepublic static void main (String[] args){ String s1 = "gfg"; String s2 = "gf"; if(isEditDistanceOne(s1, s2)) System.out.print("Yes"); else System.out.print("No");}} // This code is contributed by Anant Agarwal. # Python program to check if given two strings are# at distance one # Returns true if edit distance between s1 and s2 is# one, else falsedef isEditDistanceOne(s1, s2): # Find lengths of given strings m = len(s1) n = len(s2) # If difference between lengths is more than 1, # then strings can't be at one distance if abs(m - n) > 1: return false count = 0 # Count of isEditDistanceOne i = 0 j = 0 while i < m and j < n: # If current characters dont match if s1[i] != s2[j]: if count == 1: return false # If length of one string is # more, then only possible edit # is to remove a character if m > n: i+=1 elif m < n: j+=1 else: # If lengths of both strings is same i+=1 j+=1 # Increment count of edits count+=1 else: # if current characters match i+=1 j+=1 # if last character is extra in any string if i < m or j < n: count+=1 return count == 1 # Driver programs1 = "gfg"s2 = "gf"if isEditDistanceOne(s1, s2): print ("Yes")else: print ("No") # This code is contributed by Bhavya Jain // C# program to check if given// two strings are at distance one.using System; class GFG{ // Returns true if edit distance// between s1 and s2 is one, else falsestatic bool isEditDistanceOne(String s1, String s2){ // Find lengths of given strings int m = s1.Length, n = s2.Length; // If difference between lengths is // more than 1, then strings can't // be at one distance if (Math.Abs(m - n) > 1) return false; // Count of edits int count = 0; int i = 0, j = 0; while (i < m && j < n) { // If current characters // don't match if (s1[i] != s2[j]) { if (count == 1) return false; // If length of one string is // more, then only possible edit // is to remove a character if (m > n) i++; else if (m< n) j++; // If lengths of both // strings is same else { i++; j++; } // Increment count of edits count++; } // If current characters match else { i++; j++; } } // If last character is extra // in any string if (i < m || j < n) count++; return count == 1;} // Driver codepublic static void Main (){ String s1 = "gfg"; String s2 = "gf"; if(isEditDistanceOne(s1, s2)) Console.WriteLine("Yes"); else Console.WriteLine("No");}} // This code is contributed by Sam007. <?php// PHP program to check if given// two strings are at distance one. // Returns true if edit distance// between s1 and s2 is one, else// falsefunction isEditDistanceOne($s1, $s2){ // Find lengths of given strings $m = strlen($s1); $n = strlen($s2); // If difference between // lengths is more than // 1, then strings can't // be at one distance if (abs($m - $n) > 1) return false; // Count of edits $count = 0; $i = 0; $j = 0; while ($i < $m && $j < $n) { // If current characters // don't match if ($s1[$i] != $s2[$j]) { if ($count == 1) return false; // If length of one string is // more, then only possible edit // is to remove a character if ($m > $n) $i++; else if ($m< $n) $j++; // If lengths of both // strings is same else { $i++; $j++; } // Increment count of edits $count++; } // If current characters // match else { $i++; $j++; } } // If last character is // extra in any string if ($i < $m || $j < $n) $count++; return $count == 1;} // Driver Code$s1 = "gfg";$s2 = "gf";if(isEditDistanceOne($s1, $s2)) echo "Yes";else echo "No"; // This code is contributed by nitin mittal.?> <script> // Javascript program to check if given // two strings are at distance one. // Returns true if edit distance // between s1 and s2 is one, else false function isEditDistanceOne(s1, s2) { // Find lengths of given strings let m = s1.length, n = s2.length; // If difference between lengths is // more than 1, then strings can't // be at one distance if (Math.abs(m - n) > 1) return false; // Count of edits let count = 0; let i = 0, j = 0; while (i < m && j < n) { // If current characters // don't match if (s1[i] != s2[j]) { if (count == 1) return false; // If length of one string is // more, then only possible edit // is to remove a character if (m > n) i++; else if (m< n) j++; // If lengths of both // strings is same else { i++; j++; } // Increment count of edits count++; } // If current characters match else { i++; j++; } } // If last character is extra // in any string if (i < m || j < n) count++; return count == 1; } let s1 = "gfg"; let s2 = "gf"; if(isEditDistanceOne(s1, s2)) document.write("Yes"); else document.write("No"); // This code is contributed by decode2207.</script> Output: Yes Time complexity: O(n) Auxiliary Space: O(1)Thanks to Gaurav Ahirwar for suggesting above solution.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above Sam007 nitin mittal decode2207 amartyaghoshgfg Strings Strings Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Python program to check if a string is palindrome or not Check for Balanced Brackets in an expression (well-formedness) using Stack Different methods to reverse a string in C/C++ KMP Algorithm for Pattern Searching Convert string to char array in C++ Array of Strings in C++ (5 Different Ways to Create) Longest Palindromic Substring | Set 1 Caesar Cipher in Cryptography Reverse words in a given string Check whether two strings are anagram of each other
[ { "code": null, "e": 24377, "s": 24349, "text": "\n20 Jan, 2022" }, { "code": null, "e": 24440, "s": 24377, "text": "An edit between two strings is one of the following changes. " }, { "code": null, "e": 24492, "s": 24440, "text": "Add a characterDelete a characterChange a character" }, { "code": null, "e": 24508, "s": 24492, "text": "Add a character" }, { "code": null, "e": 24527, "s": 24508, "text": "Delete a character" }, { "code": null, "e": 24546, "s": 24527, "text": "Change a character" }, { "code": null, "e": 24720, "s": 24546, "text": "Given two string s1 and s2, find if s1 can be converted to s2 with exactly one edit. Expected time complexity is O(m+n) where m and n are lengths of two strings. Examples: " }, { "code": null, "e": 24992, "s": 24720, "text": "Input: s1 = \"geeks\", s2 = \"geek\"\nOutput: yes\nNumber of edits is 1\n\nInput: s1 = \"geeks\", s2 = \"geeks\"\nOutput: no\nNumber of edits is 0\n\nInput: s1 = \"geaks\", s2 = \"geeks\"\nOutput: yes\nNumber of edits is 1\n\nInput: s1 = \"peaks\", s2 = \"geeks\"\nOutput: no\nNumber of edits is 2" }, { "code": null, "e": 25304, "s": 24994, "text": "A Simple Solution is to find Edit Distance using Dynamic programming. If distance is 1, then return true, else return false. Time complexity of this solution is O(n2)An Efficient Solution is to simultaneously traverse both strings and keep track of count of different characters. Below is complete algorithm. " }, { "code": null, "e": 26048, "s": 25304, "text": "Let the input strings be s1 and s2 and lengths of input \nstrings be m and n respectively.\n\n1) If difference between m an n is more than 1, \n return false.\n2) Initialize count of edits as 0.\n3) Start traversing both strings from first character.\n a) If current characters don't match, then\n (i) Increment count of edits\n (ii) If count becomes more than 1, return false\n (iii) If length of one string is more, then only\n possible edit is to remove a character.\n Therefore, move ahead in larger string.\n (iv) If length is same, then only possible edit\n is to change a character. Therefore, move\n ahead in both strings. \n b) Else, move ahead in both strings. " }, { "code": null, "e": 26097, "s": 26048, "text": "Below is the implementation of the above idea : " }, { "code": null, "e": 26101, "s": 26097, "text": "C++" }, { "code": null, "e": 26106, "s": 26101, "text": "Java" }, { "code": null, "e": 26114, "s": 26106, "text": "Python3" }, { "code": null, "e": 26117, "s": 26114, "text": "C#" }, { "code": null, "e": 26121, "s": 26117, "text": "PHP" }, { "code": null, "e": 26132, "s": 26121, "text": "Javascript" }, { "code": "// C++ program to check if given two strings are// at distance one.#include <bits/stdc++.h>using namespace std; // Returns true if edit distance between s1 and// s2 is one, else falsebool isEditDistanceOne(string s1, string s2){ // Find lengths of given strings int m = s1.length(), n = s2.length(); // If difference between lengths is more than // 1, then strings can't be at one distance if (abs(m - n) > 1) return false; int count = 0; // Count of edits int i = 0, j = 0; while (i < m && j < n) { // If current characters don't match if (s1[i] != s2[j]) { if (count == 1) return false; // If length of one string is // more, then only possible edit // is to remove a character if (m > n) i++; else if (m< n) j++; else //Iflengths of both strings is same { i++; j++; } // Increment count of edits count++; } else // If current characters match { i++; j++; } } // If last character is extra in any string if (i < m || j < n) count++; return count == 1;} // Driver programint main(){ string s1 = \"gfg\"; string s2 = \"gf\"; isEditDistanceOne(s1, s2)? cout << \"Yes\": cout << \"No\"; return 0;}", "e": 27578, "s": 26132, "text": null }, { "code": "// Java program to check if given// two strings are at distance one.class GFG{// Returns true if edit distance// between s1 and s2 is one, else falsestatic boolean isEditDistanceOne(String s1, String s2){ // Find lengths of given strings int m = s1.length(), n = s2.length(); // If difference between lengths is // more than 1, then strings can't // be at one distance if (Math.abs(m - n) > 1) return false; int count = 0; // Count of edits int i = 0, j = 0; while (i < m && j < n) { // If current characters don't match if (s1.charAt(i) != s2.charAt(j)) { if (count == 1) return false; // If length of one string is // more, then only possible edit // is to remove a character if (m > n) i++; else if (m< n) j++; else // Iflengths of both strings // is same { i++; j++; } // Increment count of edits count++; } else // If current characters match { i++; j++; } } // If last character is extra // in any string if (i < m || j < n) count++; return count == 1;} // driver codepublic static void main (String[] args){ String s1 = \"gfg\"; String s2 = \"gf\"; if(isEditDistanceOne(s1, s2)) System.out.print(\"Yes\"); else System.out.print(\"No\");}} // This code is contributed by Anant Agarwal.", "e": 29181, "s": 27578, "text": null }, { "code": "# Python program to check if given two strings are# at distance one # Returns true if edit distance between s1 and s2 is# one, else falsedef isEditDistanceOne(s1, s2): # Find lengths of given strings m = len(s1) n = len(s2) # If difference between lengths is more than 1, # then strings can't be at one distance if abs(m - n) > 1: return false count = 0 # Count of isEditDistanceOne i = 0 j = 0 while i < m and j < n: # If current characters dont match if s1[i] != s2[j]: if count == 1: return false # If length of one string is # more, then only possible edit # is to remove a character if m > n: i+=1 elif m < n: j+=1 else: # If lengths of both strings is same i+=1 j+=1 # Increment count of edits count+=1 else: # if current characters match i+=1 j+=1 # if last character is extra in any string if i < m or j < n: count+=1 return count == 1 # Driver programs1 = \"gfg\"s2 = \"gf\"if isEditDistanceOne(s1, s2): print (\"Yes\")else: print (\"No\") # This code is contributed by Bhavya Jain", "e": 30458, "s": 29181, "text": null }, { "code": "// C# program to check if given// two strings are at distance one.using System; class GFG{ // Returns true if edit distance// between s1 and s2 is one, else falsestatic bool isEditDistanceOne(String s1, String s2){ // Find lengths of given strings int m = s1.Length, n = s2.Length; // If difference between lengths is // more than 1, then strings can't // be at one distance if (Math.Abs(m - n) > 1) return false; // Count of edits int count = 0; int i = 0, j = 0; while (i < m && j < n) { // If current characters // don't match if (s1[i] != s2[j]) { if (count == 1) return false; // If length of one string is // more, then only possible edit // is to remove a character if (m > n) i++; else if (m< n) j++; // If lengths of both // strings is same else { i++; j++; } // Increment count of edits count++; } // If current characters match else { i++; j++; } } // If last character is extra // in any string if (i < m || j < n) count++; return count == 1;} // Driver codepublic static void Main (){ String s1 = \"gfg\"; String s2 = \"gf\"; if(isEditDistanceOne(s1, s2)) Console.WriteLine(\"Yes\"); else Console.WriteLine(\"No\");}} // This code is contributed by Sam007.", "e": 32104, "s": 30458, "text": null }, { "code": "<?php// PHP program to check if given// two strings are at distance one. // Returns true if edit distance// between s1 and s2 is one, else// falsefunction isEditDistanceOne($s1, $s2){ // Find lengths of given strings $m = strlen($s1); $n = strlen($s2); // If difference between // lengths is more than // 1, then strings can't // be at one distance if (abs($m - $n) > 1) return false; // Count of edits $count = 0; $i = 0; $j = 0; while ($i < $m && $j < $n) { // If current characters // don't match if ($s1[$i] != $s2[$j]) { if ($count == 1) return false; // If length of one string is // more, then only possible edit // is to remove a character if ($m > $n) $i++; else if ($m< $n) $j++; // If lengths of both // strings is same else { $i++; $j++; } // Increment count of edits $count++; } // If current characters // match else { $i++; $j++; } } // If last character is // extra in any string if ($i < $m || $j < $n) $count++; return $count == 1;} // Driver Code$s1 = \"gfg\";$s2 = \"gf\";if(isEditDistanceOne($s1, $s2)) echo \"Yes\";else echo \"No\"; // This code is contributed by nitin mittal.?>", "e": 33626, "s": 32104, "text": null }, { "code": "<script> // Javascript program to check if given // two strings are at distance one. // Returns true if edit distance // between s1 and s2 is one, else false function isEditDistanceOne(s1, s2) { // Find lengths of given strings let m = s1.length, n = s2.length; // If difference between lengths is // more than 1, then strings can't // be at one distance if (Math.abs(m - n) > 1) return false; // Count of edits let count = 0; let i = 0, j = 0; while (i < m && j < n) { // If current characters // don't match if (s1[i] != s2[j]) { if (count == 1) return false; // If length of one string is // more, then only possible edit // is to remove a character if (m > n) i++; else if (m< n) j++; // If lengths of both // strings is same else { i++; j++; } // Increment count of edits count++; } // If current characters match else { i++; j++; } } // If last character is extra // in any string if (i < m || j < n) count++; return count == 1; } let s1 = \"gfg\"; let s2 = \"gf\"; if(isEditDistanceOne(s1, s2)) document.write(\"Yes\"); else document.write(\"No\"); // This code is contributed by decode2207.</script>", "e": 35368, "s": 33626, "text": null }, { "code": null, "e": 35377, "s": 35368, "text": "Output: " }, { "code": null, "e": 35381, "s": 35377, "text": "Yes" }, { "code": null, "e": 35604, "s": 35381, "text": "Time complexity: O(n) Auxiliary Space: O(1)Thanks to Gaurav Ahirwar for suggesting above solution.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above " }, { "code": null, "e": 35611, "s": 35604, "text": "Sam007" }, { "code": null, "e": 35624, "s": 35611, "text": "nitin mittal" }, { "code": null, "e": 35635, "s": 35624, "text": "decode2207" }, { "code": null, "e": 35651, "s": 35635, "text": "amartyaghoshgfg" }, { "code": null, "e": 35659, "s": 35651, "text": "Strings" }, { "code": null, "e": 35667, "s": 35659, "text": "Strings" }, { "code": null, "e": 35765, "s": 35667, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 35774, "s": 35765, "text": "Comments" }, { "code": null, "e": 35787, "s": 35774, "text": "Old Comments" }, { "code": null, "e": 35844, "s": 35787, "text": "Python program to check if a string is palindrome or not" }, { "code": null, "e": 35919, "s": 35844, "text": "Check for Balanced Brackets in an expression (well-formedness) using Stack" }, { "code": null, "e": 35966, "s": 35919, "text": "Different methods to reverse a string in C/C++" }, { "code": null, "e": 36002, "s": 35966, "text": "KMP Algorithm for Pattern Searching" }, { "code": null, "e": 36038, "s": 36002, "text": "Convert string to char array in C++" }, { "code": null, "e": 36091, "s": 36038, "text": "Array of Strings in C++ (5 Different Ways to Create)" }, { "code": null, "e": 36129, "s": 36091, "text": "Longest Palindromic Substring | Set 1" }, { "code": null, "e": 36159, "s": 36129, "text": "Caesar Cipher in Cryptography" }, { "code": null, "e": 36191, "s": 36159, "text": "Reverse words in a given string" } ]
Lua - Logical Operators
Following table shows all the logical operators supported by Lua language. Assume variable A holds true and variable B holds false then − Try the following example to understand all the logical operators available in the Lua programming language − a = 5 b = 20 if ( a and b ) then print("Line 1 - Condition is true" ) end if ( a or b ) then print("Line 2 - Condition is true" ) end --lets change the value ofa and b a = 0 b = 10 if ( a and b ) then print("Line 3 - Condition is true" ) else print("Line 3 - Condition is not true" ) end if ( not( a and b) ) then print("Line 4 - Condition is true" ) else print("Line 3 - Condition is not true" ) end When you build and execute the above program, it produces the following result − Line 1 - Condition is true Line 2 - Condition is true Line 3 - Condition is true Line 3 - Condition is not true 12 Lectures 2 hours Manish Gupta 80 Lectures 3 hours Sanjeev Mittal 54 Lectures 3.5 hours Mehmet GOKTEPE Print Add Notes Bookmark this page
[ { "code": null, "e": 2241, "s": 2103, "text": "Following table shows all the logical operators supported by Lua language. Assume variable A holds true and variable B holds false then −" }, { "code": null, "e": 2351, "s": 2241, "text": "Try the following example to understand all the logical operators available in the Lua programming language −" }, { "code": null, "e": 2775, "s": 2351, "text": "a = 5\nb = 20\n\nif ( a and b )\nthen\n print(\"Line 1 - Condition is true\" )\nend\n\nif ( a or b )\nthen\n print(\"Line 2 - Condition is true\" )\nend\n\n--lets change the value ofa and b\na = 0\nb = 10\n\nif ( a and b )\nthen\n print(\"Line 3 - Condition is true\" )\nelse\n print(\"Line 3 - Condition is not true\" )\nend\n\nif ( not( a and b) )\nthen\n print(\"Line 4 - Condition is true\" )\nelse\n print(\"Line 3 - Condition is not true\" )\nend" }, { "code": null, "e": 2856, "s": 2775, "text": "When you build and execute the above program, it produces the following result −" }, { "code": null, "e": 2969, "s": 2856, "text": "Line 1 - Condition is true\nLine 2 - Condition is true\nLine 3 - Condition is true\nLine 3 - Condition is not true\n" }, { "code": null, "e": 3002, "s": 2969, "text": "\n 12 Lectures \n 2 hours \n" }, { "code": null, "e": 3016, "s": 3002, "text": " Manish Gupta" }, { "code": null, "e": 3049, "s": 3016, "text": "\n 80 Lectures \n 3 hours \n" }, { "code": null, "e": 3065, "s": 3049, "text": " Sanjeev Mittal" }, { "code": null, "e": 3100, "s": 3065, "text": "\n 54 Lectures \n 3.5 hours \n" }, { "code": null, "e": 3116, "s": 3100, "text": " Mehmet GOKTEPE" }, { "code": null, "e": 3123, "s": 3116, "text": " Print" }, { "code": null, "e": 3134, "s": 3123, "text": " Add Notes" } ]
Download and install pip Latest Version
23 Mar, 2020 PIP is a package management system used to install and manage software packages/libraries written in Python. These files are stored in a large “on-line repository” termed as Python Package Index (PyPI). After you have successfully installed Python, you would clearly need pip in order to install packages, such as Numpy, Django and lots more on your operating system. Windows Linux macOS Verification pip can be downloaded and installed using command-line by going through the following steps: Download the get-pip.py file and store it in the same directory as python is installed. Change the current path of the directory in the command line to the path of the directory where the above file exists. Run the command given below:python get-pip.pyand wait through the installation process. python get-pip.py and wait through the installation process. Voila! pip is now installed on your system. For more, visit – How to install PIP on Windows ? pip can be downloaded and installed using the terminal in Linux by going through the following command: sudo apt-get install python3-pip python-dev Beginning the installation: Getting Started: Providing Disk Space: Downloading Libraries: Unpacking File bundles: Finishing up the Installation: For more, visit – How to install PIP in Linux? pip in macOS can be downloaded and installed using command-line by going through the following steps: Download the get-pip.py file and store it in the same directory as python is installed.orUse the following command to download pip directly,curl https://bootstrap.pypa.io/get-pip.py -o get-pip.py curl https://bootstrap.pypa.io/get-pip.py -o get-pip.py Now execute the downloaded file using below commandpython3 get-pip.pyand wait through the installation process. python3 get-pip.py and wait through the installation process. Voila! pip is now installed on your system. One can easily verify if the pip has been installed correctly by performing a version check on the same. Just go to the command line and execute the following command: pip3 --version Python-pip 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() *args and **kwargs in Python Python Classes and Objects Iterate over a list in Python Python OOPs Concepts Convert integer to string in Python
[ { "code": null, "e": 54, "s": 26, "text": "\n23 Mar, 2020" }, { "code": null, "e": 422, "s": 54, "text": "PIP is a package management system used to install and manage software packages/libraries written in Python. These files are stored in a large “on-line repository” termed as Python Package Index (PyPI). After you have successfully installed Python, you would clearly need pip in order to install packages, such as Numpy, Django and lots more on your operating system." }, { "code": null, "e": 430, "s": 422, "text": "Windows" }, { "code": null, "e": 436, "s": 430, "text": "Linux" }, { "code": null, "e": 442, "s": 436, "text": "macOS" }, { "code": null, "e": 455, "s": 442, "text": "Verification" }, { "code": null, "e": 548, "s": 455, "text": "pip can be downloaded and installed using command-line by going through the following steps:" }, { "code": null, "e": 636, "s": 548, "text": "Download the get-pip.py file and store it in the same directory as python is installed." }, { "code": null, "e": 755, "s": 636, "text": "Change the current path of the directory in the command line to the path of the directory where the above file exists." }, { "code": null, "e": 843, "s": 755, "text": "Run the command given below:python get-pip.pyand wait through the installation process." }, { "code": null, "e": 861, "s": 843, "text": "python get-pip.py" }, { "code": null, "e": 904, "s": 861, "text": "and wait through the installation process." }, { "code": null, "e": 948, "s": 904, "text": "Voila! pip is now installed on your system." }, { "code": null, "e": 998, "s": 948, "text": "For more, visit – How to install PIP on Windows ?" }, { "code": null, "e": 1102, "s": 998, "text": "pip can be downloaded and installed using the terminal in Linux by going through the following command:" }, { "code": null, "e": 1146, "s": 1102, "text": "sudo apt-get install python3-pip python-dev" }, { "code": null, "e": 1174, "s": 1146, "text": "Beginning the installation:" }, { "code": null, "e": 1191, "s": 1174, "text": "Getting Started:" }, { "code": null, "e": 1213, "s": 1191, "text": "Providing Disk Space:" }, { "code": null, "e": 1236, "s": 1213, "text": "Downloading Libraries:" }, { "code": null, "e": 1260, "s": 1236, "text": "Unpacking File bundles:" }, { "code": null, "e": 1291, "s": 1260, "text": "Finishing up the Installation:" }, { "code": null, "e": 1338, "s": 1291, "text": "For more, visit – How to install PIP in Linux?" }, { "code": null, "e": 1440, "s": 1338, "text": "pip in macOS can be downloaded and installed using command-line by going through the following steps:" }, { "code": null, "e": 1637, "s": 1440, "text": "Download the get-pip.py file and store it in the same directory as python is installed.orUse the following command to download pip directly,curl https://bootstrap.pypa.io/get-pip.py -o get-pip.py\n" }, { "code": null, "e": 1694, "s": 1637, "text": "curl https://bootstrap.pypa.io/get-pip.py -o get-pip.py\n" }, { "code": null, "e": 1806, "s": 1694, "text": "Now execute the downloaded file using below commandpython3 get-pip.pyand wait through the installation process." }, { "code": null, "e": 1825, "s": 1806, "text": "python3 get-pip.py" }, { "code": null, "e": 1868, "s": 1825, "text": "and wait through the installation process." }, { "code": null, "e": 1912, "s": 1868, "text": "Voila! pip is now installed on your system." }, { "code": null, "e": 2080, "s": 1912, "text": "One can easily verify if the pip has been installed correctly by performing a version check on the same. Just go to the command line and execute the following command:" }, { "code": null, "e": 2095, "s": 2080, "text": "pip3 --version" }, { "code": null, "e": 2106, "s": 2095, "text": "Python-pip" }, { "code": null, "e": 2113, "s": 2106, "text": "Python" }, { "code": null, "e": 2211, "s": 2113, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 2229, "s": 2211, "text": "Python Dictionary" }, { "code": null, "e": 2271, "s": 2229, "text": "Different ways to create Pandas Dataframe" }, { "code": null, "e": 2293, "s": 2271, "text": "Enumerate() in Python" }, { "code": null, "e": 2328, "s": 2293, "text": "Read a file line by line in Python" }, { "code": null, "e": 2354, "s": 2328, "text": "Python String | replace()" }, { "code": null, "e": 2383, "s": 2354, "text": "*args and **kwargs in Python" }, { "code": null, "e": 2410, "s": 2383, "text": "Python Classes and Objects" }, { "code": null, "e": 2440, "s": 2410, "text": "Iterate over a list in Python" }, { "code": null, "e": 2461, "s": 2440, "text": "Python OOPs Concepts" } ]
Different ways to copy a string in C/C++
06 Jun, 2021 Using the inbuilt function strcpy() from string.h header file to copy one string to the other. strcpy() accepts a pointer to the destination array and source array as a parameter and after copying it returns a pointer to the destination string. Using %s we can print the string(%s prints the string from the base address till the null character). Below is the implementation using the above method: C // C program to copy the string using// strcpy function #include <stdio.h>#include <stdlib.h>#include <string.h> // Function to copy the stringchar* copyString(char s[]){ char* s2; s2 = (char*)malloc(20); strcpy(s2, s); return (char*)s2;} // Driver Codeint main(){ char s1[20] = "GeeksforGeeks"; char* s2; // Function Call s2 = copyString(s1); printf("%s", s2); return 0;} GeeksforGeeks memcpy() is also defined in string.h header and used to copy from source to destination no matter what the source data contains. memcpy() requires a size parameter be passed. The main difference is that memcpy() always copies the exact number of specified bytes ; strcpy() and other str methods, on the other hand, will copy until it reads a NULL (‘\0’) byte, and then stop after that. strcpy() is not intended to be used with zero-terminated C-strings. memcpy() is hardware optimized and copy faster and work with any type of source data (like: binary or encrypted bytes). strcpy() should never use unless any specific reason, and f you know the lengths of the strings, memcpy() is a better choice. C // C program to copy the string using// memcpy function#include <stdio.h>#include <string.h> // Driver Codeint main(){ char s1[20] = "GeeksforGeeks"; char s2[20]; // Function memcpy(s2, s1, strlen(s1)); printf("%s\n", s1); return 0;} GeeksforGeeks The idea is to use a for loop to copy the content of the first array to the second array one by one. Below is the implementation using the above method: C // C program to copy string using loops #include <stdio.h>#include <stdlib.h>#include <string.h> // Function to copy the stringchar* copyString(char s[]){ int i; char* s2; s2 = (char*)malloc(20); // Executing till null character // is found for (i = 0; s[i] != '\0'; i++) { // Copy the character one // by one from s1 to s2 s2[i] = s[i]; } // Return the pointer of newly // created string return (char*)s2;} // Driver Codeint main(){ char s1[20] = "GeeksforGeeks"; char* s2; // Function Call s2 = copyString(s1); printf("%s", s2); return 0;} GeeksforGeeks The idea is to copy the contents of the string array to another array using pointers and print the resultant string by traversing the new pointer. Below is the implementation using the above method: C // C program to copy the string// using pointers #include <stdio.h>#include <stdlib.h>#include <string.h> // Function to copy the stringchar* copyString(char s[]){ char *s2, *p1, *p2; s2 = (char*)malloc(20); p1 = s; p2 = s2; // Executing till the null // character is found while (*p1 != '\0') { // Copy the content of s1 to s2 *p2 = *p1; p1++; p2++; } *p2 = '\0'; return s2;} // Driver Codeint main(){ char s1[20] = "GeeksforGeeks"; char* s2; s2 = copyString(s1); printf("%s", s2); return 0;} GeeksforGeeks The idea is to use a while loop to assigns the content of string array1 to string array2 one by one and increment using post operator as it returns ASCII value so the condition will be true and it will be in the loop and transfer till the condition is false, and we will come out of the loop. Below is the implementation using the above method: C // C program to copy the string #include <stdio.h>#include <stdlib.h> // Function to copy the stringvoid copyString(char* t, char* s){ // (return ASCII value which is True, // therefore will be in the loop // till the condition is False while (*t++ = *s++) ;} // Driver Codeint main(){ char s2[20] = "GeeksforGeeks"; char s1[20]; // Function Call copyString(s1, s2); printf("%s", s1); return 0;} GeeksforGeeks Instead of print the string in output buffer we can store it in specified char buffer or destination string in sprintf() to copy the string. C // C program to copy the string using// sprintf function#include <stdio.h> // Driver Codeint main(){ char s1[20] = "GeeksforGeeks"; char s2[20]; // Function sprintf(s2, "%s", s1); printf("%s\n", s1); return 0;} GeeksforGeeks Note: In all the above methods the size of the destination array must be greater than the length of the source string to copy all the characters. scorchingeagle C-String cpp-strings-library Technical Scripter 2020 C++ Program Output Strings Technical Scripter Strings CPP Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 53, "s": 25, "text": "\n06 Jun, 2021" }, { "code": null, "e": 400, "s": 53, "text": "Using the inbuilt function strcpy() from string.h header file to copy one string to the other. strcpy() accepts a pointer to the destination array and source array as a parameter and after copying it returns a pointer to the destination string. Using %s we can print the string(%s prints the string from the base address till the null character)." }, { "code": null, "e": 452, "s": 400, "text": "Below is the implementation using the above method:" }, { "code": null, "e": 454, "s": 452, "text": "C" }, { "code": "// C program to copy the string using// strcpy function #include <stdio.h>#include <stdlib.h>#include <string.h> // Function to copy the stringchar* copyString(char s[]){ char* s2; s2 = (char*)malloc(20); strcpy(s2, s); return (char*)s2;} // Driver Codeint main(){ char s1[20] = \"GeeksforGeeks\"; char* s2; // Function Call s2 = copyString(s1); printf(\"%s\", s2); return 0;}", "e": 859, "s": 454, "text": null }, { "code": null, "e": 873, "s": 859, "text": "GeeksforGeeks" }, { "code": null, "e": 1050, "s": 875, "text": "memcpy() is also defined in string.h header and used to copy from source to destination no matter what the source data contains. memcpy() requires a size parameter be passed." }, { "code": null, "e": 1329, "s": 1050, "text": "The main difference is that memcpy() always copies the exact number of specified bytes ; strcpy() and other str methods, on the other hand, will copy until it reads a NULL (‘\\0’) byte, and then stop after that. strcpy() is not intended to be used with zero-terminated C-strings." }, { "code": null, "e": 1575, "s": 1329, "text": "memcpy() is hardware optimized and copy faster and work with any type of source data (like: binary or encrypted bytes). strcpy() should never use unless any specific reason, and f you know the lengths of the strings, memcpy() is a better choice." }, { "code": null, "e": 1577, "s": 1575, "text": "C" }, { "code": "// C program to copy the string using// memcpy function#include <stdio.h>#include <string.h> // Driver Codeint main(){ char s1[20] = \"GeeksforGeeks\"; char s2[20]; // Function memcpy(s2, s1, strlen(s1)); printf(\"%s\\n\", s1); return 0;}", "e": 1832, "s": 1577, "text": null }, { "code": null, "e": 1846, "s": 1832, "text": "GeeksforGeeks" }, { "code": null, "e": 1947, "s": 1846, "text": "The idea is to use a for loop to copy the content of the first array to the second array one by one." }, { "code": null, "e": 1999, "s": 1947, "text": "Below is the implementation using the above method:" }, { "code": null, "e": 2001, "s": 1999, "text": "C" }, { "code": "// C program to copy string using loops #include <stdio.h>#include <stdlib.h>#include <string.h> // Function to copy the stringchar* copyString(char s[]){ int i; char* s2; s2 = (char*)malloc(20); // Executing till null character // is found for (i = 0; s[i] != '\\0'; i++) { // Copy the character one // by one from s1 to s2 s2[i] = s[i]; } // Return the pointer of newly // created string return (char*)s2;} // Driver Codeint main(){ char s1[20] = \"GeeksforGeeks\"; char* s2; // Function Call s2 = copyString(s1); printf(\"%s\", s2); return 0;}", "e": 2616, "s": 2001, "text": null }, { "code": null, "e": 2630, "s": 2616, "text": "GeeksforGeeks" }, { "code": null, "e": 2779, "s": 2632, "text": "The idea is to copy the contents of the string array to another array using pointers and print the resultant string by traversing the new pointer." }, { "code": null, "e": 2831, "s": 2779, "text": "Below is the implementation using the above method:" }, { "code": null, "e": 2833, "s": 2831, "text": "C" }, { "code": "// C program to copy the string// using pointers #include <stdio.h>#include <stdlib.h>#include <string.h> // Function to copy the stringchar* copyString(char s[]){ char *s2, *p1, *p2; s2 = (char*)malloc(20); p1 = s; p2 = s2; // Executing till the null // character is found while (*p1 != '\\0') { // Copy the content of s1 to s2 *p2 = *p1; p1++; p2++; } *p2 = '\\0'; return s2;} // Driver Codeint main(){ char s1[20] = \"GeeksforGeeks\"; char* s2; s2 = copyString(s1); printf(\"%s\", s2); return 0;}", "e": 3406, "s": 2833, "text": null }, { "code": null, "e": 3420, "s": 3406, "text": "GeeksforGeeks" }, { "code": null, "e": 3715, "s": 3422, "text": "The idea is to use a while loop to assigns the content of string array1 to string array2 one by one and increment using post operator as it returns ASCII value so the condition will be true and it will be in the loop and transfer till the condition is false, and we will come out of the loop." }, { "code": null, "e": 3767, "s": 3715, "text": "Below is the implementation using the above method:" }, { "code": null, "e": 3769, "s": 3767, "text": "C" }, { "code": "// C program to copy the string #include <stdio.h>#include <stdlib.h> // Function to copy the stringvoid copyString(char* t, char* s){ // (return ASCII value which is True, // therefore will be in the loop // till the condition is False while (*t++ = *s++) ;} // Driver Codeint main(){ char s2[20] = \"GeeksforGeeks\"; char s1[20]; // Function Call copyString(s1, s2); printf(\"%s\", s1); return 0;}", "e": 4203, "s": 3769, "text": null }, { "code": null, "e": 4217, "s": 4203, "text": "GeeksforGeeks" }, { "code": null, "e": 4361, "s": 4219, "text": "Instead of print the string in output buffer we can store it in specified char buffer or destination string in sprintf() to copy the string. " }, { "code": null, "e": 4363, "s": 4361, "text": "C" }, { "code": "// C program to copy the string using// sprintf function#include <stdio.h> // Driver Codeint main(){ char s1[20] = \"GeeksforGeeks\"; char s2[20]; // Function sprintf(s2, \"%s\", s1); printf(\"%s\\n\", s1); return 0;}", "e": 4595, "s": 4363, "text": null }, { "code": null, "e": 4609, "s": 4595, "text": "GeeksforGeeks" }, { "code": null, "e": 4757, "s": 4611, "text": "Note: In all the above methods the size of the destination array must be greater than the length of the source string to copy all the characters." }, { "code": null, "e": 4774, "s": 4759, "text": "scorchingeagle" }, { "code": null, "e": 4783, "s": 4774, "text": "C-String" }, { "code": null, "e": 4803, "s": 4783, "text": "cpp-strings-library" }, { "code": null, "e": 4827, "s": 4803, "text": "Technical Scripter 2020" }, { "code": null, "e": 4831, "s": 4827, "text": "C++" }, { "code": null, "e": 4846, "s": 4831, "text": "Program Output" }, { "code": null, "e": 4854, "s": 4846, "text": "Strings" }, { "code": null, "e": 4873, "s": 4854, "text": "Technical Scripter" }, { "code": null, "e": 4881, "s": 4873, "text": "Strings" }, { "code": null, "e": 4885, "s": 4881, "text": "CPP" } ]
CSS :nth-child() Selector
02 Nov, 2021 The :nth-child() CSS pseudo-class selector is used to match the elements based on their position in a group of siblings. It matches every element that is the nth-child, regardless of the type, of its parent. Syntax: :nth-child(number) { // CSS Property } Where number is the single argument that represents the pattern for matching elements. It can be odd, even, or in a functional notation. odd: It represents elements whose position is odd in a series: 1, 3, 5, etc. even: It represents the elements whose position is even in a series: 2, 4, 6, etc. functional notation (<An+B>): It represents elements whose position of siblings matches the pattern An+B, for every positive integer or zero value of n. Here, A represents the integer step size, B represents the integer offset. Example 1: In this example, every odd paragraph is selected. Formula used is 2n+1 i.e 1, 3, 5, etc paragraphs are selected. HTML <!DOCTYPE html><html> <head> <title>CSS :nth-child Selector</title> <style> p:nth-child(2n+1) { background: green; color: white; } </style></head> <body style="text-align:center"> <h1 style="color:green;"> GeeksforGeeks </h1> <h2> CSS :nth-child Selector </h2> <p>A computer science portal for geeks.</p> <p>Geeks classes an extensive classroom programme.</p> </body> </html> Output: Example 2: In this example, every even <li> is selected i.e. 2, 4, 6, etc. HTML <!DOCTYPE html><html> <head> <title>CSS :nth-child Selector</title> <style> li { width: 30%; } li:nth-child(even) { background: green; color: white; } </style></head> <body style="text-align:center"> <h2> CSS :nth-child Selector </h2> <p>Sorting Algorithms</p> <ul> <li>Quick sort.</li> <li>Merge sort.</li> <li>Insertion sort.</li> <li>Selection sort.</li> </ul></body> </html> Output: Supported Browsers: The browser supported by :nth-child() selector are listed below: Google Chrome 4.0 Microsoft Edge 12.0 Firefox 3.5 Opera 9.6 Apple Safari 3.2 Internet Explorer 9.0 bhaskargeeksforgeeks CSS-Selectors CSS Web Technologies Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n02 Nov, 2021" }, { "code": null, "e": 236, "s": 28, "text": "The :nth-child() CSS pseudo-class selector is used to match the elements based on their position in a group of siblings. It matches every element that is the nth-child, regardless of the type, of its parent." }, { "code": null, "e": 244, "s": 236, "text": "Syntax:" }, { "code": null, "e": 287, "s": 244, "text": ":nth-child(number) {\n // CSS Property\n}" }, { "code": null, "e": 424, "s": 287, "text": "Where number is the single argument that represents the pattern for matching elements. It can be odd, even, or in a functional notation." }, { "code": null, "e": 501, "s": 424, "text": "odd: It represents elements whose position is odd in a series: 1, 3, 5, etc." }, { "code": null, "e": 584, "s": 501, "text": "even: It represents the elements whose position is even in a series: 2, 4, 6, etc." }, { "code": null, "e": 812, "s": 584, "text": "functional notation (<An+B>): It represents elements whose position of siblings matches the pattern An+B, for every positive integer or zero value of n. Here, A represents the integer step size, B represents the integer offset." }, { "code": null, "e": 936, "s": 812, "text": "Example 1: In this example, every odd paragraph is selected. Formula used is 2n+1 i.e 1, 3, 5, etc paragraphs are selected." }, { "code": null, "e": 941, "s": 936, "text": "HTML" }, { "code": "<!DOCTYPE html><html> <head> <title>CSS :nth-child Selector</title> <style> p:nth-child(2n+1) { background: green; color: white; } </style></head> <body style=\"text-align:center\"> <h1 style=\"color:green;\"> GeeksforGeeks </h1> <h2> CSS :nth-child Selector </h2> <p>A computer science portal for geeks.</p> <p>Geeks classes an extensive classroom programme.</p> </body> </html>", "e": 1400, "s": 941, "text": null }, { "code": null, "e": 1408, "s": 1400, "text": "Output:" }, { "code": null, "e": 1483, "s": 1408, "text": "Example 2: In this example, every even <li> is selected i.e. 2, 4, 6, etc." }, { "code": null, "e": 1488, "s": 1483, "text": "HTML" }, { "code": "<!DOCTYPE html><html> <head> <title>CSS :nth-child Selector</title> <style> li { width: 30%; } li:nth-child(even) { background: green; color: white; } </style></head> <body style=\"text-align:center\"> <h2> CSS :nth-child Selector </h2> <p>Sorting Algorithms</p> <ul> <li>Quick sort.</li> <li>Merge sort.</li> <li>Insertion sort.</li> <li>Selection sort.</li> </ul></body> </html>", "e": 1980, "s": 1488, "text": null }, { "code": null, "e": 1988, "s": 1980, "text": "Output:" }, { "code": null, "e": 2073, "s": 1988, "text": "Supported Browsers: The browser supported by :nth-child() selector are listed below:" }, { "code": null, "e": 2091, "s": 2073, "text": "Google Chrome 4.0" }, { "code": null, "e": 2111, "s": 2091, "text": "Microsoft Edge 12.0" }, { "code": null, "e": 2123, "s": 2111, "text": "Firefox 3.5" }, { "code": null, "e": 2133, "s": 2123, "text": "Opera 9.6" }, { "code": null, "e": 2150, "s": 2133, "text": "Apple Safari 3.2" }, { "code": null, "e": 2172, "s": 2150, "text": "Internet Explorer 9.0" }, { "code": null, "e": 2193, "s": 2172, "text": "bhaskargeeksforgeeks" }, { "code": null, "e": 2207, "s": 2193, "text": "CSS-Selectors" }, { "code": null, "e": 2211, "s": 2207, "text": "CSS" }, { "code": null, "e": 2228, "s": 2211, "text": "Web Technologies" } ]
Find free disk space using Java
25 Sep, 2017 There are a few method calls in java that can be utilized to get the space related information about a disk drive. These methods used to fetch the such information are declared in File class, which resides in java.io package. The details of these method call along with their use are given below:Note: These codes will not run on online ide. Also, they will all work on Java 1.6 and above versions Java.io.File.getFreeSpace(): Get total free space available in a driveSyntax:public long getFreeSpace() Returns the size of the partition named by this abstract pathname. Returns: The size, in bytes, of the partition or 0L if this abstract pathname does not name a partition Throws: SecurityException - If a security manager has been installed and it denies RuntimePermission("getFileSystemAttributes") or its SecurityManager.checkRead(String) method denies read access to the file named by this abstract pathname// Java program to get the amount of free space available on any driveimport java.io.*; public class Test{ public static void main(String[] args) { File file = new File("E:\\"); double size = file.getFreeSpace() / (1024.0 * 1024 * 1024); System.out.printf( "%.3f GB\n", size); }}Output:18.242 GBJava.io.File.getUsableSpace(): Total usable space available with a drive. Returns the number of bytes available to this virtual machine on the partition named by this abstract pathname. When possible, this method checks for write permissions and other operating system restrictions and will therefore usually provide a more accurate estimate of how much new data can actually be written than getFreeSpace().The returned number of available bytes is a hint, but not a guarantee, that it is possible to use most or any of these bytes. The number of unallocated bytes is most likely to be accurate immediately after this call. It is likely to be made inaccurate by any external I/O operations including those made on the system outside of this virtual machine. This method makes no guarantee that write operations to this file system will succeed.Syntax:public long getUsableSpace() Returns: The number of available bytes on the partition or 0L if the abstract pathname does not name a partition. On systems where this information is not available, this method will be equivalent to a call to getFreeSpace(). Throws: SecurityException - If a security manager has been installed and it denies RuntimePermission("getFileSystemAttributes") or its SecurityManager.checkRead(String) method denies read access to the file named by this abstract pathnameimport java.io.*; public class Test{ public static void main(String[] args) { double size = new File("C:\\").getUsableSpace() / (1024.0 * 1024 * 1024); System.out.printf( "%.3f GB\n", size); }}Output:62.857 GBJava.io.File.getTotalSpace(): Total Capacity of a drive. The method returns the size of the partition named by this abstract pathname.Syntax:public long getTotalSpace() Returns: Returns: The size, in bytes, of the partition or 0L if this abstract pathname does not name a partition Throws: SecurityException - If a security manager has been installed and it denies RuntimePermission("getFileSystemAttributes") or its SecurityManager.checkRead(String) method denies read access to the file named by this abstract pathnameimport java.io.*; public class Test{ public static void main(String[] args) { double size = new File("C:\\").getUsableSpace() / (1024.0 * 1024 * 1024); System.out.printf( "%.3f GB\n", size); }}Output:62.857 GB Java.io.File.getFreeSpace(): Get total free space available in a driveSyntax:public long getFreeSpace() Returns the size of the partition named by this abstract pathname. Returns: The size, in bytes, of the partition or 0L if this abstract pathname does not name a partition Throws: SecurityException - If a security manager has been installed and it denies RuntimePermission("getFileSystemAttributes") or its SecurityManager.checkRead(String) method denies read access to the file named by this abstract pathname// Java program to get the amount of free space available on any driveimport java.io.*; public class Test{ public static void main(String[] args) { File file = new File("E:\\"); double size = file.getFreeSpace() / (1024.0 * 1024 * 1024); System.out.printf( "%.3f GB\n", size); }}Output:18.242 GB public long getFreeSpace() Returns the size of the partition named by this abstract pathname. Returns: The size, in bytes, of the partition or 0L if this abstract pathname does not name a partition Throws: SecurityException - If a security manager has been installed and it denies RuntimePermission("getFileSystemAttributes") or its SecurityManager.checkRead(String) method denies read access to the file named by this abstract pathname // Java program to get the amount of free space available on any driveimport java.io.*; public class Test{ public static void main(String[] args) { File file = new File("E:\\"); double size = file.getFreeSpace() / (1024.0 * 1024 * 1024); System.out.printf( "%.3f GB\n", size); }} Output: 18.242 GB Java.io.File.getUsableSpace(): Total usable space available with a drive. Returns the number of bytes available to this virtual machine on the partition named by this abstract pathname. When possible, this method checks for write permissions and other operating system restrictions and will therefore usually provide a more accurate estimate of how much new data can actually be written than getFreeSpace().The returned number of available bytes is a hint, but not a guarantee, that it is possible to use most or any of these bytes. The number of unallocated bytes is most likely to be accurate immediately after this call. It is likely to be made inaccurate by any external I/O operations including those made on the system outside of this virtual machine. This method makes no guarantee that write operations to this file system will succeed.Syntax:public long getUsableSpace() Returns: The number of available bytes on the partition or 0L if the abstract pathname does not name a partition. On systems where this information is not available, this method will be equivalent to a call to getFreeSpace(). Throws: SecurityException - If a security manager has been installed and it denies RuntimePermission("getFileSystemAttributes") or its SecurityManager.checkRead(String) method denies read access to the file named by this abstract pathnameimport java.io.*; public class Test{ public static void main(String[] args) { double size = new File("C:\\").getUsableSpace() / (1024.0 * 1024 * 1024); System.out.printf( "%.3f GB\n", size); }}Output:62.857 GB public long getUsableSpace() Returns: The number of available bytes on the partition or 0L if the abstract pathname does not name a partition. On systems where this information is not available, this method will be equivalent to a call to getFreeSpace(). Throws: SecurityException - If a security manager has been installed and it denies RuntimePermission("getFileSystemAttributes") or its SecurityManager.checkRead(String) method denies read access to the file named by this abstract pathname import java.io.*; public class Test{ public static void main(String[] args) { double size = new File("C:\\").getUsableSpace() / (1024.0 * 1024 * 1024); System.out.printf( "%.3f GB\n", size); }} Output: 62.857 GB Java.io.File.getTotalSpace(): Total Capacity of a drive. The method returns the size of the partition named by this abstract pathname.Syntax:public long getTotalSpace() Returns: Returns: The size, in bytes, of the partition or 0L if this abstract pathname does not name a partition Throws: SecurityException - If a security manager has been installed and it denies RuntimePermission("getFileSystemAttributes") or its SecurityManager.checkRead(String) method denies read access to the file named by this abstract pathnameimport java.io.*; public class Test{ public static void main(String[] args) { double size = new File("C:\\").getUsableSpace() / (1024.0 * 1024 * 1024); System.out.printf( "%.3f GB\n", size); }}Output:62.857 GB Syntax: public long getTotalSpace() Returns: Returns: The size, in bytes, of the partition or 0L if this abstract pathname does not name a partition Throws: SecurityException - If a security manager has been installed and it denies RuntimePermission("getFileSystemAttributes") or its SecurityManager.checkRead(String) method denies read access to the file named by this abstract pathname import java.io.*; public class Test{ public static void main(String[] args) { double size = new File("C:\\").getUsableSpace() / (1024.0 * 1024 * 1024); System.out.printf( "%.3f GB\n", size); }} Output: 62.857 GB Reference used: Oracle This article is contributed by Mayank Kumar. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. Java-I/O java-puzzle Java Java Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Object Oriented Programming (OOPs) Concept in Java How to iterate any Map in Java Interfaces in Java HashMap in Java with Examples ArrayList in Java Collections in Java Multidimensional Arrays in Java Stream In Java Set in Java Singleton Class in Java
[ { "code": null, "e": 28, "s": 0, "text": "\n25 Sep, 2017" }, { "code": null, "e": 426, "s": 28, "text": "There are a few method calls in java that can be utilized to get the space related information about a disk drive. These methods used to fetch the such information are declared in File class, which resides in java.io package. The details of these method call along with their use are given below:Note: These codes will not run on online ide. Also, they will all work on Java 1.6 and above versions" }, { "code": null, "e": 3656, "s": 426, "text": "Java.io.File.getFreeSpace(): Get total free space available in a driveSyntax:public long getFreeSpace()\nReturns the size of the partition named by this abstract pathname.\nReturns:\nThe size, in bytes, of the partition or 0L if this \nabstract pathname does not name a partition\nThrows:\nSecurityException - If a security manager has been installed and it \ndenies RuntimePermission(\"getFileSystemAttributes\") or its \nSecurityManager.checkRead(String) method denies read access to the file \nnamed by this abstract pathname// Java program to get the amount of free space available on any driveimport java.io.*; public class Test{ public static void main(String[] args) { File file = new File(\"E:\\\\\"); double size = file.getFreeSpace() / (1024.0 * 1024 * 1024); System.out.printf( \"%.3f GB\\n\", size); }}Output:18.242 GBJava.io.File.getUsableSpace(): Total usable space available with a drive. Returns the number of bytes available to this virtual machine on the partition named by this abstract pathname. When possible, this method checks for write permissions and other operating system restrictions and will therefore usually provide a more accurate estimate of how much new data can actually be written than getFreeSpace().The returned number of available bytes is a hint, but not a guarantee, that it is possible to use most or any of these bytes. The number of unallocated bytes is most likely to be accurate immediately after this call. It is likely to be made inaccurate by any external I/O operations including those made on the system outside of this virtual machine. This method makes no guarantee that write operations to this file system will succeed.Syntax:public long getUsableSpace()\nReturns:\nThe number of available bytes on the partition or 0L if the \nabstract pathname does not name a partition. On systems where\nthis information is not available, this method will be\nequivalent to a call to getFreeSpace().\nThrows:\nSecurityException - If a security manager has been installed and it \ndenies RuntimePermission(\"getFileSystemAttributes\") or its\nSecurityManager.checkRead(String) method denies read access to the \nfile named by this abstract pathnameimport java.io.*; public class Test{ public static void main(String[] args) { double size = new File(\"C:\\\\\").getUsableSpace() / (1024.0 * 1024 * 1024); System.out.printf( \"%.3f GB\\n\", size); }}Output:62.857 GBJava.io.File.getTotalSpace(): Total Capacity of a drive. The method returns the size of the partition named by this abstract pathname.Syntax:public long getTotalSpace()\nReturns: Returns:\nThe size, in bytes, of the partition or 0L if this abstract pathname \ndoes not name a partition\nThrows:\nSecurityException - If a security manager has been installed and it\ndenies RuntimePermission(\"getFileSystemAttributes\") or its \nSecurityManager.checkRead(String) method denies read access to \nthe file named by this abstract pathnameimport java.io.*; public class Test{ public static void main(String[] args) { double size = new File(\"C:\\\\\").getUsableSpace() / (1024.0 * 1024 * 1024); System.out.printf( \"%.3f GB\\n\", size); }}Output:62.857 GB" }, { "code": null, "e": 4514, "s": 3656, "text": "Java.io.File.getFreeSpace(): Get total free space available in a driveSyntax:public long getFreeSpace()\nReturns the size of the partition named by this abstract pathname.\nReturns:\nThe size, in bytes, of the partition or 0L if this \nabstract pathname does not name a partition\nThrows:\nSecurityException - If a security manager has been installed and it \ndenies RuntimePermission(\"getFileSystemAttributes\") or its \nSecurityManager.checkRead(String) method denies read access to the file \nnamed by this abstract pathname// Java program to get the amount of free space available on any driveimport java.io.*; public class Test{ public static void main(String[] args) { File file = new File(\"E:\\\\\"); double size = file.getFreeSpace() / (1024.0 * 1024 * 1024); System.out.printf( \"%.3f GB\\n\", size); }}Output:18.242 GB" }, { "code": null, "e": 4955, "s": 4514, "text": "public long getFreeSpace()\nReturns the size of the partition named by this abstract pathname.\nReturns:\nThe size, in bytes, of the partition or 0L if this \nabstract pathname does not name a partition\nThrows:\nSecurityException - If a security manager has been installed and it \ndenies RuntimePermission(\"getFileSystemAttributes\") or its \nSecurityManager.checkRead(String) method denies read access to the file \nnamed by this abstract pathname" }, { "code": "// Java program to get the amount of free space available on any driveimport java.io.*; public class Test{ public static void main(String[] args) { File file = new File(\"E:\\\\\"); double size = file.getFreeSpace() / (1024.0 * 1024 * 1024); System.out.printf( \"%.3f GB\\n\", size); }}", "e": 5280, "s": 4955, "text": null }, { "code": null, "e": 5288, "s": 5280, "text": "Output:" }, { "code": null, "e": 5298, "s": 5288, "text": "18.242 GB" }, { "code": null, "e": 6897, "s": 5298, "text": "Java.io.File.getUsableSpace(): Total usable space available with a drive. Returns the number of bytes available to this virtual machine on the partition named by this abstract pathname. When possible, this method checks for write permissions and other operating system restrictions and will therefore usually provide a more accurate estimate of how much new data can actually be written than getFreeSpace().The returned number of available bytes is a hint, but not a guarantee, that it is possible to use most or any of these bytes. The number of unallocated bytes is most likely to be accurate immediately after this call. It is likely to be made inaccurate by any external I/O operations including those made on the system outside of this virtual machine. This method makes no guarantee that write operations to this file system will succeed.Syntax:public long getUsableSpace()\nReturns:\nThe number of available bytes on the partition or 0L if the \nabstract pathname does not name a partition. On systems where\nthis information is not available, this method will be\nequivalent to a call to getFreeSpace().\nThrows:\nSecurityException - If a security manager has been installed and it \ndenies RuntimePermission(\"getFileSystemAttributes\") or its\nSecurityManager.checkRead(String) method denies read access to the \nfile named by this abstract pathnameimport java.io.*; public class Test{ public static void main(String[] args) { double size = new File(\"C:\\\\\").getUsableSpace() / (1024.0 * 1024 * 1024); System.out.printf( \"%.3f GB\\n\", size); }}Output:62.857 GB" }, { "code": null, "e": 7394, "s": 6897, "text": "public long getUsableSpace()\nReturns:\nThe number of available bytes on the partition or 0L if the \nabstract pathname does not name a partition. On systems where\nthis information is not available, this method will be\nequivalent to a call to getFreeSpace().\nThrows:\nSecurityException - If a security manager has been installed and it \ndenies RuntimePermission(\"getFileSystemAttributes\") or its\nSecurityManager.checkRead(String) method denies read access to the \nfile named by this abstract pathname" }, { "code": "import java.io.*; public class Test{ public static void main(String[] args) { double size = new File(\"C:\\\\\").getUsableSpace() / (1024.0 * 1024 * 1024); System.out.printf( \"%.3f GB\\n\", size); }}", "e": 7630, "s": 7394, "text": null }, { "code": null, "e": 7638, "s": 7630, "text": "Output:" }, { "code": null, "e": 7648, "s": 7638, "text": "62.857 GB" }, { "code": null, "e": 8423, "s": 7648, "text": "Java.io.File.getTotalSpace(): Total Capacity of a drive. The method returns the size of the partition named by this abstract pathname.Syntax:public long getTotalSpace()\nReturns: Returns:\nThe size, in bytes, of the partition or 0L if this abstract pathname \ndoes not name a partition\nThrows:\nSecurityException - If a security manager has been installed and it\ndenies RuntimePermission(\"getFileSystemAttributes\") or its \nSecurityManager.checkRead(String) method denies read access to \nthe file named by this abstract pathnameimport java.io.*; public class Test{ public static void main(String[] args) { double size = new File(\"C:\\\\\").getUsableSpace() / (1024.0 * 1024 * 1024); System.out.printf( \"%.3f GB\\n\", size); }}Output:62.857 GB" }, { "code": null, "e": 8431, "s": 8423, "text": "Syntax:" }, { "code": null, "e": 8814, "s": 8431, "text": "public long getTotalSpace()\nReturns: Returns:\nThe size, in bytes, of the partition or 0L if this abstract pathname \ndoes not name a partition\nThrows:\nSecurityException - If a security manager has been installed and it\ndenies RuntimePermission(\"getFileSystemAttributes\") or its \nSecurityManager.checkRead(String) method denies read access to \nthe file named by this abstract pathname" }, { "code": "import java.io.*; public class Test{ public static void main(String[] args) { double size = new File(\"C:\\\\\").getUsableSpace() / (1024.0 * 1024 * 1024); System.out.printf( \"%.3f GB\\n\", size); }}", "e": 9050, "s": 8814, "text": null }, { "code": null, "e": 9058, "s": 9050, "text": "Output:" }, { "code": null, "e": 9068, "s": 9058, "text": "62.857 GB" }, { "code": null, "e": 9091, "s": 9068, "text": "Reference used: Oracle" }, { "code": null, "e": 9391, "s": 9091, "text": "This article is contributed by Mayank Kumar. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks." }, { "code": null, "e": 9516, "s": 9391, "text": "Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above." }, { "code": null, "e": 9525, "s": 9516, "text": "Java-I/O" }, { "code": null, "e": 9537, "s": 9525, "text": "java-puzzle" }, { "code": null, "e": 9542, "s": 9537, "text": "Java" }, { "code": null, "e": 9547, "s": 9542, "text": "Java" }, { "code": null, "e": 9645, "s": 9547, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 9696, "s": 9645, "text": "Object Oriented Programming (OOPs) Concept in Java" }, { "code": null, "e": 9727, "s": 9696, "text": "How to iterate any Map in Java" }, { "code": null, "e": 9746, "s": 9727, "text": "Interfaces in Java" }, { "code": null, "e": 9776, "s": 9746, "text": "HashMap in Java with Examples" }, { "code": null, "e": 9794, "s": 9776, "text": "ArrayList in Java" }, { "code": null, "e": 9814, "s": 9794, "text": "Collections in Java" }, { "code": null, "e": 9846, "s": 9814, "text": "Multidimensional Arrays in Java" }, { "code": null, "e": 9861, "s": 9846, "text": "Stream In Java" }, { "code": null, "e": 9873, "s": 9861, "text": "Set in Java" } ]
How to set radio button checked by button click in AngularJS ?
14 Oct, 2020 In this article, we will see how to set the radio button checked by button click in AngularJS. Approach: The approach is to use the ng-checked to check the radio button in the DOM. In the first example, a single radio button is checked by the button and In the second example, multiple radio button are checked by button. ng-model is used to bind the radio buttons. Example 1: <!DOCTYPE HTML><html> <head> <script src="//ajax.googleapis.com/ajax/libs/angularjs/1.2.13/angular.min.js"> </script> <script> var myApp = angular.module("app", []); myApp.controller("controller", function ($scope) { $scope.radioCh = function () { if (!$scope.radio) { $scope.radio = true; } else { $scope.radio = false; } } }); </script></head> <body style="text-align:center;"> <h1 style="color:green;"> GeeksForGeeks </h1> <p> How to set radio button checked by button click in AngularJS </p> <div ng-app="app"> <div ng-controller="controller"> Radio button: <input type="radio" ng-checked="radio"> <br><br> <button ng-click="radioCh()" ng-model='radio'> Click here </button> <br><br> </div> </div></body> </html> Output: Example 2: <!DOCTYPE HTML><html> <head> <script src="//ajax.googleapis.com/ajax/libs/angularjs/1.2.13/angular.min.js"> </script> <script> var myApp = angular.module("app", []); myApp.controller("controller", function ($scope) { $scope.radioCh = function () { if (!$scope.radio) { $scope.radio = true; } else { $scope.radio = false; } } }); </script></head> <body style="text-align:center;"> <h1 style="color:green;"> GeeksForGeeks </h1> <p> How to set radio button checked by button click in AngularJS </p> <div ng-app="app"> <div ng-controller="controller"> Radio button 1: <input type="radio" ng-checked="radio"> <br><br> Radio button 2: <input type="radio" ng-checked="radio"> <br><br> Radio button 3: <input type="radio" ng-checked="radio"> <br><br> <button ng-click="radioCh()" ng-model='radio'> Click here </button> <br><br> </div> </div></body> </html> Output: AngularJS-Misc AngularJS HTML Web Technologies HTML Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Routing in Angular 9/10 Angular PrimeNG Dropdown Component Angular 10 (blur) Event How to make a Bootstrap Modal Popup in Angular 9/8 ? How to create module with Routing in Angular 9 ? 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
[ { "code": null, "e": 28, "s": 0, "text": "\n14 Oct, 2020" }, { "code": null, "e": 123, "s": 28, "text": "In this article, we will see how to set the radio button checked by button click in AngularJS." }, { "code": null, "e": 394, "s": 123, "text": "Approach: The approach is to use the ng-checked to check the radio button in the DOM. In the first example, a single radio button is checked by the button and In the second example, multiple radio button are checked by button. ng-model is used to bind the radio buttons." }, { "code": null, "e": 405, "s": 394, "text": "Example 1:" }, { "code": "<!DOCTYPE HTML><html> <head> <script src=\"//ajax.googleapis.com/ajax/libs/angularjs/1.2.13/angular.min.js\"> </script> <script> var myApp = angular.module(\"app\", []); myApp.controller(\"controller\", function ($scope) { $scope.radioCh = function () { if (!$scope.radio) { $scope.radio = true; } else { $scope.radio = false; } } }); </script></head> <body style=\"text-align:center;\"> <h1 style=\"color:green;\"> GeeksForGeeks </h1> <p> How to set radio button checked by button click in AngularJS </p> <div ng-app=\"app\"> <div ng-controller=\"controller\"> Radio button: <input type=\"radio\" ng-checked=\"radio\"> <br><br> <button ng-click=\"radioCh()\" ng-model='radio'> Click here </button> <br><br> </div> </div></body> </html>", "e": 1430, "s": 405, "text": null }, { "code": null, "e": 1438, "s": 1430, "text": "Output:" }, { "code": null, "e": 1449, "s": 1438, "text": "Example 2:" }, { "code": "<!DOCTYPE HTML><html> <head> <script src=\"//ajax.googleapis.com/ajax/libs/angularjs/1.2.13/angular.min.js\"> </script> <script> var myApp = angular.module(\"app\", []); myApp.controller(\"controller\", function ($scope) { $scope.radioCh = function () { if (!$scope.radio) { $scope.radio = true; } else { $scope.radio = false; } } }); </script></head> <body style=\"text-align:center;\"> <h1 style=\"color:green;\"> GeeksForGeeks </h1> <p> How to set radio button checked by button click in AngularJS </p> <div ng-app=\"app\"> <div ng-controller=\"controller\"> Radio button 1: <input type=\"radio\" ng-checked=\"radio\"> <br><br> Radio button 2: <input type=\"radio\" ng-checked=\"radio\"> <br><br> Radio button 3: <input type=\"radio\" ng-checked=\"radio\"> <br><br> <button ng-click=\"radioCh()\" ng-model='radio'> Click here </button> <br><br> </div> </div></body> </html> ", "e": 2697, "s": 1449, "text": null }, { "code": null, "e": 2705, "s": 2697, "text": "Output:" }, { "code": null, "e": 2720, "s": 2705, "text": "AngularJS-Misc" }, { "code": null, "e": 2730, "s": 2720, "text": "AngularJS" }, { "code": null, "e": 2735, "s": 2730, "text": "HTML" }, { "code": null, "e": 2752, "s": 2735, "text": "Web Technologies" }, { "code": null, "e": 2757, "s": 2752, "text": "HTML" }, { "code": null, "e": 2855, "s": 2757, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 2879, "s": 2855, "text": "Routing in Angular 9/10" }, { "code": null, "e": 2914, "s": 2879, "text": "Angular PrimeNG Dropdown Component" }, { "code": null, "e": 2938, "s": 2914, "text": "Angular 10 (blur) Event" }, { "code": null, "e": 2991, "s": 2938, "text": "How to make a Bootstrap Modal Popup in Angular 9/8 ?" }, { "code": null, "e": 3040, "s": 2991, "text": "How to create module with Routing in Angular 9 ?" }, { "code": null, "e": 3088, "s": 3040, "text": "How to update Node.js and NPM to next version ?" }, { "code": null, "e": 3150, "s": 3088, "text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills" }, { "code": null, "e": 3200, "s": 3150, "text": "How to insert spaces/tabs in text using HTML/CSS?" }, { "code": null, "e": 3224, "s": 3200, "text": "REST API (Introduction)" } ]
How to Use read.delim in R?
19 Dec, 2021 In this article, we will learn how to use the read.delim() in the R Programming Language. The read.delim() function is used to read delimited text files in the R Language. It doesn’t need any external package to work. This function converts a delimited text file into a data frame and can be used to read a variety of space-separated files for example CSV. Syntax: read.delim( file, header) where: file: determines the file name to be read with full path. header: A Boolean that determines whether the first line represents the header of the table. Default is TRUE. Under this example, we are reading a data frame from a space-separated text file using the read.delim() function in R language. Text file in use: Program: R # read the space separated dataframedata_frame <- read.delim('sample.txt') # view data framedata_frame Output: group y x 1 category1 55 -0.15703480 2 category1 63 0.63781188 3 category1 62 -1.59689179 4 category1 59 -0.61527367 5 category1 64 0.80799947 6 category1 73 1.03513951 7 category1 56 0.67577537 8 category1 66 -0.37485984 9 category1 73 0.14448351 10 category1 68 -0.53013492 11 category1 63 0.57979608 12 category1 74 -0.08396805 13 category1 67 -0.63099142 14 category1 50 -0.49751923 To read a text file separated by a manual symbol, we use the sep parameter to determine the symbol that separates the data in the text file. In this way, we can read comma-separated-values, tab-separated values, etc. Syntax: read.delim( file, sep) where: file: determines the file name to be read with full path. sep: determines table delimiter. Default is a tab (\t). In this example, we are reading a data frame from a comma-separated text file using the read.delim() function with the sep parameter in the R language. Text file in use: Program: R # read the tab separated dataframe data_frame <- read.delim('my_data.txt', sep=',') # view data framedata_frame Output: group y x 1 category1 63 0.95195245 2 category1 77 -1.68432491 3 category1 72 0.03062164 4 category1 67 -1.56885679 5 category1 69 -0.35835908 6 category1 53 -0.87003090 7 category1 73 -0.88877644 8 category1 64 0.67040206 9 category1 66 -0.20397715 10 category1 58 -0.29472917 11 category1 68 -1.47210730 12 category1 68 -1.40288930 13 category1 65 -0.14653898 14 category1 70 0.76216057 15 category1 71 -0.21718205 16 category1 64 0.72430687 17 category1 70 -0.24907560 18 category1 60 -1.24296149 Picked R-Functions R Language Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Change Color of Bars in Barchart using ggplot2 in R How to Split Column Into Multiple Columns in R DataFrame? Group by function in R using Dplyr How to Change Axis Scales in R Plots? How to filter R DataFrame by values in a column? R - if statement Logistic Regression in R Programming Replace Specific Characters in String in R How to import an Excel File into R ? Joining of Dataframes in R Programming
[ { "code": null, "e": 28, "s": 0, "text": "\n19 Dec, 2021" }, { "code": null, "e": 118, "s": 28, "text": "In this article, we will learn how to use the read.delim() in the R Programming Language." }, { "code": null, "e": 386, "s": 118, "text": "The read.delim() function is used to read delimited text files in the R Language. It doesn’t need any external package to work. This function converts a delimited text file into a data frame and can be used to read a variety of space-separated files for example CSV. " }, { "code": null, "e": 394, "s": 386, "text": "Syntax:" }, { "code": null, "e": 420, "s": 394, "text": "read.delim( file, header)" }, { "code": null, "e": 427, "s": 420, "text": "where:" }, { "code": null, "e": 485, "s": 427, "text": "file: determines the file name to be read with full path." }, { "code": null, "e": 595, "s": 485, "text": "header: A Boolean that determines whether the first line represents the header of the table. Default is TRUE." }, { "code": null, "e": 723, "s": 595, "text": "Under this example, we are reading a data frame from a space-separated text file using the read.delim() function in R language." }, { "code": null, "e": 741, "s": 723, "text": "Text file in use:" }, { "code": null, "e": 750, "s": 741, "text": "Program:" }, { "code": null, "e": 752, "s": 750, "text": "R" }, { "code": "# read the space separated dataframedata_frame <- read.delim('sample.txt') # view data framedata_frame", "e": 856, "s": 752, "text": null }, { "code": null, "e": 864, "s": 856, "text": "Output:" }, { "code": null, "e": 1284, "s": 864, "text": " group y x\n1 category1 55 -0.15703480\n2 category1 63 0.63781188\n3 category1 62 -1.59689179\n4 category1 59 -0.61527367\n5 category1 64 0.80799947\n6 category1 73 1.03513951\n7 category1 56 0.67577537\n8 category1 66 -0.37485984\n9 category1 73 0.14448351\n10 category1 68 -0.53013492\n11 category1 63 0.57979608\n12 category1 74 -0.08396805\n13 category1 67 -0.63099142\n14 category1 50 -0.49751923" }, { "code": null, "e": 1501, "s": 1284, "text": "To read a text file separated by a manual symbol, we use the sep parameter to determine the symbol that separates the data in the text file. In this way, we can read comma-separated-values, tab-separated values, etc." }, { "code": null, "e": 1509, "s": 1501, "text": "Syntax:" }, { "code": null, "e": 1532, "s": 1509, "text": "read.delim( file, sep)" }, { "code": null, "e": 1539, "s": 1532, "text": "where:" }, { "code": null, "e": 1597, "s": 1539, "text": "file: determines the file name to be read with full path." }, { "code": null, "e": 1653, "s": 1597, "text": "sep: determines table delimiter. Default is a tab (\\t)." }, { "code": null, "e": 1806, "s": 1653, "text": "In this example, we are reading a data frame from a comma-separated text file using the read.delim() function with the sep parameter in the R language. " }, { "code": null, "e": 1824, "s": 1806, "text": "Text file in use:" }, { "code": null, "e": 1833, "s": 1824, "text": "Program:" }, { "code": null, "e": 1835, "s": 1833, "text": "R" }, { "code": "# read the tab separated dataframe data_frame <- read.delim('my_data.txt', sep=',') # view data framedata_frame", "e": 1948, "s": 1835, "text": null }, { "code": null, "e": 1956, "s": 1948, "text": "Output:" }, { "code": null, "e": 2488, "s": 1956, "text": " group y x\n1 category1 63 0.95195245\n2 category1 77 -1.68432491\n3 category1 72 0.03062164\n4 category1 67 -1.56885679\n5 category1 69 -0.35835908\n6 category1 53 -0.87003090\n7 category1 73 -0.88877644\n8 category1 64 0.67040206\n9 category1 66 -0.20397715\n10 category1 58 -0.29472917\n11 category1 68 -1.47210730\n12 category1 68 -1.40288930\n13 category1 65 -0.14653898\n14 category1 70 0.76216057\n15 category1 71 -0.21718205\n16 category1 64 0.72430687\n17 category1 70 -0.24907560\n18 category1 60 -1.24296149" }, { "code": null, "e": 2495, "s": 2488, "text": "Picked" }, { "code": null, "e": 2507, "s": 2495, "text": "R-Functions" }, { "code": null, "e": 2518, "s": 2507, "text": "R Language" }, { "code": null, "e": 2616, "s": 2518, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 2668, "s": 2616, "text": "Change Color of Bars in Barchart using ggplot2 in R" }, { "code": null, "e": 2726, "s": 2668, "text": "How to Split Column Into Multiple Columns in R DataFrame?" }, { "code": null, "e": 2761, "s": 2726, "text": "Group by function in R using Dplyr" }, { "code": null, "e": 2799, "s": 2761, "text": "How to Change Axis Scales in R Plots?" }, { "code": null, "e": 2848, "s": 2799, "text": "How to filter R DataFrame by values in a column?" }, { "code": null, "e": 2865, "s": 2848, "text": "R - if statement" }, { "code": null, "e": 2902, "s": 2865, "text": "Logistic Regression in R Programming" }, { "code": null, "e": 2945, "s": 2902, "text": "Replace Specific Characters in String in R" }, { "code": null, "e": 2982, "s": 2945, "text": "How to import an Excel File into R ?" } ]
How to use font-awesome icons from Node.js-modules?
07 Oct, 2021 Font-awesome is a web’s icon library that gives you scalable vector icons that can be customized in terms of color, size, and in many more aspects. Many companies integrate this library icon’s on their websites. It has 600+ icons and every icon is mobile and desktop responsive irrespective of the resolution screen size. It also gives us to use animations without the use of javascript. Syntax for Installing the library: npm install font-awesome --save First, we need to enter the above command in the terminal for installing the package. Once the installation is fixed you can find the package inside the node-modules folder. Then you need to import the file in style.css file. After importing the file you can start using the font-awesome icons. Implementation of code: In style.css file, import font-awesome by using the following syntax. @import url('../node_modules/font-awesome/css/font-awesome.min.css'); app.component.html : <h1>Font-awesome</h1>Notification :<i class='fas fa-bell' style='font-size:24px'></i><br><br>Message or Inbox :<i class='fas fa-envelope' style='font-size:24px'></i><br><br>Bookmark : <i class='fas fa-bookmark' style='font-size:24px'></i><br><br>Like Button :<i class='fas fa-thumbs-up' style='font-size:24px'></i><br><br>Calendar:<i class='fas fa-calendar-alt' style='font-size:24px'></i> Output: Node.js-Misc Picked Node.js Web Technologies Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Difference between promise and async await in Node.js Mongoose | findByIdAndUpdate() Function JWT Authentication with Node.js Installation of Node.js on Windows How to read and write Excel file in Node.js ? 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 ? Differences between Functional Components and Class Components in React
[ { "code": null, "e": 28, "s": 0, "text": "\n07 Oct, 2021" }, { "code": null, "e": 416, "s": 28, "text": "Font-awesome is a web’s icon library that gives you scalable vector icons that can be customized in terms of color, size, and in many more aspects. Many companies integrate this library icon’s on their websites. It has 600+ icons and every icon is mobile and desktop responsive irrespective of the resolution screen size. It also gives us to use animations without the use of javascript." }, { "code": null, "e": 451, "s": 416, "text": "Syntax for Installing the library:" }, { "code": null, "e": 483, "s": 451, "text": "npm install font-awesome --save" }, { "code": null, "e": 569, "s": 483, "text": "First, we need to enter the above command in the terminal for installing the package." }, { "code": null, "e": 657, "s": 569, "text": "Once the installation is fixed you can find the package inside the node-modules folder." }, { "code": null, "e": 709, "s": 657, "text": "Then you need to import the file in style.css file." }, { "code": null, "e": 778, "s": 709, "text": "After importing the file you can start using the font-awesome icons." }, { "code": null, "e": 802, "s": 778, "text": "Implementation of code:" }, { "code": null, "e": 872, "s": 802, "text": "In style.css file, import font-awesome by using the following syntax." }, { "code": "@import url('../node_modules/font-awesome/css/font-awesome.min.css');", "e": 942, "s": 872, "text": null }, { "code": null, "e": 963, "s": 942, "text": "app.component.html :" }, { "code": "<h1>Font-awesome</h1>Notification :<i class='fas fa-bell' style='font-size:24px'></i><br><br>Message or Inbox :<i class='fas fa-envelope' style='font-size:24px'></i><br><br>Bookmark : <i class='fas fa-bookmark' style='font-size:24px'></i><br><br>Like Button :<i class='fas fa-thumbs-up' style='font-size:24px'></i><br><br>Calendar:<i class='fas fa-calendar-alt' style='font-size:24px'></i>", "e": 1353, "s": 963, "text": null }, { "code": null, "e": 1361, "s": 1353, "text": "Output:" }, { "code": null, "e": 1374, "s": 1361, "text": "Node.js-Misc" }, { "code": null, "e": 1381, "s": 1374, "text": "Picked" }, { "code": null, "e": 1389, "s": 1381, "text": "Node.js" }, { "code": null, "e": 1406, "s": 1389, "text": "Web Technologies" }, { "code": null, "e": 1504, "s": 1406, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 1558, "s": 1504, "text": "Difference between promise and async await in Node.js" }, { "code": null, "e": 1598, "s": 1558, "text": "Mongoose | findByIdAndUpdate() Function" }, { "code": null, "e": 1630, "s": 1598, "text": "JWT Authentication with Node.js" }, { "code": null, "e": 1665, "s": 1630, "text": "Installation of Node.js on Windows" }, { "code": null, "e": 1711, "s": 1665, "text": "How to read and write Excel file in Node.js ?" }, { "code": null, "e": 1773, "s": 1711, "text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills" }, { "code": null, "e": 1834, "s": 1773, "text": "Difference between var, let and const keywords in JavaScript" }, { "code": null, "e": 1884, "s": 1834, "text": "How to insert spaces/tabs in text using HTML/CSS?" }, { "code": null, "e": 1927, "s": 1884, "text": "How to fetch data from an API in ReactJS ?" } ]
How to Add Key-Value pairs to LinkedHashMap in Java?
22 Dec, 2020 LinkedHashMap is a Hash table and linked list implementation of the Map interface. In LinkedHashMap order of key-value pair depends on the order in which keys were inserted into the map. Insertion order does not affect if a key is reinserted into the map. Example: Input: Key: 1 Value : 1221 Key: 2 Value : 2112 Output: Keys : [1,2] Values : [1221,2112] Key-Value pairs : [1=1221, 2=2112] Methods Use: put(Key, Value): First parameter as key and second parameter as Value.keySet(): Creates a set out of the key elements contained in the hash map.values(): Create a set out of the values in the hash map. put(Key, Value): First parameter as key and second parameter as Value. keySet(): Creates a set out of the key elements contained in the hash map. values(): Create a set out of the values in the hash map. Approach: Create two-variable named as Key and ValueAccept the input from user in Key and in ValueUse put() method to add Key-Value pair inside the LinkedHashMap Create two-variable named as Key and Value Accept the input from user in Key and in Value Use put() method to add Key-Value pair inside the LinkedHashMap Below is the implementation of the above approach: Java // Java Program to add key-value // pairs to LinkedHashMapimport java.util.*;public class Main { public static void main(String[] args) { // create an instance of LinkedHashMap LinkedHashMap<Integer, Integer> map = new LinkedHashMap<Integer, Integer>(); int num, key, val; num = 2; for (int i = 0; i < num; i++) { // Taking inputs from user key = i + 1; val = key * 10; // Add mappings using put method map.put(key, val); } // Displaying key System.out.println("Keys: " + map.keySet()); // Displaying value System.out.println("Values: " + map.values()); // Displaying key-value pair System.out.println("Key-Value pairs: " + map.entrySet()); }} Keys: [1, 2] Values: [10, 20] Key-Value pairs: [1=10, 2=20] Time Complexity: O(1) Java-LinkedHashMap Picked Java Java Programs Java Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n22 Dec, 2020" }, { "code": null, "e": 284, "s": 28, "text": "LinkedHashMap is a Hash table and linked list implementation of the Map interface. In LinkedHashMap order of key-value pair depends on the order in which keys were inserted into the map. Insertion order does not affect if a key is reinserted into the map." }, { "code": null, "e": 293, "s": 284, "text": "Example:" }, { "code": null, "e": 450, "s": 293, "text": "Input: \n Key: 1\n Value : 1221\n Key: 2\n Value : 2112\nOutput:\n Keys : [1,2]\n Values : [1221,2112]\n Key-Value pairs : [1=1221, 2=2112]" }, { "code": null, "e": 463, "s": 450, "text": "Methods Use:" }, { "code": null, "e": 665, "s": 463, "text": "put(Key, Value): First parameter as key and second parameter as Value.keySet(): Creates a set out of the key elements contained in the hash map.values(): Create a set out of the values in the hash map." }, { "code": null, "e": 736, "s": 665, "text": "put(Key, Value): First parameter as key and second parameter as Value." }, { "code": null, "e": 811, "s": 736, "text": "keySet(): Creates a set out of the key elements contained in the hash map." }, { "code": null, "e": 869, "s": 811, "text": "values(): Create a set out of the values in the hash map." }, { "code": null, "e": 879, "s": 869, "text": "Approach:" }, { "code": null, "e": 1031, "s": 879, "text": "Create two-variable named as Key and ValueAccept the input from user in Key and in ValueUse put() method to add Key-Value pair inside the LinkedHashMap" }, { "code": null, "e": 1074, "s": 1031, "text": "Create two-variable named as Key and Value" }, { "code": null, "e": 1121, "s": 1074, "text": "Accept the input from user in Key and in Value" }, { "code": null, "e": 1185, "s": 1121, "text": "Use put() method to add Key-Value pair inside the LinkedHashMap" }, { "code": null, "e": 1236, "s": 1185, "text": "Below is the implementation of the above approach:" }, { "code": null, "e": 1241, "s": 1236, "text": "Java" }, { "code": "// Java Program to add key-value // pairs to LinkedHashMapimport java.util.*;public class Main { public static void main(String[] args) { // create an instance of LinkedHashMap LinkedHashMap<Integer, Integer> map = new LinkedHashMap<Integer, Integer>(); int num, key, val; num = 2; for (int i = 0; i < num; i++) { // Taking inputs from user key = i + 1; val = key * 10; // Add mappings using put method map.put(key, val); } // Displaying key System.out.println(\"Keys: \" + map.keySet()); // Displaying value System.out.println(\"Values: \" + map.values()); // Displaying key-value pair System.out.println(\"Key-Value pairs: \" + map.entrySet()); }}", "e": 2094, "s": 1241, "text": null }, { "code": null, "e": 2154, "s": 2094, "text": "Keys: [1, 2]\nValues: [10, 20]\nKey-Value pairs: [1=10, 2=20]" }, { "code": null, "e": 2176, "s": 2154, "text": "Time Complexity: O(1)" }, { "code": null, "e": 2195, "s": 2176, "text": "Java-LinkedHashMap" }, { "code": null, "e": 2202, "s": 2195, "text": "Picked" }, { "code": null, "e": 2207, "s": 2202, "text": "Java" }, { "code": null, "e": 2221, "s": 2207, "text": "Java Programs" }, { "code": null, "e": 2226, "s": 2221, "text": "Java" } ]