title
stringlengths
3
221
text
stringlengths
17
477k
parsed
listlengths
0
3.17k
Find the sum of all possible pairs in an array of N elements
19 Mar, 2022 Given an array arr[] of N integers, the task is to find the sum of all the pairs possible from the given array. Note that, (arr[i], arr[i]) is also considered as a valid pair.(arr[i], arr[j]) and (arr[j], arr[i]) are considered as two different pairs. (arr[i], arr[i]) is also considered as a valid pair. (arr[i], arr[j]) and (arr[j], arr[i]) are considered as two different pairs. Examples: Input: arr[] = {1, 2} Output: 12 All valid pairs are (1, 1), (1, 2), (2, 1) and (2, 2). 1 + 1 + 1 + 2 + 2 + 1 + 2 + 2 = 12 Input: arr[] = {1, 2, 3, 1, 4} Output: 110 Naive approach: Find all the possible pairs and calculate the sum of the elements of each pair. Below is the implementation of the above approach: C++ Java Python3 C# Javascript // C++ implementation of the approach#include <bits/stdc++.h>using namespace std; // Function to return the sum of the elements// of all possible pairs from the arrayint sumPairs(int arr[], int n){ // To store the required sum int sum = 0; // Nested loop for all possible pairs for (int i = 0; i < n; i++) { for (int j = 0; j < n; j++) { // Add the sum of the elements // of the current pair sum += (arr[i] + arr[j]); } } return sum;} // Driver codeint main(){ int arr[] = { 1, 2, 3 }; int n = sizeof(arr) / sizeof(arr[0]); cout << sumPairs(arr, n); return 0;} // Java implementation of the approachimport java.util.*; class GFG{ // Function to return the sum of the elements // of all possible pairs from the array static int sumPairs(int arr[], int n) { // To store the required sum int sum = 0; // Nested loop for all possible pairs for (int i = 0; i < n; i++) { for (int j = 0; j < n; j++) { // Add the sum of the elements // of the current pair sum += (arr[i] + arr[j]); } } return sum; } // Driver code public static void main(String[] args) { int arr[] = {1, 2, 3}; int n = arr.length; System.out.println(sumPairs(arr, n)); }} // This code is contributed by PrinciRaj1992 # Python3 implementation of the approach # Function to return the summ of the elements# of all possible pairs from the arraydef summPairs(arr, n): # To store the required summ summ = 0 # Nested loop for all possible pairs for i in range(n): for j in range(n): # Add the summ of the elements # of the current pair summ += (arr[i] + arr[j]) return summ # Driver codearr = [1, 2, 3]n = len(arr) print(summPairs(arr, n)) # This code is contributed by Mohit Kumar // C# implementation of the approachusing System; class GFG{ // Function to return the sum of the elements // of all possible pairs from the array static int sumPairs(int []arr, int n) { // To store the required sum int sum = 0; // Nested loop for all possible pairs for (int i = 0; i < n; i++) { for (int j = 0; j < n; j++) { // Add the sum of the elements // of the current pair sum += (arr[i] + arr[j]); } } return sum; } // Driver code public static void Main(String[] args) { int []arr = {1, 2, 3}; int n = arr.Length; Console.WriteLine(sumPairs(arr, n)); }} // This code is contributed by PrinciRaj1992 <script> // Javascript implementation of the approach // Function to return the sum of the elements// of all possible pairs from the arrayfunction sumPairs(arr, n){ // To store the required sum var sum = 0; var i, j; // Nested loop for all possible pairs for(i = 0; i < n; i++) { for(j = 0; j < n; j++) { // Add the sum of the elements // of the current pair sum += (arr[i] + arr[j]); } } return sum;} // Driver codevar arr = [ 1, 2, 3 ];var n = arr.length; document.write(sumPairs(arr, n)); // This code is contributed by ipg2016107 </script> 36 Time Complexity: O(N2) Auxiliary Space: O(1) Efficient approach: It can be observed that each element appears exactly (2 * N) times as one of the elements of the pair (x, y). Exactly N times as x and exactly N times as y. Below is the implementation of the above approach: C++ Java Python3 C# Javascript // C++ implementation of the approach#include <bits/stdc++.h>using namespace std; // Function to return the sum of the elements// of all possible pairs from the arrayint sumPairs(int arr[], int n){ // To store the required sum int sum = 0; // For every element of the array for (int i = 0; i < n; i++) { // It appears (2 * n) times sum = sum + (arr[i] * (2 * n)); } return sum;} // Driver codeint main(){ int arr[] = { 1, 2, 3 }; int n = sizeof(arr) / sizeof(arr[0]); cout << sumPairs(arr, n); return 0;} // Java implementation of the approachimport java.util.*; class GFG{ // Function to return the sum of the elements// of all possible pairs from the arraystatic int sumPairs(int arr[], int n){ // To store the required sum int sum = 0; // For every element of the array for (int i = 0; i < n; i++) { // It appears (2 * n) times sum = sum + (arr[i] * (2 * n)); } return sum;} // Driver codestatic public void main(String []arg){ int arr[] = { 1, 2, 3 }; int n = arr.length; System.out.println(sumPairs(arr, n));}} // This code is contributed by 29AjayKumar # Python3 implementation of the approach # Function to return the sum of the elements# of all possible pairs from the arraydef sumPairs(arr, n) : # To store the required sum sum = 0; # For every element of the array for i in range(n) : # It appears (2 * n) times sum = sum + (arr[i] * (2 * n)); return sum; # Driver codeif __name__ == "__main__" : arr = [ 1, 2, 3 ]; n = len(arr); print(sumPairs(arr, n)); # This code is contributed by AnkitRai01 // C# implementation of the approachusing System; class GFG{ // Function to return the sum of the elements// of all possible pairs from the arraystatic int sumPairs(int []arr, int n){ // To store the required sum int sum = 0; // For every element of the array for (int i = 0; i < n; i++) { // It appears (2 * n) times sum = sum + (arr[i] * (2 * n)); } return sum;} // Driver codestatic public void Main(String []arg){ int []arr = { 1, 2, 3 }; int n = arr.Length; Console.WriteLine(sumPairs(arr, n));}} // This code contributed by Rajput-Ji <script> // Javascript implementation of the approach // Function to return the sum of the elements// of all possible pairs from the arrayfunction sumPairs(arr, n){ // To store the required sum let sum = 0; // For every element of the array for (let i = 0; i < n; i++) { // It appears (2 * n) times sum = sum + (arr[i] * (2 * n)); } return sum;} // Driver code let arr = [ 1, 2, 3 ]; let n = arr.length; document.write(sumPairs(arr, n)); </script> 36 Time Complexity: O(N) Auxiliary Space: O(1) mohit kumar 29 ankthon princiraj1992 29AjayKumar Rajput-Ji ipg2016107 rishavmahato348 subhamkumarm348 Arrays Mathematical Arrays Mathematical Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Multidimensional Arrays in Java Maximum and minimum of an array using minimum number of comparisons Python | Using 2D arrays/lists the right way Find the smallest positive integer value that cannot be represented as sum of any subset of a given array Find a triplet that sum to a given value Program for Fibonacci numbers C++ Data Types Set in C++ Standard Template Library (STL) Write a program to print all permutations of a given string Operators in C / C++
[ { "code": null, "e": 52, "s": 24, "text": "\n19 Mar, 2022" }, { "code": null, "e": 176, "s": 52, "text": "Given an array arr[] of N integers, the task is to find the sum of all the pairs possible from the given array. Note that, " }, { "code": null, "e": 305, "s": 176, "text": "(arr[i], arr[i]) is also considered as a valid pair.(arr[i], arr[j]) and (arr[j], arr[i]) are considered as two different pairs." }, { "code": null, "e": 358, "s": 305, "text": "(arr[i], arr[i]) is also considered as a valid pair." }, { "code": null, "e": 435, "s": 358, "text": "(arr[i], arr[j]) and (arr[j], arr[i]) are considered as two different pairs." }, { "code": null, "e": 446, "s": 435, "text": "Examples: " }, { "code": null, "e": 569, "s": 446, "text": "Input: arr[] = {1, 2} Output: 12 All valid pairs are (1, 1), (1, 2), (2, 1) and (2, 2). 1 + 1 + 1 + 2 + 2 + 1 + 2 + 2 = 12" }, { "code": null, "e": 614, "s": 569, "text": "Input: arr[] = {1, 2, 3, 1, 4} Output: 110 " }, { "code": null, "e": 710, "s": 614, "text": "Naive approach: Find all the possible pairs and calculate the sum of the elements of each pair." }, { "code": null, "e": 763, "s": 710, "text": "Below is the implementation of the above approach: " }, { "code": null, "e": 767, "s": 763, "text": "C++" }, { "code": null, "e": 772, "s": 767, "text": "Java" }, { "code": null, "e": 780, "s": 772, "text": "Python3" }, { "code": null, "e": 783, "s": 780, "text": "C#" }, { "code": null, "e": 794, "s": 783, "text": "Javascript" }, { "code": "// C++ implementation of the approach#include <bits/stdc++.h>using namespace std; // Function to return the sum of the elements// of all possible pairs from the arrayint sumPairs(int arr[], int n){ // To store the required sum int sum = 0; // Nested loop for all possible pairs for (int i = 0; i < n; i++) { for (int j = 0; j < n; j++) { // Add the sum of the elements // of the current pair sum += (arr[i] + arr[j]); } } return sum;} // Driver codeint main(){ int arr[] = { 1, 2, 3 }; int n = sizeof(arr) / sizeof(arr[0]); cout << sumPairs(arr, n); return 0;}", "e": 1437, "s": 794, "text": null }, { "code": "// Java implementation of the approachimport java.util.*; class GFG{ // Function to return the sum of the elements // of all possible pairs from the array static int sumPairs(int arr[], int n) { // To store the required sum int sum = 0; // Nested loop for all possible pairs for (int i = 0; i < n; i++) { for (int j = 0; j < n; j++) { // Add the sum of the elements // of the current pair sum += (arr[i] + arr[j]); } } return sum; } // Driver code public static void main(String[] args) { int arr[] = {1, 2, 3}; int n = arr.length; System.out.println(sumPairs(arr, n)); }} // This code is contributed by PrinciRaj1992", "e": 2236, "s": 1437, "text": null }, { "code": "# Python3 implementation of the approach # Function to return the summ of the elements# of all possible pairs from the arraydef summPairs(arr, n): # To store the required summ summ = 0 # Nested loop for all possible pairs for i in range(n): for j in range(n): # Add the summ of the elements # of the current pair summ += (arr[i] + arr[j]) return summ # Driver codearr = [1, 2, 3]n = len(arr) print(summPairs(arr, n)) # This code is contributed by Mohit Kumar", "e": 2754, "s": 2236, "text": null }, { "code": "// C# implementation of the approachusing System; class GFG{ // Function to return the sum of the elements // of all possible pairs from the array static int sumPairs(int []arr, int n) { // To store the required sum int sum = 0; // Nested loop for all possible pairs for (int i = 0; i < n; i++) { for (int j = 0; j < n; j++) { // Add the sum of the elements // of the current pair sum += (arr[i] + arr[j]); } } return sum; } // Driver code public static void Main(String[] args) { int []arr = {1, 2, 3}; int n = arr.Length; Console.WriteLine(sumPairs(arr, n)); }} // This code is contributed by PrinciRaj1992", "e": 3548, "s": 2754, "text": null }, { "code": "<script> // Javascript implementation of the approach // Function to return the sum of the elements// of all possible pairs from the arrayfunction sumPairs(arr, n){ // To store the required sum var sum = 0; var i, j; // Nested loop for all possible pairs for(i = 0; i < n; i++) { for(j = 0; j < n; j++) { // Add the sum of the elements // of the current pair sum += (arr[i] + arr[j]); } } return sum;} // Driver codevar arr = [ 1, 2, 3 ];var n = arr.length; document.write(sumPairs(arr, n)); // This code is contributed by ipg2016107 </script>", "e": 4193, "s": 3548, "text": null }, { "code": null, "e": 4196, "s": 4193, "text": "36" }, { "code": null, "e": 4221, "s": 4198, "text": "Time Complexity: O(N2)" }, { "code": null, "e": 4243, "s": 4221, "text": "Auxiliary Space: O(1)" }, { "code": null, "e": 4420, "s": 4243, "text": "Efficient approach: It can be observed that each element appears exactly (2 * N) times as one of the elements of the pair (x, y). Exactly N times as x and exactly N times as y." }, { "code": null, "e": 4473, "s": 4420, "text": "Below is the implementation of the above approach: " }, { "code": null, "e": 4477, "s": 4473, "text": "C++" }, { "code": null, "e": 4482, "s": 4477, "text": "Java" }, { "code": null, "e": 4490, "s": 4482, "text": "Python3" }, { "code": null, "e": 4493, "s": 4490, "text": "C#" }, { "code": null, "e": 4504, "s": 4493, "text": "Javascript" }, { "code": "// C++ implementation of the approach#include <bits/stdc++.h>using namespace std; // Function to return the sum of the elements// of all possible pairs from the arrayint sumPairs(int arr[], int n){ // To store the required sum int sum = 0; // For every element of the array for (int i = 0; i < n; i++) { // It appears (2 * n) times sum = sum + (arr[i] * (2 * n)); } return sum;} // Driver codeint main(){ int arr[] = { 1, 2, 3 }; int n = sizeof(arr) / sizeof(arr[0]); cout << sumPairs(arr, n); return 0;}", "e": 5059, "s": 4504, "text": null }, { "code": "// Java implementation of the approachimport java.util.*; class GFG{ // Function to return the sum of the elements// of all possible pairs from the arraystatic int sumPairs(int arr[], int n){ // To store the required sum int sum = 0; // For every element of the array for (int i = 0; i < n; i++) { // It appears (2 * n) times sum = sum + (arr[i] * (2 * n)); } return sum;} // Driver codestatic public void main(String []arg){ int arr[] = { 1, 2, 3 }; int n = arr.length; System.out.println(sumPairs(arr, n));}} // This code is contributed by 29AjayKumar", "e": 5666, "s": 5059, "text": null }, { "code": "# Python3 implementation of the approach # Function to return the sum of the elements# of all possible pairs from the arraydef sumPairs(arr, n) : # To store the required sum sum = 0; # For every element of the array for i in range(n) : # It appears (2 * n) times sum = sum + (arr[i] * (2 * n)); return sum; # Driver codeif __name__ == \"__main__\" : arr = [ 1, 2, 3 ]; n = len(arr); print(sumPairs(arr, n)); # This code is contributed by AnkitRai01", "e": 6157, "s": 5666, "text": null }, { "code": "// C# implementation of the approachusing System; class GFG{ // Function to return the sum of the elements// of all possible pairs from the arraystatic int sumPairs(int []arr, int n){ // To store the required sum int sum = 0; // For every element of the array for (int i = 0; i < n; i++) { // It appears (2 * n) times sum = sum + (arr[i] * (2 * n)); } return sum;} // Driver codestatic public void Main(String []arg){ int []arr = { 1, 2, 3 }; int n = arr.Length; Console.WriteLine(sumPairs(arr, n));}} // This code contributed by Rajput-Ji", "e": 6754, "s": 6157, "text": null }, { "code": "<script> // Javascript implementation of the approach // Function to return the sum of the elements// of all possible pairs from the arrayfunction sumPairs(arr, n){ // To store the required sum let sum = 0; // For every element of the array for (let i = 0; i < n; i++) { // It appears (2 * n) times sum = sum + (arr[i] * (2 * n)); } return sum;} // Driver code let arr = [ 1, 2, 3 ]; let n = arr.length; document.write(sumPairs(arr, n)); </script>", "e": 7248, "s": 6754, "text": null }, { "code": null, "e": 7251, "s": 7248, "text": "36" }, { "code": null, "e": 7297, "s": 7253, "text": "Time Complexity: O(N) Auxiliary Space: O(1)" }, { "code": null, "e": 7312, "s": 7297, "text": "mohit kumar 29" }, { "code": null, "e": 7320, "s": 7312, "text": "ankthon" }, { "code": null, "e": 7334, "s": 7320, "text": "princiraj1992" }, { "code": null, "e": 7346, "s": 7334, "text": "29AjayKumar" }, { "code": null, "e": 7356, "s": 7346, "text": "Rajput-Ji" }, { "code": null, "e": 7367, "s": 7356, "text": "ipg2016107" }, { "code": null, "e": 7383, "s": 7367, "text": "rishavmahato348" }, { "code": null, "e": 7399, "s": 7383, "text": "subhamkumarm348" }, { "code": null, "e": 7406, "s": 7399, "text": "Arrays" }, { "code": null, "e": 7419, "s": 7406, "text": "Mathematical" }, { "code": null, "e": 7426, "s": 7419, "text": "Arrays" }, { "code": null, "e": 7439, "s": 7426, "text": "Mathematical" }, { "code": null, "e": 7537, "s": 7439, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 7569, "s": 7537, "text": "Multidimensional Arrays in Java" }, { "code": null, "e": 7637, "s": 7569, "text": "Maximum and minimum of an array using minimum number of comparisons" }, { "code": null, "e": 7682, "s": 7637, "text": "Python | Using 2D arrays/lists the right way" }, { "code": null, "e": 7788, "s": 7682, "text": "Find the smallest positive integer value that cannot be represented as sum of any subset of a given array" }, { "code": null, "e": 7829, "s": 7788, "text": "Find a triplet that sum to a given value" }, { "code": null, "e": 7859, "s": 7829, "text": "Program for Fibonacci numbers" }, { "code": null, "e": 7874, "s": 7859, "text": "C++ Data Types" }, { "code": null, "e": 7917, "s": 7874, "text": "Set in C++ Standard Template Library (STL)" }, { "code": null, "e": 7977, "s": 7917, "text": "Write a program to print all permutations of a given string" } ]
Python | os.path.relpath() method
18 Jun, 2019 OS module in Python provides functions for interacting with the operating system. OS comes under Python’s standard utility modules. This module provides a portable way of using operating system dependent functionality. os.path module is sub module of OS module in Python used for common path name manipulation. os.path.relpath() method in Python is used to get a relative filepath to the given path either from the current working directory or from the given directory. Note: This method only computes the relative path. The existence of the given path or directory is not checked. Syntax: os.path.relpath(path, start = os.curdir) Parameter:path: A path-like object representing the file system path.start (optional): A path-like object representing the file system path.The relative path for given path will be computed with respect to the directory indicated by start. The default value of this parameter is os.curdir which is a constant string used by the operating system to refer to the current directory. A path-like object is either a string or bytes object representing a path. Return Type: This method returns a string value which represents the relative file path to given path from the start directory. Code : Use of os.path.relpath() method # Python program to explain os.path.relpath() method # importing os module import os # Pathpath = "/home / User / Desktop / file.txt" # Path of Start directorystart = "/home / User" # Compute the relative file path# to the given path from the # the given start directory.relative_path = os.path.relpath(path, start) # Print the relative file path# to the given path from the # the given start directory.print(relative_path) # Pathpath = "/home / User / Desktop / file.txt" # Compute the relative file path# to the given path from the # the current directory. # if we do not specify the start# parameter it will default to# os.curdir i.e current directory relative_path = os.path.relpath(path) # Print the relative file path# to the given path from the # the given start directory.print(relative_path) # Pathpath = "/home / User / Desktop / file.txt" # Path of Start directorystart = "GeeksForGeeks / home" # Compute the relative file path# to the given path from the # the given start directory.relative_path = os.path.relpath(path, start) # Print the relative file path# to the given path from the # the given start directory.print(relative_path) # Pathpath = "/home / User / Desktop / file.txt" # Path of Start directorystart = "/home / User / ihritik / file.txt" # Compute the relative file path# to the given path from the # the given start directory.relative_path = os.path.relpath(path, start) # Print the relative file path# to the given path from the # the given start directory.print(relative_path) Desktop/file.txt ../User/Desktop/file.txt ../../../User/Desktop/file.txt ../../Desktop/file.txt Reference: https://docs.python.org/3/library/os.path.html Python OS-path-module python-os-module 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 How to Install PIP on Windows ? Python String | replace() *args and **kwargs in Python Python Classes and Objects Python OOPs Concepts Iterate over a list in Python
[ { "code": null, "e": 53, "s": 25, "text": "\n18 Jun, 2019" }, { "code": null, "e": 364, "s": 53, "text": "OS module in Python provides functions for interacting with the operating system. OS comes under Python’s standard utility modules. This module provides a portable way of using operating system dependent functionality. os.path module is sub module of OS module in Python used for common path name manipulation." }, { "code": null, "e": 523, "s": 364, "text": "os.path.relpath() method in Python is used to get a relative filepath to the given path either from the current working directory or from the given directory." }, { "code": null, "e": 635, "s": 523, "text": "Note: This method only computes the relative path. The existence of the given path or directory is not checked." }, { "code": null, "e": 684, "s": 635, "text": "Syntax: os.path.relpath(path, start = os.curdir)" }, { "code": null, "e": 1064, "s": 684, "text": "Parameter:path: A path-like object representing the file system path.start (optional): A path-like object representing the file system path.The relative path for given path will be computed with respect to the directory indicated by start. The default value of this parameter is os.curdir which is a constant string used by the operating system to refer to the current directory." }, { "code": null, "e": 1139, "s": 1064, "text": "A path-like object is either a string or bytes object representing a path." }, { "code": null, "e": 1267, "s": 1139, "text": "Return Type: This method returns a string value which represents the relative file path to given path from the start directory." }, { "code": null, "e": 1306, "s": 1267, "text": "Code : Use of os.path.relpath() method" }, { "code": "# Python program to explain os.path.relpath() method # importing os module import os # Pathpath = \"/home / User / Desktop / file.txt\" # Path of Start directorystart = \"/home / User\" # Compute the relative file path# to the given path from the # the given start directory.relative_path = os.path.relpath(path, start) # Print the relative file path# to the given path from the # the given start directory.print(relative_path) # Pathpath = \"/home / User / Desktop / file.txt\" # Compute the relative file path# to the given path from the # the current directory. # if we do not specify the start# parameter it will default to# os.curdir i.e current directory relative_path = os.path.relpath(path) # Print the relative file path# to the given path from the # the given start directory.print(relative_path) # Pathpath = \"/home / User / Desktop / file.txt\" # Path of Start directorystart = \"GeeksForGeeks / home\" # Compute the relative file path# to the given path from the # the given start directory.relative_path = os.path.relpath(path, start) # Print the relative file path# to the given path from the # the given start directory.print(relative_path) # Pathpath = \"/home / User / Desktop / file.txt\" # Path of Start directorystart = \"/home / User / ihritik / file.txt\" # Compute the relative file path# to the given path from the # the given start directory.relative_path = os.path.relpath(path, start) # Print the relative file path# to the given path from the # the given start directory.print(relative_path)", "e": 2842, "s": 1306, "text": null }, { "code": null, "e": 2939, "s": 2842, "text": "Desktop/file.txt\n../User/Desktop/file.txt\n../../../User/Desktop/file.txt\n../../Desktop/file.txt\n" }, { "code": null, "e": 2997, "s": 2939, "text": "Reference: https://docs.python.org/3/library/os.path.html" }, { "code": null, "e": 3019, "s": 2997, "text": "Python OS-path-module" }, { "code": null, "e": 3036, "s": 3019, "text": "python-os-module" }, { "code": null, "e": 3043, "s": 3036, "text": "Python" }, { "code": null, "e": 3141, "s": 3043, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 3159, "s": 3141, "text": "Python Dictionary" }, { "code": null, "e": 3201, "s": 3159, "text": "Different ways to create Pandas Dataframe" }, { "code": null, "e": 3223, "s": 3201, "text": "Enumerate() in Python" }, { "code": null, "e": 3258, "s": 3223, "text": "Read a file line by line in Python" }, { "code": null, "e": 3290, "s": 3258, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 3316, "s": 3290, "text": "Python String | replace()" }, { "code": null, "e": 3345, "s": 3316, "text": "*args and **kwargs in Python" }, { "code": null, "e": 3372, "s": 3345, "text": "Python Classes and Objects" }, { "code": null, "e": 3393, "s": 3372, "text": "Python OOPs Concepts" } ]
HashMap keySet() Method in Java
26 Nov, 2018 The java.util.HashMap.keySet() method in Java is used to create a set out of the key elements contained in the hash map. It basically returns a set view of the keys or we can create a new set and store the key elements in them. Syntax: hash_map.keySet() Parameters: The method does not take any parameter. Return Value: The method returns a set having the keys of the hash map. Below programs are used to illustrate the working of java.util.HashMap.keySet() Method:Program 1: Mapping String Values to Integer Keys. // Java code to illustrate the keySet() methodimport java.util.*; public class Hash_Map_Demo { public static void main(String[] args) { // Creating an empty HashMap HashMap<Integer, String> hash_map = new HashMap<Integer, String>(); // Mapping string values to int keys hash_map.put(10, "Geeks"); hash_map.put(15, "4"); hash_map.put(20, "Geeks"); hash_map.put(25, "Welcomes"); hash_map.put(30, "You"); // Displaying the HashMap System.out.println("Initial Mappings are: " + hash_map); // Using keySet() to get the set view of keys System.out.println("The set is: " + hash_map.keySet()); }} Initial Mappings are: {20=Geeks, 25=Welcomes, 10=Geeks, 30=You, 15=4} The set is: [20, 25, 10, 30, 15] Program 2: Mapping Integer Values to String Keys. // Java code to illustrate the keySet() methodimport java.util.*; public class Hash_Map_Demo { public static void main(String[] args) { // Creating an empty HashMap HashMap<String, Integer> hash_map = new HashMap<String, Integer>(); // Mapping int values to string keys hash_map.put("Geeks", 10); hash_map.put("4", 15); hash_map.put("Geeks", 20); hash_map.put("Welcomes", 25); hash_map.put("You", 30); // Displaying the HashMap System.out.println("Initial Mappings are: " + hash_map); // Using keySet() to get the set view of keys System.out.println("The set is: " + hash_map.keySet()); }} Initial Mappings are: {4=15, Geeks=20, You=30, Welcomes=25} The set is: [4, Geeks, You, Welcomes] Note: The same operation can be performed with any type of Mappings with variation and combination of different data types. Java - util package Java-Collections Java-Functions Java-HashMap Java Java Java-Collections Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Queue Interface In Java Object Oriented Programming (OOPs) Concept in Java Stack Class in Java Interfaces in Java ArrayList in Java Collections in Java ChronoZonedDateTime isAfter() method in Java with Examples Multidimensional Arrays in Java Introduction to Java PriorityQueue in Java
[ { "code": null, "e": 53, "s": 25, "text": "\n26 Nov, 2018" }, { "code": null, "e": 281, "s": 53, "text": "The java.util.HashMap.keySet() method in Java is used to create a set out of the key elements contained in the hash map. It basically returns a set view of the keys or we can create a new set and store the key elements in them." }, { "code": null, "e": 289, "s": 281, "text": "Syntax:" }, { "code": null, "e": 307, "s": 289, "text": "hash_map.keySet()" }, { "code": null, "e": 359, "s": 307, "text": "Parameters: The method does not take any parameter." }, { "code": null, "e": 431, "s": 359, "text": "Return Value: The method returns a set having the keys of the hash map." }, { "code": null, "e": 568, "s": 431, "text": "Below programs are used to illustrate the working of java.util.HashMap.keySet() Method:Program 1: Mapping String Values to Integer Keys." }, { "code": "// Java code to illustrate the keySet() methodimport java.util.*; public class Hash_Map_Demo { public static void main(String[] args) { // Creating an empty HashMap HashMap<Integer, String> hash_map = new HashMap<Integer, String>(); // Mapping string values to int keys hash_map.put(10, \"Geeks\"); hash_map.put(15, \"4\"); hash_map.put(20, \"Geeks\"); hash_map.put(25, \"Welcomes\"); hash_map.put(30, \"You\"); // Displaying the HashMap System.out.println(\"Initial Mappings are: \" + hash_map); // Using keySet() to get the set view of keys System.out.println(\"The set is: \" + hash_map.keySet()); }}", "e": 1260, "s": 568, "text": null }, { "code": null, "e": 1364, "s": 1260, "text": "Initial Mappings are: {20=Geeks, 25=Welcomes, 10=Geeks, 30=You, 15=4}\nThe set is: [20, 25, 10, 30, 15]\n" }, { "code": null, "e": 1414, "s": 1364, "text": "Program 2: Mapping Integer Values to String Keys." }, { "code": "// Java code to illustrate the keySet() methodimport java.util.*; public class Hash_Map_Demo { public static void main(String[] args) { // Creating an empty HashMap HashMap<String, Integer> hash_map = new HashMap<String, Integer>(); // Mapping int values to string keys hash_map.put(\"Geeks\", 10); hash_map.put(\"4\", 15); hash_map.put(\"Geeks\", 20); hash_map.put(\"Welcomes\", 25); hash_map.put(\"You\", 30); // Displaying the HashMap System.out.println(\"Initial Mappings are: \" + hash_map); // Using keySet() to get the set view of keys System.out.println(\"The set is: \" + hash_map.keySet()); }}", "e": 2106, "s": 1414, "text": null }, { "code": null, "e": 2205, "s": 2106, "text": "Initial Mappings are: {4=15, Geeks=20, You=30, Welcomes=25}\nThe set is: [4, Geeks, You, Welcomes]\n" }, { "code": null, "e": 2329, "s": 2205, "text": "Note: The same operation can be performed with any type of Mappings with variation and combination of different data types." }, { "code": null, "e": 2349, "s": 2329, "text": "Java - util package" }, { "code": null, "e": 2366, "s": 2349, "text": "Java-Collections" }, { "code": null, "e": 2381, "s": 2366, "text": "Java-Functions" }, { "code": null, "e": 2394, "s": 2381, "text": "Java-HashMap" }, { "code": null, "e": 2399, "s": 2394, "text": "Java" }, { "code": null, "e": 2404, "s": 2399, "text": "Java" }, { "code": null, "e": 2421, "s": 2404, "text": "Java-Collections" }, { "code": null, "e": 2519, "s": 2421, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 2543, "s": 2519, "text": "Queue Interface In Java" }, { "code": null, "e": 2594, "s": 2543, "text": "Object Oriented Programming (OOPs) Concept in Java" }, { "code": null, "e": 2614, "s": 2594, "text": "Stack Class in Java" }, { "code": null, "e": 2633, "s": 2614, "text": "Interfaces in Java" }, { "code": null, "e": 2651, "s": 2633, "text": "ArrayList in Java" }, { "code": null, "e": 2671, "s": 2651, "text": "Collections in Java" }, { "code": null, "e": 2730, "s": 2671, "text": "ChronoZonedDateTime isAfter() method in Java with Examples" }, { "code": null, "e": 2762, "s": 2730, "text": "Multidimensional Arrays in Java" }, { "code": null, "e": 2783, "s": 2762, "text": "Introduction to Java" } ]
Count of repeating digits in a given Number
23 Apr, 2021 Given a number N, the task is to count the total number of repeating digits in the given number. Examples: Input: N = 99677 Output: 2Explanation:In the given number only 9 and 7 are repeating, hence the answer is 2. Input: N = 12Output: 0Explanation:In the given number no digits are repeating, hence the answer is 0. Naive Approach: The idea is to use two nested loops. In the first loop, traverse from the first digit of the number to the last, one by one. Then for each digit in the first loop, run a second loop and search if this digit is present anywhere else as well in the number. If yes, then increase the required count by 1. In the end, print the calculated count. Time Complexity: O(N2)Auxiliary Space: O(1) Efficient Approach: The idea is to use Hashing to store the frequency of the digits and then count the digits with a frequency equal to more than 1. Follow the steps below to solve the problem: Create an array of size 10 to store the count of digits 0 – 9. Initially store each index as 0. Now for each digit of number N, increment the count of that index in the array. Traverse the array and count the indices that have value more than 1. In the end, print this count. Below is the implementation of the above approach: C++ Java Python3 C# Javascript // C++ program for the above approach#include <bits/stdc++.h>using namespace std; // Function that returns the count of// repeating digits of the given numberint countRepeatingDigits(int N){ // Initialize a variable to store // count of Repeating digits int res = 0; // Initialize cnt array to // store digit count int cnt[10] = { 0 }; // Iterate through the digits of N while (N > 0) { // Retrieve the last digit of N int rem = N % 10; // Increase the count of digit cnt[rem]++; // Remove the last digit of N N = N / 10; } // Iterate through the cnt array for (int i = 0; i < 10; i++) { // If frequency of digit // is greater than 1 if (cnt[i] > 1) { // Increment the count // of Repeating digits res++; } } // Return count of repeating digit return res;} // Driver Codeint main(){ // Given array arr[] int N = 12; // Function Call cout << countRepeatingDigits(N); return 0;} // Java program for the above approachclass GFG{ // Function that returns the count of// repeating digits of the given numberstatic int countRepeatingDigits(int N){ // Initialize a variable to store // count of Repeating digits int res = 0; // Initialize cnt array to // store digit count int cnt[] = new int[10]; // Iterate through the digits of N while (N > 0) { // Retrieve the last digit of N int rem = N % 10; // Increase the count of digit cnt[rem]++; // Remove the last digit of N N = N / 10; } // Iterate through the cnt array for (int i = 0; i < 10; i++) { // If frequency of digit // is greater than 1 if (cnt[i] > 1) { // Increment the count // of Repeating digits res++; } } // Return count of repeating digit return res;} // Driver Codepublic static void main(String[] args){ // Given array arr[] int N = 12; // Function Call System.out.println(countRepeatingDigits(N));}} // This code is contributed by Ritik Bansal # Python3 program for the above approach # Function that returns the count of# repeating digits of the given numberdef countRepeatingDigits(N): # Initialize a variable to store # count of Repeating digits res = 0 # Initialize cnt array to # store digit count cnt = [0] * 10 # Iterate through the digits of N while (N > 0): # Retrieve the last digit of N rem = N % 10 # Increase the count of digit cnt[rem] += 1 # Remove the last digit of N N = N // 10 # Iterate through the cnt array for i in range(10): # If frequency of digit # is greater than 1 if (cnt[i] > 1): # Increment the count # of Repeating digits res += 1 # Return count of repeating digit return res # Driver Code # Given array arr[]N = 12 # Function callprint(countRepeatingDigits(N)) # This code is contributed by sanjoy_62 // C# program for the above approachusing System;class GFG{ // Function that returns the count of// repeating digits of the given numberstatic int countRepeatingDigits(int N){ // Initialize a variable to store // count of Repeating digits int res = 0; // Initialize cnt array to // store digit count int []cnt = new int[10]; // Iterate through the digits of N while (N > 0) { // Retrieve the last digit of N int rem = N % 10; // Increase the count of digit cnt[rem]++; // Remove the last digit of N N = N / 10; } // Iterate through the cnt array for (int i = 0; i < 10; i++) { // If frequency of digit // is greater than 1 if (cnt[i] > 1) { // Increment the count // of Repeating digits res++; } } // Return count of repeating digit return res;} // Driver Codepublic static void Main(String[] args){ // Given array []arr int N = 12; // Function Call Console.WriteLine(countRepeatingDigits(N));}} // This code is contributed by Rajput-Ji <script> // Javascript program for the above approach // Function that returns the count of// repeating digits of the given numberfunction countRepeatingDigits(N){ // Initialize a variable to store // count of Repeating digits var res = 0; // Initialize cnt array to // store digit count var cnt = Array(10).fill(0); // Iterate through the digits of N while (N > 0) { // Retrieve the last digit of N var rem = N % 10; // Increase the count of digit cnt[rem]++; // Remove the last digit of N N = N / 10; } // Iterate through the cnt array for (var i = 0; i < 10; i++) { // If frequency of digit // is greater than 1 if (cnt[i] > 1) { // Increment the count // of Repeating digits res++; } } // Return count of repeating digit return res;} // Driver Code// Given array arr[]var N = 12; // Function Calldocument.write( countRepeatingDigits(N)); // This code is contributed by rrrtnx.</script> 0 Time Complexity: O(N)Auxiliary Space: O(1) Convert integer to string. Use the Counter function to count the frequency of characters. If the frequency is greater than 1 increment the count Below is the implementation: Python3 # Python3 program for the above approachfrom collections import Counter # Function that returns the count of# repeating digits of the given numberdef countRepeatingDigits(N): # converting integer to string number = str(N) # initializing count = 0 count = 0 frequency = Counter(number) # Traversing frequency for i in frequency: if(frequency[i] > 1): # increase the count count = count+1 return count # Driver Code # Given array arr[]N = 1232145 # Function callprint(countRepeatingDigits(N)) # This code is contributed by vikkycirus 2 bansal_rtk_ Rajput-Ji sanjoy_62 vikkycirus rrrtnx number-digits Mathematical School Programming 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++ Prime Numbers Minimum number of jumps to reach end Find minimum number of coins that make a given value Python Dictionary Reverse a string in Java Arrays in C/C++ Introduction To PYTHON Interfaces in Java
[ { "code": null, "e": 28, "s": 0, "text": "\n23 Apr, 2021" }, { "code": null, "e": 125, "s": 28, "text": "Given a number N, the task is to count the total number of repeating digits in the given number." }, { "code": null, "e": 135, "s": 125, "text": "Examples:" }, { "code": null, "e": 245, "s": 135, "text": "Input: N = 99677 Output: 2Explanation:In the given number only 9 and 7 are repeating, hence the answer is 2." }, { "code": null, "e": 347, "s": 245, "text": "Input: N = 12Output: 0Explanation:In the given number no digits are repeating, hence the answer is 0." }, { "code": null, "e": 705, "s": 347, "text": "Naive Approach: The idea is to use two nested loops. In the first loop, traverse from the first digit of the number to the last, one by one. Then for each digit in the first loop, run a second loop and search if this digit is present anywhere else as well in the number. If yes, then increase the required count by 1. In the end, print the calculated count." }, { "code": null, "e": 749, "s": 705, "text": "Time Complexity: O(N2)Auxiliary Space: O(1)" }, { "code": null, "e": 943, "s": 749, "text": "Efficient Approach: The idea is to use Hashing to store the frequency of the digits and then count the digits with a frequency equal to more than 1. Follow the steps below to solve the problem:" }, { "code": null, "e": 1039, "s": 943, "text": "Create an array of size 10 to store the count of digits 0 – 9. Initially store each index as 0." }, { "code": null, "e": 1119, "s": 1039, "text": "Now for each digit of number N, increment the count of that index in the array." }, { "code": null, "e": 1189, "s": 1119, "text": "Traverse the array and count the indices that have value more than 1." }, { "code": null, "e": 1219, "s": 1189, "text": "In the end, print this count." }, { "code": null, "e": 1270, "s": 1219, "text": "Below is the implementation of the above approach:" }, { "code": null, "e": 1274, "s": 1270, "text": "C++" }, { "code": null, "e": 1279, "s": 1274, "text": "Java" }, { "code": null, "e": 1287, "s": 1279, "text": "Python3" }, { "code": null, "e": 1290, "s": 1287, "text": "C#" }, { "code": null, "e": 1301, "s": 1290, "text": "Javascript" }, { "code": "// C++ program for the above approach#include <bits/stdc++.h>using namespace std; // Function that returns the count of// repeating digits of the given numberint countRepeatingDigits(int N){ // Initialize a variable to store // count of Repeating digits int res = 0; // Initialize cnt array to // store digit count int cnt[10] = { 0 }; // Iterate through the digits of N while (N > 0) { // Retrieve the last digit of N int rem = N % 10; // Increase the count of digit cnt[rem]++; // Remove the last digit of N N = N / 10; } // Iterate through the cnt array for (int i = 0; i < 10; i++) { // If frequency of digit // is greater than 1 if (cnt[i] > 1) { // Increment the count // of Repeating digits res++; } } // Return count of repeating digit return res;} // Driver Codeint main(){ // Given array arr[] int N = 12; // Function Call cout << countRepeatingDigits(N); return 0;}", "e": 2349, "s": 1301, "text": null }, { "code": "// Java program for the above approachclass GFG{ // Function that returns the count of// repeating digits of the given numberstatic int countRepeatingDigits(int N){ // Initialize a variable to store // count of Repeating digits int res = 0; // Initialize cnt array to // store digit count int cnt[] = new int[10]; // Iterate through the digits of N while (N > 0) { // Retrieve the last digit of N int rem = N % 10; // Increase the count of digit cnt[rem]++; // Remove the last digit of N N = N / 10; } // Iterate through the cnt array for (int i = 0; i < 10; i++) { // If frequency of digit // is greater than 1 if (cnt[i] > 1) { // Increment the count // of Repeating digits res++; } } // Return count of repeating digit return res;} // Driver Codepublic static void main(String[] args){ // Given array arr[] int N = 12; // Function Call System.out.println(countRepeatingDigits(N));}} // This code is contributed by Ritik Bansal", "e": 3474, "s": 2349, "text": null }, { "code": "# Python3 program for the above approach # Function that returns the count of# repeating digits of the given numberdef countRepeatingDigits(N): # Initialize a variable to store # count of Repeating digits res = 0 # Initialize cnt array to # store digit count cnt = [0] * 10 # Iterate through the digits of N while (N > 0): # Retrieve the last digit of N rem = N % 10 # Increase the count of digit cnt[rem] += 1 # Remove the last digit of N N = N // 10 # Iterate through the cnt array for i in range(10): # If frequency of digit # is greater than 1 if (cnt[i] > 1): # Increment the count # of Repeating digits res += 1 # Return count of repeating digit return res # Driver Code # Given array arr[]N = 12 # Function callprint(countRepeatingDigits(N)) # This code is contributed by sanjoy_62", "e": 4421, "s": 3474, "text": null }, { "code": "// C# program for the above approachusing System;class GFG{ // Function that returns the count of// repeating digits of the given numberstatic int countRepeatingDigits(int N){ // Initialize a variable to store // count of Repeating digits int res = 0; // Initialize cnt array to // store digit count int []cnt = new int[10]; // Iterate through the digits of N while (N > 0) { // Retrieve the last digit of N int rem = N % 10; // Increase the count of digit cnt[rem]++; // Remove the last digit of N N = N / 10; } // Iterate through the cnt array for (int i = 0; i < 10; i++) { // If frequency of digit // is greater than 1 if (cnt[i] > 1) { // Increment the count // of Repeating digits res++; } } // Return count of repeating digit return res;} // Driver Codepublic static void Main(String[] args){ // Given array []arr int N = 12; // Function Call Console.WriteLine(countRepeatingDigits(N));}} // This code is contributed by Rajput-Ji", "e": 5538, "s": 4421, "text": null }, { "code": "<script> // Javascript program for the above approach // Function that returns the count of// repeating digits of the given numberfunction countRepeatingDigits(N){ // Initialize a variable to store // count of Repeating digits var res = 0; // Initialize cnt array to // store digit count var cnt = Array(10).fill(0); // Iterate through the digits of N while (N > 0) { // Retrieve the last digit of N var rem = N % 10; // Increase the count of digit cnt[rem]++; // Remove the last digit of N N = N / 10; } // Iterate through the cnt array for (var i = 0; i < 10; i++) { // If frequency of digit // is greater than 1 if (cnt[i] > 1) { // Increment the count // of Repeating digits res++; } } // Return count of repeating digit return res;} // Driver Code// Given array arr[]var N = 12; // Function Calldocument.write( countRepeatingDigits(N)); // This code is contributed by rrrtnx.</script>", "e": 6584, "s": 5538, "text": null }, { "code": null, "e": 6586, "s": 6584, "text": "0" }, { "code": null, "e": 6629, "s": 6586, "text": "Time Complexity: O(N)Auxiliary Space: O(1)" }, { "code": null, "e": 6656, "s": 6629, "text": "Convert integer to string." }, { "code": null, "e": 6719, "s": 6656, "text": "Use the Counter function to count the frequency of characters." }, { "code": null, "e": 6774, "s": 6719, "text": "If the frequency is greater than 1 increment the count" }, { "code": null, "e": 6803, "s": 6774, "text": "Below is the implementation:" }, { "code": null, "e": 6811, "s": 6803, "text": "Python3" }, { "code": "# Python3 program for the above approachfrom collections import Counter # Function that returns the count of# repeating digits of the given numberdef countRepeatingDigits(N): # converting integer to string number = str(N) # initializing count = 0 count = 0 frequency = Counter(number) # Traversing frequency for i in frequency: if(frequency[i] > 1): # increase the count count = count+1 return count # Driver Code # Given array arr[]N = 1232145 # Function callprint(countRepeatingDigits(N)) # This code is contributed by vikkycirus", "e": 7421, "s": 6811, "text": null }, { "code": null, "e": 7423, "s": 7421, "text": "2" }, { "code": null, "e": 7435, "s": 7423, "text": "bansal_rtk_" }, { "code": null, "e": 7445, "s": 7435, "text": "Rajput-Ji" }, { "code": null, "e": 7455, "s": 7445, "text": "sanjoy_62" }, { "code": null, "e": 7466, "s": 7455, "text": "vikkycirus" }, { "code": null, "e": 7473, "s": 7466, "text": "rrrtnx" }, { "code": null, "e": 7487, "s": 7473, "text": "number-digits" }, { "code": null, "e": 7500, "s": 7487, "text": "Mathematical" }, { "code": null, "e": 7519, "s": 7500, "text": "School Programming" }, { "code": null, "e": 7532, "s": 7519, "text": "Mathematical" }, { "code": null, "e": 7630, "s": 7532, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 7654, "s": 7630, "text": "Merge two sorted arrays" }, { "code": null, "e": 7675, "s": 7654, "text": "Operators in C / C++" }, { "code": null, "e": 7689, "s": 7675, "text": "Prime Numbers" }, { "code": null, "e": 7726, "s": 7689, "text": "Minimum number of jumps to reach end" }, { "code": null, "e": 7779, "s": 7726, "text": "Find minimum number of coins that make a given value" }, { "code": null, "e": 7797, "s": 7779, "text": "Python Dictionary" }, { "code": null, "e": 7822, "s": 7797, "text": "Reverse a string in Java" }, { "code": null, "e": 7838, "s": 7822, "text": "Arrays in C/C++" }, { "code": null, "e": 7861, "s": 7838, "text": "Introduction To PYTHON" } ]
Sort a k sorted doubly linked list
03 Jul, 2022 Given a doubly linked list containing n nodes, where each node is at most k away from its target position in the list. The problem is to sort the given doubly linked list. For example, let us consider k is 2, a node at position 7 in the sorted doubly linked list, can be at positions 5, 6, 7, 8, 9 in the given doubly linked list.Examples: Naive Approach: Sort the given doubly linked list using the insertion sort technique. While inserting each element in the sorted part of the list, there will be at most k swaps to place the element to its correct position since it is at most k steps away from its correct position. C++ Java Python3 Javascript // C++ implementation to sort a k sorted doubly// linked list#include<bits/stdc++.h>using namespace std; // a node of the doubly linked liststruct Node { int data; struct Node* next; struct Node* prev;}; // function to sort a k sorted doubly linked liststruct Node* sortAKSortedDLL(struct Node* head, int k){ if(head == NULL || head->next == NULL) return head; // perform on all the nodes in list for(Node *i = head->next; i != NULL; i = i->next) { Node *j = i; // There will be atmost k swaps for each element in the list // since each node is k steps away from its correct position while(j->prev != NULL && j->data < j->prev->data) { // swap j and j.prev node Node* temp = j->prev->prev; Node* temp2 = j->prev; Node *temp3 = j->next; j->prev->next = temp3; j->prev->prev = j; j->prev = temp; j->next = temp2; if(temp != NULL) temp->next = j; if(temp3 != NULL) temp3->prev = temp2; } // if j is now the new head // then reset head if(j->prev == NULL) head = j; } return head;} // Function to insert a node at the beginning// of the Doubly Linked Listvoid push(struct Node** head_ref, int new_data){ // allocate node struct Node* new_node = (struct Node*)malloc(sizeof(struct Node)); // put in the data new_node->data = new_data; // since we are adding at the beginning, // prev is always NULL new_node->prev = NULL; // link the old list off the new node new_node->next = (*head_ref); // change prev of head node to new node if ((*head_ref) != NULL) (*head_ref)->prev = new_node; // move the head to point to the new node (*head_ref) = new_node;} // Function to print nodes in a given doubly linked listvoid printList(struct Node* head){ // if list is empty if (head == NULL) cout << "Doubly Linked list empty"; while (head != NULL) { cout << head->data << " "; head = head->next; }} // Driver program to test aboveint main(){ struct Node* head = NULL; // Create the doubly linked list: // 3<->6<->2<->12<->56<->8 push(&head, 8); push(&head, 56); push(&head, 12); push(&head, 2); push(&head, 6); push(&head, 3); int k = 2; cout << "Original Doubly linked list:\n"; printList(head); // sort the biotonic DLL head = sortAKSortedDLL(head, k); cout << "\nDoubly linked list after sorting:\n"; printList(head); return 0;} // This code is contributed by sachinejain74754. // Java implementation to sort a k sorted doublyimport java.util.*;class DoublyLinkedList{static Node head;static class Node{ int data; Node next, prev; Node(int d) { data = d; next = prev = null; }} // function to sort a k sorted doubly linked list// Using Insertion Sort// Time Complexity: O(n*k)// Space Complexity: O(1)Node sortAKSortedDLL( Node head, int k) { if(head == null || head.next == null) return head; // perform on all the nodes in list for(Node i = head.next; i != null; i = i.next) { Node j = i; // There will be atmost k swaps for each element in the list // since each node is k steps away from its correct position while(j.prev != null && j.data < j.prev.data) { // swap j and j.prev node Node temp = j.prev.prev; Node temp2 = j.prev; Node temp3 = j.next; j.prev.next = temp3; j.prev.prev = j; j.prev = temp; j.next = temp2; if(temp != null) temp.next = j; if(temp3 != null) temp3.prev = temp2; } // if j is now the new head // then reset head if(j.prev == null) head = j; } return head;} /* UTILITY FUNCTIONS *//* Function to insert a node at the beginning of the * Doubly Linked List */void push(int new_data){ /* allocate node */ Node new_node = new Node(new_data); /* since we are adding at the beginning, prev is always NULL */ new_node.prev = null; /* link the old list off the new node */ new_node.next = head; /* change prev of head node to new node */ if (head != null) { head.prev = new_node; } /* move the head to point to the new node */ head = new_node;} /* Function to print nodes in a given doubly linked list This function is same as printList() of singly linked list */void printList(Node node){ while (node != null) { System.out.print(node.data + " "); node = node.next; }} // Driver codepublic static void main(String[] args){ DoublyLinkedList list = new DoublyLinkedList(); /* Let us create a k sorted doubly linked list to test the functions Created doubly linked list will be 3<->6<->2<->12<->56<->8 */ list.push(8); list.push(56); list.push(12); list.push(2); list.push(6); list.push(3); int k = 2; System.out.println("Original Doubly linked list:"); list.printList(head); Node sortedDLL = list.sortAKSortedDLL(head, k); System.out.println(""); System.out.println("Doubly Linked List after sorting:"); list.printList(sortedDLL);}} // This code is contributed by Mittul Mandhan(@mittulmandhan) # Python implementation to sort a k sorted doublyclass DoublyLinkedList {head = None class Node: def __init__(self, val): self.data = val self.prev = None self.next = None # function to sort a k sorted doubly linked list# Using Insertion Sort# Time Complexity: O(n*k)# Space Complexity: O(1)def sortAKSortedDLL(head , k): if (head == None or head.next == None): return head # perform on all the nodes in list i = head.next while(i != None): j = i # There will be atmost k swaps for each element in the list # since each node is k steps away from its correct position while (j.prev != None and j.data < j.prev.data): # swap j and j.prev node temp = j.prev.prev temp2 = j.prev temp3 = j.next j.prev.next = temp3 j.prev.prev = j j.prev = temp j.next = temp2 if (temp != None): temp.next = j if (temp3 != None): temp3.prev = temp2 # if j is now the new head # then reset head if (j.prev == None): head = j i = i.next return head # UTILITY FUNCTIONS ## Function to insert a node at the beginning of the Doubly Linked Listdef push(new_data): global head # allocate node new_node = Node(new_data) # # since we are adding at the beginning, prev is always NULL # new_node.prev = None # link the old list off the new node new_node.next = head # change prev of head node to new node if (head != None): head.prev = new_node # move the head to point to the new node head = new_node # Function to print nodes in a given doubly linked list This function is same# as printList() of singly linked listdef printList(node): while (node != None): print(node.data,end = " ") node = node.next # Driver code # Let us create a k sorted doubly linked list to test the functions Created# doubly linked list will be 3<->6<->2<->12<->56<->8push(8)push(56)push(12)push(2)push(6)push(3) k = 2 print("Original Doubly linked list:")printList(head) sortedDLL = sortAKSortedDLL(head, k)print("")print("Doubly Linked List after sorting:")printList(sortedDLL) # This codeis contributed by shinjanpatra <script>// javascript implementation to sort a k sorted doublyclass DoublyLinkedList { var head; class Node { constructor(val) { this.data = val; this.prev = null; this.next = null; } } // function to sort a k sorted doubly linked list // Using Insertion Sort // Time Complexity: O(n*k) // Space Complexity: O(1) function sortAKSortedDLL(head , k) { if (head == null || head.next == null) return head; // perform on all the nodes in list for (i = head.next; i != null; i = i.next) { var j = i; // There will be atmost k swaps for each element in the list // since each node is k steps away from its correct position while (j.prev != null && j.data < j.prev.data) { // swap j and j.prev node var temp = j.prev.prev; var temp2 = j.prev; var temp3 = j.next; j.prev.next = temp3; j.prev.prev = j; j.prev = temp; j.next = temp2; if (temp != null) temp.next = j; if (temp3 != null) temp3.prev = temp2; } // if j is now the new head // then reset head if (j.prev == null) head = j; } return head; } /* UTILITY FUNCTIONS */ /* * Function to insert a node at the beginning of the Doubly Linked List */ function push(new_data) { /* allocate node */var new_node = new Node(new_data); /* * since we are adding at the beginning, prev is always NULL */ new_node.prev = null; /* link the old list off the new node */ new_node.next = head; /* change prev of head node to new node */ if (head != null) { head.prev = new_node; } /* move the head to point to the new node */ head = new_node; } /* * Function to print nodes in a given doubly linked list This function is same * as printList() of singly linked list */ function printList(node) { while (node != null) { document.write(node.data + " "); node = node.next; } } // Driver code /* * Let us create a k sorted doubly linked list to test the functions Created * doubly linked list will be 3<->6<->2<->12<->56<->8 */ push(8); push(56); push(12); push(2); push(6); push(3); var k = 2; document.write("Original Doubly linked list:<br/>"); printList(head); var sortedDLL = sortAKSortedDLL(head, k); document.write(""); document.write("<br/>Doubly Linked List after sorting:<br/>"); printList(sortedDLL); // This code contributed by aashish1995</script> Original Doubly linked list: 3 6 2 12 56 8 Doubly Linked List after sorting: 2 3 6 8 12 56 Time Complexity: O(n*k) Auxiliary Space: O(1) Efficient Approach: We can sort the list using the MIN HEAP data structure. The approach has been explained in Sort a nearly sorted (or K sorted) array. We only have to be careful while traversing the input doubly linked list and adjusting the required next and previous links in the final sorted list. CPP Java // C++ implementation to sort a k sorted doubly// linked list#include <bits/stdc++.h>using namespace std; // a node of the doubly linked liststruct Node { int data; struct Node* next; struct Node* prev;}; // 'compare' function used to build up the// priority queuestruct compare { bool operator()(struct Node* p1, struct Node* p2) { return p1->data > p2->data; }}; // function to sort a k sorted doubly linked liststruct Node* sortAKSortedDLL(struct Node* head, int k){ // if list is empty if (head == NULL) return head; // priority_queue 'pq' implemented as min heap with the // help of 'compare' function priority_queue<Node*, vector<Node*>, compare> pq; struct Node* newHead = NULL, *last; // Create a Min Heap of first (k+1) elements from // input doubly linked list for (int i = 0; head != NULL && i <= k; i++) { // push the node on to 'pq' pq.push(head); // move to the next node head = head->next; } // loop till there are elements in 'pq' while (!pq.empty()) { // place root or top of 'pq' at the end of the // result sorted list so far having the first node // pointed to by 'newHead' // and adjust the required links if (newHead == NULL) { newHead = pq.top(); newHead->prev = NULL; // 'last' points to the last node // of the result sorted list so far last = newHead; } else { last->next = pq.top(); pq.top()->prev = last; last = pq.top(); } // remove element from 'pq' pq.pop(); // if there are more nodes left in the input list if (head != NULL) { // push the node on to 'pq' pq.push(head); // move to the next node head = head->next; } } // making 'next' of last node point to NULL last->next = NULL; // new head of the required sorted DLL return newHead;} // Function to insert a node at the beginning// of the Doubly Linked Listvoid push(struct Node** head_ref, int new_data){ // allocate node struct Node* new_node = (struct Node*)malloc(sizeof(struct Node)); // put in the data new_node->data = new_data; // since we are adding at the beginning, // prev is always NULL new_node->prev = NULL; // link the old list off the new node new_node->next = (*head_ref); // change prev of head node to new node if ((*head_ref) != NULL) (*head_ref)->prev = new_node; // move the head to point to the new node (*head_ref) = new_node;} // Function to print nodes in a given doubly linked listvoid printList(struct Node* head){ // if list is empty if (head == NULL) cout << "Doubly Linked list empty"; while (head != NULL) { cout << head->data << " "; head = head->next; }} // Driver program to test aboveint main(){ struct Node* head = NULL; // Create the doubly linked list: // 3<->6<->2<->12<->56<->8 push(&head, 8); push(&head, 56); push(&head, 12); push(&head, 2); push(&head, 6); push(&head, 3); int k = 2; cout << "Original Doubly linked list:\n"; printList(head); // sort the biotonic DLL head = sortAKSortedDLL(head, k); cout << "\nDoubly linked list after sorting:\n"; printList(head); return 0;} // Java implementation to sort a k sorted doubly import java.util.*;class DoublyLinkedList{ static Node head; static class Node { int data; Node next, prev; Node(int d) { data = d; next = prev = null; } } class compareNode implements Comparator<Node> { public int compare(Node n1, Node n2){ return n1.data-n2.data; } } // function to sort a k sorted doubly linked list Node sortAKSortedDLL( Node head, int k) { // if list is empty if (head == null) return head; // priority_queue 'pq' implemented as min heap with the // help of 'compare' function in compare Node class PriorityQueue<Node> pq = new PriorityQueue<Node>(new compareNode()); Node newHead = null, last = null; // Create a Min Heap of first (k+1) elements from // input doubly linked list for (int i = 0; head != null && i <= k; i++) { // push the node on to 'pq' pq.add(head); // move to the next node head = head.next; } // loop till there are elements in 'pq' while (!pq.isEmpty()) { // place root or top of 'pq' at the end of the // result sorted list so far having the first node // pointed to by 'newHead' // and adjust the required links if (newHead == null) { newHead = pq.peek(); newHead.prev = null; // 'last' points to the last node // of the result sorted list so far last = newHead; } else { last.next = pq.peek(); pq.peek().prev = last; last = pq.peek(); } // remove element from 'pq' pq.poll(); // if there are more nodes left in the input list if (head != null) { // push the node on to 'pq' pq.add(head); // move to the next node head = head.next; } } // making 'next' of last node point to NULL last.next = null; // new head of the required sorted DLL return newHead; } /* UTILITY FUNCTIONS */ /* Function to insert a node at the beginning of the * Doubly Linked List */ void push(int new_data) { /* allocate node */ Node new_node = new Node(new_data); /* since we are adding at the beginning, prev is always NULL */ new_node.prev = null; /* link the old list off the new node */ new_node.next = head; /* change prev of head node to new node */ if (head != null) { head.prev = new_node; } /* move the head to point to the new node */ head = new_node; } /* Function to print nodes in a given doubly linked list This function is same as printList() of singly linked list */ void printList(Node node) { while (node != null) { System.out.print(node.data + " "); node = node.next; } } // Driver code public static void main(String[] args) { DoublyLinkedList list = new DoublyLinkedList(); /* Let us create a k sorted doubly linked list to test the functions Created doubly linked list will be 3<->6<->2<->12<->56<->8 */ list.push(8); list.push(56); list.push(12); list.push(2); list.push(6); list.push(3); int k = 2; System.out.println("Original Doubly linked list:"); list.printList(head); Node sortedDLL = list.sortAKSortedDLL(head, k); System.out.println(""); System.out.println("Doubly Linked List after sorting:"); list.printList(sortedDLL); }} // This code is contributed by Kushagra Keserwani Original Doubly linked list: 3 6 2 12 56 8 Doubly linked list after sorting: 2 3 6 8 12 56 Time Complexity: O(n*log k)Auxiliary Space: O(k) This article is contributed by Ayush Jauhari. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to review-team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. Akanksha_Rai kushagrakeserwani mittulmandhan sachinjain74754 aashish1995 simmytarika5 ankita_saini shinjanpatra doubly linked list Linked-List-Sorting Linked List Linked List Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Introduction to Data Structures What is Data Structure: Types, Classifications and Applications Add two numbers represented by linked lists | Set 1 Implementing a Linked List in Java using Class Find Length of a Linked List (Iterative and Recursive) Detect and Remove Loop in a Linked List Remove duplicates from an unsorted linked list Function to check if a singly linked list is palindrome Write a function to get the intersection point of two Linked Lists Circular Linked List | Set 1 (Introduction and Applications)
[ { "code": null, "e": 52, "s": 24, "text": "\n03 Jul, 2022" }, { "code": null, "e": 393, "s": 52, "text": "Given a doubly linked list containing n nodes, where each node is at most k away from its target position in the list. The problem is to sort the given doubly linked list. For example, let us consider k is 2, a node at position 7 in the sorted doubly linked list, can be at positions 5, 6, 7, 8, 9 in the given doubly linked list.Examples: " }, { "code": null, "e": 677, "s": 395, "text": "Naive Approach: Sort the given doubly linked list using the insertion sort technique. While inserting each element in the sorted part of the list, there will be at most k swaps to place the element to its correct position since it is at most k steps away from its correct position." }, { "code": null, "e": 681, "s": 677, "text": "C++" }, { "code": null, "e": 686, "s": 681, "text": "Java" }, { "code": null, "e": 694, "s": 686, "text": "Python3" }, { "code": null, "e": 705, "s": 694, "text": "Javascript" }, { "code": "// C++ implementation to sort a k sorted doubly// linked list#include<bits/stdc++.h>using namespace std; // a node of the doubly linked liststruct Node { int data; struct Node* next; struct Node* prev;}; // function to sort a k sorted doubly linked liststruct Node* sortAKSortedDLL(struct Node* head, int k){ if(head == NULL || head->next == NULL) return head; // perform on all the nodes in list for(Node *i = head->next; i != NULL; i = i->next) { Node *j = i; // There will be atmost k swaps for each element in the list // since each node is k steps away from its correct position while(j->prev != NULL && j->data < j->prev->data) { // swap j and j.prev node Node* temp = j->prev->prev; Node* temp2 = j->prev; Node *temp3 = j->next; j->prev->next = temp3; j->prev->prev = j; j->prev = temp; j->next = temp2; if(temp != NULL) temp->next = j; if(temp3 != NULL) temp3->prev = temp2; } // if j is now the new head // then reset head if(j->prev == NULL) head = j; } return head;} // Function to insert a node at the beginning// of the Doubly Linked Listvoid push(struct Node** head_ref, int new_data){ // allocate node struct Node* new_node = (struct Node*)malloc(sizeof(struct Node)); // put in the data new_node->data = new_data; // since we are adding at the beginning, // prev is always NULL new_node->prev = NULL; // link the old list off the new node new_node->next = (*head_ref); // change prev of head node to new node if ((*head_ref) != NULL) (*head_ref)->prev = new_node; // move the head to point to the new node (*head_ref) = new_node;} // Function to print nodes in a given doubly linked listvoid printList(struct Node* head){ // if list is empty if (head == NULL) cout << \"Doubly Linked list empty\"; while (head != NULL) { cout << head->data << \" \"; head = head->next; }} // Driver program to test aboveint main(){ struct Node* head = NULL; // Create the doubly linked list: // 3<->6<->2<->12<->56<->8 push(&head, 8); push(&head, 56); push(&head, 12); push(&head, 2); push(&head, 6); push(&head, 3); int k = 2; cout << \"Original Doubly linked list:\\n\"; printList(head); // sort the biotonic DLL head = sortAKSortedDLL(head, k); cout << \"\\nDoubly linked list after sorting:\\n\"; printList(head); return 0;} // This code is contributed by sachinejain74754.", "e": 3386, "s": 705, "text": null }, { "code": "// Java implementation to sort a k sorted doublyimport java.util.*;class DoublyLinkedList{static Node head;static class Node{ int data; Node next, prev; Node(int d) { data = d; next = prev = null; }} // function to sort a k sorted doubly linked list// Using Insertion Sort// Time Complexity: O(n*k)// Space Complexity: O(1)Node sortAKSortedDLL( Node head, int k) { if(head == null || head.next == null) return head; // perform on all the nodes in list for(Node i = head.next; i != null; i = i.next) { Node j = i; // There will be atmost k swaps for each element in the list // since each node is k steps away from its correct position while(j.prev != null && j.data < j.prev.data) { // swap j and j.prev node Node temp = j.prev.prev; Node temp2 = j.prev; Node temp3 = j.next; j.prev.next = temp3; j.prev.prev = j; j.prev = temp; j.next = temp2; if(temp != null) temp.next = j; if(temp3 != null) temp3.prev = temp2; } // if j is now the new head // then reset head if(j.prev == null) head = j; } return head;} /* UTILITY FUNCTIONS *//* Function to insert a node at the beginning of the * Doubly Linked List */void push(int new_data){ /* allocate node */ Node new_node = new Node(new_data); /* since we are adding at the beginning, prev is always NULL */ new_node.prev = null; /* link the old list off the new node */ new_node.next = head; /* change prev of head node to new node */ if (head != null) { head.prev = new_node; } /* move the head to point to the new node */ head = new_node;} /* Function to print nodes in a given doubly linked list This function is same as printList() of singly linked list */void printList(Node node){ while (node != null) { System.out.print(node.data + \" \"); node = node.next; }} // Driver codepublic static void main(String[] args){ DoublyLinkedList list = new DoublyLinkedList(); /* Let us create a k sorted doubly linked list to test the functions Created doubly linked list will be 3<->6<->2<->12<->56<->8 */ list.push(8); list.push(56); list.push(12); list.push(2); list.push(6); list.push(3); int k = 2; System.out.println(\"Original Doubly linked list:\"); list.printList(head); Node sortedDLL = list.sortAKSortedDLL(head, k); System.out.println(\"\"); System.out.println(\"Doubly Linked List after sorting:\"); list.printList(sortedDLL);}} // This code is contributed by Mittul Mandhan(@mittulmandhan)", "e": 6128, "s": 3386, "text": null }, { "code": "# Python implementation to sort a k sorted doublyclass DoublyLinkedList {head = None class Node: def __init__(self, val): self.data = val self.prev = None self.next = None # function to sort a k sorted doubly linked list# Using Insertion Sort# Time Complexity: O(n*k)# Space Complexity: O(1)def sortAKSortedDLL(head , k): if (head == None or head.next == None): return head # perform on all the nodes in list i = head.next while(i != None): j = i # There will be atmost k swaps for each element in the list # since each node is k steps away from its correct position while (j.prev != None and j.data < j.prev.data): # swap j and j.prev node temp = j.prev.prev temp2 = j.prev temp3 = j.next j.prev.next = temp3 j.prev.prev = j j.prev = temp j.next = temp2 if (temp != None): temp.next = j if (temp3 != None): temp3.prev = temp2 # if j is now the new head # then reset head if (j.prev == None): head = j i = i.next return head # UTILITY FUNCTIONS ## Function to insert a node at the beginning of the Doubly Linked Listdef push(new_data): global head # allocate node new_node = Node(new_data) # # since we are adding at the beginning, prev is always NULL # new_node.prev = None # link the old list off the new node new_node.next = head # change prev of head node to new node if (head != None): head.prev = new_node # move the head to point to the new node head = new_node # Function to print nodes in a given doubly linked list This function is same# as printList() of singly linked listdef printList(node): while (node != None): print(node.data,end = \" \") node = node.next # Driver code # Let us create a k sorted doubly linked list to test the functions Created# doubly linked list will be 3<->6<->2<->12<->56<->8push(8)push(56)push(12)push(2)push(6)push(3) k = 2 print(\"Original Doubly linked list:\")printList(head) sortedDLL = sortAKSortedDLL(head, k)print(\"\")print(\"Doubly Linked List after sorting:\")printList(sortedDLL) # This codeis contributed by shinjanpatra", "e": 8489, "s": 6128, "text": null }, { "code": "<script>// javascript implementation to sort a k sorted doublyclass DoublyLinkedList { var head; class Node { constructor(val) { this.data = val; this.prev = null; this.next = null; } } // function to sort a k sorted doubly linked list // Using Insertion Sort // Time Complexity: O(n*k) // Space Complexity: O(1) function sortAKSortedDLL(head , k) { if (head == null || head.next == null) return head; // perform on all the nodes in list for (i = head.next; i != null; i = i.next) { var j = i; // There will be atmost k swaps for each element in the list // since each node is k steps away from its correct position while (j.prev != null && j.data < j.prev.data) { // swap j and j.prev node var temp = j.prev.prev; var temp2 = j.prev; var temp3 = j.next; j.prev.next = temp3; j.prev.prev = j; j.prev = temp; j.next = temp2; if (temp != null) temp.next = j; if (temp3 != null) temp3.prev = temp2; } // if j is now the new head // then reset head if (j.prev == null) head = j; } return head; } /* UTILITY FUNCTIONS */ /* * Function to insert a node at the beginning of the Doubly Linked List */ function push(new_data) { /* allocate node */var new_node = new Node(new_data); /* * since we are adding at the beginning, prev is always NULL */ new_node.prev = null; /* link the old list off the new node */ new_node.next = head; /* change prev of head node to new node */ if (head != null) { head.prev = new_node; } /* move the head to point to the new node */ head = new_node; } /* * Function to print nodes in a given doubly linked list This function is same * as printList() of singly linked list */ function printList(node) { while (node != null) { document.write(node.data + \" \"); node = node.next; } } // Driver code /* * Let us create a k sorted doubly linked list to test the functions Created * doubly linked list will be 3<->6<->2<->12<->56<->8 */ push(8); push(56); push(12); push(2); push(6); push(3); var k = 2; document.write(\"Original Doubly linked list:<br/>\"); printList(head); var sortedDLL = sortAKSortedDLL(head, k); document.write(\"\"); document.write(\"<br/>Doubly Linked List after sorting:<br/>\"); printList(sortedDLL); // This code contributed by aashish1995</script>", "e": 11407, "s": 8489, "text": null }, { "code": null, "e": 11500, "s": 11407, "text": "Original Doubly linked list:\n3 6 2 12 56 8 \nDoubly Linked List after sorting:\n2 3 6 8 12 56 " }, { "code": null, "e": 11524, "s": 11500, "text": "Time Complexity: O(n*k)" }, { "code": null, "e": 11546, "s": 11524, "text": "Auxiliary Space: O(1)" }, { "code": null, "e": 11850, "s": 11546, "text": "Efficient Approach: We can sort the list using the MIN HEAP data structure. The approach has been explained in Sort a nearly sorted (or K sorted) array. We only have to be careful while traversing the input doubly linked list and adjusting the required next and previous links in the final sorted list. " }, { "code": null, "e": 11854, "s": 11850, "text": "CPP" }, { "code": null, "e": 11859, "s": 11854, "text": "Java" }, { "code": "// C++ implementation to sort a k sorted doubly// linked list#include <bits/stdc++.h>using namespace std; // a node of the doubly linked liststruct Node { int data; struct Node* next; struct Node* prev;}; // 'compare' function used to build up the// priority queuestruct compare { bool operator()(struct Node* p1, struct Node* p2) { return p1->data > p2->data; }}; // function to sort a k sorted doubly linked liststruct Node* sortAKSortedDLL(struct Node* head, int k){ // if list is empty if (head == NULL) return head; // priority_queue 'pq' implemented as min heap with the // help of 'compare' function priority_queue<Node*, vector<Node*>, compare> pq; struct Node* newHead = NULL, *last; // Create a Min Heap of first (k+1) elements from // input doubly linked list for (int i = 0; head != NULL && i <= k; i++) { // push the node on to 'pq' pq.push(head); // move to the next node head = head->next; } // loop till there are elements in 'pq' while (!pq.empty()) { // place root or top of 'pq' at the end of the // result sorted list so far having the first node // pointed to by 'newHead' // and adjust the required links if (newHead == NULL) { newHead = pq.top(); newHead->prev = NULL; // 'last' points to the last node // of the result sorted list so far last = newHead; } else { last->next = pq.top(); pq.top()->prev = last; last = pq.top(); } // remove element from 'pq' pq.pop(); // if there are more nodes left in the input list if (head != NULL) { // push the node on to 'pq' pq.push(head); // move to the next node head = head->next; } } // making 'next' of last node point to NULL last->next = NULL; // new head of the required sorted DLL return newHead;} // Function to insert a node at the beginning// of the Doubly Linked Listvoid push(struct Node** head_ref, int new_data){ // allocate node struct Node* new_node = (struct Node*)malloc(sizeof(struct Node)); // put in the data new_node->data = new_data; // since we are adding at the beginning, // prev is always NULL new_node->prev = NULL; // link the old list off the new node new_node->next = (*head_ref); // change prev of head node to new node if ((*head_ref) != NULL) (*head_ref)->prev = new_node; // move the head to point to the new node (*head_ref) = new_node;} // Function to print nodes in a given doubly linked listvoid printList(struct Node* head){ // if list is empty if (head == NULL) cout << \"Doubly Linked list empty\"; while (head != NULL) { cout << head->data << \" \"; head = head->next; }} // Driver program to test aboveint main(){ struct Node* head = NULL; // Create the doubly linked list: // 3<->6<->2<->12<->56<->8 push(&head, 8); push(&head, 56); push(&head, 12); push(&head, 2); push(&head, 6); push(&head, 3); int k = 2; cout << \"Original Doubly linked list:\\n\"; printList(head); // sort the biotonic DLL head = sortAKSortedDLL(head, k); cout << \"\\nDoubly linked list after sorting:\\n\"; printList(head); return 0;}", "e": 15298, "s": 11859, "text": null }, { "code": "// Java implementation to sort a k sorted doubly import java.util.*;class DoublyLinkedList{ static Node head; static class Node { int data; Node next, prev; Node(int d) { data = d; next = prev = null; } } class compareNode implements Comparator<Node> { public int compare(Node n1, Node n2){ return n1.data-n2.data; } } // function to sort a k sorted doubly linked list Node sortAKSortedDLL( Node head, int k) { // if list is empty if (head == null) return head; // priority_queue 'pq' implemented as min heap with the // help of 'compare' function in compare Node class PriorityQueue<Node> pq = new PriorityQueue<Node>(new compareNode()); Node newHead = null, last = null; // Create a Min Heap of first (k+1) elements from // input doubly linked list for (int i = 0; head != null && i <= k; i++) { // push the node on to 'pq' pq.add(head); // move to the next node head = head.next; } // loop till there are elements in 'pq' while (!pq.isEmpty()) { // place root or top of 'pq' at the end of the // result sorted list so far having the first node // pointed to by 'newHead' // and adjust the required links if (newHead == null) { newHead = pq.peek(); newHead.prev = null; // 'last' points to the last node // of the result sorted list so far last = newHead; } else { last.next = pq.peek(); pq.peek().prev = last; last = pq.peek(); } // remove element from 'pq' pq.poll(); // if there are more nodes left in the input list if (head != null) { // push the node on to 'pq' pq.add(head); // move to the next node head = head.next; } } // making 'next' of last node point to NULL last.next = null; // new head of the required sorted DLL return newHead; } /* UTILITY FUNCTIONS */ /* Function to insert a node at the beginning of the * Doubly Linked List */ void push(int new_data) { /* allocate node */ Node new_node = new Node(new_data); /* since we are adding at the beginning, prev is always NULL */ new_node.prev = null; /* link the old list off the new node */ new_node.next = head; /* change prev of head node to new node */ if (head != null) { head.prev = new_node; } /* move the head to point to the new node */ head = new_node; } /* Function to print nodes in a given doubly linked list This function is same as printList() of singly linked list */ void printList(Node node) { while (node != null) { System.out.print(node.data + \" \"); node = node.next; } } // Driver code public static void main(String[] args) { DoublyLinkedList list = new DoublyLinkedList(); /* Let us create a k sorted doubly linked list to test the functions Created doubly linked list will be 3<->6<->2<->12<->56<->8 */ list.push(8); list.push(56); list.push(12); list.push(2); list.push(6); list.push(3); int k = 2; System.out.println(\"Original Doubly linked list:\"); list.printList(head); Node sortedDLL = list.sortAKSortedDLL(head, k); System.out.println(\"\"); System.out.println(\"Doubly Linked List after sorting:\"); list.printList(sortedDLL); }} // This code is contributed by Kushagra Keserwani", "e": 18847, "s": 15298, "text": null }, { "code": null, "e": 18940, "s": 18847, "text": "Original Doubly linked list:\n3 6 2 12 56 8 \nDoubly linked list after sorting:\n2 3 6 8 12 56 " }, { "code": null, "e": 18989, "s": 18940, "text": "Time Complexity: O(n*log k)Auxiliary Space: O(k)" }, { "code": null, "e": 19411, "s": 18989, "text": "This article is contributed by Ayush Jauhari. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to review-team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. " }, { "code": null, "e": 19424, "s": 19411, "text": "Akanksha_Rai" }, { "code": null, "e": 19442, "s": 19424, "text": "kushagrakeserwani" }, { "code": null, "e": 19456, "s": 19442, "text": "mittulmandhan" }, { "code": null, "e": 19472, "s": 19456, "text": "sachinjain74754" }, { "code": null, "e": 19484, "s": 19472, "text": "aashish1995" }, { "code": null, "e": 19497, "s": 19484, "text": "simmytarika5" }, { "code": null, "e": 19510, "s": 19497, "text": "ankita_saini" }, { "code": null, "e": 19523, "s": 19510, "text": "shinjanpatra" }, { "code": null, "e": 19542, "s": 19523, "text": "doubly linked list" }, { "code": null, "e": 19562, "s": 19542, "text": "Linked-List-Sorting" }, { "code": null, "e": 19574, "s": 19562, "text": "Linked List" }, { "code": null, "e": 19586, "s": 19574, "text": "Linked List" }, { "code": null, "e": 19684, "s": 19586, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 19716, "s": 19684, "text": "Introduction to Data Structures" }, { "code": null, "e": 19780, "s": 19716, "text": "What is Data Structure: Types, Classifications and Applications" }, { "code": null, "e": 19832, "s": 19780, "text": "Add two numbers represented by linked lists | Set 1" }, { "code": null, "e": 19879, "s": 19832, "text": "Implementing a Linked List in Java using Class" }, { "code": null, "e": 19934, "s": 19879, "text": "Find Length of a Linked List (Iterative and Recursive)" }, { "code": null, "e": 19974, "s": 19934, "text": "Detect and Remove Loop in a Linked List" }, { "code": null, "e": 20021, "s": 19974, "text": "Remove duplicates from an unsorted linked list" }, { "code": null, "e": 20077, "s": 20021, "text": "Function to check if a singly linked list is palindrome" }, { "code": null, "e": 20144, "s": 20077, "text": "Write a function to get the intersection point of two Linked Lists" } ]
Java Program to Read Content From One File and Write it into Another File
16 Jun, 2022 File handling plays a major role in doing so as the first essential step is writing content to a file. For this is one must know how to write content in a file using the FileWriter class. The secondary step is reading content from a file and print the same. For this, one must have good hands on File Reader class to do so. Now in order to read content from one file and write it into another file, it is already discussed achieving the same how to write content on a file and also how to read contents from a file. Now, the time to combine both of them. Now we will use FileReader class to read the contents from a class and the FileWriter class to write it on another file. Methods: In order to read contents from a file and write it into another file, one must have to know how to read a file or write a file. Using the variableWithout using any variable Using the variable Without using any variable Method 1: Using the variable Example 1: Java // Java program to read content from one file// and write it into another file // Custom paths for this program// Reading from - gfgInput.txt// Writing to - gfgOutput.txt // Importing input output classesimport java.io.FileReader;import java.io.FileWriter;import java.io.IOException; // Classclass GFG { // Main driver method public static void main(String[] args) { // The file reading process may sometimes give // IOException // Try block to check for exceptions try { // Creating a FileReader object and // file to be read is passed as in parameters // from the local directory of computer FileReader fr = new FileReader("gfgInput.txt"); // FileReader will open that file from that // directory, if there is no file found it will // through an IOException // Creating a FileWriter object FileWriter fw = new FileWriter("gfgOutput.txt"); // It will create a new file with name // "gfgOutput.text", if it is already available, // then it will open that instead // Declaring a blank string in which // whole content of file is to be stored String str = ""; int i; // read() method will read the file character by // character and print it until it end the end // of the file // Condition check // Reading the file using read() method which // returns -1 at EOF while reading while ((i = fr.read()) != -1) { // Storing every character in the string str += (char)i; } // Print and display the string that // contains file data System.out.println(str); // Writing above string data to // FileWriter object fw.write(str); // Closing the file using close() method // of Reader class which closes the stream & // release resources that were busy in stream fr.close(); fw.close(); // Display message System.out.println( "File reading and writing both done"); } // Catch block to handle the exception catch (IOException e) { // If there is no file in specified path or // any other error occurred during runtime // then it will print IOException // Display message System.out.println( "There are some IOException"); } }} Output: As this code is accessing internal storage to save that file, so it wouldn’t run on the compiler so the output is hard-coded below as shown The program prints the content in that file, and then in the next line, it will print File reading and writing done(if there is no error occurred), and the contents of the input file will be written in the new output file. If there is some error, then it will print There are some IOException. Method 2: Without using any variable In the previous program, we were storing all the contents of the input file in a variable, and then we were writing the string in the output file. Now we can directly store those characters in the output file directly. Java // Java program to read content from one file// and write it into another file // Custom paths for this program// Reading from - gfgInput.txt// Writing to - gfgOutput.txt // Importing FileWriter class// to write into a fileimport java.io.FileWriter;// Also importing IOException class to// throw exception if occursimport java.io.IOException; // Classclass GFG { // Main driver method public static void main(String[] args) { // The file writing and creating process may give // some IOException, that's why it is mandatory to // use try block // Try block to check for exception/s try { // Creating a FileWriter object which will // create a new file and if already available // it will open it FileWriter fw = new FileWriter("gfg.txt"); // Content to be written on file // Custom input string // write() method will write the string // in the file fw.write("We love GeeksForGeeks"); // Closing the file freeing up resources // in the memory fw.close(); // Print and display message System.out.println("\nFile write done"); } // Catch block to catch if exception/s occurs catch (IOException e) { // Print and display message System.out.println( "There are some IOException"); } }} Output: As this code is accessing internal storage to save that file, so it wouldn’t run on the compiler so the output is hard-coded below as shown As output the program will print FIle write done(if there is no error), and will create a file with the same name given as file name, i.e, ‘gfg.text’ rs1686740 sweetyty nikhatkhan11 Java-Files Picked Java Java Programs Java Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 52, "s": 24, "text": "\n16 Jun, 2022" }, { "code": null, "e": 379, "s": 52, "text": " File handling plays a major role in doing so as the first essential step is writing content to a file. For this is one must know how to write content in a file using the FileWriter class. The secondary step is reading content from a file and print the same. For this, one must have good hands on File Reader class to do so. " }, { "code": null, "e": 731, "s": 379, "text": "Now in order to read content from one file and write it into another file, it is already discussed achieving the same how to write content on a file and also how to read contents from a file. Now, the time to combine both of them. Now we will use FileReader class to read the contents from a class and the FileWriter class to write it on another file." }, { "code": null, "e": 868, "s": 731, "text": "Methods: In order to read contents from a file and write it into another file, one must have to know how to read a file or write a file." }, { "code": null, "e": 913, "s": 868, "text": "Using the variableWithout using any variable" }, { "code": null, "e": 932, "s": 913, "text": "Using the variable" }, { "code": null, "e": 959, "s": 932, "text": "Without using any variable" }, { "code": null, "e": 988, "s": 959, "text": "Method 1: Using the variable" }, { "code": null, "e": 999, "s": 988, "text": "Example 1:" }, { "code": null, "e": 1004, "s": 999, "text": "Java" }, { "code": "// Java program to read content from one file// and write it into another file // Custom paths for this program// Reading from - gfgInput.txt// Writing to - gfgOutput.txt // Importing input output classesimport java.io.FileReader;import java.io.FileWriter;import java.io.IOException; // Classclass GFG { // Main driver method public static void main(String[] args) { // The file reading process may sometimes give // IOException // Try block to check for exceptions try { // Creating a FileReader object and // file to be read is passed as in parameters // from the local directory of computer FileReader fr = new FileReader(\"gfgInput.txt\"); // FileReader will open that file from that // directory, if there is no file found it will // through an IOException // Creating a FileWriter object FileWriter fw = new FileWriter(\"gfgOutput.txt\"); // It will create a new file with name // \"gfgOutput.text\", if it is already available, // then it will open that instead // Declaring a blank string in which // whole content of file is to be stored String str = \"\"; int i; // read() method will read the file character by // character and print it until it end the end // of the file // Condition check // Reading the file using read() method which // returns -1 at EOF while reading while ((i = fr.read()) != -1) { // Storing every character in the string str += (char)i; } // Print and display the string that // contains file data System.out.println(str); // Writing above string data to // FileWriter object fw.write(str); // Closing the file using close() method // of Reader class which closes the stream & // release resources that were busy in stream fr.close(); fw.close(); // Display message System.out.println( \"File reading and writing both done\"); } // Catch block to handle the exception catch (IOException e) { // If there is no file in specified path or // any other error occurred during runtime // then it will print IOException // Display message System.out.println( \"There are some IOException\"); } }}", "e": 3627, "s": 1004, "text": null }, { "code": null, "e": 3775, "s": 3627, "text": "Output: As this code is accessing internal storage to save that file, so it wouldn’t run on the compiler so the output is hard-coded below as shown" }, { "code": null, "e": 4069, "s": 3775, "text": "The program prints the content in that file, and then in the next line, it will print File reading and writing done(if there is no error occurred), and the contents of the input file will be written in the new output file. If there is some error, then it will print There are some IOException." }, { "code": null, "e": 4106, "s": 4069, "text": "Method 2: Without using any variable" }, { "code": null, "e": 4325, "s": 4106, "text": "In the previous program, we were storing all the contents of the input file in a variable, and then we were writing the string in the output file. Now we can directly store those characters in the output file directly." }, { "code": null, "e": 4330, "s": 4325, "text": "Java" }, { "code": "// Java program to read content from one file// and write it into another file // Custom paths for this program// Reading from - gfgInput.txt// Writing to - gfgOutput.txt // Importing FileWriter class// to write into a fileimport java.io.FileWriter;// Also importing IOException class to// throw exception if occursimport java.io.IOException; // Classclass GFG { // Main driver method public static void main(String[] args) { // The file writing and creating process may give // some IOException, that's why it is mandatory to // use try block // Try block to check for exception/s try { // Creating a FileWriter object which will // create a new file and if already available // it will open it FileWriter fw = new FileWriter(\"gfg.txt\"); // Content to be written on file // Custom input string // write() method will write the string // in the file fw.write(\"We love GeeksForGeeks\"); // Closing the file freeing up resources // in the memory fw.close(); // Print and display message System.out.println(\"\\nFile write done\"); } // Catch block to catch if exception/s occurs catch (IOException e) { // Print and display message System.out.println( \"There are some IOException\"); } }}", "e": 5787, "s": 4330, "text": null }, { "code": null, "e": 5935, "s": 5787, "text": "Output: As this code is accessing internal storage to save that file, so it wouldn’t run on the compiler so the output is hard-coded below as shown" }, { "code": null, "e": 6086, "s": 5935, "text": "As output the program will print FIle write done(if there is no error), and will create a file with the same name given as file name, i.e, ‘gfg.text’" }, { "code": null, "e": 6096, "s": 6086, "text": "rs1686740" }, { "code": null, "e": 6105, "s": 6096, "text": "sweetyty" }, { "code": null, "e": 6118, "s": 6105, "text": "nikhatkhan11" }, { "code": null, "e": 6129, "s": 6118, "text": "Java-Files" }, { "code": null, "e": 6136, "s": 6129, "text": "Picked" }, { "code": null, "e": 6141, "s": 6136, "text": "Java" }, { "code": null, "e": 6155, "s": 6141, "text": "Java Programs" }, { "code": null, "e": 6160, "s": 6155, "text": "Java" } ]
PHP make sure string has no whitespace?
To check whether a string has no whitespace, use the preg_match() in PHP. The syntax is as follows preg_match('/\s/',$yourVariableName); The PHP code is as follows Live Demo <!DOCTYPE html> <html> <body> <?php $name="John Smith"; if ( preg_match('/\s/',$name) ){ echo "The name (",$name,") has the space"; } else { echo "The Name (",$name,") has not the space"; } ?> </body> </html> This will produce the following output The name (John Smith) has the space
[ { "code": null, "e": 1261, "s": 1187, "text": "To check whether a string has no whitespace, use the preg_match() in PHP." }, { "code": null, "e": 1287, "s": 1261, "text": "The syntax is as follows " }, { "code": null, "e": 1325, "s": 1287, "text": "preg_match('/\\s/',$yourVariableName);" }, { "code": null, "e": 1352, "s": 1325, "text": "The PHP code is as follows" }, { "code": null, "e": 1363, "s": 1352, "text": " Live Demo" }, { "code": null, "e": 1578, "s": 1363, "text": "<!DOCTYPE html>\n<html>\n<body>\n<?php\n$name=\"John Smith\";\nif ( preg_match('/\\s/',$name) ){\n echo \"The name (\",$name,\") has the space\";\n} else {\n echo \"The Name (\",$name,\") has not the space\";\n}\n?>\n</body>\n</html>" }, { "code": null, "e": 1617, "s": 1578, "text": "This will produce the following output" }, { "code": null, "e": 1653, "s": 1617, "text": "The name (John Smith) has the space" } ]
Explain Bootstrap’s collapsing elements
31 Oct, 2021 In this article, we will see how can we create a collapsing element using Bootstrap classes and also see their different properties, along with understanding their implementation through the example. Bootstrap Collapsing Element: Collapsing elements are those elements that show data to the user when the user clicks or hover over it. It is a modern approach that helps us to show a large amount of data to the user. It keeps the website neat and closes or collapses again when the user hovers out or clicks out of it. We can make our own collapsing element using the basic HTML, CSS, and JavaScript. But Bootstrap facilitates the collapsing element property in its components. Working of Bootstrap Collapsing Element: Bootstrap collapse is used to show or hide content. Buttons or anchors are used to trigger the request and they are mapped to the specific element that needs to be collapsed. In Bootstrap, the collapsing element animates the height of the element from its current height to 0. The classes used for collapsing element: .collapse: This class hides the content. .collapsing: This class is used during the transition. .collapse-show: This class shows the content. Please refer to the Bootstrap 4 Collapse article for further details. Generally, the collapsing element is done using the button. Here, we will use a button to show the working of the collapsible element. Syntax: <button type="button" data-bs-toggle="collapse" data-bs-target="#collapseExample">Button </button> The two attributes are used with the button, are given below: data-bs-target: This attribute holds the id of the element that is needed to be hidden or shown on a button click. data-bs-toggle: This attribute is always set to “collapse”. From the below example, we can see a button is given with both the attributes “data-bs-toggle” set to “collapse” and “data-bs-target” with the value set to “#collapseExample” i.e. the id of the div element that should be made collapsible. The “div” is given the class “collapse” to make it collapsible. Example: This example describes the collapsing element. HTML <!DOCTYPE html><html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@4.6.0/dist/css/bootstrap.min.css" integrity="sha384-B0vP5xmATw1+K9KRQjQERJvTumQW0nPEzvF6L/Z6nronJ3oUOFUFpCjEUQouq2+l" crossorigin="anonymous"> <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/js/bootstrap.bundle.min.js" integrity="sha384-ka7Sk0Gln4gmtz2MlQnikT1wXgYsOg+OMhuP+IlRH9sENBO0LRn5q+8nbTov4+1p" crossorigin="anonymous"> </script> <title>Document</title></head> <body> <h1 class=text-success>GeeksforGeeks</h1> <p> <button class="btn btn-primary" type="button" data-bs-toggle="collapse" data-bs-target="#collapseExample" aria-expanded="false" aria-controls="collapseExample"> Button of Collapsing Element </button> </p> <div class="collapse" id="collapseExample"> <div class="card card-body"> This text is shown when the above button is clicked and hides when user clicks on it again. </div> </div></body> </html> Output: Simple Collapsing Element in Bootstrap Horizontal Collapsing Element: We can also make horizontal collapsing elements. Here, instead of vertical the element will collapse horizontally. To make a horizontal collapsing element, we need to add the class “collapse-horizontal” to the element that is to be collapsed. We need the width of the child element to be mentioned either using the inline CSS or using width-utilities only. Syntax: <div class="collapse collapse-horizontal"></div> Example: This example describes the Horizontal Collapsing Element. HTML <!DOCTYPE html><html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@4.6.0/dist/css/bootstrap.min.css" integrity="sha384-B0vP5xmATw1+K9KRQjQERJvTumQW0nPEzvF6L/Z6nronJ3oUOFUFpCjEUQouq2+l" crossorigin="anonymous"> <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/js/bootstrap.bundle.min.js" integrity="sha384-ka7Sk0Gln4gmtz2MlQnikT1wXgYsOg+OMhuP+IlRH9sENBO0LRn5q+8nbTov4+1p" crossorigin="anonymous"> </script> <title>Document</title></head> <body> <h1 class=text-success>GeeksforGeeks</h1> <p> <button class="btn btn-primary" type="button" data-bs-toggle="collapse" data-bs-target="#collapseExample" aria-expanded="false" aria-controls="collapseExample"> Button of Collapsing Element </button> </p> <div> <div class="collapse collapse-horizontal" id="collapseExample"> <div class="card card-body" style="width: 500px;"> This text is shown when the above button is clicked and hides when user clicks on it again. </div> </div> </div> </body> </html> Output: Collapsing Element in Horizontal Manner Multiple Collapsible: We can also make a single button to control multiple collapsible elements at once. The idea is very simple, here we have to make multiple-element with the same class name and add that class name to the “data-bs-target”. Note: We use the class name here not id because id is unique to every element in HTML. Syntax: <div class="collapse multi-collapse"></div> Example: This example describes the Multiple Collapsible Element. HTML <!DOCTYPE html><html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@4.6.0/dist/css/bootstrap.min.css" integrity="sha384-B0vP5xmATw1+K9KRQjQERJvTumQW0nPEzvF6L/Z6nronJ3oUOFUFpCjEUQouq2+l" crossorigin="anonymous"> <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/js/bootstrap.bundle.min.js" integrity="sha384-ka7Sk0Gln4gmtz2MlQnikT1wXgYsOg+OMhuP+IlRH9sENBO0LRn5q+8nbTov4+1p" crossorigin="anonymous"> </script> <title>Document</title></head> <body> <h1 class=text-success>GeeksforGeeks</h1> <button class="btn btn-primary" type="button" data-bs-toggle="collapse" data-bs-target=".collapse" aria-expanded="false" aria-controls="multiCollapseExample1 multiCollapseExample2"> Toggle both elements </button> <div class="row"> <div class="col"> <div class="collapse multi-collapse" id="multiCollapseExample1"> <div class="card card-body"> This text is shown when the above button is clicked and hides when user clicks on it again. </div> </div> </div> <div class="col"> <div class="collapse multi-collapse" id="multiCollapseExample2"> <div class="card card-body"> This text is shown when the above button is clicked and hides when user clicks on it again. </div> </div> </div> </div> </body> </html> Output: Multiple Collapsible in Bootstrap In the above code, the “data-bs-target” attribute of the button is given the value of the class name “.collapse” and thus the button now works on both the collapsible element at once. Note: We can also make the above elements show content individually by assigning them to separate buttons using their “id”. Supported Browser: Google Chrome Microsoft Edge Internet Explorer 10+ Opera Safari Firefox Bootstrap-Questions HTML-Questions Picked Bootstrap HTML Web Technologies HTML Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n31 Oct, 2021" }, { "code": null, "e": 228, "s": 28, "text": "In this article, we will see how can we create a collapsing element using Bootstrap classes and also see their different properties, along with understanding their implementation through the example." }, { "code": null, "e": 258, "s": 228, "text": "Bootstrap Collapsing Element:" }, { "code": null, "e": 708, "s": 258, "text": "Collapsing elements are those elements that show data to the user when the user clicks or hover over it. It is a modern approach that helps us to show a large amount of data to the user. It keeps the website neat and closes or collapses again when the user hovers out or clicks out of it. We can make our own collapsing element using the basic HTML, CSS, and JavaScript. But Bootstrap facilitates the collapsing element property in its components. " }, { "code": null, "e": 749, "s": 708, "text": "Working of Bootstrap Collapsing Element:" }, { "code": null, "e": 1026, "s": 749, "text": "Bootstrap collapse is used to show or hide content. Buttons or anchors are used to trigger the request and they are mapped to the specific element that needs to be collapsed. In Bootstrap, the collapsing element animates the height of the element from its current height to 0." }, { "code": null, "e": 1067, "s": 1026, "text": "The classes used for collapsing element:" }, { "code": null, "e": 1108, "s": 1067, "text": ".collapse: This class hides the content." }, { "code": null, "e": 1163, "s": 1108, "text": ".collapsing: This class is used during the transition." }, { "code": null, "e": 1209, "s": 1163, "text": ".collapse-show: This class shows the content." }, { "code": null, "e": 1279, "s": 1209, "text": "Please refer to the Bootstrap 4 Collapse article for further details." }, { "code": null, "e": 1414, "s": 1279, "text": "Generally, the collapsing element is done using the button. Here, we will use a button to show the working of the collapsible element." }, { "code": null, "e": 1422, "s": 1414, "text": "Syntax:" }, { "code": null, "e": 1540, "s": 1422, "text": "<button type=\"button\" \n data-bs-toggle=\"collapse\" \n data-bs-target=\"#collapseExample\">Button \n</button>" }, { "code": null, "e": 1602, "s": 1540, "text": "The two attributes are used with the button, are given below:" }, { "code": null, "e": 1717, "s": 1602, "text": "data-bs-target: This attribute holds the id of the element that is needed to be hidden or shown on a button click." }, { "code": null, "e": 1777, "s": 1717, "text": "data-bs-toggle: This attribute is always set to “collapse”." }, { "code": null, "e": 2080, "s": 1777, "text": "From the below example, we can see a button is given with both the attributes “data-bs-toggle” set to “collapse” and “data-bs-target” with the value set to “#collapseExample” i.e. the id of the div element that should be made collapsible. The “div” is given the class “collapse” to make it collapsible." }, { "code": null, "e": 2136, "s": 2080, "text": "Example: This example describes the collapsing element." }, { "code": null, "e": 2141, "s": 2136, "text": "HTML" }, { "code": "<!DOCTYPE html><html lang=\"en\"> <head> <meta charset=\"UTF-8\"> <meta http-equiv=\"X-UA-Compatible\" content=\"IE=edge\"> <meta name=\"viewport\" content=\"width=device-width, initial-scale=1.0\"> <link rel=\"stylesheet\" href=\"https://cdn.jsdelivr.net/npm/bootstrap@4.6.0/dist/css/bootstrap.min.css\" integrity=\"sha384-B0vP5xmATw1+K9KRQjQERJvTumQW0nPEzvF6L/Z6nronJ3oUOFUFpCjEUQouq2+l\" crossorigin=\"anonymous\"> <script src=\"https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/js/bootstrap.bundle.min.js\" integrity=\"sha384-ka7Sk0Gln4gmtz2MlQnikT1wXgYsOg+OMhuP+IlRH9sENBO0LRn5q+8nbTov4+1p\" crossorigin=\"anonymous\"> </script> <title>Document</title></head> <body> <h1 class=text-success>GeeksforGeeks</h1> <p> <button class=\"btn btn-primary\" type=\"button\" data-bs-toggle=\"collapse\" data-bs-target=\"#collapseExample\" aria-expanded=\"false\" aria-controls=\"collapseExample\"> Button of Collapsing Element </button> </p> <div class=\"collapse\" id=\"collapseExample\"> <div class=\"card card-body\"> This text is shown when the above button is clicked and hides when user clicks on it again. </div> </div></body> </html>", "e": 3509, "s": 2141, "text": null }, { "code": null, "e": 3517, "s": 3509, "text": "Output:" }, { "code": null, "e": 3556, "s": 3517, "text": "Simple Collapsing Element in Bootstrap" }, { "code": null, "e": 3587, "s": 3556, "text": "Horizontal Collapsing Element:" }, { "code": null, "e": 3944, "s": 3587, "text": "We can also make horizontal collapsing elements. Here, instead of vertical the element will collapse horizontally. To make a horizontal collapsing element, we need to add the class “collapse-horizontal” to the element that is to be collapsed. We need the width of the child element to be mentioned either using the inline CSS or using width-utilities only." }, { "code": null, "e": 3952, "s": 3944, "text": "Syntax:" }, { "code": null, "e": 4001, "s": 3952, "text": "<div class=\"collapse collapse-horizontal\"></div>" }, { "code": null, "e": 4068, "s": 4001, "text": "Example: This example describes the Horizontal Collapsing Element." }, { "code": null, "e": 4073, "s": 4068, "text": "HTML" }, { "code": "<!DOCTYPE html><html lang=\"en\"> <head> <meta charset=\"UTF-8\"> <meta http-equiv=\"X-UA-Compatible\" content=\"IE=edge\"> <meta name=\"viewport\" content=\"width=device-width, initial-scale=1.0\"> <link rel=\"stylesheet\" href=\"https://cdn.jsdelivr.net/npm/bootstrap@4.6.0/dist/css/bootstrap.min.css\" integrity=\"sha384-B0vP5xmATw1+K9KRQjQERJvTumQW0nPEzvF6L/Z6nronJ3oUOFUFpCjEUQouq2+l\" crossorigin=\"anonymous\"> <script src=\"https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/js/bootstrap.bundle.min.js\" integrity=\"sha384-ka7Sk0Gln4gmtz2MlQnikT1wXgYsOg+OMhuP+IlRH9sENBO0LRn5q+8nbTov4+1p\" crossorigin=\"anonymous\"> </script> <title>Document</title></head> <body> <h1 class=text-success>GeeksforGeeks</h1> <p> <button class=\"btn btn-primary\" type=\"button\" data-bs-toggle=\"collapse\" data-bs-target=\"#collapseExample\" aria-expanded=\"false\" aria-controls=\"collapseExample\"> Button of Collapsing Element </button> </p> <div> <div class=\"collapse collapse-horizontal\" id=\"collapseExample\"> <div class=\"card card-body\" style=\"width: 500px;\"> This text is shown when the above button is clicked and hides when user clicks on it again. </div> </div> </div> </body> </html>", "e": 5586, "s": 4073, "text": null }, { "code": null, "e": 5594, "s": 5586, "text": "Output:" }, { "code": null, "e": 5634, "s": 5594, "text": "Collapsing Element in Horizontal Manner" }, { "code": null, "e": 5656, "s": 5634, "text": "Multiple Collapsible:" }, { "code": null, "e": 5876, "s": 5656, "text": "We can also make a single button to control multiple collapsible elements at once. The idea is very simple, here we have to make multiple-element with the same class name and add that class name to the “data-bs-target”." }, { "code": null, "e": 5963, "s": 5876, "text": "Note: We use the class name here not id because id is unique to every element in HTML." }, { "code": null, "e": 5971, "s": 5963, "text": "Syntax:" }, { "code": null, "e": 6015, "s": 5971, "text": "<div class=\"collapse multi-collapse\"></div>" }, { "code": null, "e": 6081, "s": 6015, "text": "Example: This example describes the Multiple Collapsible Element." }, { "code": null, "e": 6086, "s": 6081, "text": "HTML" }, { "code": "<!DOCTYPE html><html lang=\"en\"> <head> <meta charset=\"UTF-8\"> <meta http-equiv=\"X-UA-Compatible\" content=\"IE=edge\"> <meta name=\"viewport\" content=\"width=device-width, initial-scale=1.0\"> <link rel=\"stylesheet\" href=\"https://cdn.jsdelivr.net/npm/bootstrap@4.6.0/dist/css/bootstrap.min.css\" integrity=\"sha384-B0vP5xmATw1+K9KRQjQERJvTumQW0nPEzvF6L/Z6nronJ3oUOFUFpCjEUQouq2+l\" crossorigin=\"anonymous\"> <script src=\"https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/js/bootstrap.bundle.min.js\" integrity=\"sha384-ka7Sk0Gln4gmtz2MlQnikT1wXgYsOg+OMhuP+IlRH9sENBO0LRn5q+8nbTov4+1p\" crossorigin=\"anonymous\"> </script> <title>Document</title></head> <body> <h1 class=text-success>GeeksforGeeks</h1> <button class=\"btn btn-primary\" type=\"button\" data-bs-toggle=\"collapse\" data-bs-target=\".collapse\" aria-expanded=\"false\" aria-controls=\"multiCollapseExample1 multiCollapseExample2\"> Toggle both elements </button> <div class=\"row\"> <div class=\"col\"> <div class=\"collapse multi-collapse\" id=\"multiCollapseExample1\"> <div class=\"card card-body\"> This text is shown when the above button is clicked and hides when user clicks on it again. </div> </div> </div> <div class=\"col\"> <div class=\"collapse multi-collapse\" id=\"multiCollapseExample2\"> <div class=\"card card-body\"> This text is shown when the above button is clicked and hides when user clicks on it again. </div> </div> </div> </div> </body> </html>", "e": 7971, "s": 6086, "text": null }, { "code": null, "e": 7979, "s": 7971, "text": "Output:" }, { "code": null, "e": 8013, "s": 7979, "text": "Multiple Collapsible in Bootstrap" }, { "code": null, "e": 8199, "s": 8013, "text": "In the above code, the “data-bs-target” attribute of the button is given the value of the class name “.collapse” and thus the button now works on both the collapsible element at once. " }, { "code": null, "e": 8324, "s": 8199, "text": "Note: We can also make the above elements show content individually by assigning them to separate buttons using their “id”." }, { "code": null, "e": 8343, "s": 8324, "text": "Supported Browser:" }, { "code": null, "e": 8357, "s": 8343, "text": "Google Chrome" }, { "code": null, "e": 8372, "s": 8357, "text": "Microsoft Edge" }, { "code": null, "e": 8394, "s": 8372, "text": "Internet Explorer 10+" }, { "code": null, "e": 8400, "s": 8394, "text": "Opera" }, { "code": null, "e": 8407, "s": 8400, "text": "Safari" }, { "code": null, "e": 8415, "s": 8407, "text": "Firefox" }, { "code": null, "e": 8435, "s": 8415, "text": "Bootstrap-Questions" }, { "code": null, "e": 8450, "s": 8435, "text": "HTML-Questions" }, { "code": null, "e": 8457, "s": 8450, "text": "Picked" }, { "code": null, "e": 8467, "s": 8457, "text": "Bootstrap" }, { "code": null, "e": 8472, "s": 8467, "text": "HTML" }, { "code": null, "e": 8489, "s": 8472, "text": "Web Technologies" }, { "code": null, "e": 8494, "s": 8489, "text": "HTML" } ]
Lodash _.findKey() Method - GeeksforGeeks
10 Sep, 2020 Lodash is a JavaScript library that works on the top of underscore.js. Lodash helps in working with arrays, collection, strings, lang, function, objects, numbers etc. The _.findKey() method is similar to _.find() method except that it returns the key of the first element, predicate returns true for instead of the element itself. Syntax: _.findKey(object, predicate) Parameters: This method accepts two parameters as mentioned above and described below: object: It holds the object to inspect every element. predicate: It holds the function that the method invoked per iteration. Return Value: This method returns the key of the matched element else undefined. Example 1: Here, const _ = require(‘lodash’) is used to import the lodash library in the file. // Requiring the lodash library const _ = require("lodash"); // Original array var users = { 'meetu': { 'salary': 36000, 'active': true }, 'teetu': { 'salary': 40000, 'active': false }, 'seetu': { 'salary': 10000, 'active': true }}; // Using the _.findKey() methodlet found_elem = _.findKey(users, function(o) { return o.salary < 40000; }); // Printing the output console.log(found_elem); Output: meetu Example 2: // Requiring the lodash library const _ = require("lodash"); // Original array var users = { 'meetu': { 'salary': 36000, 'active': true }, 'teetu': { 'salary': 40000, 'active': false }, 'seetu': { 'salary': 10000, 'active': true }}; // Using the _.findKey() method// The `_.matches` iteratee shorthandlet found_elem = _.findKey(users, { 'salary': 10000, 'active': true }); // Printing the output console.log(found_elem); Output: seetu Example 3: // Requiring the lodash library const _ = require("lodash"); // Original array var users = { 'meetu': { 'salary': 36000, 'active': true }, 'teetu': { 'salary': 40000, 'active': false }, 'seetu': { 'salary': 10000, 'active': true }}; // Using the _.findKey() method// The `_.matchesProperty` iteratee shorthandlet found_elem = _.findKey(users, ['active', false]); // Printing the output console.log(found_elem); Output: teetu Example 4: // Requiring the lodash library const _ = require("lodash"); // Original array var users = { 'meetu': { 'salary': 36000, 'active': true }, 'teetu': { 'salary': 40000, 'active': false }, 'seetu': { 'salary': 10000, 'active': true }}; // Using the _.findKey() method// The `_.property` iteratee shorthandlet found_elem = _.findKey(users, 'active'); // Printing the output console.log(found_elem); Output: meetu Note: This code will not work in normal JavaScript because it requires the library lodash to be installed. JavaScript-Lodash 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": 37045, "s": 37017, "text": "\n10 Sep, 2020" }, { "code": null, "e": 37212, "s": 37045, "text": "Lodash is a JavaScript library that works on the top of underscore.js. Lodash helps in working with arrays, collection, strings, lang, function, objects, numbers etc." }, { "code": null, "e": 37376, "s": 37212, "text": "The _.findKey() method is similar to _.find() method except that it returns the key of the first element, predicate returns true for instead of the element itself." }, { "code": null, "e": 37384, "s": 37376, "text": "Syntax:" }, { "code": null, "e": 37413, "s": 37384, "text": "_.findKey(object, predicate)" }, { "code": null, "e": 37500, "s": 37413, "text": "Parameters: This method accepts two parameters as mentioned above and described below:" }, { "code": null, "e": 37554, "s": 37500, "text": "object: It holds the object to inspect every element." }, { "code": null, "e": 37626, "s": 37554, "text": "predicate: It holds the function that the method invoked per iteration." }, { "code": null, "e": 37707, "s": 37626, "text": "Return Value: This method returns the key of the matched element else undefined." }, { "code": null, "e": 37802, "s": 37707, "text": "Example 1: Here, const _ = require(‘lodash’) is used to import the lodash library in the file." }, { "code": "// Requiring the lodash library const _ = require(\"lodash\"); // Original array var users = { 'meetu': { 'salary': 36000, 'active': true }, 'teetu': { 'salary': 40000, 'active': false }, 'seetu': { 'salary': 10000, 'active': true }}; // Using the _.findKey() methodlet found_elem = _.findKey(users, function(o) { return o.salary < 40000; }); // Printing the output console.log(found_elem);", "e": 38209, "s": 37802, "text": null }, { "code": null, "e": 38217, "s": 38209, "text": "Output:" }, { "code": null, "e": 38223, "s": 38217, "text": "meetu" }, { "code": null, "e": 38234, "s": 38223, "text": "Example 2:" }, { "code": "// Requiring the lodash library const _ = require(\"lodash\"); // Original array var users = { 'meetu': { 'salary': 36000, 'active': true }, 'teetu': { 'salary': 40000, 'active': false }, 'seetu': { 'salary': 10000, 'active': true }}; // Using the _.findKey() method// The `_.matches` iteratee shorthandlet found_elem = _.findKey(users, { 'salary': 10000, 'active': true }); // Printing the output console.log(found_elem);", "e": 38673, "s": 38234, "text": null }, { "code": null, "e": 38681, "s": 38673, "text": "Output:" }, { "code": null, "e": 38687, "s": 38681, "text": "seetu" }, { "code": null, "e": 38698, "s": 38687, "text": "Example 3:" }, { "code": "// Requiring the lodash library const _ = require(\"lodash\"); // Original array var users = { 'meetu': { 'salary': 36000, 'active': true }, 'teetu': { 'salary': 40000, 'active': false }, 'seetu': { 'salary': 10000, 'active': true }}; // Using the _.findKey() method// The `_.matchesProperty` iteratee shorthandlet found_elem = _.findKey(users, ['active', false]); // Printing the output console.log(found_elem);", "e": 39125, "s": 38698, "text": null }, { "code": null, "e": 39133, "s": 39125, "text": "Output:" }, { "code": null, "e": 39139, "s": 39133, "text": "teetu" }, { "code": null, "e": 39150, "s": 39139, "text": "Example 4:" }, { "code": "// Requiring the lodash library const _ = require(\"lodash\"); // Original array var users = { 'meetu': { 'salary': 36000, 'active': true }, 'teetu': { 'salary': 40000, 'active': false }, 'seetu': { 'salary': 10000, 'active': true }}; // Using the _.findKey() method// The `_.property` iteratee shorthandlet found_elem = _.findKey(users, 'active'); // Printing the output console.log(found_elem);", "e": 39561, "s": 39150, "text": null }, { "code": null, "e": 39569, "s": 39561, "text": "Output:" }, { "code": null, "e": 39575, "s": 39569, "text": "meetu" }, { "code": null, "e": 39682, "s": 39575, "text": "Note: This code will not work in normal JavaScript because it requires the library lodash to be installed." }, { "code": null, "e": 39700, "s": 39682, "text": "JavaScript-Lodash" }, { "code": null, "e": 39711, "s": 39700, "text": "JavaScript" }, { "code": null, "e": 39728, "s": 39711, "text": "Web Technologies" }, { "code": null, "e": 39826, "s": 39728, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 39835, "s": 39826, "text": "Comments" }, { "code": null, "e": 39848, "s": 39835, "text": "Old Comments" }, { "code": null, "e": 39909, "s": 39848, "text": "Difference between var, let and const keywords in JavaScript" }, { "code": null, "e": 39954, "s": 39909, "text": "Convert a string to an integer in JavaScript" }, { "code": null, "e": 40026, "s": 39954, "text": "Differences between Functional Components and Class Components in React" }, { "code": null, "e": 40095, "s": 40026, "text": "How to calculate the number of days between two dates in javascript?" }, { "code": null, "e": 40122, "s": 40095, "text": "File uploading in React.js" }, { "code": null, "e": 40178, "s": 40122, "text": "Top 10 Front End Developer Skills That You Need in 2022" }, { "code": null, "e": 40211, "s": 40178, "text": "Installation of Node.js on Linux" }, { "code": null, "e": 40273, "s": 40211, "text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills" }, { "code": null, "e": 40316, "s": 40273, "text": "How to fetch data from an API in ReactJS ?" } ]
HTML - Formatting
If you use a word processor, you must be familiar with the ability to make text bold, italicized, or underlined; these are just three of the ten options available to indicate how text can appear in HTML and XHTML. Anything that appears within <b>...</b> element, is displayed in bold as shown below − <!DOCTYPE html> <html> <head> <title>Bold Text Example</title> </head> <body> <p>The following word uses a <b>bold</b> typeface.</p> </body> </html> This will produce the following result − The following word uses a bold typeface. Anything that appears within <i>...</i> element is displayed in italicized as shown below − <!DOCTYPE html> <html> <head> <title>Italic Text Example</title> </head> <body> <p>The following word uses an <i>italicized</i> typeface.</p> </body> </html> This will produce the following result − The following word uses an italicized typeface. Anything that appears within <u>...</u> element, is displayed with underline as shown below − <!DOCTYPE html> <html> <head> <title>Underlined Text Example</title> </head> <body> <p>The following word uses an <u>underlined</u> typeface.</p> </body> </html> This will produce the following result − The following word uses an underlined typeface. Anything that appears within <strike>...</strike> element is displayed with strikethrough, which is a thin line through the text as shown below − <!DOCTYPE html> <html> <head> <title>Strike Text Example</title> </head> <body> <p>The following word uses a <strike>strikethrough</strike> typeface.</p> </body> </html> This will produce the following result − The following word uses a strikethrough typeface. The content of a <tt>...</tt> element is written in monospaced font. Most of the fonts are known as variable-width fonts because different letters are of different widths (for example, the letter 'm' is wider than the letter 'i'). In a monospaced font, however, each letter has the same width. <!DOCTYPE html> <html> <head> <title>Monospaced Font Example</title> </head> <body> <p>The following word uses a <tt>monospaced</tt> typeface.</p> </body> </html> This will produce the following result − The following word uses a monospaced typeface. The content of a <sup>...</sup> element is written in superscript; the font size used is the same size as the characters surrounding it but is displayed half a character's height above the other characters. <!DOCTYPE html> <html> <head> <title>Superscript Text Example</title> </head> <body> <p>The following word uses a <sup>superscript</sup> typeface.</p> </body> </html> This will produce the following result − The following word uses a superscript typeface. The content of a <sub>...</sub> element is written in subscript; the font size used is the same as the characters surrounding it, but is displayed half a character's height beneath the other characters. <!DOCTYPE html> <html> <head> <title>Subscript Text Example</title> </head> <body> <p>The following word uses a <sub>subscript</sub> typeface.</p> </body> </html> This will produce the following result − The following word uses a subscript typeface. Anything that appears within <ins>...</ins> element is displayed as inserted text. <!DOCTYPE html> <html> <head> <title>Inserted Text Example</title> </head> <body> <p>I want to drink <del>cola</del> <ins>wine</ins></p> </body> </html> This will produce the following result − I want to drink cola wine Anything that appears within <del>...</del> element, is displayed as deleted text. <!DOCTYPE html> <html> <head> <title>Deleted Text Example</title> </head> <body> <p>I want to drink <del>cola</del> <ins>wine</ins></p> </body> </html> This will produce the following result − I want to drink cola wine The content of the <big>...</big> element is displayed one font size larger than the rest of the text surrounding it as shown below − <!DOCTYPE html> <html> <head> <title>Larger Text Example</title> </head> <body> <p>The following word uses a <big>big</big> typeface.</p> </body> </html> This will produce the following result − The following word uses a big typeface. The content of the <small>...</small> element is displayed one font size smaller than the rest of the text surrounding it as shown below − <!DOCTYPE html> <html> <head> <title>Smaller Text Example</title> </head> <body> <p>The following word uses a <small>small</small> typeface.</p> </body> </html> This will produce the following result − The following word uses a small typeface. The <div> and <span> elements allow you to group together several elements to create sections or subsections of a page. For example, you might want to put all of the footnotes on a page within a <div> element to indicate that all of the elements within that <div> element relate to the footnotes. You might then attach a style to this <div> element so that they appear using a special set of style rules. <!DOCTYPE html> <html> <head> <title>Div Tag Example</title> </head> <body> <div id = "menu" align = "middle" > <a href = "/index.htm">HOME</a> | <a href = "/about/contact_us.htm">CONTACT</a> | <a href = "/about/index.htm">ABOUT</a> </div> <div id = "content" align = "left" > <h5>Content Articles</h5> <p>Actual content goes here.....</p> </div> </body> </html> This will produce the following result − Actual content goes here..... The <span> element, on the other hand, can be used to group inline elements only. So, if you have a part of a sentence or paragraph which you want to group together, you could use the <span> element as follows. <!DOCTYPE html> <html> <head> <title>Span Tag Example</title> </head> <body> <p>This is the example of <span style = "color:green">span tag</span> and the <span style = "color:red">div tag</span> alongwith CSS</p> </body> </html> This will produce the following result − This is the example of span tag and the div tag alongwith CSS These tags are commonly used with CSS to allow you to attach a style to a section of a page. 19 Lectures 2 hours Anadi Sharma 16 Lectures 1.5 hours Anadi Sharma 18 Lectures 1.5 hours Frahaan Hussain 57 Lectures 5.5 hours DigiFisk (Programming Is Fun) 54 Lectures 6 hours DigiFisk (Programming Is Fun) 45 Lectures 5.5 hours DigiFisk (Programming Is Fun) Print Add Notes Bookmark this page
[ { "code": null, "e": 2588, "s": 2374, "text": "If you use a word processor, you must be familiar with the ability to make text bold, italicized, or underlined; these are just three of the ten options available to indicate how text can appear in HTML and XHTML." }, { "code": null, "e": 2675, "s": 2588, "text": "Anything that appears within <b>...</b> element, is displayed in bold as shown below −" }, { "code": null, "e": 2853, "s": 2675, "text": "<!DOCTYPE html>\n<html>\n\n <head>\n <title>Bold Text Example</title>\n </head>\n\t\n <body>\n <p>The following word uses a <b>bold</b> typeface.</p>\n </body>\n\t\n</html>" }, { "code": null, "e": 2894, "s": 2853, "text": "This will produce the following result −" }, { "code": null, "e": 2935, "s": 2894, "text": "The following word uses a bold typeface." }, { "code": null, "e": 3027, "s": 2935, "text": "Anything that appears within <i>...</i> element is displayed in italicized as shown below −" }, { "code": null, "e": 3214, "s": 3027, "text": "<!DOCTYPE html>\n<html>\n\n <head>\n <title>Italic Text Example</title>\n </head>\n\t\n <body>\n <p>The following word uses an <i>italicized</i> typeface.</p>\n </body>\n\t\n</html>" }, { "code": null, "e": 3255, "s": 3214, "text": "This will produce the following result −" }, { "code": null, "e": 3303, "s": 3255, "text": "The following word uses an italicized typeface." }, { "code": null, "e": 3397, "s": 3303, "text": "Anything that appears within <u>...</u> element, is displayed with underline as shown below −" }, { "code": null, "e": 3588, "s": 3397, "text": "<!DOCTYPE html>\n<html>\n\n <head>\n <title>Underlined Text Example</title>\n </head>\n\t\n <body>\n <p>The following word uses an <u>underlined</u> typeface.</p>\n </body>\n\t\n</html>" }, { "code": null, "e": 3629, "s": 3588, "text": "This will produce the following result −" }, { "code": null, "e": 3677, "s": 3629, "text": "The following word uses an underlined typeface." }, { "code": null, "e": 3823, "s": 3677, "text": "Anything that appears within <strike>...</strike> element is displayed with strikethrough, which is a thin line through the text as shown below −" }, { "code": null, "e": 4022, "s": 3823, "text": "<!DOCTYPE html>\n<html>\n\n <head>\n <title>Strike Text Example</title>\n </head>\n\t\n <body>\n <p>The following word uses a <strike>strikethrough</strike> typeface.</p>\n </body>\n\t\n</html>" }, { "code": null, "e": 4063, "s": 4022, "text": "This will produce the following result −" }, { "code": null, "e": 4113, "s": 4063, "text": "The following word uses a strikethrough typeface." }, { "code": null, "e": 4407, "s": 4113, "text": "The content of a <tt>...</tt> element is written in monospaced font. Most of the fonts are known as variable-width fonts because different letters are of different widths (for example, the letter 'm' is wider than the letter 'i'). In a monospaced font, however, each letter has the same width." }, { "code": null, "e": 4599, "s": 4407, "text": "<!DOCTYPE html>\n<html>\n\n <head>\n <title>Monospaced Font Example</title>\n </head>\n\t\n <body>\n <p>The following word uses a <tt>monospaced</tt> typeface.</p>\n </body>\n\t\n</html>" }, { "code": null, "e": 4640, "s": 4599, "text": "This will produce the following result −" }, { "code": null, "e": 4687, "s": 4640, "text": "The following word uses a monospaced typeface." }, { "code": null, "e": 4894, "s": 4687, "text": "The content of a <sup>...</sup> element is written in superscript; the font size used is the same size as the characters surrounding it but is displayed half a character's height above the other characters." }, { "code": null, "e": 5090, "s": 4894, "text": "<!DOCTYPE html>\n<html>\n\n <head>\n <title>Superscript Text Example</title>\n </head>\n\t\n <body>\n <p>The following word uses a <sup>superscript</sup> typeface.</p>\n </body>\n\t\n</html>" }, { "code": null, "e": 5131, "s": 5090, "text": "This will produce the following result −" }, { "code": null, "e": 5179, "s": 5131, "text": "The following word uses a superscript typeface." }, { "code": null, "e": 5382, "s": 5179, "text": "The content of a <sub>...</sub> element is written in subscript; the font size used is the same as the characters surrounding it, but is displayed half a character's height beneath the other characters." }, { "code": null, "e": 5574, "s": 5382, "text": "<!DOCTYPE html>\n<html>\n\n <head>\n <title>Subscript Text Example</title>\n </head>\n\t\n <body>\n <p>The following word uses a <sub>subscript</sub> typeface.</p>\n </body>\n\t\n</html>" }, { "code": null, "e": 5615, "s": 5574, "text": "This will produce the following result −" }, { "code": null, "e": 5661, "s": 5615, "text": "The following word uses a subscript typeface." }, { "code": null, "e": 5744, "s": 5661, "text": "Anything that appears within <ins>...</ins> element is displayed as inserted text." }, { "code": null, "e": 5926, "s": 5744, "text": "<!DOCTYPE html>\n<html>\n\n <head>\n <title>Inserted Text Example</title>\n </head>\n\t\n <body>\n <p>I want to drink <del>cola</del> <ins>wine</ins></p>\n </body>\n\t\n</html>" }, { "code": null, "e": 5967, "s": 5926, "text": "This will produce the following result −" }, { "code": null, "e": 5993, "s": 5967, "text": "I want to drink cola wine" }, { "code": null, "e": 6076, "s": 5993, "text": "Anything that appears within <del>...</del> element, is displayed as deleted text." }, { "code": null, "e": 6257, "s": 6076, "text": "<!DOCTYPE html>\n<html>\n\n <head>\n <title>Deleted Text Example</title>\n </head>\n\t\n <body>\n <p>I want to drink <del>cola</del> <ins>wine</ins></p>\n </body>\n\t\n</html>" }, { "code": null, "e": 6298, "s": 6257, "text": "This will produce the following result −" }, { "code": null, "e": 6324, "s": 6298, "text": "I want to drink cola wine" }, { "code": null, "e": 6458, "s": 6324, "text": "The content of the <big>...</big> element is displayed one font size larger than the rest of the text surrounding it as shown below −" }, { "code": null, "e": 6641, "s": 6458, "text": "<!DOCTYPE html>\n<html>\n\n <head>\n <title>Larger Text Example</title>\n </head>\n\t\n <body>\n <p>The following word uses a <big>big</big> typeface.</p>\n </body>\n\t\n</html>" }, { "code": null, "e": 6682, "s": 6641, "text": "This will produce the following result −" }, { "code": null, "e": 6722, "s": 6682, "text": "The following word uses a big typeface." }, { "code": null, "e": 6861, "s": 6722, "text": "The content of the <small>...</small> element is displayed one font size smaller than the rest of the text surrounding it as shown below −" }, { "code": null, "e": 7049, "s": 6861, "text": "<!DOCTYPE html>\n<html>\n\n <head>\n <title>Smaller Text Example</title>\n </head>\n\n <body>\n <p>The following word uses a <small>small</small> typeface.</p>\n </body>\n\n</html>" }, { "code": null, "e": 7090, "s": 7049, "text": "This will produce the following result −" }, { "code": null, "e": 7132, "s": 7090, "text": "The following word uses a small typeface." }, { "code": null, "e": 7252, "s": 7132, "text": "The <div> and <span> elements allow you to group together several elements to create sections or subsections of a page." }, { "code": null, "e": 7537, "s": 7252, "text": "For example, you might want to put all of the footnotes on a page within a <div> element to indicate that all of the elements within that <div> element relate to the footnotes. You might then attach a style to this <div> element so that they appear using a special set of style rules." }, { "code": null, "e": 7995, "s": 7537, "text": "<!DOCTYPE html>\n<html>\n\n <head>\n <title>Div Tag Example</title>\n </head>\n\t\n <body>\n <div id = \"menu\" align = \"middle\" >\n <a href = \"/index.htm\">HOME</a> | \n <a href = \"/about/contact_us.htm\">CONTACT</a> | \n <a href = \"/about/index.htm\">ABOUT</a>\n </div>\n\n <div id = \"content\" align = \"left\" >\n <h5>Content Articles</h5>\n <p>Actual content goes here.....</p>\n </div>\n </body>\n\t\n</html>" }, { "code": null, "e": 8036, "s": 7995, "text": "This will produce the following result −" }, { "code": null, "e": 8066, "s": 8036, "text": "Actual content goes here....." }, { "code": null, "e": 8277, "s": 8066, "text": "The <span> element, on the other hand, can be used to group inline elements only. So, if you have a part of a sentence or paragraph which you want to group together, you could use the <span> element as follows." }, { "code": null, "e": 8545, "s": 8277, "text": "<!DOCTYPE html>\n<html>\n\n <head>\n <title>Span Tag Example</title>\n </head>\n\t\n <body>\n <p>This is the example of <span style = \"color:green\">span tag</span>\n and the <span style = \"color:red\">div tag</span> alongwith CSS</p>\n </body>\n\t\n</html>" }, { "code": null, "e": 8586, "s": 8545, "text": "This will produce the following result −" }, { "code": null, "e": 8648, "s": 8586, "text": "This is the example of span tag and the div tag alongwith CSS" }, { "code": null, "e": 8741, "s": 8648, "text": "These tags are commonly used with CSS to allow you to attach a style to a section of a page." }, { "code": null, "e": 8774, "s": 8741, "text": "\n 19 Lectures \n 2 hours \n" }, { "code": null, "e": 8788, "s": 8774, "text": " Anadi Sharma" }, { "code": null, "e": 8823, "s": 8788, "text": "\n 16 Lectures \n 1.5 hours \n" }, { "code": null, "e": 8837, "s": 8823, "text": " Anadi Sharma" }, { "code": null, "e": 8872, "s": 8837, "text": "\n 18 Lectures \n 1.5 hours \n" }, { "code": null, "e": 8889, "s": 8872, "text": " Frahaan Hussain" }, { "code": null, "e": 8924, "s": 8889, "text": "\n 57 Lectures \n 5.5 hours \n" }, { "code": null, "e": 8955, "s": 8924, "text": " DigiFisk (Programming Is Fun)" }, { "code": null, "e": 8988, "s": 8955, "text": "\n 54 Lectures \n 6 hours \n" }, { "code": null, "e": 9019, "s": 8988, "text": " DigiFisk (Programming Is Fun)" }, { "code": null, "e": 9054, "s": 9019, "text": "\n 45 Lectures \n 5.5 hours \n" }, { "code": null, "e": 9085, "s": 9054, "text": " DigiFisk (Programming Is Fun)" }, { "code": null, "e": 9092, "s": 9085, "text": " Print" }, { "code": null, "e": 9103, "s": 9092, "text": " Add Notes" } ]
Servlets - Session Tracking
HTTP is a "stateless" protocol which means each time a client retrieves a Web page, the client opens a separate connection to the Web server and the server automatically does not keep any record of previous client request. Still there are following three ways to maintain session between web client and web server − A webserver can assign a unique session ID as a cookie to each web client and for subsequent requests from the client they can be recognized using the recieved cookie. This may not be an effective way because many time browser does not support a cookie, so I would not recommend to use this procedure to maintain the sessions. A web server can send a hidden HTML form field along with a unique session ID as follows − <input type = "hidden" name = "sessionid" value = "12345"> This entry means that, when the form is submitted, the specified name and value are automatically included in the GET or POST data. Each time when web browser sends request back, then session_id value can be used to keep the track of different web browsers. This could be an effective way of keeping track of the session but clicking on a regular (<A HREF...>) hypertext link does not result in a form submission, so hidden form fields also cannot support general session tracking. You can append some extra data on the end of each URL that identifies the session, and the server can associate that session identifier with data it has stored about that session. For example, with http://tutorialspoint.com/file.htm;sessionid = 12345, the session identifier is attached as sessionid = 12345 which can be accessed at the web server to identify the client. URL rewriting is a better way to maintain sessions and it works even when browsers don't support cookies. The drawback of URL re-writing is that you would have to generate every URL dynamically to assign a session ID, even in case of a simple static HTML page. Apart from the above mentioned three ways, servlet provides HttpSession Interface which provides a way to identify a user across more than one page request or visit to a Web site and to store information about that user. The servlet container uses this interface to create a session between an HTTP client and an HTTP server. The session persists for a specified time period, across more than one connection or page request from the user. You would get HttpSession object by calling the public method getSession() of HttpServletRequest, as below − HttpSession session = request.getSession(); You need to call request.getSession() before you send any document content to the client. Here is a summary of the important methods available through HttpSession object − public Object getAttribute(String name) This method returns the object bound with the specified name in this session, or null if no object is bound under the name. public Enumeration getAttributeNames() This method returns an Enumeration of String objects containing the names of all the objects bound to this session. public long getCreationTime() This method returns the time when this session was created, measured in milliseconds since midnight January 1, 1970 GMT. public String getId() This method returns a string containing the unique identifier assigned to this session. public long getLastAccessedTime() This method returns the last accessed time of the session, in the format of milliseconds since midnight January 1, 1970 GMT public int getMaxInactiveInterval() This method returns the maximum time interval (seconds), that the servlet container will keep the session open between client accesses. public void invalidate() This method invalidates this session and unbinds any objects bound to it. public boolean isNew( This method returns true if the client does not yet know about the session or if the client chooses not to join the session. public void removeAttribute(String name) This method removes the object bound with the specified name from this session. public void setAttribute(String name, Object value) This method binds an object to this session, using the name specified. public void setMaxInactiveInterval(int interval) This method specifies the time, in seconds, between client requests before the servlet container will invalidate this session. This example describes how to use the HttpSession object to find out the creation time and the last-accessed time for a session. We would associate a new session with the request if one does not already exist. // Import required java libraries import java.io.*; import javax.servlet.*; import javax.servlet.http.*; import java.util.*; // Extend HttpServlet class public class SessionTrack extends HttpServlet { public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // Create a session object if it is already not created. HttpSession session = request.getSession(true); // Get session creation time. Date createTime = new Date(session.getCreationTime()); // Get last access time of this web page. Date lastAccessTime = new Date(session.getLastAccessedTime()); String title = "Welcome Back to my website"; Integer visitCount = new Integer(0); String visitCountKey = new String("visitCount"); String userIDKey = new String("userID"); String userID = new String("ABCD"); // Check if this is new comer on your web page. if (session.isNew()) { title = "Welcome to my website"; session.setAttribute(userIDKey, userID); } else { visitCount = (Integer)session.getAttribute(visitCountKey); visitCount = visitCount + 1; userID = (String)session.getAttribute(userIDKey); } session.setAttribute(visitCountKey, visitCount); // Set response content type response.setContentType("text/html"); PrintWriter out = response.getWriter(); String docType = "<!doctype html public \"-//w3c//dtd html 4.0 " + "transitional//en\">\n"; out.println(docType + "<html>\n" + "<head><title>" + title + "</title></head>\n" + "<body bgcolor = \"#f0f0f0\">\n" + "<h1 align = \"center\">" + title + "</h1>\n" + "<h2 align = \"center\">Session Infomation</h2>\n" + "<table border = \"1\" align = \"center\">\n" + "<tr bgcolor = \"#949494\">\n" + " <th>Session info</th><th>value</th> </tr>\n" + "<tr>\n" + " <td>id</td>\n" + " <td>" + session.getId() + "</td> </tr>\n" + "<tr>\n" + " <td>Creation Time</td>\n" + " <td>" + createTime + " </td> </tr>\n" + "<tr>\n" + " <td>Time of Last Access</td>\n" + " <td>" + lastAccessTime + " </td> </tr>\n" + "<tr>\n" + " <td>User ID</td>\n" + " <td>" + userID + " </td> </tr>\n" + "<tr>\n" + " <td>Number of visits</td>\n" + " <td>" + visitCount + "</td> </tr>\n" + "</table>\n" + "</body> </html>" ); } } Compile the above servlet SessionTrack and create appropriate entry in web.xml file. Now running http://localhost:8080/SessionTrack would display the following result when you would run for the first time − Welcome to my website Session Infomation Session info value id 0AE3EC93FF44E3C525B4351B77ABB2D5 Creation Time Tue Jun 08 17:26:40 GMT+04:00 2010 Time of Last Access Tue Jun 08 17:26:40 GMT+04:00 2010 User ID ABCD Number of visits 0 Now try to run the same servlet for second time, it would display following result. Welcome Back to my website Session Infomation info type value id 0AE3EC93FF44E3C525B4351B77ABB2D5 Creation Time Tue Jun 08 17:26:40 GMT+04:00 2010 Time of Last Access Tue Jun 08 17:26:40 GMT+04:00 2010 User ID ABCD Number of visits 1 When you are done with a user's session data, you have several options − Remove a particular attribute − You can call public void removeAttribute(String name) method to delete the value associated with a particular key. Remove a particular attribute − You can call public void removeAttribute(String name) method to delete the value associated with a particular key. Delete the whole session − You can call public void invalidate() method to discard an entire session. Delete the whole session − You can call public void invalidate() method to discard an entire session. Setting Session timeout − You can call public void setMaxInactiveInterval(int interval) method to set the timeout for a session individually. Setting Session timeout − You can call public void setMaxInactiveInterval(int interval) method to set the timeout for a session individually. Log the user out − The servers that support servlets 2.4, you can call logout to log the client out of the Web server and invalidate all sessions belonging to all the users. Log the user out − The servers that support servlets 2.4, you can call logout to log the client out of the Web server and invalidate all sessions belonging to all the users. web.xml Configuration − If you are using Tomcat, apart from the above mentioned methods, you can configure session time out in web.xml file as follows. web.xml Configuration − If you are using Tomcat, apart from the above mentioned methods, you can configure session time out in web.xml file as follows. <session-config> <session-timeout>15</session-timeout> </session-config> The timeout is expressed as minutes, and overrides the default timeout which is 30 minutes in Tomcat. The getMaxInactiveInterval( ) method in a servlet returns the timeout period for that session in seconds. So if your session is configured in web.xml for 15 minutes, getMaxInactiveInterval( ) returns 900. 41 Lectures 4.5 hours Karthikeya T 42 Lectures 5.5 hours TELCOMA Global 15 Lectures 3 hours TELCOMA Global 31 Lectures 12.5 hours Uplatz 38 Lectures 4.5 hours Packt Publishing Print Add Notes Bookmark this page
[ { "code": null, "e": 2408, "s": 2185, "text": "HTTP is a \"stateless\" protocol which means each time a client retrieves a Web page, the client opens a separate connection to the Web server and the server automatically does not keep any record of previous client request." }, { "code": null, "e": 2501, "s": 2408, "text": "Still there are following three ways to maintain session between web client and web server −" }, { "code": null, "e": 2669, "s": 2501, "text": "A webserver can assign a unique session ID as a cookie to each web client and for subsequent requests from the client they can be recognized using the recieved cookie." }, { "code": null, "e": 2828, "s": 2669, "text": "This may not be an effective way because many time browser does not support a cookie, so I would not recommend to use this procedure to maintain the sessions." }, { "code": null, "e": 2919, "s": 2828, "text": "A web server can send a hidden HTML form field along with a unique session ID as follows −" }, { "code": null, "e": 2979, "s": 2919, "text": "<input type = \"hidden\" name = \"sessionid\" value = \"12345\">\n" }, { "code": null, "e": 3237, "s": 2979, "text": "This entry means that, when the form is submitted, the specified name and value are automatically included in the GET or POST data. Each time when web browser sends request back, then session_id value can be used to keep the track of different web browsers." }, { "code": null, "e": 3461, "s": 3237, "text": "This could be an effective way of keeping track of the session but clicking on a regular (<A HREF...>) hypertext link does not result in a form submission, so hidden form fields also cannot support general session tracking." }, { "code": null, "e": 3641, "s": 3461, "text": "You can append some extra data on the end of each URL that identifies the session, and the server can associate that session identifier with data it has stored about that session." }, { "code": null, "e": 3833, "s": 3641, "text": "For example, with http://tutorialspoint.com/file.htm;sessionid = 12345, the session identifier is attached as sessionid = 12345 which can be accessed at the web server to identify the client." }, { "code": null, "e": 4095, "s": 3833, "text": "URL rewriting is a better way to maintain sessions and it works even when browsers don't support cookies. The drawback of URL re-writing is that you would have to generate every URL dynamically to assign a session ID, even in case of a simple static HTML page." }, { "code": null, "e": 4316, "s": 4095, "text": "Apart from the above mentioned three ways, servlet provides HttpSession Interface which provides a way to identify a user across more than one page request or visit to a Web site and to store information about that user." }, { "code": null, "e": 4534, "s": 4316, "text": "The servlet container uses this interface to create a session between an HTTP client and an HTTP server. The session persists for a specified time period, across more than one connection or page request from the user." }, { "code": null, "e": 4643, "s": 4534, "text": "You would get HttpSession object by calling the public method getSession() of HttpServletRequest, as below −" }, { "code": null, "e": 4687, "s": 4643, "text": "HttpSession session = request.getSession();" }, { "code": null, "e": 4859, "s": 4687, "text": "You need to call request.getSession() before you send any document content to the client. Here is a summary of the important methods available through HttpSession object −" }, { "code": null, "e": 4900, "s": 4859, "text": "public Object getAttribute(String name) " }, { "code": null, "e": 5024, "s": 4900, "text": "This method returns the object bound with the specified name in this session, or null if no object is bound under the name." }, { "code": null, "e": 5063, "s": 5024, "text": "public Enumeration getAttributeNames()" }, { "code": null, "e": 5179, "s": 5063, "text": "This method returns an Enumeration of String objects containing the names of all the objects bound to this session." }, { "code": null, "e": 5210, "s": 5179, "text": "public long getCreationTime() " }, { "code": null, "e": 5331, "s": 5210, "text": "This method returns the time when this session was created, measured in milliseconds since midnight January 1, 1970 GMT." }, { "code": null, "e": 5354, "s": 5331, "text": "public String getId() " }, { "code": null, "e": 5442, "s": 5354, "text": "This method returns a string containing the unique identifier assigned to this session." }, { "code": null, "e": 5477, "s": 5442, "text": "public long getLastAccessedTime() " }, { "code": null, "e": 5601, "s": 5477, "text": "This method returns the last accessed time of the session, in the format of milliseconds since midnight January 1, 1970 GMT" }, { "code": null, "e": 5638, "s": 5601, "text": "public int getMaxInactiveInterval() " }, { "code": null, "e": 5774, "s": 5638, "text": "This method returns the maximum time interval (seconds), that the servlet container will keep the session open between client accesses." }, { "code": null, "e": 5800, "s": 5774, "text": "public void invalidate() " }, { "code": null, "e": 5874, "s": 5800, "text": "This method invalidates this session and unbinds any objects bound to it." }, { "code": null, "e": 5897, "s": 5874, "text": "public boolean isNew( " }, { "code": null, "e": 6022, "s": 5897, "text": "This method returns true if the client does not yet know about the session or if the client chooses not to join the session." }, { "code": null, "e": 6064, "s": 6022, "text": "public void removeAttribute(String name) " }, { "code": null, "e": 6145, "s": 6064, "text": "This method removes the object bound with the specified name from this session. " }, { "code": null, "e": 6198, "s": 6145, "text": "public void setAttribute(String name, Object value) " }, { "code": null, "e": 6269, "s": 6198, "text": "This method binds an object to this session, using the name specified." }, { "code": null, "e": 6319, "s": 6269, "text": "public void setMaxInactiveInterval(int interval) " }, { "code": null, "e": 6447, "s": 6319, "text": "This method specifies the time, in seconds, between client requests before the servlet container will invalidate this session. " }, { "code": null, "e": 6657, "s": 6447, "text": "This example describes how to use the HttpSession object to find out the creation time and the last-accessed time for a session. We would associate a new session with the request if one does not already exist." }, { "code": null, "e": 9770, "s": 6657, "text": "// Import required java libraries\nimport java.io.*;\nimport javax.servlet.*;\nimport javax.servlet.http.*;\nimport java.util.*;\n \n// Extend HttpServlet class\npublic class SessionTrack extends HttpServlet {\n \n public void doGet(HttpServletRequest request, HttpServletResponse response)\n throws ServletException, IOException {\n \n // Create a session object if it is already not created.\n HttpSession session = request.getSession(true);\n \n // Get session creation time.\n Date createTime = new Date(session.getCreationTime());\n \n // Get last access time of this web page.\n Date lastAccessTime = new Date(session.getLastAccessedTime());\n\n String title = \"Welcome Back to my website\";\n Integer visitCount = new Integer(0);\n String visitCountKey = new String(\"visitCount\");\n String userIDKey = new String(\"userID\");\n String userID = new String(\"ABCD\");\n\n // Check if this is new comer on your web page.\n if (session.isNew()) {\n title = \"Welcome to my website\";\n session.setAttribute(userIDKey, userID);\n } else {\n visitCount = (Integer)session.getAttribute(visitCountKey);\n visitCount = visitCount + 1;\n userID = (String)session.getAttribute(userIDKey);\n }\n session.setAttribute(visitCountKey, visitCount);\n\n // Set response content type\n response.setContentType(\"text/html\");\n PrintWriter out = response.getWriter();\n\n String docType =\n \"<!doctype html public \\\"-//w3c//dtd html 4.0 \" +\n \"transitional//en\\\">\\n\";\n\n out.println(docType +\n \"<html>\\n\" +\n \"<head><title>\" + title + \"</title></head>\\n\" +\n \n \"<body bgcolor = \\\"#f0f0f0\\\">\\n\" +\n \"<h1 align = \\\"center\\\">\" + title + \"</h1>\\n\" +\n \"<h2 align = \\\"center\\\">Session Infomation</h2>\\n\" +\n \"<table border = \\\"1\\\" align = \\\"center\\\">\\n\" +\n \n \"<tr bgcolor = \\\"#949494\\\">\\n\" +\n \" <th>Session info</th><th>value</th>\n </tr>\\n\" +\n \n \"<tr>\\n\" +\n \" <td>id</td>\\n\" +\n \" <td>\" + session.getId() + \"</td>\n </tr>\\n\" +\n \n \"<tr>\\n\" +\n \" <td>Creation Time</td>\\n\" +\n \" <td>\" + createTime + \" </td>\n </tr>\\n\" +\n \n \"<tr>\\n\" +\n \" <td>Time of Last Access</td>\\n\" +\n \" <td>\" + lastAccessTime + \" </td>\n </tr>\\n\" +\n \n \"<tr>\\n\" +\n \" <td>User ID</td>\\n\" +\n \" <td>\" + userID + \" </td>\n </tr>\\n\" +\n \n \"<tr>\\n\" +\n \" <td>Number of visits</td>\\n\" +\n \" <td>\" + visitCount + \"</td>\n </tr>\\n\" +\n \"</table>\\n\" +\n \"</body>\n </html>\"\n );\n }\n}" }, { "code": null, "e": 9978, "s": 9770, "text": "Compile the above servlet SessionTrack and create appropriate entry in web.xml file. Now running http://localhost:8080/SessionTrack would display the following result when you would run for the first time −" }, { "code": null, "e": 10231, "s": 9978, "text": "Welcome to my website\nSession Infomation\n\n\nSession info\nvalue\n\n\nid\n0AE3EC93FF44E3C525B4351B77ABB2D5\n\n\nCreation Time\nTue Jun 08 17:26:40 GMT+04:00 2010 \n\n\nTime of Last Access\nTue Jun 08 17:26:40 GMT+04:00 2010 \n\n\nUser ID\nABCD \n\n\nNumber of visits\n0\n\n\n" }, { "code": null, "e": 10315, "s": 10231, "text": "Now try to run the same servlet for second time, it would display following result." }, { "code": null, "e": 10570, "s": 10315, "text": "Welcome Back to my website\nSession Infomation\n\n\ninfo type\nvalue\n\n\nid\n0AE3EC93FF44E3C525B4351B77ABB2D5\n\n\nCreation Time\nTue Jun 08 17:26:40 GMT+04:00 2010 \n\n\nTime of Last Access\nTue Jun 08 17:26:40 GMT+04:00 2010 \n\n\nUser ID\nABCD \n\n\nNumber of visits\n1\n\n\n" }, { "code": null, "e": 10643, "s": 10570, "text": "When you are done with a user's session data, you have several options −" }, { "code": null, "e": 10790, "s": 10643, "text": "Remove a particular attribute − You can call public void removeAttribute(String name) method to delete the value associated with a particular key." }, { "code": null, "e": 10937, "s": 10790, "text": "Remove a particular attribute − You can call public void removeAttribute(String name) method to delete the value associated with a particular key." }, { "code": null, "e": 11039, "s": 10937, "text": "Delete the whole session − You can call public void invalidate() method to discard an entire session." }, { "code": null, "e": 11141, "s": 11039, "text": "Delete the whole session − You can call public void invalidate() method to discard an entire session." }, { "code": null, "e": 11283, "s": 11141, "text": "Setting Session timeout − You can call public void setMaxInactiveInterval(int interval) method to set the timeout for a session individually." }, { "code": null, "e": 11425, "s": 11283, "text": "Setting Session timeout − You can call public void setMaxInactiveInterval(int interval) method to set the timeout for a session individually." }, { "code": null, "e": 11599, "s": 11425, "text": "Log the user out − The servers that support servlets 2.4, you can call logout to log the client out of the Web server and invalidate all sessions belonging to all the users." }, { "code": null, "e": 11773, "s": 11599, "text": "Log the user out − The servers that support servlets 2.4, you can call logout to log the client out of the Web server and invalidate all sessions belonging to all the users." }, { "code": null, "e": 11925, "s": 11773, "text": "web.xml Configuration − If you are using Tomcat, apart from the above mentioned methods, you can configure session time out in web.xml file as follows." }, { "code": null, "e": 12077, "s": 11925, "text": "web.xml Configuration − If you are using Tomcat, apart from the above mentioned methods, you can configure session time out in web.xml file as follows." }, { "code": null, "e": 12153, "s": 12077, "text": "<session-config>\n <session-timeout>15</session-timeout>\n</session-config>" }, { "code": null, "e": 12256, "s": 12153, "text": "The timeout is expressed as minutes, and overrides the default timeout which is 30 minutes in Tomcat. " }, { "code": null, "e": 12461, "s": 12256, "text": "The getMaxInactiveInterval( ) method in a servlet returns the timeout period for that session in seconds. So if your session is configured in web.xml for 15 minutes, getMaxInactiveInterval( ) returns 900." }, { "code": null, "e": 12496, "s": 12461, "text": "\n 41 Lectures \n 4.5 hours \n" }, { "code": null, "e": 12510, "s": 12496, "text": " Karthikeya T" }, { "code": null, "e": 12545, "s": 12510, "text": "\n 42 Lectures \n 5.5 hours \n" }, { "code": null, "e": 12561, "s": 12545, "text": " TELCOMA Global" }, { "code": null, "e": 12594, "s": 12561, "text": "\n 15 Lectures \n 3 hours \n" }, { "code": null, "e": 12610, "s": 12594, "text": " TELCOMA Global" }, { "code": null, "e": 12646, "s": 12610, "text": "\n 31 Lectures \n 12.5 hours \n" }, { "code": null, "e": 12654, "s": 12646, "text": " Uplatz" }, { "code": null, "e": 12689, "s": 12654, "text": "\n 38 Lectures \n 4.5 hours \n" }, { "code": null, "e": 12707, "s": 12689, "text": " Packt Publishing" }, { "code": null, "e": 12714, "s": 12707, "text": " Print" }, { "code": null, "e": 12725, "s": 12714, "text": " Add Notes" } ]
How to plot the confidence interval of the regression model using ggplot2 with transparency in R?
To plot the confidence interval of the regression model, we can use geom_ribbon function of ggplot2 package but by default it will have dark grey color. It can become transparent with the help of alpha argument inside the same function, the alpha argument can be adjusted as per our requirement but the most recommended value by me is 0.2. Consider the below data frame − Live Demo > x<-rnorm(20,25,2.24) > y<-rnorm(20,30,1.27) > df<-data.frame(x,y) > df x y 1 22.67102 29.37057 2 21.59415 29.54027 3 20.56817 28.27672 4 24.97228 31.38193 5 21.41651 31.86811 6 23.94699 28.22775 7 23.90155 30.03807 8 26.57466 29.32966 9 22.32727 32.10336 10 30.04399 31.76219 11 26.84023 30.12260 12 23.73143 31.71349 13 22.57145 29.10705 14 25.86364 30.61687 15 25.17939 30.79297 16 22.49971 27.51084 17 22.01182 29.96766 18 23.93069 30.31963 19 19.57823 30.01839 20 22.90537 32.30613 Loading ggplot2 package and creating a regression model plot with confidence interval − > library(ggplot2) > ggplot(df,aes(x,y))+geom_point()+geom_ribbon(stat="smooth",method="lm",se=TRUE)+geom_line(stat="smooth",method="lm") Creating the plot with transparent confidence interval − > ggplot(df,aes(x,y))+geom_point()+geom_ribbon(stat="smooth",method="lm",se=TRUE,alpha=0.2)+geom_line(stat="smooth",method="lm")
[ { "code": null, "e": 1402, "s": 1062, "text": "To plot the confidence interval of the regression model, we can use geom_ribbon function of ggplot2 package but by default it will have dark grey color. It can become transparent with the help of alpha argument inside the same function, the alpha argument can be adjusted as per our requirement but the most recommended value by me is 0.2." }, { "code": null, "e": 1434, "s": 1402, "text": "Consider the below data frame −" }, { "code": null, "e": 1444, "s": 1434, "text": "Live Demo" }, { "code": null, "e": 1517, "s": 1444, "text": "> x<-rnorm(20,25,2.24)\n> y<-rnorm(20,30,1.27)\n> df<-data.frame(x,y)\n> df" }, { "code": null, "e": 1946, "s": 1517, "text": " x y\n1 22.67102 29.37057\n2 21.59415 29.54027\n3 20.56817 28.27672\n4 24.97228 31.38193\n5 21.41651 31.86811\n6 23.94699 28.22775\n7 23.90155 30.03807\n8 26.57466 29.32966\n9 22.32727 32.10336\n10 30.04399 31.76219\n11 26.84023 30.12260\n12 23.73143 31.71349\n13 22.57145 29.10705\n14 25.86364 30.61687\n15 25.17939 30.79297\n16 22.49971 27.51084\n17 22.01182 29.96766\n18 23.93069 30.31963\n19 19.57823 30.01839\n20 22.90537 32.30613" }, { "code": null, "e": 2034, "s": 1946, "text": "Loading ggplot2 package and creating a regression model plot with confidence interval −" }, { "code": null, "e": 2172, "s": 2034, "text": "> library(ggplot2)\n> ggplot(df,aes(x,y))+geom_point()+geom_ribbon(stat=\"smooth\",method=\"lm\",se=TRUE)+geom_line(stat=\"smooth\",method=\"lm\")" }, { "code": null, "e": 2229, "s": 2172, "text": "Creating the plot with transparent confidence interval −" }, { "code": null, "e": 2358, "s": 2229, "text": "> ggplot(df,aes(x,y))+geom_point()+geom_ribbon(stat=\"smooth\",method=\"lm\",se=TRUE,alpha=0.2)+geom_line(stat=\"smooth\",method=\"lm\")" } ]
Inorder Traversal and BST | Practice | GeeksforGeeks
Given an array arr of size N, write a program that returns 1 if array represents Inorder traversal of a BST, else returns 0. Note: All keys in BST must be unique. Example 1: Input: N = 3 arr = {2, 4, 5} Output: 1 Explaination: Given arr representing inorder traversal of a BST. Example 2: Input: N = 3 arr = {2, 4, 1} Output: 0 Explaination: Given arr is not representing inorder traversal of a BST. Your Task: You don't need to read input or print anything. Your task is to complete the function isRepresentingBST() which takes the array arr[] and its size N as input parameters and returns 1 if array represents Inorder traversal of a BST, else returns 0. Expected Time Complexity: O(N) Expected Auxiliary Space: O(1) Constraints: 1 ≤ N ≤ 103 1 ≤ arr[i] ≤ 103 0 vrajeshmodi991 month ago Recursive approach: int isRepresentingBST(int arr[], int N) { if(N==0)return 1; if(arr[N-1]<=arr[N-2])return 0; return isRepresentingBST(arr,N-1); } 0 vrajeshmodi991 month ago int isRepresentingBST(int arr[], int N) { for(int i=0;i<N-1;i++){ if(arr[i]>=arr[i+1]){ return 0; } } return 1; } 0 guptaram4656912 months ago { set<int> s; for (int i = 0; i < N - 1; i++) { s.insert(arr[i]); if (arr[i] > arr[i + 1]) { return 0; } } s.insert(arr[N - 1]); if (s.size() != N) { return 0; } return 1; } 0 detroix072 months ago int isRepresentingBST(int arr[], int n) { for(int i=1;i<n;i++){ if(arr[i] <= arr[i-1]) return 0; } return 1; } 0 harshit68rocking2 months ago int isRepresentingBST(int arr[], int N) { // code here int c = arr[0]; for(int i =1;i<N;i++){ if(arr[i] <= c) return 0; else c= arr[i]; } return 1; } 0 singhsrijan8093 months ago JAVA SOLUTION 0.3/5.3 sec PLAYERG SOLUTIONS static int isRepresentingBST(int a[], int n) { // code here if(n==1) return 1; for(int i=1;i<n;i++){ if(a[i-1]>=a[i]) return 0; } return 1; } LIVE GREEN PLAYERG..!!!!!!!!!PGxJAANWAR 0 kronizerdeltac3 months ago C++ Solution - 0 ms passed. int isRepresentingBST(int arr[], int N) { if(N == 1) return 1; for(int i = 1; i < N; i++) { int prev = arr[i - 1], curr = arr[i]; if(prev >= curr) return 0; } return 1; } 0 chessnoobdj3 months ago C++ one liner STL int isRepresentingBST(int arr[], int N) { return is_sorted(arr, arr+N, [](int a, int b){ return a<=b; }); } +1 badgujarsachin836 months ago int isRepresentingBST(int arr[], int N) { // code here for(int i=0;i<N-1;i++){ if(arr[i]>=arr[i+1]){ return 0; } } return 1; } -1 vs5094117 months ago not accepting the correct solution We strongly recommend solving this problem on your own before viewing its editorial. Do you still want to view the editorial? Login to access your submissions. Problem Contest Reset the IDE using the second button on the top right corner. Avoid using static/global variables in your code as your code is tested against multiple test cases and these tend to retain their previous values. Passing the Sample/Custom Test cases does not guarantee the correctness of code. On submission, your code is tested against multiple test cases consisting of all possible corner cases and stress constraints. You can access the hints to get an idea about what is expected of you as well as the final solution code. You can view the solutions submitted by other users from the submission tab.
[ { "code": null, "e": 401, "s": 238, "text": "Given an array arr of size N, write a program that returns 1 if array represents Inorder traversal of a BST, else returns 0.\nNote: All keys in BST must be unique." }, { "code": null, "e": 413, "s": 401, "text": "\nExample 1:" }, { "code": null, "e": 518, "s": 413, "text": "Input:\nN = 3\narr = {2, 4, 5}\nOutput: 1\nExplaination: Given arr representing\ninorder traversal of a BST.\n" }, { "code": null, "e": 530, "s": 518, "text": "\nExample 2:" }, { "code": null, "e": 641, "s": 530, "text": "Input:\nN = 3\narr = {2, 4, 1}\nOutput: 0\nExplaination: Given arr is not representing\ninorder traversal of a BST." }, { "code": null, "e": 901, "s": 641, "text": "\nYour Task:\nYou don't need to read input or print anything. Your task is to complete the function isRepresentingBST() which takes the array arr[] and its size N as input parameters and returns 1 if array represents Inorder traversal of a BST, else returns 0. " }, { "code": null, "e": 964, "s": 901, "text": "\nExpected Time Complexity: O(N)\nExpected Auxiliary Space: O(1)" }, { "code": null, "e": 1007, "s": 964, "text": "\nConstraints:\n1 ≤ N ≤ 103\n1 ≤ arr[i] ≤ 103" }, { "code": null, "e": 1009, "s": 1007, "text": "0" }, { "code": null, "e": 1034, "s": 1009, "text": "vrajeshmodi991 month ago" }, { "code": null, "e": 1054, "s": 1034, "text": "Recursive approach:" }, { "code": null, "e": 1231, "s": 1054, "text": "int isRepresentingBST(int arr[], int N)\n {\n if(N==0)return 1;\n \n if(arr[N-1]<=arr[N-2])return 0;\n \n return isRepresentingBST(arr,N-1);\n }" }, { "code": null, "e": 1233, "s": 1231, "text": "0" }, { "code": null, "e": 1258, "s": 1233, "text": "vrajeshmodi991 month ago" }, { "code": null, "e": 1445, "s": 1258, "text": " int isRepresentingBST(int arr[], int N)\n {\n for(int i=0;i<N-1;i++){\n if(arr[i]>=arr[i+1]){\n return 0;\n }\n }\n return 1;\n }" }, { "code": null, "e": 1447, "s": 1445, "text": "0" }, { "code": null, "e": 1474, "s": 1447, "text": "guptaram4656912 months ago" }, { "code": null, "e": 1481, "s": 1474, "text": " {" }, { "code": null, "e": 1771, "s": 1481, "text": " set<int> s; for (int i = 0; i < N - 1; i++) { s.insert(arr[i]); if (arr[i] > arr[i + 1]) { return 0; } } s.insert(arr[N - 1]); if (s.size() != N) { return 0; } return 1;" }, { "code": null, "e": 1775, "s": 1773, "text": "}" }, { "code": null, "e": 1777, "s": 1775, "text": "0" }, { "code": null, "e": 1799, "s": 1777, "text": "detroix072 months ago" }, { "code": null, "e": 1933, "s": 1799, "text": "int isRepresentingBST(int arr[], int n) { for(int i=1;i<n;i++){ if(arr[i] <= arr[i-1]) return 0; } return 1; }" }, { "code": null, "e": 1935, "s": 1933, "text": "0" }, { "code": null, "e": 1964, "s": 1935, "text": "harshit68rocking2 months ago" }, { "code": null, "e": 2187, "s": 1964, "text": " int isRepresentingBST(int arr[], int N)\n {\n // code here\n int c = arr[0];\n for(int i =1;i<N;i++){\n if(arr[i] <= c) return 0;\n else c= arr[i];\n }\n return 1;\n }" }, { "code": null, "e": 2189, "s": 2187, "text": "0" }, { "code": null, "e": 2216, "s": 2189, "text": "singhsrijan8093 months ago" }, { "code": null, "e": 2242, "s": 2216, "text": "JAVA SOLUTION 0.3/5.3 sec" }, { "code": null, "e": 2260, "s": 2242, "text": "PLAYERG SOLUTIONS" }, { "code": null, "e": 2523, "s": 2262, "text": "static int isRepresentingBST(int a[], int n)\n {\n // code here\n if(n==1) return 1;\n \n for(int i=1;i<n;i++){\n if(a[i-1]>=a[i]) return 0;\n }\n \n \n return 1;\n }\n LIVE GREEN PLAYERG..!!!!!!!!!PGxJAANWAR" }, { "code": null, "e": 2525, "s": 2523, "text": "0" }, { "code": null, "e": 2552, "s": 2525, "text": "kronizerdeltac3 months ago" }, { "code": null, "e": 2580, "s": 2552, "text": "C++ Solution - 0 ms passed." }, { "code": null, "e": 2834, "s": 2580, "text": "int isRepresentingBST(int arr[], int N) { if(N == 1) return 1; for(int i = 1; i < N; i++) { int prev = arr[i - 1], curr = arr[i]; if(prev >= curr) return 0; } return 1; }" }, { "code": null, "e": 2836, "s": 2834, "text": "0" }, { "code": null, "e": 2860, "s": 2836, "text": "chessnoobdj3 months ago" }, { "code": null, "e": 2878, "s": 2860, "text": "C++ one liner STL" }, { "code": null, "e": 3022, "s": 2878, "text": "int isRepresentingBST(int arr[], int N)\n {\n return is_sorted(arr, arr+N, [](int a, int b){\n return a<=b;\n });\n }" }, { "code": null, "e": 3025, "s": 3022, "text": "+1" }, { "code": null, "e": 3054, "s": 3025, "text": "badgujarsachin836 months ago" }, { "code": null, "e": 3261, "s": 3054, "text": "int isRepresentingBST(int arr[], int N)\n {\n // code here\n for(int i=0;i<N-1;i++){\n if(arr[i]>=arr[i+1]){\n return 0;\n }\n }\n return 1;\n }" }, { "code": null, "e": 3264, "s": 3261, "text": "-1" }, { "code": null, "e": 3285, "s": 3264, "text": "vs5094117 months ago" }, { "code": null, "e": 3321, "s": 3285, "text": "not accepting the correct solution " }, { "code": null, "e": 3469, "s": 3323, "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": 3505, "s": 3469, "text": " Login to access your submissions. " }, { "code": null, "e": 3515, "s": 3505, "text": "\nProblem\n" }, { "code": null, "e": 3525, "s": 3515, "text": "\nContest\n" }, { "code": null, "e": 3588, "s": 3525, "text": "Reset the IDE using the second button on the top right corner." }, { "code": null, "e": 3736, "s": 3588, "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": 3944, "s": 3736, "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": 4050, "s": 3944, "text": "You can access the hints to get an idea about what is expected of you as well as the final solution code." } ]
Creating and using packages in Java
While creating a package, you should choose a name for the package and include a package statement along with that name at the top of every source file that contains the classes, interfaces, enumerations, and annotation types that you want to include in the package. The package statement should be the first line in the source file. There can be only one package statement in each source file, and it applies to all types in the file. If a package statement is not used then the class, interfaces, enumerations, and annotation types will be placed in the current default package. To compile the Java programs with package statements, you have to use -d option as shown below. javac -d Destination_folder file_name.java Then a folder with the given package name is created in the specified destination, and the compiled class files will be placed in that folder. Let us look at an example that creates a package called animals. It is a good practice to use names of packages with lower case letters to avoid any conflicts with the names of classes and interfaces. Following package example contains interface named animals − /* File name : Animal.java */ package animals; interface Animal { public void eat(); public void travel(); } Now, let us implement the above interface in the same package animals − package animals; /* File name : MammalInt.java */ public class MammalInt implements Animal { public void eat() { System.out.println("Mammal eats"); } public void travel() { System.out.println("Mammal travels"); } public int noOfLegs() { return 0; } public static void main(String args[]) { MammalInt m = new MammalInt(); m.eat(); m.travel(); } } Now compile the java files as shown below − $ javac -d . Animal.java $ javac -d . MammalInt.java Now a package/folder with the name animals will be created in the current directory and these class files will be placed in it as shown below. You can execute the class file within the package and get the result as shown below. Mammal eats Mammal travels
[ { "code": null, "e": 1330, "s": 1062, "text": "While creating a package, you should choose a name for the package and include a package statement along with that name at the top of every source file that contains the classes, interfaces, enumerations, and annotation types that you want to include in the package. " }, { "code": null, "e": 1499, "s": 1330, "text": "The package statement should be the first line in the source file. There can be only one package statement in each source file, and it applies to all types in the file." }, { "code": null, "e": 1645, "s": 1499, "text": "If a package statement is not used then the class, interfaces, enumerations, and annotation types will be placed in the current default package. " }, { "code": null, "e": 1741, "s": 1645, "text": "To compile the Java programs with package statements, you have to use -d option as shown below." }, { "code": null, "e": 1784, "s": 1741, "text": "javac -d Destination_folder file_name.java" }, { "code": null, "e": 1927, "s": 1784, "text": "Then a folder with the given package name is created in the specified destination, and the compiled class files will be placed in that folder." }, { "code": null, "e": 2128, "s": 1927, "text": "Let us look at an example that creates a package called animals. It is a good practice to use names of packages with lower case letters to avoid any conflicts with the names of classes and interfaces." }, { "code": null, "e": 2189, "s": 2128, "text": "Following package example contains interface named animals −" }, { "code": null, "e": 2298, "s": 2189, "text": "/* File name : Animal.java */ package animals;\ninterface Animal { public void eat(); public void travel(); }" }, { "code": null, "e": 2370, "s": 2298, "text": "Now, let us implement the above interface in the same package animals −" }, { "code": null, "e": 2776, "s": 2370, "text": "package animals; /* File name :\nMammalInt.java */\npublic class MammalInt implements Animal {\n public void eat() {\n System.out.println(\"Mammal eats\");\n }\n public void travel() {\n System.out.println(\"Mammal travels\");\n }\n public int noOfLegs() {\n return 0;\n }\n public static void main(String args[]) {\n MammalInt m = new MammalInt();\n m.eat();\n m.travel();\n }\n}" }, { "code": null, "e": 2820, "s": 2776, "text": "Now compile the java files as shown below −" }, { "code": null, "e": 2873, "s": 2820, "text": "$ javac -d . Animal.java $ javac -d . MammalInt.java" }, { "code": null, "e": 3016, "s": 2873, "text": "Now a package/folder with the name animals will be created in the current directory and these class files will be placed in it as shown below." }, { "code": null, "e": 3101, "s": 3016, "text": "You can execute the class file within the package and get the result as shown below." }, { "code": null, "e": 3128, "s": 3101, "text": "Mammal eats\nMammal travels" } ]
How to get the value of div content using jQuery?
To get the value of div content in jQuery, use the text() method. The text( ) method gets the combined text contents of all matched elements. This method works for both on XML and XHTML documents. You can try to run the following code to get the value of div content using jQuery: Live Demo <!DOCTYPE html> <html> <head> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script> <script> $(document).ready(function() { $("#button1").click(function() { var res = $('#demo').text(); alert(res); }); }); </script> </head> <body> <div id="demo"> This is <b>demo</b> text. </div> <button id="button1">Get</button> </body> </html>
[ { "code": null, "e": 1259, "s": 1062, "text": "To get the value of div content in jQuery, use the text() method. The text( ) method gets the combined text contents of all matched elements. This method works for both on XML and XHTML documents." }, { "code": null, "e": 1343, "s": 1259, "text": "You can try to run the following code to get the value of div content using jQuery:" }, { "code": null, "e": 1353, "s": 1343, "text": "Live Demo" }, { "code": null, "e": 1736, "s": 1353, "text": "<!DOCTYPE html>\n<html>\n<head>\n<script src=\"https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js\"></script>\n<script>\n$(document).ready(function() {\n $(\"#button1\").click(function() {\n var res = $('#demo').text();\n alert(res);\n });\n});\n</script>\n</head>\n<body>\n\n<div id=\"demo\"> This is <b>demo</b> text.\n</div>\n<button id=\"button1\">Get</button>\n\n</body>\n</html>" } ]
Tryit Editor v3.7
Tryit: CSS borders
[]
What’s the difference between “is” and “==” in Python? | by Ahmed Besbes | Towards Data Science
When we compare objects in Python, we usually use the ==operator. We may sometimes be tempted to use the is operator as well to perform the same task. Are these two operators any different? This is a short post to explain the nuances between the two and provide a recommendation as to when to use which. I personally never knew until I looked it up. It’s actually very simple to understand and also important to know. == is for value equality. It's used to know if two objects have the same value. is is for reference equality. It's used to know if two references refer (or point) to the same object, i.e if they're identical. Two objects are identical if they have the same memory address. Two objects having equal values are not necessarily identical. Put simply: ==determines if the values of two objects are equal, while isdetermines if they are the exact same object. Or even simpler: the isstatement is syntactic sugar for id(a) == id(b) *id() is a built-in function in Python. It accepts a single parameter and is used to return the identity of an object. Let’s define a variable a to hold a list and let’s affect it to a variable b. a and breference the same object in memory and this is something we can check using the id function. (the id is guaranteed to be unique among simultaneously existing objects). a and bhave therefore the same id and hence the statement a is b is true. a = [1, 2, 3]b = aid(a)# 140545544215872id(b)# 140545544215872a is b# Truea == b# True Let’s now make a copy of the list avia the slice operator. A copy should create a new object in memory, with a new address, thus a new id is allocated. c = a[:]id(a)# 140545544215872id(c)# 140545544587008 therefore: a is c# Falsea == c# True Here a and c point to two different objects in memory even if their values are equal. Let’s run this small example. >>> a = 1000>>> b = 1000>>> a == bTrue>>> a is bFalse The behaviour is expected, just like what we saw in the previous example. Let’s now replace 1000 with 100. >>> c = 100>>> d = 100>>> c == dTrue>>> c is dTrue What happened here? this is inconsistent with the previous result. It turns out the reference implementation of Python caches integer objects in the range -5..256 as singleton instances for performance reasons. The same thing happens for strings as well. PEP 8, the official Python style guide for the standard library also mentions two use-cases for is: Comparisons to singletons like None should always be done with is or is not, never the equality operators. Also, beware of writing if x when you really mean if x is not None — e.g. when testing whether a variable or argument that defaults to None was set to some other value. The other value might have a type (such as a container) that could be false in a boolean context! Two objects are identical if they have the same memory address Two identical objects have equal values but two objects with equal values are not necessarily identical Use is to check the identity and use== to check the equality. Use is when you compare to singletons like None and == in most other cases: this is a safe choice.
[ { "code": null, "e": 322, "s": 171, "text": "When we compare objects in Python, we usually use the ==operator. We may sometimes be tempted to use the is operator as well to perform the same task." }, { "code": null, "e": 361, "s": 322, "text": "Are these two operators any different?" }, { "code": null, "e": 475, "s": 361, "text": "This is a short post to explain the nuances between the two and provide a recommendation as to when to use which." }, { "code": null, "e": 589, "s": 475, "text": "I personally never knew until I looked it up. It’s actually very simple to understand and also important to know." }, { "code": null, "e": 669, "s": 589, "text": "== is for value equality. It's used to know if two objects have the same value." }, { "code": null, "e": 862, "s": 669, "text": "is is for reference equality. It's used to know if two references refer (or point) to the same object, i.e if they're identical. Two objects are identical if they have the same memory address." }, { "code": null, "e": 925, "s": 862, "text": "Two objects having equal values are not necessarily identical." }, { "code": null, "e": 1044, "s": 925, "text": "Put simply: ==determines if the values of two objects are equal, while isdetermines if they are the exact same object." }, { "code": null, "e": 1115, "s": 1044, "text": "Or even simpler: the isstatement is syntactic sugar for id(a) == id(b)" }, { "code": null, "e": 1234, "s": 1115, "text": "*id() is a built-in function in Python. It accepts a single parameter and is used to return the identity of an object." }, { "code": null, "e": 1312, "s": 1234, "text": "Let’s define a variable a to hold a list and let’s affect it to a variable b." }, { "code": null, "e": 1488, "s": 1312, "text": "a and breference the same object in memory and this is something we can check using the id function. (the id is guaranteed to be unique among simultaneously existing objects)." }, { "code": null, "e": 1562, "s": 1488, "text": "a and bhave therefore the same id and hence the statement a is b is true." }, { "code": null, "e": 1649, "s": 1562, "text": "a = [1, 2, 3]b = aid(a)# 140545544215872id(b)# 140545544215872a is b# Truea == b# True" }, { "code": null, "e": 1801, "s": 1649, "text": "Let’s now make a copy of the list avia the slice operator. A copy should create a new object in memory, with a new address, thus a new id is allocated." }, { "code": null, "e": 1854, "s": 1801, "text": "c = a[:]id(a)# 140545544215872id(c)# 140545544587008" }, { "code": null, "e": 1865, "s": 1854, "text": "therefore:" }, { "code": null, "e": 1891, "s": 1865, "text": "a is c# Falsea == c# True" }, { "code": null, "e": 1977, "s": 1891, "text": "Here a and c point to two different objects in memory even if their values are equal." }, { "code": null, "e": 2007, "s": 1977, "text": "Let’s run this small example." }, { "code": null, "e": 2061, "s": 2007, "text": ">>> a = 1000>>> b = 1000>>> a == bTrue>>> a is bFalse" }, { "code": null, "e": 2135, "s": 2061, "text": "The behaviour is expected, just like what we saw in the previous example." }, { "code": null, "e": 2168, "s": 2135, "text": "Let’s now replace 1000 with 100." }, { "code": null, "e": 2219, "s": 2168, "text": ">>> c = 100>>> d = 100>>> c == dTrue>>> c is dTrue" }, { "code": null, "e": 2286, "s": 2219, "text": "What happened here? this is inconsistent with the previous result." }, { "code": null, "e": 2430, "s": 2286, "text": "It turns out the reference implementation of Python caches integer objects in the range -5..256 as singleton instances for performance reasons." }, { "code": null, "e": 2474, "s": 2430, "text": "The same thing happens for strings as well." }, { "code": null, "e": 2574, "s": 2474, "text": "PEP 8, the official Python style guide for the standard library also mentions two use-cases for is:" }, { "code": null, "e": 2681, "s": 2574, "text": "Comparisons to singletons like None should always be done with is or is not, never the equality operators." }, { "code": null, "e": 2948, "s": 2681, "text": "Also, beware of writing if x when you really mean if x is not None — e.g. when testing whether a variable or argument that defaults to None was set to some other value. The other value might have a type (such as a container) that could be false in a boolean context!" }, { "code": null, "e": 3011, "s": 2948, "text": "Two objects are identical if they have the same memory address" }, { "code": null, "e": 3115, "s": 3011, "text": "Two identical objects have equal values but two objects with equal values are not necessarily identical" }, { "code": null, "e": 3177, "s": 3115, "text": "Use is to check the identity and use== to check the equality." } ]
While working with Java in eclipse I got a warning saying "dead code". What does it mean?
A code block/statement in Java to which the control never reaches and never gets executed during the lifetime of the program is known as unreachable block/statement. public class UnreachableCodeExample { public String greet() { System.out.println("This is a greet method "); return "Hello"; System.out.println("This is an unreachable code "); } public static void main(String args[]) { new UnreachableCodeExample().greet(); } } A dead code is an unreachable code, but it doesn’t generate compile time error. But if you execute it in eclipse it gives you a warning. In the following Java program Live Demo public class UnreachableCodeExample { public void greet() { System.out.println("This is the greet method "); if(true){ return; } System.out.println("This is a dead code "); } public static void main(String args[]) { new UnreachableCodeExample().greet(); } } This is the greet method If you run the same program in eclipse it raises a warning as −
[ { "code": null, "e": 1228, "s": 1062, "text": "A code block/statement in Java to which the control never reaches and never gets executed during the lifetime of the program is known as unreachable block/statement." }, { "code": null, "e": 1526, "s": 1228, "text": "public class UnreachableCodeExample {\n public String greet() {\n System.out.println(\"This is a greet method \");\n return \"Hello\";\n System.out.println(\"This is an unreachable code \");\n }\n public static void main(String args[]) {\n new UnreachableCodeExample().greet();\n }\n}" }, { "code": null, "e": 1663, "s": 1526, "text": "A dead code is an unreachable code, but it doesn’t generate compile time error. But if you execute it in eclipse it gives you a warning." }, { "code": null, "e": 1693, "s": 1663, "text": "In the following Java program" }, { "code": null, "e": 1704, "s": 1693, "text": " Live Demo" }, { "code": null, "e": 2013, "s": 1704, "text": "public class UnreachableCodeExample {\n public void greet() {\n System.out.println(\"This is the greet method \");\n if(true){\n return;\n }\n System.out.println(\"This is a dead code \");\n }\n public static void main(String args[]) {\n new UnreachableCodeExample().greet();\n }\n}" }, { "code": null, "e": 2038, "s": 2013, "text": "This is the greet method" }, { "code": null, "e": 2102, "s": 2038, "text": "If you run the same program in eclipse it raises a warning as −" } ]
Remove Invalid Parentheses in C++
Suppose we have a string of parentheses. We have to remove minimum number of invalid parentheses and return the well formed parentheses strings, So if the input is like “()(()()”, so the result will be [“()()()”, “()(())”] To solve this, we will follow these steps − Define a method called solve(), this will take pos, left, right, l, r, string array res and string temp. Define a method called solve(), this will take pos, left, right, l, r, string array res and string temp. if pos is same as size of s, then,if left is same as 0 and right is same as 0, then,if (m[temp] is non-zero) is false, then,insert temp at the end of resm[temp] := 1return if pos is same as size of s, then, if left is same as 0 and right is same as 0, then,if (m[temp] is non-zero) is false, then,insert temp at the end of resm[temp] := 1 if left is same as 0 and right is same as 0, then, if (m[temp] is non-zero) is false, then,insert temp at the end of res if (m[temp] is non-zero) is false, then, insert temp at the end of res insert temp at the end of res m[temp] := 1 m[temp] := 1 return return if s[pos] is same as '(' and right > 0, then,call solve(pos + 1, left, right - 1, l, r, res, temp + empty string) if s[pos] is same as '(' and right > 0, then, call solve(pos + 1, left, right - 1, l, r, res, temp + empty string) call solve(pos + 1, left, right - 1, l, r, res, temp + empty string) Otherwise when s[pos] is same as ')' and left > 0, then −call solve(pos + 1, left - 1, right, l, r, res, temp + empty string) Otherwise when s[pos] is same as ')' and left > 0, then − call solve(pos + 1, left - 1, right, l, r, res, temp + empty string) call solve(pos + 1, left - 1, right, l, r, res, temp + empty string) if s[pos] is same as '(', then,call solve(pos + 1, left, right, l + 1, r, res, temp + "(") if s[pos] is same as '(', then, call solve(pos + 1, left, right, l + 1, r, res, temp + "(") call solve(pos + 1, left, right, l + 1, r, res, temp + "(") Otherwise when s[pos] is same as ')' and l > r, then −call solve(pos + 1, left, right, l, r + 1, res, temp + ')') Otherwise when s[pos] is same as ')' and l > r, then − call solve(pos + 1, left, right, l, r + 1, res, temp + ')') call solve(pos + 1, left, right, l, r + 1, res, temp + ')') if s[pos] is not equal to '(' and s[pos] is not equal to ')', then,call solve(pos + 1, left, right, l, r, res, temp + s[pos]) if s[pos] is not equal to '(' and s[pos] is not equal to ')', then, call solve(pos + 1, left, right, l, r, res, temp + s[pos]) call solve(pos + 1, left, right, l, r, res, temp + s[pos]) From the main method do the following − From the main method do the following − Make one array res Make one array res l := 0, r := 0 l := 0, r := 0 for initializing i := 0, when i< size of s, increase i by 1 do −if s[i] is same as '(', then,increase r by 1Otherwise when s[i] is same as ')', then −if r is non-zero, then, decrease r by 1increase else l by 1 for initializing i := 0, when i< size of s, increase i by 1 do − if s[i] is same as '(', then,increase r by 1 if s[i] is same as '(', then, increase r by 1 increase r by 1 Otherwise when s[i] is same as ')', then −if r is non-zero, then, decrease r by 1increase else l by 1 Otherwise when s[i] is same as ')', then − if r is non-zero, then, decrease r by 1 if r is non-zero, then, decrease r by 1 increase else l by 1 increase else l by 1 Call the function solve(0,l,r,0,0,res) Call the function solve(0,l,r,0,0,res) return res return res Let us see the following implementation to get better understanding − Live Demo #include <bits/stdc++.h> using namespace std; void print_vector(vector<auto> v){ cout << "["; for(int i = 0; i<v.size(); i++){ cout << v[i] << ", "; } cout << "]"<<endl; } class Solution { public: string s; map <string ,int> m; void solve(int pos, int left, int right,int l, int r, vector <string> &res, string temp=""){ if(pos == s.size()){ if(left==0 && right==0 && l==r){ if(!m[temp]) res.push_back(temp); m[temp] = 1; } return; } if(s[pos] =='(' && right>0 ){ solve(pos+1,left,right-1,l,r,res,temp+""); } else if(s[pos] ==')' && left>0) { solve(pos+1,left-1,right,l,r,res,temp+""); } if(s[pos] =='(')solve(pos+1,left,right,l+1,r,res,temp+"("); else if(s[pos] == ')' && l>r)solve(pos+1,left,right,l,r+1,res,temp+')'); if(s[pos]!='(' && s[pos]!=')')solve(pos+1,left,right,l,r,res,temp+s[pos]); } vector<string> removeInvalidParentheses(string s) { vector <string > res; int l = 0; int r=0; this->s = s; for(int i =0;i<s.size();i++){ if(s[i] == '('){ r++; } else if(s[i]==')') { if(r)r--; else l++; } } solve(0,l,r,0,0,res); return res; } }; main(){ Solution ob; print_vector(ob.removeInvalidParentheses("()(()()")); } “()(()()” [()()(), ()(()), ]
[ { "code": null, "e": 1285, "s": 1062, "text": "Suppose we have a string of parentheses. We have to remove minimum number of invalid parentheses and return the well formed parentheses strings, So if the input is like “()(()()”, so the result will be [“()()()”, “()(())”]" }, { "code": null, "e": 1329, "s": 1285, "text": "To solve this, we will follow these steps −" }, { "code": null, "e": 1434, "s": 1329, "text": "Define a method called solve(), this will take pos, left, right, l, r, string array res and string temp." }, { "code": null, "e": 1539, "s": 1434, "text": "Define a method called solve(), this will take pos, left, right, l, r, string array res and string temp." }, { "code": null, "e": 1711, "s": 1539, "text": "if pos is same as size of s, then,if left is same as 0 and right is same as 0, then,if (m[temp] is non-zero) is false, then,insert temp at the end of resm[temp] := 1return" }, { "code": null, "e": 1746, "s": 1711, "text": "if pos is same as size of s, then," }, { "code": null, "e": 1878, "s": 1746, "text": "if left is same as 0 and right is same as 0, then,if (m[temp] is non-zero) is false, then,insert temp at the end of resm[temp] := 1" }, { "code": null, "e": 1929, "s": 1878, "text": "if left is same as 0 and right is same as 0, then," }, { "code": null, "e": 1999, "s": 1929, "text": "if (m[temp] is non-zero) is false, then,insert temp at the end of res" }, { "code": null, "e": 2040, "s": 1999, "text": "if (m[temp] is non-zero) is false, then," }, { "code": null, "e": 2070, "s": 2040, "text": "insert temp at the end of res" }, { "code": null, "e": 2100, "s": 2070, "text": "insert temp at the end of res" }, { "code": null, "e": 2113, "s": 2100, "text": "m[temp] := 1" }, { "code": null, "e": 2126, "s": 2113, "text": "m[temp] := 1" }, { "code": null, "e": 2133, "s": 2126, "text": "return" }, { "code": null, "e": 2140, "s": 2133, "text": "return" }, { "code": null, "e": 2254, "s": 2140, "text": "if s[pos] is same as '(' and right > 0, then,call solve(pos + 1, left, right - 1, l, r, res, temp + empty string)" }, { "code": null, "e": 2300, "s": 2254, "text": "if s[pos] is same as '(' and right > 0, then," }, { "code": null, "e": 2369, "s": 2300, "text": "call solve(pos + 1, left, right - 1, l, r, res, temp + empty string)" }, { "code": null, "e": 2438, "s": 2369, "text": "call solve(pos + 1, left, right - 1, l, r, res, temp + empty string)" }, { "code": null, "e": 2564, "s": 2438, "text": "Otherwise when s[pos] is same as ')' and left > 0, then −call solve(pos + 1, left - 1, right, l, r, res, temp + empty string)" }, { "code": null, "e": 2622, "s": 2564, "text": "Otherwise when s[pos] is same as ')' and left > 0, then −" }, { "code": null, "e": 2691, "s": 2622, "text": "call solve(pos + 1, left - 1, right, l, r, res, temp + empty string)" }, { "code": null, "e": 2760, "s": 2691, "text": "call solve(pos + 1, left - 1, right, l, r, res, temp + empty string)" }, { "code": null, "e": 2851, "s": 2760, "text": "if s[pos] is same as '(', then,call solve(pos + 1, left, right, l + 1, r, res, temp + \"(\")" }, { "code": null, "e": 2883, "s": 2851, "text": "if s[pos] is same as '(', then," }, { "code": null, "e": 2943, "s": 2883, "text": "call solve(pos + 1, left, right, l + 1, r, res, temp + \"(\")" }, { "code": null, "e": 3003, "s": 2943, "text": "call solve(pos + 1, left, right, l + 1, r, res, temp + \"(\")" }, { "code": null, "e": 3117, "s": 3003, "text": "Otherwise when s[pos] is same as ')' and l > r, then −call solve(pos + 1, left, right, l, r + 1, res, temp + ')')" }, { "code": null, "e": 3172, "s": 3117, "text": "Otherwise when s[pos] is same as ')' and l > r, then −" }, { "code": null, "e": 3232, "s": 3172, "text": "call solve(pos + 1, left, right, l, r + 1, res, temp + ')')" }, { "code": null, "e": 3292, "s": 3232, "text": "call solve(pos + 1, left, right, l, r + 1, res, temp + ')')" }, { "code": null, "e": 3418, "s": 3292, "text": "if s[pos] is not equal to '(' and s[pos] is not equal to ')', then,call solve(pos + 1, left, right, l, r, res, temp + s[pos])" }, { "code": null, "e": 3486, "s": 3418, "text": "if s[pos] is not equal to '(' and s[pos] is not equal to ')', then," }, { "code": null, "e": 3545, "s": 3486, "text": "call solve(pos + 1, left, right, l, r, res, temp + s[pos])" }, { "code": null, "e": 3604, "s": 3545, "text": "call solve(pos + 1, left, right, l, r, res, temp + s[pos])" }, { "code": null, "e": 3644, "s": 3604, "text": "From the main method do the following −" }, { "code": null, "e": 3684, "s": 3644, "text": "From the main method do the following −" }, { "code": null, "e": 3703, "s": 3684, "text": "Make one array res" }, { "code": null, "e": 3722, "s": 3703, "text": "Make one array res" }, { "code": null, "e": 3737, "s": 3722, "text": "l := 0, r := 0" }, { "code": null, "e": 3752, "s": 3737, "text": "l := 0, r := 0" }, { "code": null, "e": 3962, "s": 3752, "text": "for initializing i := 0, when i< size of s, increase i by 1 do −if s[i] is same as '(', then,increase r by 1Otherwise when s[i] is same as ')', then −if r is non-zero, then, decrease r by 1increase else l by 1" }, { "code": null, "e": 4027, "s": 3962, "text": "for initializing i := 0, when i< size of s, increase i by 1 do −" }, { "code": null, "e": 4072, "s": 4027, "text": "if s[i] is same as '(', then,increase r by 1" }, { "code": null, "e": 4102, "s": 4072, "text": "if s[i] is same as '(', then," }, { "code": null, "e": 4118, "s": 4102, "text": "increase r by 1" }, { "code": null, "e": 4134, "s": 4118, "text": "increase r by 1" }, { "code": null, "e": 4236, "s": 4134, "text": "Otherwise when s[i] is same as ')', then −if r is non-zero, then, decrease r by 1increase else l by 1" }, { "code": null, "e": 4279, "s": 4236, "text": "Otherwise when s[i] is same as ')', then −" }, { "code": null, "e": 4319, "s": 4279, "text": "if r is non-zero, then, decrease r by 1" }, { "code": null, "e": 4359, "s": 4319, "text": "if r is non-zero, then, decrease r by 1" }, { "code": null, "e": 4380, "s": 4359, "text": "increase else l by 1" }, { "code": null, "e": 4401, "s": 4380, "text": "increase else l by 1" }, { "code": null, "e": 4440, "s": 4401, "text": "Call the function solve(0,l,r,0,0,res)" }, { "code": null, "e": 4479, "s": 4440, "text": "Call the function solve(0,l,r,0,0,res)" }, { "code": null, "e": 4490, "s": 4479, "text": "return res" }, { "code": null, "e": 4501, "s": 4490, "text": "return res" }, { "code": null, "e": 4571, "s": 4501, "text": "Let us see the following implementation to get better understanding −" }, { "code": null, "e": 4582, "s": 4571, "text": " Live Demo" }, { "code": null, "e": 5990, "s": 4582, "text": "#include <bits/stdc++.h>\nusing namespace std;\nvoid print_vector(vector<auto> v){\n cout << \"[\";\n for(int i = 0; i<v.size(); i++){\n cout << v[i] << \", \";\n }\n cout << \"]\"<<endl;\n}\nclass Solution {\n public:\n string s;\n map <string ,int> m;\n void solve(int pos, int left, int right,int l, int r, vector <string> &res, string temp=\"\"){\n if(pos == s.size()){\n if(left==0 && right==0 && l==r){\n if(!m[temp])\n res.push_back(temp);\n m[temp] = 1;\n }\n return;\n }\n if(s[pos] =='(' && right>0 ){\n solve(pos+1,left,right-1,l,r,res,temp+\"\");\n } else if(s[pos] ==')' && left>0) {\n solve(pos+1,left-1,right,l,r,res,temp+\"\");\n }\n if(s[pos] =='(')solve(pos+1,left,right,l+1,r,res,temp+\"(\");\n else if(s[pos] == ')' && l>r)solve(pos+1,left,right,l,r+1,res,temp+')');\n if(s[pos]!='(' && s[pos]!=')')solve(pos+1,left,right,l,r,res,temp+s[pos]);\n }\n vector<string> removeInvalidParentheses(string s) {\n vector <string > res;\n int l = 0;\n int r=0;\n this->s = s;\n for(int i =0;i<s.size();i++){\n if(s[i] == '('){\n r++;\n } else if(s[i]==')') {\n if(r)r--;\n else l++;\n }\n }\n solve(0,l,r,0,0,res);\n return res;\n }\n};\nmain(){\n Solution ob;\n print_vector(ob.removeInvalidParentheses(\"()(()()\"));\n}" }, { "code": null, "e": 6000, "s": 5990, "text": "“()(()()”" }, { "code": null, "e": 6019, "s": 6000, "text": "[()()(), ()(()), ]" } ]
Python’s Collections Module — High-performance container data types. | by Parul Pandey | Towards Data Science
If the implementation is hard to explain, it’s a bad idea :The Zen of Python Python is a pretty powerful language and a large part of this power comes from the fact that it supports modular programming. Modular programming is essentially the process of breaking down a large and complex programming task into smaller and more manageable subtask/module. Modules are like LEGO bricks which can be bundled up together to create a larger task. Modularity has a lot of advantages when writing code like: Reusability Maintainability Simplicity Functions, modules and packages are all constructs in Python that promote code modularization. Through this article, we will explore Python’s Collections Module. This module aims to improve the functionalities and provides alternatives to Python’s general purpose built-in containers such as dict, list, set, and tuple. Let’s begin the article with a quick glance at the concept of modules and packages. A module is nothing but a .py script that can be called in another .py script. A module is a file containing Python definitions and statements which helps to implement a set of functions. The file name is the module name with the suffix .py appended. Modules are imported from other modules using the import command. Let’s import the math module. # import the libraryimport math#Using it for taking the logmath.log(10)2.302585092994046 Python has innumerable inbuilt modules and there are packages already created for almost any use case you can think of. Check out the complete list here. Two very important functions come in handy when exploring modules in Python — the dir and help functions. The built-in function dir() is used to find out which functions are implemented in each module. It returns a sorted list of strings: print(dir(math)) After locating our desired function in the module, we can read more about it using the help function, inside the Python interpreter: help(math.factorial) Packages are a collection of related modules stacked up together. Numpy and Scipy, the core machine Learning packages, are made up of a collection of hundreds of modules. here is a partial list of sub-packages available within SciPy. Let us now hop over to the actual objective of this article which is to get to know about the Python’s Collection module. This is just an overview and for detailed explanations and examples please refer to the official Python documentation. Collections is a built-in Python module that implements specialized container datatypes providing alternatives to Python’s general purpose built-in containers such as dict, list, set, and tuple. Some of the useful data structures present in this module are: The data stored in a plain tuple can only be accessed through indexes as can be seen in the example below: plain_tuple = (10,11,12,13)plain_tuple[0]10plain_tuple[3]13 We can’t give names to individual elements stored in a tuple. Now, this might not be needed in simple cases. However, in case a tuple has many fields this might be kind of a necessity and will also impact the code’s readability. It is here that namedtuple’s functionality comes into the picture. It is a function for tuples with Named Fields and can be seen as an extension of the built-in tuple data type. Named tuples assign meaning to each position in a tuple and allow for more readable, self-documenting code. Each object stored in them can be accessed through a unique (human-readable) identifier and this frees us from having to remember integer indexes. Let’s see its implementation. from collections import namedtuplefruit = namedtuple('fruit','number variety color')guava = fruit(number=2,variety='HoneyCrisp',color='green')apple = fruit(number=5,variety='Granny Smith',color='red') We construct the namedtuple by first passing the object type name (fruit) and then passing a string with the variety of fields as a string with spaces between the field names. We can then call on the various attributes: guava.color'green'apple.variety'Granny Smith' Namedtuples are also a memory-efficient option when defining an immutable class in Python. Counter is a dict subclass which helps to count hashable objects. The elements are stored as dictionary keys while the object counts are stored as the value. Let’s work through a few examples with Counter. #Importing Counter from collectionsfrom collections import Counter With Strings c = Counter('abcacdabcacd')print(c)Counter({'a': 4, 'c': 4, 'b': 2, 'd': 2}) With Lists lst = [5,6,7,1,3,9,9,1,2,5,5,7,7]c = Counter(lst)print(c)Counter({'a': 4, 'c': 4, 'b': 2, 'd': 2}) With Sentence s = 'the lazy dog jumped over another lazy dog'words = s.split()Counter(words)Counter({'another': 1, 'dog': 2, 'jumped': 1, 'lazy': 2, 'over': 1, 'the': 1}) Counter objects support three methods beyond those available for all dictionaries: elements() Returns a count of each element and If an element’s count is less than one, it is ignored. c = Counter(a=3, b=2, c=1, d=-2)sorted(c.elements())['a', 'a', 'a', 'b', 'b', 'c'] most_common([n]) Returns a list of the most common elements with their counts. The number of elements has to be specified as n. If none is specified it returns the count of all the elements. s = 'the lazy dog jumped over another lazy dog'words = s.split()Counter(words).most_common(3)[('lazy', 2), ('dog', 2), ('the', 1)] sum(c.values()) # total of all counts c.clear() # reset all counts list(c) # list unique elements set(c) # convert to a set dict(c) # convert to a regular dictionary c.items() # convert to a list like (elem, cnt) Counter(dict(list_of_pairs)) # convert from a list of(elem, cnt) c.most_common()[:-n-1:-1] # n least common elements c += Counter() # remove zero and negative counts Dictionaries are an efficient way to store data for later retrieval having an unordered set of key: value pairs. Keys must be unique and immutable objects. fruits = {'apple':300, 'guava': 200}fruits['guava']200 Things are simple if the values are ints or strings. However, if the values are in the form of collections like lists or dictionaries, the value (an empty list or dict) must be initialized the first time a given key is used. defaultdict automates and simplifies this stuff. The example below will make it more obvious: d = {}print(d['A']) Here, the Python dictionary throws an error since ‘A’ is not currently in the dictionary. Let us now run the same example with defaultdict. from collections import defaultdictd = defaultdict(object)print(d['A'])<object object at 0x7fc9bed4cb00> The defaultdict in contrast will simply create any items that you try to access (provided of course they do not exist yet).The defaultdict is also a dictionary-like object and provides all methods provided by a dictionary. However, the point of difference is that it takes the first argument (default_factory) as a default data type for the dictionary. An OrderedDict is a dictionary subclass that remembers the order in which that keys were first inserted. When iterating over an ordered dictionary, the items are returned in the order their keys were first added. Since an ordered dictionary remembers its insertion order, it can be used in conjunction with sorting to make a sorted dictionary: regular dictionary d = {'banana': 3, 'apple': 4, 'pear': 1, 'orange': 2} dictionary sorted by key OrderedDict(sorted(d.items(), key=lambda t: t[0]))OrderedDict([('apple', 4), ('banana', 3), ('orange', 2), ('pear', 1)]) dictionary sorted by value OrderedDict(sorted(d.items(), key=lambda t: t[1]))OrderedDict([('pear', 1), ('orange', 2), ('banana', 3), ('apple', 4)]) dictionary sorted by the length of the key string OrderedDict(sorted(d.items(), key=lambda t: len(t[0])))OrderedDict([('pear', 1), ('apple', 4), ('banana', 3), ('orange', 2)]) A point to note here is that in Python 3.6, the regular dictionaries are insertion ordered i.e dictionaries remember the order of items inserted. Read the discussion here. Collections module also contain some other useful datatypes like deque, Chainmap, UserString and few more. However, I have shared the ones which I use in my day to day programming to makes things simple. For a detailed explanation and usage visit the official Python documentation page.
[ { "code": null, "e": 249, "s": 172, "text": "If the implementation is hard to explain, it’s a bad idea :The Zen of Python" }, { "code": null, "e": 612, "s": 249, "text": "Python is a pretty powerful language and a large part of this power comes from the fact that it supports modular programming. Modular programming is essentially the process of breaking down a large and complex programming task into smaller and more manageable subtask/module. Modules are like LEGO bricks which can be bundled up together to create a larger task." }, { "code": null, "e": 671, "s": 612, "text": "Modularity has a lot of advantages when writing code like:" }, { "code": null, "e": 683, "s": 671, "text": "Reusability" }, { "code": null, "e": 699, "s": 683, "text": "Maintainability" }, { "code": null, "e": 710, "s": 699, "text": "Simplicity" }, { "code": null, "e": 805, "s": 710, "text": "Functions, modules and packages are all constructs in Python that promote code modularization." }, { "code": null, "e": 1030, "s": 805, "text": "Through this article, we will explore Python’s Collections Module. This module aims to improve the functionalities and provides alternatives to Python’s general purpose built-in containers such as dict, list, set, and tuple." }, { "code": null, "e": 1114, "s": 1030, "text": "Let’s begin the article with a quick glance at the concept of modules and packages." }, { "code": null, "e": 1461, "s": 1114, "text": "A module is nothing but a .py script that can be called in another .py script. A module is a file containing Python definitions and statements which helps to implement a set of functions. The file name is the module name with the suffix .py appended. Modules are imported from other modules using the import command. Let’s import the math module." }, { "code": null, "e": 1550, "s": 1461, "text": "# import the libraryimport math#Using it for taking the logmath.log(10)2.302585092994046" }, { "code": null, "e": 1704, "s": 1550, "text": "Python has innumerable inbuilt modules and there are packages already created for almost any use case you can think of. Check out the complete list here." }, { "code": null, "e": 1810, "s": 1704, "text": "Two very important functions come in handy when exploring modules in Python — the dir and help functions." }, { "code": null, "e": 1943, "s": 1810, "text": "The built-in function dir() is used to find out which functions are implemented in each module. It returns a sorted list of strings:" }, { "code": null, "e": 1960, "s": 1943, "text": "print(dir(math))" }, { "code": null, "e": 2093, "s": 1960, "text": "After locating our desired function in the module, we can read more about it using the help function, inside the Python interpreter:" }, { "code": null, "e": 2114, "s": 2093, "text": "help(math.factorial)" }, { "code": null, "e": 2348, "s": 2114, "text": "Packages are a collection of related modules stacked up together. Numpy and Scipy, the core machine Learning packages, are made up of a collection of hundreds of modules. here is a partial list of sub-packages available within SciPy." }, { "code": null, "e": 2589, "s": 2348, "text": "Let us now hop over to the actual objective of this article which is to get to know about the Python’s Collection module. This is just an overview and for detailed explanations and examples please refer to the official Python documentation." }, { "code": null, "e": 2784, "s": 2589, "text": "Collections is a built-in Python module that implements specialized container datatypes providing alternatives to Python’s general purpose built-in containers such as dict, list, set, and tuple." }, { "code": null, "e": 2847, "s": 2784, "text": "Some of the useful data structures present in this module are:" }, { "code": null, "e": 2954, "s": 2847, "text": "The data stored in a plain tuple can only be accessed through indexes as can be seen in the example below:" }, { "code": null, "e": 3014, "s": 2954, "text": "plain_tuple = (10,11,12,13)plain_tuple[0]10plain_tuple[3]13" }, { "code": null, "e": 3243, "s": 3014, "text": "We can’t give names to individual elements stored in a tuple. Now, this might not be needed in simple cases. However, in case a tuple has many fields this might be kind of a necessity and will also impact the code’s readability." }, { "code": null, "e": 3706, "s": 3243, "text": "It is here that namedtuple’s functionality comes into the picture. It is a function for tuples with Named Fields and can be seen as an extension of the built-in tuple data type. Named tuples assign meaning to each position in a tuple and allow for more readable, self-documenting code. Each object stored in them can be accessed through a unique (human-readable) identifier and this frees us from having to remember integer indexes. Let’s see its implementation." }, { "code": null, "e": 3907, "s": 3706, "text": "from collections import namedtuplefruit = namedtuple('fruit','number variety color')guava = fruit(number=2,variety='HoneyCrisp',color='green')apple = fruit(number=5,variety='Granny Smith',color='red')" }, { "code": null, "e": 4127, "s": 3907, "text": "We construct the namedtuple by first passing the object type name (fruit) and then passing a string with the variety of fields as a string with spaces between the field names. We can then call on the various attributes:" }, { "code": null, "e": 4173, "s": 4127, "text": "guava.color'green'apple.variety'Granny Smith'" }, { "code": null, "e": 4264, "s": 4173, "text": "Namedtuples are also a memory-efficient option when defining an immutable class in Python." }, { "code": null, "e": 4470, "s": 4264, "text": "Counter is a dict subclass which helps to count hashable objects. The elements are stored as dictionary keys while the object counts are stored as the value. Let’s work through a few examples with Counter." }, { "code": null, "e": 4537, "s": 4470, "text": "#Importing Counter from collectionsfrom collections import Counter" }, { "code": null, "e": 4550, "s": 4537, "text": "With Strings" }, { "code": null, "e": 4627, "s": 4550, "text": "c = Counter('abcacdabcacd')print(c)Counter({'a': 4, 'c': 4, 'b': 2, 'd': 2})" }, { "code": null, "e": 4638, "s": 4627, "text": "With Lists" }, { "code": null, "e": 4737, "s": 4638, "text": "lst = [5,6,7,1,3,9,9,1,2,5,5,7,7]c = Counter(lst)print(c)Counter({'a': 4, 'c': 4, 'b': 2, 'd': 2})" }, { "code": null, "e": 4751, "s": 4737, "text": "With Sentence" }, { "code": null, "e": 4908, "s": 4751, "text": "s = 'the lazy dog jumped over another lazy dog'words = s.split()Counter(words)Counter({'another': 1, 'dog': 2, 'jumped': 1, 'lazy': 2, 'over': 1, 'the': 1})" }, { "code": null, "e": 4991, "s": 4908, "text": "Counter objects support three methods beyond those available for all dictionaries:" }, { "code": null, "e": 5002, "s": 4991, "text": "elements()" }, { "code": null, "e": 5093, "s": 5002, "text": "Returns a count of each element and If an element’s count is less than one, it is ignored." }, { "code": null, "e": 5176, "s": 5093, "text": "c = Counter(a=3, b=2, c=1, d=-2)sorted(c.elements())['a', 'a', 'a', 'b', 'b', 'c']" }, { "code": null, "e": 5193, "s": 5176, "text": "most_common([n])" }, { "code": null, "e": 5367, "s": 5193, "text": "Returns a list of the most common elements with their counts. The number of elements has to be specified as n. If none is specified it returns the count of all the elements." }, { "code": null, "e": 5498, "s": 5367, "text": "s = 'the lazy dog jumped over another lazy dog'words = s.split()Counter(words).most_common(3)[('lazy', 2), ('dog', 2), ('the', 1)]" }, { "code": null, "e": 6036, "s": 5498, "text": "sum(c.values()) # total of all counts c.clear() # reset all counts list(c) # list unique elements set(c) # convert to a set dict(c) # convert to a regular dictionary c.items() # convert to a list like (elem, cnt) Counter(dict(list_of_pairs)) # convert from a list of(elem, cnt) c.most_common()[:-n-1:-1] # n least common elements c += Counter() # remove zero and negative counts" }, { "code": null, "e": 6192, "s": 6036, "text": "Dictionaries are an efficient way to store data for later retrieval having an unordered set of key: value pairs. Keys must be unique and immutable objects." }, { "code": null, "e": 6247, "s": 6192, "text": "fruits = {'apple':300, 'guava': 200}fruits['guava']200" }, { "code": null, "e": 6566, "s": 6247, "text": "Things are simple if the values are ints or strings. However, if the values are in the form of collections like lists or dictionaries, the value (an empty list or dict) must be initialized the first time a given key is used. defaultdict automates and simplifies this stuff. The example below will make it more obvious:" }, { "code": null, "e": 6586, "s": 6566, "text": "d = {}print(d['A'])" }, { "code": null, "e": 6726, "s": 6586, "text": "Here, the Python dictionary throws an error since ‘A’ is not currently in the dictionary. Let us now run the same example with defaultdict." }, { "code": null, "e": 6831, "s": 6726, "text": "from collections import defaultdictd = defaultdict(object)print(d['A'])<object object at 0x7fc9bed4cb00>" }, { "code": null, "e": 7184, "s": 6831, "text": "The defaultdict in contrast will simply create any items that you try to access (provided of course they do not exist yet).The defaultdict is also a dictionary-like object and provides all methods provided by a dictionary. However, the point of difference is that it takes the first argument (default_factory) as a default data type for the dictionary." }, { "code": null, "e": 7528, "s": 7184, "text": "An OrderedDict is a dictionary subclass that remembers the order in which that keys were first inserted. When iterating over an ordered dictionary, the items are returned in the order their keys were first added. Since an ordered dictionary remembers its insertion order, it can be used in conjunction with sorting to make a sorted dictionary:" }, { "code": null, "e": 7547, "s": 7528, "text": "regular dictionary" }, { "code": null, "e": 7601, "s": 7547, "text": "d = {'banana': 3, 'apple': 4, 'pear': 1, 'orange': 2}" }, { "code": null, "e": 7626, "s": 7601, "text": "dictionary sorted by key" }, { "code": null, "e": 7747, "s": 7626, "text": "OrderedDict(sorted(d.items(), key=lambda t: t[0]))OrderedDict([('apple', 4), ('banana', 3), ('orange', 2), ('pear', 1)])" }, { "code": null, "e": 7774, "s": 7747, "text": "dictionary sorted by value" }, { "code": null, "e": 7895, "s": 7774, "text": "OrderedDict(sorted(d.items(), key=lambda t: t[1]))OrderedDict([('pear', 1), ('orange', 2), ('banana', 3), ('apple', 4)])" }, { "code": null, "e": 7945, "s": 7895, "text": "dictionary sorted by the length of the key string" }, { "code": null, "e": 8071, "s": 7945, "text": "OrderedDict(sorted(d.items(), key=lambda t: len(t[0])))OrderedDict([('pear', 1), ('apple', 4), ('banana', 3), ('orange', 2)])" }, { "code": null, "e": 8243, "s": 8071, "text": "A point to note here is that in Python 3.6, the regular dictionaries are insertion ordered i.e dictionaries remember the order of items inserted. Read the discussion here." } ]
Print all combinations of factors in C++
In this problem, we are given a number n. Our task is to print all combinations of factors of n. Let’s take an example to understand the topic better − Input: 24 Output: 2 2 2 3 2 4 3 8 3 4 6 2 12 For this, we will use recursion function which will find a combination of factors of the number. And we will store all our combinations in an array of array. This code will show the implementation of our solution. Live Demo #include<bits/stdc++.h> using namespace std; vector<vector<int>> factor_Combo; void genreateFactorCombinations(int first, int eachFactor, int n, vector<int>factor) { if (first>n || eachFactor>n) return; if (eachFactor == n){ factor_Combo.push_back(factor); return; } for (int i = first; i < n; i++) { if (i*eachFactor>n) break; if (n % i == 0){ factor.push_back(i); genreateFactorCombinations(i, i*eachFactor, n, factor); factor.pop_back(); } } } void printcombination() { for (int i = 0; i < factor_Combo.size(); i++){ for (int j = 0; j < factor_Combo[i].size(); j++) cout<<factor_Combo[i][j]<<"\t"; cout<<endl; } } int main() { int n = 24; vector<int>single_result_list; cout<<"All Factor combinations of "<<n<<" are :\n"; genreateFactorCombinations(2, 1, n, single_result_list); printcombination(); return 0; } All Factor combinations of 24 are − 2 2 2 3 2 2 6 2 3 4 2 12 3 8 4 6
[ { "code": null, "e": 1159, "s": 1062, "text": "In this problem, we are given a number n. Our task is to print all combinations of factors of n." }, { "code": null, "e": 1214, "s": 1159, "text": "Let’s take an example to understand the topic better −" }, { "code": null, "e": 1259, "s": 1214, "text": "Input: 24\nOutput:\n2 2 2 3\n2 4 3\n8 3\n4 6\n2 12" }, { "code": null, "e": 1417, "s": 1259, "text": "For this, we will use recursion function which will find a combination of factors of the number. And we will store all our combinations in an array of array." }, { "code": null, "e": 1473, "s": 1417, "text": "This code will show the implementation of our solution." }, { "code": null, "e": 1484, "s": 1473, "text": " Live Demo" }, { "code": null, "e": 2427, "s": 1484, "text": "#include<bits/stdc++.h>\nusing namespace std;\nvector<vector<int>> factor_Combo;\nvoid genreateFactorCombinations(int first, int eachFactor, int n, vector<int>factor) {\n if (first>n || eachFactor>n)\n return;\n if (eachFactor == n){\n factor_Combo.push_back(factor);\n return;\n }\n for (int i = first; i < n; i++) {\n if (i*eachFactor>n)\n break;\n if (n % i == 0){\n factor.push_back(i);\n genreateFactorCombinations(i, i*eachFactor, n, factor);\n factor.pop_back();\n }\n }\n}\nvoid printcombination() {\n for (int i = 0; i < factor_Combo.size(); i++){\n for (int j = 0; j < factor_Combo[i].size(); j++)\n cout<<factor_Combo[i][j]<<\"\\t\";\n cout<<endl;\n }\n}\nint main() {\n int n = 24;\n vector<int>single_result_list;\n cout<<\"All Factor combinations of \"<<n<<\" are :\\n\";\n genreateFactorCombinations(2, 1, n, single_result_list);\n printcombination();\n return 0;\n}" }, { "code": null, "e": 2496, "s": 2427, "text": "All Factor combinations of 24 are −\n2 2 2 3\n2 2 6\n2 3 4\n2 12\n3 8\n4 6" } ]
How to build and apply Naive Bayes classification for spam filtering | by Pavlo Horbonos | Towards Data Science
I believe, that today almost everyone has a smartphone and a lot of people keep an email or two. This means that you have to be familiar with tons of messages proposing a lot of money, fantastic lottery wins, great presents and secrets of life. We get dozens of spam messages every day unless you use well-trained filters. They may be harmful, just annoying or space-consuming, but they also can contain viruses or fishing attempts. In any case, it is not the content we want to deal with. So the demand for good spam filters is always high. Let me acquaint you (or remind if you are already familiar) with one of the pretty effective algorithms for spam filtering: Naive Bayes classification. Although there is already existing implementation in scikit-learn package, I want to recreate the algorithm from scratch. Firstly, I want to uncover the logic hidden behind the implementation. And secondly, I want to show the algorithm in conjunction with the dataset preparation. Naive Bayes classification is a simple probability algorithm based on the fact, that all features of the model are independent. In the context of the spam filter, we suppose, that every word in the message is independent of all other words and we count them with the ignorance of the context. Our classification algorithm produces probabilities of the message to be spam or not spam by the condition of the current set of words. Calculation of the probability is based on the Bayes formula and the components of the formula are calculated based on the frequencies of the words in the whole set of messages. So, how does the algorithm work? First of all, we take the Bayes formula of the conditional probability and apply it to our task: The probability of the message, that contains words (w1, w2, w3, ...) to be spam is proportional to the probability to get the spam multiplied by a product of probabilities for every word in the message to belong to a spam message. What does it mean? For every word in the message, we calculate a probability of it to be found in spam. In our context: P_spam — the part of spam messages in our dataset P_wi_spam — the probability of a word to be found in the spam messages. By the same logic we define: P_not_spam — the part of non-spam messages in the dataset P_wi_non_spam — the probability of a word to be found in the non-spam messages. But we still do not know how to calculate each word probabilities. Though, we have another formula: What do we have here: N_vocabulary — the number of unique words in the whole dataset. N_spam — the total number of words in the spam messages. N_wi_spam — the number of a word repeats in all spam messages. Alpha — the coefficient for the cases when a word in the message is absent in our dataset. Shortly: the probability of a word to belong to the spam message is a frequency of this word in the “spam part” of our dataset. Also, the same formula (but with other values) is correct for the probability of a word to belong to non-spam messages. The math is over, but do not worry — I will show all the values and formulas on the dataset example. For our purpose, we will use the collection of SMS messages, which was put together by Tiago A. Almeida and José María Gómez Hidalgo. It is free and can be downloaded from the UCI Machine Learning Repository. Dataset structure is simple. It contains two columns — one for the label “spam/ham” and another for the text of the message. It contains 5572 records of different messages together with 747 spam messages. sms_data.groupby('Label').count()Out[6]:ham 4825spam 747 We have enough data to start the analysis. Before the algorithm application, we need to prepare data. First of all, we will remove the punctuation. Then we will convert all the text into the lower-case and split it into the separate words. The next thing is to split the dataset to train and test data. But we also need to keep the distribution of spam and non-spam messages. And at last, we have to prepare the vocabulary and count the number of separate words in each message. Concat the resulting table of words count to our train data: And the data is ready. We will follow the formulas mentioned above and define the main values: probability of message to be spam Pspam = train_data[‘Label’].value_counts()[‘spam’] / train_data.shape[0] probability of non-spam message Pham = train_data[‘Label’].value_counts()[‘ham’] / train_data.shape[0] the number of words in spam messages Nspam = train_data.loc[train_data[‘Label’] == ‘spam’, ‘SMS’].apply(len).sum() the number of words in non-spam messages Nham = train_data.loc[train_data[‘Label’] == ‘ham’, ‘SMS’].apply(len).sum() the size of the vocabulary Nvoc = len(train_data.columns - 3) set alpha = 1 To complete the formula we will define the functions to determine the probabilities of the given word to belong to spam and non-spam messages: Our classification function: After the function application, we see impressive results on the test data: 99.1% of data were successfully classified. Just for the interest let’s look on the incorrectly recognized messages: Now you are familiar (or freshened up in the memory) with one of the most effective spam-classification algorithms. I hope it was helpful and descriptive. You can find the Jupyter notebook with working example on my GitHub: github.com You are welcome to share other algorithms called upon the fight with spam.
[ { "code": null, "e": 714, "s": 172, "text": "I believe, that today almost everyone has a smartphone and a lot of people keep an email or two. This means that you have to be familiar with tons of messages proposing a lot of money, fantastic lottery wins, great presents and secrets of life. We get dozens of spam messages every day unless you use well-trained filters. They may be harmful, just annoying or space-consuming, but they also can contain viruses or fishing attempts. In any case, it is not the content we want to deal with. So the demand for good spam filters is always high." }, { "code": null, "e": 1147, "s": 714, "text": "Let me acquaint you (or remind if you are already familiar) with one of the pretty effective algorithms for spam filtering: Naive Bayes classification. Although there is already existing implementation in scikit-learn package, I want to recreate the algorithm from scratch. Firstly, I want to uncover the logic hidden behind the implementation. And secondly, I want to show the algorithm in conjunction with the dataset preparation." }, { "code": null, "e": 1440, "s": 1147, "text": "Naive Bayes classification is a simple probability algorithm based on the fact, that all features of the model are independent. In the context of the spam filter, we suppose, that every word in the message is independent of all other words and we count them with the ignorance of the context." }, { "code": null, "e": 1754, "s": 1440, "text": "Our classification algorithm produces probabilities of the message to be spam or not spam by the condition of the current set of words. Calculation of the probability is based on the Bayes formula and the components of the formula are calculated based on the frequencies of the words in the whole set of messages." }, { "code": null, "e": 1787, "s": 1754, "text": "So, how does the algorithm work?" }, { "code": null, "e": 1884, "s": 1787, "text": "First of all, we take the Bayes formula of the conditional probability and apply it to our task:" }, { "code": null, "e": 2236, "s": 1884, "text": "The probability of the message, that contains words (w1, w2, w3, ...) to be spam is proportional to the probability to get the spam multiplied by a product of probabilities for every word in the message to belong to a spam message. What does it mean? For every word in the message, we calculate a probability of it to be found in spam. In our context:" }, { "code": null, "e": 2286, "s": 2236, "text": "P_spam — the part of spam messages in our dataset" }, { "code": null, "e": 2358, "s": 2286, "text": "P_wi_spam — the probability of a word to be found in the spam messages." }, { "code": null, "e": 2387, "s": 2358, "text": "By the same logic we define:" }, { "code": null, "e": 2445, "s": 2387, "text": "P_not_spam — the part of non-spam messages in the dataset" }, { "code": null, "e": 2525, "s": 2445, "text": "P_wi_non_spam — the probability of a word to be found in the non-spam messages." }, { "code": null, "e": 2625, "s": 2525, "text": "But we still do not know how to calculate each word probabilities. Though, we have another formula:" }, { "code": null, "e": 2647, "s": 2625, "text": "What do we have here:" }, { "code": null, "e": 2711, "s": 2647, "text": "N_vocabulary — the number of unique words in the whole dataset." }, { "code": null, "e": 2768, "s": 2711, "text": "N_spam — the total number of words in the spam messages." }, { "code": null, "e": 2831, "s": 2768, "text": "N_wi_spam — the number of a word repeats in all spam messages." }, { "code": null, "e": 2922, "s": 2831, "text": "Alpha — the coefficient for the cases when a word in the message is absent in our dataset." }, { "code": null, "e": 3050, "s": 2922, "text": "Shortly: the probability of a word to belong to the spam message is a frequency of this word in the “spam part” of our dataset." }, { "code": null, "e": 3170, "s": 3050, "text": "Also, the same formula (but with other values) is correct for the probability of a word to belong to non-spam messages." }, { "code": null, "e": 3271, "s": 3170, "text": "The math is over, but do not worry — I will show all the values and formulas on the dataset example." }, { "code": null, "e": 3483, "s": 3271, "text": "For our purpose, we will use the collection of SMS messages, which was put together by Tiago A. Almeida and José María Gómez Hidalgo. It is free and can be downloaded from the UCI Machine Learning Repository." }, { "code": null, "e": 3608, "s": 3483, "text": "Dataset structure is simple. It contains two columns — one for the label “spam/ham” and another for the text of the message." }, { "code": null, "e": 3688, "s": 3608, "text": "It contains 5572 records of different messages together with 747 spam messages." }, { "code": null, "e": 3745, "s": 3688, "text": "sms_data.groupby('Label').count()Out[6]:ham 4825spam 747" }, { "code": null, "e": 3788, "s": 3745, "text": "We have enough data to start the analysis." }, { "code": null, "e": 3985, "s": 3788, "text": "Before the algorithm application, we need to prepare data. First of all, we will remove the punctuation. Then we will convert all the text into the lower-case and split it into the separate words." }, { "code": null, "e": 4121, "s": 3985, "text": "The next thing is to split the dataset to train and test data. But we also need to keep the distribution of spam and non-spam messages." }, { "code": null, "e": 4224, "s": 4121, "text": "And at last, we have to prepare the vocabulary and count the number of separate words in each message." }, { "code": null, "e": 4285, "s": 4224, "text": "Concat the resulting table of words count to our train data:" }, { "code": null, "e": 4308, "s": 4285, "text": "And the data is ready." }, { "code": null, "e": 4380, "s": 4308, "text": "We will follow the formulas mentioned above and define the main values:" }, { "code": null, "e": 4414, "s": 4380, "text": "probability of message to be spam" }, { "code": null, "e": 4487, "s": 4414, "text": "Pspam = train_data[‘Label’].value_counts()[‘spam’] / train_data.shape[0]" }, { "code": null, "e": 4519, "s": 4487, "text": "probability of non-spam message" }, { "code": null, "e": 4590, "s": 4519, "text": "Pham = train_data[‘Label’].value_counts()[‘ham’] / train_data.shape[0]" }, { "code": null, "e": 4627, "s": 4590, "text": "the number of words in spam messages" }, { "code": null, "e": 4728, "s": 4627, "text": "Nspam = train_data.loc[train_data[‘Label’] == ‘spam’, ‘SMS’].apply(len).sum()" }, { "code": null, "e": 4769, "s": 4728, "text": "the number of words in non-spam messages" }, { "code": null, "e": 4866, "s": 4769, "text": "Nham = train_data.loc[train_data[‘Label’] == ‘ham’, ‘SMS’].apply(len).sum()" }, { "code": null, "e": 4893, "s": 4866, "text": "the size of the vocabulary" }, { "code": null, "e": 4928, "s": 4893, "text": "Nvoc = len(train_data.columns - 3)" }, { "code": null, "e": 4942, "s": 4928, "text": "set alpha = 1" }, { "code": null, "e": 5085, "s": 4942, "text": "To complete the formula we will define the functions to determine the probabilities of the given word to belong to spam and non-spam messages:" }, { "code": null, "e": 5114, "s": 5085, "text": "Our classification function:" }, { "code": null, "e": 5234, "s": 5114, "text": "After the function application, we see impressive results on the test data: 99.1% of data were successfully classified." }, { "code": null, "e": 5307, "s": 5234, "text": "Just for the interest let’s look on the incorrectly recognized messages:" }, { "code": null, "e": 5531, "s": 5307, "text": "Now you are familiar (or freshened up in the memory) with one of the most effective spam-classification algorithms. I hope it was helpful and descriptive. You can find the Jupyter notebook with working example on my GitHub:" }, { "code": null, "e": 5542, "s": 5531, "text": "github.com" } ]
How to change color of Button in Android when Clicked?
This example demonstrates about How do I change the color of Button in Android when clicked. Step 1 − Create a new project in Android Studio, go to File ⇒ New Project and fill all required details to create a new project. Step 2 − Add the following code to res/layout/activity_main.xml. <?xml version="1.0" encoding="utf-8"?> <android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" tools:context=".MainActivity"> <Button android:id="@+id/button" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Click here to change color!" app:layout_constraintBottom_toBottomOf="parent" app:layout_constraintLeft_toLeftOf="parent" app:layout_constraintRight_toRightOf="parent" app:layout_constraintTop_toTopOf="parent" tools:ignore="HardcodedText" /> </android.support.constraint.ConstraintLayout> Step 3 − Add the following code to src/MainActivity.java import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.view.View; import android.widget.Button; public class MainActivity extends AppCompatActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); final Button button = findViewById(R.id.button); button.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { button.setBackgroundColor(getResources().getColor(R.color.colorPrimary)); } }); } } Step 4 − Add the following code to androidManifest.xml <?xml version="1.0" encoding="utf-8"?> <manifest xmlns:android="http://schemas.android.com/apk/res/android" package="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": 1155, "s": 1062, "text": "This example demonstrates about How do I change the color of Button in Android when clicked." }, { "code": null, "e": 1284, "s": 1155, "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": 1349, "s": 1284, "text": "Step 2 − Add the following code to res/layout/activity_main.xml." }, { "code": null, "e": 2178, "s": 1349, "text": "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<android.support.constraint.ConstraintLayout\n xmlns:android=\"http://schemas.android.com/apk/res/android\"\n xmlns:app=\"http://schemas.android.com/apk/res-auto\"\n xmlns:tools=\"http://schemas.android.com/tools\"\n android:layout_width=\"match_parent\"\n android:layout_height=\"match_parent\"\n tools:context=\".MainActivity\">\n <Button\n android:id=\"@+id/button\"\n android:layout_width=\"wrap_content\"\n android:layout_height=\"wrap_content\"\n android:text=\"Click here to change color!\"\n app:layout_constraintBottom_toBottomOf=\"parent\"\n app:layout_constraintLeft_toLeftOf=\"parent\"\n app:layout_constraintRight_toRightOf=\"parent\"\n app:layout_constraintTop_toTopOf=\"parent\"\n tools:ignore=\"HardcodedText\" />\n</android.support.constraint.ConstraintLayout>" }, { "code": null, "e": 2235, "s": 2178, "text": "Step 3 − Add the following code to src/MainActivity.java" }, { "code": null, "e": 2868, "s": 2235, "text": "import android.support.v7.app.AppCompatActivity;\nimport android.os.Bundle;\nimport android.view.View;\nimport android.widget.Button;\npublic class MainActivity extends AppCompatActivity {\n @Override\n protected void onCreate(Bundle savedInstanceState) {\n super.onCreate(savedInstanceState);\n setContentView(R.layout.activity_main);\n final Button button = findViewById(R.id.button);\n button.setOnClickListener(new View.OnClickListener() {\n @Override\n public void onClick(View view) {\n button.setBackgroundColor(getResources().getColor(R.color.colorPrimary));\n }\n });\n }\n}" }, { "code": null, "e": 2923, "s": 2868, "text": "Step 4 − Add the following code to androidManifest.xml" }, { "code": null, "e": 3593, "s": 2923, "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": 3941, "s": 3593, "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": 3983, "s": 3941, "text": "Click here to download the project code" } ]
Estimating Causal Effects on Financial Time-Series with Causal Impact BSTS | by Chris Price | Towards Data Science
Note from Towards Data Science’s editors: While we allow independent authors to publish articles in accordance with our rules and guidelines, we do not endorse each author’s contribution. You should not rely on an author’s works without seeking professional advice. See our Reader Terms for details. The ability to quantify and explicate the impact of a known event on a dependent variable is a data science skill whose utility applies to innumerable disciplines. The impact of such analysis, however, and its ability to influence a business decision (notwithstanding the veracity of the analysis itself!) is only as a good as the Data Scientist/Analyst/Quant’s ability to rationalise the underlying choice of model and its decision, as well as the requisite domain expertise and understanding of the dependent variable. Google’s Causal Impact library (implemented in both R and Python) can help us accomplish such a task in a very short space of time while providing methods that enable the user to fully explain the underlying modelling process and the model’s decision. In this article, we are going to briefly explore how we can implement a Causal Impact model to estimate the effect of the Vale dam collapse on the spot price of Iron Ore. You can find all of the code found in this article here. Google’s Causal Impact library provides a very straightforward implementation of a Structural Time-Series model that estimates the effect of a ‘designed’ intervention on a target time-series. This effect is measured by analysing the differences between the expected and the observed behaviour — specifically, the model generates a forecast counterfactual i.e. the expected observations of how the dependent variable might have evolved after the event had the event not occurred. Originally developed as an R package, Causal Impact works by fitting a Bayesian Structural Time Series (BSTS) model to a set of target and control time series observations, and subsequently performs posterior inference on the counterfactual. For reference, structural time-series models are state-space models for time-series data, and can be defined in terms of the following pair of equations: In the above expressions: Eq 1. is the observation equation. This links the observed data y_t to a latent d-dimensional state vector, α_t. Equation 2. is the state equation; it governs the evolution of the state vector α_t through time. In other words, the alpha variable refers to the “state” of the time-series, and y_t is a linear combination of the states, plus a linear regression with some explanatory covariates, X, plus some epsilon, ε, of noise that is normally distributed about a mean of 0. Epsilon_t and eta_t are independent of all other unknowns. At this stage, it is worth noting one of the key differences between BSTS models and traditional statistical/deep learning variants: Traditional time series forecasting architectures such as Linear Regression models, which estimate their coefficients via Maximum Likelihood Estimation, or, on the more powerful end of the scale, an LSTM which learns a function that maps a sequence of past observations as input to an output observation. BSTS models, on the other hand, employ a probabilistic approach to modelling a time series problem, namely, they return a posterior predictive distribution over which we can sample to provide not only a forecast but also a means of quantifying model uncertainty. Bayesian Structural-Time Series models are particularly powerful models in that they can generalise to a very large class of time series models such as ARIMA, SARIMAX, Holt-Winters to name but a few. You can observe, in the above expression, how we can achieve this by varying the matrices X, Z, T, G and R in order to model distinct behaviours and structure in the observed time-series, as well as adding linear covariates, BetaX, that might also be predictive of the dependent variable. Example - Second-Order AutoRegressive Process: Consider an example where we want to model a time series’s temporal structure (autocorrelation). We can model the time series as a second-order autoregressive process AR(2), by adjusting the expressions above!: Definition of an AR(2) process: In state-space form: In light of this flexibility to choose any time series model you want to fit your data, one can quickly see how powerful these models can be. But this sounds like a lot of work? Well, yes, but fear not. The wonderful thing about Causal Impact, should you require an expedient initial analysis, is that you don’t have to explicitly define any of the model’s structural components. If this is indeed the case, and you do not specify a model as in input, a local level model is built by default and is one that estimates the salient structural components of your time series for you. With the local level model, the target time-series, y, is defined as: Here, a given point in time is modelled as a random-walk component, mu_t (also known as the local level component). Trend and seasonal components, gamma_t, are modelled as unobserved components. The trend is modelled as a fixed intercept and the seasonal components using trigonometric functions with fixed periodicities and harmonics. For a more detailed mathematical explanation, one can refer to the Causal Impact documentation here, and the Statsmodels state-space seasonal documentation, whose logic is followed by that of the Python variant of Causal Impact. In summary, our implementation (in Python) therefore is reduced to a one-line expression!: ci_model = CausalImpact(target, pre_period, post_period) For those interested in how to build a Bayesian Structural Time-Series in detail using TensorFlow you can see how in this article: https://towardsdatascience.com/structural-time-series-forecasting-with-tensorflow-probability-iron-ore-mine-production-897d2334c72b Otherwise, let’s take a look at Causal Impact in action. We are going to explore how we can implement Causal Impact in estimating the effect of the Vale dam collapse on the spot price of Iron Ore. Whilst this event does not constitute a ‘designed’ intervention, utility still exists in the financial world in providing estimates of price moves in response to future events of a similar nature. Moreover, this is intended to serve as a demonstration of the utility of Google’s Causal Impact package in estimating the impact of an event on a response time-series. As a reminder, the link to the Python colab notebook can be found here. Vale Dam Incident In this instance, we are estimating the impact of the Vale dam incident that occurred at Vale’s (the worlds largest producer of Iron ore) Córrego do Feijão mine on the 25th January 2019, on the spot price of Iron ore. Caveat: Whilst modelling the outcome of any financial time-series is generally a highly-complicated, non-linear problem requiring far greater consideration and technical application than we are demonstrating, the intention of this demonstration is to illustrate the utility and expediency at which CI can perform such an analysis, and its interpretability — a pre-requisite quality in any business environment. We begin by acquiring our spot iron ore price data, then plotting the close price of the spot iron ore time-series. We also create a 21 and 252 day rolling average to give us a directional steer on the current price movements: import matplotlib.pyplot as pltimport numpy as npimport pandas as pdfrom causalimpact import CausalImpactfrom statsmodels.tsa.seasonal import seasonal_decompose# Get spot pricesdf = pd.read_excel( '/Users/CMP/OneDrive/PriceCurves/IO_Spot_2015010120200501.xlsx', index_col='date')# Plot close price, 21d and 252 roll avg.df['close'].plot(lw=2., figsize=(14,6), label='Close Price',c='royalblue')df['close'].rolling(21).mean().plot(lw=1.5, label='Roll_21d',c='orange')df['close'].rolling(252).mean().plot(lw=1.5, label='Roll_252d', c='salmon')plt.title('Spot Iron Ore Historical ($/MT), 2015-2020')plt.ylabel('Close Price, $/MT')plt.grid(); plt.legend() So far so good. Prior to defining our pre-event and post-event periods, we can get a better idea of the magnitude of the event itself visually by marking the date of the event and plotting it: In the above chart, you can observe two events: The first data point indicates the date of the Vale dam collapse.The second data-point/event was a warning from Vale regarding the stability of one of its tailings dams. The first data point indicates the date of the Vale dam collapse. The second data-point/event was a warning from Vale regarding the stability of one of its tailings dams. As with all forecast problems, it is imperative that we fully consider the assumptions made by any model before applying it to our problem. Control Set: In the case of Causal Impact, the model assumes that a set control time series exists that was not itself affected by the event. In the context of our problem, this assumption is not strictly relevant.External Covariates: An additional assumption that is relevant, however, is that the model assumes that the relationship between external covariates and the target time series, as established during the pre-period, remains stable throughout the post-period. In the context of our problem, it is highly likely that features may be predictive of the price of iron ore would likely also be affected by the event.Model Priors: The prior distributions for the unobserved states differ depending on whether you have chosen to implement Causal Impact in R, or Python. The R variant of Causal Impact sets the prior for the unobserved state based on the first observation of the target series, and the variance of the dataset. Statsmodels, on the other hand, uses a diffuse (uniform) prior. This shouldn’t result in any major differences between the two but it is worth bearing in mind (see observations, criticisms & further analysis for the key differences between the R and Python packages). Control Set: In the case of Causal Impact, the model assumes that a set control time series exists that was not itself affected by the event. In the context of our problem, this assumption is not strictly relevant. External Covariates: An additional assumption that is relevant, however, is that the model assumes that the relationship between external covariates and the target time series, as established during the pre-period, remains stable throughout the post-period. In the context of our problem, it is highly likely that features may be predictive of the price of iron ore would likely also be affected by the event. Model Priors: The prior distributions for the unobserved states differ depending on whether you have chosen to implement Causal Impact in R, or Python. The R variant of Causal Impact sets the prior for the unobserved state based on the first observation of the target series, and the variance of the dataset. Statsmodels, on the other hand, uses a diffuse (uniform) prior. This shouldn’t result in any major differences between the two but it is worth bearing in mind (see observations, criticisms & further analysis for the key differences between the R and Python packages). With the basic information above, let’s fit the basic model to our spot price data, and examine the output. Implementation simple and straightforward: # Define training data - period prior to the eventpre_period = ['2016-01-04', '2019-01-24'] # Define post-event period - i.e. time AFTER the event occurred.post_period = ['2019-01-25', '2019-08-01'] # Instantiate CI model.ci = CausalImpact(df['close'], pre_period, post_period) Note: Causal Impact can (handily) accept date strings when specifying the bounds of our pre and post-event periods. Fitting the Causal Impact model to our data returns an object whose methods when invoked, allow us to check model results, fitted parameters, etc. For now, we shall plot the results: As you can observe in the above chart, by calling the.plot()method on our CI object we can access the results of the fitting process. By default, the plot method renders three separate charts: The observed ‘post-event’ time series and fitted model’s forecast counterfactualThe pointwise causal effect, as estimated by the model. This is the difference between the observed outcome and the predicted outcome.The cumulative effect. The observed ‘post-event’ time series and fitted model’s forecast counterfactual The pointwise causal effect, as estimated by the model. This is the difference between the observed outcome and the predicted outcome. The cumulative effect. Additionally, by invoking the CI object’s .summary()method, we yield a convenient summary report: print(ci.summary()) Examination of the above output reveals the results of the fitted model: The Average column refers to the average price (over the time period) during the post-intervention period. The Cumulative column is the sum of the individual daily observations — not so useful in our case, however very useful if the dependant variable is a metric whose cumulative sum is part of your experiment; additional sales, clicks, etc. A cursory glance at the forecast counterfactual and the point-wise effect suggests that an event of this magnitude has had a significant effect on the spot price. Indeed, the model asserts, with confidence, that the Vale dam incident had an absolute causal effect of $21, varying from $18.04 to $23.98. It is also important to note the p-value here (< .05) to understand whether the observed behaviour is statistically significant or simply occurred by chance. It is immediately apparent, however, that our default model’s forecast counterfactual doesn’t look terribly convincing. For the most part, it would appear directionally accurate, however, it has clearly failed to capture the salient price movements, and the forecast appears to lag behind the observed spot price. We can check the fitted model’s parameters and diagnostics to assess whether the model conforms to its underlying statistical assumptions: ci.trained_model.summary() # Plot residuals diagnostics _ = ci.trained_model.plot_diagnostics(figsize=(14,6)) Examination of Figure.1 above shows the parameters of the fitted model. A full explanation of the individual results is beyond the scope of this article, however the salient points, namely the model components; sigma2.irregular and sigma2.level and their coefficients show how weakly predictive they are of our target, the spot price of iron ore. Indeed, if we consider figure 2 and the plot of the residuals we can examine the magnitude of the model errors, ‘Standardized residual for c’. We can also observe that the errors follow a distinctly non-normal distribution, and exhibit strong autocorrelation. Nevertheless, we have effectively established a baseline model to estimate the effect of the event on our target variable. We have just implemented our first Causal Impact model and estimated the causal effect of the Vale dam incident on our spot iron ore data. So far, we’ve let the package decide how to construct a time-series model for our spot price data, and found, as a result of the fitted model’s diagnostics, that we cannot be confident of the inferred effect. As mentioned above, a useful quality of structural time-series models is their modularity, affording us the flexibility to model individual behavioural dynamics of our time series such as seasonality, for example. The Causal Impact module offers several options that enable us to accomplish this, which we will exploit in an attempt to improve our inferred counterfactual. In an attempt to improve our model and the forecast counterfactual, we will employ our domain expertise and adjust our model to include a known seasonal component frequently manifest in spot iron ore price action, and incorporate two features that exhibit a known linear correlation with the spot price of iron ore: spot steel scrap and Chinese domestic steel reinforcing bar (rebar): We will begin by trialling the addition of a known seasonal component to our model. For many bulk commodities, prices tend to rise in the Chinese summer and winter ahead of peak periods of construction in the spring and autumn. The same behaviour can typically be observed with that of iron ore. For reference, a seasonal component can be described as a pattern that repeats itself with periodicity i.e. the signal is periodic. By decomposing our time series into its constituent structural components, we observe the degree to which the aforementioned seasonality affects the spot price: s_dc = seasonal_decompose(df['close'], model='additive', period=252).plot() Note: Statsmodels seasonal_decompose performs a naive decomposition of our time series — more sophisticated approaches would, and should typically be employed, particularly as our time-series is a financial one. For the purposes of this article and demonstrating how to add these as components to our model, however, this shall suffice. Isolating a few examples corroborates our prior belief/domain expertise: we can see that the seasonal component’s frequency and amplitude correspond with the Chinese summer and winter: It would appear that the signal has a rough periodicity of 146 days, and a harmonic of 1, although these are crude interpretations. We can observe that the amplitude of the winter peak in both examples is of lesser magnitude than that of the summer, therefore the signal itself is not strictly symmetric. For now, we will proceed on our assumptions for the purposes of demonstration. Incorporating seasonal components in Causal Impact is very straightforward: the Causal Impact class accepts a list of dictionaries containing the periodicity of each seasonal signal, and, if known, the harmonics: # Example - Adding seasonal components to a CI modelci = CausalImpact( df['close'], pre_period, post_period, nseasons=[{'period': 146, 'harmonics': 1}]) We can now add the external covariates to our model, spot steel scrap price and Chinese domestic reinforcing bar. Again, adding external covariates to our Causal Impact model is simple. These can be passed as a Pandas data frame along with our target variable. As per the source code, Causal Impact expects the target/label column to be in the first index (0). All subsequent columns are registered as external covariates: df_1 = pd.concat([df, steel_scrap_df, rebar_df], join='inner', axis=1) We then pass this data frame to our Causal Impact model, along with the same pre and post-period event definitions and our seasonal component. Note that we will not specify the harmonics of our seasonal component*: # Fit new seasonal + beta coef variantci_1 = CausalImpact(df_1, pre_period, post_period, nseasons=[{'period': 146}])# Plot resultci_1.plot(figsize=(12, 6)) *model defaults to calculating this as math.floor(periodicity / 2)) Upon inspecting the counterfactual of our new model, we can observe a far more credible result. It would still appear as though we need to account for the temporal (autocorrelative) structure in the time series and can include this in a subsequent model, but the result would appear credible for a first pass. Upon checking the fitted model’s parameters, we can see that our seasonal component and it’s definition needs re-evaluating, whereas our external covariates explain a lot of what is observed in our response variable: Finally, we can have our model estimate the impact as a result of the Vale dam incident on our target with the useful method,.summary('report') that returns a detailed explanation of the observed effects: Here, we can see that the model concludes, with significance, that the incident resulted in a +33% increase in the spot price of iron ore — and logically, therefore, had the incident not occurred, then the spot price would have traded 33% lower during this period. In this article, we have learned how Google’s Causal Impact package can be used to estimate the causal effect of an intervention on an observed time-series. Specifically, we implemented a CI model to estimate the effect of the Vale dam incident on the spot price of Iron Ore. Furthermore, we have learned: What Bayesian Structural Time-Series Models are, their capabilities and to a degree, their limitations (see below). What Google’s Causal Impact library is, and what it does. How to implement a basic/default Causal Impact model. How to implement a more sophisticated variant, by defining and adding known seasonal components and linearly correlated exogenous variables as linear covariates. How to evaluate our fitted model’s results. Parameter Estimation: Depending on whether you implement Causal Impact in R or Python, you may find your models return disparate results. This is as a result of the different estimation methods employed by the respective libraries: The Python variant employs a Statsmodels Unobserved Components implementation to model the target time-series and whose parameters are estimated using maximum likelihood. The R variant employs the BSTS library whose parameters are estimated with Bayesian MCMC. Seasonality: See limitations mentioned above under ‘Adding seasonal component’ Models Architectural Ability: It is a good idea to examine how well the target variable can be predicted before the intervention, by running CausalImpact() on a contrived intervention. This acts as a sanity check as to the model’s ability to capture the relevant structure in the data following this imaginary intervention. Logically, we would expect not to find a significant effect, i.e., counterfactual estimates and actual data should agree reasonably close. Model Assumptions: see ‘model assumptions’ above. Further note that we did not model for autocorrelation, inherent in nearly all financial time-series. Custom models: Please note that did not cover how to define custom models in this article, which would be verbose, and out of scope. However, a parameter of the Causal Impact class, model , enables us to pass any Statsmodels state-space model as an argument, illustrating the power and flexibility of the CI library. Many thanks for taking the time to read this article and as always, I welcome all constructive criticisms and comments. CausalImpact 1.2.1, Brodersen et al., Annals of Applied Statistics (2015), http://google.github.io/CausalImpact/” CausalImpact 1.2.1, Brodersen et al., Annals of Applied Statistics (2015), http://google.github.io/CausalImpact/”
[ { "code": null, "e": 471, "s": 171, "text": "Note from Towards Data Science’s editors: While we allow independent authors to publish articles in accordance with our rules and guidelines, we do not endorse each author’s contribution. You should not rely on an author’s works without seeking professional advice. See our Reader Terms for details." }, { "code": null, "e": 992, "s": 471, "text": "The ability to quantify and explicate the impact of a known event on a dependent variable is a data science skill whose utility applies to innumerable disciplines. The impact of such analysis, however, and its ability to influence a business decision (notwithstanding the veracity of the analysis itself!) is only as a good as the Data Scientist/Analyst/Quant’s ability to rationalise the underlying choice of model and its decision, as well as the requisite domain expertise and understanding of the dependent variable." }, { "code": null, "e": 1244, "s": 992, "text": "Google’s Causal Impact library (implemented in both R and Python) can help us accomplish such a task in a very short space of time while providing methods that enable the user to fully explain the underlying modelling process and the model’s decision." }, { "code": null, "e": 1472, "s": 1244, "text": "In this article, we are going to briefly explore how we can implement a Causal Impact model to estimate the effect of the Vale dam collapse on the spot price of Iron Ore. You can find all of the code found in this article here." }, { "code": null, "e": 1951, "s": 1472, "text": "Google’s Causal Impact library provides a very straightforward implementation of a Structural Time-Series model that estimates the effect of a ‘designed’ intervention on a target time-series. This effect is measured by analysing the differences between the expected and the observed behaviour — specifically, the model generates a forecast counterfactual i.e. the expected observations of how the dependent variable might have evolved after the event had the event not occurred." }, { "code": null, "e": 2193, "s": 1951, "text": "Originally developed as an R package, Causal Impact works by fitting a Bayesian Structural Time Series (BSTS) model to a set of target and control time series observations, and subsequently performs posterior inference on the counterfactual." }, { "code": null, "e": 2347, "s": 2193, "text": "For reference, structural time-series models are state-space models for time-series data, and can be defined in terms of the following pair of equations:" }, { "code": null, "e": 2373, "s": 2347, "text": "In the above expressions:" }, { "code": null, "e": 2486, "s": 2373, "text": "Eq 1. is the observation equation. This links the observed data y_t to a latent d-dimensional state vector, α_t." }, { "code": null, "e": 2849, "s": 2486, "text": "Equation 2. is the state equation; it governs the evolution of the state vector α_t through time. In other words, the alpha variable refers to the “state” of the time-series, and y_t is a linear combination of the states, plus a linear regression with some explanatory covariates, X, plus some epsilon, ε, of noise that is normally distributed about a mean of 0." }, { "code": null, "e": 2908, "s": 2849, "text": "Epsilon_t and eta_t are independent of all other unknowns." }, { "code": null, "e": 3041, "s": 2908, "text": "At this stage, it is worth noting one of the key differences between BSTS models and traditional statistical/deep learning variants:" }, { "code": null, "e": 3609, "s": 3041, "text": "Traditional time series forecasting architectures such as Linear Regression models, which estimate their coefficients via Maximum Likelihood Estimation, or, on the more powerful end of the scale, an LSTM which learns a function that maps a sequence of past observations as input to an output observation. BSTS models, on the other hand, employ a probabilistic approach to modelling a time series problem, namely, they return a posterior predictive distribution over which we can sample to provide not only a forecast but also a means of quantifying model uncertainty." }, { "code": null, "e": 4098, "s": 3609, "text": "Bayesian Structural-Time Series models are particularly powerful models in that they can generalise to a very large class of time series models such as ARIMA, SARIMAX, Holt-Winters to name but a few. You can observe, in the above expression, how we can achieve this by varying the matrices X, Z, T, G and R in order to model distinct behaviours and structure in the observed time-series, as well as adding linear covariates, BetaX, that might also be predictive of the dependent variable." }, { "code": null, "e": 4145, "s": 4098, "text": "Example - Second-Order AutoRegressive Process:" }, { "code": null, "e": 4356, "s": 4145, "text": "Consider an example where we want to model a time series’s temporal structure (autocorrelation). We can model the time series as a second-order autoregressive process AR(2), by adjusting the expressions above!:" }, { "code": null, "e": 4388, "s": 4356, "text": "Definition of an AR(2) process:" }, { "code": null, "e": 4409, "s": 4388, "text": "In state-space form:" }, { "code": null, "e": 4551, "s": 4409, "text": "In light of this flexibility to choose any time series model you want to fit your data, one can quickly see how powerful these models can be." }, { "code": null, "e": 4587, "s": 4551, "text": "But this sounds like a lot of work?" }, { "code": null, "e": 4789, "s": 4587, "text": "Well, yes, but fear not. The wonderful thing about Causal Impact, should you require an expedient initial analysis, is that you don’t have to explicitly define any of the model’s structural components." }, { "code": null, "e": 5060, "s": 4789, "text": "If this is indeed the case, and you do not specify a model as in input, a local level model is built by default and is one that estimates the salient structural components of your time series for you. With the local level model, the target time-series, y, is defined as:" }, { "code": null, "e": 5625, "s": 5060, "text": "Here, a given point in time is modelled as a random-walk component, mu_t (also known as the local level component). Trend and seasonal components, gamma_t, are modelled as unobserved components. The trend is modelled as a fixed intercept and the seasonal components using trigonometric functions with fixed periodicities and harmonics. For a more detailed mathematical explanation, one can refer to the Causal Impact documentation here, and the Statsmodels state-space seasonal documentation, whose logic is followed by that of the Python variant of Causal Impact." }, { "code": null, "e": 5716, "s": 5625, "text": "In summary, our implementation (in Python) therefore is reduced to a one-line expression!:" }, { "code": null, "e": 5773, "s": 5716, "text": "ci_model = CausalImpact(target, pre_period, post_period)" }, { "code": null, "e": 5904, "s": 5773, "text": "For those interested in how to build a Bayesian Structural Time-Series in detail using TensorFlow you can see how in this article:" }, { "code": null, "e": 6036, "s": 5904, "text": "https://towardsdatascience.com/structural-time-series-forecasting-with-tensorflow-probability-iron-ore-mine-production-897d2334c72b" }, { "code": null, "e": 6093, "s": 6036, "text": "Otherwise, let’s take a look at Causal Impact in action." }, { "code": null, "e": 6670, "s": 6093, "text": "We are going to explore how we can implement Causal Impact in estimating the effect of the Vale dam collapse on the spot price of Iron Ore. Whilst this event does not constitute a ‘designed’ intervention, utility still exists in the financial world in providing estimates of price moves in response to future events of a similar nature. Moreover, this is intended to serve as a demonstration of the utility of Google’s Causal Impact package in estimating the impact of an event on a response time-series. As a reminder, the link to the Python colab notebook can be found here." }, { "code": null, "e": 6688, "s": 6670, "text": "Vale Dam Incident" }, { "code": null, "e": 6908, "s": 6688, "text": "In this instance, we are estimating the impact of the Vale dam incident that occurred at Vale’s (the worlds largest producer of Iron ore) Córrego do Feijão mine on the 25th January 2019, on the spot price of Iron ore." }, { "code": null, "e": 7319, "s": 6908, "text": "Caveat: Whilst modelling the outcome of any financial time-series is generally a highly-complicated, non-linear problem requiring far greater consideration and technical application than we are demonstrating, the intention of this demonstration is to illustrate the utility and expediency at which CI can perform such an analysis, and its interpretability — a pre-requisite quality in any business environment." }, { "code": null, "e": 7546, "s": 7319, "text": "We begin by acquiring our spot iron ore price data, then plotting the close price of the spot iron ore time-series. We also create a 21 and 252 day rolling average to give us a directional steer on the current price movements:" }, { "code": null, "e": 8204, "s": 7546, "text": "import matplotlib.pyplot as pltimport numpy as npimport pandas as pdfrom causalimpact import CausalImpactfrom statsmodels.tsa.seasonal import seasonal_decompose# Get spot pricesdf = pd.read_excel( '/Users/CMP/OneDrive/PriceCurves/IO_Spot_2015010120200501.xlsx', index_col='date')# Plot close price, 21d and 252 roll avg.df['close'].plot(lw=2., figsize=(14,6), label='Close Price',c='royalblue')df['close'].rolling(21).mean().plot(lw=1.5, label='Roll_21d',c='orange')df['close'].rolling(252).mean().plot(lw=1.5, label='Roll_252d', c='salmon')plt.title('Spot Iron Ore Historical ($/MT), 2015-2020')plt.ylabel('Close Price, $/MT')plt.grid(); plt.legend()" }, { "code": null, "e": 8397, "s": 8204, "text": "So far so good. Prior to defining our pre-event and post-event periods, we can get a better idea of the magnitude of the event itself visually by marking the date of the event and plotting it:" }, { "code": null, "e": 8445, "s": 8397, "text": "In the above chart, you can observe two events:" }, { "code": null, "e": 8615, "s": 8445, "text": "The first data point indicates the date of the Vale dam collapse.The second data-point/event was a warning from Vale regarding the stability of one of its tailings dams." }, { "code": null, "e": 8681, "s": 8615, "text": "The first data point indicates the date of the Vale dam collapse." }, { "code": null, "e": 8786, "s": 8681, "text": "The second data-point/event was a warning from Vale regarding the stability of one of its tailings dams." }, { "code": null, "e": 8926, "s": 8786, "text": "As with all forecast problems, it is imperative that we fully consider the assumptions made by any model before applying it to our problem." }, { "code": null, "e": 10126, "s": 8926, "text": "Control Set: In the case of Causal Impact, the model assumes that a set control time series exists that was not itself affected by the event. In the context of our problem, this assumption is not strictly relevant.External Covariates: An additional assumption that is relevant, however, is that the model assumes that the relationship between external covariates and the target time series, as established during the pre-period, remains stable throughout the post-period. In the context of our problem, it is highly likely that features may be predictive of the price of iron ore would likely also be affected by the event.Model Priors: The prior distributions for the unobserved states differ depending on whether you have chosen to implement Causal Impact in R, or Python. The R variant of Causal Impact sets the prior for the unobserved state based on the first observation of the target series, and the variance of the dataset. Statsmodels, on the other hand, uses a diffuse (uniform) prior. This shouldn’t result in any major differences between the two but it is worth bearing in mind (see observations, criticisms & further analysis for the key differences between the R and Python packages)." }, { "code": null, "e": 10341, "s": 10126, "text": "Control Set: In the case of Causal Impact, the model assumes that a set control time series exists that was not itself affected by the event. In the context of our problem, this assumption is not strictly relevant." }, { "code": null, "e": 10751, "s": 10341, "text": "External Covariates: An additional assumption that is relevant, however, is that the model assumes that the relationship between external covariates and the target time series, as established during the pre-period, remains stable throughout the post-period. In the context of our problem, it is highly likely that features may be predictive of the price of iron ore would likely also be affected by the event." }, { "code": null, "e": 11328, "s": 10751, "text": "Model Priors: The prior distributions for the unobserved states differ depending on whether you have chosen to implement Causal Impact in R, or Python. The R variant of Causal Impact sets the prior for the unobserved state based on the first observation of the target series, and the variance of the dataset. Statsmodels, on the other hand, uses a diffuse (uniform) prior. This shouldn’t result in any major differences between the two but it is worth bearing in mind (see observations, criticisms & further analysis for the key differences between the R and Python packages)." }, { "code": null, "e": 11479, "s": 11328, "text": "With the basic information above, let’s fit the basic model to our spot price data, and examine the output. Implementation simple and straightforward:" }, { "code": null, "e": 11757, "s": 11479, "text": "# Define training data - period prior to the eventpre_period = ['2016-01-04', '2019-01-24'] # Define post-event period - i.e. time AFTER the event occurred.post_period = ['2019-01-25', '2019-08-01'] # Instantiate CI model.ci = CausalImpact(df['close'], pre_period, post_period)" }, { "code": null, "e": 11873, "s": 11757, "text": "Note: Causal Impact can (handily) accept date strings when specifying the bounds of our pre and post-event periods." }, { "code": null, "e": 12056, "s": 11873, "text": "Fitting the Causal Impact model to our data returns an object whose methods when invoked, allow us to check model results, fitted parameters, etc. For now, we shall plot the results:" }, { "code": null, "e": 12249, "s": 12056, "text": "As you can observe in the above chart, by calling the.plot()method on our CI object we can access the results of the fitting process. By default, the plot method renders three separate charts:" }, { "code": null, "e": 12486, "s": 12249, "text": "The observed ‘post-event’ time series and fitted model’s forecast counterfactualThe pointwise causal effect, as estimated by the model. This is the difference between the observed outcome and the predicted outcome.The cumulative effect." }, { "code": null, "e": 12567, "s": 12486, "text": "The observed ‘post-event’ time series and fitted model’s forecast counterfactual" }, { "code": null, "e": 12702, "s": 12567, "text": "The pointwise causal effect, as estimated by the model. This is the difference between the observed outcome and the predicted outcome." }, { "code": null, "e": 12725, "s": 12702, "text": "The cumulative effect." }, { "code": null, "e": 12823, "s": 12725, "text": "Additionally, by invoking the CI object’s .summary()method, we yield a convenient summary report:" }, { "code": null, "e": 12843, "s": 12823, "text": "print(ci.summary())" }, { "code": null, "e": 12916, "s": 12843, "text": "Examination of the above output reveals the results of the fitted model:" }, { "code": null, "e": 13023, "s": 12916, "text": "The Average column refers to the average price (over the time period) during the post-intervention period." }, { "code": null, "e": 13260, "s": 13023, "text": "The Cumulative column is the sum of the individual daily observations — not so useful in our case, however very useful if the dependant variable is a metric whose cumulative sum is part of your experiment; additional sales, clicks, etc." }, { "code": null, "e": 13721, "s": 13260, "text": "A cursory glance at the forecast counterfactual and the point-wise effect suggests that an event of this magnitude has had a significant effect on the spot price. Indeed, the model asserts, with confidence, that the Vale dam incident had an absolute causal effect of $21, varying from $18.04 to $23.98. It is also important to note the p-value here (< .05) to understand whether the observed behaviour is statistically significant or simply occurred by chance." }, { "code": null, "e": 14035, "s": 13721, "text": "It is immediately apparent, however, that our default model’s forecast counterfactual doesn’t look terribly convincing. For the most part, it would appear directionally accurate, however, it has clearly failed to capture the salient price movements, and the forecast appears to lag behind the observed spot price." }, { "code": null, "e": 14174, "s": 14035, "text": "We can check the fitted model’s parameters and diagnostics to assess whether the model conforms to its underlying statistical assumptions:" }, { "code": null, "e": 14201, "s": 14174, "text": "ci.trained_model.summary()" }, { "code": null, "e": 14284, "s": 14201, "text": "# Plot residuals diagnostics _ = ci.trained_model.plot_diagnostics(figsize=(14,6))" }, { "code": null, "e": 14631, "s": 14284, "text": "Examination of Figure.1 above shows the parameters of the fitted model. A full explanation of the individual results is beyond the scope of this article, however the salient points, namely the model components; sigma2.irregular and sigma2.level and their coefficients show how weakly predictive they are of our target, the spot price of iron ore." }, { "code": null, "e": 15014, "s": 14631, "text": "Indeed, if we consider figure 2 and the plot of the residuals we can examine the magnitude of the model errors, ‘Standardized residual for c’. We can also observe that the errors follow a distinctly non-normal distribution, and exhibit strong autocorrelation. Nevertheless, we have effectively established a baseline model to estimate the effect of the event on our target variable." }, { "code": null, "e": 15362, "s": 15014, "text": "We have just implemented our first Causal Impact model and estimated the causal effect of the Vale dam incident on our spot iron ore data. So far, we’ve let the package decide how to construct a time-series model for our spot price data, and found, as a result of the fitted model’s diagnostics, that we cannot be confident of the inferred effect." }, { "code": null, "e": 15735, "s": 15362, "text": "As mentioned above, a useful quality of structural time-series models is their modularity, affording us the flexibility to model individual behavioural dynamics of our time series such as seasonality, for example. The Causal Impact module offers several options that enable us to accomplish this, which we will exploit in an attempt to improve our inferred counterfactual." }, { "code": null, "e": 16120, "s": 15735, "text": "In an attempt to improve our model and the forecast counterfactual, we will employ our domain expertise and adjust our model to include a known seasonal component frequently manifest in spot iron ore price action, and incorporate two features that exhibit a known linear correlation with the spot price of iron ore: spot steel scrap and Chinese domestic steel reinforcing bar (rebar):" }, { "code": null, "e": 16548, "s": 16120, "text": "We will begin by trialling the addition of a known seasonal component to our model. For many bulk commodities, prices tend to rise in the Chinese summer and winter ahead of peak periods of construction in the spring and autumn. The same behaviour can typically be observed with that of iron ore. For reference, a seasonal component can be described as a pattern that repeats itself with periodicity i.e. the signal is periodic." }, { "code": null, "e": 16709, "s": 16548, "text": "By decomposing our time series into its constituent structural components, we observe the degree to which the aforementioned seasonality affects the spot price:" }, { "code": null, "e": 16785, "s": 16709, "text": "s_dc = seasonal_decompose(df['close'], model='additive', period=252).plot()" }, { "code": null, "e": 17122, "s": 16785, "text": "Note: Statsmodels seasonal_decompose performs a naive decomposition of our time series — more sophisticated approaches would, and should typically be employed, particularly as our time-series is a financial one. For the purposes of this article and demonstrating how to add these as components to our model, however, this shall suffice." }, { "code": null, "e": 17307, "s": 17122, "text": "Isolating a few examples corroborates our prior belief/domain expertise: we can see that the seasonal component’s frequency and amplitude correspond with the Chinese summer and winter:" }, { "code": null, "e": 17691, "s": 17307, "text": "It would appear that the signal has a rough periodicity of 146 days, and a harmonic of 1, although these are crude interpretations. We can observe that the amplitude of the winter peak in both examples is of lesser magnitude than that of the summer, therefore the signal itself is not strictly symmetric. For now, we will proceed on our assumptions for the purposes of demonstration." }, { "code": null, "e": 17904, "s": 17691, "text": "Incorporating seasonal components in Causal Impact is very straightforward: the Causal Impact class accepts a list of dictionaries containing the periodicity of each seasonal signal, and, if known, the harmonics:" }, { "code": null, "e": 18071, "s": 17904, "text": "# Example - Adding seasonal components to a CI modelci = CausalImpact( df['close'], pre_period, post_period, nseasons=[{'period': 146, 'harmonics': 1}])" }, { "code": null, "e": 18185, "s": 18071, "text": "We can now add the external covariates to our model, spot steel scrap price and Chinese domestic reinforcing bar." }, { "code": null, "e": 18494, "s": 18185, "text": "Again, adding external covariates to our Causal Impact model is simple. These can be passed as a Pandas data frame along with our target variable. As per the source code, Causal Impact expects the target/label column to be in the first index (0). All subsequent columns are registered as external covariates:" }, { "code": null, "e": 18565, "s": 18494, "text": "df_1 = pd.concat([df, steel_scrap_df, rebar_df], join='inner', axis=1)" }, { "code": null, "e": 18780, "s": 18565, "text": "We then pass this data frame to our Causal Impact model, along with the same pre and post-period event definitions and our seasonal component. Note that we will not specify the harmonics of our seasonal component*:" }, { "code": null, "e": 18936, "s": 18780, "text": "# Fit new seasonal + beta coef variantci_1 = CausalImpact(df_1, pre_period, post_period, nseasons=[{'period': 146}])# Plot resultci_1.plot(figsize=(12, 6))" }, { "code": null, "e": 19004, "s": 18936, "text": "*model defaults to calculating this as math.floor(periodicity / 2))" }, { "code": null, "e": 19531, "s": 19004, "text": "Upon inspecting the counterfactual of our new model, we can observe a far more credible result. It would still appear as though we need to account for the temporal (autocorrelative) structure in the time series and can include this in a subsequent model, but the result would appear credible for a first pass. Upon checking the fitted model’s parameters, we can see that our seasonal component and it’s definition needs re-evaluating, whereas our external covariates explain a lot of what is observed in our response variable:" }, { "code": null, "e": 19736, "s": 19531, "text": "Finally, we can have our model estimate the impact as a result of the Vale dam incident on our target with the useful method,.summary('report') that returns a detailed explanation of the observed effects:" }, { "code": null, "e": 20001, "s": 19736, "text": "Here, we can see that the model concludes, with significance, that the incident resulted in a +33% increase in the spot price of iron ore — and logically, therefore, had the incident not occurred, then the spot price would have traded 33% lower during this period." }, { "code": null, "e": 20277, "s": 20001, "text": "In this article, we have learned how Google’s Causal Impact package can be used to estimate the causal effect of an intervention on an observed time-series. Specifically, we implemented a CI model to estimate the effect of the Vale dam incident on the spot price of Iron Ore." }, { "code": null, "e": 20307, "s": 20277, "text": "Furthermore, we have learned:" }, { "code": null, "e": 20423, "s": 20307, "text": "What Bayesian Structural Time-Series Models are, their capabilities and to a degree, their limitations (see below)." }, { "code": null, "e": 20481, "s": 20423, "text": "What Google’s Causal Impact library is, and what it does." }, { "code": null, "e": 20535, "s": 20481, "text": "How to implement a basic/default Causal Impact model." }, { "code": null, "e": 20697, "s": 20535, "text": "How to implement a more sophisticated variant, by defining and adding known seasonal components and linearly correlated exogenous variables as linear covariates." }, { "code": null, "e": 20741, "s": 20697, "text": "How to evaluate our fitted model’s results." }, { "code": null, "e": 21234, "s": 20741, "text": "Parameter Estimation: Depending on whether you implement Causal Impact in R or Python, you may find your models return disparate results. This is as a result of the different estimation methods employed by the respective libraries: The Python variant employs a Statsmodels Unobserved Components implementation to model the target time-series and whose parameters are estimated using maximum likelihood. The R variant employs the BSTS library whose parameters are estimated with Bayesian MCMC." }, { "code": null, "e": 21313, "s": 21234, "text": "Seasonality: See limitations mentioned above under ‘Adding seasonal component’" }, { "code": null, "e": 21776, "s": 21313, "text": "Models Architectural Ability: It is a good idea to examine how well the target variable can be predicted before the intervention, by running CausalImpact() on a contrived intervention. This acts as a sanity check as to the model’s ability to capture the relevant structure in the data following this imaginary intervention. Logically, we would expect not to find a significant effect, i.e., counterfactual estimates and actual data should agree reasonably close." }, { "code": null, "e": 21928, "s": 21776, "text": "Model Assumptions: see ‘model assumptions’ above. Further note that we did not model for autocorrelation, inherent in nearly all financial time-series." }, { "code": null, "e": 22245, "s": 21928, "text": "Custom models: Please note that did not cover how to define custom models in this article, which would be verbose, and out of scope. However, a parameter of the Causal Impact class, model , enables us to pass any Statsmodels state-space model as an argument, illustrating the power and flexibility of the CI library." }, { "code": null, "e": 22365, "s": 22245, "text": "Many thanks for taking the time to read this article and as always, I welcome all constructive criticisms and comments." }, { "code": null, "e": 22479, "s": 22365, "text": "CausalImpact 1.2.1, Brodersen et al., Annals of Applied Statistics (2015), http://google.github.io/CausalImpact/”" } ]
How to identify the right independent variables for Machine Learning Supervised Algorithms? | by Kaushik Choudhury | Towards Data Science
There is a very famous acronym GIGO in the field of computer science which I have learnt in my school days. GIGO stands for garbage in and garbages out. Essentially it means that if we feed inappropriate and junk data to computer programs and algorithms, then it will result in junk and incorrect results. Machine learning algorithms are the same as us human beings. Broadly machine learning algorithms have two phases — learning and predicting. Learning environment and parameters should be similar to the condition in which prediction to be done in future. Algorithms trained on an unbiased data sample, and permutations of the input variables values a true reflection of full population dataset are well equipped to make an accurate prediction. One of the cornerstones for the success of the Supervised machine learning algorithms is selecting the right set of the independent variable for the learning phase. In this article, I will discuss a structured approach to select the right independent variables to feed the algorithms. We do not want to overfeed redundant data points i.e. highly related (Multicollinearity) data and complicate the model without increasing the prediction accuracy. In fact, sometime overfeeding the data can decrease the prediction accuracy. On the other hand, we need to make sure that the model is not oversimplified and reflects true complexity. Objective We want to build a model to predict the stock price of the company ASML. We have downloaded the stock price data of few of the ASML’s customer, competitors and index points for the last 20 years. We are not sure which of these data points to include to build the ASML stock prediction model. Sample Data File I have written a small function which I can call from different programs to download the stock price for the last 20 years. """Filename - GetStockData.py is a function to download the stock from 1st Jan 2000 until current date"""import datetime as dtimport pandas as pdimport pandas_datareader.data as webimport numpy as npdef stockdata(ticker): start= dt.datetime(2000,1,1) ## Start Date Range end=dt.datetime.now() ## Curret date as end date Range Stock=web.DataReader(ticker, "yahoo", start, end) name=str(ticker) + ".xlsx" Stock.to_excel(name) return () Function stockdata() is called from another program with ticker symbols to download the data. """ Filename - stockdownload.py"""import GetStockDataticker= ["MU", "ASML","TSM","QCOM", "UMC", "^SOX", "INTC","^IXIC"]for i in ticker: GetStockData.stockdata(i) Please note that GetStockData python file and stockdownload.py files are placed in the same file directory to import the file successfully. Step 1- The first step is to think of all the variables which may influence the dependent variables. At this step, I will suggest not to constraint your thinking and brain dump all the variables. Step 2- Next step is to collect/download the prospective independent variables data points for analysis. I have formatted and collated the downloaded data into one excel file “StockData.xlsx” Step 3- We will import the packages pandas, matplotlib, seaborn and statsmodels packages which we are going to use for our analysis. import pandas as pdimport matplotlib.pyplot as pltimport seaborn as snsfrom statsmodels.stats.outliers_influence import variance_inflation_factor Step 4- Read the full data sample data excel file into the PandasDataframe called “data”. Further, we will replace the index with the date column data=pd.read_excel("StockData.xlsx")data.set_index("Date", inplace= True) I will not focus on preliminary data quality checks like blank values, outliers, etc. and respective correction approach in this article, and assuming that there are no data series related to the discrepancy. Step 5- One of the best places to start understanding the relationship between the independent variable is the correlation between the variables. In the below code, heatmap of the correlation is plotted using .corr method in Pandas. sns.heatmap(data.corr(), annot=True, cmap="YlGnBu")plt.show() Correlation heatmap, as shown below, provides us with a visual depiction of the relationship between the variables. Now, we do not want a set of independent variables which has a more or less similar relationship with the dependent variables. For example, TSM and Nasdaq index has a correlation coefficient of 0.99 and 0.97 with ASML respectively. Including both TSM and NASDAQ may not improve the prediction accuracy as they have a similar relationship with the dependent variable, ASML stock price. Step 6- Before we start dropping the redundant independent variables, let us check the Variance inflation factor (VIF) among the independent variables. VIF quantifies the severity of multicollinearity in an ordinary least squares regression analysis. It provides an index that measures how much the variance (the square of the estimate’s standard deviation) of an estimated regression coefficient is increased because of collinearity. I will encourage you all to read the Wikipedia page on Variance inflation factor to gain a good understanding of it. In the below code we calculate the VIF of each independent variables and print it. We will create a new DataFrame without ASML historical stock prices as we aim is to determine the VIF among the potential independent variables. X=data.drop(["ASML"], axis=1)vif = pd.DataFrame()vif["features"] = X.columnsvif["vif_Factor"] = [variance_inflation_factor(X.values, i) for i in range(X.shape[1])]print(vif) In general, we should aim for the VIF of less than 10 for the independent variables. We have seen from the heatmap earlier that TSM and NASDAQ have similar correlation coefficient with ASML and the same is also reflecting with high VIF indicator. Based on our understanding from heatmap and VIF result let us drop NASDAQ (as highest VIF) as a potential candidate for the independent variable for our model and re-evaluate the VIF. X=data.drop(["ASML","NASDAQ"], axis=1)vif = pd.DataFrame()vif["features"] = X.columnsvif["vif_Factor"] = [variance_inflation_factor(X.values, i) for i in range(X.shape[1])]print(vif) We can see that on removing the NASDAQ, VIF of few other potential independent also decreased. Selecting the right combination of independent variables is a bit of experience along with trial and error VIF checking with different permutations. TSMC is a leading semiconductor foundry in the world and as a customer of ASML has a strong influence on ASML’s business. Considering this aspect, I will drop “INTC” and “PHLX” and re-evaluate the VIF for the remaining variables. As we can see that after two iterations we have VIF of all the remaining variables less than 10. We have removed the variables with multicollinearity and have identified the list of independent variables which are relevant for predicting the stock prices of ASML. I hope, in selecting the right sets of the independent variable for your machine learning models, you will find the approach explained in this program helpful. If you like this article then you may also like Machine Learning and Supply Chain Management: Hands-on Series Disclaimer — This article is written for educational purpose only. Do not make any actual stock buying, selling or any financial transaction based on the independent variables identified in this article.
[ { "code": null, "e": 477, "s": 171, "text": "There is a very famous acronym GIGO in the field of computer science which I have learnt in my school days. GIGO stands for garbage in and garbages out. Essentially it means that if we feed inappropriate and junk data to computer programs and algorithms, then it will result in junk and incorrect results." }, { "code": null, "e": 919, "s": 477, "text": "Machine learning algorithms are the same as us human beings. Broadly machine learning algorithms have two phases — learning and predicting. Learning environment and parameters should be similar to the condition in which prediction to be done in future. Algorithms trained on an unbiased data sample, and permutations of the input variables values a true reflection of full population dataset are well equipped to make an accurate prediction." }, { "code": null, "e": 1551, "s": 919, "text": "One of the cornerstones for the success of the Supervised machine learning algorithms is selecting the right set of the independent variable for the learning phase. In this article, I will discuss a structured approach to select the right independent variables to feed the algorithms. We do not want to overfeed redundant data points i.e. highly related (Multicollinearity) data and complicate the model without increasing the prediction accuracy. In fact, sometime overfeeding the data can decrease the prediction accuracy. On the other hand, we need to make sure that the model is not oversimplified and reflects true complexity." }, { "code": null, "e": 1561, "s": 1551, "text": "Objective" }, { "code": null, "e": 1853, "s": 1561, "text": "We want to build a model to predict the stock price of the company ASML. We have downloaded the stock price data of few of the ASML’s customer, competitors and index points for the last 20 years. We are not sure which of these data points to include to build the ASML stock prediction model." }, { "code": null, "e": 1870, "s": 1853, "text": "Sample Data File" }, { "code": null, "e": 1994, "s": 1870, "text": "I have written a small function which I can call from different programs to download the stock price for the last 20 years." }, { "code": null, "e": 2456, "s": 1994, "text": "\"\"\"Filename - GetStockData.py is a function to download the stock from 1st Jan 2000 until current date\"\"\"import datetime as dtimport pandas as pdimport pandas_datareader.data as webimport numpy as npdef stockdata(ticker): start= dt.datetime(2000,1,1) ## Start Date Range end=dt.datetime.now() ## Curret date as end date Range Stock=web.DataReader(ticker, \"yahoo\", start, end) name=str(ticker) + \".xlsx\" Stock.to_excel(name) return ()" }, { "code": null, "e": 2550, "s": 2456, "text": "Function stockdata() is called from another program with ticker symbols to download the data." }, { "code": null, "e": 2715, "s": 2550, "text": "\"\"\" Filename - stockdownload.py\"\"\"import GetStockDataticker= [\"MU\", \"ASML\",\"TSM\",\"QCOM\", \"UMC\", \"^SOX\", \"INTC\",\"^IXIC\"]for i in ticker: GetStockData.stockdata(i)" }, { "code": null, "e": 2855, "s": 2715, "text": "Please note that GetStockData python file and stockdownload.py files are placed in the same file directory to import the file successfully." }, { "code": null, "e": 3051, "s": 2855, "text": "Step 1- The first step is to think of all the variables which may influence the dependent variables. At this step, I will suggest not to constraint your thinking and brain dump all the variables." }, { "code": null, "e": 3156, "s": 3051, "text": "Step 2- Next step is to collect/download the prospective independent variables data points for analysis." }, { "code": null, "e": 3243, "s": 3156, "text": "I have formatted and collated the downloaded data into one excel file “StockData.xlsx”" }, { "code": null, "e": 3376, "s": 3243, "text": "Step 3- We will import the packages pandas, matplotlib, seaborn and statsmodels packages which we are going to use for our analysis." }, { "code": null, "e": 3523, "s": 3376, "text": "import pandas as pdimport matplotlib.pyplot as pltimport seaborn as snsfrom statsmodels.stats.outliers_influence import variance_inflation_factor" }, { "code": null, "e": 3669, "s": 3523, "text": "Step 4- Read the full data sample data excel file into the PandasDataframe called “data”. Further, we will replace the index with the date column" }, { "code": null, "e": 3743, "s": 3669, "text": "data=pd.read_excel(\"StockData.xlsx\")data.set_index(\"Date\", inplace= True)" }, { "code": null, "e": 3952, "s": 3743, "text": "I will not focus on preliminary data quality checks like blank values, outliers, etc. and respective correction approach in this article, and assuming that there are no data series related to the discrepancy." }, { "code": null, "e": 4185, "s": 3952, "text": "Step 5- One of the best places to start understanding the relationship between the independent variable is the correlation between the variables. In the below code, heatmap of the correlation is plotted using .corr method in Pandas." }, { "code": null, "e": 4247, "s": 4185, "text": "sns.heatmap(data.corr(), annot=True, cmap=\"YlGnBu\")plt.show()" }, { "code": null, "e": 4748, "s": 4247, "text": "Correlation heatmap, as shown below, provides us with a visual depiction of the relationship between the variables. Now, we do not want a set of independent variables which has a more or less similar relationship with the dependent variables. For example, TSM and Nasdaq index has a correlation coefficient of 0.99 and 0.97 with ASML respectively. Including both TSM and NASDAQ may not improve the prediction accuracy as they have a similar relationship with the dependent variable, ASML stock price." }, { "code": null, "e": 5300, "s": 4748, "text": "Step 6- Before we start dropping the redundant independent variables, let us check the Variance inflation factor (VIF) among the independent variables. VIF quantifies the severity of multicollinearity in an ordinary least squares regression analysis. It provides an index that measures how much the variance (the square of the estimate’s standard deviation) of an estimated regression coefficient is increased because of collinearity. I will encourage you all to read the Wikipedia page on Variance inflation factor to gain a good understanding of it." }, { "code": null, "e": 5528, "s": 5300, "text": "In the below code we calculate the VIF of each independent variables and print it. We will create a new DataFrame without ASML historical stock prices as we aim is to determine the VIF among the potential independent variables." }, { "code": null, "e": 5702, "s": 5528, "text": "X=data.drop([\"ASML\"], axis=1)vif = pd.DataFrame()vif[\"features\"] = X.columnsvif[\"vif_Factor\"] = [variance_inflation_factor(X.values, i) for i in range(X.shape[1])]print(vif)" }, { "code": null, "e": 5949, "s": 5702, "text": "In general, we should aim for the VIF of less than 10 for the independent variables. We have seen from the heatmap earlier that TSM and NASDAQ have similar correlation coefficient with ASML and the same is also reflecting with high VIF indicator." }, { "code": null, "e": 6133, "s": 5949, "text": "Based on our understanding from heatmap and VIF result let us drop NASDAQ (as highest VIF) as a potential candidate for the independent variable for our model and re-evaluate the VIF." }, { "code": null, "e": 6316, "s": 6133, "text": "X=data.drop([\"ASML\",\"NASDAQ\"], axis=1)vif = pd.DataFrame()vif[\"features\"] = X.columnsvif[\"vif_Factor\"] = [variance_inflation_factor(X.values, i) for i in range(X.shape[1])]print(vif)" }, { "code": null, "e": 6411, "s": 6316, "text": "We can see that on removing the NASDAQ, VIF of few other potential independent also decreased." }, { "code": null, "e": 6790, "s": 6411, "text": "Selecting the right combination of independent variables is a bit of experience along with trial and error VIF checking with different permutations. TSMC is a leading semiconductor foundry in the world and as a customer of ASML has a strong influence on ASML’s business. Considering this aspect, I will drop “INTC” and “PHLX” and re-evaluate the VIF for the remaining variables." }, { "code": null, "e": 7054, "s": 6790, "text": "As we can see that after two iterations we have VIF of all the remaining variables less than 10. We have removed the variables with multicollinearity and have identified the list of independent variables which are relevant for predicting the stock prices of ASML." }, { "code": null, "e": 7214, "s": 7054, "text": "I hope, in selecting the right sets of the independent variable for your machine learning models, you will find the approach explained in this program helpful." }, { "code": null, "e": 7324, "s": 7214, "text": "If you like this article then you may also like Machine Learning and Supply Chain Management: Hands-on Series" } ]
Aggregate Functions in Tableau - GeeksforGeeks
24 Oct, 2020 In this article, we will learn about aggregate functions, their types and uses in Tableau. Tableau: Tableau is a very powerful data visualization tool that can be used by data analysts, scientists, statisticians, etc. to visualize the data and get a clear opinion based on the data analysis. Tableau is very famous as it can take in data and produce the required data visualization output in a very short time. Aggregate Function: Aggregate function can be a function where the values ​​of multiple lines are grouped together to form a single summative value. Typical integration functions include: Measurement (e.g., arithmetic means), Count, etc. In a Tableau, you will combine steps or sizes, although it is very common to combine steps. Whenever you add a rating to your view, the aggregation is used when the rating is automated, the type of aggregation used varies by counting in viewing context. Tableau offers a variety of integrated functions, which help to make aggregations such as calculating total, average, minimum, quantity, etc. between this article, we will show you ways to use the functions of Tableau Aggregate with examples. The most commonly used functions in tableau are listed below: SUM: sum of valuesAVG: average of valuesMIN: minimum of valuesMAX: maximum of valuesVAR: variance of sample populationVARP: variance of entire populationSTDEV: standard deviation of sample populationSTDEVP: standard deviation of entire populationCOUNT: count of values SUM: sum of values AVG: average of values MIN: minimum of values MAX: maximum of values VAR: variance of sample population VARP: variance of entire population STDEV: standard deviation of sample population STDEVP: standard deviation of entire population COUNT: count of values The Tableau Sum function is employed to seek out the Sum of records during a column. Syntax: SUM(Expression) Example: To demonstrate these Tableau aggregate functions, we’ve to use the Calculated Field. Please navigate to Analysis Tab and choose the Create Calculated Field (choice to create a calculated field and use sum aggregate function). The Tableau Avg or average function is used to calculate the Average. Syntax: AVG(Expression) Example: As you’ll see from the below screenshot, we are creating a replacement field (Sales Average) using Tableau function. The Tableau MIN function is an aggregate function in Tableau, which is employed to seek out the minimum value. Syntax: MIN(Expression1, Expression2) Example: The Tableau MIN function accepts two arguments. Use this to find the smallest between two numbers. The Tableau MAX function is employed to seek out the utmost value. Syntax: MAX(Expression 1, Expression 2) Example: In Tableau, the MAX function accepts two arguments. Use this to find the largest among two numbers. The Tableau VAR function is an aggregate function in tableau, which is used to find the Variance of the sample population. Syntax: VAR(Expression) Example: The Tableau VARP function is employed to seek out the Variance of the whole population. Syntax: VARP(Expression) Example: The Tableau STDEV function is one of the aggregate functions in tableau, which is used to find the standard deviation of the sample population. Syntax: STDEV(Expression) Example: The Tableau STDEVP function is for locating the quality deviation of the whole population. Syntax: STDEVP(Expression) Example: The Tableau COUNT function is one of the Tableau aggregate function, which is used to find the number of not null values. Syntax: COUNT(Expression) Example: TIP: Use COUNTD function to urge a definite count. Tableau Tableau Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Introduction to Tableau Word Cloud in Tableau Parameters in Tableau Funnel Chart in Tableau Line graph in Tableau Replacing data source in Tableau Tableau Drivers - Download and Connect Waterfall Chart in Tableau Manual Sorting of Visualization in Tableau IF Function in Tableau
[ { "code": null, "e": 23848, "s": 23820, "text": "\n24 Oct, 2020" }, { "code": null, "e": 23940, "s": 23848, "text": "In this article, we will learn about aggregate functions, their types and uses in Tableau. " }, { "code": null, "e": 24260, "s": 23940, "text": "Tableau: Tableau is a very powerful data visualization tool that can be used by data analysts, scientists, statisticians, etc. to visualize the data and get a clear opinion based on the data analysis. Tableau is very famous as it can take in data and produce the required data visualization output in a very short time." }, { "code": null, "e": 24498, "s": 24260, "text": "Aggregate Function: Aggregate function can be a function where the values ​​of multiple lines are grouped together to form a single summative value. Typical integration functions include: Measurement (e.g., arithmetic means), Count, etc." }, { "code": null, "e": 24996, "s": 24498, "text": "In a Tableau, you will combine steps or sizes, although it is very common to combine steps. Whenever you add a rating to your view, the aggregation is used when the rating is automated, the type of aggregation used varies by counting in viewing context. Tableau offers a variety of integrated functions, which help to make aggregations such as calculating total, average, minimum, quantity, etc. between this article, we will show you ways to use the functions of Tableau Aggregate with examples. " }, { "code": null, "e": 25058, "s": 24996, "text": "The most commonly used functions in tableau are listed below:" }, { "code": null, "e": 25327, "s": 25058, "text": "SUM: sum of valuesAVG: average of valuesMIN: minimum of valuesMAX: maximum of valuesVAR: variance of sample populationVARP: variance of entire populationSTDEV: standard deviation of sample populationSTDEVP: standard deviation of entire populationCOUNT: count of values" }, { "code": null, "e": 25346, "s": 25327, "text": "SUM: sum of values" }, { "code": null, "e": 25369, "s": 25346, "text": "AVG: average of values" }, { "code": null, "e": 25392, "s": 25369, "text": "MIN: minimum of values" }, { "code": null, "e": 25415, "s": 25392, "text": "MAX: maximum of values" }, { "code": null, "e": 25450, "s": 25415, "text": "VAR: variance of sample population" }, { "code": null, "e": 25486, "s": 25450, "text": "VARP: variance of entire population" }, { "code": null, "e": 25533, "s": 25486, "text": "STDEV: standard deviation of sample population" }, { "code": null, "e": 25581, "s": 25533, "text": "STDEVP: standard deviation of entire population" }, { "code": null, "e": 25604, "s": 25581, "text": "COUNT: count of values" }, { "code": null, "e": 25690, "s": 25604, "text": "The Tableau Sum function is employed to seek out the Sum of records during a column. " }, { "code": null, "e": 25698, "s": 25690, "text": "Syntax:" }, { "code": null, "e": 25715, "s": 25698, "text": "SUM(Expression)\n" }, { "code": null, "e": 25724, "s": 25715, "text": "Example:" }, { "code": null, "e": 25950, "s": 25724, "text": "To demonstrate these Tableau aggregate functions, we’ve to use the Calculated Field. Please navigate to Analysis Tab and choose the Create Calculated Field (choice to create a calculated field and use sum aggregate function)." }, { "code": null, "e": 26021, "s": 25950, "text": "The Tableau Avg or average function is used to calculate the Average. " }, { "code": null, "e": 26029, "s": 26021, "text": "Syntax:" }, { "code": null, "e": 26046, "s": 26029, "text": "AVG(Expression)\n" }, { "code": null, "e": 26055, "s": 26046, "text": "Example:" }, { "code": null, "e": 26172, "s": 26055, "text": "As you’ll see from the below screenshot, we are creating a replacement field (Sales Average) using Tableau function." }, { "code": null, "e": 26284, "s": 26172, "text": "The Tableau MIN function is an aggregate function in Tableau, which is employed to seek out the minimum value. " }, { "code": null, "e": 26292, "s": 26284, "text": "Syntax:" }, { "code": null, "e": 26323, "s": 26292, "text": "MIN(Expression1, Expression2)\n" }, { "code": null, "e": 26332, "s": 26323, "text": "Example:" }, { "code": null, "e": 26432, "s": 26332, "text": "The Tableau MIN function accepts two arguments. Use this to find the smallest between two numbers. " }, { "code": null, "e": 26500, "s": 26432, "text": "The Tableau MAX function is employed to seek out the utmost value. " }, { "code": null, "e": 26508, "s": 26500, "text": "Syntax:" }, { "code": null, "e": 26541, "s": 26508, "text": "MAX(Expression 1, Expression 2)\n" }, { "code": null, "e": 26550, "s": 26541, "text": "Example:" }, { "code": null, "e": 26650, "s": 26550, "text": "In Tableau, the MAX function accepts two arguments. Use this to find the largest among two numbers." }, { "code": null, "e": 26774, "s": 26650, "text": "The Tableau VAR function is an aggregate function in tableau, which is used to find the Variance of the sample population. " }, { "code": null, "e": 26782, "s": 26774, "text": "Syntax:" }, { "code": null, "e": 26799, "s": 26782, "text": "VAR(Expression)\n" }, { "code": null, "e": 26808, "s": 26799, "text": "Example:" }, { "code": null, "e": 26897, "s": 26808, "text": "The Tableau VARP function is employed to seek out the Variance of the whole population. " }, { "code": null, "e": 26905, "s": 26897, "text": "Syntax:" }, { "code": null, "e": 26923, "s": 26905, "text": "VARP(Expression)\n" }, { "code": null, "e": 26932, "s": 26923, "text": "Example:" }, { "code": null, "e": 27077, "s": 26932, "text": "The Tableau STDEV function is one of the aggregate functions in tableau, which is used to find the standard deviation of the sample population. " }, { "code": null, "e": 27085, "s": 27077, "text": "Syntax:" }, { "code": null, "e": 27104, "s": 27085, "text": "STDEV(Expression)\n" }, { "code": null, "e": 27113, "s": 27104, "text": "Example:" }, { "code": null, "e": 27205, "s": 27113, "text": "The Tableau STDEVP function is for locating the quality deviation of the whole population. " }, { "code": null, "e": 27213, "s": 27205, "text": "Syntax:" }, { "code": null, "e": 27233, "s": 27213, "text": "STDEVP(Expression)\n" }, { "code": null, "e": 27242, "s": 27233, "text": "Example:" }, { "code": null, "e": 27365, "s": 27242, "text": "The Tableau COUNT function is one of the Tableau aggregate function, which is used to find the number of not null values. " }, { "code": null, "e": 27373, "s": 27365, "text": "Syntax:" }, { "code": null, "e": 27392, "s": 27373, "text": "COUNT(Expression)\n" }, { "code": null, "e": 27401, "s": 27392, "text": "Example:" }, { "code": null, "e": 27452, "s": 27401, "text": "TIP: Use COUNTD function to urge a definite count." }, { "code": null, "e": 27460, "s": 27452, "text": "Tableau" }, { "code": null, "e": 27468, "s": 27460, "text": "Tableau" }, { "code": null, "e": 27566, "s": 27468, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 27590, "s": 27566, "text": "Introduction to Tableau" }, { "code": null, "e": 27612, "s": 27590, "text": "Word Cloud in Tableau" }, { "code": null, "e": 27634, "s": 27612, "text": "Parameters in Tableau" }, { "code": null, "e": 27658, "s": 27634, "text": "Funnel Chart in Tableau" }, { "code": null, "e": 27680, "s": 27658, "text": "Line graph in Tableau" }, { "code": null, "e": 27713, "s": 27680, "text": "Replacing data source in Tableau" }, { "code": null, "e": 27752, "s": 27713, "text": "Tableau Drivers - Download and Connect" }, { "code": null, "e": 27779, "s": 27752, "text": "Waterfall Chart in Tableau" }, { "code": null, "e": 27822, "s": 27779, "text": "Manual Sorting of Visualization in Tableau" } ]
How to copy files with the specific extension in PowerShell?
To copy the files with the specific extension, you need to use the Get-ChildItem command. Through the Get-ChildItem you first need to retrieve the files with the specific extension(s) and then you need to pipeline Copy-Item command. Here, we need to copy *.txt files from the source to the destination location. First, we will retrieve all the *.txt files available in the source path. Get-ChildItem D:\Temp\ -Filter *.txt PS C:\WINDOWS\system32> Get-ChildItem D:\Temp\ -Filter *.txt Directory: D:\Temp Mode LastWriteTime Length Name ---- ------------- ------ ---- -a---- 26-01-2020 19:20 13818 aliases.txt -a---- 18-01-2020 18:25 48 delim.txt -a---- 18-01-2020 17:25 14 GetContentExample.txt -a---- 17-01-2020 22:04 55190 Processes.txt -a---- 18-01-2020 18:22 27620 ReadC.txt -ar--- 13-01-2020 18:19 0 Readonlyfile.txt -a---- 18-01-2020 18:44 22 stream1.txt -a---- 18-01-2020 16:26 27620 testreadC.txt We are going to copy the above files to the destination folder. Get-ChildItem D:\Temp\ -Filter *.txt | Copy-Item - Destination D:\TempContent\ -Force -PassThru PS C:\WINDOWS\system32> Get-ChildItem D:\Temp\ -Filter *.txt | Copy-Item -Destination D:\TempContent\ -Force -PassThru Directory: D:\TempContent Mode LastWriteTime Length Name ---- ------------- ------ ---- -a---- 26-01-2020 19:20 13818 aliases.txt -a---- 18-01-2020 18:25 48 delim.txt -a---- 18-01-2020 17:25 14 GetContentExample.txt -a---- 17-01-2020 22:04 55190 Processes.txt -a---- 18-01-2020 18:22 27620 ReadC.txt -ar--- 13-01-2020 18:19 0 Readonlyfile.txt -a---- 18-01-2020 18:44 22 stream1.txt -a---- 18-01-2020 16:26 27620 testreadC.txt
[ { "code": null, "e": 1295, "s": 1062, "text": "To copy the files with the specific extension, you need to use the Get-ChildItem command. Through the Get-ChildItem you first need to retrieve the files with the specific extension(s) and then you need to pipeline Copy-Item command." }, { "code": null, "e": 1374, "s": 1295, "text": "Here, we need to copy *.txt files from the source to the destination location." }, { "code": null, "e": 1448, "s": 1374, "text": "First, we will retrieve all the *.txt files available in the source path." }, { "code": null, "e": 1485, "s": 1448, "text": "Get-ChildItem D:\\Temp\\ -Filter *.txt" }, { "code": null, "e": 2180, "s": 1485, "text": "PS C:\\WINDOWS\\system32> Get-ChildItem D:\\Temp\\ -Filter *.txt\n Directory: D:\\Temp\nMode LastWriteTime Length Name\n---- ------------- ------ ----\n-a---- 26-01-2020 19:20 13818 aliases.txt\n-a---- 18-01-2020 18:25 48 delim.txt\n-a---- 18-01-2020 17:25 14 GetContentExample.txt\n-a---- 17-01-2020 22:04 55190 Processes.txt\n-a---- 18-01-2020 18:22 27620 ReadC.txt\n-ar--- 13-01-2020 18:19 0 Readonlyfile.txt\n-a---- 18-01-2020 18:44 22 stream1.txt\n-a---- 18-01-2020 16:26 27620 testreadC.txt" }, { "code": null, "e": 2244, "s": 2180, "text": "We are going to copy the above files to the destination folder." }, { "code": null, "e": 2340, "s": 2244, "text": "Get-ChildItem D:\\Temp\\ -Filter *.txt | Copy-Item -\nDestination D:\\TempContent\\ -Force -PassThru" }, { "code": null, "e": 3100, "s": 2340, "text": "PS C:\\WINDOWS\\system32> Get-ChildItem D:\\Temp\\ -Filter *.txt | Copy-Item -Destination D:\\TempContent\\ -Force -PassThru\n Directory: D:\\TempContent\nMode LastWriteTime Length Name\n---- ------------- ------ ----\n-a---- 26-01-2020 19:20 13818 aliases.txt\n-a---- 18-01-2020 18:25 48 delim.txt\n-a---- 18-01-2020 17:25 14 GetContentExample.txt\n-a---- 17-01-2020 22:04 55190 Processes.txt\n-a---- 18-01-2020 18:22 27620 ReadC.txt\n-ar--- 13-01-2020 18:19 0 Readonlyfile.txt\n-a---- 18-01-2020 18:44 22 stream1.txt\n-a---- 18-01-2020 16:26 27620 testreadC.txt" } ]
trunc() , truncf() , truncl() in C language
Here we will see three functions. These functions are trunc(), truncf() and the truncl(). These functions are used to convert floating point values into truncated form. This function is used to truncate double type value. And return only the integer part. The syntax is like below. double trunc(double argument) #include <stdio.h> #include <math.h> main() { double a, b, x, y; x = 53.26; y = 75.86; a = trunc(x); b = trunc(y); printf("The value of a: %lf\n",a); printf("The value of a: %lf\n",b); } The value of a: 53.000000 The value of a: 75.000000 This function is used to truncate floating type value. And return only the integer part. The syntax is like below. float tuncf(float argument) #include <stdio.h> #include <math.h> main() { float a, b, x, y; x = 53.26; y = 75.86; a = truncf(x); b = truncf(y); printf("The value of a: %f\n",a); printf("The value of a: %f\n",b); } The value of a: 53.000000 The value of a: 75.000000 This is like trunc() or truncf(). But the main difference is, this function is used to truncate long double type value. And return only the integer part. The syntax is like below. long double truncl(long double argument) #include <stdio.h> #include <math.h> main() { long double a, b, x, y; x = 53547.55555555555; y = 78547.55555555523; a = truncl(x); b = truncl(y); printf("The value of a: %Lf\n",a); printf("The value of a: %Lf\n",b); } The value of a: 53547.000000 The value of a: 78547.000000
[ { "code": null, "e": 1231, "s": 1062, "text": "Here we will see three functions. These functions are trunc(), truncf() and the truncl(). These functions are used to convert floating point values into truncated form." }, { "code": null, "e": 1344, "s": 1231, "text": "This function is used to truncate double type value. And return only the integer part. The syntax is like below." }, { "code": null, "e": 1374, "s": 1344, "text": "double trunc(double argument)" }, { "code": null, "e": 1582, "s": 1374, "text": "#include <stdio.h>\n#include <math.h>\nmain() {\n double a, b, x, y;\n x = 53.26;\n y = 75.86;\n a = trunc(x);\n b = trunc(y);\n printf(\"The value of a: %lf\\n\",a);\n printf(\"The value of a: %lf\\n\",b);\n}" }, { "code": null, "e": 1634, "s": 1582, "text": "The value of a: 53.000000\nThe value of a: 75.000000" }, { "code": null, "e": 1749, "s": 1634, "text": "This function is used to truncate floating type value. And return only the integer part. The syntax is like below." }, { "code": null, "e": 1777, "s": 1749, "text": "float tuncf(float argument)" }, { "code": null, "e": 1984, "s": 1777, "text": "#include <stdio.h>\n#include <math.h>\nmain() {\n float a, b, x, y;\n x = 53.26;\n y = 75.86;\n a = truncf(x);\n b = truncf(y);\n printf(\"The value of a: %f\\n\",a);\n printf(\"The value of a: %f\\n\",b);\n}" }, { "code": null, "e": 2036, "s": 1984, "text": "The value of a: 53.000000\nThe value of a: 75.000000" }, { "code": null, "e": 2190, "s": 2036, "text": "This is like trunc() or truncf(). But the main difference is, this function is used to truncate long double type value. And return only the integer part." }, { "code": null, "e": 2216, "s": 2190, "text": "The syntax is like below." }, { "code": null, "e": 2257, "s": 2216, "text": "long double truncl(long double argument)" }, { "code": null, "e": 2496, "s": 2257, "text": "#include <stdio.h>\n#include <math.h>\nmain() {\n long double a, b, x, y;\n x = 53547.55555555555;\n y = 78547.55555555523;\n a = truncl(x);\n b = truncl(y);\n printf(\"The value of a: %Lf\\n\",a);\n printf(\"The value of a: %Lf\\n\",b);\n}" }, { "code": null, "e": 2554, "s": 2496, "text": "The value of a: 53547.000000\nThe value of a: 78547.000000" } ]
Nested Classes in C#
Nested class is a class declared in another enclosing class. It is a member of its enclosing class and the members of an enclosing class have no access to members of a nested class. Let us see an example code snippet of nested classes in C# − class One { public int val1; public class Two { public int val1; } } class Demo { static void Main() { One a = new One(); a.val1++; One.Two ab = new One.Two(); ab.val2++; } } The example shows that class Two is a nested class. The class Two is enclosed inside the class One declaration. The class Two here is enclosed inside the declaration of class One. Class Two is thus a nested class. Because it has a public accessibility modifier, it can be accessed in places other than class One's scope.
[ { "code": null, "e": 1244, "s": 1062, "text": "Nested class is a class declared in another enclosing class. It is a member of its enclosing class and the members of an enclosing class have no access to members of a nested class." }, { "code": null, "e": 1305, "s": 1244, "text": "Let us see an example code snippet of nested classes in C# −" }, { "code": null, "e": 1528, "s": 1305, "text": "class One {\n public int val1;\n\n public class Two {\n public int val1;\n }\n}\n\nclass Demo {\n static void Main() {\n One a = new One();\n a.val1++;\n\n One.Two ab = new One.Two();\n ab.val2++;\n }\n}" }, { "code": null, "e": 1640, "s": 1528, "text": "The example shows that class Two is a nested class. The class Two is enclosed inside the class One declaration." }, { "code": null, "e": 1849, "s": 1640, "text": "The class Two here is enclosed inside the declaration of class One. Class Two is thus a nested class. Because it has a public accessibility modifier, it can be accessed in places other than class One's scope." } ]
Chi-Square Distribution in R - GeeksforGeeks
18 Jul, 2021 The chi-squared distribution with df degrees of freedom is the distribution computed over the sums of the squares of df independent standard normal random variables. This distribution is used for the categorical analysis of the data. Let us consider X1, X2,..., Xm to be the m independent random variables with a standard normal distribution, then the quantity following the Chi-Squared distribution with m degrees of freedom can be evaluated as below. The mean of this distribution is m, and its variance is equivalent to 2*m, respectively. Formula: qchisq gives the quantile function. When we supply the value of ncp = 0, the algorithm for the non-central distribution is used. The value of this method is equivalent to the value of x at the qth percentile (lower.tail = TRUE). Syntax: qchisq(p, df, ncp = 0, lower.tail = TRUE, log.p = FALSE) Parameter : p – vector of probabilities df – degrees of freedom ncp – non-centrality parameter (non-negative). log.p – logical; if TRUE, probabilities p are given as log(p). lower.tail – logical; if TRUE (default), probabilities are P[X ≤ x], otherwise, P[X > x]. Example: R # defining the degrees of freedom free = 5qchisq(.75, df=free) Output [1] 6.62568 This function can also be used to calculate quantile for a given area under the curve. Example: R # defining the degrees of freedom free = 5qchisq(.999, df=free, lower.tail = TRUE) Output [1] 20.51501 dchisq gives the density function. That is, it is used for computing the cumulative probability (lower.tail = TRUE for left tail, lower.tail = FALSE for right tail) of less than or equal to the value of vector of quantiles, that is q. Syntax: dchisq(x, df, ncp = 0, log = FALSE) Parameter : x – vector of quantiles df – degrees of freedom ncp – non-centrality parameter (non-negative). log.p – logical; if TRUE, probabilities p are given as log(p). Example: R # defining degrees of freedomdf = 6vec <- 1:4 print ("Density function values") dchisq(vec, df = df) Output [1] “Density function values” [1] 0.03790817 0.09196986 0.12551072 0.13533528 pchisq gives the distribution function. dchisq(x, df) gives us the probability of χ2 with equivalent to a value of x when the degree of freedom is df. This method can be used to calculate the area under the curve for the specified intervals of the χ2-curve with a given number of degree of freedoms. Syntax: pchisq(q, df, ncp = 0, lower.tail = TRUE, log.p = FALSE) Parameter : q – vector of quantiles df – degrees of freedom ncp – non-centrality parameter (non-negative). log.p – logical; if TRUE, probabilities p are given as log(p). lower.tail – logical; if TRUE (default), probabilities are P[X ≤ x], otherwise, P[X > x]. Example: R # defining degrees of freedomdf = 5 # calculating for the values in the interval [0,5]print ("Calculating for the values [0,5]")pchisq(5, df = df,lower.tail = TRUE) # calculating for the values in the interval [5,inf)print ("Calculating for the values [5,inf)")pchisq(5, df = df,lower.tail = FALSE) Output [1] “Calculating for the values [0,5]” [1] 0.5841198 [1] “Calculating for the values [5,inf)” [1] 0.4158802 The summation of the curves under both the intervals [0,5] and [5,∞) is equivalent to 1. rchisq(n, df) returns n random numbers from the chi-square distribution. It is therefore to generate random deviates. Syntax: rchisq(n, df, ncp = 0) Parameter : n – number of observations. If length(n) > 1, the length is taken to be the number required. df – degrees of freedom (non-negative, but can be non-integer). ncp – non-centrality parameter (non-negative). Example: R # computing values of 50k random values with 5 degrees of freedomx <- rchisq(50000, df = 5) hist(x, freq = FALSE, xlim = c(0,16), ylim = c(0,0.2)) curve(dchisq(x, df = 5), from = 0, to = 15, n = 5000, col= 'red', lwd=2, add = T) Output Picked R-Statistics R Language Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Change Color of Bars in Barchart using ggplot2 in R Group by function in R using Dplyr How to Change Axis Scales in R Plots? How to Split Column Into Multiple Columns in R DataFrame? Replace Specific Characters in String in R How to filter R DataFrame by values in a column? R - if statement How to filter R dataframe by multiple conditions? Plot mean and standard deviation using ggplot2 in R How to import an Excel File into R ?
[ { "code": null, "e": 26487, "s": 26459, "text": "\n18 Jul, 2021" }, { "code": null, "e": 26721, "s": 26487, "text": "The chi-squared distribution with df degrees of freedom is the distribution computed over the sums of the squares of df independent standard normal random variables. This distribution is used for the categorical analysis of the data." }, { "code": null, "e": 27029, "s": 26721, "text": "Let us consider X1, X2,..., Xm to be the m independent random variables with a standard normal distribution, then the quantity following the Chi-Squared distribution with m degrees of freedom can be evaluated as below. The mean of this distribution is m, and its variance is equivalent to 2*m, respectively." }, { "code": null, "e": 27038, "s": 27029, "text": "Formula:" }, { "code": null, "e": 27267, "s": 27038, "text": "qchisq gives the quantile function. When we supply the value of ncp = 0, the algorithm for the non-central distribution is used. The value of this method is equivalent to the value of x at the qth percentile (lower.tail = TRUE)." }, { "code": null, "e": 27275, "s": 27267, "text": "Syntax:" }, { "code": null, "e": 27332, "s": 27275, "text": "qchisq(p, df, ncp = 0, lower.tail = TRUE, log.p = FALSE)" }, { "code": null, "e": 27345, "s": 27332, "text": "Parameter : " }, { "code": null, "e": 27373, "s": 27345, "text": "p – vector of probabilities" }, { "code": null, "e": 27398, "s": 27373, "text": "df – degrees of freedom " }, { "code": null, "e": 27445, "s": 27398, "text": "ncp – non-centrality parameter (non-negative)." }, { "code": null, "e": 27508, "s": 27445, "text": "log.p – logical; if TRUE, probabilities p are given as log(p)." }, { "code": null, "e": 27598, "s": 27508, "text": "lower.tail – logical; if TRUE (default), probabilities are P[X ≤ x], otherwise, P[X > x]." }, { "code": null, "e": 27608, "s": 27598, "text": "Example: " }, { "code": null, "e": 27610, "s": 27608, "text": "R" }, { "code": "# defining the degrees of freedom free = 5qchisq(.75, df=free) ", "e": 27674, "s": 27610, "text": null }, { "code": null, "e": 27681, "s": 27674, "text": "Output" }, { "code": null, "e": 27693, "s": 27681, "text": "[1] 6.62568" }, { "code": null, "e": 27780, "s": 27693, "text": "This function can also be used to calculate quantile for a given area under the curve." }, { "code": null, "e": 27789, "s": 27780, "text": "Example:" }, { "code": null, "e": 27791, "s": 27789, "text": "R" }, { "code": "# defining the degrees of freedom free = 5qchisq(.999, df=free, lower.tail = TRUE)", "e": 27874, "s": 27791, "text": null }, { "code": null, "e": 27881, "s": 27874, "text": "Output" }, { "code": null, "e": 27894, "s": 27881, "text": "[1] 20.51501" }, { "code": null, "e": 28130, "s": 27894, "text": "dchisq gives the density function. That is, it is used for computing the cumulative probability (lower.tail = TRUE for left tail, lower.tail = FALSE for right tail) of less than or equal to the value of vector of quantiles, that is q. " }, { "code": null, "e": 28138, "s": 28130, "text": "Syntax:" }, { "code": null, "e": 28174, "s": 28138, "text": "dchisq(x, df, ncp = 0, log = FALSE)" }, { "code": null, "e": 28186, "s": 28174, "text": "Parameter :" }, { "code": null, "e": 28210, "s": 28186, "text": "x – vector of quantiles" }, { "code": null, "e": 28234, "s": 28210, "text": "df – degrees of freedom" }, { "code": null, "e": 28281, "s": 28234, "text": "ncp – non-centrality parameter (non-negative)." }, { "code": null, "e": 28344, "s": 28281, "text": "log.p – logical; if TRUE, probabilities p are given as log(p)." }, { "code": null, "e": 28353, "s": 28344, "text": "Example:" }, { "code": null, "e": 28355, "s": 28353, "text": "R" }, { "code": "# defining degrees of freedomdf = 6vec <- 1:4 print (\"Density function values\") dchisq(vec, df = df)", "e": 28458, "s": 28355, "text": null }, { "code": null, "e": 28465, "s": 28458, "text": "Output" }, { "code": null, "e": 28496, "s": 28465, "text": "[1] “Density function values” " }, { "code": null, "e": 28544, "s": 28496, "text": "[1] 0.03790817 0.09196986 0.12551072 0.13533528" }, { "code": null, "e": 28845, "s": 28544, "text": "pchisq gives the distribution function. dchisq(x, df) gives us the probability of χ2 with equivalent to a value of x when the degree of freedom is df. This method can be used to calculate the area under the curve for the specified intervals of the χ2-curve with a given number of degree of freedoms." }, { "code": null, "e": 28854, "s": 28845, "text": "Syntax: " }, { "code": null, "e": 28911, "s": 28854, "text": "pchisq(q, df, ncp = 0, lower.tail = TRUE, log.p = FALSE)" }, { "code": null, "e": 28923, "s": 28911, "text": "Parameter :" }, { "code": null, "e": 28947, "s": 28923, "text": "q – vector of quantiles" }, { "code": null, "e": 28971, "s": 28947, "text": "df – degrees of freedom" }, { "code": null, "e": 29018, "s": 28971, "text": "ncp – non-centrality parameter (non-negative)." }, { "code": null, "e": 29081, "s": 29018, "text": "log.p – logical; if TRUE, probabilities p are given as log(p)." }, { "code": null, "e": 29171, "s": 29081, "text": "lower.tail – logical; if TRUE (default), probabilities are P[X ≤ x], otherwise, P[X > x]." }, { "code": null, "e": 29180, "s": 29171, "text": "Example:" }, { "code": null, "e": 29182, "s": 29180, "text": "R" }, { "code": "# defining degrees of freedomdf = 5 # calculating for the values in the interval [0,5]print (\"Calculating for the values [0,5]\")pchisq(5, df = df,lower.tail = TRUE) # calculating for the values in the interval [5,inf)print (\"Calculating for the values [5,inf)\")pchisq(5, df = df,lower.tail = FALSE)", "e": 29483, "s": 29182, "text": null }, { "code": null, "e": 29490, "s": 29483, "text": "Output" }, { "code": null, "e": 29530, "s": 29490, "text": "[1] “Calculating for the values [0,5]” " }, { "code": null, "e": 29545, "s": 29530, "text": "[1] 0.5841198 " }, { "code": null, "e": 29587, "s": 29545, "text": "[1] “Calculating for the values [5,inf)” " }, { "code": null, "e": 29601, "s": 29587, "text": "[1] 0.4158802" }, { "code": null, "e": 29690, "s": 29601, "text": "The summation of the curves under both the intervals [0,5] and [5,∞) is equivalent to 1." }, { "code": null, "e": 29809, "s": 29690, "text": "rchisq(n, df) returns n random numbers from the chi-square distribution. It is therefore to generate random deviates. " }, { "code": null, "e": 29817, "s": 29809, "text": "Syntax:" }, { "code": null, "e": 29840, "s": 29817, "text": "rchisq(n, df, ncp = 0)" }, { "code": null, "e": 29853, "s": 29840, "text": "Parameter : " }, { "code": null, "e": 29946, "s": 29853, "text": "n – number of observations. If length(n) > 1, the length is taken to be the number required." }, { "code": null, "e": 30010, "s": 29946, "text": "df – degrees of freedom (non-negative, but can be non-integer)." }, { "code": null, "e": 30057, "s": 30010, "text": "ncp – non-centrality parameter (non-negative)." }, { "code": null, "e": 30066, "s": 30057, "text": "Example:" }, { "code": null, "e": 30068, "s": 30066, "text": "R" }, { "code": "# computing values of 50k random values with 5 degrees of freedomx <- rchisq(50000, df = 5) hist(x, freq = FALSE, xlim = c(0,16), ylim = c(0,0.2)) curve(dchisq(x, df = 5), from = 0, to = 15, n = 5000, col= 'red', lwd=2, add = T)", "e": 30320, "s": 30068, "text": null }, { "code": null, "e": 30327, "s": 30320, "text": "Output" }, { "code": null, "e": 30334, "s": 30327, "text": "Picked" }, { "code": null, "e": 30347, "s": 30334, "text": "R-Statistics" }, { "code": null, "e": 30358, "s": 30347, "text": "R Language" }, { "code": null, "e": 30456, "s": 30358, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 30508, "s": 30456, "text": "Change Color of Bars in Barchart using ggplot2 in R" }, { "code": null, "e": 30543, "s": 30508, "text": "Group by function in R using Dplyr" }, { "code": null, "e": 30581, "s": 30543, "text": "How to Change Axis Scales in R Plots?" }, { "code": null, "e": 30639, "s": 30581, "text": "How to Split Column Into Multiple Columns in R DataFrame?" }, { "code": null, "e": 30682, "s": 30639, "text": "Replace Specific Characters in String in R" }, { "code": null, "e": 30731, "s": 30682, "text": "How to filter R DataFrame by values in a column?" }, { "code": null, "e": 30748, "s": 30731, "text": "R - if statement" }, { "code": null, "e": 30798, "s": 30748, "text": "How to filter R dataframe by multiple conditions?" }, { "code": null, "e": 30850, "s": 30798, "text": "Plot mean and standard deviation using ggplot2 in R" } ]
How to Install WordPress on the Linux Apache MySQL and PHP stack ? - GeeksforGeeks
06 Jul, 2021 WordPress is one of the commonly used Content Management systems on the web. It is written in PHP web servers like Apache are enough to run it. WordPress supports MySQL and MariaDB, but MySQL is widely used. This tutorial will help you to run WordPress using the LAMP(Linux, Apache, MySQL, PHP) stack on your Linux machine (probably VPS). Prerequisites: A Linux machine (Here using Ubuntu) A sudo user account Some basic command line experience Little MySQL experience This article assumes that you are familiar with PHP, MySQL, and WordPress. Installing PHP: PHP (Hypertext Preprocessor) is a language used to write WordPress. You can install PHP using below command. libapache2-mod-php and php-mysql are libraries that help PHP, Apache and MySQL smoothly. sudo apt install php libapache2-mod-php php-mysql To verify that you have successfully installed PHP, type the below command: php -v // output should look like below content PHP 7.4.3 (cli) (built: Oct 6 2020 15:47:56) ( NTS ) Copyright (c) The PHP Group Zend Engine v3.4.0, Copyright (c) Zend Technologies with Zend OPcache v7.4.3, Copyright (c), by Zend Technologies Install additional PHP modules like Curl, XML, XMLRPC to help ease the run of WordPress sudo apt install php-curl php-gd php-mbstring php-xml php-xmlrpc php-soap php-intl php-zip Installing and Configuring Apache: Apache is one of the most widely used web servers. Apache2 is the latest version of the webserver. You can install Apache using the below command: sudo apt install apache2 To verify that you have successfully installed Apache, type the below command apache2 -v // output Server version: Apache/2.4.41 (Ubuntu) We will configure Apache virtual hosts for WordPress, we will create a new conf file wordpress. sudo nano /etc/apache2/sites-available/wordpress.conf Use the below template to configure to .htaccess file, we will be installing WordPress in /var/www/wordpress, so we will use it as a directory. <VirtualHost *:80> ServerName yourdomain.name <Directory /var/www/wordpress> AllowOverride All DirectoryIndex index.php </Directory> </VirtualHost> Now enable the Apache rewrite module and check the Apache config syntax. If you have used syntax correctly, you will get syntax as correct. sudo a2enmod rewrite sudo apache2ctl configtest . // output Syntax OK If you get an error like the below one before Syntax OK, it’s perfectly alright because we are using localhost. AH00558: apache2: Could not reliably determine the server’s fully qualified domain name, using 127.0.0.1. Set the ‘ServerName’ directive globally to suppress this message Installing and Configure MySQL: MySQL is a popular open-source relational database management system. To install MySQL you can run the below commands, you can also verify whether MySQL is installed successfully or not. sudo apt install mysql-server mysql -V // output mysql Ver 8.0.25-0ubuntu0.20.04.1 for Linux on x86_64 ((Ubuntu)) Now login into MySQL and change the mysql-native-password sudo mysql -u rootALTER USER ‘root’@’localhost’ IDENTIFIED WITH mysql_native_password BY ‘secure password’;FLUSH PRIVILEGES;EXIT; Now login into MySQL using the root user with the new password and create a new database for wordpress CREATE DATABASE wordpress DEFAULT CHARACTER SET utf8 COLLATE utf8_unicode_ci; Now we will create a new MySQL user and Grant all access to WordPress database to the new wordpress user mysql> CREATE DATABASE wordpress DEFAULT CHARACTER SET utf8 COLLATE utf8_unicode_ci; mysql> CREATE USER ‘wordpressuser’@’%’ IDENTIFIED WITH mysql_native_password BY ‘secure password’; mysql> GRANT ALL ON wordpress.* TO ‘wordpressuser’@’%’; mysql> FLUSH PRIVILEGES; mysql> EXIT; Downloading WordPress: If you are on Ubuntu, you can directly install using APT and you can skip this step sudo apt install wordpress But we will directly install WordPress from the WordPress repository First, we will download the WordPress latest version from its repository (we are downloading it into a temporary folder so that the downloaded package and another file that helps in building WordPress but not helpful while it’s running will be deleted automatically on a reboot). Now we will unzip the WordPress package cd /tmp curl -O https://wordpress.org/latest.tar.gz tar xzvf latest.tar.gz Now we will create the Apache .htaccess file and WordPress config file from the sample config. We will also create a directory named “upgrade”, which makes sure that WordPress won’t run into permissions issues when trying to do an update to its software. touch /tmp/wordpress/.htaccess cp /tmp/wordpress/wp-config-sample.php /tmp/wordpress/wp-config.php mkdir /tmp/wordpress/wp-content/upgrade Now we will copy the unpacked wordpress directory to /var/www for apache to run sudo cp -a /tmp/wordpress/. /var/www/wordpress Configuring WordPress: Now we will adjust the wordpress files and directory permission. “www-data” user and group is the user that the Apache webserver runs as, and Apache will need to be able to read and write WordPress files in order to serve the website and perform automatic updates. We need to give wordpress directories 750 permission which means the current user(www-data) can read, write, and execute, the group cannot write, and others cannot read, write, or execute. We need to give wordpress files 640 permission which means the current user(www-data) can read, write, and the group can only read and others cannot read, write, or execute. sudo chown -R www-data:www-data /var/www/wordpress sudo find /var/www/wordpress/ -type d -exec chmod 750 {} \; sudo find /var/www/wordpress/ -type f -exec chmod 640 {} \; Now we will create some secure keys for our installation, you can make a request to WordPress API, and it will provide you with the keys, Don’t copy these keys make sure you have your own keys curl -s https://api.wordpress.org/secret-key/1.1/salt/ // the output will be similar to the one belowdefine(‘AUTH_KEY’, ‘:BiuKIi%W7<p?4Jm}`1XTJOw!cQBKxcOt]DylUDyO$BB<>t)*FN.qf*q|+-W7}8f’);define(‘SECURE_AUTH_KEY’, ‘7[Kh-{P#A~<PGMkIOHC#9Fta$XGemco5F8k}G66I[lXqD|`IZ8cyM2O>!NjtvW(o’);define(‘LOGGED_IN_KEY’, ‘La{SEJ{$uI<6Txgv QqY4cxG]3+-r[Iqcx.IFxlfN.f/Yd?317zR*+Yt=*PMWM$(‘);define(‘NONCE_KEY’, ‘U5pGQf.`J{.Hd~P/9Snw`V2+#<t+;>OTY!VOW[-aoruh;dhSUX]09xj*O<KXdZ6+’);define(‘AUTH_SALT’, ‘fmByAIfcEq&V}Xf,mF)!a09:-Q$R^/:79!k|<pEL@>VU)|C7|(>;`{N(4ZHg O)n’);define(‘SECURE_AUTH_SALT’, ‘s5N%EIR(eM@tlg;M%L-+F#:<|r_x5-]Ix.&eYN)ya5ktoWLE+H~zUGkX#HceO/;H’);define(‘LOGGED_IN_SALT’, ‘EGcaE`=DAh7lv*klFyV0VLy5<@af_*–3otD$3:^;z~C(f^JB[C0T;`yqE)2@y${‘);define(‘NONCE_SALT’, ‘rP1%&ojrP0XLRuQ1AS#@u}#2-Q+)5ftKeJpWC$oxD]?&3}|+n2Gt{1$`kZbSW`-q’); Now open the WordPress config file and add these keys along with details of the database, we have setup for wordpress. Below is a sample config file- sudo nano /var/www/wordpress/wp-config.php PHP <?php /* MySQL settings - You can get this info from your web host *//** The name of database for WordPress */define( 'DB_NAME', 'wordpress' ); /** MySQL database username */define( 'DB_USER', 'wordpressuser' ); /** MySQL database password */define( 'DB_PASSWORD', 'wordpress' ); /** MySQL hostname */define( 'DB_HOST', 'localhost' ); /** Database Charset to use in creating database tables. */define( 'DB_CHARSET', 'utf8' ); /** The Database Collate type. Don't change this if in doubt. */define( 'DB_COLLATE', '' ); /**#@+ * Authentication Unique Keys and Salts. * * Change these to different unique phrases! * You can generate these using the { * @link https://api.wordpress.org/secret-key/1.1/salt/ * WordPress.org secret-key service} * You can change these at any point in time to * invalidate all existing cookies. This will force * all users to have to log in again. * * @since 2.6.0 */define('AUTH_KEY', ':BiuKIi%W7<p?4Jm}`1XTJOw!cQBKxcOt]DylUDyO$BB<>t)*FN.qf*q|+-W7}8f');define('SECURE_AUTH_KEY', '7[Kh-{P#A~<PGMkIOHC#9Fta$XGemco5F8k}G66I[lXqD|`IZ8cyM2O>!NjtvW(o');define('LOGGED_IN_KEY', 'La{SEJ{$uI<6Txgv QqY4cxG]3+-r[Iqcx.IFxlfN.f/Yd?317zR*+Yt=*PMWM$(');define('NONCE_KEY', 'U5pGQf.`J{.Hd~P/9Snw`V2+#<t+;>OTY!VOW[-aoruh;dhSUX]09xj*O<KXdZ6+');define('AUTH_SALT', 'fmByAIfcEq&V}Xf,mF)!a09:-Q$R^/:79!k|<pEL@>VU)|C7|(>;`{N(4ZHg O)n');define('SECURE_AUTH_SALT', 's5N%EIR(eM@tlg;M%L-+F#:<|r_x5-]Ix.&eYN)ya5ktoWLE+H~zUGkX#HceO/;H');define('LOGGED_IN_SALT', 'EGcaE`=DAh7lv*klFyV0VLy5<@af_*--3otD$3:^;z~C(f^JB[C0T;`yqE)2@y${');define('NONCE_SALT', 'rP1%&ojrP0XLRuQ1AS#@u}#2-Q+)5ftKeJpWC$oxD]?&3}|+n2Gt{1$`kZbSW`-q'); /**#@-*/ /** * WordPress Database Table prefix. * * You can have multiple installations in * one database if you give each * a unique prefix. Only numbers, letters, * and underscores please! */$table_prefix = 'blog_'; /** * For developers: WordPress debugging mode. * * Change this to true to enable the display * of notices during development. * It is strongly recommended that plugin * and theme developers use WP_DEBUG * in their development environments. * * For information on other constants that * can be used for debugging, * visit the documentation. * * @link https://wordpress.org/support/article/debugging-in-wordpress/ */define( 'WP_DEBUG', false ); /* That's all, stop editing! Happy publishing. */ /** Absolute path to the WordPress directory. */if ( ! defined( 'ABSPATH' ) ) { define( 'ABSPATH', __DIR__ . '/' );} /** Sets up WordPress vars and included files. */require_once ABSPATH . 'wp-settings.php';?> Change database name, database user, and password to the values that we have created while configuring MySQL. Change the salt keys from the keys that you have received when requested wordpress Changing table prefix from “wp_” to “blog_” which is optional Setting up WordPress: Now start the apache2 server and visit the WordPress installation sudo service apache2 start // visit 127.0.0.1/wordpress Now select the user language Select language Now configure WordPress user details(This will be the default admin user) User and site details Give your WordPress a Site Name Now choose a username for the user Now give a password Give a valid email (The email in the image) should not be used in Production). Search engine visibility means gives site admin to allow search engines to index the site. After you click “Install WordPress”, WordPress will be installed, and you will get a success screen. WordPress installed successfully Now, login into the WordPress dashboard using your login details Login into WordPress After login, you can see the WordPress dashboard WordPress Dashboard Now you can see your WordPress site by visiting its URL http://127.0.0.1/wordpress WordPress successfully running Apache PHP-MySQL PHP-Questions Picked PHP Web Technologies PHP Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments How to fetch data from localserver database and display on HTML table using PHP ? How to create admin login page using PHP? How to generate PDF file using PHP ? Different ways for passing data to view in Laravel Create a drop-down list that options fetched from a MySQL database in PHP Roadmap to Become a Web Developer 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": 24892, "s": 24864, "text": "\n06 Jul, 2021" }, { "code": null, "e": 25232, "s": 24892, "text": "WordPress is one of the commonly used Content Management systems on the web. It is written in PHP web servers like Apache are enough to run it. WordPress supports MySQL and MariaDB, but MySQL is widely used. This tutorial will help you to run WordPress using the LAMP(Linux, Apache, MySQL, PHP) stack on your Linux machine (probably VPS). " }, { "code": null, "e": 25247, "s": 25232, "text": "Prerequisites:" }, { "code": null, "e": 25283, "s": 25247, "text": "A Linux machine (Here using Ubuntu)" }, { "code": null, "e": 25303, "s": 25283, "text": "A sudo user account" }, { "code": null, "e": 25338, "s": 25303, "text": "Some basic command line experience" }, { "code": null, "e": 25362, "s": 25338, "text": "Little MySQL experience" }, { "code": null, "e": 25437, "s": 25362, "text": "This article assumes that you are familiar with PHP, MySQL, and WordPress." }, { "code": null, "e": 25651, "s": 25437, "text": "Installing PHP: PHP (Hypertext Preprocessor) is a language used to write WordPress. You can install PHP using below command. libapache2-mod-php and php-mysql are libraries that help PHP, Apache and MySQL smoothly." }, { "code": null, "e": 25701, "s": 25651, "text": "sudo apt install php libapache2-mod-php php-mysql" }, { "code": null, "e": 25779, "s": 25703, "text": "To verify that you have successfully installed PHP, type the below command:" }, { "code": null, "e": 26028, "s": 25779, "text": "php -v\n\n// output should look like below content\nPHP 7.4.3 (cli) (built: Oct 6 2020 15:47:56) ( NTS )\nCopyright (c) The PHP Group\nZend Engine v3.4.0, Copyright (c) Zend Technologies\n with Zend OPcache v7.4.3, Copyright (c), by Zend Technologies" }, { "code": null, "e": 26116, "s": 26028, "text": "Install additional PHP modules like Curl, XML, XMLRPC to help ease the run of WordPress" }, { "code": null, "e": 26207, "s": 26116, "text": "sudo apt install php-curl php-gd php-mbstring php-xml php-xmlrpc php-soap php-intl php-zip" }, { "code": null, "e": 26390, "s": 26207, "text": "Installing and Configuring Apache: Apache is one of the most widely used web servers. Apache2 is the latest version of the webserver. You can install Apache using the below command:" }, { "code": null, "e": 26415, "s": 26390, "text": "sudo apt install apache2" }, { "code": null, "e": 26493, "s": 26415, "text": "To verify that you have successfully installed Apache, type the below command" }, { "code": null, "e": 26554, "s": 26493, "text": "apache2 -v\n\n// output\nServer version: Apache/2.4.41 (Ubuntu)" }, { "code": null, "e": 26650, "s": 26554, "text": "We will configure Apache virtual hosts for WordPress, we will create a new conf file wordpress." }, { "code": null, "e": 26704, "s": 26650, "text": "sudo nano /etc/apache2/sites-available/wordpress.conf" }, { "code": null, "e": 26848, "s": 26704, "text": "Use the below template to configure to .htaccess file, we will be installing WordPress in /var/www/wordpress, so we will use it as a directory." }, { "code": null, "e": 27023, "s": 26848, "text": "<VirtualHost *:80>\n ServerName yourdomain.name\n <Directory /var/www/wordpress>\n AllowOverride All\n DirectoryIndex index.php\n </Directory>\n</VirtualHost>" }, { "code": null, "e": 27165, "s": 27025, "text": "Now enable the Apache rewrite module and check the Apache config syntax. If you have used syntax correctly, you will get syntax as correct." }, { "code": null, "e": 27235, "s": 27165, "text": "sudo a2enmod rewrite\nsudo apache2ctl configtest\n.\n// output\nSyntax OK" }, { "code": null, "e": 27347, "s": 27235, "text": "If you get an error like the below one before Syntax OK, it’s perfectly alright because we are using localhost." }, { "code": null, "e": 27518, "s": 27347, "text": "AH00558: apache2: Could not reliably determine the server’s fully qualified domain name, using 127.0.0.1. Set the ‘ServerName’ directive globally to suppress this message" }, { "code": null, "e": 27737, "s": 27518, "text": "Installing and Configure MySQL: MySQL is a popular open-source relational database management system. To install MySQL you can run the below commands, you can also verify whether MySQL is installed successfully or not." }, { "code": null, "e": 27853, "s": 27737, "text": "sudo apt install mysql-server\nmysql -V\n\n// output\nmysql Ver 8.0.25-0ubuntu0.20.04.1 for Linux on x86_64 ((Ubuntu))" }, { "code": null, "e": 27911, "s": 27853, "text": "Now login into MySQL and change the mysql-native-password" }, { "code": null, "e": 28041, "s": 27911, "text": "sudo mysql -u rootALTER USER ‘root’@’localhost’ IDENTIFIED WITH mysql_native_password BY ‘secure password’;FLUSH PRIVILEGES;EXIT;" }, { "code": null, "e": 28144, "s": 28041, "text": "Now login into MySQL using the root user with the new password and create a new database for wordpress" }, { "code": null, "e": 28222, "s": 28144, "text": "CREATE DATABASE wordpress DEFAULT CHARACTER SET utf8 COLLATE utf8_unicode_ci;" }, { "code": null, "e": 28329, "s": 28224, "text": "Now we will create a new MySQL user and Grant all access to WordPress database to the new wordpress user" }, { "code": null, "e": 28414, "s": 28329, "text": "mysql> CREATE DATABASE wordpress DEFAULT CHARACTER SET utf8 COLLATE utf8_unicode_ci;" }, { "code": null, "e": 28513, "s": 28414, "text": "mysql> CREATE USER ‘wordpressuser’@’%’ IDENTIFIED WITH mysql_native_password BY ‘secure password’;" }, { "code": null, "e": 28569, "s": 28513, "text": "mysql> GRANT ALL ON wordpress.* TO ‘wordpressuser’@’%’;" }, { "code": null, "e": 28594, "s": 28569, "text": "mysql> FLUSH PRIVILEGES;" }, { "code": null, "e": 28607, "s": 28594, "text": "mysql> EXIT;" }, { "code": null, "e": 28714, "s": 28607, "text": "Downloading WordPress: If you are on Ubuntu, you can directly install using APT and you can skip this step" }, { "code": null, "e": 28741, "s": 28714, "text": "sudo apt install wordpress" }, { "code": null, "e": 28810, "s": 28741, "text": "But we will directly install WordPress from the WordPress repository" }, { "code": null, "e": 29090, "s": 28810, "text": "First, we will download the WordPress latest version from its repository (we are downloading it into a temporary folder so that the downloaded package and another file that helps in building WordPress but not helpful while it’s running will be deleted automatically on a reboot)." }, { "code": null, "e": 29130, "s": 29090, "text": "Now we will unzip the WordPress package" }, { "code": null, "e": 29205, "s": 29130, "text": "cd /tmp\ncurl -O https://wordpress.org/latest.tar.gz\ntar xzvf latest.tar.gz" }, { "code": null, "e": 29460, "s": 29205, "text": "Now we will create the Apache .htaccess file and WordPress config file from the sample config. We will also create a directory named “upgrade”, which makes sure that WordPress won’t run into permissions issues when trying to do an update to its software." }, { "code": null, "e": 29599, "s": 29460, "text": "touch /tmp/wordpress/.htaccess\ncp /tmp/wordpress/wp-config-sample.php /tmp/wordpress/wp-config.php\nmkdir /tmp/wordpress/wp-content/upgrade" }, { "code": null, "e": 29679, "s": 29599, "text": "Now we will copy the unpacked wordpress directory to /var/www for apache to run" }, { "code": null, "e": 29726, "s": 29679, "text": "sudo cp -a /tmp/wordpress/. /var/www/wordpress" }, { "code": null, "e": 30015, "s": 29726, "text": "Configuring WordPress: Now we will adjust the wordpress files and directory permission. “www-data” user and group is the user that the Apache webserver runs as, and Apache will need to be able to read and write WordPress files in order to serve the website and perform automatic updates. " }, { "code": null, "e": 30204, "s": 30015, "text": "We need to give wordpress directories 750 permission which means the current user(www-data) can read, write, and execute, the group cannot write, and others cannot read, write, or execute." }, { "code": null, "e": 30378, "s": 30204, "text": "We need to give wordpress files 640 permission which means the current user(www-data) can read, write, and the group can only read and others cannot read, write, or execute." }, { "code": null, "e": 30549, "s": 30378, "text": "sudo chown -R www-data:www-data /var/www/wordpress\nsudo find /var/www/wordpress/ -type d -exec chmod 750 {} \\;\nsudo find /var/www/wordpress/ -type f -exec chmod 640 {} \\;" }, { "code": null, "e": 30742, "s": 30549, "text": "Now we will create some secure keys for our installation, you can make a request to WordPress API, and it will provide you with the keys, Don’t copy these keys make sure you have your own keys" }, { "code": null, "e": 30797, "s": 30742, "text": "curl -s https://api.wordpress.org/secret-key/1.1/salt/" }, { "code": null, "e": 31569, "s": 30797, "text": "// the output will be similar to the one belowdefine(‘AUTH_KEY’, ‘:BiuKIi%W7<p?4Jm}`1XTJOw!cQBKxcOt]DylUDyO$BB<>t)*FN.qf*q|+-W7}8f’);define(‘SECURE_AUTH_KEY’, ‘7[Kh-{P#A~<PGMkIOHC#9Fta$XGemco5F8k}G66I[lXqD|`IZ8cyM2O>!NjtvW(o’);define(‘LOGGED_IN_KEY’, ‘La{SEJ{$uI<6Txgv QqY4cxG]3+-r[Iqcx.IFxlfN.f/Yd?317zR*+Yt=*PMWM$(‘);define(‘NONCE_KEY’, ‘U5pGQf.`J{.Hd~P/9Snw`V2+#<t+;>OTY!VOW[-aoruh;dhSUX]09xj*O<KXdZ6+’);define(‘AUTH_SALT’, ‘fmByAIfcEq&V}Xf,mF)!a09:-Q$R^/:79!k|<pEL@>VU)|C7|(>;`{N(4ZHg O)n’);define(‘SECURE_AUTH_SALT’, ‘s5N%EIR(eM@tlg;M%L-+F#:<|r_x5-]Ix.&eYN)ya5ktoWLE+H~zUGkX#HceO/;H’);define(‘LOGGED_IN_SALT’, ‘EGcaE`=DAh7lv*klFyV0VLy5<@af_*–3otD$3:^;z~C(f^JB[C0T;`yqE)2@y${‘);define(‘NONCE_SALT’, ‘rP1%&ojrP0XLRuQ1AS#@u}#2-Q+)5ftKeJpWC$oxD]?&3}|+n2Gt{1$`kZbSW`-q’);" }, { "code": null, "e": 31719, "s": 31569, "text": "Now open the WordPress config file and add these keys along with details of the database, we have setup for wordpress. Below is a sample config file-" }, { "code": null, "e": 31762, "s": 31719, "text": "sudo nano /var/www/wordpress/wp-config.php" }, { "code": null, "e": 31766, "s": 31762, "text": "PHP" }, { "code": "<?php /* MySQL settings - You can get this info from your web host *//** The name of database for WordPress */define( 'DB_NAME', 'wordpress' ); /** MySQL database username */define( 'DB_USER', 'wordpressuser' ); /** MySQL database password */define( 'DB_PASSWORD', 'wordpress' ); /** MySQL hostname */define( 'DB_HOST', 'localhost' ); /** Database Charset to use in creating database tables. */define( 'DB_CHARSET', 'utf8' ); /** The Database Collate type. Don't change this if in doubt. */define( 'DB_COLLATE', '' ); /**#@+ * Authentication Unique Keys and Salts. * * Change these to different unique phrases! * You can generate these using the { * @link https://api.wordpress.org/secret-key/1.1/salt/ * WordPress.org secret-key service} * You can change these at any point in time to * invalidate all existing cookies. This will force * all users to have to log in again. * * @since 2.6.0 */define('AUTH_KEY', ':BiuKIi%W7<p?4Jm}`1XTJOw!cQBKxcOt]DylUDyO$BB<>t)*FN.qf*q|+-W7}8f');define('SECURE_AUTH_KEY', '7[Kh-{P#A~<PGMkIOHC#9Fta$XGemco5F8k}G66I[lXqD|`IZ8cyM2O>!NjtvW(o');define('LOGGED_IN_KEY', 'La{SEJ{$uI<6Txgv QqY4cxG]3+-r[Iqcx.IFxlfN.f/Yd?317zR*+Yt=*PMWM$(');define('NONCE_KEY', 'U5pGQf.`J{.Hd~P/9Snw`V2+#<t+;>OTY!VOW[-aoruh;dhSUX]09xj*O<KXdZ6+');define('AUTH_SALT', 'fmByAIfcEq&V}Xf,mF)!a09:-Q$R^/:79!k|<pEL@>VU)|C7|(>;`{N(4ZHg O)n');define('SECURE_AUTH_SALT', 's5N%EIR(eM@tlg;M%L-+F#:<|r_x5-]Ix.&eYN)ya5ktoWLE+H~zUGkX#HceO/;H');define('LOGGED_IN_SALT', 'EGcaE`=DAh7lv*klFyV0VLy5<@af_*--3otD$3:^;z~C(f^JB[C0T;`yqE)2@y${');define('NONCE_SALT', 'rP1%&ojrP0XLRuQ1AS#@u}#2-Q+)5ftKeJpWC$oxD]?&3}|+n2Gt{1$`kZbSW`-q'); /**#@-*/ /** * WordPress Database Table prefix. * * You can have multiple installations in * one database if you give each * a unique prefix. Only numbers, letters, * and underscores please! */$table_prefix = 'blog_'; /** * For developers: WordPress debugging mode. * * Change this to true to enable the display * of notices during development. * It is strongly recommended that plugin * and theme developers use WP_DEBUG * in their development environments. * * For information on other constants that * can be used for debugging, * visit the documentation. * * @link https://wordpress.org/support/article/debugging-in-wordpress/ */define( 'WP_DEBUG', false ); /* That's all, stop editing! Happy publishing. */ /** Absolute path to the WordPress directory. */if ( ! defined( 'ABSPATH' ) ) { define( 'ABSPATH', __DIR__ . '/' );} /** Sets up WordPress vars and included files. */require_once ABSPATH . 'wp-settings.php';?>", "e": 34377, "s": 31766, "text": null }, { "code": null, "e": 34487, "s": 34377, "text": "Change database name, database user, and password to the values that we have created while configuring MySQL." }, { "code": null, "e": 34570, "s": 34487, "text": "Change the salt keys from the keys that you have received when requested wordpress" }, { "code": null, "e": 34632, "s": 34570, "text": "Changing table prefix from “wp_” to “blog_” which is optional" }, { "code": null, "e": 34720, "s": 34632, "text": "Setting up WordPress: Now start the apache2 server and visit the WordPress installation" }, { "code": null, "e": 34777, "s": 34720, "text": "sudo service apache2 start\n\n// visit 127.0.0.1/wordpress" }, { "code": null, "e": 34806, "s": 34777, "text": "Now select the user language" }, { "code": null, "e": 34822, "s": 34806, "text": "Select language" }, { "code": null, "e": 34896, "s": 34822, "text": "Now configure WordPress user details(This will be the default admin user)" }, { "code": null, "e": 34918, "s": 34896, "text": "User and site details" }, { "code": null, "e": 34950, "s": 34918, "text": "Give your WordPress a Site Name" }, { "code": null, "e": 34985, "s": 34950, "text": "Now choose a username for the user" }, { "code": null, "e": 35005, "s": 34985, "text": "Now give a password" }, { "code": null, "e": 35084, "s": 35005, "text": "Give a valid email (The email in the image) should not be used in Production)." }, { "code": null, "e": 35175, "s": 35084, "text": "Search engine visibility means gives site admin to allow search engines to index the site." }, { "code": null, "e": 35276, "s": 35175, "text": "After you click “Install WordPress”, WordPress will be installed, and you will get a success screen." }, { "code": null, "e": 35309, "s": 35276, "text": "WordPress installed successfully" }, { "code": null, "e": 35374, "s": 35309, "text": "Now, login into the WordPress dashboard using your login details" }, { "code": null, "e": 35395, "s": 35374, "text": "Login into WordPress" }, { "code": null, "e": 35444, "s": 35395, "text": "After login, you can see the WordPress dashboard" }, { "code": null, "e": 35464, "s": 35444, "text": "WordPress Dashboard" }, { "code": null, "e": 35520, "s": 35464, "text": "Now you can see your WordPress site by visiting its URL" }, { "code": null, "e": 35547, "s": 35520, "text": "http://127.0.0.1/wordpress" }, { "code": null, "e": 35578, "s": 35547, "text": "WordPress successfully running" }, { "code": null, "e": 35585, "s": 35578, "text": "Apache" }, { "code": null, "e": 35595, "s": 35585, "text": "PHP-MySQL" }, { "code": null, "e": 35609, "s": 35595, "text": "PHP-Questions" }, { "code": null, "e": 35616, "s": 35609, "text": "Picked" }, { "code": null, "e": 35620, "s": 35616, "text": "PHP" }, { "code": null, "e": 35637, "s": 35620, "text": "Web Technologies" }, { "code": null, "e": 35641, "s": 35637, "text": "PHP" }, { "code": null, "e": 35739, "s": 35641, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 35748, "s": 35739, "text": "Comments" }, { "code": null, "e": 35761, "s": 35748, "text": "Old Comments" }, { "code": null, "e": 35843, "s": 35761, "text": "How to fetch data from localserver database and display on HTML table using PHP ?" }, { "code": null, "e": 35885, "s": 35843, "text": "How to create admin login page using PHP?" }, { "code": null, "e": 35922, "s": 35885, "text": "How to generate PDF file using PHP ?" }, { "code": null, "e": 35973, "s": 35922, "text": "Different ways for passing data to view in Laravel" }, { "code": null, "e": 36047, "s": 35973, "text": "Create a drop-down list that options fetched from a MySQL database in PHP" }, { "code": null, "e": 36089, "s": 36047, "text": "Roadmap to Become a Web Developer in 2022" }, { "code": null, "e": 36122, "s": 36089, "text": "Installation of Node.js on Linux" }, { "code": null, "e": 36184, "s": 36122, "text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills" }, { "code": null, "e": 36227, "s": 36184, "text": "How to fetch data from an API in ReactJS ?" } ]
Logistic Regression on MNIST with PyTorch | by Asad Mahmood | Towards Data Science
Logistic regression is used to describe data and to explain the relationship between one dependent binary variable and one or more nominal, ordinal, interval or ratio-level independent variables[1]. The figure below shows the difference between Logistic and Linear regression. In this post, I’ll show how to code a Logistic Regression Model in PyTorch. We’ll try and solve the classification problem of MNIST dataset. First, let’s import all the libraries we’ll need. import torchfrom torch.autograd import Variableimport torchvision.transforms as transformsimport torchvision.datasets as dsets I prefer to keep the following list of steps in front of me when creating a model. This list is present on the PyTorch website [2]. # Step 1. Load Dataset# Step 2. Make Dataset Iterable# Step 3. Create Model Class# Step 4. Instantiate Model Class# Step 5. Instantiate Loss Class# Step 6. Instantiate Optimizer Class# Step 7. Train Model So let’s go through these steps one by one. To load the dataset, we make use of torchvision.datasets, a library which has almost all the popular datasets used in Machine Learning. You can check out the complete list of datasets at [3]. train_dataset = dsets.MNIST(root='./data', train=True, transform=transforms.ToTensor(), download=False)test_dataset = dsets.MNIST(root='./data', train=False, transform=transforms.ToTensor()) We will use the DataLoader class to make our dataset iterable using the following lines of code. train_loader = torch.utils.data.DataLoader(dataset=train_dataset, batch_size=batch_size, shuffle=True)test_loader = torch.utils.data.DataLoader(dataset=test_dataset, batch_size=batch_size, shuffle=False) Now, we will create a class that defines the architecture of Logistic Regression. class LogisticRegression(torch.nn.Module): def __init__(self, input_dim, output_dim): super(LogisticRegression, self).__init__() self.linear = torch.nn.Linear(input_dim, output_dim) def forward(self, x): outputs = self.linear(x) return outputs Before instantiation, we’ll initialize some parameters like following. batch_size = 100n_iters = 3000epochs = n_iters / (len(train_dataset) / batch_size)input_dim = 784output_dim = 10lr_rate = 0.001 Now, we initialize our Logistic Regression Model. model = LogisticRegression(input_dim, output_dim) We use the cross-entropy to compute the loss. criterion = torch.nn.CrossEntropyLoss() # computes softmax and then the cross entropy The optimizer will be the learning algorithm we use. In this case, we will use the Stochastic Gradient Descent. optimizer = torch.optim.SGD(model.parameters(), lr=lr_rate) Now in the last step, we’ll train the model using the following code. iter = 0for epoch in range(int(epochs)): for i, (images, labels) in enumerate(train_loader): images = Variable(images.view(-1, 28 * 28)) labels = Variable(labels) optimizer.zero_grad() outputs = model(images) loss = criterion(outputs, labels) loss.backward() optimizer.step() iter+=1 if iter%500==0: # calculate Accuracy correct = 0 total = 0 for images, labels in test_loader: images = Variable(images.view(-1, 28*28)) outputs = model(images) _, predicted = torch.max(outputs.data, 1) total+= labels.size(0) # for gpu, bring the predicted and labels back to cpu fro python operations to work correct+= (predicted == labels).sum() accuracy = 100 * correct/total print("Iteration: {}. Loss: {}. Accuracy: {}.".format(iter, loss.item(), accuracy)) Training, this model for just 3000 iterations gives an accuracy of 82%. You can go ahead and tweak the parameters a bit, to see if the accuracy increases or not. A good exercise to get a more deep understanding of Logistic Regression models in PyTorch, would be to apply this to any classification problem you could think of. For Example, You could train a Logistic Regression Model to classify the images of your favorite Marvel superheroes (shouldn’t be very hard since half of them are gone :) ).
[ { "code": null, "e": 324, "s": 47, "text": "Logistic regression is used to describe data and to explain the relationship between one dependent binary variable and one or more nominal, ordinal, interval or ratio-level independent variables[1]. The figure below shows the difference between Logistic and Linear regression." }, { "code": null, "e": 400, "s": 324, "text": "In this post, I’ll show how to code a Logistic Regression Model in PyTorch." }, { "code": null, "e": 515, "s": 400, "text": "We’ll try and solve the classification problem of MNIST dataset. First, let’s import all the libraries we’ll need." }, { "code": null, "e": 642, "s": 515, "text": "import torchfrom torch.autograd import Variableimport torchvision.transforms as transformsimport torchvision.datasets as dsets" }, { "code": null, "e": 774, "s": 642, "text": "I prefer to keep the following list of steps in front of me when creating a model. This list is present on the PyTorch website [2]." }, { "code": null, "e": 979, "s": 774, "text": "# Step 1. Load Dataset# Step 2. Make Dataset Iterable# Step 3. Create Model Class# Step 4. Instantiate Model Class# Step 5. Instantiate Loss Class# Step 6. Instantiate Optimizer Class# Step 7. Train Model" }, { "code": null, "e": 1023, "s": 979, "text": "So let’s go through these steps one by one." }, { "code": null, "e": 1215, "s": 1023, "text": "To load the dataset, we make use of torchvision.datasets, a library which has almost all the popular datasets used in Machine Learning. You can check out the complete list of datasets at [3]." }, { "code": null, "e": 1406, "s": 1215, "text": "train_dataset = dsets.MNIST(root='./data', train=True, transform=transforms.ToTensor(), download=False)test_dataset = dsets.MNIST(root='./data', train=False, transform=transforms.ToTensor())" }, { "code": null, "e": 1503, "s": 1406, "text": "We will use the DataLoader class to make our dataset iterable using the following lines of code." }, { "code": null, "e": 1707, "s": 1503, "text": "train_loader = torch.utils.data.DataLoader(dataset=train_dataset, batch_size=batch_size, shuffle=True)test_loader = torch.utils.data.DataLoader(dataset=test_dataset, batch_size=batch_size, shuffle=False)" }, { "code": null, "e": 1789, "s": 1707, "text": "Now, we will create a class that defines the architecture of Logistic Regression." }, { "code": null, "e": 2067, "s": 1789, "text": "class LogisticRegression(torch.nn.Module): def __init__(self, input_dim, output_dim): super(LogisticRegression, self).__init__() self.linear = torch.nn.Linear(input_dim, output_dim) def forward(self, x): outputs = self.linear(x) return outputs" }, { "code": null, "e": 2138, "s": 2067, "text": "Before instantiation, we’ll initialize some parameters like following." }, { "code": null, "e": 2266, "s": 2138, "text": "batch_size = 100n_iters = 3000epochs = n_iters / (len(train_dataset) / batch_size)input_dim = 784output_dim = 10lr_rate = 0.001" }, { "code": null, "e": 2316, "s": 2266, "text": "Now, we initialize our Logistic Regression Model." }, { "code": null, "e": 2366, "s": 2316, "text": "model = LogisticRegression(input_dim, output_dim)" }, { "code": null, "e": 2412, "s": 2366, "text": "We use the cross-entropy to compute the loss." }, { "code": null, "e": 2498, "s": 2412, "text": "criterion = torch.nn.CrossEntropyLoss() # computes softmax and then the cross entropy" }, { "code": null, "e": 2610, "s": 2498, "text": "The optimizer will be the learning algorithm we use. In this case, we will use the Stochastic Gradient Descent." }, { "code": null, "e": 2670, "s": 2610, "text": "optimizer = torch.optim.SGD(model.parameters(), lr=lr_rate)" }, { "code": null, "e": 2740, "s": 2670, "text": "Now in the last step, we’ll train the model using the following code." }, { "code": null, "e": 3708, "s": 2740, "text": "iter = 0for epoch in range(int(epochs)): for i, (images, labels) in enumerate(train_loader): images = Variable(images.view(-1, 28 * 28)) labels = Variable(labels) optimizer.zero_grad() outputs = model(images) loss = criterion(outputs, labels) loss.backward() optimizer.step() iter+=1 if iter%500==0: # calculate Accuracy correct = 0 total = 0 for images, labels in test_loader: images = Variable(images.view(-1, 28*28)) outputs = model(images) _, predicted = torch.max(outputs.data, 1) total+= labels.size(0) # for gpu, bring the predicted and labels back to cpu fro python operations to work correct+= (predicted == labels).sum() accuracy = 100 * correct/total print(\"Iteration: {}. Loss: {}. Accuracy: {}.\".format(iter, loss.item(), accuracy))" }, { "code": null, "e": 3870, "s": 3708, "text": "Training, this model for just 3000 iterations gives an accuracy of 82%. You can go ahead and tweak the parameters a bit, to see if the accuracy increases or not." } ]
Bidirectional Iterators in C++ - GeeksforGeeks
25 Apr, 2019 After going through the template definition of various STL algorithms like std::reverse, std::next_permutation and std::reverse_copy you must have found their template definition consisting of objects of type Bidirectional Iterator. So what are they and why are they used ? Bidirectional iterators are one of the five main types of iterators present in C++ Standard Library, others being Input iterators, Output iterator, Forward iterator and Random – access iterators. Bidirectional iterators are iterators that can be used to access the sequence of elements in a range in both directions (towards the end and towards the beginning). They are similar to forward iterators, except that they can move in the backward direction also, unlike the forward iterators, which can move only in the forward direction. It is to be noted that containers like list, map, multimap, set and multiset support bidirectional iterators. This means that if we declare normal iterators for them, and then those will be bidirectional iterators, just like in case of vectors and deque they are random-access iterators. One important thing to be kept in mind is that random-access iterators are also valid bidirectional iterators, as shown in the iterator hierarchy above. Salient Features Usability: Since, forward iterators can be used in multi-pass algorithms, i.e., algorithm which involves processing the container several times in various passes, therefore bidirectional iterators can also be used in multi-pass algorithms..Equality / Inequality Comparison: A Bidirectional iterator can be compared for equality with another iterator. Since, iterators point to some location, so the two iterators will be equal only when they point to the same position, otherwise not.So, the following two expressions are valid if A and B are Bidirectional iterators:A == B // Checking for equality A != B // Checking for inequality Dereferencing: Because an input iterator can be dereferenced, using operator * and -> as an rvalue and an output iterator can be dereferenced as an lvalue, so forward iterators being the combination of both can be used for both the purposes, and similarly, bidirectional operators can also serve both the purposes.// C++ program to demonstrate bidirectional iterator#include<iostream>#include<list>using namespace std;int main(){ list<int>v1 = {1, 2, 3, 4, 5}; // Declaring an iterator list<int>::iterator i1; for (i1=v1.begin();i1!=v1.end();++i1) { // Assigning values to locations pointed by iterator *i1 = 1; } for (i1=v1.begin();i1!=v1.end();++i1) { // Accessing values at locations pointed by iterator cout << (*i1) << " "; } return 0;}Output:1 1 1 1 1 So, as we can see here we can both access as well as assign value to the iterator, therefore the iterator is a bidirectional iterator.Incrementable: A Bidirectional iterator can be incremented, so that it refers to the next element in sequence, using operator ++().So, the following two expressions are valid if A is a bidirectional iterator:A++ // Using post increment operator ++A // Using pre increment operator Decrementable: This is the feature which differentiates a Bidirectional iterator from a forward iterator. Just like we can use operator ++() with bidirectional iterators for incrementing them, we can also decrement them.That is why, its name is bidirectional, which shows that it can move in both directions.// C++ program to demonstrate bidirectional iterator#include<iostream>#include<list>using namespace std;int main(){ list<int>v1 = {1, 2, 3, 4, 5}; // Declaring an iterator list<int>::iterator i1; // Accessing the elements from end using decrement // operator for (i1=v1.end();i1!=v1.begin();--i1) { if (i1 != v1.end()) { cout << (*i1) << " "; } } cout << (*i1); return 0;}Output:5 4 3 2 1 Since, we are starting from the end of the list and then moving towards the beginning by decrementing the pointer, which shows that decrement operator can be used with such iterators. Here, we have run the loop till the iterator becomes equal to the begin(), that is why the first value is not printed inside the loop and we have printed it separately.Swappable: The value pointed to by these iterators can be exchanged or swapped. Usability: Since, forward iterators can be used in multi-pass algorithms, i.e., algorithm which involves processing the container several times in various passes, therefore bidirectional iterators can also be used in multi-pass algorithms.. Equality / Inequality Comparison: A Bidirectional iterator can be compared for equality with another iterator. Since, iterators point to some location, so the two iterators will be equal only when they point to the same position, otherwise not.So, the following two expressions are valid if A and B are Bidirectional iterators:A == B // Checking for equality A != B // Checking for inequality So, the following two expressions are valid if A and B are Bidirectional iterators: A == B // Checking for equality A != B // Checking for inequality Dereferencing: Because an input iterator can be dereferenced, using operator * and -> as an rvalue and an output iterator can be dereferenced as an lvalue, so forward iterators being the combination of both can be used for both the purposes, and similarly, bidirectional operators can also serve both the purposes.// C++ program to demonstrate bidirectional iterator#include<iostream>#include<list>using namespace std;int main(){ list<int>v1 = {1, 2, 3, 4, 5}; // Declaring an iterator list<int>::iterator i1; for (i1=v1.begin();i1!=v1.end();++i1) { // Assigning values to locations pointed by iterator *i1 = 1; } for (i1=v1.begin();i1!=v1.end();++i1) { // Accessing values at locations pointed by iterator cout << (*i1) << " "; } return 0;}Output:1 1 1 1 1 So, as we can see here we can both access as well as assign value to the iterator, therefore the iterator is a bidirectional iterator. // C++ program to demonstrate bidirectional iterator#include<iostream>#include<list>using namespace std;int main(){ list<int>v1 = {1, 2, 3, 4, 5}; // Declaring an iterator list<int>::iterator i1; for (i1=v1.begin();i1!=v1.end();++i1) { // Assigning values to locations pointed by iterator *i1 = 1; } for (i1=v1.begin();i1!=v1.end();++i1) { // Accessing values at locations pointed by iterator cout << (*i1) << " "; } return 0;} Output: 1 1 1 1 1 So, as we can see here we can both access as well as assign value to the iterator, therefore the iterator is a bidirectional iterator. Incrementable: A Bidirectional iterator can be incremented, so that it refers to the next element in sequence, using operator ++().So, the following two expressions are valid if A is a bidirectional iterator:A++ // Using post increment operator ++A // Using pre increment operator So, the following two expressions are valid if A is a bidirectional iterator: A++ // Using post increment operator ++A // Using pre increment operator Decrementable: This is the feature which differentiates a Bidirectional iterator from a forward iterator. Just like we can use operator ++() with bidirectional iterators for incrementing them, we can also decrement them.That is why, its name is bidirectional, which shows that it can move in both directions.// C++ program to demonstrate bidirectional iterator#include<iostream>#include<list>using namespace std;int main(){ list<int>v1 = {1, 2, 3, 4, 5}; // Declaring an iterator list<int>::iterator i1; // Accessing the elements from end using decrement // operator for (i1=v1.end();i1!=v1.begin();--i1) { if (i1 != v1.end()) { cout << (*i1) << " "; } } cout << (*i1); return 0;}Output:5 4 3 2 1 Since, we are starting from the end of the list and then moving towards the beginning by decrementing the pointer, which shows that decrement operator can be used with such iterators. Here, we have run the loop till the iterator becomes equal to the begin(), that is why the first value is not printed inside the loop and we have printed it separately. That is why, its name is bidirectional, which shows that it can move in both directions. // C++ program to demonstrate bidirectional iterator#include<iostream>#include<list>using namespace std;int main(){ list<int>v1 = {1, 2, 3, 4, 5}; // Declaring an iterator list<int>::iterator i1; // Accessing the elements from end using decrement // operator for (i1=v1.end();i1!=v1.begin();--i1) { if (i1 != v1.end()) { cout << (*i1) << " "; } } cout << (*i1); return 0;} Output: 5 4 3 2 1 Since, we are starting from the end of the list and then moving towards the beginning by decrementing the pointer, which shows that decrement operator can be used with such iterators. Here, we have run the loop till the iterator becomes equal to the begin(), that is why the first value is not printed inside the loop and we have printed it separately. Swappable: The value pointed to by these iterators can be exchanged or swapped. Practical implementation After understanding its features, it is very important to learn about its practical implementation as well. As told earlier, Bidirectional iterators can be used for all the purposes that forward iterator can be used along within those situations where iterator needs to be decremented. The following two STL algorithms can show this fact: std::reverse_copy: As the name suggests, this algorithm is used to copy a range into another range, but in reverse order. Now, as far as accessing elements and assigning elements are concerned, forward iterators are fine, but as soon as we have to decrement the iterator, then we cannot use these forward iterators for this purpose, and that’s where bidirectional iterators come for our rescue.// Definition of std::reverse_copy()template OutputIterator reverse_copy(BidirectionalIterator first, BidirectionalIterator last, OutputIterator result) { while (first != last) *result++ = *--last; return result;}Here, we can see that we have declared last as a bidirectional iterator, as we cannot decrement a forward iterator as done in case of last, so we cannot use it in this scenario, and we have to declare it as a bidirectional iterator only. // Definition of std::reverse_copy()template OutputIterator reverse_copy(BidirectionalIterator first, BidirectionalIterator last, OutputIterator result) { while (first != last) *result++ = *--last; return result;} Here, we can see that we have declared last as a bidirectional iterator, as we cannot decrement a forward iterator as done in case of last, so we cannot use it in this scenario, and we have to declare it as a bidirectional iterator only. std::random_shuffle: As we know this algorithm is used to randomly shuffle all the elements present in a container. So, let us look at its internal working (Don’t go into detail just look where bidirectional iterators can be used and where they cannot be):// Definition of std::random_shuffle()template void random_shuffle(RandomAccessIterator first, RandomAccessIterator last, RandomNumberGenerator& gen){ iterator_traits::difference_type i, n; n = (last - first); for (i=n-1; i>0; --i) { swap (first[i],first[gen(i+1)]); }}Here, we can see that we have made use of Random-access iterators, as although we can increment a bidirectional iterator, decrement it as well, but we cannot apply arithmetic operator like +, – to it and this what is required in this algorithm , where (last – first) is done, so, for this reason, we cannot use a bidirectional iterator in these scenarios. // Definition of std::random_shuffle()template void random_shuffle(RandomAccessIterator first, RandomAccessIterator last, RandomNumberGenerator& gen){ iterator_traits::difference_type i, n; n = (last - first); for (i=n-1; i>0; --i) { swap (first[i],first[gen(i+1)]); }} Here, we can see that we have made use of Random-access iterators, as although we can increment a bidirectional iterator, decrement it as well, but we cannot apply arithmetic operator like +, – to it and this what is required in this algorithm , where (last – first) is done, so, for this reason, we cannot use a bidirectional iterator in these scenarios. Note: As we know that Bidirectional iterator is higher in the hierarchy than forward iterator which is itself higher than input and output iterators, therefore, all these three types of iterators can be substituted by bidirectional iterators, without affecting the working of the algorithm. So, the two above examples very well show when, where, why and how bidirectional iterators are used practically. Limitations After studying the salient features, one must also know its deficiencies as well although there are not as many as there are in input or output iterators as it is higher in the hierarchy. Relational Operators: Although, Bidirectional iterators can be used with equality operator (==), but it can not be used with other relational operators like , =.If A and B are Bidirectional iterators, then A == B // Allowed A <= B // Not Allowed Arithmetic Operators: Similar to relational operators, they also can’t be used with arithmetic operators like +, – and so on. This means that bidirectional iterators can move in both the direction, but sequentially.If A and B are Bidirectional iterators, then A + 1 // Not allowed B - 2 // Not allowed // C++ program to demonstrate bidirectional iterator#include<iostream>#include<list>using namespace std;int main(){ list<int>v1 = {1, 2, 3, 4, 5}; // Declaring first iterator list<int>::iterator i1; // Declaring second iterator list<int>::iterator i2; // i1 points to the beginning of the list i1 = v1.begin(); // i2 points to the end of the list i2 = v1.end(); // Applying relational operator to them if ( i1 > i2) { cout << "Yes"; } // This will throw an error because relational // operators cannot be applied to bidirectional iterators // Applying arithmetic operator to them int count = i1 - i2; // This will also throw an error because arithmetic // operators cannot be applied to bidirectional iterators return 0;}Output:Error, because of use of arithmetic and relational operators with bidirectional iterators Use of offset dereference operator ([ ]): Bidirectional iterators doesnot support offset dereference operator ([ ]), which is used for random-access.If A is a Bidirectional iterator, then A[3] // Not allowed Relational Operators: Although, Bidirectional iterators can be used with equality operator (==), but it can not be used with other relational operators like , =.If A and B are Bidirectional iterators, then A == B // Allowed A <= B // Not Allowed If A and B are Bidirectional iterators, then A == B // Allowed A <= B // Not Allowed Arithmetic Operators: Similar to relational operators, they also can’t be used with arithmetic operators like +, – and so on. This means that bidirectional iterators can move in both the direction, but sequentially.If A and B are Bidirectional iterators, then A + 1 // Not allowed B - 2 // Not allowed // C++ program to demonstrate bidirectional iterator#include<iostream>#include<list>using namespace std;int main(){ list<int>v1 = {1, 2, 3, 4, 5}; // Declaring first iterator list<int>::iterator i1; // Declaring second iterator list<int>::iterator i2; // i1 points to the beginning of the list i1 = v1.begin(); // i2 points to the end of the list i2 = v1.end(); // Applying relational operator to them if ( i1 > i2) { cout << "Yes"; } // This will throw an error because relational // operators cannot be applied to bidirectional iterators // Applying arithmetic operator to them int count = i1 - i2; // This will also throw an error because arithmetic // operators cannot be applied to bidirectional iterators return 0;}Output:Error, because of use of arithmetic and relational operators with bidirectional iterators If A and B are Bidirectional iterators, then A + 1 // Not allowed B - 2 // Not allowed // C++ program to demonstrate bidirectional iterator#include<iostream>#include<list>using namespace std;int main(){ list<int>v1 = {1, 2, 3, 4, 5}; // Declaring first iterator list<int>::iterator i1; // Declaring second iterator list<int>::iterator i2; // i1 points to the beginning of the list i1 = v1.begin(); // i2 points to the end of the list i2 = v1.end(); // Applying relational operator to them if ( i1 > i2) { cout << "Yes"; } // This will throw an error because relational // operators cannot be applied to bidirectional iterators // Applying arithmetic operator to them int count = i1 - i2; // This will also throw an error because arithmetic // operators cannot be applied to bidirectional iterators return 0;} Output: Error, because of use of arithmetic and relational operators with bidirectional iterators Use of offset dereference operator ([ ]): Bidirectional iterators doesnot support offset dereference operator ([ ]), which is used for random-access.If A is a Bidirectional iterator, then A[3] // Not allowed If A is a Bidirectional iterator, then A[3] // Not allowed This article is contributed by Mrigendra Singh. 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. Akanksha_Rai cpp-iterator STL C++ Misc Misc Misc STL CPP Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Operator Overloading in C++ Iterators in C++ STL Friend class and function in C++ Polymorphism in C++ Sorting a vector in C++ Top 10 algorithms in Interview Questions vector::push_back() and vector::pop_back() in C++ STL Overview of Data Structures | Set 1 (Linear Data Structures) How to write Regular Expressions? fgets() and gets() in C language
[ { "code": null, "e": 24044, "s": 24016, "text": "\n25 Apr, 2019" }, { "code": null, "e": 24318, "s": 24044, "text": "After going through the template definition of various STL algorithms like std::reverse, std::next_permutation and std::reverse_copy you must have found their template definition consisting of objects of type Bidirectional Iterator. So what are they and why are they used ?" }, { "code": null, "e": 24514, "s": 24318, "text": "Bidirectional iterators are one of the five main types of iterators present in C++ Standard Library, others being Input iterators, Output iterator, Forward iterator and Random – access iterators." }, { "code": null, "e": 24852, "s": 24514, "text": "Bidirectional iterators are iterators that can be used to access the sequence of elements in a range in both directions (towards the end and towards the beginning). They are similar to forward iterators, except that they can move in the backward direction also, unlike the forward iterators, which can move only in the forward direction." }, { "code": null, "e": 25140, "s": 24852, "text": "It is to be noted that containers like list, map, multimap, set and multiset support bidirectional iterators. This means that if we declare normal iterators for them, and then those will be bidirectional iterators, just like in case of vectors and deque they are random-access iterators." }, { "code": null, "e": 25293, "s": 25140, "text": "One important thing to be kept in mind is that random-access iterators are also valid bidirectional iterators, as shown in the iterator hierarchy above." }, { "code": null, "e": 25310, "s": 25293, "text": "Salient Features" }, { "code": null, "e": 28393, "s": 25310, "text": "Usability: Since, forward iterators can be used in multi-pass algorithms, i.e., algorithm which involves processing the container several times in various passes, therefore bidirectional iterators can also be used in multi-pass algorithms..Equality / Inequality Comparison: A Bidirectional iterator can be compared for equality with another iterator. Since, iterators point to some location, so the two iterators will be equal only when they point to the same position, otherwise not.So, the following two expressions are valid if A and B are Bidirectional iterators:A == B // Checking for equality\nA != B // Checking for inequality\nDereferencing: Because an input iterator can be dereferenced, using operator * and -> as an rvalue and an output iterator can be dereferenced as an lvalue, so forward iterators being the combination of both can be used for both the purposes, and similarly, bidirectional operators can also serve both the purposes.// C++ program to demonstrate bidirectional iterator#include<iostream>#include<list>using namespace std;int main(){ list<int>v1 = {1, 2, 3, 4, 5}; // Declaring an iterator list<int>::iterator i1; for (i1=v1.begin();i1!=v1.end();++i1) { // Assigning values to locations pointed by iterator *i1 = 1; } for (i1=v1.begin();i1!=v1.end();++i1) { // Accessing values at locations pointed by iterator cout << (*i1) << \" \"; } return 0;}Output:1 1 1 1 1\nSo, as we can see here we can both access as well as assign value to the iterator, therefore the iterator is a bidirectional iterator.Incrementable: A Bidirectional iterator can be incremented, so that it refers to the next element in sequence, using operator ++().So, the following two expressions are valid if A is a bidirectional iterator:A++ // Using post increment operator\n++A // Using pre increment operator\nDecrementable: This is the feature which differentiates a Bidirectional iterator from a forward iterator. Just like we can use operator ++() with bidirectional iterators for incrementing them, we can also decrement them.That is why, its name is bidirectional, which shows that it can move in both directions.// C++ program to demonstrate bidirectional iterator#include<iostream>#include<list>using namespace std;int main(){ list<int>v1 = {1, 2, 3, 4, 5}; // Declaring an iterator list<int>::iterator i1; // Accessing the elements from end using decrement // operator for (i1=v1.end();i1!=v1.begin();--i1) { if (i1 != v1.end()) { cout << (*i1) << \" \"; } } cout << (*i1); return 0;}Output:5 4 3 2 1\nSince, we are starting from the end of the list and then moving towards the beginning by decrementing the pointer, which shows that decrement operator can be used with such iterators. Here, we have run the loop till the iterator becomes equal to the begin(), that is why the first value is not printed inside the loop and we have printed it separately.Swappable: The value pointed to by these iterators can be exchanged or swapped." }, { "code": null, "e": 28634, "s": 28393, "text": "Usability: Since, forward iterators can be used in multi-pass algorithms, i.e., algorithm which involves processing the container several times in various passes, therefore bidirectional iterators can also be used in multi-pass algorithms.." }, { "code": null, "e": 29030, "s": 28634, "text": "Equality / Inequality Comparison: A Bidirectional iterator can be compared for equality with another iterator. Since, iterators point to some location, so the two iterators will be equal only when they point to the same position, otherwise not.So, the following two expressions are valid if A and B are Bidirectional iterators:A == B // Checking for equality\nA != B // Checking for inequality\n" }, { "code": null, "e": 29114, "s": 29030, "text": "So, the following two expressions are valid if A and B are Bidirectional iterators:" }, { "code": null, "e": 29183, "s": 29114, "text": "A == B // Checking for equality\nA != B // Checking for inequality\n" }, { "code": null, "e": 30146, "s": 29183, "text": "Dereferencing: Because an input iterator can be dereferenced, using operator * and -> as an rvalue and an output iterator can be dereferenced as an lvalue, so forward iterators being the combination of both can be used for both the purposes, and similarly, bidirectional operators can also serve both the purposes.// C++ program to demonstrate bidirectional iterator#include<iostream>#include<list>using namespace std;int main(){ list<int>v1 = {1, 2, 3, 4, 5}; // Declaring an iterator list<int>::iterator i1; for (i1=v1.begin();i1!=v1.end();++i1) { // Assigning values to locations pointed by iterator *i1 = 1; } for (i1=v1.begin();i1!=v1.end();++i1) { // Accessing values at locations pointed by iterator cout << (*i1) << \" \"; } return 0;}Output:1 1 1 1 1\nSo, as we can see here we can both access as well as assign value to the iterator, therefore the iterator is a bidirectional iterator." }, { "code": "// C++ program to demonstrate bidirectional iterator#include<iostream>#include<list>using namespace std;int main(){ list<int>v1 = {1, 2, 3, 4, 5}; // Declaring an iterator list<int>::iterator i1; for (i1=v1.begin();i1!=v1.end();++i1) { // Assigning values to locations pointed by iterator *i1 = 1; } for (i1=v1.begin();i1!=v1.end();++i1) { // Accessing values at locations pointed by iterator cout << (*i1) << \" \"; } return 0;}", "e": 30644, "s": 30146, "text": null }, { "code": null, "e": 30652, "s": 30644, "text": "Output:" }, { "code": null, "e": 30663, "s": 30652, "text": "1 1 1 1 1\n" }, { "code": null, "e": 30798, "s": 30663, "text": "So, as we can see here we can both access as well as assign value to the iterator, therefore the iterator is a bidirectional iterator." }, { "code": null, "e": 31084, "s": 30798, "text": "Incrementable: A Bidirectional iterator can be incremented, so that it refers to the next element in sequence, using operator ++().So, the following two expressions are valid if A is a bidirectional iterator:A++ // Using post increment operator\n++A // Using pre increment operator\n" }, { "code": null, "e": 31162, "s": 31084, "text": "So, the following two expressions are valid if A is a bidirectional iterator:" }, { "code": null, "e": 31240, "s": 31162, "text": "A++ // Using post increment operator\n++A // Using pre increment operator\n" }, { "code": null, "e": 32362, "s": 31240, "text": "Decrementable: This is the feature which differentiates a Bidirectional iterator from a forward iterator. Just like we can use operator ++() with bidirectional iterators for incrementing them, we can also decrement them.That is why, its name is bidirectional, which shows that it can move in both directions.// C++ program to demonstrate bidirectional iterator#include<iostream>#include<list>using namespace std;int main(){ list<int>v1 = {1, 2, 3, 4, 5}; // Declaring an iterator list<int>::iterator i1; // Accessing the elements from end using decrement // operator for (i1=v1.end();i1!=v1.begin();--i1) { if (i1 != v1.end()) { cout << (*i1) << \" \"; } } cout << (*i1); return 0;}Output:5 4 3 2 1\nSince, we are starting from the end of the list and then moving towards the beginning by decrementing the pointer, which shows that decrement operator can be used with such iterators. Here, we have run the loop till the iterator becomes equal to the begin(), that is why the first value is not printed inside the loop and we have printed it separately." }, { "code": null, "e": 32451, "s": 32362, "text": "That is why, its name is bidirectional, which shows that it can move in both directions." }, { "code": "// C++ program to demonstrate bidirectional iterator#include<iostream>#include<list>using namespace std;int main(){ list<int>v1 = {1, 2, 3, 4, 5}; // Declaring an iterator list<int>::iterator i1; // Accessing the elements from end using decrement // operator for (i1=v1.end();i1!=v1.begin();--i1) { if (i1 != v1.end()) { cout << (*i1) << \" \"; } } cout << (*i1); return 0;}", "e": 32896, "s": 32451, "text": null }, { "code": null, "e": 32904, "s": 32896, "text": "Output:" }, { "code": null, "e": 32915, "s": 32904, "text": "5 4 3 2 1\n" }, { "code": null, "e": 33268, "s": 32915, "text": "Since, we are starting from the end of the list and then moving towards the beginning by decrementing the pointer, which shows that decrement operator can be used with such iterators. Here, we have run the loop till the iterator becomes equal to the begin(), that is why the first value is not printed inside the loop and we have printed it separately." }, { "code": null, "e": 33348, "s": 33268, "text": "Swappable: The value pointed to by these iterators can be exchanged or swapped." }, { "code": null, "e": 33373, "s": 33348, "text": "Practical implementation" }, { "code": null, "e": 33712, "s": 33373, "text": "After understanding its features, it is very important to learn about its practical implementation as well. As told earlier, Bidirectional iterators can be used for all the purposes that forward iterator can be used along within those situations where iterator needs to be decremented. The following two STL algorithms can show this fact:" }, { "code": null, "e": 34621, "s": 33712, "text": "std::reverse_copy: As the name suggests, this algorithm is used to copy a range into another range, but in reverse order. Now, as far as accessing elements and assigning elements are concerned, forward iterators are fine, but as soon as we have to decrement the iterator, then we cannot use these forward iterators for this purpose, and that’s where bidirectional iterators come for our rescue.// Definition of std::reverse_copy()template OutputIterator reverse_copy(BidirectionalIterator first, BidirectionalIterator last, OutputIterator result) { while (first != last) *result++ = *--last; return result;}Here, we can see that we have declared last as a bidirectional iterator, as we cannot decrement a forward iterator as done in case of last, so we cannot use it in this scenario, and we have to declare it as a bidirectional iterator only." }, { "code": "// Definition of std::reverse_copy()template OutputIterator reverse_copy(BidirectionalIterator first, BidirectionalIterator last, OutputIterator result) { while (first != last) *result++ = *--last; return result;}", "e": 34899, "s": 34621, "text": null }, { "code": null, "e": 35137, "s": 34899, "text": "Here, we can see that we have declared last as a bidirectional iterator, as we cannot decrement a forward iterator as done in case of last, so we cannot use it in this scenario, and we have to declare it as a bidirectional iterator only." }, { "code": null, "e": 36079, "s": 35137, "text": "std::random_shuffle: As we know this algorithm is used to randomly shuffle all the elements present in a container. So, let us look at its internal working (Don’t go into detail just look where bidirectional iterators can be used and where they cannot be):// Definition of std::random_shuffle()template void random_shuffle(RandomAccessIterator first, RandomAccessIterator last, RandomNumberGenerator& gen){ iterator_traits::difference_type i, n; n = (last - first); for (i=n-1; i>0; --i) { swap (first[i],first[gen(i+1)]); }}Here, we can see that we have made use of Random-access iterators, as although we can increment a bidirectional iterator, decrement it as well, but we cannot apply arithmetic operator like +, – to it and this what is required in this algorithm , where (last – first) is done, so, for this reason, we cannot use a bidirectional iterator in these scenarios." }, { "code": "// Definition of std::random_shuffle()template void random_shuffle(RandomAccessIterator first, RandomAccessIterator last, RandomNumberGenerator& gen){ iterator_traits::difference_type i, n; n = (last - first); for (i=n-1; i>0; --i) { swap (first[i],first[gen(i+1)]); }}", "e": 36410, "s": 36079, "text": null }, { "code": null, "e": 36766, "s": 36410, "text": "Here, we can see that we have made use of Random-access iterators, as although we can increment a bidirectional iterator, decrement it as well, but we cannot apply arithmetic operator like +, – to it and this what is required in this algorithm , where (last – first) is done, so, for this reason, we cannot use a bidirectional iterator in these scenarios." }, { "code": null, "e": 37057, "s": 36766, "text": "Note: As we know that Bidirectional iterator is higher in the hierarchy than forward iterator which is itself higher than input and output iterators, therefore, all these three types of iterators can be substituted by bidirectional iterators, without affecting the working of the algorithm." }, { "code": null, "e": 37170, "s": 37057, "text": "So, the two above examples very well show when, where, why and how bidirectional iterators are used practically." }, { "code": null, "e": 37182, "s": 37170, "text": "Limitations" }, { "code": null, "e": 37370, "s": 37182, "text": "After studying the salient features, one must also know its deficiencies as well although there are not as many as there are in input or output iterators as it is higher in the hierarchy." }, { "code": null, "e": 39054, "s": 37370, "text": "Relational Operators: Although, Bidirectional iterators can be used with equality operator (==), but it can not be used with other relational operators like , =.If A and B are Bidirectional iterators, then\n\nA == B // Allowed\nA <= B // Not Allowed\nArithmetic Operators: Similar to relational operators, they also can’t be used with arithmetic operators like +, – and so on. This means that bidirectional iterators can move in both the direction, but sequentially.If A and B are Bidirectional iterators, then\n\nA + 1 // Not allowed\nB - 2 // Not allowed\n// C++ program to demonstrate bidirectional iterator#include<iostream>#include<list>using namespace std;int main(){ list<int>v1 = {1, 2, 3, 4, 5}; // Declaring first iterator list<int>::iterator i1; // Declaring second iterator list<int>::iterator i2; // i1 points to the beginning of the list i1 = v1.begin(); // i2 points to the end of the list i2 = v1.end(); // Applying relational operator to them if ( i1 > i2) { cout << \"Yes\"; } // This will throw an error because relational // operators cannot be applied to bidirectional iterators // Applying arithmetic operator to them int count = i1 - i2; // This will also throw an error because arithmetic // operators cannot be applied to bidirectional iterators return 0;}Output:Error, because of use of arithmetic and relational operators \nwith bidirectional iterators \nUse of offset dereference operator ([ ]): Bidirectional iterators doesnot support offset dereference operator ([ ]), which is used for random-access.If A is a Bidirectional iterator, then\nA[3] // Not allowed \n" }, { "code": null, "e": 39310, "s": 39054, "text": "Relational Operators: Although, Bidirectional iterators can be used with equality operator (==), but it can not be used with other relational operators like , =.If A and B are Bidirectional iterators, then\n\nA == B // Allowed\nA <= B // Not Allowed\n" }, { "code": null, "e": 39405, "s": 39310, "text": "If A and B are Bidirectional iterators, then\n\nA == B // Allowed\nA <= B // Not Allowed\n" }, { "code": null, "e": 40622, "s": 39405, "text": "Arithmetic Operators: Similar to relational operators, they also can’t be used with arithmetic operators like +, – and so on. This means that bidirectional iterators can move in both the direction, but sequentially.If A and B are Bidirectional iterators, then\n\nA + 1 // Not allowed\nB - 2 // Not allowed\n// C++ program to demonstrate bidirectional iterator#include<iostream>#include<list>using namespace std;int main(){ list<int>v1 = {1, 2, 3, 4, 5}; // Declaring first iterator list<int>::iterator i1; // Declaring second iterator list<int>::iterator i2; // i1 points to the beginning of the list i1 = v1.begin(); // i2 points to the end of the list i2 = v1.end(); // Applying relational operator to them if ( i1 > i2) { cout << \"Yes\"; } // This will throw an error because relational // operators cannot be applied to bidirectional iterators // Applying arithmetic operator to them int count = i1 - i2; // This will also throw an error because arithmetic // operators cannot be applied to bidirectional iterators return 0;}Output:Error, because of use of arithmetic and relational operators \nwith bidirectional iterators \n" }, { "code": null, "e": 40719, "s": 40622, "text": "If A and B are Bidirectional iterators, then\n\nA + 1 // Not allowed\nB - 2 // Not allowed\n" }, { "code": "// C++ program to demonstrate bidirectional iterator#include<iostream>#include<list>using namespace std;int main(){ list<int>v1 = {1, 2, 3, 4, 5}; // Declaring first iterator list<int>::iterator i1; // Declaring second iterator list<int>::iterator i2; // i1 points to the beginning of the list i1 = v1.begin(); // i2 points to the end of the list i2 = v1.end(); // Applying relational operator to them if ( i1 > i2) { cout << \"Yes\"; } // This will throw an error because relational // operators cannot be applied to bidirectional iterators // Applying arithmetic operator to them int count = i1 - i2; // This will also throw an error because arithmetic // operators cannot be applied to bidirectional iterators return 0;}", "e": 41526, "s": 40719, "text": null }, { "code": null, "e": 41534, "s": 41526, "text": "Output:" }, { "code": null, "e": 41627, "s": 41534, "text": "Error, because of use of arithmetic and relational operators \nwith bidirectional iterators \n" }, { "code": null, "e": 41840, "s": 41627, "text": "Use of offset dereference operator ([ ]): Bidirectional iterators doesnot support offset dereference operator ([ ]), which is used for random-access.If A is a Bidirectional iterator, then\nA[3] // Not allowed \n" }, { "code": null, "e": 41904, "s": 41840, "text": "If A is a Bidirectional iterator, then\nA[3] // Not allowed \n" }, { "code": null, "e": 42207, "s": 41904, "text": "This article is contributed by Mrigendra Singh. 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": 42332, "s": 42207, "text": "Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above." }, { "code": null, "e": 42345, "s": 42332, "text": "Akanksha_Rai" }, { "code": null, "e": 42358, "s": 42345, "text": "cpp-iterator" }, { "code": null, "e": 42362, "s": 42358, "text": "STL" }, { "code": null, "e": 42366, "s": 42362, "text": "C++" }, { "code": null, "e": 42371, "s": 42366, "text": "Misc" }, { "code": null, "e": 42376, "s": 42371, "text": "Misc" }, { "code": null, "e": 42381, "s": 42376, "text": "Misc" }, { "code": null, "e": 42385, "s": 42381, "text": "STL" }, { "code": null, "e": 42389, "s": 42385, "text": "CPP" }, { "code": null, "e": 42487, "s": 42389, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 42496, "s": 42487, "text": "Comments" }, { "code": null, "e": 42509, "s": 42496, "text": "Old Comments" }, { "code": null, "e": 42537, "s": 42509, "text": "Operator Overloading in C++" }, { "code": null, "e": 42558, "s": 42537, "text": "Iterators in C++ STL" }, { "code": null, "e": 42591, "s": 42558, "text": "Friend class and function in C++" }, { "code": null, "e": 42611, "s": 42591, "text": "Polymorphism in C++" }, { "code": null, "e": 42635, "s": 42611, "text": "Sorting a vector in C++" }, { "code": null, "e": 42676, "s": 42635, "text": "Top 10 algorithms in Interview Questions" }, { "code": null, "e": 42730, "s": 42676, "text": "vector::push_back() and vector::pop_back() in C++ STL" }, { "code": null, "e": 42791, "s": 42730, "text": "Overview of Data Structures | Set 1 (Linear Data Structures)" }, { "code": null, "e": 42825, "s": 42791, "text": "How to write Regular Expressions?" } ]
How to Fix: TypeError: ‘numpy.float’ object is not callable? - GeeksforGeeks
28 Nov, 2021 In this article, we are going to see how to fix TypeError: ‘numpy.float’ object is not callable in Python. There is only one case in which we can see this error: If we try to call a NumPy array as a function, we are most likely to get such an error. Example: Python3 import numpy as np a = np.array([1,2,3]) a() Output: TypeError: 'numpy.ndarray' object is not callable In the older version of Numpy, we used to see “numpy.float64” instead of “numpy.ndarray”. Solution: This can be solved simply by removing the parenthesis after the array. Python3 import numpy as np a = np.array([1,2,3]) a Output: array([1, 2, 3]) Here version of NumPy is ‘1.21.2’. Note: In the earlier version of Numpy, we also used to get this error while using Python min() or max() function with a NumPy array. In the recent versions of NumPy, this is solved. In the earlier versions, this particular error was supposed to be solved using np.max() or np.min() instead of min() and max(). Picked Python How-to-fix Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to Install PIP on Windows ? Check if element exists in list in Python How To Convert Python Dictionary To JSON? How to drop one or multiple columns in Pandas Dataframe Python Classes and Objects Python | os.path.join() method Python | Get unique values from a list Create a directory in Python Defaultdict in Python Python | Pandas dataframe.groupby()
[ { "code": null, "e": 25537, "s": 25509, "text": "\n28 Nov, 2021" }, { "code": null, "e": 25700, "s": 25537, "text": "In this article, we are going to see how to fix TypeError: ‘numpy.float’ object is not callable in Python. There is only one case in which we can see this error: " }, { "code": null, "e": 25789, "s": 25700, "text": "If we try to call a NumPy array as a function, we are most likely to get such an error. " }, { "code": null, "e": 25798, "s": 25789, "text": "Example:" }, { "code": null, "e": 25806, "s": 25798, "text": "Python3" }, { "code": "import numpy as np a = np.array([1,2,3]) a()", "e": 25853, "s": 25806, "text": null }, { "code": null, "e": 25861, "s": 25853, "text": "Output:" }, { "code": null, "e": 25911, "s": 25861, "text": "TypeError: 'numpy.ndarray' object is not callable" }, { "code": null, "e": 26001, "s": 25911, "text": "In the older version of Numpy, we used to see “numpy.float64” instead of “numpy.ndarray”." }, { "code": null, "e": 26012, "s": 26001, "text": "Solution: " }, { "code": null, "e": 26084, "s": 26012, "text": "This can be solved simply by removing the parenthesis after the array. " }, { "code": null, "e": 26092, "s": 26084, "text": "Python3" }, { "code": "import numpy as np a = np.array([1,2,3]) a", "e": 26137, "s": 26092, "text": null }, { "code": null, "e": 26145, "s": 26137, "text": "Output:" }, { "code": null, "e": 26162, "s": 26145, "text": "array([1, 2, 3])" }, { "code": null, "e": 26197, "s": 26162, "text": "Here version of NumPy is ‘1.21.2’." }, { "code": null, "e": 26509, "s": 26197, "text": "Note: In the earlier version of Numpy, we also used to get this error while using Python min() or max() function with a NumPy array. In the recent versions of NumPy, this is solved. In the earlier versions, this particular error was supposed to be solved using np.max() or np.min() instead of min() and max(). " }, { "code": null, "e": 26516, "s": 26509, "text": "Picked" }, { "code": null, "e": 26534, "s": 26516, "text": "Python How-to-fix" }, { "code": null, "e": 26541, "s": 26534, "text": "Python" }, { "code": null, "e": 26639, "s": 26541, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 26671, "s": 26639, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 26713, "s": 26671, "text": "Check if element exists in list in Python" }, { "code": null, "e": 26755, "s": 26713, "text": "How To Convert Python Dictionary To JSON?" }, { "code": null, "e": 26811, "s": 26755, "text": "How to drop one or multiple columns in Pandas Dataframe" }, { "code": null, "e": 26838, "s": 26811, "text": "Python Classes and Objects" }, { "code": null, "e": 26869, "s": 26838, "text": "Python | os.path.join() method" }, { "code": null, "e": 26908, "s": 26869, "text": "Python | Get unique values from a list" }, { "code": null, "e": 26937, "s": 26908, "text": "Create a directory in Python" }, { "code": null, "e": 26959, "s": 26937, "text": "Defaultdict in Python" } ]
pow() in Python - GeeksforGeeks
22 Sep, 2021 Python pow() function returns the power of the given numbers. This function computes x**y. This function first converts its arguments into float and then computes the power. Syntax: pow(x,y) Parameters : x : Number whose power has to be calculated. y : Value raised to compute power. Return Value : Returns the value x**y in float. Python3 # Python code to demonstrate pow()# version 1 print("The value of 3**4 is : ", end="") # Returns 81print(pow(3, 4)) Output: The value of 3**4 is : 81.0 float pow(x,y,mod) function computes (x**y) % mod. This function first converts its arguments into float and then computes the power. Syntax: float pow(x,y,mod) Parameters : x : Number whose power has to be calculated. y : Value raised to compute power. mod : Value with which modulus has to be computed. Return Value : Returns the value (x**y) % mod in float. Python3 # Python code to demonstrate pow()# version 2 print("The value of (3**4) % 10 is : ", end="") # Returns 81%10# Returns 1print(pow(3, 4, 10)) Output: The value of (3**4) % 10 is : 1 Python3 # Python code to discuss negative# and non-negative cases # positive x, positive y (x**y)print("Positive x and positive y : ", end="")print(pow(4, 3)) print("Negative x and positive y : ", end="")# negative x, positive y (-x**y)print(pow(-4, 3)) print("Positive x and negative y : ", end="")# positive x, negative y (x**-y)print(pow(4, -3)) print("Negative x and negative y : ", end="")# negative x, negative y (-x**-y)print(pow(-4, -3)) Output: Positive x and positive y : 64 Negative x and positive y : -64 Positive x and negative y : 0.015625 Negative x and negative y : -0.015625 This article is contributed by Manjeet Singh. 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. RajuKumar19 kumar_satyam 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": 25298, "s": 25270, "text": "\n22 Sep, 2021" }, { "code": null, "e": 25473, "s": 25298, "text": "Python pow() function returns the power of the given numbers. This function computes x**y. This function first converts its arguments into float and then computes the power. " }, { "code": null, "e": 25490, "s": 25473, "text": "Syntax: pow(x,y)" }, { "code": null, "e": 25504, "s": 25490, "text": "Parameters : " }, { "code": null, "e": 25549, "s": 25504, "text": "x : Number whose power has to be calculated." }, { "code": null, "e": 25584, "s": 25549, "text": "y : Value raised to compute power." }, { "code": null, "e": 25633, "s": 25584, "text": "Return Value : Returns the value x**y in float." }, { "code": null, "e": 25641, "s": 25633, "text": "Python3" }, { "code": "# Python code to demonstrate pow()# version 1 print(\"The value of 3**4 is : \", end=\"\") # Returns 81print(pow(3, 4))", "e": 25757, "s": 25641, "text": null }, { "code": null, "e": 25766, "s": 25757, "text": "Output: " }, { "code": null, "e": 25794, "s": 25766, "text": "The value of 3**4 is : 81.0" }, { "code": null, "e": 25929, "s": 25794, "text": "float pow(x,y,mod) function computes (x**y) % mod. This function first converts its arguments into float and then computes the power. " }, { "code": null, "e": 25956, "s": 25929, "text": "Syntax: float pow(x,y,mod)" }, { "code": null, "e": 25970, "s": 25956, "text": "Parameters : " }, { "code": null, "e": 26015, "s": 25970, "text": "x : Number whose power has to be calculated." }, { "code": null, "e": 26050, "s": 26015, "text": "y : Value raised to compute power." }, { "code": null, "e": 26102, "s": 26050, "text": "mod : Value with which modulus has to be computed." }, { "code": null, "e": 26159, "s": 26102, "text": "Return Value : Returns the value (x**y) % mod in float." }, { "code": null, "e": 26167, "s": 26159, "text": "Python3" }, { "code": "# Python code to demonstrate pow()# version 2 print(\"The value of (3**4) % 10 is : \", end=\"\") # Returns 81%10# Returns 1print(pow(3, 4, 10))", "e": 26308, "s": 26167, "text": null }, { "code": null, "e": 26317, "s": 26308, "text": "Output: " }, { "code": null, "e": 26349, "s": 26317, "text": "The value of (3**4) % 10 is : 1" }, { "code": null, "e": 26357, "s": 26349, "text": "Python3" }, { "code": "# Python code to discuss negative# and non-negative cases # positive x, positive y (x**y)print(\"Positive x and positive y : \", end=\"\")print(pow(4, 3)) print(\"Negative x and positive y : \", end=\"\")# negative x, positive y (-x**y)print(pow(-4, 3)) print(\"Positive x and negative y : \", end=\"\")# positive x, negative y (x**-y)print(pow(4, -3)) print(\"Negative x and negative y : \", end=\"\")# negative x, negative y (-x**-y)print(pow(-4, -3))", "e": 26795, "s": 26357, "text": null }, { "code": null, "e": 26803, "s": 26795, "text": "Output:" }, { "code": null, "e": 26941, "s": 26803, "text": "Positive x and positive y : 64\nNegative x and positive y : -64\nPositive x and negative y : 0.015625\nNegative x and negative y : -0.015625" }, { "code": null, "e": 27238, "s": 26941, "text": "This article is contributed by Manjeet Singh. 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." }, { "code": null, "e": 27363, "s": 27238, "text": "Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above." }, { "code": null, "e": 27375, "s": 27363, "text": "RajuKumar19" }, { "code": null, "e": 27388, "s": 27375, "text": "kumar_satyam" }, { "code": null, "e": 27395, "s": 27388, "text": "Python" }, { "code": null, "e": 27493, "s": 27395, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 27511, "s": 27493, "text": "Python Dictionary" }, { "code": null, "e": 27546, "s": 27511, "text": "Read a file line by line in Python" }, { "code": null, "e": 27578, "s": 27546, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 27600, "s": 27578, "text": "Enumerate() in Python" }, { "code": null, "e": 27642, "s": 27600, "text": "Different ways to create Pandas Dataframe" }, { "code": null, "e": 27672, "s": 27642, "text": "Iterate over a list in Python" }, { "code": null, "e": 27698, "s": 27672, "text": "Python String | replace()" }, { "code": null, "e": 27727, "s": 27698, "text": "*args and **kwargs in Python" }, { "code": null, "e": 27771, "s": 27727, "text": "Reading and Writing to text files in Python" } ]
Lodash _.concat() Function - GeeksforGeeks
05 May, 2021 Lodash proves to be much useful when working with arrays, strings, objects etc. It makes math operations and function paradigm much easier, concise. The _.concat() function is used to concatenating the arrays in JavaScript. Syntax: _.concat(array, [values]) Parameters: This function accept two parameters as mentioned above and described below: array: It is an array to which values are to be added. values: It is the Array of values that is to be added to the original array. Note: The array value can also contain arrays of array or simple a single object to be added to original array. Return Value: This function returns the array after concatenation. Few examples are given below for better understanding of the function. Example 1: Javascript // Requiring the lodash librarylet lodash = require("lodash"); // Original array to be concatenatedlet array = [1, 2, 3]; // Values to be added to original arraylet values = [0, 5, "a", "b"] let newArray = lodash.concat(array, values);console.log("Before concat: " + array); // Printing newArrayconsole.log("After concat: " + newArray); Output: Example 2: Adding array of array to original array. JavaScript // Requiring the lodash librarylet lodash = require("lodash"); // Original array to be concatenatedlet array = ["a", 2, 3]; // Array of array to be added// to original arraylet values = [0, 5, ["a", "b"]]let newArray = lodash.concat(array, values);console.log("Before concat: ", array); // Printing arrayconsole.log("After concat: ", newArray); Output: Example 3: This example adding the object to the array. Javascript // Requiring the lodash librarylet lodash = require("lodash"); // Original array to be concatenatedlet array = ["a", 2, 3]; // Object of values to be// added to original arraylet values = { "a": 1, "b": 2 }let newArray = lodash.concat(array, values);console.log("Before concat: ", array); // Printing arrayconsole.log("After concat: ", newArray); Output: surinderdawra388 JavaScript-Lodash JavaScript Web Technologies Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Remove elements from a JavaScript Array Convert a string to an integer in JavaScript Difference between var, let and const keywords in JavaScript Differences between Functional Components and Class Components in React How to calculate the number of days between two dates in javascript? Remove elements from a JavaScript Array Installation of Node.js on Linux Convert a string to an integer in JavaScript How to fetch data from an API in ReactJS ? How to insert spaces/tabs in text using HTML/CSS?
[ { "code": null, "e": 38681, "s": 38653, "text": "\n05 May, 2021" }, { "code": null, "e": 38905, "s": 38681, "text": "Lodash proves to be much useful when working with arrays, strings, objects etc. It makes math operations and function paradigm much easier, concise. The _.concat() function is used to concatenating the arrays in JavaScript." }, { "code": null, "e": 38913, "s": 38905, "text": "Syntax:" }, { "code": null, "e": 38939, "s": 38913, "text": "_.concat(array, [values])" }, { "code": null, "e": 39028, "s": 38939, "text": "Parameters: This function accept two parameters as mentioned above and described below: " }, { "code": null, "e": 39083, "s": 39028, "text": "array: It is an array to which values are to be added." }, { "code": null, "e": 39160, "s": 39083, "text": "values: It is the Array of values that is to be added to the original array." }, { "code": null, "e": 39272, "s": 39160, "text": "Note: The array value can also contain arrays of array or simple a single object to be added to original array." }, { "code": null, "e": 39339, "s": 39272, "text": "Return Value: This function returns the array after concatenation." }, { "code": null, "e": 39410, "s": 39339, "text": "Few examples are given below for better understanding of the function." }, { "code": null, "e": 39421, "s": 39410, "text": "Example 1:" }, { "code": null, "e": 39432, "s": 39421, "text": "Javascript" }, { "code": "// Requiring the lodash librarylet lodash = require(\"lodash\"); // Original array to be concatenatedlet array = [1, 2, 3]; // Values to be added to original arraylet values = [0, 5, \"a\", \"b\"] let newArray = lodash.concat(array, values);console.log(\"Before concat: \" + array); // Printing newArrayconsole.log(\"After concat: \" + newArray);", "e": 39769, "s": 39432, "text": null }, { "code": null, "e": 39777, "s": 39769, "text": "Output:" }, { "code": null, "e": 39829, "s": 39777, "text": "Example 2: Adding array of array to original array." }, { "code": null, "e": 39840, "s": 39829, "text": "JavaScript" }, { "code": "// Requiring the lodash librarylet lodash = require(\"lodash\"); // Original array to be concatenatedlet array = [\"a\", 2, 3]; // Array of array to be added// to original arraylet values = [0, 5, [\"a\", \"b\"]]let newArray = lodash.concat(array, values);console.log(\"Before concat: \", array); // Printing arrayconsole.log(\"After concat: \", newArray);", "e": 40185, "s": 39840, "text": null }, { "code": null, "e": 40193, "s": 40185, "text": "Output:" }, { "code": null, "e": 40249, "s": 40193, "text": "Example 3: This example adding the object to the array." }, { "code": null, "e": 40260, "s": 40249, "text": "Javascript" }, { "code": "// Requiring the lodash librarylet lodash = require(\"lodash\"); // Original array to be concatenatedlet array = [\"a\", 2, 3]; // Object of values to be// added to original arraylet values = { \"a\": 1, \"b\": 2 }let newArray = lodash.concat(array, values);console.log(\"Before concat: \", array); // Printing arrayconsole.log(\"After concat: \", newArray);", "e": 40607, "s": 40260, "text": null }, { "code": null, "e": 40615, "s": 40607, "text": "Output:" }, { "code": null, "e": 40632, "s": 40615, "text": "surinderdawra388" }, { "code": null, "e": 40650, "s": 40632, "text": "JavaScript-Lodash" }, { "code": null, "e": 40661, "s": 40650, "text": "JavaScript" }, { "code": null, "e": 40678, "s": 40661, "text": "Web Technologies" }, { "code": null, "e": 40776, "s": 40678, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 40816, "s": 40776, "text": "Remove elements from a JavaScript Array" }, { "code": null, "e": 40861, "s": 40816, "text": "Convert a string to an integer in JavaScript" }, { "code": null, "e": 40922, "s": 40861, "text": "Difference between var, let and const keywords in JavaScript" }, { "code": null, "e": 40994, "s": 40922, "text": "Differences between Functional Components and Class Components in React" }, { "code": null, "e": 41063, "s": 40994, "text": "How to calculate the number of days between two dates in javascript?" }, { "code": null, "e": 41103, "s": 41063, "text": "Remove elements from a JavaScript Array" }, { "code": null, "e": 41136, "s": 41103, "text": "Installation of Node.js on Linux" }, { "code": null, "e": 41181, "s": 41136, "text": "Convert a string to an integer in JavaScript" }, { "code": null, "e": 41224, "s": 41181, "text": "How to fetch data from an API in ReactJS ?" } ]
Java Applet | Digital Stopwatch - GeeksforGeeks
29 Aug, 2018 This article will provide an instance of creating one type of stopwatch with Java Applet, AWT and Thread. We shall be using all these library to make a working model of a stopwatch. The GUI shall have 3 buttons for interaction, namely, start (to start the time), reset (to reset the time to default value) and stop (to stop the timer). With the help of actionListener in Java we can learn which button is pressed when. When the start button is pressed, we start the timer. While the reset or the stop button isn’t pressed we shall keep the timer running i.e. we shall change the value of the timer (hh:mm:ss:ms) every 1 millisecond and update the screen.When reset button is pressed, we shall stop the timer and set it to is default value (00:00:00:000).When the stop button is pressed, we stop the timer with the value as it is. When the start button is pressed, we start the timer. While the reset or the stop button isn’t pressed we shall keep the timer running i.e. we shall change the value of the timer (hh:mm:ss:ms) every 1 millisecond and update the screen. When reset button is pressed, we shall stop the timer and set it to is default value (00:00:00:000). When the stop button is pressed, we stop the timer with the value as it is. Below is the implementation of Digital Stopwatch // Java program to illustrate// digital stop watch// using Applets // importing required packagesimport java.applet.*;import java.awt.*;import java.awt.event.ActionEvent;import java.awt.event.ActionListener; public class GeeksforGeeks extends Applet implements Runnable, ActionListener { // Panel to keep all the buttons and labels Panel p; Label display; // Button Button start, stop, reset; // Time int hour, minute, second, millisecond; // string to be displayed on the label String disp; // State of stopwatch on/off boolean on; // initialization public void init() { // initially off on = false; p = new Panel(); // Setting layout of the panel p.setLayout(new GridLayout(4, 1, 6, 10)); // initial time 00 : 00 : 00 : 000 hour = minute = second = millisecond = 0; // Label display = new Label(); disp = "00 : 00 : 00 : 000"; display.setText(disp); p.add(display); // Start button start = new Button("Start"); start.addActionListener((ActionListener) this); p.add(start); // Reset button reset = new Button("Reset"); reset.addActionListener((ActionListener) this); p.add(reset); // Stop button stop = new Button("Stop"); stop.addActionListener((ActionListener) this); p.add(stop); add(p); // starting thread new Thread(this, "StopWatch").start(); } // Reset Function // reset to default value public void reset() { try { Thread.sleep(1); } catch (Exception e) { System.out.println(e); } hour = minute = second = millisecond = 0; } // update function // update the timer public void update() { millisecond++; if (millisecond == 1000) { millisecond = 0; second++; if (second == 60) { second = 0; minute++; if (minute == 60) { minute = 0; hour++; } } } } // changing label public void changeLabel() { // Properly formatting the display of the timer if (hour < 10) disp = "0" + hour + " : "; else disp = hour + " : "; if (minute < 10) disp += "0" + minute + " : "; else disp += minute + " : "; if (second < 10) disp += "0" + second + " : "; else disp += second + " : "; if (millisecond < 10) disp += "00" + millisecond; else if (millisecond < 100) disp += "0" + millisecond; else disp += millisecond; display.setText(disp); } // thread.run function public void run() { // while the stopwatch is on while (on) { try { // pause 1 millisecond Thread.sleep(1); // update the time update(); // changeLabel changeLabel(); } catch (InterruptedException e) { System.out.println(e); } } } // actionPerformed // To listen to the actions on the buttons public void actionPerformed(ActionEvent e) { // start a thread when start button is clicked if (e.getSource() == start) { // stopwatch is on on = true; new Thread(this, "StopWatch").start(); } // reset if (e.getSource() == reset) { // stopwatch off on = false; reset(); changeLabel(); } if (e.getSource() == stop) { // stopwatch off on = false; } }} Output : See here java-applet Java Java Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Stream In Java Constructors in Java Exceptions in Java Functional Interfaces in Java Different ways of Reading a text file in Java Generics in Java Introduction to Java Comparator Interface in Java with Examples Internal Working of HashMap in Java Strings in Java
[ { "code": null, "e": 25225, "s": 25197, "text": "\n29 Aug, 2018" }, { "code": null, "e": 25331, "s": 25225, "text": "This article will provide an instance of creating one type of stopwatch with Java Applet, AWT and Thread." }, { "code": null, "e": 25561, "s": 25331, "text": "We shall be using all these library to make a working model of a stopwatch. The GUI shall have 3 buttons for interaction, namely, start (to start the time), reset (to reset the time to default value) and stop (to stop the timer)." }, { "code": null, "e": 25644, "s": 25561, "text": "With the help of actionListener in Java we can learn which button is pressed when." }, { "code": null, "e": 26055, "s": 25644, "text": "When the start button is pressed, we start the timer. While the reset or the stop button isn’t pressed we shall keep the timer running i.e. we shall change the value of the timer (hh:mm:ss:ms) every 1 millisecond and update the screen.When reset button is pressed, we shall stop the timer and set it to is default value (00:00:00:000).When the stop button is pressed, we stop the timer with the value as it is." }, { "code": null, "e": 26291, "s": 26055, "text": "When the start button is pressed, we start the timer. While the reset or the stop button isn’t pressed we shall keep the timer running i.e. we shall change the value of the timer (hh:mm:ss:ms) every 1 millisecond and update the screen." }, { "code": null, "e": 26392, "s": 26291, "text": "When reset button is pressed, we shall stop the timer and set it to is default value (00:00:00:000)." }, { "code": null, "e": 26468, "s": 26392, "text": "When the stop button is pressed, we stop the timer with the value as it is." }, { "code": null, "e": 26517, "s": 26468, "text": "Below is the implementation of Digital Stopwatch" }, { "code": "// Java program to illustrate// digital stop watch// using Applets // importing required packagesimport java.applet.*;import java.awt.*;import java.awt.event.ActionEvent;import java.awt.event.ActionListener; public class GeeksforGeeks extends Applet implements Runnable, ActionListener { // Panel to keep all the buttons and labels Panel p; Label display; // Button Button start, stop, reset; // Time int hour, minute, second, millisecond; // string to be displayed on the label String disp; // State of stopwatch on/off boolean on; // initialization public void init() { // initially off on = false; p = new Panel(); // Setting layout of the panel p.setLayout(new GridLayout(4, 1, 6, 10)); // initial time 00 : 00 : 00 : 000 hour = minute = second = millisecond = 0; // Label display = new Label(); disp = \"00 : 00 : 00 : 000\"; display.setText(disp); p.add(display); // Start button start = new Button(\"Start\"); start.addActionListener((ActionListener) this); p.add(start); // Reset button reset = new Button(\"Reset\"); reset.addActionListener((ActionListener) this); p.add(reset); // Stop button stop = new Button(\"Stop\"); stop.addActionListener((ActionListener) this); p.add(stop); add(p); // starting thread new Thread(this, \"StopWatch\").start(); } // Reset Function // reset to default value public void reset() { try { Thread.sleep(1); } catch (Exception e) { System.out.println(e); } hour = minute = second = millisecond = 0; } // update function // update the timer public void update() { millisecond++; if (millisecond == 1000) { millisecond = 0; second++; if (second == 60) { second = 0; minute++; if (minute == 60) { minute = 0; hour++; } } } } // changing label public void changeLabel() { // Properly formatting the display of the timer if (hour < 10) disp = \"0\" + hour + \" : \"; else disp = hour + \" : \"; if (minute < 10) disp += \"0\" + minute + \" : \"; else disp += minute + \" : \"; if (second < 10) disp += \"0\" + second + \" : \"; else disp += second + \" : \"; if (millisecond < 10) disp += \"00\" + millisecond; else if (millisecond < 100) disp += \"0\" + millisecond; else disp += millisecond; display.setText(disp); } // thread.run function public void run() { // while the stopwatch is on while (on) { try { // pause 1 millisecond Thread.sleep(1); // update the time update(); // changeLabel changeLabel(); } catch (InterruptedException e) { System.out.println(e); } } } // actionPerformed // To listen to the actions on the buttons public void actionPerformed(ActionEvent e) { // start a thread when start button is clicked if (e.getSource() == start) { // stopwatch is on on = true; new Thread(this, \"StopWatch\").start(); } // reset if (e.getSource() == reset) { // stopwatch off on = false; reset(); changeLabel(); } if (e.getSource() == stop) { // stopwatch off on = false; } }}", "e": 30390, "s": 26517, "text": null }, { "code": null, "e": 30399, "s": 30390, "text": "Output :" }, { "code": null, "e": 30408, "s": 30399, "text": "See here" }, { "code": null, "e": 30420, "s": 30408, "text": "java-applet" }, { "code": null, "e": 30425, "s": 30420, "text": "Java" }, { "code": null, "e": 30430, "s": 30425, "text": "Java" }, { "code": null, "e": 30528, "s": 30430, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 30543, "s": 30528, "text": "Stream In Java" }, { "code": null, "e": 30564, "s": 30543, "text": "Constructors in Java" }, { "code": null, "e": 30583, "s": 30564, "text": "Exceptions in Java" }, { "code": null, "e": 30613, "s": 30583, "text": "Functional Interfaces in Java" }, { "code": null, "e": 30659, "s": 30613, "text": "Different ways of Reading a text file in Java" }, { "code": null, "e": 30676, "s": 30659, "text": "Generics in Java" }, { "code": null, "e": 30697, "s": 30676, "text": "Introduction to Java" }, { "code": null, "e": 30740, "s": 30697, "text": "Comparator Interface in Java with Examples" }, { "code": null, "e": 30776, "s": 30740, "text": "Internal Working of HashMap in Java" } ]
How to wrap the text around an image using HTML and CSS ? - GeeksforGeeks
30 Jul, 2021 Wrapping the text around an image is quite attractive for any kind of website. Now the image can be in different shapes or the basic square shape. We have to wrap that image with the text. By using HTML and CSS wrapping an image with the text is possible and there are many ways to do so because the shape of any image is not constant. Wrapping a text means adjusting/wrapping text around an image. In HTML, we can either align the image on the right side of the text, or to the left, or to the center. In CSS, besides these we can also insert the images in a circle or rectangle, etc. and can wrap a text around it. You can also use CSS shape-outside Property depending on the shape of your image.Below examples illustrate the above approach:Example 1: In this example, the image is floating right side of the screen and the text is wrapping the image. In this example, we don’t require shape-outside property because the shape image is usual(square). html <!DOCTYPE html><html> <head> <title> Wrapping an Image with the text </title> <style> body { margin: 20px; text-align: center; } h1 { color: green; } img { float: left; margin: 5px; } p { text-align: justify; font-size: 25px; } </style></head> <body> <h1>GeeksforGeeks</h1> <b> A Computer Science Portal for Geeks </b> <div class="square"> <div> <img src= "https://media.geeksforgeeks.org/wp-content/uploads/20190808143838/logsm.png" alt="Longtail boat in Thailand"> </div> <p> How many times were you frustrated while looking out for a good collection of programming/algorithm /interview questions? What did you expect and what did you get? This portal has been created to provide well written, well thought and well explained solutions for selected questions. An IIT Roorkee alumnus and founder of GeeksforGeeks. He loves to solve programming problems in most efficient ways. Apart from GeeksforGeeks, he has worked with DE Shaw and Co. as a software developer and JIIT Noida as an assistant professor. It is a good platform to learn programming. It is an educational website. Prepare for the Recruitment drive of product based companies like Microsoft, Amazon, Adobe etc with a free online placement preparation course. </p> </div></body> </html> Output: Example 2: In this example, we will wrap different shape images and here we will use CSS shape-outside property for the better viewing experience. html <!DOCTYPE html><html> <head> <title> Wrapping an Image with the text </title> <style> body { margin: 20px; text-align:center; } h1 { color: green; } /* This div design part is used as an Image */ .round { width: 200px; height: 200px; border-radius: 50%; text-align: center; font-size: 30px; float: left; font-weight: bold; /* Change the shape according to the image */ shape-outside: circle(); background-color: Green; color: white; } article{ padding-top: 75px; display: inline-block; } p { text-align: justify; font-size: 22px; } </style></head> <body> <h1>GeeksforGeeks</h1> <b> A Computer Science Portal for Geeks </b> <div class="round"> <article>GeeksforGeeks</article> </div> <p> How many times were you frustrated while looking out for a good collection of programming/ algorithm/ interview questions? What did you expect and what did you get? This portal has been created to provide well written, well thought and well explained solutions for selected questions. An IIT Roorkee alumnus and founder of GeeksforGeeks. He loves to solve programming problems in most efficient ways. Apart from GeeksforGeeks, he has worked with DE Shaw and Co. as a software developer and JIIT Noida as an assistant professor. It is a good platform to learn programming. It is an educational website. Prepare for the Recruitment drive of product based companies like Microsoft, Amazon, Adobe etc with a free online placement preparation course. </p> </body> </html> Output: HTML is the foundation of webpages, is used for webpage development by structuring websites and web apps.You can learn HTML from the ground up by following this HTML Tutorial and HTML Examples. CSS is the foundation of webpages, is used for webpage development by styling websites and web apps.You can learn CSS from the ground up by following this CSS Tutorial and CSS Examples. Attention reader! Don’t stop learning now. Get hold of all the important HTML concepts with the Web Design for Beginners | HTML course. sumitgumber28 CSS-Misc HTML-Misc Picked CSS HTML Web Technologies Web technologies Questions HTML Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Types of CSS (Cascading Style Sheet) How to set space between the flexbox ? Design a web page using HTML and CSS How to Upload Image into Database and Display it using PHP ? Create a Responsive Navbar using ReactJS How to set the default value for an HTML <select> element ? Hide or show elements in HTML using display property How to set input type date in dd-mm-yyyy format using HTML ? REST API (Introduction) How to Insert Form Data into Database using PHP ?
[ { "code": null, "e": 26527, "s": 26499, "text": "\n30 Jul, 2021" }, { "code": null, "e": 27481, "s": 26527, "text": "Wrapping the text around an image is quite attractive for any kind of website. Now the image can be in different shapes or the basic square shape. We have to wrap that image with the text. By using HTML and CSS wrapping an image with the text is possible and there are many ways to do so because the shape of any image is not constant. Wrapping a text means adjusting/wrapping text around an image. In HTML, we can either align the image on the right side of the text, or to the left, or to the center. In CSS, besides these we can also insert the images in a circle or rectangle, etc. and can wrap a text around it. You can also use CSS shape-outside Property depending on the shape of your image.Below examples illustrate the above approach:Example 1: In this example, the image is floating right side of the screen and the text is wrapping the image. In this example, we don’t require shape-outside property because the shape image is usual(square). " }, { "code": null, "e": 27486, "s": 27481, "text": "html" }, { "code": "<!DOCTYPE html><html> <head> <title> Wrapping an Image with the text </title> <style> body { margin: 20px; text-align: center; } h1 { color: green; } img { float: left; margin: 5px; } p { text-align: justify; font-size: 25px; } </style></head> <body> <h1>GeeksforGeeks</h1> <b> A Computer Science Portal for Geeks </b> <div class=\"square\"> <div> <img src= \"https://media.geeksforgeeks.org/wp-content/uploads/20190808143838/logsm.png\" alt=\"Longtail boat in Thailand\"> </div> <p> How many times were you frustrated while looking out for a good collection of programming/algorithm /interview questions? What did you expect and what did you get? This portal has been created to provide well written, well thought and well explained solutions for selected questions. An IIT Roorkee alumnus and founder of GeeksforGeeks. He loves to solve programming problems in most efficient ways. Apart from GeeksforGeeks, he has worked with DE Shaw and Co. as a software developer and JIIT Noida as an assistant professor. It is a good platform to learn programming. It is an educational website. Prepare for the Recruitment drive of product based companies like Microsoft, Amazon, Adobe etc with a free online placement preparation course. </p> </div></body> </html>", "e": 29190, "s": 27486, "text": null }, { "code": null, "e": 29200, "s": 29190, "text": "Output: " }, { "code": null, "e": 29349, "s": 29200, "text": "Example 2: In this example, we will wrap different shape images and here we will use CSS shape-outside property for the better viewing experience. " }, { "code": null, "e": 29354, "s": 29349, "text": "html" }, { "code": "<!DOCTYPE html><html> <head> <title> Wrapping an Image with the text </title> <style> body { margin: 20px; text-align:center; } h1 { color: green; } /* This div design part is used as an Image */ .round { width: 200px; height: 200px; border-radius: 50%; text-align: center; font-size: 30px; float: left; font-weight: bold; /* Change the shape according to the image */ shape-outside: circle(); background-color: Green; color: white; } article{ padding-top: 75px; display: inline-block; } p { text-align: justify; font-size: 22px; } </style></head> <body> <h1>GeeksforGeeks</h1> <b> A Computer Science Portal for Geeks </b> <div class=\"round\"> <article>GeeksforGeeks</article> </div> <p> How many times were you frustrated while looking out for a good collection of programming/ algorithm/ interview questions? What did you expect and what did you get? This portal has been created to provide well written, well thought and well explained solutions for selected questions. An IIT Roorkee alumnus and founder of GeeksforGeeks. He loves to solve programming problems in most efficient ways. Apart from GeeksforGeeks, he has worked with DE Shaw and Co. as a software developer and JIIT Noida as an assistant professor. It is a good platform to learn programming. It is an educational website. Prepare for the Recruitment drive of product based companies like Microsoft, Amazon, Adobe etc with a free online placement preparation course. </p> </body> </html>", "e": 31355, "s": 29354, "text": null }, { "code": null, "e": 31365, "s": 31355, "text": "Output: " }, { "code": null, "e": 31561, "s": 31367, "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": 31747, "s": 31561, "text": "CSS is the foundation of webpages, is used for webpage development by styling websites and web apps.You can learn CSS from the ground up by following this CSS Tutorial and CSS Examples." }, { "code": null, "e": 31884, "s": 31747, "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": 31898, "s": 31884, "text": "sumitgumber28" }, { "code": null, "e": 31907, "s": 31898, "text": "CSS-Misc" }, { "code": null, "e": 31917, "s": 31907, "text": "HTML-Misc" }, { "code": null, "e": 31924, "s": 31917, "text": "Picked" }, { "code": null, "e": 31928, "s": 31924, "text": "CSS" }, { "code": null, "e": 31933, "s": 31928, "text": "HTML" }, { "code": null, "e": 31950, "s": 31933, "text": "Web Technologies" }, { "code": null, "e": 31977, "s": 31950, "text": "Web technologies Questions" }, { "code": null, "e": 31982, "s": 31977, "text": "HTML" }, { "code": null, "e": 32080, "s": 31982, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 32117, "s": 32080, "text": "Types of CSS (Cascading Style Sheet)" }, { "code": null, "e": 32156, "s": 32117, "text": "How to set space between the flexbox ?" }, { "code": null, "e": 32193, "s": 32156, "text": "Design a web page using HTML and CSS" }, { "code": null, "e": 32254, "s": 32193, "text": "How to Upload Image into Database and Display it using PHP ?" }, { "code": null, "e": 32295, "s": 32254, "text": "Create a Responsive Navbar using ReactJS" }, { "code": null, "e": 32355, "s": 32295, "text": "How to set the default value for an HTML <select> element ?" }, { "code": null, "e": 32408, "s": 32355, "text": "Hide or show elements in HTML using display property" }, { "code": null, "e": 32469, "s": 32408, "text": "How to set input type date in dd-mm-yyyy format using HTML ?" }, { "code": null, "e": 32493, "s": 32469, "text": "REST API (Introduction)" } ]
Bootstrap Buttons, Glyphicons, Tables - GeeksforGeeks
12 Jan, 2022 Introduction and InstallationGrid SystemVertical Forms, Horizontal Forms, Inline FormsDropDowns and Responsive TabsProgress Bar and Jumbotron Introduction and Installation Grid System Vertical Forms, Horizontal Forms, Inline Forms DropDowns and Responsive Tabs Progress Bar and Jumbotron After the previous article, one should be familiar with the Grid System of Bootstrap. Now, we’ll learn about making Buttons, the all new Glyphicons and Tables. Lets get started. We can make Buttons in Bootstrap in two ways ( or more specifically, using two tags ). Firstly, with the <a> tag and secondly by using the <button> tag. <a href="https://www.geeksforgeeks.org"class="btn btn-danger"> Button with'a'tag </a> <button type="button" class="btn btn-info" >Button with 'button' tag </button> We can have Buttons in different colours using Bootstrap. Each having a specific name like btn-default, btn-primary, btn-success, btn-info, btn-warning, btn-danger and btn-link. All of them represent a specific colour of button. We can also make buttons of different sizes ( by using btn-lg, btn-sm, btn-xs and btn-block attributes) <a href=” “>Button with <a> tag </a>Example:htmlhtml<!DOCTYPE html><html lang="en"><head> <title>Bootstrap Example</title> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.0/css/bootstrap.min.css"> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.0/jquery.min.js"></script> <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.0/js/bootstrap.min.js"></script></head><body> <div class="container" style="color:green"> <h1>GeeksforGeeks</h1> </div><div class="container"> <h2>Button Styles</h2> <button type="button" class="btn">Basic</button> <button type="button" class="btn btn-default">Default</button> <button type="button" class="btn btn-primary">Primary</button> <button type="button" class="btn btn-success">Success</button> <button type="button" class="btn btn-info">Info</button> <button type="button" class="btn btn-warning">Warning</button> <button type="button" class="btn btn-danger">Danger</button></div><br> <div class="container"> <h4>Button with <a> and <button> tag</h4> <a href="https://ide.geeksforgeeks.org/tryit.php"class="btn btn-danger"> Button with <a> tag </a> <button type="button" class="btn btn-success">Button with <button> tag </button> </div> </body></html>Output: html <!DOCTYPE html><html lang="en"><head> <title>Bootstrap Example</title> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.0/css/bootstrap.min.css"> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.0/jquery.min.js"></script> <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.0/js/bootstrap.min.js"></script></head><body> <div class="container" style="color:green"> <h1>GeeksforGeeks</h1> </div><div class="container"> <h2>Button Styles</h2> <button type="button" class="btn">Basic</button> <button type="button" class="btn btn-default">Default</button> <button type="button" class="btn btn-primary">Primary</button> <button type="button" class="btn btn-success">Success</button> <button type="button" class="btn btn-info">Info</button> <button type="button" class="btn btn-warning">Warning</button> <button type="button" class="btn btn-danger">Danger</button></div><br> <div class="container"> <h4>Button with <a> and <button> tag</h4> <a href="https://ide.geeksforgeeks.org/tryit.php"class="btn btn-danger"> Button with <a> tag </a> <button type="button" class="btn btn-success">Button with <button> tag </button> </div> </body></html> Output: Gorgeous Glyphicons:Glyphicons is a library of precisely prepared monochromatic icons and symbols, created with an emphasis to simplicity and easy orientation. We can use Glyphicons inside the span tag like this:<span class="Name of the glyphicon"> </span>Glyphicons can also be used within buttons like this:<a href="" class="btn btn-default"><span class="Name of the glyphicon"> </span> </a>One can see all the glyphicons available at http://getbootstrap.com/components for free. You can copy their names and paste within the quotes class=”Paste here”. If you need more specific glyphicon you can visit http://glyphicons.com/ and buy them.Example:htmlhtml<!DOCTYPE html><html lang="en"><head> <title>Bootstrap Example</title> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.0/css/bootstrap.min.css"> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.0/jquery.min.js"></script> <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.0/js/bootstrap.min.js"></script></head><body> <div class="container" style="color:green"> <h1>GeeksforGeeks</h1> </div> <div class="container"> <p>Correct<span class="glyphicon glyphicon-ok"></span></p> <p>Incorrect<span class="glyphicon glyphicon-remove"></span></p> <h4>Glyphicon with buttons</h4> <a href="https://www.geeksforgeeks.org"class="btn btn-primary"> <span class="glyphicon glyphicon-backward"></span> </a> <a href="https://www.geeksforgeeks.org"class="btn btn-danger"> <span class="glyphicon glyphicon-pause"></span> </a> <a href="https://www.geeksforgeeks.org"class="btn btn-success"> <span class="glyphicon glyphicon-play"></span> </a> <a href="https://www.geeksforgeeks.org"class="btn btn-primary"> <span class="glyphicon glyphicon-forward"></span> </a> </div> <br> <div class="container"> <a href="https://www.geeksforgeeks.org"class="btn btn-primary"> <span class="glyphicon glyphicon-thumbs-up"></span>Like Button </a> </div></body></html>Output: Glyphicons is a library of precisely prepared monochromatic icons and symbols, created with an emphasis to simplicity and easy orientation. We can use Glyphicons inside the span tag like this: <span class="Name of the glyphicon"> </span> Glyphicons can also be used within buttons like this: <a href="" class="btn btn-default"><span class="Name of the glyphicon"> </span> </a> One can see all the glyphicons available at http://getbootstrap.com/components for free. You can copy their names and paste within the quotes class=”Paste here”. If you need more specific glyphicon you can visit http://glyphicons.com/ and buy them. Example: html <!DOCTYPE html><html lang="en"><head> <title>Bootstrap Example</title> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.0/css/bootstrap.min.css"> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.0/jquery.min.js"></script> <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.0/js/bootstrap.min.js"></script></head><body> <div class="container" style="color:green"> <h1>GeeksforGeeks</h1> </div> <div class="container"> <p>Correct<span class="glyphicon glyphicon-ok"></span></p> <p>Incorrect<span class="glyphicon glyphicon-remove"></span></p> <h4>Glyphicon with buttons</h4> <a href="https://www.geeksforgeeks.org"class="btn btn-primary"> <span class="glyphicon glyphicon-backward"></span> </a> <a href="https://www.geeksforgeeks.org"class="btn btn-danger"> <span class="glyphicon glyphicon-pause"></span> </a> <a href="https://www.geeksforgeeks.org"class="btn btn-success"> <span class="glyphicon glyphicon-play"></span> </a> <a href="https://www.geeksforgeeks.org"class="btn btn-primary"> <span class="glyphicon glyphicon-forward"></span> </a> </div> <br> <div class="container"> <a href="https://www.geeksforgeeks.org"class="btn btn-primary"> <span class="glyphicon glyphicon-thumbs-up"></span>Like Button </a> </div></body></html> Tantalizing Tables:For creating tables, we need the <table> tag within which we use <tr> tag to define each row and <td>/<th> tag to represent actual data cell. In the table tag we can add different classes attributed to them which can make our table look better. Some of the table classes would be table-striped, table-bordered, table-hover, table-condensed, etc. You can find all the table classes here. The basic structure of the table is :<table class="table-striped"> <tr> <td>First Column</td> <td>Second Column</td> <td>Third Column</td> </tr> </table> You can also add different colours to each row of the table using the colour in the<tr> tag like <tr class=”danger”> </tr>Similarly, you can also add colours to each cell by including the class of colours in the <td> tag.Example:htmlhtml<!DOCTYPE html><html lang="en"><head> <title>Bootstrap Example</title> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.0/css/bootstrap.min.css"> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.0/jquery.min.js"></script> <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.0/js/bootstrap.min.js"></script></head><body> <div class="container" style="color:green"> <h1>GeeksforGeeks</h1> </div> <div class="container"> <h4>Tables using Bootstrap</h4> <hr><hr> <div class="container"> <div class="bg bg-success"> <table class="table table-hover"> <tr class="danger"> <td>First Column</td> <td>Second Column</td> <td>Third Column</td> </tr> <tr class="info"> <td>Python</td> <td>Java</td> <td>Swift</td> </tr> <tr class="danger"> <td>HTML</td> <td>CSS</td> <td>JavaScript</td> </tr> <tr class="info"> <td>MySql</td> <td>MongoDB</td> <td>SQL lit</td> </tr> </table> </div> </div> </div></body></html>Output:Supported Browsers:Google ChromeMicrosoft EdgeFirefoxOperaSafariYou’ll learn more of Bootstrap stuff in the next article. Keep Learning!Article By Harshit Gupta: Kolkata based Harshit Gupta is an active blogger having keen interest in writing about current affairs, technical Blogs, stories, and personal life experiences. Besides passionate about writing, he also loves coding and dancing. Currently studying at IIEST, he is an active blog contributor at geeksforgeeks.If you also wish to showcase your blog here,please see GBlog for guest blog writing on GeeksforGeeks. My Personal Notes arrow_drop_upSave For creating tables, we need the <table> tag within which we use <tr> tag to define each row and <td>/<th> tag to represent actual data cell. In the table tag we can add different classes attributed to them which can make our table look better. Some of the table classes would be table-striped, table-bordered, table-hover, table-condensed, etc. You can find all the table classes here. The basic structure of the table is : <table class="table-striped"> <tr> <td>First Column</td> <td>Second Column</td> <td>Third Column</td> </tr> </table> You can also add different colours to each row of the table using the colour in the <tr> tag like <tr class=”danger”> </tr> Similarly, you can also add colours to each cell by including the class of colours in the <td> tag.Example: html <!DOCTYPE html><html lang="en"><head> <title>Bootstrap Example</title> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.0/css/bootstrap.min.css"> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.0/jquery.min.js"></script> <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.0/js/bootstrap.min.js"></script></head><body> <div class="container" style="color:green"> <h1>GeeksforGeeks</h1> </div> <div class="container"> <h4>Tables using Bootstrap</h4> <hr><hr> <div class="container"> <div class="bg bg-success"> <table class="table table-hover"> <tr class="danger"> <td>First Column</td> <td>Second Column</td> <td>Third Column</td> </tr> <tr class="info"> <td>Python</td> <td>Java</td> <td>Swift</td> </tr> <tr class="danger"> <td>HTML</td> <td>CSS</td> <td>JavaScript</td> </tr> <tr class="info"> <td>MySql</td> <td>MongoDB</td> <td>SQL lit</td> </tr> </table> </div> </div> </div></body></html> Supported Browsers: Google Chrome Microsoft Edge Firefox Opera Safari You’ll learn more of Bootstrap stuff in the next article. Keep Learning! Article By Harshit Gupta: Kolkata based Harshit Gupta is an active blogger having keen interest in writing about current affairs, technical Blogs, stories, and personal life experiences. Besides passionate about writing, he also loves coding and dancing. Currently studying at IIEST, he is an active blog contributor at geeksforgeeks. If you also wish to showcase your blog here,please see GBlog for guest blog writing on GeeksforGeeks. Akanksha_Rai ysachin2314 Web technologies Bootstrap Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to change navigation bar color in Bootstrap ? Form validation using jQuery How to pass data into a bootstrap modal? How to align navbar items to the right in Bootstrap 4 ? How to Show Images on Click using HTML ? How to set Bootstrap Timepicker using datetimepicker library ? How to align button to right side of text box in Bootstrap? How to Use Bootstrap with React? Difference between Bootstrap 4 and Bootstrap 5 How to change the background color of the active nav-item?
[ { "code": null, "e": 29725, "s": 29697, "text": "\n12 Jan, 2022" }, { "code": null, "e": 29867, "s": 29725, "text": "Introduction and InstallationGrid SystemVertical Forms, Horizontal Forms, Inline FormsDropDowns and Responsive TabsProgress Bar and Jumbotron" }, { "code": null, "e": 29897, "s": 29867, "text": "Introduction and Installation" }, { "code": null, "e": 29909, "s": 29897, "text": "Grid System" }, { "code": null, "e": 29956, "s": 29909, "text": "Vertical Forms, Horizontal Forms, Inline Forms" }, { "code": null, "e": 29986, "s": 29956, "text": "DropDowns and Responsive Tabs" }, { "code": null, "e": 30013, "s": 29986, "text": "Progress Bar and Jumbotron" }, { "code": null, "e": 30191, "s": 30013, "text": "After the previous article, one should be familiar with the Grid System of Bootstrap. Now, we’ll learn about making Buttons, the all new Glyphicons and Tables. Lets get started." }, { "code": null, "e": 30345, "s": 30191, "text": "We can make Buttons in Bootstrap in two ways ( or more specifically, using two tags ). Firstly, with the <a> tag and secondly by using the <button> tag." }, { "code": null, "e": 30512, "s": 30345, "text": " <a href=\"https://www.geeksforgeeks.org\"class=\"btn btn-danger\">\nButton with'a'tag </a>\n<button type=\"button\" class=\"btn btn-info\" >Button with 'button' tag </button>\n" }, { "code": null, "e": 30741, "s": 30512, "text": "We can have Buttons in different colours using Bootstrap. Each having a specific name like btn-default, btn-primary, btn-success, btn-info, btn-warning, btn-danger and btn-link. All of them represent a specific colour of button." }, { "code": null, "e": 30845, "s": 30741, "text": "We can also make buttons of different sizes ( by using btn-lg, btn-sm, btn-xs and btn-block attributes)" }, { "code": null, "e": 32216, "s": 30845, "text": "<a href=” “>Button with <a> tag </a>Example:htmlhtml<!DOCTYPE html><html lang=\"en\"><head> <title>Bootstrap Example</title> <meta charset=\"utf-8\"> <meta name=\"viewport\" content=\"width=device-width, initial-scale=1\"> <link rel=\"stylesheet\" href=\"https://maxcdn.bootstrapcdn.com/bootstrap/3.4.0/css/bootstrap.min.css\"> <script src=\"https://ajax.googleapis.com/ajax/libs/jquery/3.4.0/jquery.min.js\"></script> <script src=\"https://maxcdn.bootstrapcdn.com/bootstrap/3.4.0/js/bootstrap.min.js\"></script></head><body> <div class=\"container\" style=\"color:green\"> <h1>GeeksforGeeks</h1> </div><div class=\"container\"> <h2>Button Styles</h2> <button type=\"button\" class=\"btn\">Basic</button> <button type=\"button\" class=\"btn btn-default\">Default</button> <button type=\"button\" class=\"btn btn-primary\">Primary</button> <button type=\"button\" class=\"btn btn-success\">Success</button> <button type=\"button\" class=\"btn btn-info\">Info</button> <button type=\"button\" class=\"btn btn-warning\">Warning</button> <button type=\"button\" class=\"btn btn-danger\">Danger</button></div><br> <div class=\"container\"> <h4>Button with <a> and <button> tag</h4> <a href=\"https://ide.geeksforgeeks.org/tryit.php\"class=\"btn btn-danger\"> Button with <a> tag </a> <button type=\"button\" class=\"btn btn-success\">Button with <button> tag </button> </div> </body></html>Output:" }, { "code": null, "e": 32221, "s": 32216, "text": "html" }, { "code": "<!DOCTYPE html><html lang=\"en\"><head> <title>Bootstrap Example</title> <meta charset=\"utf-8\"> <meta name=\"viewport\" content=\"width=device-width, initial-scale=1\"> <link rel=\"stylesheet\" href=\"https://maxcdn.bootstrapcdn.com/bootstrap/3.4.0/css/bootstrap.min.css\"> <script src=\"https://ajax.googleapis.com/ajax/libs/jquery/3.4.0/jquery.min.js\"></script> <script src=\"https://maxcdn.bootstrapcdn.com/bootstrap/3.4.0/js/bootstrap.min.js\"></script></head><body> <div class=\"container\" style=\"color:green\"> <h1>GeeksforGeeks</h1> </div><div class=\"container\"> <h2>Button Styles</h2> <button type=\"button\" class=\"btn\">Basic</button> <button type=\"button\" class=\"btn btn-default\">Default</button> <button type=\"button\" class=\"btn btn-primary\">Primary</button> <button type=\"button\" class=\"btn btn-success\">Success</button> <button type=\"button\" class=\"btn btn-info\">Info</button> <button type=\"button\" class=\"btn btn-warning\">Warning</button> <button type=\"button\" class=\"btn btn-danger\">Danger</button></div><br> <div class=\"container\"> <h4>Button with <a> and <button> tag</h4> <a href=\"https://ide.geeksforgeeks.org/tryit.php\"class=\"btn btn-danger\"> Button with <a> tag </a> <button type=\"button\" class=\"btn btn-success\">Button with <button> tag </button> </div> </body></html>", "e": 33533, "s": 32221, "text": null }, { "code": null, "e": 33541, "s": 33533, "text": "Output:" }, { "code": null, "e": 35759, "s": 33541, "text": "Gorgeous Glyphicons:Glyphicons is a library of precisely prepared monochromatic icons and symbols, created with an emphasis to simplicity and easy orientation. We can use Glyphicons inside the span tag like this:<span class=\"Name of the glyphicon\"> </span>Glyphicons can also be used within buttons like this:<a href=\"\" class=\"btn btn-default\"><span class=\"Name of the glyphicon\"> </span> </a>One can see all the glyphicons available at http://getbootstrap.com/components for free. You can copy their names and paste within the quotes class=”Paste here”. If you need more specific glyphicon you can visit http://glyphicons.com/ and buy them.Example:htmlhtml<!DOCTYPE html><html lang=\"en\"><head> <title>Bootstrap Example</title> <meta charset=\"utf-8\"> <meta name=\"viewport\" content=\"width=device-width, initial-scale=1\"> <link rel=\"stylesheet\" href=\"https://maxcdn.bootstrapcdn.com/bootstrap/3.4.0/css/bootstrap.min.css\"> <script src=\"https://ajax.googleapis.com/ajax/libs/jquery/3.4.0/jquery.min.js\"></script> <script src=\"https://maxcdn.bootstrapcdn.com/bootstrap/3.4.0/js/bootstrap.min.js\"></script></head><body> <div class=\"container\" style=\"color:green\"> <h1>GeeksforGeeks</h1> </div> <div class=\"container\"> <p>Correct<span class=\"glyphicon glyphicon-ok\"></span></p> <p>Incorrect<span class=\"glyphicon glyphicon-remove\"></span></p> <h4>Glyphicon with buttons</h4> <a href=\"https://www.geeksforgeeks.org\"class=\"btn btn-primary\"> <span class=\"glyphicon glyphicon-backward\"></span> </a> <a href=\"https://www.geeksforgeeks.org\"class=\"btn btn-danger\"> <span class=\"glyphicon glyphicon-pause\"></span> </a> <a href=\"https://www.geeksforgeeks.org\"class=\"btn btn-success\"> <span class=\"glyphicon glyphicon-play\"></span> </a> <a href=\"https://www.geeksforgeeks.org\"class=\"btn btn-primary\"> <span class=\"glyphicon glyphicon-forward\"></span> </a> </div> <br> <div class=\"container\"> <a href=\"https://www.geeksforgeeks.org\"class=\"btn btn-primary\"> <span class=\"glyphicon glyphicon-thumbs-up\"></span>Like Button </a> </div></body></html>Output:" }, { "code": null, "e": 35952, "s": 35759, "text": "Glyphicons is a library of precisely prepared monochromatic icons and symbols, created with an emphasis to simplicity and easy orientation. We can use Glyphicons inside the span tag like this:" }, { "code": null, "e": 35997, "s": 35952, "text": "<span class=\"Name of the glyphicon\"> </span>" }, { "code": null, "e": 36051, "s": 35997, "text": "Glyphicons can also be used within buttons like this:" }, { "code": null, "e": 36136, "s": 36051, "text": "<a href=\"\" class=\"btn btn-default\"><span class=\"Name of the glyphicon\"> </span> </a>" }, { "code": null, "e": 36386, "s": 36136, "text": "One can see all the glyphicons available at http://getbootstrap.com/components for free. You can copy their names and paste within the quotes class=”Paste here”. If you need more specific glyphicon you can visit http://glyphicons.com/ and buy them." }, { "code": null, "e": 36395, "s": 36386, "text": "Example:" }, { "code": null, "e": 36400, "s": 36395, "text": "html" }, { "code": "<!DOCTYPE html><html lang=\"en\"><head> <title>Bootstrap Example</title> <meta charset=\"utf-8\"> <meta name=\"viewport\" content=\"width=device-width, initial-scale=1\"> <link rel=\"stylesheet\" href=\"https://maxcdn.bootstrapcdn.com/bootstrap/3.4.0/css/bootstrap.min.css\"> <script src=\"https://ajax.googleapis.com/ajax/libs/jquery/3.4.0/jquery.min.js\"></script> <script src=\"https://maxcdn.bootstrapcdn.com/bootstrap/3.4.0/js/bootstrap.min.js\"></script></head><body> <div class=\"container\" style=\"color:green\"> <h1>GeeksforGeeks</h1> </div> <div class=\"container\"> <p>Correct<span class=\"glyphicon glyphicon-ok\"></span></p> <p>Incorrect<span class=\"glyphicon glyphicon-remove\"></span></p> <h4>Glyphicon with buttons</h4> <a href=\"https://www.geeksforgeeks.org\"class=\"btn btn-primary\"> <span class=\"glyphicon glyphicon-backward\"></span> </a> <a href=\"https://www.geeksforgeeks.org\"class=\"btn btn-danger\"> <span class=\"glyphicon glyphicon-pause\"></span> </a> <a href=\"https://www.geeksforgeeks.org\"class=\"btn btn-success\"> <span class=\"glyphicon glyphicon-play\"></span> </a> <a href=\"https://www.geeksforgeeks.org\"class=\"btn btn-primary\"> <span class=\"glyphicon glyphicon-forward\"></span> </a> </div> <br> <div class=\"container\"> <a href=\"https://www.geeksforgeeks.org\"class=\"btn btn-primary\"> <span class=\"glyphicon glyphicon-thumbs-up\"></span>Like Button </a> </div></body></html>", "e": 37953, "s": 36400, "text": null }, { "code": null, "e": 40903, "s": 37953, "text": "Tantalizing Tables:For creating tables, we need the <table> tag within which we use <tr> tag to define each row and <td>/<th> tag to represent actual data cell. In the table tag we can add different classes attributed to them which can make our table look better. Some of the table classes would be table-striped, table-bordered, table-hover, table-condensed, etc. You can find all the table classes here. The basic structure of the table is :<table class=\"table-striped\">\n <tr>\n <td>First Column</td>\n <td>Second Column</td>\n <td>Third Column</td>\n </tr>\n</table>\nYou can also add different colours to each row of the table using the colour in the<tr> tag like <tr class=”danger”> </tr>Similarly, you can also add colours to each cell by including the class of colours in the <td> tag.Example:htmlhtml<!DOCTYPE html><html lang=\"en\"><head> <title>Bootstrap Example</title> <meta charset=\"utf-8\"> <meta name=\"viewport\" content=\"width=device-width, initial-scale=1\"> <link rel=\"stylesheet\" href=\"https://maxcdn.bootstrapcdn.com/bootstrap/3.4.0/css/bootstrap.min.css\"> <script src=\"https://ajax.googleapis.com/ajax/libs/jquery/3.4.0/jquery.min.js\"></script> <script src=\"https://maxcdn.bootstrapcdn.com/bootstrap/3.4.0/js/bootstrap.min.js\"></script></head><body> <div class=\"container\" style=\"color:green\"> <h1>GeeksforGeeks</h1> </div> <div class=\"container\"> <h4>Tables using Bootstrap</h4> <hr><hr> <div class=\"container\"> <div class=\"bg bg-success\"> <table class=\"table table-hover\"> <tr class=\"danger\"> <td>First Column</td> <td>Second Column</td> <td>Third Column</td> </tr> <tr class=\"info\"> <td>Python</td> <td>Java</td> <td>Swift</td> </tr> <tr class=\"danger\"> <td>HTML</td> <td>CSS</td> <td>JavaScript</td> </tr> <tr class=\"info\"> <td>MySql</td> <td>MongoDB</td> <td>SQL lit</td> </tr> </table> </div> </div> </div></body></html>Output:Supported Browsers:Google ChromeMicrosoft EdgeFirefoxOperaSafariYou’ll learn more of Bootstrap stuff in the next article. Keep Learning!Article By Harshit Gupta: Kolkata based Harshit Gupta is an active blogger having keen interest in writing about current affairs, technical Blogs, stories, and personal life experiences. Besides passionate about writing, he also loves coding and dancing. Currently studying at IIEST, he is an active blog contributor at geeksforgeeks.If you also wish to showcase your blog here,please see GBlog for guest blog writing on GeeksforGeeks. My Personal Notes\narrow_drop_upSave" }, { "code": null, "e": 41328, "s": 40903, "text": "For creating tables, we need the <table> tag within which we use <tr> tag to define each row and <td>/<th> tag to represent actual data cell. In the table tag we can add different classes attributed to them which can make our table look better. Some of the table classes would be table-striped, table-bordered, table-hover, table-condensed, etc. You can find all the table classes here. The basic structure of the table is :" }, { "code": null, "e": 41470, "s": 41328, "text": "<table class=\"table-striped\">\n <tr>\n <td>First Column</td>\n <td>Second Column</td>\n <td>Third Column</td>\n </tr>\n</table>\n" }, { "code": null, "e": 41554, "s": 41470, "text": "You can also add different colours to each row of the table using the colour in the" }, { "code": null, "e": 41594, "s": 41554, "text": "<tr> tag like <tr class=”danger”> </tr>" }, { "code": null, "e": 41702, "s": 41594, "text": "Similarly, you can also add colours to each cell by including the class of colours in the <td> tag.Example:" }, { "code": null, "e": 41707, "s": 41702, "text": "html" }, { "code": "<!DOCTYPE html><html lang=\"en\"><head> <title>Bootstrap Example</title> <meta charset=\"utf-8\"> <meta name=\"viewport\" content=\"width=device-width, initial-scale=1\"> <link rel=\"stylesheet\" href=\"https://maxcdn.bootstrapcdn.com/bootstrap/3.4.0/css/bootstrap.min.css\"> <script src=\"https://ajax.googleapis.com/ajax/libs/jquery/3.4.0/jquery.min.js\"></script> <script src=\"https://maxcdn.bootstrapcdn.com/bootstrap/3.4.0/js/bootstrap.min.js\"></script></head><body> <div class=\"container\" style=\"color:green\"> <h1>GeeksforGeeks</h1> </div> <div class=\"container\"> <h4>Tables using Bootstrap</h4> <hr><hr> <div class=\"container\"> <div class=\"bg bg-success\"> <table class=\"table table-hover\"> <tr class=\"danger\"> <td>First Column</td> <td>Second Column</td> <td>Third Column</td> </tr> <tr class=\"info\"> <td>Python</td> <td>Java</td> <td>Swift</td> </tr> <tr class=\"danger\"> <td>HTML</td> <td>CSS</td> <td>JavaScript</td> </tr> <tr class=\"info\"> <td>MySql</td> <td>MongoDB</td> <td>SQL lit</td> </tr> </table> </div> </div> </div></body></html>", "e": 43221, "s": 41707, "text": null }, { "code": null, "e": 43241, "s": 43221, "text": "Supported Browsers:" }, { "code": null, "e": 43255, "s": 43241, "text": "Google Chrome" }, { "code": null, "e": 43270, "s": 43255, "text": "Microsoft Edge" }, { "code": null, "e": 43278, "s": 43270, "text": "Firefox" }, { "code": null, "e": 43284, "s": 43278, "text": "Opera" }, { "code": null, "e": 43291, "s": 43284, "text": "Safari" }, { "code": null, "e": 43364, "s": 43291, "text": "You’ll learn more of Bootstrap stuff in the next article. Keep Learning!" }, { "code": null, "e": 43699, "s": 43364, "text": "Article By Harshit Gupta: Kolkata based Harshit Gupta is an active blogger having keen interest in writing about current affairs, technical Blogs, stories, and personal life experiences. Besides passionate about writing, he also loves coding and dancing. Currently studying at IIEST, he is an active blog contributor at geeksforgeeks." }, { "code": null, "e": 43801, "s": 43699, "text": "If you also wish to showcase your blog here,please see GBlog for guest blog writing on GeeksforGeeks." }, { "code": null, "e": 43818, "s": 43805, "text": "Akanksha_Rai" }, { "code": null, "e": 43830, "s": 43818, "text": "ysachin2314" }, { "code": null, "e": 43847, "s": 43830, "text": "Web technologies" }, { "code": null, "e": 43857, "s": 43847, "text": "Bootstrap" }, { "code": null, "e": 43955, "s": 43857, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 44005, "s": 43955, "text": "How to change navigation bar color in Bootstrap ?" }, { "code": null, "e": 44034, "s": 44005, "text": "Form validation using jQuery" }, { "code": null, "e": 44075, "s": 44034, "text": "How to pass data into a bootstrap modal?" }, { "code": null, "e": 44131, "s": 44075, "text": "How to align navbar items to the right in Bootstrap 4 ?" }, { "code": null, "e": 44172, "s": 44131, "text": "How to Show Images on Click using HTML ?" }, { "code": null, "e": 44235, "s": 44172, "text": "How to set Bootstrap Timepicker using datetimepicker library ?" }, { "code": null, "e": 44295, "s": 44235, "text": "How to align button to right side of text box in Bootstrap?" }, { "code": null, "e": 44328, "s": 44295, "text": "How to Use Bootstrap with React?" }, { "code": null, "e": 44375, "s": 44328, "text": "Difference between Bootstrap 4 and Bootstrap 5" } ]
Print a given matrix in spiral form - GeeksforGeeks
27 Apr, 2022 Given a 2D array, print it in spiral form. See the following examples. Examples: Input: {{1, 2, 3, 4}, {5, 6, 7, 8}, {9, 10, 11, 12}, {13, 14, 15, 16 }}Output: 1 2 3 4 8 12 16 15 14 13 9 5 6 7 11 10 Explanation: The output is matrix in spiral format. Input: { {1, 2, 3, 4, 5, 6}, {7, 8, 9, 10, 11, 12}, {13, 14, 15, 16, 17, 18}} Output: 1 2 3 4 5 6 12 18 17 16 15 14 13 7 8 9 10 11Explanation :The output is matrix in spiral format. 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. Best Optimized Method 1: (Simulation Approach) Intuition: Draw the path that the spiral makes. We know that the path should turn clockwise whenever it would go out of bounds or into a cell that was previously visited. Algorithm: Let the array have R rows and C columns. seen[r] denotes that the cell on the r-th row and c-th column was previously visited. Our current position is (r, c), facing direction di, and we want to visit R x C total cells. As we move through the matrix, our candidate’s next position is (cr, cc). If the candidate is in the bounds of the matrix and unseen, then it becomes our next position; otherwise, our next position is the one after performing a clockwise turn. C++ Java Python3 C# Javascript #include <bits/stdc++.h>using namespace std; vector<int> spiralOrder(vector<vector<int>> &matrix){ vector<int> ans; if (matrix.size() == 0) return ans; int R = matrix.size(), C = matrix[0].size(); vector<vector<bool>> seen(R, vector<bool>(C, false)); int dr[] = {0, 1, 0, -1}; int dc[] = {1, 0, -1, 0}; int r = 0, c = 0, di = 0; // Iterate from 0 to R * C - 1 for (int i = 0; i < R * C; i++) { ans.push_back(matrix[r]); seen[r] = true; int cr = r + dr[di]; int cc = c + dc[di]; if (0 <= cr && cr < R && 0 <= cc && cc < C && !seen[cr][cc]) { r = cr; c = cc; } else { di = (di + 1) % 4; r += dr[di]; c += dc[di]; } } return ans;} // Driver codeint main(){ vector<vector<int>> a{{1, 2, 3, 4}, {5, 6, 7, 8}, {9, 10, 11, 12}, {13, 14, 15, 16}}; for (int x : spiralOrder(a)) { cout << x << " "; } return 0;} // This code is contributed by Yashvendra Singh // Java program for the above approachimport java.util.*; class Solution { // Function to print in spiral order public static List<Integer> spiralOrder(int[][] matrix) { List<Integer> ans = new ArrayList<Integer>(); if (matrix.length == 0) return ans; int R = matrix.length, C = matrix[0].length; boolean[][] seen = new boolean[R][C]; int[] dr = { 0, 1, 0, -1 }; int[] dc = { 1, 0, -1, 0 }; int r = 0, c = 0, di = 0; // Iterate from 0 to R * C - 1 for (int i = 0; i < R * C; i++) { ans.add(matrix[r]); seen[r] = true; int cr = r + dr[di]; int cc = c + dc[di]; if (0 <= cr && cr < R && 0 <= cc && cc < C && !seen[cr][cc]) { r = cr; c = cc; } else { di = (di + 1) % 4; r += dr[di]; c += dc[di]; } } return ans; } // Driver Code public static void main(String[] args) { int a[][] = { { 1, 2, 3, 4 }, { 5, 6, 7, 8 }, { 9, 10, 11, 12 }, { 13, 14, 15, 16 } }; System.out.println(spiralOrder(a)); }} def spiralOrder(matrix): ans = [] if (len(matrix) == 0): return ans R = len(matrix) C = len(matrix[0]) seen = [[0 for i in range(C)] for j in range(R)] dr = [0, 1, 0, -1] dc = [1, 0, -1, 0] r = 0 c = 0 di = 0 # Iterate from 0 to R * C - 1 for i in range(R * C): ans.append(matrix[r]) seen[r] = True cr = r + dr[di] cc = c + dc[di] if (0 <= cr and cr < R and 0 <= cc and cc < C and not(seen[cr][cc])): r = cr c = cc else: di = (di + 1) % 4 r += dr[di] c += dc[di] return ans # Driver codea = [[1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12], [13, 14, 15, 16]] for x in spiralOrder(a): print(x, end=" ")print() // C# program for the above approachusing System;using System.Collections.Generic; public class GFG { // Function to print in spiral order public static List<int> spiralOrder(int[,] matrix) { List<int> ans = new List<int>(); if (matrix.Length == 0) return ans; int R = matrix.GetLength(0), C = matrix.GetLength(1); bool[,] seen = new bool[R,C]; int[] dr = { 0, 1, 0, -1 }; int[] dc = { 1, 0, -1, 0 }; int r = 0, c = 0, di = 0; // Iterate from 0 to R * C - 1 for (int i = 0; i < R * C; i++) { ans.Add(matrix[r,c]); seen[r,c] = true; int cr = r + dr[di]; int cc = c + dc[di]; if (0 <= cr && cr < R && 0 <= cc && cc < C && !seen[cr,cc]) { r = cr; c = cc; } else { di = (di + 1) % 4; r += dr[di]; c += dc[di]; } } return ans; } // Driver Code public static void Main(String[] args) { int[,]a = { { 1, 2, 3, 4 }, { 5, 6, 7, 8 }, { 9, 10, 11, 12 }, { 13, 14, 15, 16 } }; spiralOrder(a).ForEach(i=>Console.Write(i+" ")); }} // This code is contributed by 29AjayKumar <script> // JavaScript program for the above approach // Function to print in spiral orderfunction spiralOrder(matrix){ let ans = []; if (matrix.length == 0) return ans; let R = matrix.length, C = matrix[0].length; let seen = new Array(R); for(let i=0;i<R;i++) { seen[i]=new Array(C); for(let j=0;j<C;j++) { seen[i][j]=false; } } let dr = [ 0, 1, 0, -1 ]; let dc = [ 1, 0, -1, 0 ]; let r = 0, c = 0, di = 0; // Iterate from 0 to R * C - 1 for (let i = 0; i < R * C; i++) { ans.push(matrix[r]); seen[r] = true; let cr = r + dr[di]; let cc = c + dc[di]; if (0 <= cr && cr < R && 0 <= cc && cc < C && !seen[cr][cc]) { r = cr; c = cc; } else { di = (di + 1) % 4; r += dr[di]; c += dc[di]; } } return ans;} // Driver Codelet a=[[ 1, 2, 3, 4 ],[ 5, 6, 7, 8 ],[ 9, 10, 11, 12 ],[ 13, 14, 15, 16 ]];document.write(spiralOrder(a)); // This code is contributed by unknown2108 </script> 1 2 3 4 8 12 16 15 14 13 9 5 6 7 11 10 Complexity Analysis: Time Complexity: O(N), where N is the total number of elements in the input matrix. We add every element in the matrix to our final answer. Auxiliary Space: O(N), the information stored in seen and in ans. Method 2: This is a simple method to solve the following problem. Approach: The problem can be solved by dividing the matrix into loops or squares or boundaries. It can be seen that the elements of the outer loop are printed first in a clockwise manner then the elements of the inner loop is printed. So printing the elements of a loop can be solved using four loops which prints all the elements. Every ‘for’ loop defines a single direction movement along with the matrix. The first for loop represents the movement from left to right, whereas the second crawl represents the movement from top to bottom, the third represents the movement from the right to left, and the fourth represents the movement from bottom to up. Algorithm: Create and initialize variables k – starting row index, m – ending row index, l – starting column index, n – ending column indexRun a loop until all the squares of loops are printed.In each outer loop traversal print the elements of a square in a clockwise manner.Print the top row, i.e. Print the elements of the kth row from column index l to n, and increase the count of k.Print the right column, i.e. Print the last column or n-1th column from row index k to m and decrease the count of n.Print the bottom row, i.e. if k < m, then print the elements of m-1th row from column n-1 to l and decrease the count of mPrint the left column, i.e. if l < n, then print the elements of lth column from m-1th row to k and increase the count of l. Create and initialize variables k – starting row index, m – ending row index, l – starting column index, n – ending column indexRun a loop until all the squares of loops are printed.In each outer loop traversal print the elements of a square in a clockwise manner.Print the top row, i.e. Print the elements of the kth row from column index l to n, and increase the count of k.Print the right column, i.e. Print the last column or n-1th column from row index k to m and decrease the count of n.Print the bottom row, i.e. if k < m, then print the elements of m-1th row from column n-1 to l and decrease the count of mPrint the left column, i.e. if l < n, then print the elements of lth column from m-1th row to k and increase the count of l. Create and initialize variables k – starting row index, m – ending row index, l – starting column index, n – ending column index Run a loop until all the squares of loops are printed. In each outer loop traversal print the elements of a square in a clockwise manner. Print the top row, i.e. Print the elements of the kth row from column index l to n, and increase the count of k. Print the right column, i.e. Print the last column or n-1th column from row index k to m and decrease the count of n. Print the bottom row, i.e. if k < m, then print the elements of m-1th row from column n-1 to l and decrease the count of m Print the left column, i.e. if l < n, then print the elements of lth column from m-1th row to k and increase the count of l. Below is the implementation of the above algorithm: C++ C Java Python3 C# PHP Javascript // C++ Program to print a matrix spirally #include <bits/stdc++.h>using namespace std;#define R 4#define C 4 void spiralPrint(int m, int n, int a[R][C]){ int i, k = 0, l = 0; /* k - starting row index m - ending row index l - starting column index n - ending column index i - iterator */ while (k < m && l < n) { /* Print the first row from the remaining rows */ for (i = l; i < n; ++i) { cout << a[k][i] << " "; } k++; /* Print the last column from the remaining columns */ for (i = k; i < m; ++i) { cout << a[i][n - 1] << " "; } n--; /* Print the last row from the remaining rows */ if (k < m) { for (i = n - 1; i >= l; --i) { cout << a[m - 1][i] << " "; } m--; } /* Print the first column from the remaining columns */ if (l < n) { for (i = m - 1; i >= k; --i) { cout << a[i][l] << " "; } l++; } }} /* Driver Code */int main(){ int a[R][C] = {{1, 2, 3, 4}, {5, 6, 7, 8}, {9, 10, 11, 12}, {13, 14, 15, 16}}; // Function Call spiralPrint(R, C, a); return 0;} // This is code is contributed by rathbhupendra // C program to print the array in a// spiral form #include <stdio.h>#define R 4#define C 4 void spiralPrint(int m, int n, int a[R][C]){ int i, k = 0, l = 0; /* k - starting row index m - ending row index l - starting column index n - ending column index i - iterator */ while (k < m && l < n) { /* Print the first row from the remaining rows */ for (i = l; i < n; ++i) { printf("%d ", a[k][i]); } k++; /* Print the last column from the remaining columns */ for (i = k; i < m; ++i) { printf("%d ", a[i][n - 1]); } n--; /* Print the last row from the remaining rows */ if (k < m) { for (i = n - 1; i >= l; --i) { printf("%d ", a[m - 1][i]); } m--; } /* Print the first column from the remaining columns */ if (l < n) { for (i = m - 1; i >= k; --i) { printf("%d ", a[i][l]); } l++; } }} /* Driver Code */int main(){ int a[R][C] = {{1, 2, 3, 4}, {5, 6, 7, 8}, {9, 10, 11, 12}, {13, 14, 15, 16}}; // Function Call spiralPrint(R, C, a); return 0;} // Java program to print a given matrix in spiral formimport java.io.*; class GFG { // Function print matrix in spiral form static void spiralPrint(int m, int n, int a[][]) { int i, k = 0, l = 0; /* k - starting row index m - ending row index l - starting column index n - ending column index i - iterator */ while (k < m && l < n) { // Print the first row from the remaining rows for (i = l; i < n; ++i) { System.out.print(a[k][i] + " "); } k++; // Print the last column from the remaining // columns for (i = k; i < m; ++i) { System.out.print(a[i][n - 1] + " "); } n--; // Print the last row from the remaining rows */ if (k < m) { for (i = n - 1; i >= l; --i) { System.out.print(a[m - 1][i] + " "); } m--; } // Print the first column from the remaining // columns */ if (l < n) { for (i = m - 1; i >= k; --i) { System.out.print(a[i][l] + " "); } l++; } } } // Driver Code public static void main(String[] args) { int R = 4; int C = 4; int a[][] = {{1, 2, 3, 4}, {5, 6, 7, 8}, {9, 10, 11, 12}, {13, 14, 15, 16}}; // Function Call spiralPrint(R, C, a); }} // Contributed by Pramod Kumar # Python3 program to print# given matrix in spiral form def spiralPrint(m, n, a): k = 0 l = 0 ''' k - starting row index m - ending row index l - starting column index n - ending column index i - iterator ''' while (k < m and l < n): # Print the first row from # the remaining rows for i in range(l, n): print(a[k][i], end=" ") k += 1 # Print the last column from # the remaining columns for i in range(k, m): print(a[i][n - 1], end=" ") n -= 1 # Print the last row from # the remaining rows if (k < m): for i in range(n - 1, (l - 1), -1): print(a[m - 1][i], end=" ") m -= 1 # Print the first column from # the remaining columns if (l < n): for i in range(m - 1, k - 1, -1): print(a[i][l], end=" ") l += 1 # Driver Codea = [[ 1, 2, 3, 4 ], [ 5, 6, 7, 8 ], [ 9, 10, 11, 12 ], [ 13, 14, 15, 16 ]] R = 4C = 4 # Function CallspiralPrint(R, C, a) # This code is contributed by Nikita Tiwari. // C# program to print a given// matrix in spiral formusing System; class GFG { // Function print matrix in spiral form static void spiralPrint(int m, int n, int[, ] a) { int i, k = 0, l = 0; /* k - starting row index m - ending row index l - starting column index n - ending column index i - iterator */ while (k < m && l < n) { // Print the first row // from the remaining rows for (i = l; i < n; ++i) { Console.Write(a[k, i] + " "); } k++; // Print the last column from the // remaining columns for (i = k; i < m; ++i) { Console.Write(a[i, n - 1] + " "); } n--; // Print the last row from // the remaining rows if (k < m) { for (i = n - 1; i >= l; --i) { Console.Write(a[m - 1, i] + " "); } m--; } // Print the first column from // the remaining columns if (l < n) { for (i = m - 1; i >= k; --i) { Console.Write(a[i, l] + " "); } l++; } } } // Driver Code public static void Main() { int R = 4; int C = 4; int[, ] a = {{1, 2, 3, 4}, {5, 6, 7, 8}, {9, 10, 11, 12}, {13, 14, 15, 16}}; // Function Call spiralPrint(R, C, a); }} // This code is contributed by Sam007 <?php// PHP program to print a given// matrix in spiral form$R = 4;$C = 4; function spiralPrint($m, $n, &$a){ $k = 0; $l = 0; /* $k - starting row index $m - ending row index $l - starting column index $n - ending column index $i - iterator */ while ($k < $m && $l < $n) { /* Print the first row from the remaining rows */ for ($i = $l; $i < $n; ++$i) { echo $a[$k][$i] . " "; } $k++; /* Print the last column from the remaining columns */ for ($i = $k; $i < $m; ++$i) { echo $a[$i][$n - 1] . " "; } $n--; /* Print the last row from the remaining rows */ if ($k < $m) { for ($i = $n - 1; $i >= $l; --$i) { echo $a[$m - 1][$i] . " "; } $m--; } /* Print the first column from the remaining columns */ if ($l < $n) { for ($i = $m - 1; $i >= $k; --$i) { echo $a[$i][$l] . " "; } $l++; } }} // Driver code$a = array(array(1, 2, 3, 4), array(5, 6, 7, 8), array(9, 10, 11, 12), array(13, 14, 15, 16));// Function CallspiralPrint($R, $C, $a); // This code is contributed// by ChitraNayal?> <script> // JavaScript Program to print a matrix spirally function spiralPrint(m, n, arr) { let i, k = 0, l = 0; /* k - starting row index m - ending row index l - starting column index n - ending column index i - iterator */ while (k < m && l < n) { // print the first row from the remaining rows for (i = l; i < n; ++i) { document.write(arr[k][i] + ' '); } k++; // print the last column from the remaining columns for (i = k; i < m; ++i) { document.write(arr[i][n - 1] + ' '); } n--; // print the last row from the remaining rows if (k < m) { for (i = n - 1; i >= l; --i) { document.write(arr[m - 1][i] + ' '); } m--; } // print the first column from the remaining columns if (l < n) { for (i = m - 1; i >= k; --i) { document.write(arr[i][l] + ' '); } l++; } }} // function calllet arr = [[ 1, 2, 3, 4 ], [ 5, 6, 7, 8 ], [ 9, 10, 11, 12 ], [ 13, 14, 15, 16 ]];let r = arr.length;let c = arr[0].length; spiralPrint(r, c, arr); // This code is contributed by karthiksrinivasprasad </script> 1 2 3 4 5 6 12 18 17 16 15 14 13 7 8 9 10 11 Complexity Analysis: Time Complexity: O(m*n). To traverse the matrix O(m*n) time is required. Auxiliary Space: O(1). No extra space is required. Method 3: (Recursive Approach) Approach: The above problem can be solved by printing the boundary of the Matrix recursively. In each recursive call, we decrease the dimensions of the matrix. The idea of printing the boundary or loops is the same. Algorithm: create a recursive function that takes a matrix and some variables (k – starting row index, m – ending row index, l – starting column index, n – ending column index) as parametersCheck the base cases (starting index is less than or equal to ending index) and print the boundary elements in clockwise mannerPrint the top row, i.e. Print the elements of kth row from column index l to n, and increase the count of k.Print the right column, i.e. Print the last column or n-1th column from row index k to m and decrease the count of n.Print the bottom row, i.e. if k > m, then print the elements of m-1th row from column n-1 to l and decrease the count of mPrint the left column, i.e. if l < n, then print the elements of lth column from m-1th row to k and increase the count of l.Call the function recursively with the values of starting and ending indices of rows and columns. create a recursive function that takes a matrix and some variables (k – starting row index, m – ending row index, l – starting column index, n – ending column index) as parametersCheck the base cases (starting index is less than or equal to ending index) and print the boundary elements in clockwise mannerPrint the top row, i.e. Print the elements of kth row from column index l to n, and increase the count of k.Print the right column, i.e. Print the last column or n-1th column from row index k to m and decrease the count of n.Print the bottom row, i.e. if k > m, then print the elements of m-1th row from column n-1 to l and decrease the count of mPrint the left column, i.e. if l < n, then print the elements of lth column from m-1th row to k and increase the count of l.Call the function recursively with the values of starting and ending indices of rows and columns. create a recursive function that takes a matrix and some variables (k – starting row index, m – ending row index, l – starting column index, n – ending column index) as parameters Check the base cases (starting index is less than or equal to ending index) and print the boundary elements in clockwise manner Print the top row, i.e. Print the elements of kth row from column index l to n, and increase the count of k. Print the right column, i.e. Print the last column or n-1th column from row index k to m and decrease the count of n. Print the bottom row, i.e. if k > m, then print the elements of m-1th row from column n-1 to l and decrease the count of m Print the left column, i.e. if l < n, then print the elements of lth column from m-1th row to k and increase the count of l. Call the function recursively with the values of starting and ending indices of rows and columns. Below is the implementation of the above algorithm: C++ Java Python3 C# Javascript // C++. program for the above approach#include <iostream>using namespace std; #define R 4#define C 4 // Function for printing matrix in spiral// form i, j: Start index of matrix, row// and column respectively m, n: End index// of matrix row and column respectivelyvoid print(int arr[R][C], int i, int j, int m, int n){ // If i or j lies outside the matrix if (i >= m or j >= n) return; // Print First Row for (int p = j; p < n; p++) cout << arr[i][p] << " "; // Print Last Column for (int p = i + 1; p < m; p++) cout << arr[p][n - 1] << " "; // Print Last Row, if Last and // First Row are not same if ((m - 1) != i) for (int p = n - 2; p >= j; p--) cout << arr[m - 1][p] << " "; // Print First Column, if Last and // First Column are not same if ((n - 1) != j) for (int p = m - 2; p > i; p--) cout << arr[p][j] << " "; print(arr, i + 1, j + 1, m - 1, n - 1);} // Driver Codeint main(){ int a[R][C] = { { 1, 2, 3, 4 }, { 5, 6, 7, 8 }, { 9, 10, 11, 12 }, { 13, 14, 15, 16 } }; // Function Call print(a, 0, 0, R, C); return 0;}// This Code is contributed by Ankur Goel // Java program for the above approachimport java.util.*; class GFG { static int R = 4; static int C = 4; // Function for printing matrix in spiral // form i, j: Start index of matrix, row // and column respectively m, n: End index // of matrix row and column respectively static void print(int arr[][], int i, int j, int m, int n) { // If i or j lies outside the matrix if (i >= m || j >= n) { return; } // Print First Row for (int p = i; p < n; p++) { System.out.print(arr[i][p] + " "); } // Print Last Column for (int p = i + 1; p < m; p++) { System.out.print(arr[p][n - 1] + " "); } // Print Last Row, if Last and // First Row are not same if ((m - 1) != i) { for (int p = n - 2; p >= j; p--) { System.out.print(arr[m - 1][p] + " "); } } // Print First Column, if Last and // First Column are not same if ((n - 1) != j) { for (int p = m - 2; p > i; p--) { System.out.print(arr[p][j] + " "); } } print(arr, i + 1, j + 1, m - 1, n - 1); } // Driver Code public static void main(String[] args) { int a[][] = { { 1, 2, 3, 4 }, { 5, 6, 7, 8 }, { 9, 10, 11, 12 }, { 13, 14, 15, 16 } }; // Function Call print(a, 0, 0, R, C); }} // This code is contributed by 29AjayKumar # Python3 program for the above approach # Function for printing matrix in spiral# form i, j: Start index of matrix, row# and column respectively m, n: End index# of matrix row and column respectively def printdata(arr, i, j, m, n): # If i or j lies outside the matrix if (i >= m or j >= n): return # Print First Row for p in range(i, n): print(arr[i][p], end=" ") # Print Last Column for p in range(i + 1, m): print(arr[p][n - 1], end=" ") # Print Last Row, if Last and # First Row are not same if ((m - 1) != i): for p in range(n - 2, j - 1, -1): print(arr[m - 1][p], end=" ") # Print First Column, if Last and # First Column are not same if ((n - 1) != j): for p in range(m - 2, i, -1): print(arr[p][j], end=" ") printdata(arr, i + 1, j + 1, m - 1, n - 1) # Driver codeR = 4C = 4arr = [[1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12], [13, 14, 15, 16]] # Function Callprintdata(arr, 0, 0, R, C) # This code is contributed by avsadityavardhan // C# program for the above approachusing System; class GFG { static int R = 4; static int C = 4; // Function for printing matrix in spiral // form i, j: Start index of matrix, row // and column respectively m, n: End index // of matrix row and column respectively static void print(int[, ] arr, int i, int j, int m, int n) { // If i or j lies outside the matrix if (i >= m || j >= n) { return; } // Print First Row for (int p = i; p < n; p++) { Console.Write(arr[i, p] + " "); } // Print Last Column for (int p = i + 1; p < m; p++) { Console.Write(arr[p, n - 1] + " "); } // Print Last Row, if Last and // First Row are not same if ((m - 1) != i) { for (int p = n - 2; p >= j; p--) { Console.Write(arr[m - 1, p] + " "); } } // Print First Column, if Last and // First Column are not same if ((n - 1) != j) { for (int p = m - 2; p > i; p--) { Console.Write(arr[p, j] + " "); } } print(arr, i + 1, j + 1, m - 1, n - 1); } // Driver Code public static void Main(String[] args) { int[, ] a = { { 1, 2, 3, 4 }, { 5, 6, 7, 8 }, { 9, 10, 11, 12 }, { 13, 14, 15, 16 } }; // Function Call print(a, 0, 0, R, C); }} // This code is contributed by Princi Singh <script>// JavaScript program for the above approach // Function for printing matrix in spiral// form i, j: Start index of matrix, row// and column respectively m, n: End index// of matrix row and column respectively function print(arr, i, j, m, n) { // If i or j lies outside the matrix if (i >= m || j >= n) return; // Print First Row for (let p = j; p < n; p++) { document.write(arr[i][p] + ' ') } // Print Last Column for (let p = i + 1; p < m; p++) { document.write(arr[p][n - 1] + ' ') } // Print Last Row, if Last and // First Row are not same if ((m - 1) != i) { for (let p = n - 2; p >= j; p--) { document.write(arr[m - 1][p] + ' '); } } // Print First Column, if Last and // First Column are not same if ((n - 1) != j) { for (let p = m - 2; p > i; p--) { document.write(arr[p][j] + ' '); } } print(arr, i + 1, j + 1, m - 1, n - 1)} // function calllet arr = [ [1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12], [13, 14, 15, 16] ];let r = arr.length;let c = arr[0].length; print(arr, 0, 0, r, c); // This code is contributed by karthiksrinivasprasad </script> 1 2 3 4 8 12 16 15 14 13 9 5 6 7 11 10 Complexity Analysis: Time Complexity: O(m*n). To traverse the matrix O(m*n) time is required. Auxiliary Space: O(1). No extra space is required. Method 4: (DFS Recursive Approach) Approach: Another recursive approach is to consider DFS movement within the matrix (right->down->left->up->right->..->end). We do this by modifying the matrix itself such that when DFS algorithm visits each matrix cell it’s changed to a value which cannot be contained within the matrix. The DFS algorithm is terminated when it visits a cell such that all of its surrounding cells are already visited. The direction of the DFS search is controlled by a variable. Algorithm: create a DFS function which takes matrix, cell indices and directioncheck are cell indices pointing to a valid cell (that is, not visited and in bounds)? if not, skip this cellprint cell valuemark matrix cell pointed by indicates as visited by changing it to a value not supported in the matrixcheck are surrounding cells valid? if not stop algorithm, else continueif direction given is right then check, is the cell to the right valid? if so, DFS to the right cell given the steps above, else, change the direction to down and DFS downwards given the steps above.else, if the direction given is down then check, is the cell to the down valid? if so, DFS to the cell below given the steps above, else, change the direction to left and DFS leftwards given the steps above.else, if the direction given is left then check, is the cell to the left valid? if so, DFS to the left cell given the steps above, else, change the direction to up and DFS upwards given the steps above.else, if the direction given is up then check, is the cell to the up valid? if so, DFS to the upper cell given the steps above, else, change the direction to right and DFS rightwards given the steps above. create a DFS function which takes matrix, cell indices and direction check are cell indices pointing to a valid cell (that is, not visited and in bounds)? if not, skip this cell print cell value mark matrix cell pointed by indicates as visited by changing it to a value not supported in the matrix check are surrounding cells valid? if not stop algorithm, else continue if direction given is right then check, is the cell to the right valid? if so, DFS to the right cell given the steps above, else, change the direction to down and DFS downwards given the steps above. else, if the direction given is down then check, is the cell to the down valid? if so, DFS to the cell below given the steps above, else, change the direction to left and DFS leftwards given the steps above. else, if the direction given is left then check, is the cell to the left valid? if so, DFS to the left cell given the steps above, else, change the direction to up and DFS upwards given the steps above. else, if the direction given is up then check, is the cell to the up valid? if so, DFS to the upper cell given the steps above, else, change the direction to right and DFS rightwards given the steps above. Below is an implementation of this algorithm: C++ Java Python3 C# Javascript #include <iostream>#include <vector>using namespace std;#define R 4#define C 4 bool isInBounds(int i, int j){ if (i < 0 || i >= R || j < 0 || j >= C) return false; return true;} // check if the position is blockedbool isBlocked(int matrix[R][C], int i, int j){ if (!isInBounds(i, j)) return true; if (matrix[i][j] == -1) return true; return false;} // DFS code to traverse spirallyvoid spirallyDFSTravserse(int matrix[R][C], int i, int j, int dir, vector<int>& res){ if (isBlocked(matrix, i, j)) return; bool allBlocked = true; for (int k = -1; k <= 1; k += 2) { allBlocked = allBlocked && isBlocked(matrix, k + i, j) && isBlocked(matrix, i, j + k); } res.push_back(matrix[i][j]); matrix[i][j] = -1; if (allBlocked) { return; } // dir: 0 - right, 1 - down, 2 - left, 3 - up int nxt_i = i; int nxt_j = j; int nxt_dir = dir; if (dir == 0) { if (!isBlocked(matrix, i, j + 1)) { nxt_j++; } else { nxt_dir = 1; nxt_i++; } } else if (dir == 1) { if (!isBlocked(matrix, i + 1, j)) { nxt_i++; } else { nxt_dir = 2; nxt_j--; } } else if (dir == 2) { if (!isBlocked(matrix, i, j - 1)) { nxt_j--; } else { nxt_dir = 3; nxt_i--; } } else if (dir == 3) { if (!isBlocked(matrix, i - 1, j)) { nxt_i--; } else { nxt_dir = 0; nxt_j++; } } spirallyDFSTravserse(matrix, nxt_i, nxt_j, nxt_dir, res);} // to traverse spirallyvector<int> spirallyTraverse(int matrix[R][C]){ vector<int> res; spirallyDFSTravserse(matrix, 0, 0, 0, res); return res;} // Driver Codeint main(){ int a[R][C] = { { 1, 2, 3, 4 }, { 5, 6, 7, 8 }, { 9, 10, 11, 12 }, { 13, 14, 15, 16 } }; // Function Call vector<int> res = spirallyTraverse(a); int size = res.size(); for (int i = 0; i < size; ++i) cout << res[i] << " "; cout << endl; return 0;} // code contributed by Ephi F import java.io.*;import java.util.*; class GFG { public static int R = 4, C = 4; public static boolean isInBounds(int i, int j) { if (i < 0 || i >= R || j < 0 || j >= C) return false; return true; } // check if the position is blocked public static boolean isBlocked(int[][] matrix, int i, int j) { if (!isInBounds(i, j)) return true; if (matrix[i][j] == -1) return true; return false; } // DFS code to traverse spirally public static void spirallyDFSTravserse(int[][] matrix, int i, int j, int dir, ArrayList<Integer> res) { if (isBlocked(matrix, i, j)) return; boolean allBlocked = true; for (int k = -1; k <= 1; k += 2) { allBlocked = allBlocked && isBlocked(matrix, k + i, j) && isBlocked(matrix, i, j + k); } res.add(matrix[i][j]); matrix[i][j] = -1; if (allBlocked) { return; } // dir: 0 - right, 1 - down, 2 - left, 3 - up int nxt_i = i; int nxt_j = j; int nxt_dir = dir; if (dir == 0) { if (!isBlocked(matrix, i, j + 1)) { nxt_j++; } else { nxt_dir = 1; nxt_i++; } } else if (dir == 1) { if (!isBlocked(matrix, i + 1, j)) { nxt_i++; } else { nxt_dir = 2; nxt_j--; } } else if (dir == 2) { if (!isBlocked(matrix, i, j - 1)) { nxt_j--; } else { nxt_dir = 3; nxt_i--; } } else if (dir == 3) { if (!isBlocked(matrix, i - 1, j)) { nxt_i--; } else { nxt_dir = 0; nxt_j++; } } spirallyDFSTravserse(matrix, nxt_i, nxt_j, nxt_dir, res); } // to traverse spirally public static ArrayList<Integer> spirallyTraverse(int[][] matrix) { ArrayList<Integer> res = new ArrayList<Integer>(); spirallyDFSTravserse(matrix, 0, 0, 0, res); return res; } // Driver code public static void main(String[] args) { int a[][] = { { 1, 2, 3, 4 }, { 5, 6, 7, 8 }, { 9, 10, 11, 12 }, { 13, 14, 15, 16 } }; // Function Call ArrayList<Integer> res = spirallyTraverse(a); int size = res.size(); for (int i = 0; i < size; ++i) System.out.print(res.get(i) + " "); System.out.println(); }} // This code is contributed by Manu Pathria R = 4C = 4 def isInBounds(i, j): global R global C if (i < 0 or i >= R or j < 0 or j >= C): return False return True # Check if the position is blocked def isBlocked(matrix, i, j): if (not isInBounds(i, j)): return True if (matrix[i][j] == -1): return True return False # DFS code to traverse spirally def spirallyDFSTravserse(matrix, i, j, Dir, res): if (isBlocked(matrix, i, j)): return allBlocked = True for k in range(-1, 2, 2): allBlocked = allBlocked and isBlocked( matrix, k + i, j) and isBlocked(matrix, i, j + k) res.append(matrix[i][j]) matrix[i][j] = -1 if (allBlocked): return # dir: 0 - right, 1 - down, 2 - left, 3 - up nxt_i = i nxt_j = j nxt_dir = Dir if (Dir == 0): if (not isBlocked(matrix, i, j + 1)): nxt_j += 1 else: nxt_dir = 1 nxt_i += 1 elif(Dir == 1): if (not isBlocked(matrix, i + 1, j)): nxt_i += 1 else: nxt_dir = 2 nxt_j -= 1 elif(Dir == 2): if (not isBlocked(matrix, i, j - 1)): nxt_j -= 1 else: nxt_dir = 3 nxt_i -= 1 elif(Dir == 3): if (not isBlocked(matrix, i - 1, j)): nxt_i -= 1 else: nxt_dir = 0 nxt_j += 1 spirallyDFSTravserse(matrix, nxt_i, nxt_j, nxt_dir, res) # To traverse spirally def spirallyTraverse(matrix): res = [] spirallyDFSTravserse(matrix, 0, 0, 0, res) return res # Driver codea = [[1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12], [13, 14, 15, 16]] # Function Callres = spirallyTraverse(a)print(*res) # This code is contributed by rag2127 using System;using System.Collections.Generic; class GFG { public static int R = 4, C = 4; public static bool isInBounds(int i, int j) { if (i < 0 || i >= R || j < 0 || j >= C) return false; return true; } // Check if the position is blocked public static bool isBlocked(int[, ] matrix, int i, int j) { if (!isInBounds(i, j)) return true; if (matrix[i, j] == -1) return true; return false; } // DFS code to traverse spirally public static void spirallyDFSTravserse(int[, ] matrix, int i, int j, int dir, List<int> res) { if (isBlocked(matrix, i, j)) return; bool allBlocked = true; for (int k = -1; k <= 1; k += 2) { allBlocked = allBlocked && isBlocked(matrix, k + i, j) && isBlocked(matrix, i, j + k); } res.Add(matrix[i, j]); matrix[i, j] = -1; if (allBlocked) { return; } // dir: 0 - right, 1 - down, 2 - left, 3 - up int nxt_i = i; int nxt_j = j; int nxt_dir = dir; if (dir == 0) { if (!isBlocked(matrix, i, j + 1)) { nxt_j++; } else { nxt_dir = 1; nxt_i++; } } else if (dir == 1) { if (!isBlocked(matrix, i + 1, j)) { nxt_i++; } else { nxt_dir = 2; nxt_j--; } } else if (dir == 2) { if (!isBlocked(matrix, i, j - 1)) { nxt_j--; } else { nxt_dir = 3; nxt_i--; } } else if (dir == 3) { if (!isBlocked(matrix, i - 1, j)) { nxt_i--; } else { nxt_dir = 0; nxt_j++; } } spirallyDFSTravserse(matrix, nxt_i, nxt_j, nxt_dir, res); } // To traverse spirally public static List<int> spirallyTraverse(int[, ] matrix) { List<int> res = new List<int>(); spirallyDFSTravserse(matrix, 0, 0, 0, res); return res; } // Driver code static public void Main() { int[, ] a = { { 1, 2, 3, 4 }, { 5, 6, 7, 8 }, { 9, 10, 11, 12 }, { 13, 14, 15, 16 } }; // Function Call List<int> res = spirallyTraverse(a); int size = res.Count; for (int i = 0; i < size; ++i) Console.Write(res[i] + " "); Console.WriteLine(); }} // This code is contributed by avanitrachhadiya2155 <script> var R = 4, C = 4;function isInBounds(i, j){ if (i < 0 || i >= R || j < 0 || j >= C) return false; return true;}// Check if the position is blockedfunction isBlocked(matrix, i, j){ if (!isInBounds(i, j)) return true; if (matrix[i][j] == -1) return true; return false;}// DFS code to traverse spirallyfunction spirallyDFSTravserse(matrix, i, j, dir, res){ if (isBlocked(matrix, i, j)) return; var allBlocked = true; for (var k = -1; k <= 1; k += 2) { allBlocked = allBlocked && isBlocked(matrix, k + i, j) && isBlocked(matrix, i, j + k); } res.push(matrix[i][j]); matrix[i][j] = -1; if (allBlocked) { return; } // dir: 0 - right, 1 - down, 2 - left, 3 - up var nxt_i = i; var nxt_j = j; var nxt_dir = dir; if (dir == 0) { if (!isBlocked(matrix, i, j + 1)) { nxt_j++; } else { nxt_dir = 1; nxt_i++; } } else if (dir == 1) { if (!isBlocked(matrix, i + 1, j)) { nxt_i++; } else { nxt_dir = 2; nxt_j--; } } else if (dir == 2) { if (!isBlocked(matrix, i, j - 1)) { nxt_j--; } else { nxt_dir = 3; nxt_i--; } } else if (dir == 3) { if (!isBlocked(matrix, i - 1, j)) { nxt_i--; } else { nxt_dir = 0; nxt_j++; } } spirallyDFSTravserse(matrix, nxt_i, nxt_j, nxt_dir, res);}// To traverse spirallyfunction spirallyTraverse(matrix){ var res = []; spirallyDFSTravserse(matrix, 0, 0, 0, res); return res;}// Driver codevar a = [ [ 1, 2, 3, 4 ], [ 5, 6, 7, 8 ], [ 9, 10, 11, 12 ], [ 13, 14, 15, 16 ]];// Function Callvar res = spirallyTraverse(a);var size = res.length;for (var i = 0; i < size; ++i) document.write(res[i] + " "); </script> 1 2 3 4 8 12 16 15 14 13 9 5 6 7 11 10 Complexity Analysis: Time Complexity: O(m*n). To traverse the matrix O(m*n) time is required.Auxiliary Space: O(1). No extra space is required (without consideration of the stack used by the recursion). Diagonal traversal of Matrix Print matrix in antispiral form Print a given matrix in zigzag form Please write comments if you find the above code incorrect, or find other ways to solve the same problem. ukasp rathbhupendra Ankur Goel 29AjayKumar princi singh andrew1234 avsadityavardhan harshvardhansingh17 ephi2g theadinova swaroopksahu manupathria avanitrachhadiya2155 karthiksrinivasprasad rag2127 koulick_sadhu rohitsingh07052 yashvendrasengar1111 sonirudrakshi99 itsok unknown2108 sagartomar9927 animeshbarun rohithp8899 sumitgumber28 nikhil070g harendrakumar123 Accolite Amazon Amazon-Question BrowserStack D-E-Shaw MakeMyTrip MAQ Software Microsoft Morgan Stanley Nagarro nearbuy Oracle pattern-printing Paytm Snapdeal Snapdeal-Question spiral Zoho Arrays Matrix School Programming Paytm Zoho Morgan Stanley Accolite Amazon Microsoft Snapdeal D-E-Shaw MakeMyTrip Oracle MAQ Software nearbuy Nagarro BrowserStack Arrays pattern-printing Matrix Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Arrays in Java Arrays in C/C++ Write a program to reverse an array or string Program for array rotation Largest Sum Contiguous Subarray Matrix Chain Multiplication | DP-8 Program to find largest element in an array Rat in a Maze | Backtracking-2 Maximum size square sub-matrix with all 1s Sudoku | Backtracking-7
[ { "code": null, "e": 42521, "s": 42493, "text": "\n27 Apr, 2022" }, { "code": null, "e": 42592, "s": 42521, "text": "Given a 2D array, print it in spiral form. See the following examples." }, { "code": null, "e": 42603, "s": 42592, "text": "Examples: " }, { "code": null, "e": 42832, "s": 42603, "text": "Input: {{1, 2, 3, 4}, {5, 6, 7, 8}, {9, 10, 11, 12}, {13, 14, 15, 16 }}Output: 1 2 3 4 8 12 16 15 14 13 9 5 6 7 11 10 Explanation: The output is matrix in spiral format. " }, { "code": null, "e": 42949, "s": 42832, "text": "Input: { {1, 2, 3, 4, 5, 6}, {7, 8, 9, 10, 11, 12}, {13, 14, 15, 16, 17, 18}}" }, { "code": null, "e": 43053, "s": 42949, "text": "Output: 1 2 3 4 5 6 12 18 17 16 15 14 13 7 8 9 10 11Explanation :The output is matrix in spiral format." }, { "code": null, "e": 43062, "s": 43053, "text": "Chapters" }, { "code": null, "e": 43089, "s": 43062, "text": "descriptions off, selected" }, { "code": null, "e": 43139, "s": 43089, "text": "captions settings, opens captions settings dialog" }, { "code": null, "e": 43162, "s": 43139, "text": "captions off, selected" }, { "code": null, "e": 43170, "s": 43162, "text": "English" }, { "code": null, "e": 43194, "s": 43170, "text": "This is a modal window." }, { "code": null, "e": 43263, "s": 43194, "text": "Beginning of dialog window. Escape will cancel and close the window." }, { "code": null, "e": 43285, "s": 43263, "text": "End of dialog window." }, { "code": null, "e": 43332, "s": 43285, "text": "Best Optimized Method 1: (Simulation Approach)" }, { "code": null, "e": 43343, "s": 43332, "text": "Intuition:" }, { "code": null, "e": 43503, "s": 43343, "text": "Draw the path that the spiral makes. We know that the path should turn clockwise whenever it would go out of bounds or into a cell that was previously visited." }, { "code": null, "e": 43514, "s": 43503, "text": "Algorithm:" }, { "code": null, "e": 43734, "s": 43514, "text": "Let the array have R rows and C columns. seen[r] denotes that the cell on the r-th row and c-th column was previously visited. Our current position is (r, c), facing direction di, and we want to visit R x C total cells." }, { "code": null, "e": 43978, "s": 43734, "text": "As we move through the matrix, our candidate’s next position is (cr, cc). If the candidate is in the bounds of the matrix and unseen, then it becomes our next position; otherwise, our next position is the one after performing a clockwise turn." }, { "code": null, "e": 43982, "s": 43978, "text": "C++" }, { "code": null, "e": 43987, "s": 43982, "text": "Java" }, { "code": null, "e": 43995, "s": 43987, "text": "Python3" }, { "code": null, "e": 43998, "s": 43995, "text": "C#" }, { "code": null, "e": 44009, "s": 43998, "text": "Javascript" }, { "code": "#include <bits/stdc++.h>using namespace std; vector<int> spiralOrder(vector<vector<int>> &matrix){ vector<int> ans; if (matrix.size() == 0) return ans; int R = matrix.size(), C = matrix[0].size(); vector<vector<bool>> seen(R, vector<bool>(C, false)); int dr[] = {0, 1, 0, -1}; int dc[] = {1, 0, -1, 0}; int r = 0, c = 0, di = 0; // Iterate from 0 to R * C - 1 for (int i = 0; i < R * C; i++) { ans.push_back(matrix[r]); seen[r] = true; int cr = r + dr[di]; int cc = c + dc[di]; if (0 <= cr && cr < R && 0 <= cc && cc < C && !seen[cr][cc]) { r = cr; c = cc; } else { di = (di + 1) % 4; r += dr[di]; c += dc[di]; } } return ans;} // Driver codeint main(){ vector<vector<int>> a{{1, 2, 3, 4}, {5, 6, 7, 8}, {9, 10, 11, 12}, {13, 14, 15, 16}}; for (int x : spiralOrder(a)) { cout << x << \" \"; } return 0;} // This code is contributed by Yashvendra Singh", "e": 45129, "s": 44009, "text": null }, { "code": "// Java program for the above approachimport java.util.*; class Solution { // Function to print in spiral order public static List<Integer> spiralOrder(int[][] matrix) { List<Integer> ans = new ArrayList<Integer>(); if (matrix.length == 0) return ans; int R = matrix.length, C = matrix[0].length; boolean[][] seen = new boolean[R][C]; int[] dr = { 0, 1, 0, -1 }; int[] dc = { 1, 0, -1, 0 }; int r = 0, c = 0, di = 0; // Iterate from 0 to R * C - 1 for (int i = 0; i < R * C; i++) { ans.add(matrix[r]); seen[r] = true; int cr = r + dr[di]; int cc = c + dc[di]; if (0 <= cr && cr < R && 0 <= cc && cc < C && !seen[cr][cc]) { r = cr; c = cc; } else { di = (di + 1) % 4; r += dr[di]; c += dc[di]; } } return ans; } // Driver Code public static void main(String[] args) { int a[][] = { { 1, 2, 3, 4 }, { 5, 6, 7, 8 }, { 9, 10, 11, 12 }, { 13, 14, 15, 16 } }; System.out.println(spiralOrder(a)); }}", "e": 46365, "s": 45129, "text": null }, { "code": "def spiralOrder(matrix): ans = [] if (len(matrix) == 0): return ans R = len(matrix) C = len(matrix[0]) seen = [[0 for i in range(C)] for j in range(R)] dr = [0, 1, 0, -1] dc = [1, 0, -1, 0] r = 0 c = 0 di = 0 # Iterate from 0 to R * C - 1 for i in range(R * C): ans.append(matrix[r]) seen[r] = True cr = r + dr[di] cc = c + dc[di] if (0 <= cr and cr < R and 0 <= cc and cc < C and not(seen[cr][cc])): r = cr c = cc else: di = (di + 1) % 4 r += dr[di] c += dc[di] return ans # Driver codea = [[1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12], [13, 14, 15, 16]] for x in spiralOrder(a): print(x, end=\" \")print()", "e": 47133, "s": 46365, "text": null }, { "code": "// C# program for the above approachusing System;using System.Collections.Generic; public class GFG { // Function to print in spiral order public static List<int> spiralOrder(int[,] matrix) { List<int> ans = new List<int>(); if (matrix.Length == 0) return ans; int R = matrix.GetLength(0), C = matrix.GetLength(1); bool[,] seen = new bool[R,C]; int[] dr = { 0, 1, 0, -1 }; int[] dc = { 1, 0, -1, 0 }; int r = 0, c = 0, di = 0; // Iterate from 0 to R * C - 1 for (int i = 0; i < R * C; i++) { ans.Add(matrix[r,c]); seen[r,c] = true; int cr = r + dr[di]; int cc = c + dc[di]; if (0 <= cr && cr < R && 0 <= cc && cc < C && !seen[cr,cc]) { r = cr; c = cc; } else { di = (di + 1) % 4; r += dr[di]; c += dc[di]; } } return ans; } // Driver Code public static void Main(String[] args) { int[,]a = { { 1, 2, 3, 4 }, { 5, 6, 7, 8 }, { 9, 10, 11, 12 }, { 13, 14, 15, 16 } }; spiralOrder(a).ForEach(i=>Console.Write(i+\" \")); }} // This code is contributed by 29AjayKumar", "e": 48467, "s": 47133, "text": null }, { "code": "<script> // JavaScript program for the above approach // Function to print in spiral orderfunction spiralOrder(matrix){ let ans = []; if (matrix.length == 0) return ans; let R = matrix.length, C = matrix[0].length; let seen = new Array(R); for(let i=0;i<R;i++) { seen[i]=new Array(C); for(let j=0;j<C;j++) { seen[i][j]=false; } } let dr = [ 0, 1, 0, -1 ]; let dc = [ 1, 0, -1, 0 ]; let r = 0, c = 0, di = 0; // Iterate from 0 to R * C - 1 for (let i = 0; i < R * C; i++) { ans.push(matrix[r]); seen[r] = true; let cr = r + dr[di]; let cc = c + dc[di]; if (0 <= cr && cr < R && 0 <= cc && cc < C && !seen[cr][cc]) { r = cr; c = cc; } else { di = (di + 1) % 4; r += dr[di]; c += dc[di]; } } return ans;} // Driver Codelet a=[[ 1, 2, 3, 4 ],[ 5, 6, 7, 8 ],[ 9, 10, 11, 12 ],[ 13, 14, 15, 16 ]];document.write(spiralOrder(a)); // This code is contributed by unknown2108 </script>", "e": 49726, "s": 48467, "text": null }, { "code": null, "e": 49766, "s": 49726, "text": "1 2 3 4 8 12 16 15 14 13 9 5 6 7 11 10 " }, { "code": null, "e": 49787, "s": 49766, "text": "Complexity Analysis:" }, { "code": null, "e": 49927, "s": 49787, "text": "Time Complexity: O(N), where N is the total number of elements in the input matrix. We add every element in the matrix to our final answer." }, { "code": null, "e": 49993, "s": 49927, "text": "Auxiliary Space: O(N), the information stored in seen and in ans." }, { "code": null, "e": 50060, "s": 49993, "text": "Method 2: This is a simple method to solve the following problem. " }, { "code": null, "e": 50716, "s": 50060, "text": "Approach: The problem can be solved by dividing the matrix into loops or squares or boundaries. It can be seen that the elements of the outer loop are printed first in a clockwise manner then the elements of the inner loop is printed. So printing the elements of a loop can be solved using four loops which prints all the elements. Every ‘for’ loop defines a single direction movement along with the matrix. The first for loop represents the movement from left to right, whereas the second crawl represents the movement from top to bottom, the third represents the movement from the right to left, and the fourth represents the movement from bottom to up." }, { "code": null, "e": 51467, "s": 50716, "text": "Algorithm: Create and initialize variables k – starting row index, m – ending row index, l – starting column index, n – ending column indexRun a loop until all the squares of loops are printed.In each outer loop traversal print the elements of a square in a clockwise manner.Print the top row, i.e. Print the elements of the kth row from column index l to n, and increase the count of k.Print the right column, i.e. Print the last column or n-1th column from row index k to m and decrease the count of n.Print the bottom row, i.e. if k < m, then print the elements of m-1th row from column n-1 to l and decrease the count of mPrint the left column, i.e. if l < n, then print the elements of lth column from m-1th row to k and increase the count of l." }, { "code": null, "e": 52207, "s": 51467, "text": "Create and initialize variables k – starting row index, m – ending row index, l – starting column index, n – ending column indexRun a loop until all the squares of loops are printed.In each outer loop traversal print the elements of a square in a clockwise manner.Print the top row, i.e. Print the elements of the kth row from column index l to n, and increase the count of k.Print the right column, i.e. Print the last column or n-1th column from row index k to m and decrease the count of n.Print the bottom row, i.e. if k < m, then print the elements of m-1th row from column n-1 to l and decrease the count of mPrint the left column, i.e. if l < n, then print the elements of lth column from m-1th row to k and increase the count of l." }, { "code": null, "e": 52336, "s": 52207, "text": "Create and initialize variables k – starting row index, m – ending row index, l – starting column index, n – ending column index" }, { "code": null, "e": 52391, "s": 52336, "text": "Run a loop until all the squares of loops are printed." }, { "code": null, "e": 52474, "s": 52391, "text": "In each outer loop traversal print the elements of a square in a clockwise manner." }, { "code": null, "e": 52587, "s": 52474, "text": "Print the top row, i.e. Print the elements of the kth row from column index l to n, and increase the count of k." }, { "code": null, "e": 52705, "s": 52587, "text": "Print the right column, i.e. Print the last column or n-1th column from row index k to m and decrease the count of n." }, { "code": null, "e": 52828, "s": 52705, "text": "Print the bottom row, i.e. if k < m, then print the elements of m-1th row from column n-1 to l and decrease the count of m" }, { "code": null, "e": 52953, "s": 52828, "text": "Print the left column, i.e. if l < n, then print the elements of lth column from m-1th row to k and increase the count of l." }, { "code": null, "e": 53006, "s": 52953, "text": "Below is the implementation of the above algorithm: " }, { "code": null, "e": 53010, "s": 53006, "text": "C++" }, { "code": null, "e": 53012, "s": 53010, "text": "C" }, { "code": null, "e": 53017, "s": 53012, "text": "Java" }, { "code": null, "e": 53025, "s": 53017, "text": "Python3" }, { "code": null, "e": 53028, "s": 53025, "text": "C#" }, { "code": null, "e": 53032, "s": 53028, "text": "PHP" }, { "code": null, "e": 53043, "s": 53032, "text": "Javascript" }, { "code": "// C++ Program to print a matrix spirally #include <bits/stdc++.h>using namespace std;#define R 4#define C 4 void spiralPrint(int m, int n, int a[R][C]){ int i, k = 0, l = 0; /* k - starting row index m - ending row index l - starting column index n - ending column index i - iterator */ while (k < m && l < n) { /* Print the first row from the remaining rows */ for (i = l; i < n; ++i) { cout << a[k][i] << \" \"; } k++; /* Print the last column from the remaining columns */ for (i = k; i < m; ++i) { cout << a[i][n - 1] << \" \"; } n--; /* Print the last row from the remaining rows */ if (k < m) { for (i = n - 1; i >= l; --i) { cout << a[m - 1][i] << \" \"; } m--; } /* Print the first column from the remaining columns */ if (l < n) { for (i = m - 1; i >= k; --i) { cout << a[i][l] << \" \"; } l++; } }} /* Driver Code */int main(){ int a[R][C] = {{1, 2, 3, 4}, {5, 6, 7, 8}, {9, 10, 11, 12}, {13, 14, 15, 16}}; // Function Call spiralPrint(R, C, a); return 0;} // This is code is contributed by rathbhupendra", "e": 54437, "s": 53043, "text": null }, { "code": "// C program to print the array in a// spiral form #include <stdio.h>#define R 4#define C 4 void spiralPrint(int m, int n, int a[R][C]){ int i, k = 0, l = 0; /* k - starting row index m - ending row index l - starting column index n - ending column index i - iterator */ while (k < m && l < n) { /* Print the first row from the remaining rows */ for (i = l; i < n; ++i) { printf(\"%d \", a[k][i]); } k++; /* Print the last column from the remaining columns */ for (i = k; i < m; ++i) { printf(\"%d \", a[i][n - 1]); } n--; /* Print the last row from the remaining rows */ if (k < m) { for (i = n - 1; i >= l; --i) { printf(\"%d \", a[m - 1][i]); } m--; } /* Print the first column from the remaining columns */ if (l < n) { for (i = m - 1; i >= k; --i) { printf(\"%d \", a[i][l]); } l++; } }} /* Driver Code */int main(){ int a[R][C] = {{1, 2, 3, 4}, {5, 6, 7, 8}, {9, 10, 11, 12}, {13, 14, 15, 16}}; // Function Call spiralPrint(R, C, a); return 0;}", "e": 55729, "s": 54437, "text": null }, { "code": "// Java program to print a given matrix in spiral formimport java.io.*; class GFG { // Function print matrix in spiral form static void spiralPrint(int m, int n, int a[][]) { int i, k = 0, l = 0; /* k - starting row index m - ending row index l - starting column index n - ending column index i - iterator */ while (k < m && l < n) { // Print the first row from the remaining rows for (i = l; i < n; ++i) { System.out.print(a[k][i] + \" \"); } k++; // Print the last column from the remaining // columns for (i = k; i < m; ++i) { System.out.print(a[i][n - 1] + \" \"); } n--; // Print the last row from the remaining rows */ if (k < m) { for (i = n - 1; i >= l; --i) { System.out.print(a[m - 1][i] + \" \"); } m--; } // Print the first column from the remaining // columns */ if (l < n) { for (i = m - 1; i >= k; --i) { System.out.print(a[i][l] + \" \"); } l++; } } } // Driver Code public static void main(String[] args) { int R = 4; int C = 4; int a[][] = {{1, 2, 3, 4}, {5, 6, 7, 8}, {9, 10, 11, 12}, {13, 14, 15, 16}}; // Function Call spiralPrint(R, C, a); }} // Contributed by Pramod Kumar", "e": 57337, "s": 55729, "text": null }, { "code": "# Python3 program to print# given matrix in spiral form def spiralPrint(m, n, a): k = 0 l = 0 ''' k - starting row index m - ending row index l - starting column index n - ending column index i - iterator ''' while (k < m and l < n): # Print the first row from # the remaining rows for i in range(l, n): print(a[k][i], end=\" \") k += 1 # Print the last column from # the remaining columns for i in range(k, m): print(a[i][n - 1], end=\" \") n -= 1 # Print the last row from # the remaining rows if (k < m): for i in range(n - 1, (l - 1), -1): print(a[m - 1][i], end=\" \") m -= 1 # Print the first column from # the remaining columns if (l < n): for i in range(m - 1, k - 1, -1): print(a[i][l], end=\" \") l += 1 # Driver Codea = [[ 1, 2, 3, 4 ], [ 5, 6, 7, 8 ], [ 9, 10, 11, 12 ], [ 13, 14, 15, 16 ]] R = 4C = 4 # Function CallspiralPrint(R, C, a) # This code is contributed by Nikita Tiwari.", "e": 58483, "s": 57337, "text": null }, { "code": "// C# program to print a given// matrix in spiral formusing System; class GFG { // Function print matrix in spiral form static void spiralPrint(int m, int n, int[, ] a) { int i, k = 0, l = 0; /* k - starting row index m - ending row index l - starting column index n - ending column index i - iterator */ while (k < m && l < n) { // Print the first row // from the remaining rows for (i = l; i < n; ++i) { Console.Write(a[k, i] + \" \"); } k++; // Print the last column from the // remaining columns for (i = k; i < m; ++i) { Console.Write(a[i, n - 1] + \" \"); } n--; // Print the last row from // the remaining rows if (k < m) { for (i = n - 1; i >= l; --i) { Console.Write(a[m - 1, i] + \" \"); } m--; } // Print the first column from // the remaining columns if (l < n) { for (i = m - 1; i >= k; --i) { Console.Write(a[i, l] + \" \"); } l++; } } } // Driver Code public static void Main() { int R = 4; int C = 4; int[, ] a = {{1, 2, 3, 4}, {5, 6, 7, 8}, {9, 10, 11, 12}, {13, 14, 15, 16}}; // Function Call spiralPrint(R, C, a); }} // This code is contributed by Sam007", "e": 60088, "s": 58483, "text": null }, { "code": "<?php// PHP program to print a given// matrix in spiral form$R = 4;$C = 4; function spiralPrint($m, $n, &$a){ $k = 0; $l = 0; /* $k - starting row index $m - ending row index $l - starting column index $n - ending column index $i - iterator */ while ($k < $m && $l < $n) { /* Print the first row from the remaining rows */ for ($i = $l; $i < $n; ++$i) { echo $a[$k][$i] . \" \"; } $k++; /* Print the last column from the remaining columns */ for ($i = $k; $i < $m; ++$i) { echo $a[$i][$n - 1] . \" \"; } $n--; /* Print the last row from the remaining rows */ if ($k < $m) { for ($i = $n - 1; $i >= $l; --$i) { echo $a[$m - 1][$i] . \" \"; } $m--; } /* Print the first column from the remaining columns */ if ($l < $n) { for ($i = $m - 1; $i >= $k; --$i) { echo $a[$i][$l] . \" \"; } $l++; } }} // Driver code$a = array(array(1, 2, 3, 4), array(5, 6, 7, 8), array(9, 10, 11, 12), array(13, 14, 15, 16));// Function CallspiralPrint($R, $C, $a); // This code is contributed// by ChitraNayal?>", "e": 61461, "s": 60088, "text": null }, { "code": "<script> // JavaScript Program to print a matrix spirally function spiralPrint(m, n, arr) { let i, k = 0, l = 0; /* k - starting row index m - ending row index l - starting column index n - ending column index i - iterator */ while (k < m && l < n) { // print the first row from the remaining rows for (i = l; i < n; ++i) { document.write(arr[k][i] + ' '); } k++; // print the last column from the remaining columns for (i = k; i < m; ++i) { document.write(arr[i][n - 1] + ' '); } n--; // print the last row from the remaining rows if (k < m) { for (i = n - 1; i >= l; --i) { document.write(arr[m - 1][i] + ' '); } m--; } // print the first column from the remaining columns if (l < n) { for (i = m - 1; i >= k; --i) { document.write(arr[i][l] + ' '); } l++; } }} // function calllet arr = [[ 1, 2, 3, 4 ], [ 5, 6, 7, 8 ], [ 9, 10, 11, 12 ], [ 13, 14, 15, 16 ]];let r = arr.length;let c = arr[0].length; spiralPrint(r, c, arr); // This code is contributed by karthiksrinivasprasad </script>", "e": 62735, "s": 61461, "text": null }, { "code": null, "e": 62781, "s": 62735, "text": "1 2 3 4 5 6 12 18 17 16 15 14 13 7 8 9 10 11 " }, { "code": null, "e": 62803, "s": 62781, "text": "Complexity Analysis: " }, { "code": null, "e": 62876, "s": 62803, "text": "Time Complexity: O(m*n). To traverse the matrix O(m*n) time is required." }, { "code": null, "e": 62927, "s": 62876, "text": "Auxiliary Space: O(1). No extra space is required." }, { "code": null, "e": 62958, "s": 62927, "text": "Method 3: (Recursive Approach)" }, { "code": null, "e": 63174, "s": 62958, "text": "Approach: The above problem can be solved by printing the boundary of the Matrix recursively. In each recursive call, we decrease the dimensions of the matrix. The idea of printing the boundary or loops is the same." }, { "code": null, "e": 64060, "s": 63174, "text": "Algorithm: create a recursive function that takes a matrix and some variables (k – starting row index, m – ending row index, l – starting column index, n – ending column index) as parametersCheck the base cases (starting index is less than or equal to ending index) and print the boundary elements in clockwise mannerPrint the top row, i.e. Print the elements of kth row from column index l to n, and increase the count of k.Print the right column, i.e. Print the last column or n-1th column from row index k to m and decrease the count of n.Print the bottom row, i.e. if k > m, then print the elements of m-1th row from column n-1 to l and decrease the count of mPrint the left column, i.e. if l < n, then print the elements of lth column from m-1th row to k and increase the count of l.Call the function recursively with the values of starting and ending indices of rows and columns." }, { "code": null, "e": 64935, "s": 64060, "text": "create a recursive function that takes a matrix and some variables (k – starting row index, m – ending row index, l – starting column index, n – ending column index) as parametersCheck the base cases (starting index is less than or equal to ending index) and print the boundary elements in clockwise mannerPrint the top row, i.e. Print the elements of kth row from column index l to n, and increase the count of k.Print the right column, i.e. Print the last column or n-1th column from row index k to m and decrease the count of n.Print the bottom row, i.e. if k > m, then print the elements of m-1th row from column n-1 to l and decrease the count of mPrint the left column, i.e. if l < n, then print the elements of lth column from m-1th row to k and increase the count of l.Call the function recursively with the values of starting and ending indices of rows and columns." }, { "code": null, "e": 65115, "s": 64935, "text": "create a recursive function that takes a matrix and some variables (k – starting row index, m – ending row index, l – starting column index, n – ending column index) as parameters" }, { "code": null, "e": 65243, "s": 65115, "text": "Check the base cases (starting index is less than or equal to ending index) and print the boundary elements in clockwise manner" }, { "code": null, "e": 65352, "s": 65243, "text": "Print the top row, i.e. Print the elements of kth row from column index l to n, and increase the count of k." }, { "code": null, "e": 65470, "s": 65352, "text": "Print the right column, i.e. Print the last column or n-1th column from row index k to m and decrease the count of n." }, { "code": null, "e": 65593, "s": 65470, "text": "Print the bottom row, i.e. if k > m, then print the elements of m-1th row from column n-1 to l and decrease the count of m" }, { "code": null, "e": 65718, "s": 65593, "text": "Print the left column, i.e. if l < n, then print the elements of lth column from m-1th row to k and increase the count of l." }, { "code": null, "e": 65816, "s": 65718, "text": "Call the function recursively with the values of starting and ending indices of rows and columns." }, { "code": null, "e": 65869, "s": 65816, "text": "Below is the implementation of the above algorithm: " }, { "code": null, "e": 65873, "s": 65869, "text": "C++" }, { "code": null, "e": 65878, "s": 65873, "text": "Java" }, { "code": null, "e": 65886, "s": 65878, "text": "Python3" }, { "code": null, "e": 65889, "s": 65886, "text": "C#" }, { "code": null, "e": 65900, "s": 65889, "text": "Javascript" }, { "code": "// C++. program for the above approach#include <iostream>using namespace std; #define R 4#define C 4 // Function for printing matrix in spiral// form i, j: Start index of matrix, row// and column respectively m, n: End index// of matrix row and column respectivelyvoid print(int arr[R][C], int i, int j, int m, int n){ // If i or j lies outside the matrix if (i >= m or j >= n) return; // Print First Row for (int p = j; p < n; p++) cout << arr[i][p] << \" \"; // Print Last Column for (int p = i + 1; p < m; p++) cout << arr[p][n - 1] << \" \"; // Print Last Row, if Last and // First Row are not same if ((m - 1) != i) for (int p = n - 2; p >= j; p--) cout << arr[m - 1][p] << \" \"; // Print First Column, if Last and // First Column are not same if ((n - 1) != j) for (int p = m - 2; p > i; p--) cout << arr[p][j] << \" \"; print(arr, i + 1, j + 1, m - 1, n - 1);} // Driver Codeint main(){ int a[R][C] = { { 1, 2, 3, 4 }, { 5, 6, 7, 8 }, { 9, 10, 11, 12 }, { 13, 14, 15, 16 } }; // Function Call print(a, 0, 0, R, C); return 0;}// This Code is contributed by Ankur Goel", "e": 67140, "s": 65900, "text": null }, { "code": "// Java program for the above approachimport java.util.*; class GFG { static int R = 4; static int C = 4; // Function for printing matrix in spiral // form i, j: Start index of matrix, row // and column respectively m, n: End index // of matrix row and column respectively static void print(int arr[][], int i, int j, int m, int n) { // If i or j lies outside the matrix if (i >= m || j >= n) { return; } // Print First Row for (int p = i; p < n; p++) { System.out.print(arr[i][p] + \" \"); } // Print Last Column for (int p = i + 1; p < m; p++) { System.out.print(arr[p][n - 1] + \" \"); } // Print Last Row, if Last and // First Row are not same if ((m - 1) != i) { for (int p = n - 2; p >= j; p--) { System.out.print(arr[m - 1][p] + \" \"); } } // Print First Column, if Last and // First Column are not same if ((n - 1) != j) { for (int p = m - 2; p > i; p--) { System.out.print(arr[p][j] + \" \"); } } print(arr, i + 1, j + 1, m - 1, n - 1); } // Driver Code public static void main(String[] args) { int a[][] = { { 1, 2, 3, 4 }, { 5, 6, 7, 8 }, { 9, 10, 11, 12 }, { 13, 14, 15, 16 } }; // Function Call print(a, 0, 0, R, C); }} // This code is contributed by 29AjayKumar", "e": 68693, "s": 67140, "text": null }, { "code": "# Python3 program for the above approach # Function for printing matrix in spiral# form i, j: Start index of matrix, row# and column respectively m, n: End index# of matrix row and column respectively def printdata(arr, i, j, m, n): # If i or j lies outside the matrix if (i >= m or j >= n): return # Print First Row for p in range(i, n): print(arr[i][p], end=\" \") # Print Last Column for p in range(i + 1, m): print(arr[p][n - 1], end=\" \") # Print Last Row, if Last and # First Row are not same if ((m - 1) != i): for p in range(n - 2, j - 1, -1): print(arr[m - 1][p], end=\" \") # Print First Column, if Last and # First Column are not same if ((n - 1) != j): for p in range(m - 2, i, -1): print(arr[p][j], end=\" \") printdata(arr, i + 1, j + 1, m - 1, n - 1) # Driver codeR = 4C = 4arr = [[1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12], [13, 14, 15, 16]] # Function Callprintdata(arr, 0, 0, R, C) # This code is contributed by avsadityavardhan", "e": 69756, "s": 68693, "text": null }, { "code": "// C# program for the above approachusing System; class GFG { static int R = 4; static int C = 4; // Function for printing matrix in spiral // form i, j: Start index of matrix, row // and column respectively m, n: End index // of matrix row and column respectively static void print(int[, ] arr, int i, int j, int m, int n) { // If i or j lies outside the matrix if (i >= m || j >= n) { return; } // Print First Row for (int p = i; p < n; p++) { Console.Write(arr[i, p] + \" \"); } // Print Last Column for (int p = i + 1; p < m; p++) { Console.Write(arr[p, n - 1] + \" \"); } // Print Last Row, if Last and // First Row are not same if ((m - 1) != i) { for (int p = n - 2; p >= j; p--) { Console.Write(arr[m - 1, p] + \" \"); } } // Print First Column, if Last and // First Column are not same if ((n - 1) != j) { for (int p = m - 2; p > i; p--) { Console.Write(arr[p, j] + \" \"); } } print(arr, i + 1, j + 1, m - 1, n - 1); } // Driver Code public static void Main(String[] args) { int[, ] a = { { 1, 2, 3, 4 }, { 5, 6, 7, 8 }, { 9, 10, 11, 12 }, { 13, 14, 15, 16 } }; // Function Call print(a, 0, 0, R, C); }} // This code is contributed by Princi Singh", "e": 71289, "s": 69756, "text": null }, { "code": "<script>// JavaScript program for the above approach // Function for printing matrix in spiral// form i, j: Start index of matrix, row// and column respectively m, n: End index// of matrix row and column respectively function print(arr, i, j, m, n) { // If i or j lies outside the matrix if (i >= m || j >= n) return; // Print First Row for (let p = j; p < n; p++) { document.write(arr[i][p] + ' ') } // Print Last Column for (let p = i + 1; p < m; p++) { document.write(arr[p][n - 1] + ' ') } // Print Last Row, if Last and // First Row are not same if ((m - 1) != i) { for (let p = n - 2; p >= j; p--) { document.write(arr[m - 1][p] + ' '); } } // Print First Column, if Last and // First Column are not same if ((n - 1) != j) { for (let p = m - 2; p > i; p--) { document.write(arr[p][j] + ' '); } } print(arr, i + 1, j + 1, m - 1, n - 1)} // function calllet arr = [ [1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12], [13, 14, 15, 16] ];let r = arr.length;let c = arr[0].length; print(arr, 0, 0, r, c); // This code is contributed by karthiksrinivasprasad </script>", "e": 72518, "s": 71289, "text": null }, { "code": null, "e": 72558, "s": 72518, "text": "1 2 3 4 8 12 16 15 14 13 9 5 6 7 11 10 " }, { "code": null, "e": 72580, "s": 72558, "text": "Complexity Analysis: " }, { "code": null, "e": 72653, "s": 72580, "text": "Time Complexity: O(m*n). To traverse the matrix O(m*n) time is required." }, { "code": null, "e": 72704, "s": 72653, "text": "Auxiliary Space: O(1). No extra space is required." }, { "code": null, "e": 72739, "s": 72704, "text": "Method 4: (DFS Recursive Approach)" }, { "code": null, "e": 72863, "s": 72739, "text": "Approach: Another recursive approach is to consider DFS movement within the matrix (right->down->left->up->right->..->end)." }, { "code": null, "e": 73203, "s": 72863, "text": "We do this by modifying the matrix itself such that when DFS algorithm visits each matrix cell it’s changed to a value which cannot be contained within the matrix. The DFS algorithm is terminated when it visits a cell such that all of its surrounding cells are already visited. The direction of the DFS search is controlled by a variable. " }, { "code": null, "e": 73215, "s": 73203, "text": "Algorithm: " }, { "code": null, "e": 74461, "s": 73215, "text": "create a DFS function which takes matrix, cell indices and directioncheck are cell indices pointing to a valid cell (that is, not visited and in bounds)? if not, skip this cellprint cell valuemark matrix cell pointed by indicates as visited by changing it to a value not supported in the matrixcheck are surrounding cells valid? if not stop algorithm, else continueif direction given is right then check, is the cell to the right valid? if so, DFS to the right cell given the steps above, else, change the direction to down and DFS downwards given the steps above.else, if the direction given is down then check, is the cell to the down valid? if so, DFS to the cell below given the steps above, else, change the direction to left and DFS leftwards given the steps above.else, if the direction given is left then check, is the cell to the left valid? if so, DFS to the left cell given the steps above, else, change the direction to up and DFS upwards given the steps above.else, if the direction given is up then check, is the cell to the up valid? if so, DFS to the upper cell given the steps above, else, change the direction to right and DFS rightwards given the steps above." }, { "code": null, "e": 74530, "s": 74461, "text": "create a DFS function which takes matrix, cell indices and direction" }, { "code": null, "e": 74639, "s": 74530, "text": "check are cell indices pointing to a valid cell (that is, not visited and in bounds)? if not, skip this cell" }, { "code": null, "e": 74656, "s": 74639, "text": "print cell value" }, { "code": null, "e": 74759, "s": 74656, "text": "mark matrix cell pointed by indicates as visited by changing it to a value not supported in the matrix" }, { "code": null, "e": 74831, "s": 74759, "text": "check are surrounding cells valid? if not stop algorithm, else continue" }, { "code": null, "e": 75031, "s": 74831, "text": "if direction given is right then check, is the cell to the right valid? if so, DFS to the right cell given the steps above, else, change the direction to down and DFS downwards given the steps above." }, { "code": null, "e": 75254, "s": 75031, "text": "else, if the direction given is down then check, is the cell to the down valid? if so, DFS to the cell below given the steps above, else, change the direction to left and DFS leftwards given the steps above." }, { "code": null, "e": 75483, "s": 75254, "text": "else, if the direction given is left then check, is the cell to the left valid? if so, DFS to the left cell given the steps above, else, change the direction to up and DFS upwards given the steps above." }, { "code": null, "e": 75715, "s": 75483, "text": "else, if the direction given is up then check, is the cell to the up valid? if so, DFS to the upper cell given the steps above, else, change the direction to right and DFS rightwards given the steps above." }, { "code": null, "e": 75762, "s": 75715, "text": "Below is an implementation of this algorithm: " }, { "code": null, "e": 75766, "s": 75762, "text": "C++" }, { "code": null, "e": 75771, "s": 75766, "text": "Java" }, { "code": null, "e": 75779, "s": 75771, "text": "Python3" }, { "code": null, "e": 75782, "s": 75779, "text": "C#" }, { "code": null, "e": 75793, "s": 75782, "text": "Javascript" }, { "code": "#include <iostream>#include <vector>using namespace std;#define R 4#define C 4 bool isInBounds(int i, int j){ if (i < 0 || i >= R || j < 0 || j >= C) return false; return true;} // check if the position is blockedbool isBlocked(int matrix[R][C], int i, int j){ if (!isInBounds(i, j)) return true; if (matrix[i][j] == -1) return true; return false;} // DFS code to traverse spirallyvoid spirallyDFSTravserse(int matrix[R][C], int i, int j, int dir, vector<int>& res){ if (isBlocked(matrix, i, j)) return; bool allBlocked = true; for (int k = -1; k <= 1; k += 2) { allBlocked = allBlocked && isBlocked(matrix, k + i, j) && isBlocked(matrix, i, j + k); } res.push_back(matrix[i][j]); matrix[i][j] = -1; if (allBlocked) { return; } // dir: 0 - right, 1 - down, 2 - left, 3 - up int nxt_i = i; int nxt_j = j; int nxt_dir = dir; if (dir == 0) { if (!isBlocked(matrix, i, j + 1)) { nxt_j++; } else { nxt_dir = 1; nxt_i++; } } else if (dir == 1) { if (!isBlocked(matrix, i + 1, j)) { nxt_i++; } else { nxt_dir = 2; nxt_j--; } } else if (dir == 2) { if (!isBlocked(matrix, i, j - 1)) { nxt_j--; } else { nxt_dir = 3; nxt_i--; } } else if (dir == 3) { if (!isBlocked(matrix, i - 1, j)) { nxt_i--; } else { nxt_dir = 0; nxt_j++; } } spirallyDFSTravserse(matrix, nxt_i, nxt_j, nxt_dir, res);} // to traverse spirallyvector<int> spirallyTraverse(int matrix[R][C]){ vector<int> res; spirallyDFSTravserse(matrix, 0, 0, 0, res); return res;} // Driver Codeint main(){ int a[R][C] = { { 1, 2, 3, 4 }, { 5, 6, 7, 8 }, { 9, 10, 11, 12 }, { 13, 14, 15, 16 } }; // Function Call vector<int> res = spirallyTraverse(a); int size = res.size(); for (int i = 0; i < size; ++i) cout << res[i] << \" \"; cout << endl; return 0;} // code contributed by Ephi F", "e": 78071, "s": 75793, "text": null }, { "code": "import java.io.*;import java.util.*; class GFG { public static int R = 4, C = 4; public static boolean isInBounds(int i, int j) { if (i < 0 || i >= R || j < 0 || j >= C) return false; return true; } // check if the position is blocked public static boolean isBlocked(int[][] matrix, int i, int j) { if (!isInBounds(i, j)) return true; if (matrix[i][j] == -1) return true; return false; } // DFS code to traverse spirally public static void spirallyDFSTravserse(int[][] matrix, int i, int j, int dir, ArrayList<Integer> res) { if (isBlocked(matrix, i, j)) return; boolean allBlocked = true; for (int k = -1; k <= 1; k += 2) { allBlocked = allBlocked && isBlocked(matrix, k + i, j) && isBlocked(matrix, i, j + k); } res.add(matrix[i][j]); matrix[i][j] = -1; if (allBlocked) { return; } // dir: 0 - right, 1 - down, 2 - left, 3 - up int nxt_i = i; int nxt_j = j; int nxt_dir = dir; if (dir == 0) { if (!isBlocked(matrix, i, j + 1)) { nxt_j++; } else { nxt_dir = 1; nxt_i++; } } else if (dir == 1) { if (!isBlocked(matrix, i + 1, j)) { nxt_i++; } else { nxt_dir = 2; nxt_j--; } } else if (dir == 2) { if (!isBlocked(matrix, i, j - 1)) { nxt_j--; } else { nxt_dir = 3; nxt_i--; } } else if (dir == 3) { if (!isBlocked(matrix, i - 1, j)) { nxt_i--; } else { nxt_dir = 0; nxt_j++; } } spirallyDFSTravserse(matrix, nxt_i, nxt_j, nxt_dir, res); } // to traverse spirally public static ArrayList<Integer> spirallyTraverse(int[][] matrix) { ArrayList<Integer> res = new ArrayList<Integer>(); spirallyDFSTravserse(matrix, 0, 0, 0, res); return res; } // Driver code public static void main(String[] args) { int a[][] = { { 1, 2, 3, 4 }, { 5, 6, 7, 8 }, { 9, 10, 11, 12 }, { 13, 14, 15, 16 } }; // Function Call ArrayList<Integer> res = spirallyTraverse(a); int size = res.size(); for (int i = 0; i < size; ++i) System.out.print(res.get(i) + \" \"); System.out.println(); }} // This code is contributed by Manu Pathria", "e": 80923, "s": 78071, "text": null }, { "code": "R = 4C = 4 def isInBounds(i, j): global R global C if (i < 0 or i >= R or j < 0 or j >= C): return False return True # Check if the position is blocked def isBlocked(matrix, i, j): if (not isInBounds(i, j)): return True if (matrix[i][j] == -1): return True return False # DFS code to traverse spirally def spirallyDFSTravserse(matrix, i, j, Dir, res): if (isBlocked(matrix, i, j)): return allBlocked = True for k in range(-1, 2, 2): allBlocked = allBlocked and isBlocked( matrix, k + i, j) and isBlocked(matrix, i, j + k) res.append(matrix[i][j]) matrix[i][j] = -1 if (allBlocked): return # dir: 0 - right, 1 - down, 2 - left, 3 - up nxt_i = i nxt_j = j nxt_dir = Dir if (Dir == 0): if (not isBlocked(matrix, i, j + 1)): nxt_j += 1 else: nxt_dir = 1 nxt_i += 1 elif(Dir == 1): if (not isBlocked(matrix, i + 1, j)): nxt_i += 1 else: nxt_dir = 2 nxt_j -= 1 elif(Dir == 2): if (not isBlocked(matrix, i, j - 1)): nxt_j -= 1 else: nxt_dir = 3 nxt_i -= 1 elif(Dir == 3): if (not isBlocked(matrix, i - 1, j)): nxt_i -= 1 else: nxt_dir = 0 nxt_j += 1 spirallyDFSTravserse(matrix, nxt_i, nxt_j, nxt_dir, res) # To traverse spirally def spirallyTraverse(matrix): res = [] spirallyDFSTravserse(matrix, 0, 0, 0, res) return res # Driver codea = [[1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12], [13, 14, 15, 16]] # Function Callres = spirallyTraverse(a)print(*res) # This code is contributed by rag2127", "e": 82639, "s": 80923, "text": null }, { "code": "using System;using System.Collections.Generic; class GFG { public static int R = 4, C = 4; public static bool isInBounds(int i, int j) { if (i < 0 || i >= R || j < 0 || j >= C) return false; return true; } // Check if the position is blocked public static bool isBlocked(int[, ] matrix, int i, int j) { if (!isInBounds(i, j)) return true; if (matrix[i, j] == -1) return true; return false; } // DFS code to traverse spirally public static void spirallyDFSTravserse(int[, ] matrix, int i, int j, int dir, List<int> res) { if (isBlocked(matrix, i, j)) return; bool allBlocked = true; for (int k = -1; k <= 1; k += 2) { allBlocked = allBlocked && isBlocked(matrix, k + i, j) && isBlocked(matrix, i, j + k); } res.Add(matrix[i, j]); matrix[i, j] = -1; if (allBlocked) { return; } // dir: 0 - right, 1 - down, 2 - left, 3 - up int nxt_i = i; int nxt_j = j; int nxt_dir = dir; if (dir == 0) { if (!isBlocked(matrix, i, j + 1)) { nxt_j++; } else { nxt_dir = 1; nxt_i++; } } else if (dir == 1) { if (!isBlocked(matrix, i + 1, j)) { nxt_i++; } else { nxt_dir = 2; nxt_j--; } } else if (dir == 2) { if (!isBlocked(matrix, i, j - 1)) { nxt_j--; } else { nxt_dir = 3; nxt_i--; } } else if (dir == 3) { if (!isBlocked(matrix, i - 1, j)) { nxt_i--; } else { nxt_dir = 0; nxt_j++; } } spirallyDFSTravserse(matrix, nxt_i, nxt_j, nxt_dir, res); } // To traverse spirally public static List<int> spirallyTraverse(int[, ] matrix) { List<int> res = new List<int>(); spirallyDFSTravserse(matrix, 0, 0, 0, res); return res; } // Driver code static public void Main() { int[, ] a = { { 1, 2, 3, 4 }, { 5, 6, 7, 8 }, { 9, 10, 11, 12 }, { 13, 14, 15, 16 } }; // Function Call List<int> res = spirallyTraverse(a); int size = res.Count; for (int i = 0; i < size; ++i) Console.Write(res[i] + \" \"); Console.WriteLine(); }} // This code is contributed by avanitrachhadiya2155", "e": 85536, "s": 82639, "text": null }, { "code": "<script> var R = 4, C = 4;function isInBounds(i, j){ if (i < 0 || i >= R || j < 0 || j >= C) return false; return true;}// Check if the position is blockedfunction isBlocked(matrix, i, j){ if (!isInBounds(i, j)) return true; if (matrix[i][j] == -1) return true; return false;}// DFS code to traverse spirallyfunction spirallyDFSTravserse(matrix, i, j, dir, res){ if (isBlocked(matrix, i, j)) return; var allBlocked = true; for (var k = -1; k <= 1; k += 2) { allBlocked = allBlocked && isBlocked(matrix, k + i, j) && isBlocked(matrix, i, j + k); } res.push(matrix[i][j]); matrix[i][j] = -1; if (allBlocked) { return; } // dir: 0 - right, 1 - down, 2 - left, 3 - up var nxt_i = i; var nxt_j = j; var nxt_dir = dir; if (dir == 0) { if (!isBlocked(matrix, i, j + 1)) { nxt_j++; } else { nxt_dir = 1; nxt_i++; } } else if (dir == 1) { if (!isBlocked(matrix, i + 1, j)) { nxt_i++; } else { nxt_dir = 2; nxt_j--; } } else if (dir == 2) { if (!isBlocked(matrix, i, j - 1)) { nxt_j--; } else { nxt_dir = 3; nxt_i--; } } else if (dir == 3) { if (!isBlocked(matrix, i - 1, j)) { nxt_i--; } else { nxt_dir = 0; nxt_j++; } } spirallyDFSTravserse(matrix, nxt_i, nxt_j, nxt_dir, res);}// To traverse spirallyfunction spirallyTraverse(matrix){ var res = []; spirallyDFSTravserse(matrix, 0, 0, 0, res); return res;}// Driver codevar a = [ [ 1, 2, 3, 4 ], [ 5, 6, 7, 8 ], [ 9, 10, 11, 12 ], [ 13, 14, 15, 16 ]];// Function Callvar res = spirallyTraverse(a);var size = res.length;for (var i = 0; i < size; ++i) document.write(res[i] + \" \"); </script>", "e": 87547, "s": 85536, "text": null }, { "code": null, "e": 87587, "s": 87547, "text": "1 2 3 4 8 12 16 15 14 13 9 5 6 7 11 10 " }, { "code": null, "e": 87608, "s": 87587, "text": "Complexity Analysis:" }, { "code": null, "e": 87791, "s": 87608, "text": "Time Complexity: O(m*n). To traverse the matrix O(m*n) time is required.Auxiliary Space: O(1). No extra space is required (without consideration of the stack used by the recursion). " }, { "code": null, "e": 87820, "s": 87791, "text": "Diagonal traversal of Matrix" }, { "code": null, "e": 87852, "s": 87820, "text": "Print matrix in antispiral form" }, { "code": null, "e": 87888, "s": 87852, "text": "Print a given matrix in zigzag form" }, { "code": null, "e": 87995, "s": 87888, "text": "Please write comments if you find the above code incorrect, or find other ways to solve the same problem. " }, { "code": null, "e": 88001, "s": 87995, "text": "ukasp" }, { "code": null, "e": 88015, "s": 88001, "text": "rathbhupendra" }, { "code": null, "e": 88026, "s": 88015, "text": "Ankur Goel" }, { "code": null, "e": 88038, "s": 88026, "text": "29AjayKumar" }, { "code": null, "e": 88051, "s": 88038, "text": "princi singh" }, { "code": null, "e": 88062, "s": 88051, "text": "andrew1234" }, { "code": null, "e": 88079, "s": 88062, "text": "avsadityavardhan" }, { "code": null, "e": 88099, "s": 88079, "text": "harshvardhansingh17" }, { "code": null, "e": 88106, "s": 88099, "text": "ephi2g" }, { "code": null, "e": 88117, "s": 88106, "text": "theadinova" }, { "code": null, "e": 88130, "s": 88117, "text": "swaroopksahu" }, { "code": null, "e": 88142, "s": 88130, "text": "manupathria" }, { "code": null, "e": 88163, "s": 88142, "text": "avanitrachhadiya2155" }, { "code": null, "e": 88185, "s": 88163, "text": "karthiksrinivasprasad" }, { "code": null, "e": 88193, "s": 88185, "text": "rag2127" }, { "code": null, "e": 88207, "s": 88193, "text": "koulick_sadhu" }, { "code": null, "e": 88223, "s": 88207, "text": "rohitsingh07052" }, { "code": null, "e": 88244, "s": 88223, "text": "yashvendrasengar1111" }, { "code": null, "e": 88260, "s": 88244, "text": "sonirudrakshi99" }, { "code": null, "e": 88266, "s": 88260, "text": "itsok" }, { "code": null, "e": 88278, "s": 88266, "text": "unknown2108" }, { "code": null, "e": 88293, "s": 88278, "text": "sagartomar9927" }, { "code": null, "e": 88306, "s": 88293, "text": "animeshbarun" }, { "code": null, "e": 88318, "s": 88306, "text": "rohithp8899" }, { "code": null, "e": 88332, "s": 88318, "text": "sumitgumber28" }, { "code": null, "e": 88343, "s": 88332, "text": "nikhil070g" }, { "code": null, "e": 88360, "s": 88343, "text": "harendrakumar123" }, { "code": null, "e": 88369, "s": 88360, "text": "Accolite" }, { "code": null, "e": 88376, "s": 88369, "text": "Amazon" }, { "code": null, "e": 88392, "s": 88376, "text": "Amazon-Question" }, { "code": null, "e": 88405, "s": 88392, "text": "BrowserStack" }, { "code": null, "e": 88414, "s": 88405, "text": "D-E-Shaw" }, { "code": null, "e": 88425, "s": 88414, "text": "MakeMyTrip" }, { "code": null, "e": 88438, "s": 88425, "text": "MAQ Software" }, { "code": null, "e": 88448, "s": 88438, "text": "Microsoft" }, { "code": null, "e": 88463, "s": 88448, "text": "Morgan Stanley" }, { "code": null, "e": 88471, "s": 88463, "text": "Nagarro" }, { "code": null, "e": 88479, "s": 88471, "text": "nearbuy" }, { "code": null, "e": 88486, "s": 88479, "text": "Oracle" }, { "code": null, "e": 88503, "s": 88486, "text": "pattern-printing" }, { "code": null, "e": 88509, "s": 88503, "text": "Paytm" }, { "code": null, "e": 88518, "s": 88509, "text": "Snapdeal" }, { "code": null, "e": 88536, "s": 88518, "text": "Snapdeal-Question" }, { "code": null, "e": 88543, "s": 88536, "text": "spiral" }, { "code": null, "e": 88548, "s": 88543, "text": "Zoho" }, { "code": null, "e": 88555, "s": 88548, "text": "Arrays" }, { "code": null, "e": 88562, "s": 88555, "text": "Matrix" }, { "code": null, "e": 88581, "s": 88562, "text": "School Programming" }, { "code": null, "e": 88587, "s": 88581, "text": "Paytm" }, { "code": null, "e": 88592, "s": 88587, "text": "Zoho" }, { "code": null, "e": 88607, "s": 88592, "text": "Morgan Stanley" }, { "code": null, "e": 88616, "s": 88607, "text": "Accolite" }, { "code": null, "e": 88623, "s": 88616, "text": "Amazon" }, { "code": null, "e": 88633, "s": 88623, "text": "Microsoft" }, { "code": null, "e": 88642, "s": 88633, "text": "Snapdeal" }, { "code": null, "e": 88651, "s": 88642, "text": "D-E-Shaw" }, { "code": null, "e": 88662, "s": 88651, "text": "MakeMyTrip" }, { "code": null, "e": 88669, "s": 88662, "text": "Oracle" }, { "code": null, "e": 88682, "s": 88669, "text": "MAQ Software" }, { "code": null, "e": 88690, "s": 88682, "text": "nearbuy" }, { "code": null, "e": 88698, "s": 88690, "text": "Nagarro" }, { "code": null, "e": 88711, "s": 88698, "text": "BrowserStack" }, { "code": null, "e": 88718, "s": 88711, "text": "Arrays" }, { "code": null, "e": 88735, "s": 88718, "text": "pattern-printing" }, { "code": null, "e": 88742, "s": 88735, "text": "Matrix" }, { "code": null, "e": 88840, "s": 88742, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 88855, "s": 88840, "text": "Arrays in Java" }, { "code": null, "e": 88871, "s": 88855, "text": "Arrays in C/C++" }, { "code": null, "e": 88917, "s": 88871, "text": "Write a program to reverse an array or string" }, { "code": null, "e": 88944, "s": 88917, "text": "Program for array rotation" }, { "code": null, "e": 88976, "s": 88944, "text": "Largest Sum Contiguous Subarray" }, { "code": null, "e": 89011, "s": 88976, "text": "Matrix Chain Multiplication | DP-8" }, { "code": null, "e": 89055, "s": 89011, "text": "Program to find largest element in an array" }, { "code": null, "e": 89086, "s": 89055, "text": "Rat in a Maze | Backtracking-2" }, { "code": null, "e": 89129, "s": 89086, "text": "Maximum size square sub-matrix with all 1s" } ]
Java Signature sign() method with Examples - GeeksforGeeks
11 May, 2021 The sign() method of java.security.Provider class is used to finish the signature operation and stores the resulting signature bytes in the provided buffer dataBuffer, starting at offset. The format of the signature depends on the underlying signature scheme.This signature object is reset to its initial state (the state it was in after a call to one of the initSign methods) and can be reused to generate further signatures with the same private key.Syntax: public final int sign( byte[] data, int offset, int length ) Parameters: This method takes the following argument as a parameterdataBuffer– buffer for the signature result as byte[] array.offset– offset into dataBuffer where the signature is stored.length– number of bytes within dataBuffer allotted for the signature.Return Value: This method returns the number of bytes placed into dataBuffer. Exception: This method throws SignatureException if this signature object is not initialized properly or if this signature algorithm is unable to process the input data provided.Below are the examples to illustrate the sign() method:Note: The following program will not run in online IDEExample 1: Java // Java program to demonstrate// sign() method import java.security.*;import java.util.*;import sun.misc.BASE64Encoder; public class GFG1 { public static void main(String[] argv) throws Exception { try { // calling getKeyPair() method and assigning in // keypair KeyPair keyPair = getKeyPair(); // creating byte array object byte[] outbuff = new byte[1000]; // data to be updated byte[] data = "test".getBytes("UTF8"); // creating the object of Signature Signature sr = Signature.getInstance("SHA1WithRSA"); // initializing the signature object with key // pair for signing sr.initSign(keyPair.getPrivate()); // updating the data sr.update(data); // getting the number of bytes // placed in outbuffer // by using method sign() int bytes = sr.sign(outbuff, 0, 550); // printing the number of byte System.out.println("Signature:" + bytes); } catch (NoSuchAlgorithmException e) { System.out.println("Exception thrown : " + e); } catch (SignatureException e) { System.out.println("Exception thrown : " + e); } } // defining getKeyPair method private static KeyPair getKeyPair() throws NoSuchAlgorithmException { // creating the object of KeyPairGenerator KeyPairGenerator kpg = KeyPairGenerator.getInstance("RSA"); // initializing with 1024 kpg.initialize(1024); // returning the key pairs return kpg.genKeyPair(); }} Output: Signature:128 Example 2: Java // Java program to demonstrate// sign() method import java.security.*;import java.util.*; public class GFG1 { public static void main(String[] argv) throws Exception { try { // creating byte array object byte[] outbuff = new byte[1000]; // creating the object of Signature Signature sr = Signature.getInstance("SHA1WithRSA"); ; // getting the number of bytes // placed in outbuffer // by using method sign() int bytes = sr.sign(outbuff, 0, 550); // printing the number of byte System.out.println("Signature:" + bytes); } catch (NoSuchAlgorithmException e) { System.out.println("Exception thrown : " + e); } catch (SignatureException e) { System.out.println("Exception thrown : " + e); } }} Output: Exception thrown : java.security.SignatureException: object not initialized for signing The sign() method of java.security.Provider class is used to return the signature bytes of all the data updated. The format of the signature depends on the underlying signature scheme.A call to this method resets this signature object to the state it was in when previously initialized for signing via a call to initSign(PrivateKey). That is, the object is reset and available to generate another signature from the same signer, if desired, via new calls to update and sign.Return Value: This method returns the signature bytes of the signing operation’s result.Exception: This method throws SignatureException if this signature object is not initialized properly or if this signature algorithm is unable to process the input data provided.Below are the examples to illustrate the sign() method:Note: The following program will not run in online IDEExample 1: Java // Java program to demonstrate// sign() method import java.security.*;import java.util.*;import sun.misc.BASE64Encoder; public class GFG1 { public static void main(String[] argv) throws Exception { try { // calling getKeyPair() method and assigning in // keypair KeyPair keyPair = getKeyPair(); // data to be updated byte[] data = "test".getBytes("UTF8"); // creating the object of Signature Signature sr = Signature.getInstance("SHA1WithRSA"); // initializing the signature object with key // pair for signing sr.initSign(keyPair.getPrivate()); // updating the data sr.update(data); // getting the signature byte // of an signing operation // by using method sign() byte[] bytes = sr.sign(); // printing the number of byte System.out.println("Signature:" + Arrays.toString(bytes)); } catch (NoSuchAlgorithmException e) { System.out.println("Exception thrown : " + e); } catch (SignatureException e) { System.out.println("Exception thrown : " + e); } } // defining getKeyPair method private static KeyPair getKeyPair() throws NoSuchAlgorithmException { // creating the object of KeyPairGenerator KeyPairGenerator kpg = KeyPairGenerator.getInstance("RSA"); // initializing with 1024 kpg.initialize(1024); // returning the key pairs return kpg.genKeyPair(); }} Output: Signature : [96, 101, 38, 76, ... -59] Example 2: Java // Java program to demonstrate// sign() method import java.security.*;import java.util.*; public class GFG1 { public static void main(String[] argv) throws Exception { try { // creating byte array object byte[] outbuff = new byte[1000]; // creating the object of Signature Signature sr = Signature.getInstance("SHA1WithRSA"); ; // getting the number of bytes // placed in outbuffer // by using method sign() System.out.println( "Trying to get" + " the signature byte before initializing"); byte[] bytes = sr.sign(); // printing the number of byte System.out.println("Signature:" + bytes); } catch (NoSuchAlgorithmException e) { System.out.println("Exception thrown : " + e); } catch (SignatureException e) { System.out.println("Exception thrown : " + e); } }} Output: Trying to get the signature byte before initializing Exception thrown : java.security.SignatureException: object not initialized for signing Akanksha_Rai anikakapoor Java-Functions Java-security package Java-Signature Java Java Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Stream In Java Interfaces in Java ArrayList in Java Initialize an ArrayList in Java Stack Class in Java Multidimensional Arrays in Java Set in Java Multithreading in Java Collections in Java Queue Interface In Java
[ { "code": null, "e": 25981, "s": 25953, "text": "\n11 May, 2021" }, { "code": null, "e": 26442, "s": 25981, "text": "The sign() method of java.security.Provider class is used to finish the signature operation and stores the resulting signature bytes in the provided buffer dataBuffer, starting at offset. The format of the signature depends on the underlying signature scheme.This signature object is reset to its initial state (the state it was in after a call to one of the initSign methods) and can be reused to generate further signatures with the same private key.Syntax: " }, { "code": null, "e": 26503, "s": 26442, "text": "public final int sign( byte[] data, int offset, int length )" }, { "code": null, "e": 26838, "s": 26503, "text": "Parameters: This method takes the following argument as a parameterdataBuffer– buffer for the signature result as byte[] array.offset– offset into dataBuffer where the signature is stored.length– number of bytes within dataBuffer allotted for the signature.Return Value: This method returns the number of bytes placed into dataBuffer." }, { "code": null, "e": 27138, "s": 26838, "text": "Exception: This method throws SignatureException if this signature object is not initialized properly or if this signature algorithm is unable to process the input data provided.Below are the examples to illustrate the sign() method:Note: The following program will not run in online IDEExample 1: " }, { "code": null, "e": 27143, "s": 27138, "text": "Java" }, { "code": "// Java program to demonstrate// sign() method import java.security.*;import java.util.*;import sun.misc.BASE64Encoder; public class GFG1 { public static void main(String[] argv) throws Exception { try { // calling getKeyPair() method and assigning in // keypair KeyPair keyPair = getKeyPair(); // creating byte array object byte[] outbuff = new byte[1000]; // data to be updated byte[] data = \"test\".getBytes(\"UTF8\"); // creating the object of Signature Signature sr = Signature.getInstance(\"SHA1WithRSA\"); // initializing the signature object with key // pair for signing sr.initSign(keyPair.getPrivate()); // updating the data sr.update(data); // getting the number of bytes // placed in outbuffer // by using method sign() int bytes = sr.sign(outbuff, 0, 550); // printing the number of byte System.out.println(\"Signature:\" + bytes); } catch (NoSuchAlgorithmException e) { System.out.println(\"Exception thrown : \" + e); } catch (SignatureException e) { System.out.println(\"Exception thrown : \" + e); } } // defining getKeyPair method private static KeyPair getKeyPair() throws NoSuchAlgorithmException { // creating the object of KeyPairGenerator KeyPairGenerator kpg = KeyPairGenerator.getInstance(\"RSA\"); // initializing with 1024 kpg.initialize(1024); // returning the key pairs return kpg.genKeyPair(); }}", "e": 28852, "s": 27143, "text": null }, { "code": null, "e": 28862, "s": 28852, "text": "Output: " }, { "code": null, "e": 28876, "s": 28862, "text": "Signature:128" }, { "code": null, "e": 28889, "s": 28876, "text": "Example 2: " }, { "code": null, "e": 28894, "s": 28889, "text": "Java" }, { "code": "// Java program to demonstrate// sign() method import java.security.*;import java.util.*; public class GFG1 { public static void main(String[] argv) throws Exception { try { // creating byte array object byte[] outbuff = new byte[1000]; // creating the object of Signature Signature sr = Signature.getInstance(\"SHA1WithRSA\"); ; // getting the number of bytes // placed in outbuffer // by using method sign() int bytes = sr.sign(outbuff, 0, 550); // printing the number of byte System.out.println(\"Signature:\" + bytes); } catch (NoSuchAlgorithmException e) { System.out.println(\"Exception thrown : \" + e); } catch (SignatureException e) { System.out.println(\"Exception thrown : \" + e); } }}", "e": 29800, "s": 28894, "text": null }, { "code": null, "e": 29810, "s": 29800, "text": "Output: " }, { "code": null, "e": 29898, "s": 29810, "text": "Exception thrown : java.security.SignatureException: object not initialized for signing" }, { "code": null, "e": 30762, "s": 29900, "text": "The sign() method of java.security.Provider class is used to return the signature bytes of all the data updated. The format of the signature depends on the underlying signature scheme.A call to this method resets this signature object to the state it was in when previously initialized for signing via a call to initSign(PrivateKey). That is, the object is reset and available to generate another signature from the same signer, if desired, via new calls to update and sign.Return Value: This method returns the signature bytes of the signing operation’s result.Exception: This method throws SignatureException if this signature object is not initialized properly or if this signature algorithm is unable to process the input data provided.Below are the examples to illustrate the sign() method:Note: The following program will not run in online IDEExample 1: " }, { "code": null, "e": 30767, "s": 30762, "text": "Java" }, { "code": "// Java program to demonstrate// sign() method import java.security.*;import java.util.*;import sun.misc.BASE64Encoder; public class GFG1 { public static void main(String[] argv) throws Exception { try { // calling getKeyPair() method and assigning in // keypair KeyPair keyPair = getKeyPair(); // data to be updated byte[] data = \"test\".getBytes(\"UTF8\"); // creating the object of Signature Signature sr = Signature.getInstance(\"SHA1WithRSA\"); // initializing the signature object with key // pair for signing sr.initSign(keyPair.getPrivate()); // updating the data sr.update(data); // getting the signature byte // of an signing operation // by using method sign() byte[] bytes = sr.sign(); // printing the number of byte System.out.println(\"Signature:\" + Arrays.toString(bytes)); } catch (NoSuchAlgorithmException e) { System.out.println(\"Exception thrown : \" + e); } catch (SignatureException e) { System.out.println(\"Exception thrown : \" + e); } } // defining getKeyPair method private static KeyPair getKeyPair() throws NoSuchAlgorithmException { // creating the object of KeyPairGenerator KeyPairGenerator kpg = KeyPairGenerator.getInstance(\"RSA\"); // initializing with 1024 kpg.initialize(1024); // returning the key pairs return kpg.genKeyPair(); }}", "e": 32428, "s": 30767, "text": null }, { "code": null, "e": 32438, "s": 32428, "text": "Output: " }, { "code": null, "e": 32477, "s": 32438, "text": "Signature : [96, 101, 38, 76, ... -59]" }, { "code": null, "e": 32490, "s": 32477, "text": "Example 2: " }, { "code": null, "e": 32495, "s": 32490, "text": "Java" }, { "code": "// Java program to demonstrate// sign() method import java.security.*;import java.util.*; public class GFG1 { public static void main(String[] argv) throws Exception { try { // creating byte array object byte[] outbuff = new byte[1000]; // creating the object of Signature Signature sr = Signature.getInstance(\"SHA1WithRSA\"); ; // getting the number of bytes // placed in outbuffer // by using method sign() System.out.println( \"Trying to get\" + \" the signature byte before initializing\"); byte[] bytes = sr.sign(); // printing the number of byte System.out.println(\"Signature:\" + bytes); } catch (NoSuchAlgorithmException e) { System.out.println(\"Exception thrown : \" + e); } catch (SignatureException e) { System.out.println(\"Exception thrown : \" + e); } }}", "e": 33512, "s": 32495, "text": null }, { "code": null, "e": 33522, "s": 33512, "text": "Output: " }, { "code": null, "e": 33665, "s": 33522, "text": "Trying to get the signature byte before initializing\nException thrown : java.security.SignatureException: object not initialized for signing\n " }, { "code": null, "e": 33678, "s": 33665, "text": "Akanksha_Rai" }, { "code": null, "e": 33690, "s": 33678, "text": "anikakapoor" }, { "code": null, "e": 33705, "s": 33690, "text": "Java-Functions" }, { "code": null, "e": 33727, "s": 33705, "text": "Java-security package" }, { "code": null, "e": 33742, "s": 33727, "text": "Java-Signature" }, { "code": null, "e": 33747, "s": 33742, "text": "Java" }, { "code": null, "e": 33752, "s": 33747, "text": "Java" }, { "code": null, "e": 33850, "s": 33752, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 33865, "s": 33850, "text": "Stream In Java" }, { "code": null, "e": 33884, "s": 33865, "text": "Interfaces in Java" }, { "code": null, "e": 33902, "s": 33884, "text": "ArrayList in Java" }, { "code": null, "e": 33934, "s": 33902, "text": "Initialize an ArrayList in Java" }, { "code": null, "e": 33954, "s": 33934, "text": "Stack Class in Java" }, { "code": null, "e": 33986, "s": 33954, "text": "Multidimensional Arrays in Java" }, { "code": null, "e": 33998, "s": 33986, "text": "Set in Java" }, { "code": null, "e": 34021, "s": 33998, "text": "Multithreading in Java" }, { "code": null, "e": 34041, "s": 34021, "text": "Collections in Java" } ]
Matcher lookingAt() method in Java with Examples - GeeksforGeeks
26 Nov, 2018 The lookingAt() method of Matcher Class attempts to match the pattern partially or fully in the matcher. It returns a boolean value showing if the pattern was matched even partially or fully starting from the start of the pattern. Syntax: public boolean lookingAt() Parameters: This method do not takes any parameter. Return Value: This method returns a boolean value showing if a prefix of the input sequence matches this matcher’s pattern. Below examples illustrate the Matcher.lookingAt() method: Example 1: // Java code to illustrate lookingAt() method import java.util.regex.*; public class GFG { public static void main(String[] args) { // Get the regex to be checked String regex = "Geeks"; // Create a pattern from regex Pattern pattern = Pattern.compile(regex); // Get the String to be matched String stringToBeMatched = "GeeksForGeeks"; // Create a matcher for the input String Matcher matcher = pattern .matcher(stringToBeMatched); // Get the possible result // using lookingAt() method System.out.println(matcher.lookingAt()); }} true Example 2: // Java code to illustrate lookingAt() method import java.util.regex.*; public class GFG { public static void main(String[] args) { // Get the regex to be checked String regex = "GFG"; // Create a pattern from regex Pattern pattern = Pattern.compile(regex); // Get the String to be matched String stringToBeMatched = "GFGFGFGFGFGFGFGFGFG"; // Create a matcher for the input String Matcher matcher = pattern .matcher(stringToBeMatched); // Get the possible result // using lookingAt() method System.out.println(matcher.lookingAt()); }} true Reference: https://docs.oracle.com/javase/9/docs/api/java/util/regex/Matcher.html#lookingAt– Java - util package Java-Functions Java-Matcher Java Java Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Stream In Java Constructors in Java Exceptions in Java Functional Interfaces in Java Different ways of Reading a text file in Java Generics in Java Introduction to Java Comparator Interface in Java with Examples Internal Working of HashMap in Java Strings in Java
[ { "code": null, "e": 25225, "s": 25197, "text": "\n26 Nov, 2018" }, { "code": null, "e": 25456, "s": 25225, "text": "The lookingAt() method of Matcher Class attempts to match the pattern partially or fully in the matcher. It returns a boolean value showing if the pattern was matched even partially or fully starting from the start of the pattern." }, { "code": null, "e": 25464, "s": 25456, "text": "Syntax:" }, { "code": null, "e": 25492, "s": 25464, "text": "public boolean lookingAt()\n" }, { "code": null, "e": 25544, "s": 25492, "text": "Parameters: This method do not takes any parameter." }, { "code": null, "e": 25668, "s": 25544, "text": "Return Value: This method returns a boolean value showing if a prefix of the input sequence matches this matcher’s pattern." }, { "code": null, "e": 25726, "s": 25668, "text": "Below examples illustrate the Matcher.lookingAt() method:" }, { "code": null, "e": 25737, "s": 25726, "text": "Example 1:" }, { "code": "// Java code to illustrate lookingAt() method import java.util.regex.*; public class GFG { public static void main(String[] args) { // Get the regex to be checked String regex = \"Geeks\"; // Create a pattern from regex Pattern pattern = Pattern.compile(regex); // Get the String to be matched String stringToBeMatched = \"GeeksForGeeks\"; // Create a matcher for the input String Matcher matcher = pattern .matcher(stringToBeMatched); // Get the possible result // using lookingAt() method System.out.println(matcher.lookingAt()); }}", "e": 26416, "s": 25737, "text": null }, { "code": null, "e": 26422, "s": 26416, "text": "true\n" }, { "code": null, "e": 26433, "s": 26422, "text": "Example 2:" }, { "code": "// Java code to illustrate lookingAt() method import java.util.regex.*; public class GFG { public static void main(String[] args) { // Get the regex to be checked String regex = \"GFG\"; // Create a pattern from regex Pattern pattern = Pattern.compile(regex); // Get the String to be matched String stringToBeMatched = \"GFGFGFGFGFGFGFGFGFG\"; // Create a matcher for the input String Matcher matcher = pattern .matcher(stringToBeMatched); // Get the possible result // using lookingAt() method System.out.println(matcher.lookingAt()); }}", "e": 27116, "s": 26433, "text": null }, { "code": null, "e": 27122, "s": 27116, "text": "true\n" }, { "code": null, "e": 27215, "s": 27122, "text": "Reference: https://docs.oracle.com/javase/9/docs/api/java/util/regex/Matcher.html#lookingAt–" }, { "code": null, "e": 27235, "s": 27215, "text": "Java - util package" }, { "code": null, "e": 27250, "s": 27235, "text": "Java-Functions" }, { "code": null, "e": 27263, "s": 27250, "text": "Java-Matcher" }, { "code": null, "e": 27268, "s": 27263, "text": "Java" }, { "code": null, "e": 27273, "s": 27268, "text": "Java" }, { "code": null, "e": 27371, "s": 27273, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 27386, "s": 27371, "text": "Stream In Java" }, { "code": null, "e": 27407, "s": 27386, "text": "Constructors in Java" }, { "code": null, "e": 27426, "s": 27407, "text": "Exceptions in Java" }, { "code": null, "e": 27456, "s": 27426, "text": "Functional Interfaces in Java" }, { "code": null, "e": 27502, "s": 27456, "text": "Different ways of Reading a text file in Java" }, { "code": null, "e": 27519, "s": 27502, "text": "Generics in Java" }, { "code": null, "e": 27540, "s": 27519, "text": "Introduction to Java" }, { "code": null, "e": 27583, "s": 27540, "text": "Comparator Interface in Java with Examples" }, { "code": null, "e": 27619, "s": 27583, "text": "Internal Working of HashMap in Java" } ]
HTML DOM revokeObjectURL() method - GeeksforGeeks
14 Jul, 2020 The URL revokeObjectURL() method releases an existing object URL which was created by using URL createObjectURL(). This method is called when you are finished using an object URL and don’t want the browser to keep the reference to that file any longer. Syntax: URL.revokeObjectURL(objectURL); Parameters: objectURL: A DOMString object URL to be released. Return Value: This method has no return value. Example: In this example, create an objectURL using createObjectURL() method and then revoked it. <!DOCTYPE html><html><head> <meta charset="utf-8"> <title>URL.revokeObjectURL example</title></head><body> <h1>GeeksforGeeks</h1> <input type="file"> <img> <p class="p">The URL of this image is : </p></body><script> var Element = document.querySelector('input'); var img = document.querySelector('img'); Element.addEventListener('change', function() { var url = URL.createObjectURL(Element.files[0]); img.src = url; console.log(url); URL.revokeObjectURL(url) var d=document.querySelector(".p"); d.textContent+=url;});</script></html> Output: Before Choosing Image: After Choosing Image: In the console, an error can be seen that “Not allowed to load local resource” as the URL is revoked. Checking the Object URL will also give “File not found”: Supported Browsers: Google Chrome Edge Firefox Safari Opera Internet Explorer Attention reader! Don’t stop learning now. Get hold of all the important HTML concepts with the Web Design for Beginners | HTML course. HTML-DOM HTML JavaScript Web Technologies HTML Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to update Node.js and NPM to next version ? REST API (Introduction) How to Insert Form Data into Database using PHP ? Types of CSS (Cascading Style Sheet) How to position a div at the bottom of its container using CSS? Remove elements from a JavaScript Array Convert a string to an integer in JavaScript Difference between var, let and const keywords in JavaScript Differences between Functional Components and Class Components in React How to calculate the number of days between two dates in javascript?
[ { "code": null, "e": 26033, "s": 26005, "text": "\n14 Jul, 2020" }, { "code": null, "e": 26286, "s": 26033, "text": "The URL revokeObjectURL() method releases an existing object URL which was created by using URL createObjectURL(). This method is called when you are finished using an object URL and don’t want the browser to keep the reference to that file any longer." }, { "code": null, "e": 26294, "s": 26286, "text": "Syntax:" }, { "code": null, "e": 26326, "s": 26294, "text": "URL.revokeObjectURL(objectURL);" }, { "code": null, "e": 26338, "s": 26326, "text": "Parameters:" }, { "code": null, "e": 26388, "s": 26338, "text": "objectURL: A DOMString object URL to be released." }, { "code": null, "e": 26435, "s": 26388, "text": "Return Value: This method has no return value." }, { "code": null, "e": 26533, "s": 26435, "text": "Example: In this example, create an objectURL using createObjectURL() method and then revoked it." }, { "code": "<!DOCTYPE html><html><head> <meta charset=\"utf-8\"> <title>URL.revokeObjectURL example</title></head><body> <h1>GeeksforGeeks</h1> <input type=\"file\"> <img> <p class=\"p\">The URL of this image is : </p></body><script> var Element = document.querySelector('input'); var img = document.querySelector('img'); Element.addEventListener('change', function() { var url = URL.createObjectURL(Element.files[0]); img.src = url; console.log(url); URL.revokeObjectURL(url) var d=document.querySelector(\".p\"); d.textContent+=url;});</script></html>", "e": 27112, "s": 26533, "text": null }, { "code": null, "e": 27120, "s": 27112, "text": "Output:" }, { "code": null, "e": 27143, "s": 27120, "text": "Before Choosing Image:" }, { "code": null, "e": 27267, "s": 27143, "text": "After Choosing Image: In the console, an error can be seen that “Not allowed to load local resource” as the URL is revoked." }, { "code": null, "e": 27324, "s": 27267, "text": "Checking the Object URL will also give “File not found”:" }, { "code": null, "e": 27344, "s": 27324, "text": "Supported Browsers:" }, { "code": null, "e": 27358, "s": 27344, "text": "Google Chrome" }, { "code": null, "e": 27363, "s": 27358, "text": "Edge" }, { "code": null, "e": 27371, "s": 27363, "text": "Firefox" }, { "code": null, "e": 27378, "s": 27371, "text": "Safari" }, { "code": null, "e": 27384, "s": 27378, "text": "Opera" }, { "code": null, "e": 27402, "s": 27384, "text": "Internet Explorer" }, { "code": null, "e": 27539, "s": 27402, "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": 27548, "s": 27539, "text": "HTML-DOM" }, { "code": null, "e": 27553, "s": 27548, "text": "HTML" }, { "code": null, "e": 27564, "s": 27553, "text": "JavaScript" }, { "code": null, "e": 27581, "s": 27564, "text": "Web Technologies" }, { "code": null, "e": 27586, "s": 27581, "text": "HTML" }, { "code": null, "e": 27684, "s": 27586, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 27732, "s": 27684, "text": "How to update Node.js and NPM to next version ?" }, { "code": null, "e": 27756, "s": 27732, "text": "REST API (Introduction)" }, { "code": null, "e": 27806, "s": 27756, "text": "How to Insert Form Data into Database using PHP ?" }, { "code": null, "e": 27843, "s": 27806, "text": "Types of CSS (Cascading Style Sheet)" }, { "code": null, "e": 27907, "s": 27843, "text": "How to position a div at the bottom of its container using CSS?" }, { "code": null, "e": 27947, "s": 27907, "text": "Remove elements from a JavaScript Array" }, { "code": null, "e": 27992, "s": 27947, "text": "Convert a string to an integer in JavaScript" }, { "code": null, "e": 28053, "s": 27992, "text": "Difference between var, let and const keywords in JavaScript" }, { "code": null, "e": 28125, "s": 28053, "text": "Differences between Functional Components and Class Components in React" } ]
GATE | GATE-CS-2009 | Question 17 - GeeksforGeeks
17 Sep, 2017 Match all items in Group 1 with correct options from those given in Group 2. Group 1 Group 2 P. Regular expression 1. Syntax analysis Q. Pushdown automata 2. Code generation R. Dataflow analysis 3. Lexical analysis S. Register allocation 4. Code optimization (A) P-4. Q-1, R-2, S-3(B) P-3, Q-1, R-4, S-2(C) P-3, Q-4, R-1, S-2(D) P-2, Q-1, R-4, S-3Answer: (B)Explanation: Regular expressions are used in lexical analysis. Pushdown automata is related to context free grammar which is related to syntax analysis. Dataflow analysis is done in code optimization. Register allocation is done in code generation.Quiz of this Question GATE-CS-2009 GATE-GATE-CS-2009 GATE Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. GATE | Gate IT 2007 | Question 25 GATE | GATE-CS-2001 | Question 39 GATE | GATE-CS-2000 | Question 41 GATE | GATE-CS-2005 | Question 6 GATE | GATE MOCK 2017 | Question 21 GATE | GATE MOCK 2017 | Question 24 GATE | GATE-CS-2006 | Question 47 GATE | Gate IT 2008 | Question 43 GATE | GATE-CS-2009 | Question 38 GATE | GATE-CS-2003 | Question 90
[ { "code": null, "e": 25605, "s": 25577, "text": "\n17 Sep, 2017" }, { "code": null, "e": 25682, "s": 25605, "text": "Match all items in Group 1 with correct options from those given in Group 2." }, { "code": null, "e": 25918, "s": 25682, "text": "Group 1 Group 2\nP. Regular expression 1. Syntax analysis\nQ. Pushdown automata 2. Code generation\nR. Dataflow analysis 3. Lexical analysis\nS. Register allocation 4. Code optimization" }, { "code": null, "e": 26081, "s": 25918, "text": " (A) P-4. Q-1, R-2, S-3(B) P-3, Q-1, R-4, S-2(C) P-3, Q-4, R-1, S-2(D) P-2, Q-1, R-4, S-3Answer: (B)Explanation: Regular expressions are used in lexical analysis." }, { "code": null, "e": 26171, "s": 26081, "text": "Pushdown automata is related to context free grammar which is related to syntax analysis." }, { "code": null, "e": 26219, "s": 26171, "text": "Dataflow analysis is done in code optimization." }, { "code": null, "e": 26288, "s": 26219, "text": "Register allocation is done in code generation.Quiz of this Question" }, { "code": null, "e": 26301, "s": 26288, "text": "GATE-CS-2009" }, { "code": null, "e": 26319, "s": 26301, "text": "GATE-GATE-CS-2009" }, { "code": null, "e": 26324, "s": 26319, "text": "GATE" }, { "code": null, "e": 26422, "s": 26324, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 26456, "s": 26422, "text": "GATE | Gate IT 2007 | Question 25" }, { "code": null, "e": 26490, "s": 26456, "text": "GATE | GATE-CS-2001 | Question 39" }, { "code": null, "e": 26524, "s": 26490, "text": "GATE | GATE-CS-2000 | Question 41" }, { "code": null, "e": 26557, "s": 26524, "text": "GATE | GATE-CS-2005 | Question 6" }, { "code": null, "e": 26593, "s": 26557, "text": "GATE | GATE MOCK 2017 | Question 21" }, { "code": null, "e": 26629, "s": 26593, "text": "GATE | GATE MOCK 2017 | Question 24" }, { "code": null, "e": 26663, "s": 26629, "text": "GATE | GATE-CS-2006 | Question 47" }, { "code": null, "e": 26697, "s": 26663, "text": "GATE | Gate IT 2008 | Question 43" }, { "code": null, "e": 26731, "s": 26697, "text": "GATE | GATE-CS-2009 | Question 38" } ]
How to Calculate Cumulative Product in MATLAB - GeeksforGeeks
18 Oct, 2021 The cumulative product of a sequence is a running products or partial products of a sequence The cumulative products of the sequence {a,b,c,...}, are a, a*b, a*b*c, .... Matlab allows us to calculate the cumulative product of a vector, matrix using cumprod() method. Differenct syntaxes of cumprod() method are B = cumprod(A) B = cumprod(A,dim) B = cumsprod(___,direction) B = cumprod(___,nanflag) Now we will discuss the above syntaxes in detail: The method returns the cumulative product of A starting at the beginning of array A. If A is a vector, then it returns the cumulative product of sequence A If A is a matrix, then it returns the cumulative product along each column of A. Example 1: Matlab % Input vectorA = 2:8; B = cumprod(A); % Displays cumulative% products of Adisp(B) Output : Example 2: Matlab % Input matrixA = [1 4 7; 2 5 8; 3 6 9];disp("Matrix :")disp(A) B = cumprod(A);% Display cumulative product of matrix Adisp("Cumulative product :")disp(B) Output : Returns the cumulative product of matrix A along with each dim. dim takes two values 1 or 2. dim = 1, refers to along each column. dim = 2, refers along each row. Matlab % input matrixA = [1 3 5; 2 4 6];disp("Matrix :")disp(A) % Cumulative product along each% row from left to rightB = cumprod(A,2);disp("Cumulative product :")disp(B); Output : Returns the cumulative product of the input vector or matrix in the given direction. direction takes two values ‘forward’ or ‘reverse’ If the direction is ‘reverse’, then calculates cumulative product in reverse i.e if we are considering matrix along each column, then it returns cumulative product starting from bottom to top of each column. Matlab % input matrixA = [1 3 5; 2 4 6];disp("Matrix :")disp(A) % Cumulative product of A along each row% starting from right to leftB = cumprod(A,2,'reverse');disp("Cumulative product :")disp(B) Output : nanflag value decides whether to include or exclude NaN value of the vector in cumulative product or not. nanflag takes two values ‘includenan’ or ‘omitnan’ corresponds to including NaN elements and excluding NaN elements respectively. ‘omitNaN’ considers NaN values as 1. Note: NaN * number = NaN Matlab % Input vectorA = [3 5 NaN 9 0 NaN];disp("Vector :");disp(A); % Including NaN valuesB = cumprod(A,'includenan');disp("Cumulative product Include NaN :");disp(B); % Excluding NaN valuesB = cumprod(A,'omitnan');disp("Cumulative product Exclude NaN :");disp(B); Output : gabaa406 varshagumber28 MATLAB-Maths Picked MATLAB Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Forward and Inverse Fourier Transform of an Image in MATLAB Boundary Extraction of image using MATLAB How to Remove Noise from Digital Image in Frequency Domain Using MATLAB? How to Solve Histogram Equalization Numerical Problem in MATLAB? How to Normalize a Histogram in MATLAB? How to Remove Salt and Pepper Noise from Image Using MATLAB? Double Integral in MATLAB Classes and Object in MATLAB How to Convert Three Channels of Colored Image into Grayscale Image in MATLAB? Adaptive Histogram Equalization in Image Processing Using MATLAB
[ { "code": null, "e": 25861, "s": 25833, "text": "\n18 Oct, 2021" }, { "code": null, "e": 25954, "s": 25861, "text": "The cumulative product of a sequence is a running products or partial products of a sequence" }, { "code": null, "e": 26031, "s": 25954, "text": "The cumulative products of the sequence {a,b,c,...}, are a, a*b, a*b*c, ...." }, { "code": null, "e": 26172, "s": 26031, "text": "Matlab allows us to calculate the cumulative product of a vector, matrix using cumprod() method. Differenct syntaxes of cumprod() method are" }, { "code": null, "e": 26187, "s": 26172, "text": "B = cumprod(A)" }, { "code": null, "e": 26206, "s": 26187, "text": "B = cumprod(A,dim)" }, { "code": null, "e": 26234, "s": 26206, "text": "B = cumsprod(___,direction)" }, { "code": null, "e": 26259, "s": 26234, "text": "B = cumprod(___,nanflag)" }, { "code": null, "e": 26309, "s": 26259, "text": "Now we will discuss the above syntaxes in detail:" }, { "code": null, "e": 26394, "s": 26309, "text": "The method returns the cumulative product of A starting at the beginning of array A." }, { "code": null, "e": 26465, "s": 26394, "text": "If A is a vector, then it returns the cumulative product of sequence A" }, { "code": null, "e": 26546, "s": 26465, "text": "If A is a matrix, then it returns the cumulative product along each column of A." }, { "code": null, "e": 26557, "s": 26546, "text": "Example 1:" }, { "code": null, "e": 26564, "s": 26557, "text": "Matlab" }, { "code": "% Input vectorA = 2:8; B = cumprod(A); % Displays cumulative% products of Adisp(B)", "e": 26647, "s": 26564, "text": null }, { "code": null, "e": 26656, "s": 26647, "text": "Output :" }, { "code": null, "e": 26667, "s": 26656, "text": "Example 2:" }, { "code": null, "e": 26674, "s": 26667, "text": "Matlab" }, { "code": "% Input matrixA = [1 4 7; 2 5 8; 3 6 9];disp(\"Matrix :\")disp(A) B = cumprod(A);% Display cumulative product of matrix Adisp(\"Cumulative product :\")disp(B)", "e": 26829, "s": 26674, "text": null }, { "code": null, "e": 26838, "s": 26829, "text": "Output :" }, { "code": null, "e": 26902, "s": 26838, "text": "Returns the cumulative product of matrix A along with each dim." }, { "code": null, "e": 26931, "s": 26902, "text": "dim takes two values 1 or 2." }, { "code": null, "e": 26969, "s": 26931, "text": "dim = 1, refers to along each column." }, { "code": null, "e": 27001, "s": 26969, "text": "dim = 2, refers along each row." }, { "code": null, "e": 27008, "s": 27001, "text": "Matlab" }, { "code": "% input matrixA = [1 3 5; 2 4 6];disp(\"Matrix :\")disp(A) % Cumulative product along each% row from left to rightB = cumprod(A,2);disp(\"Cumulative product :\")disp(B);", "e": 27174, "s": 27008, "text": null }, { "code": null, "e": 27184, "s": 27174, "text": "Output : " }, { "code": null, "e": 27269, "s": 27184, "text": "Returns the cumulative product of the input vector or matrix in the given direction." }, { "code": null, "e": 27319, "s": 27269, "text": "direction takes two values ‘forward’ or ‘reverse’" }, { "code": null, "e": 27527, "s": 27319, "text": "If the direction is ‘reverse’, then calculates cumulative product in reverse i.e if we are considering matrix along each column, then it returns cumulative product starting from bottom to top of each column." }, { "code": null, "e": 27534, "s": 27527, "text": "Matlab" }, { "code": "% input matrixA = [1 3 5; 2 4 6];disp(\"Matrix :\")disp(A) % Cumulative product of A along each row% starting from right to leftB = cumprod(A,2,'reverse');disp(\"Cumulative product :\")disp(B)", "e": 27723, "s": 27534, "text": null }, { "code": null, "e": 27732, "s": 27723, "text": "Output :" }, { "code": null, "e": 27838, "s": 27732, "text": "nanflag value decides whether to include or exclude NaN value of the vector in cumulative product or not." }, { "code": null, "e": 27968, "s": 27838, "text": "nanflag takes two values ‘includenan’ or ‘omitnan’ corresponds to including NaN elements and excluding NaN elements respectively." }, { "code": null, "e": 28005, "s": 27968, "text": "‘omitNaN’ considers NaN values as 1." }, { "code": null, "e": 28030, "s": 28005, "text": "Note: NaN * number = NaN" }, { "code": null, "e": 28037, "s": 28030, "text": "Matlab" }, { "code": "% Input vectorA = [3 5 NaN 9 0 NaN];disp(\"Vector :\");disp(A); % Including NaN valuesB = cumprod(A,'includenan');disp(\"Cumulative product Include NaN :\");disp(B); % Excluding NaN valuesB = cumprod(A,'omitnan');disp(\"Cumulative product Exclude NaN :\");disp(B);", "e": 28296, "s": 28037, "text": null }, { "code": null, "e": 28306, "s": 28296, "text": " Output :" }, { "code": null, "e": 28315, "s": 28306, "text": "gabaa406" }, { "code": null, "e": 28330, "s": 28315, "text": "varshagumber28" }, { "code": null, "e": 28343, "s": 28330, "text": "MATLAB-Maths" }, { "code": null, "e": 28350, "s": 28343, "text": "Picked" }, { "code": null, "e": 28357, "s": 28350, "text": "MATLAB" }, { "code": null, "e": 28455, "s": 28357, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 28515, "s": 28455, "text": "Forward and Inverse Fourier Transform of an Image in MATLAB" }, { "code": null, "e": 28557, "s": 28515, "text": "Boundary Extraction of image using MATLAB" }, { "code": null, "e": 28630, "s": 28557, "text": "How to Remove Noise from Digital Image in Frequency Domain Using MATLAB?" }, { "code": null, "e": 28695, "s": 28630, "text": "How to Solve Histogram Equalization Numerical Problem in MATLAB?" }, { "code": null, "e": 28735, "s": 28695, "text": "How to Normalize a Histogram in MATLAB?" }, { "code": null, "e": 28796, "s": 28735, "text": "How to Remove Salt and Pepper Noise from Image Using MATLAB?" }, { "code": null, "e": 28822, "s": 28796, "text": "Double Integral in MATLAB" }, { "code": null, "e": 28851, "s": 28822, "text": "Classes and Object in MATLAB" }, { "code": null, "e": 28930, "s": 28851, "text": "How to Convert Three Channels of Colored Image into Grayscale Image in MATLAB?" } ]
ML | Getting Started With AlexNet - GeeksforGeeks
26 Mar, 2020 This article is focused on providing an introduction to the AlexNet architecture. Its name comes from one of the leading authors of the AlexNet paper– Alex Krizhevsky. It won the ImageNet Large Scale Visual Recognition Challenge (ILSVRC) 2012 with a top-5 error rate of 15.3% (beating the runner up which had a top-5 error rate of 26.2%). The most important features of the AlexNet paper are: As the model had to train 60 million parameters (which is quite a lot), it was prone to overfitting. According to the paper, the usage of Dropout and Data Augmentation significantly helped in reducing overfitting. The first and second fully connected layers in the architecture thus used a dropout of 0.5 for the purpose. Artificially increasing the number of images through data augmentation helped in the expansion of the dataset dynamically during runtime, which helped the model generalize better. Another distinct factor was using the ReLU activation function instead of tanh or sigmoid, which resulted in faster training times (a decrease in training time by 6 times). Deep Learning Networks usually employ ReLU non-linearity to achieve faster training times as the others start saturating when they hit higher activation values. The architecture consists of 5 Convolutional layers, with the 1st, 2nd and 5th having Max-Pooling layers for proper feature extraction. The Max-Pooling layers are overlapped having strides of 2 with filter size 3×3. This resulted in decreasing the top-1 and top-5 error rates by 0.4% and 0.3% respectively in comparison to non-overlapped Max-Pooling layers. They are followed by 2 fully-connected layers (each with dropout) and a softmax layer at the end for predictions. The figure below shows the architecture of AlexNet with all the layers defined. Code: Python code to implement AlexNet for object classification model = Sequential() # 1st Convolutional Layermodel.add(Conv2D(filters = 96, input_shape = (224, 224, 3), kernel_size = (11, 11), strides = (4, 4), padding = 'valid'))model.add(Activation('relu'))# Max-Pooling model.add(MaxPooling2D(pool_size = (2, 2), strides = (2, 2), padding = 'valid'))# Batch Normalisationmodel.add(BatchNormalization()) # 2nd Convolutional Layermodel.add(Conv2D(filters = 256, kernel_size = (11, 11), strides = (1, 1), padding = 'valid'))model.add(Activation('relu'))# Max-Poolingmodel.add(MaxPooling2D(pool_size = (2, 2), strides = (2, 2), padding = 'valid'))# Batch Normalisationmodel.add(BatchNormalization()) # 3rd Convolutional Layermodel.add(Conv2D(filters = 384, kernel_size = (3, 3), strides = (1, 1), padding = 'valid'))model.add(Activation('relu'))# Batch Normalisationmodel.add(BatchNormalization()) # 4th Convolutional Layermodel.add(Conv2D(filters = 384, kernel_size = (3, 3), strides = (1, 1), padding = 'valid'))model.add(Activation('relu'))# Batch Normalisationmodel.add(BatchNormalization()) # 5th Convolutional Layermodel.add(Conv2D(filters = 256, kernel_size = (3, 3), strides = (1, 1), padding = 'valid'))model.add(Activation('relu'))# Max-Poolingmodel.add(MaxPooling2D(pool_size = (2, 2), strides = (2, 2), padding = 'valid'))# Batch Normalisationmodel.add(BatchNormalization()) # Flatteningmodel.add(Flatten()) # 1st Dense Layermodel.add(Dense(4096, input_shape = (224*224*3, )))model.add(Activation('relu'))# Add Dropout to prevent overfittingmodel.add(Dropout(0.4))# Batch Normalisationmodel.add(BatchNormalization()) # 2nd Dense Layermodel.add(Dense(4096))model.add(Activation('relu'))# Add Dropoutmodel.add(Dropout(0.4))# Batch Normalisationmodel.add(BatchNormalization()) # Output Softmax Layermodel.add(Dense(num_classes))model.add(Activation('softmax')) Neural Network 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": "\n26 Mar, 2020" }, { "code": null, "e": 25928, "s": 25589, "text": "This article is focused on providing an introduction to the AlexNet architecture. Its name comes from one of the leading authors of the AlexNet paper– Alex Krizhevsky. It won the ImageNet Large Scale Visual Recognition Challenge (ILSVRC) 2012 with a top-5 error rate of 15.3% (beating the runner up which had a top-5 error rate of 26.2%)." }, { "code": null, "e": 25982, "s": 25928, "text": "The most important features of the AlexNet paper are:" }, { "code": null, "e": 26484, "s": 25982, "text": "As the model had to train 60 million parameters (which is quite a lot), it was prone to overfitting. According to the paper, the usage of Dropout and Data Augmentation significantly helped in reducing overfitting. The first and second fully connected layers in the architecture thus used a dropout of 0.5 for the purpose. Artificially increasing the number of images through data augmentation helped in the expansion of the dataset dynamically during runtime, which helped the model generalize better." }, { "code": null, "e": 26818, "s": 26484, "text": "Another distinct factor was using the ReLU activation function instead of tanh or sigmoid, which resulted in faster training times (a decrease in training time by 6 times). Deep Learning Networks usually employ ReLU non-linearity to achieve faster training times as the others start saturating when they hit higher activation values." }, { "code": null, "e": 27290, "s": 26818, "text": "The architecture consists of 5 Convolutional layers, with the 1st, 2nd and 5th having Max-Pooling layers for proper feature extraction. The Max-Pooling layers are overlapped having strides of 2 with filter size 3×3. This resulted in decreasing the top-1 and top-5 error rates by 0.4% and 0.3% respectively in comparison to non-overlapped Max-Pooling layers. They are followed by 2 fully-connected layers (each with dropout) and a softmax layer at the end for predictions." }, { "code": null, "e": 27370, "s": 27290, "text": "The figure below shows the architecture of AlexNet with all the layers defined." }, { "code": null, "e": 27435, "s": 27370, "text": "Code: Python code to implement AlexNet for object classification" }, { "code": "model = Sequential() # 1st Convolutional Layermodel.add(Conv2D(filters = 96, input_shape = (224, 224, 3), kernel_size = (11, 11), strides = (4, 4), padding = 'valid'))model.add(Activation('relu'))# Max-Pooling model.add(MaxPooling2D(pool_size = (2, 2), strides = (2, 2), padding = 'valid'))# Batch Normalisationmodel.add(BatchNormalization()) # 2nd Convolutional Layermodel.add(Conv2D(filters = 256, kernel_size = (11, 11), strides = (1, 1), padding = 'valid'))model.add(Activation('relu'))# Max-Poolingmodel.add(MaxPooling2D(pool_size = (2, 2), strides = (2, 2), padding = 'valid'))# Batch Normalisationmodel.add(BatchNormalization()) # 3rd Convolutional Layermodel.add(Conv2D(filters = 384, kernel_size = (3, 3), strides = (1, 1), padding = 'valid'))model.add(Activation('relu'))# Batch Normalisationmodel.add(BatchNormalization()) # 4th Convolutional Layermodel.add(Conv2D(filters = 384, kernel_size = (3, 3), strides = (1, 1), padding = 'valid'))model.add(Activation('relu'))# Batch Normalisationmodel.add(BatchNormalization()) # 5th Convolutional Layermodel.add(Conv2D(filters = 256, kernel_size = (3, 3), strides = (1, 1), padding = 'valid'))model.add(Activation('relu'))# Max-Poolingmodel.add(MaxPooling2D(pool_size = (2, 2), strides = (2, 2), padding = 'valid'))# Batch Normalisationmodel.add(BatchNormalization()) # Flatteningmodel.add(Flatten()) # 1st Dense Layermodel.add(Dense(4096, input_shape = (224*224*3, )))model.add(Activation('relu'))# Add Dropout to prevent overfittingmodel.add(Dropout(0.4))# Batch Normalisationmodel.add(BatchNormalization()) # 2nd Dense Layermodel.add(Dense(4096))model.add(Activation('relu'))# Add Dropoutmodel.add(Dropout(0.4))# Batch Normalisationmodel.add(BatchNormalization()) # Output Softmax Layermodel.add(Dense(num_classes))model.add(Activation('softmax'))", "e": 29357, "s": 27435, "text": null }, { "code": null, "e": 29372, "s": 29357, "text": "Neural Network" }, { "code": null, "e": 29389, "s": 29372, "text": "Machine Learning" }, { "code": null, "e": 29396, "s": 29389, "text": "Python" }, { "code": null, "e": 29413, "s": 29396, "text": "Machine Learning" }, { "code": null, "e": 29511, "s": 29413, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 29552, "s": 29511, "text": "Introduction to Recurrent Neural Network" }, { "code": null, "e": 29585, "s": 29552, "text": "Support Vector Machine Algorithm" }, { "code": null, "e": 29613, "s": 29585, "text": "Intuition of Adam Optimizer" }, { "code": null, "e": 29649, "s": 29613, "text": "CNN | Introduction to Pooling Layer" }, { "code": null, "e": 29704, "s": 29649, "text": "Convolutional Neural Network (CNN) in Machine Learning" }, { "code": null, "e": 29732, "s": 29704, "text": "Read JSON file using Python" }, { "code": null, "e": 29782, "s": 29732, "text": "Adding new column to existing DataFrame in Pandas" }, { "code": null, "e": 29804, "s": 29782, "text": "Python map() function" } ]
XOR of a subarray in C++
In this problem, we are given an arr[] and some queries that are range between L to R in the array. Our task is to print the XOR of the subarray between L to R. Let’s take an example to understand the problem, Input − array = {1, 4, 5, 7, 2, 9} L = 1 , R = 5 Output − Explanation − 4^5^7^2^9 To solve this problem, we will create an array, based on the following observation, To solve this problem, we will create an array, based on the following observation, We will XOR multiple bits, if there are odd number of 1s, the result will be 1 otherwise the result is 0. We will XOR multiple bits, if there are odd number of 1s, the result will be 1 otherwise the result is 0. Now, we will create a two-dimensional array count that will store the count of 1s. The value count[i][j] is the count of number of 1s for position i-j which is the number of 1’s that are present in subarray arr[0..j] at ith position of the bit. The number of 1s for all bits of the sub-array arr[L..R] is found using the count array. Formula to find arr[L...R] = count[i][R] - count[i][L-1]. If the number of 1s is odd, then ith bit is set in result. The final result can be obtained by summing up the power of 2 corresponding to ith bit given that it is set bit. Program to show the implementation of our solution, Live Demo #include <bits/stdc++.h> using namespace std; void preProcessArray(int arr[], int n, vector<vector<int> >& cnt) { int i, j; for (i = 0; i < 32; i++) { cnt[i][0] = 0; for (j = 0; j < n; j++) { if (j > 0) { cnt[i][j] = cnt[i][j - 1]; } if (arr[j] & (1 << i)) cnt[i][j]++; } } } int findXORofSubArray(int L, int R, const vector<vector<int> > count) { int result = 0; int noOfOnes; int i, j; for (i = 0; i < 32; i++) { noOfOnes = count[i][R] - ((L > 0) ? count[i][L - 1] : 0); if (noOfOnes & 1) { result+=(1 << i); } } return result; } int main(){ int arr[] = { 1, 4, 5, 7, 2, 9 }; int n = sizeof(arr) / sizeof(arr[0]); vector<vector<int> > count(32, vector<int>(n)); preProcessArray(arr, n, count); int L = 1; int R = 5; cout<<"The XOR of SubArray: "<<findXORofSubArray(L, R, count); return 0; } The XOR of SubArray: 13
[ { "code": null, "e": 1223, "s": 1062, "text": "In this problem, we are given an arr[] and some queries that are range between L to R in the array. Our task is to print the XOR of the subarray between L to R." }, { "code": null, "e": 1272, "s": 1223, "text": "Let’s take an example to understand the problem," }, { "code": null, "e": 1321, "s": 1272, "text": "Input − array = {1, 4, 5, 7, 2, 9} L = 1 , R = 5" }, { "code": null, "e": 1330, "s": 1321, "text": "Output −" }, { "code": null, "e": 1354, "s": 1330, "text": "Explanation − 4^5^7^2^9" }, { "code": null, "e": 1438, "s": 1354, "text": "To solve this problem, we will create an array, based on the following observation," }, { "code": null, "e": 1522, "s": 1438, "text": "To solve this problem, we will create an array, based on the following observation," }, { "code": null, "e": 1628, "s": 1522, "text": "We will XOR multiple bits, if there are odd number of 1s, the result will be 1 otherwise the result is 0." }, { "code": null, "e": 1734, "s": 1628, "text": "We will XOR multiple bits, if there are odd number of 1s, the result will be 1 otherwise the result is 0." }, { "code": null, "e": 2298, "s": 1734, "text": "Now, we will create a two-dimensional array count that will store the count of 1s. The value count[i][j] is the count of number of 1s for position i-j which is the number of 1’s that are present in subarray arr[0..j] at ith position of the bit. The number of 1s for all bits of the sub-array arr[L..R] is found using the count array. Formula to find arr[L...R] = count[i][R] - count[i][L-1]. If the number of 1s is odd, then ith bit is set in result. The final result can be obtained by summing up the power of 2 corresponding to ith bit given that it is set bit." }, { "code": null, "e": 2350, "s": 2298, "text": "Program to show the implementation of our solution," }, { "code": null, "e": 2361, "s": 2350, "text": " Live Demo" }, { "code": null, "e": 3298, "s": 2361, "text": "#include <bits/stdc++.h>\nusing namespace std;\nvoid preProcessArray(int arr[], int n, vector<vector<int> >& cnt) {\n int i, j;\n for (i = 0; i < 32; i++) {\n cnt[i][0] = 0;\n for (j = 0; j < n; j++) {\n if (j > 0) {\n cnt[i][j] = cnt[i][j - 1];\n }\n if (arr[j] & (1 << i))\n cnt[i][j]++;\n }\n }\n}\nint findXORofSubArray(int L, int R, const vector<vector<int> > count) {\n int result = 0;\n int noOfOnes;\n int i, j;\n for (i = 0; i < 32; i++) {\n noOfOnes = count[i][R] - ((L > 0) ? count[i][L - 1] : 0);\n if (noOfOnes & 1) {\n result+=(1 << i);\n }\n }\n return result;\n}\nint main(){\n int arr[] = { 1, 4, 5, 7, 2, 9 };\n int n = sizeof(arr) / sizeof(arr[0]);\n vector<vector<int> > count(32, vector<int>(n));\n preProcessArray(arr, n, count);\n int L = 1;\n int R = 5;\n cout<<\"The XOR of SubArray: \"<<findXORofSubArray(L, R, count);\n return 0;\n}" }, { "code": null, "e": 3322, "s": 3298, "text": "The XOR of SubArray: 13" } ]
Rexx - Debugging
Debugging is an important feature in any programming language. It helps the developer to diagnose errors, find the root cause and then resolve them accordingly. In Rexx, the trace utility is used for debugging. The trace instruction can be implemented in 2 ways, one is the batch mode and the other is the interactive mode. Let’s look at how to implement both options. The trace command is used to give a detailed level of each Rexx command which is executed. The general syntax of the trace statement is shown as follows − trace [setting] Where the setting can be anyone of the following options − A − Traces all the commands. A − Traces all the commands. C − Only traces the host commands which are sent to the operating system. C − Only traces the host commands which are sent to the operating system. E − Only traces the host commands which are sent to the operating system which have resulted in an error. E − Only traces the host commands which are sent to the operating system which have resulted in an error. F − Only traces the host commands which are sent to the operating system which have resulted in a failure. F − Only traces the host commands which are sent to the operating system which have resulted in a failure. I − This provides an intermediate level tracing of Rexx commands. I − This provides an intermediate level tracing of Rexx commands. L − This option is if you want to label the tracing as it happens. L − This option is if you want to label the tracing as it happens. N − This is the default option in which no tracing happens. N − This is the default option in which no tracing happens. Let’s take a look at an example of the trace command. /* Main program */ trace A /* Main program */ n = 100.45 if datatype( n, wholenumber ) then signal msg say 'This is a whole number' return 0 msg : say ' This is an incorrect number ' The output of the above program will be as follows − 5 *-* n = 100.45 if datatype( n, wholenumber ) then signal msg 7 *-* say 'This is a whole number This is a whole number 8 *-* return 0 From the output, you can see that an additional trace was added to the output of the program. The following things can be noted about the output − The line number along with the statement executed is added to the trace output. The line number along with the statement executed is added to the trace output. Each line that gets executed is shown in the trace output. Each line that gets executed is shown in the trace output. Trace can also be enabled with the help of the trace function. The general syntax and example are shown below. trace() The above function returns the current trace level. None The above function gives the current trace level. /* Main program */ say trace() /* Main program */ n = 100.45 if datatype( n, wholenumber ) then signal msg say 'This is a whole number' return 0 msg : say 'This is an incorrect number ' The output of the above program will be as follows. N This is an incorrect number The first line of N denotes that the trace is set to Normal. The trace level can be set with the trace function. The general syntax and example are shown below. trace(travel_level) trace_level − This is similar to the options available for setting the trace level. trace_level − This is similar to the options available for setting the trace level. The above function gives the current trace level. /* Main program */ say trace() current_trace = trace('A') say current_trace /* Main program */ n = 100.45 if datatype( n, wholenumber ) then signal msg say 'This is a whole number' return 0 msg : say ' This is an incorrect number ' The output of the above program will be as follows − N 4 *-* say current_trace N 6 *-* n = 100.45 7 *-* if \ datatype( n, wholenumber ) then 8 *-* signal msg 12 *-* say 'This is an incorrect number' 'This is an incorrect number' Interactive tracing is wherein, tracing is carried out as the program runs. Just like in an IDE such as Visual Studio for .Net, in which you can add breakpoints and see how each statement executes, similarly here also you can see the program as each code line runs. The general syntax is as follows − trace ?options Where, options are the same for the trace command as shown below. A − Traces all the commands A − Traces all the commands C − Only traces the host commands which are sent to the operating system. C − Only traces the host commands which are sent to the operating system. E − Only traces the host commands which are sent to the operating system which have resulted in an error. E − Only traces the host commands which are sent to the operating system which have resulted in an error. F − Only traces the host commands which are sent to the operating system which have resulted in a failure. F − Only traces the host commands which are sent to the operating system which have resulted in a failure. I − This provides an intermediate level tracing of Rexx commands. I − This provides an intermediate level tracing of Rexx commands. L − This option is if you want to label the tracing as it happens. L − This option is if you want to label the tracing as it happens. N − This is the default option in which no tracing happens. N − This is the default option in which no tracing happens. Let’s take a look at an example of implementing active tracing. /* Main program */ trace ?A /* Main program */ n = 100.45 if datatype( n, wholenumber ) then signal msg say 'This is a whole number' return 0 msg : say 'This is an incorrect number' The output of the above program will be as shown in the following program. The trace will stop at each line of code; then you need to press the Enter button to move onto the next line of code. This is an incorrect number +++ "LINUX COMMAND /home/cg/root/5798511/main.rex" 5 *-* n = 100.45 if datatype( n, wholenumber ) then +++ Interactive trace. "Trace Off" to end debug, ENTER to Continue. +++ 6 *-* signal msg 10 *-* msg : 10 *-* say 'This is an incorrect number' Print Add Notes Bookmark this page
[ { "code": null, "e": 2708, "s": 2339, "text": "Debugging is an important feature in any programming language. It helps the developer to diagnose errors, find the root cause and then resolve them accordingly. In Rexx, the trace utility is used for debugging. The trace instruction can be implemented in 2 ways, one is the batch mode and the other is the interactive mode. Let’s look at how to implement both options." }, { "code": null, "e": 2799, "s": 2708, "text": "The trace command is used to give a detailed level of each Rexx command which is executed." }, { "code": null, "e": 2863, "s": 2799, "text": "The general syntax of the trace statement is shown as follows −" }, { "code": null, "e": 2881, "s": 2863, "text": "trace [setting] \n" }, { "code": null, "e": 2940, "s": 2881, "text": "Where the setting can be anyone of the following options −" }, { "code": null, "e": 2969, "s": 2940, "text": "A − Traces all the commands." }, { "code": null, "e": 2998, "s": 2969, "text": "A − Traces all the commands." }, { "code": null, "e": 3072, "s": 2998, "text": "C − Only traces the host commands which are sent to the operating system." }, { "code": null, "e": 3146, "s": 3072, "text": "C − Only traces the host commands which are sent to the operating system." }, { "code": null, "e": 3252, "s": 3146, "text": "E − Only traces the host commands which are sent to the operating system which have resulted in an error." }, { "code": null, "e": 3358, "s": 3252, "text": "E − Only traces the host commands which are sent to the operating system which have resulted in an error." }, { "code": null, "e": 3465, "s": 3358, "text": "F − Only traces the host commands which are sent to the operating system which have resulted in a failure." }, { "code": null, "e": 3572, "s": 3465, "text": "F − Only traces the host commands which are sent to the operating system which have resulted in a failure." }, { "code": null, "e": 3638, "s": 3572, "text": "I − This provides an intermediate level tracing of Rexx commands." }, { "code": null, "e": 3704, "s": 3638, "text": "I − This provides an intermediate level tracing of Rexx commands." }, { "code": null, "e": 3771, "s": 3704, "text": "L − This option is if you want to label the tracing as it happens." }, { "code": null, "e": 3838, "s": 3771, "text": "L − This option is if you want to label the tracing as it happens." }, { "code": null, "e": 3898, "s": 3838, "text": "N − This is the default option in which no tracing happens." }, { "code": null, "e": 3958, "s": 3898, "text": "N − This is the default option in which no tracing happens." }, { "code": null, "e": 4012, "s": 3958, "text": "Let’s take a look at an example of the trace command." }, { "code": null, "e": 4209, "s": 4012, "text": "/* Main program */ \ntrace A \n\n/* Main program */ \nn = 100.45 if datatype( n, wholenumber ) then signal msg \n\nsay 'This is a whole number' \nreturn 0 \n\nmsg : \n say ' This is an incorrect number ' " }, { "code": null, "e": 4262, "s": 4209, "text": "The output of the above program will be as follows −" }, { "code": null, "e": 4455, "s": 4262, "text": "5 *-* n = 100.45 if datatype( n, wholenumber ) then signal msg\n 7 *-* say 'This is a whole number\nThis is a whole number \n 8 *-* return 0\n" }, { "code": null, "e": 4602, "s": 4455, "text": "From the output, you can see that an additional trace was added to the output of the program. The following things can be noted about the output −" }, { "code": null, "e": 4682, "s": 4602, "text": "The line number along with the statement executed is added to the trace output." }, { "code": null, "e": 4762, "s": 4682, "text": "The line number along with the statement executed is added to the trace output." }, { "code": null, "e": 4821, "s": 4762, "text": "Each line that gets executed is shown in the trace output." }, { "code": null, "e": 4880, "s": 4821, "text": "Each line that gets executed is shown in the trace output." }, { "code": null, "e": 4991, "s": 4880, "text": "Trace can also be enabled with the help of the trace function. The general syntax and example are shown below." }, { "code": null, "e": 5001, "s": 4991, "text": "trace() \n" }, { "code": null, "e": 5053, "s": 5001, "text": "The above function returns the current trace level." }, { "code": null, "e": 5058, "s": 5053, "text": "None" }, { "code": null, "e": 5108, "s": 5058, "text": "The above function gives the current trace level." }, { "code": null, "e": 5305, "s": 5108, "text": "/* Main program */ \nsay trace() \n\n/* Main program */ \nn = 100.45 if datatype( n, wholenumber ) then signal msg \n\nsay 'This is a whole number' \nreturn 0 \nmsg : \n\nsay 'This is an incorrect number ' " }, { "code": null, "e": 5357, "s": 5305, "text": "The output of the above program will be as follows." }, { "code": null, "e": 5390, "s": 5357, "text": "N \nThis is an incorrect number \n" }, { "code": null, "e": 5451, "s": 5390, "text": "The first line of N denotes that the trace is set to Normal." }, { "code": null, "e": 5551, "s": 5451, "text": "The trace level can be set with the trace function. The general syntax and example are shown below." }, { "code": null, "e": 5573, "s": 5551, "text": "trace(travel_level) \n" }, { "code": null, "e": 5657, "s": 5573, "text": "trace_level − This is similar to the options available for setting the trace level." }, { "code": null, "e": 5741, "s": 5657, "text": "trace_level − This is similar to the options available for setting the trace level." }, { "code": null, "e": 5791, "s": 5741, "text": "The above function gives the current trace level." }, { "code": null, "e": 6034, "s": 5791, "text": "/* Main program */ \nsay trace() \ncurrent_trace = trace('A') \nsay current_trace \n\n/* Main program */ \nn = 100.45 if datatype( n, wholenumber ) then \nsignal msg say 'This is a whole number' \nreturn 0 \nmsg : \nsay ' This is an incorrect number ' " }, { "code": null, "e": 6087, "s": 6034, "text": "The output of the above program will be as follows −" }, { "code": null, "e": 6287, "s": 6087, "text": "N \n 4 *-* say current_trace \nN \n 6 *-* n = 100.45 \n 7 *-* if \\ datatype( n, wholenumber ) then \n 8 *-* signal msg \n 12 *-* say 'This is an incorrect number' \n'This is an incorrect number' \n" }, { "code": null, "e": 6553, "s": 6287, "text": "Interactive tracing is wherein, tracing is carried out as the program runs. Just like in an IDE such as Visual Studio for .Net, in which you can add breakpoints and see how each statement executes, similarly here also you can see the program as each code line runs." }, { "code": null, "e": 6588, "s": 6553, "text": "The general syntax is as follows −" }, { "code": null, "e": 6605, "s": 6588, "text": "trace ?options \n" }, { "code": null, "e": 6671, "s": 6605, "text": "Where, options are the same for the trace command as shown below." }, { "code": null, "e": 6699, "s": 6671, "text": "A − Traces all the commands" }, { "code": null, "e": 6727, "s": 6699, "text": "A − Traces all the commands" }, { "code": null, "e": 6801, "s": 6727, "text": "C − Only traces the host commands which are sent to the operating system." }, { "code": null, "e": 6875, "s": 6801, "text": "C − Only traces the host commands which are sent to the operating system." }, { "code": null, "e": 6981, "s": 6875, "text": "E − Only traces the host commands which are sent to the operating system which have resulted in an error." }, { "code": null, "e": 7087, "s": 6981, "text": "E − Only traces the host commands which are sent to the operating system which have resulted in an error." }, { "code": null, "e": 7194, "s": 7087, "text": "F − Only traces the host commands which are sent to the operating system which have resulted in a failure." }, { "code": null, "e": 7301, "s": 7194, "text": "F − Only traces the host commands which are sent to the operating system which have resulted in a failure." }, { "code": null, "e": 7367, "s": 7301, "text": "I − This provides an intermediate level tracing of Rexx commands." }, { "code": null, "e": 7433, "s": 7367, "text": "I − This provides an intermediate level tracing of Rexx commands." }, { "code": null, "e": 7500, "s": 7433, "text": "L − This option is if you want to label the tracing as it happens." }, { "code": null, "e": 7567, "s": 7500, "text": "L − This option is if you want to label the tracing as it happens." }, { "code": null, "e": 7627, "s": 7567, "text": "N − This is the default option in which no tracing happens." }, { "code": null, "e": 7687, "s": 7627, "text": "N − This is the default option in which no tracing happens." }, { "code": null, "e": 7751, "s": 7687, "text": "Let’s take a look at an example of implementing active tracing." }, { "code": null, "e": 7942, "s": 7751, "text": "/* Main program */ \ntrace ?A\n\n/* Main program */ \nn = 100.45 if datatype( n, wholenumber ) then \nsignal msg \n\nsay 'This is a whole number' \nreturn 0 \nmsg : say 'This is an incorrect number' " }, { "code": null, "e": 8135, "s": 7942, "text": "The output of the above program will be as shown in the following program. The trace will stop at each line of code; then you need to press the Enter button to move onto the next line of code." }, { "code": null, "e": 8439, "s": 8135, "text": " This is an incorrect number\n +++ \"LINUX COMMAND /home/cg/root/5798511/main.rex\"\n 5 *-* n = 100.45 if datatype( n, wholenumber ) then \n+++ Interactive trace. \"Trace Off\" to end debug, ENTER to Continue. +++\n 6 *-* signal msg \n 10 *-* msg :\n 10 *-* say 'This is an incorrect number'\n" }, { "code": null, "e": 8446, "s": 8439, "text": " Print" }, { "code": null, "e": 8457, "s": 8446, "text": " Add Notes" } ]
XSD - Validation
We'll use Java based XSD validator to validate students.xml against the students.xsd. <?xml version = "1.0"?> <class> <student rollno = "393"> <firstname>Dinkar</firstname> <lastname>Kad</lastname> <nickname>Dinkar</nickname> <marks>85</marks> </student> <student rollno = "493"> <firstname>Vaneet</firstname> <lastname>Gupta</lastname> <nickname>Vinni</nickname> <marks>95</marks> </student> <student rollno = "593"> <firstname>Jasvir</firstname> <lastname>Singh</lastname> <nickname>Jazz</nickname> <marks>90</marks> </student> </class> <?xml version = "1.0"?> <xs:schema xmlns:xs = "http://www.w3.org/2001/XMLSchema"> <xs:element name = 'class'> <xs:complexType> <xs:sequence> <xs:element name = 'student' type = 'StudentType' minOccurs = '0' maxOccurs = 'unbounded' /> </xs:sequence> </xs:complexType> </xs:element> <xs:complexType name = "StudentType"> <xs:sequence> <xs:element name = "firstname" type = "xs:string"/> <xs:element name = "lastname" type = "xs:string"/> <xs:element name = "nickname" type = "xs:string"/> <xs:element name = "marks" type = "xs:positiveInteger"/> </xs:sequence> <xs:attribute name = 'rollno' type = 'xs:positiveInteger'/> </xs:complexType> </xs:schema> import java.io.File; import java.io.IOException; import javax.xml.XMLConstants; import javax.xml.transform.stream.StreamSource; import javax.xml.validation.Schema; import javax.xml.validation.SchemaFactory; import javax.xml.validation.Validator; import org.xml.sax.SAXException; public class XSDValidator { public static void main(String[] args) { if(args.length !=2){ System.out.println("Usage : XSDValidator <file-name.xsd> <file-name.xml>" ); } else { boolean isValid = validateXMLSchema(args[0],args[1]); if(isValid){ System.out.println(args[1] + " is valid against " + args[0]); } else { System.out.println(args[1] + " is not valid against " + args[0]); } } } public static boolean validateXMLSchema(String xsdPath, String xmlPath){ try { SchemaFactory factory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI); Schema schema = factory.newSchema(new File(xsdPath)); Validator validator = schema.newValidator(); validator.validate(new StreamSource(new File(xmlPath))); } catch (IOException e){ System.out.println("Exception: "+e.getMessage()); return false; }catch(SAXException e1){ System.out.println("SAX Exception: "+e1.getMessage()); return false; } return true; } } Copy the XSDValidator.java file to any location, say E: > java Copy the XSDValidator.java file to any location, say E: > java Copy the students.xml to same location E: > java Copy the students.xml to same location E: > java Copy the students.xsd to same location E: > java Copy the students.xsd to same location E: > java Compile XSDValidator.java using console. Make sure you have JDK 1.5 onwards installed on your machine and classpaths are configured. For details on how to use JAVA, see JAVA Tutorial Compile XSDValidator.java using console. Make sure you have JDK 1.5 onwards installed on your machine and classpaths are configured. For details on how to use JAVA, see JAVA Tutorial E:\java\javac XSDValidator.java Execute XSDValidator with students.xsd and students.xml passed as argument. Execute XSDValidator with students.xsd and students.xml passed as argument. E:\java\java XSDValidator students.xsd students.xml You'll see the following result − students.xml is valid against students.xsd Print Add Notes Bookmark this page
[ { "code": null, "e": 1790, "s": 1704, "text": "We'll use Java based XSD validator to validate students.xml against the students.xsd." }, { "code": null, "e": 2356, "s": 1790, "text": "<?xml version = \"1.0\"?>\n\n<class> \n <student rollno = \"393\">\n <firstname>Dinkar</firstname> \n <lastname>Kad</lastname>\n <nickname>Dinkar</nickname>\n <marks>85</marks>\t \n </student>\n \n <student rollno = \"493\">\t \n <firstname>Vaneet</firstname>\n <lastname>Gupta</lastname>\n <nickname>Vinni</nickname>\n <marks>95</marks>\n </student>\n \n <student rollno = \"593\"> \n <firstname>Jasvir</firstname>\n <lastname>Singh</lastname>\n <nickname>Jazz</nickname>\n <marks>90</marks>\n </student>\n</class>" }, { "code": null, "e": 3138, "s": 2356, "text": "<?xml version = \"1.0\"?>\n\n<xs:schema xmlns:xs = \"http://www.w3.org/2001/XMLSchema\">\n <xs:element name = 'class'>\n <xs:complexType>\n <xs:sequence>\n <xs:element name = 'student' type = 'StudentType' minOccurs = '0' \n maxOccurs = 'unbounded' />\n </xs:sequence>\n </xs:complexType>\n </xs:element>\n\n <xs:complexType name = \"StudentType\">\n <xs:sequence>\n <xs:element name = \"firstname\" type = \"xs:string\"/>\n <xs:element name = \"lastname\" type = \"xs:string\"/>\n <xs:element name = \"nickname\" type = \"xs:string\"/>\n <xs:element name = \"marks\" type = \"xs:positiveInteger\"/>\n </xs:sequence>\n <xs:attribute name = 'rollno' type = 'xs:positiveInteger'/>\n </xs:complexType>\t\t\t \n</xs:schema>" }, { "code": null, "e": 4572, "s": 3138, "text": "import java.io.File;\nimport java.io.IOException;\n\nimport javax.xml.XMLConstants;\nimport javax.xml.transform.stream.StreamSource;\n\nimport javax.xml.validation.Schema;\nimport javax.xml.validation.SchemaFactory;\nimport javax.xml.validation.Validator;\n\nimport org.xml.sax.SAXException;\n\npublic class XSDValidator {\n public static void main(String[] args) {\n if(args.length !=2){\n System.out.println(\"Usage : XSDValidator <file-name.xsd> <file-name.xml>\" );\n } else {\n boolean isValid = validateXMLSchema(args[0],args[1]);\n \n if(isValid){\n System.out.println(args[1] + \" is valid against \" + args[0]);\n } else {\n System.out.println(args[1] + \" is not valid against \" + args[0]);\n }\n }\n }\n \n public static boolean validateXMLSchema(String xsdPath, String xmlPath){\n try {\n SchemaFactory factory =\n SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);\n Schema schema = factory.newSchema(new File(xsdPath));\n Validator validator = schema.newValidator();\n validator.validate(new StreamSource(new File(xmlPath)));\n } catch (IOException e){\n System.out.println(\"Exception: \"+e.getMessage());\n return false;\n }catch(SAXException e1){\n System.out.println(\"SAX Exception: \"+e1.getMessage());\n return false;\n }\n\t\t\n return true;\n\t\n }\n}" }, { "code": null, "e": 4635, "s": 4572, "text": "Copy the XSDValidator.java file to any location, say E: > java" }, { "code": null, "e": 4698, "s": 4635, "text": "Copy the XSDValidator.java file to any location, say E: > java" }, { "code": null, "e": 4748, "s": 4698, "text": "Copy the students.xml to same location E: > java" }, { "code": null, "e": 4798, "s": 4748, "text": "Copy the students.xml to same location E: > java" }, { "code": null, "e": 4848, "s": 4798, "text": "Copy the students.xsd to same location E: > java" }, { "code": null, "e": 4898, "s": 4848, "text": "Copy the students.xsd to same location E: > java" }, { "code": null, "e": 5082, "s": 4898, "text": "Compile XSDValidator.java using console. Make sure you have JDK 1.5 onwards installed on your machine and classpaths are configured. For details on how to use JAVA, see JAVA Tutorial" }, { "code": null, "e": 5266, "s": 5082, "text": "Compile XSDValidator.java using console. Make sure you have JDK 1.5 onwards installed on your machine and classpaths are configured. For details on how to use JAVA, see JAVA Tutorial" }, { "code": null, "e": 5299, "s": 5266, "text": "E:\\java\\javac XSDValidator.java\n" }, { "code": null, "e": 5375, "s": 5299, "text": "Execute XSDValidator with students.xsd and students.xml passed as argument." }, { "code": null, "e": 5451, "s": 5375, "text": "Execute XSDValidator with students.xsd and students.xml passed as argument." }, { "code": null, "e": 5504, "s": 5451, "text": "E:\\java\\java XSDValidator students.xsd students.xml\n" }, { "code": null, "e": 5538, "s": 5504, "text": "You'll see the following result −" }, { "code": null, "e": 5582, "s": 5538, "text": "students.xml is valid against students.xsd\n" }, { "code": null, "e": 5589, "s": 5582, "text": " Print" }, { "code": null, "e": 5600, "s": 5589, "text": " Add Notes" } ]
Offsetting the Model — Logic to Implementation | by Ajay Tiwari | Towards Data Science
In our property and casualty insurance world very often we use a term called ‘offset’ which is widely used for modeling rate (count/exposure) such as the number of claims per exposure unit. This helps the model to transform the response variable from rate to count keeping coefficient as 1 by using simple algebra. This term may confuse the beginners, I had this question when I first introduced to this approach. Why can’t we manually derive a new response variable by simply dividing the count by its respective exposure instead of using an offset term? I will walk you through the log-likelihood functions of both versions, with and without offset to show the difference and highlight any discrepancies followed in the approach. One important point to be noted, offset should be included on the same “scale” as the linear predictor. In the case of a log link model, this requires the offset variable to be logged before inclusion in the model. Here is the regression model in its original form with an offset variable (Si), response variable Y, xi as independent variables and a set of parameters θ that can be estimated by maximum likelihood. This is achieved by just multiplying the exposure variable to the original form. Further, we can simplify this equation by taking natural logarithm both sides Now, this equation can be rewritten as a likelihood function in terms of θ as below Finally, we arrive at the log-likelihood equation of the first version (with offset), only terms dependent on θ will remain in the equation, other terms gets dropped out during differentiation: Let’s take a look at the other case when we are modeling rate (Yi/si) as the response variable, here is our new model equation. Again, we arrive at the same equation as we had in the first case. So, what is the difference? Both equations look the same. In the first case, we are assuming yi (count response) following a Poisson distribution, whereas in the second case we are assuming (yi/si)has a Poisson distribution, this second assumption is not appropriate which makes our model incorrect. Let’s take a look at the new likelihood function: The new equation after keeping only θ dependent terms during differentiation Now, we can compare log-likelihood functions (1) and (2), and observe the difference, both the approach will produce different outcomes. Also, we have seen, the second equation is based on a wrong assumption about the Poisson distribution, data is no more integers. Therefore, we can conclude that using a transformed rate variable as the response and without an offset is an incorrect approach. However, still, we have an option to correct the latter approach by applying a weight equivalent to exposure (si) to each observation. We can see the following equation is equivalent to equation (1). Let’s understand the difference in the implementation through the following R code examples. Similarly, these can be implemented in other modeling packages as well, both approaches will give the same output. #Implementation of equation (1) in Rpoi_r <- glm(numclaims ~ x1+x2+x3,data=train, family = "poisson", offset=log(exposure))#Implementation of equation (3) in Rpoi_r <- glm(numclaims/exposure ~ x1+x2+x3,data=train, family = "poisson", weight = exposure) There are cases when we already know the effect of an explanatory variable and rather than estimating parameters β for this variable, it is better to use available information. Another scenario, boosting a new model using an existing model output, e.g., you trained a model for 200 iterations, and later wanted to restart from there to finish another 300 iterations, instead of re-starting the process from scratch you can provide previous model output as base margin or offset. This implementation is quite easy and straight forward in R, SAS, Emblem (insurance industry-specific GLM software from Willis Tower Watson) and in statsmodels (a statistical modeling counterpart of sci-kit learn in python), whereas it’s less popular in machine learning models. Instead, they use some function to set the base score before training a new model, this base score can be used from an existing model or any known effect of a variable. As an alternative, this function of ML algorithms can help us in implementing offset while modeling rates. This implementation is possible in all the cases where Poisson, Gamma and Tweedie loss functions have been used with log-link. Offset in the case of a GLM in R can be achieved using the offset() function, similar implementation is possible for pscl, GBM, and glmnet packages. poi_r <- glm(numclaims ~ x1+x2+x3,data=train, family = "poisson", offset=log(exposure)) Offset in the case of a GLM in Python (statsmodels) can be achieved using the exposure() function, one important point to note here, this doesn’t require logged variable, the function itself will take care and log the variable. poi_py = sm.GLM(y_train, X_train, exposure = df_train.exposure, family=sm.families.Poisson()).fit() Offset in the case of XGBOOST in Python can be achieved using the set_base_margin() function, which requires a logged variable. In lightgbm, we can use set_init_score() before training. #Convert training data into DMatrixdtrain_offset = xgb.DMatrix(data=X_train.iloc[:,2:29],label=y_train)#Before training the model set a base margin into DMatrix dtrain_offset.set_base_margin(np.log(X_train['exposure'])) We discussed how Poisson regression can be used to model rate using an offset variable and how this functionality can be implemented in machine learning models. The examples of algorithms given here are not an exhaustive list, readers can explore other algorithms such as model-based decision trees and neural networks. Thanks for reading! I hope you find this article informative. xgboost.readthedocs.io lightgbm.readthedocs.io [3]Duncan Anderson and Team, 2007, A Practitioner’s Guide to Generalized Linear Models
[ { "code": null, "e": 486, "s": 171, "text": "In our property and casualty insurance world very often we use a term called ‘offset’ which is widely used for modeling rate (count/exposure) such as the number of claims per exposure unit. This helps the model to transform the response variable from rate to count keeping coefficient as 1 by using simple algebra." }, { "code": null, "e": 727, "s": 486, "text": "This term may confuse the beginners, I had this question when I first introduced to this approach. Why can’t we manually derive a new response variable by simply dividing the count by its respective exposure instead of using an offset term?" }, { "code": null, "e": 903, "s": 727, "text": "I will walk you through the log-likelihood functions of both versions, with and without offset to show the difference and highlight any discrepancies followed in the approach." }, { "code": null, "e": 1118, "s": 903, "text": "One important point to be noted, offset should be included on the same “scale” as the linear predictor. In the case of a log link model, this requires the offset variable to be logged before inclusion in the model." }, { "code": null, "e": 1399, "s": 1118, "text": "Here is the regression model in its original form with an offset variable (Si), response variable Y, xi as independent variables and a set of parameters θ that can be estimated by maximum likelihood. This is achieved by just multiplying the exposure variable to the original form." }, { "code": null, "e": 1477, "s": 1399, "text": "Further, we can simplify this equation by taking natural logarithm both sides" }, { "code": null, "e": 1561, "s": 1477, "text": "Now, this equation can be rewritten as a likelihood function in terms of θ as below" }, { "code": null, "e": 1755, "s": 1561, "text": "Finally, we arrive at the log-likelihood equation of the first version (with offset), only terms dependent on θ will remain in the equation, other terms gets dropped out during differentiation:" }, { "code": null, "e": 1883, "s": 1755, "text": "Let’s take a look at the other case when we are modeling rate (Yi/si) as the response variable, here is our new model equation." }, { "code": null, "e": 1950, "s": 1883, "text": "Again, we arrive at the same equation as we had in the first case." }, { "code": null, "e": 2008, "s": 1950, "text": "So, what is the difference? Both equations look the same." }, { "code": null, "e": 2250, "s": 2008, "text": "In the first case, we are assuming yi (count response) following a Poisson distribution, whereas in the second case we are assuming (yi/si)has a Poisson distribution, this second assumption is not appropriate which makes our model incorrect." }, { "code": null, "e": 2300, "s": 2250, "text": "Let’s take a look at the new likelihood function:" }, { "code": null, "e": 2377, "s": 2300, "text": "The new equation after keeping only θ dependent terms during differentiation" }, { "code": null, "e": 2773, "s": 2377, "text": "Now, we can compare log-likelihood functions (1) and (2), and observe the difference, both the approach will produce different outcomes. Also, we have seen, the second equation is based on a wrong assumption about the Poisson distribution, data is no more integers. Therefore, we can conclude that using a transformed rate variable as the response and without an offset is an incorrect approach." }, { "code": null, "e": 2973, "s": 2773, "text": "However, still, we have an option to correct the latter approach by applying a weight equivalent to exposure (si) to each observation. We can see the following equation is equivalent to equation (1)." }, { "code": null, "e": 3181, "s": 2973, "text": "Let’s understand the difference in the implementation through the following R code examples. Similarly, these can be implemented in other modeling packages as well, both approaches will give the same output." }, { "code": null, "e": 3434, "s": 3181, "text": "#Implementation of equation (1) in Rpoi_r <- glm(numclaims ~ x1+x2+x3,data=train, family = \"poisson\", offset=log(exposure))#Implementation of equation (3) in Rpoi_r <- glm(numclaims/exposure ~ x1+x2+x3,data=train, family = \"poisson\", weight = exposure)" }, { "code": null, "e": 3611, "s": 3434, "text": "There are cases when we already know the effect of an explanatory variable and rather than estimating parameters β for this variable, it is better to use available information." }, { "code": null, "e": 3913, "s": 3611, "text": "Another scenario, boosting a new model using an existing model output, e.g., you trained a model for 200 iterations, and later wanted to restart from there to finish another 300 iterations, instead of re-starting the process from scratch you can provide previous model output as base margin or offset." }, { "code": null, "e": 4361, "s": 3913, "text": "This implementation is quite easy and straight forward in R, SAS, Emblem (insurance industry-specific GLM software from Willis Tower Watson) and in statsmodels (a statistical modeling counterpart of sci-kit learn in python), whereas it’s less popular in machine learning models. Instead, they use some function to set the base score before training a new model, this base score can be used from an existing model or any known effect of a variable." }, { "code": null, "e": 4595, "s": 4361, "text": "As an alternative, this function of ML algorithms can help us in implementing offset while modeling rates. This implementation is possible in all the cases where Poisson, Gamma and Tweedie loss functions have been used with log-link." }, { "code": null, "e": 4744, "s": 4595, "text": "Offset in the case of a GLM in R can be achieved using the offset() function, similar implementation is possible for pscl, GBM, and glmnet packages." }, { "code": null, "e": 4832, "s": 4744, "text": "poi_r <- glm(numclaims ~ x1+x2+x3,data=train, family = \"poisson\", offset=log(exposure))" }, { "code": null, "e": 5060, "s": 4832, "text": "Offset in the case of a GLM in Python (statsmodels) can be achieved using the exposure() function, one important point to note here, this doesn’t require logged variable, the function itself will take care and log the variable." }, { "code": null, "e": 5160, "s": 5060, "text": "poi_py = sm.GLM(y_train, X_train, exposure = df_train.exposure, family=sm.families.Poisson()).fit()" }, { "code": null, "e": 5346, "s": 5160, "text": "Offset in the case of XGBOOST in Python can be achieved using the set_base_margin() function, which requires a logged variable. In lightgbm, we can use set_init_score() before training." }, { "code": null, "e": 5567, "s": 5346, "text": "#Convert training data into DMatrixdtrain_offset = xgb.DMatrix(data=X_train.iloc[:,2:29],label=y_train)#Before training the model set a base margin into DMatrix dtrain_offset.set_base_margin(np.log(X_train['exposure']))" }, { "code": null, "e": 5887, "s": 5567, "text": "We discussed how Poisson regression can be used to model rate using an offset variable and how this functionality can be implemented in machine learning models. The examples of algorithms given here are not an exhaustive list, readers can explore other algorithms such as model-based decision trees and neural networks." }, { "code": null, "e": 5949, "s": 5887, "text": "Thanks for reading! I hope you find this article informative." }, { "code": null, "e": 5972, "s": 5949, "text": "xgboost.readthedocs.io" }, { "code": null, "e": 5996, "s": 5972, "text": "lightgbm.readthedocs.io" } ]
Design a Turing Machine for equal number of a's and b's - GeeksforGeeks
03 Dec, 2020 Prerequisite – Turing Machine Task :Our task is to design a Turing Machine for an equal number of a’s and b’s. Analysis :Here the main thing to analyze that string consist of equal numbers of a’s and b’s can be of 4 types – Here ‘n’ is the count of a’s or b’s. a) a^n b^n like aabb b) b^n a^n like bbaa c) (ab)^n like abab d) (ba)^n like baba Example : Input-1 : aabb Output : Yes Input-2 : bababa Output : Yes Input-3 : aabbbb Output : No Input-4 : aaabbaa Output : No Approach : We have to scan the input from left to right. Convert first ‘a’ and first ‘b’ in the scanning to ‘X’, then in the second turn convert second ‘a’ and second ‘b’ to ‘X’ and so on. We have to repeat the process until we convert all a’s and b’s to ‘X’. Character scanned in between ‘a’ and ‘b’ will not be changed. Let us understand this approach by taking a string “aabb” – Scan the input from the left.Our string looks like this –Now we see that we get our first ‘a’ at the first position and first b in the third position. We convert these ‘a’ and ‘b’ to ‘X’.Now the character ‘a’ we get in between ‘a’ and ‘b’. So it will remain the same. When we read our first b we move our pointer to left. The pointer will move to the left until it gets a Blank(B). Now our string looks like this –Our pointer is at Blank(B). We again scan the input from left to right and convert second ‘a’ and second ‘b’ to ‘X’. When we read our second b we move our pointer to left. The pointer will move to the left until it gets a Blank(B). Now our string looks like this –We repeat this process until all a’s and b’s converted to X.As we see that we convert all a’s and b’s to ‘X’. Hence our machine will halt.When we analyze this process we see that we convert a’s and b’s to X in pair i.e. in point 3 we convert the first occurrence of a and b to X and then in point 4 we convert the second occurrence of a and b to X. If there are an unequal number of and b then, in this case, some a or b will be left in ou string, otherwise all the character will be converted to X. Hence it will give us a point to proof our condition that our string consists of an equal number of a’s and b’s. Scan the input from the left. Our string looks like this – Now we see that we get our first ‘a’ at the first position and first b in the third position. We convert these ‘a’ and ‘b’ to ‘X’.Now the character ‘a’ we get in between ‘a’ and ‘b’. So it will remain the same. When we read our first b we move our pointer to left. The pointer will move to the left until it gets a Blank(B). Now our string looks like this – Now the character ‘a’ we get in between ‘a’ and ‘b’. So it will remain the same. When we read our first b we move our pointer to left. The pointer will move to the left until it gets a Blank(B). Now our string looks like this – Our pointer is at Blank(B). We again scan the input from left to right and convert second ‘a’ and second ‘b’ to ‘X’. When we read our second b we move our pointer to left. The pointer will move to the left until it gets a Blank(B). Now our string looks like this – We repeat this process until all a’s and b’s converted to X. As we see that we convert all a’s and b’s to ‘X’. Hence our machine will halt. When we analyze this process we see that we convert a’s and b’s to X in pair i.e. in point 3 we convert the first occurrence of a and b to X and then in point 4 we convert the second occurrence of a and b to X. If there are an unequal number of and b then, in this case, some a or b will be left in ou string, otherwise all the character will be converted to X. Hence it will give us a point to proof our condition that our string consists of an equal number of a’s and b’s. Turing machine : Technical Scripter 2020 Technical Scripter Theory of Computation & Automata Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Difference between DFA and NFA Introduction of Finite Automata Regular Expressions, Regular Grammar and Regular Languages Conversion from NFA to DFA Pumping Lemma in Theory of Computation Chomsky Hierarchy in Theory of Computation Introduction of Pushdown Automata Turing Machine in TOC How to identify if a language is regular or not Difference between Mealy machine and Moore machine
[ { "code": null, "e": 24131, "s": 24103, "text": "\n03 Dec, 2020" }, { "code": null, "e": 24161, "s": 24131, "text": "Prerequisite – Turing Machine" }, { "code": null, "e": 24242, "s": 24161, "text": "Task :Our task is to design a Turing Machine for an equal number of a’s and b’s." }, { "code": null, "e": 24355, "s": 24242, "text": "Analysis :Here the main thing to analyze that string consist of equal numbers of a’s and b’s can be of 4 types –" }, { "code": null, "e": 24392, "s": 24355, "text": "Here ‘n’ is the count of a’s or b’s." }, { "code": null, "e": 24477, "s": 24392, "text": "a) a^n b^n like aabb\n\nb) b^n a^n like bbaa\n\nc) (ab)^n like abab\n\nd) (ba)^n like baba" }, { "code": null, "e": 24487, "s": 24477, "text": "Example :" }, { "code": null, "e": 24608, "s": 24487, "text": "Input-1 : aabb\nOutput : Yes\n\nInput-2 : bababa\nOutput : Yes\n\nInput-3 : aabbbb\nOutput : No\n\nInput-4 : aaabbaa\nOutput : No" }, { "code": null, "e": 24619, "s": 24608, "text": "Approach :" }, { "code": null, "e": 24665, "s": 24619, "text": "We have to scan the input from left to right." }, { "code": null, "e": 24868, "s": 24665, "text": "Convert first ‘a’ and first ‘b’ in the scanning to ‘X’, then in the second turn convert second ‘a’ and second ‘b’ to ‘X’ and so on. We have to repeat the process until we convert all a’s and b’s to ‘X’." }, { "code": null, "e": 24930, "s": 24868, "text": "Character scanned in between ‘a’ and ‘b’ will not be changed." }, { "code": null, "e": 24990, "s": 24930, "text": "Let us understand this approach by taking a string “aabb” –" }, { "code": null, "e": 26281, "s": 24990, "text": "Scan the input from the left.Our string looks like this –Now we see that we get our first ‘a’ at the first position and first b in the third position. We convert these ‘a’ and ‘b’ to ‘X’.Now the character ‘a’ we get in between ‘a’ and ‘b’. So it will remain the same. When we read our first b we move our pointer to left. The pointer will move to the left until it gets a Blank(B). Now our string looks like this –Our pointer is at Blank(B). We again scan the input from left to right and convert second ‘a’ and second ‘b’ to ‘X’. When we read our second b we move our pointer to left. The pointer will move to the left until it gets a Blank(B). Now our string looks like this –We repeat this process until all a’s and b’s converted to X.As we see that we convert all a’s and b’s to ‘X’. Hence our machine will halt.When we analyze this process we see that we convert a’s and b’s to X in pair i.e. in point 3 we convert the first occurrence of a and b to X and then in point 4 we convert the second occurrence of a and b to X. If there are an unequal number of and b then, in this case, some a or b will be left in ou string, otherwise all the character will be converted to X. Hence it will give us a point to proof our condition that our string consists of an equal number of a’s and b’s." }, { "code": null, "e": 26311, "s": 26281, "text": "Scan the input from the left." }, { "code": null, "e": 26340, "s": 26311, "text": "Our string looks like this –" }, { "code": null, "e": 26698, "s": 26340, "text": "Now we see that we get our first ‘a’ at the first position and first b in the third position. We convert these ‘a’ and ‘b’ to ‘X’.Now the character ‘a’ we get in between ‘a’ and ‘b’. So it will remain the same. When we read our first b we move our pointer to left. The pointer will move to the left until it gets a Blank(B). Now our string looks like this –" }, { "code": null, "e": 26926, "s": 26698, "text": "Now the character ‘a’ we get in between ‘a’ and ‘b’. So it will remain the same. When we read our first b we move our pointer to left. The pointer will move to the left until it gets a Blank(B). Now our string looks like this –" }, { "code": null, "e": 27191, "s": 26926, "text": "Our pointer is at Blank(B). We again scan the input from left to right and convert second ‘a’ and second ‘b’ to ‘X’. When we read our second b we move our pointer to left. The pointer will move to the left until it gets a Blank(B). Now our string looks like this –" }, { "code": null, "e": 27252, "s": 27191, "text": "We repeat this process until all a’s and b’s converted to X." }, { "code": null, "e": 27331, "s": 27252, "text": "As we see that we convert all a’s and b’s to ‘X’. Hence our machine will halt." }, { "code": null, "e": 27806, "s": 27331, "text": "When we analyze this process we see that we convert a’s and b’s to X in pair i.e. in point 3 we convert the first occurrence of a and b to X and then in point 4 we convert the second occurrence of a and b to X. If there are an unequal number of and b then, in this case, some a or b will be left in ou string, otherwise all the character will be converted to X. Hence it will give us a point to proof our condition that our string consists of an equal number of a’s and b’s." }, { "code": null, "e": 27823, "s": 27806, "text": "Turing machine :" }, { "code": null, "e": 27847, "s": 27823, "text": "Technical Scripter 2020" }, { "code": null, "e": 27866, "s": 27847, "text": "Technical Scripter" }, { "code": null, "e": 27899, "s": 27866, "text": "Theory of Computation & Automata" }, { "code": null, "e": 27997, "s": 27899, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 28006, "s": 27997, "text": "Comments" }, { "code": null, "e": 28019, "s": 28006, "text": "Old Comments" }, { "code": null, "e": 28050, "s": 28019, "text": "Difference between DFA and NFA" }, { "code": null, "e": 28082, "s": 28050, "text": "Introduction of Finite Automata" }, { "code": null, "e": 28141, "s": 28082, "text": "Regular Expressions, Regular Grammar and Regular Languages" }, { "code": null, "e": 28168, "s": 28141, "text": "Conversion from NFA to DFA" }, { "code": null, "e": 28207, "s": 28168, "text": "Pumping Lemma in Theory of Computation" }, { "code": null, "e": 28250, "s": 28207, "text": "Chomsky Hierarchy in Theory of Computation" }, { "code": null, "e": 28284, "s": 28250, "text": "Introduction of Pushdown Automata" }, { "code": null, "e": 28306, "s": 28284, "text": "Turing Machine in TOC" }, { "code": null, "e": 28354, "s": 28306, "text": "How to identify if a language is regular or not" } ]
For and While loops in Arduino
The for and while loops in Arduino follow the C language syntax. The syntax for the for loop is − for(iterator initialization; stop condition; increment instruction){ //Do something } for(int i = 0; i< 50; i++){ //Do something } Similarly, the syntax for the while loop is − while(condition){ //Do something } int i = 0 while(i < 50){ //Do something i = i+1; } The following example will illustrate the working of for and while loops in an Arduino program. void setup() { Serial.begin(9600); } void loop() { // put your main code here, to run repeatedly: int i = 0; for(i = 0; i< 10; i++){ Serial.println(i); } while(i < 20){ i = i+1; Serial.println(i); } } Note that we defined the integer i outside the for loop. Had I written for(int i = 0; i< 10; i++), then the scope of the variable i would have been restricted to the for loop only, and the while loop would not have been able to access it. The Serial Monitor output of the above program is shown below − As you can see, the two loops are sharing the variable, i. In order to write infinite loops, you can use the following syntax for for loops − for(;;){ //Do something continuously } And the following for the while loops − while(1){ //Do something continuously }
[ { "code": null, "e": 1127, "s": 1062, "text": "The for and while loops in Arduino follow the C language syntax." }, { "code": null, "e": 1160, "s": 1127, "text": "The syntax for the for loop is −" }, { "code": null, "e": 1249, "s": 1160, "text": "for(iterator initialization; stop condition; increment instruction){\n //Do something\n}" }, { "code": null, "e": 1297, "s": 1249, "text": "for(int i = 0; i< 50; i++){\n //Do something\n}" }, { "code": null, "e": 1343, "s": 1297, "text": "Similarly, the syntax for the while loop is −" }, { "code": null, "e": 1381, "s": 1343, "text": "while(condition){\n //Do something\n}" }, { "code": null, "e": 1438, "s": 1381, "text": "int i = 0\nwhile(i < 50){\n //Do something\n i = i+1;\n}" }, { "code": null, "e": 1534, "s": 1438, "text": "The following example will illustrate the working of for and while loops in an Arduino program." }, { "code": null, "e": 1790, "s": 1534, "text": "void setup() {\n Serial.begin(9600);\n}\nvoid loop() {\n // put your main code here, to run repeatedly:\n int i = 0;\n for(i = 0; i< 10; i++){\n Serial.println(i);\n }\n\n while(i < 20){\n i = i+1;\n Serial.println(i);\n }\n}" }, { "code": null, "e": 2030, "s": 1790, "text": "Note that we defined the integer i outside the for loop. Had I written for(int i = 0; i< 10; i++), then the scope of the variable i would have been restricted to the for loop only, and the while loop would not have been able to access it. " }, { "code": null, "e": 2094, "s": 2030, "text": "The Serial Monitor output of the above program is shown below −" }, { "code": null, "e": 2153, "s": 2094, "text": "As you can see, the two loops are sharing the variable, i." }, { "code": null, "e": 2236, "s": 2153, "text": "In order to write infinite loops, you can use the following syntax for for loops −" }, { "code": null, "e": 2278, "s": 2236, "text": "for(;;){\n //Do something continuously\n}" }, { "code": null, "e": 2318, "s": 2278, "text": "And the following for the while loops −" }, { "code": null, "e": 2361, "s": 2318, "text": "while(1){\n //Do something continuously\n}" } ]
How do I get interactive plots again in Spyder/Ipython/matplotlib?
To get interactive plots, we need to activate the figure. Using plt.ioff() and plt.ion(), we can perform interactive actions with plot. Create fig and ax variables using subplots method, where default nrows and ncols are 1. Create fig and ax variables using subplots method, where default nrows and ncols are 1. Draw a line, using plot() method. Draw a line, using plot() method. Set the color of the line, i.e., orange. Set the color of the line, i.e., orange. Stopped the interaction, using plt.ioff() method. Stopped the interaction, using plt.ioff() method. To make the interaction plots, change the color of the line coordinate. To make the interaction plots, change the color of the line coordinate. Start the interaction, using plt.ion() method. Start the interaction, using plt.ion() method. To use interactive plot in Ipython - In [1]: %matplotlib auto Using matplotlib backend: GTK3Agg In [2]: import matplotlib.pyplot as plt In [3]: fig, ax = plt.subplots() # Diagram will get popped up, Let’s interact. In [4]: ln, = ax.plot(range(5)) # Drawing a line In [5]: ln.set_color('orange') # Changing drawn line to orange In [6]: plt.ioff() # Stopped interaction In [7]: ln.set_color('green') # Since we have stopped the interaction in the last step In [8]: plt.ion() # Started interaction
[ { "code": null, "e": 1198, "s": 1062, "text": "To get interactive plots, we need to activate the figure. Using plt.ioff() and plt.ion(), we can perform interactive actions with plot." }, { "code": null, "e": 1286, "s": 1198, "text": "Create fig and ax variables using subplots method, where default nrows and ncols are 1." }, { "code": null, "e": 1374, "s": 1286, "text": "Create fig and ax variables using subplots method, where default nrows and ncols are 1." }, { "code": null, "e": 1408, "s": 1374, "text": "Draw a line, using plot() method." }, { "code": null, "e": 1442, "s": 1408, "text": "Draw a line, using plot() method." }, { "code": null, "e": 1483, "s": 1442, "text": "Set the color of the line, i.e., orange." }, { "code": null, "e": 1524, "s": 1483, "text": "Set the color of the line, i.e., orange." }, { "code": null, "e": 1574, "s": 1524, "text": "Stopped the interaction, using plt.ioff() method." }, { "code": null, "e": 1624, "s": 1574, "text": "Stopped the interaction, using plt.ioff() method." }, { "code": null, "e": 1696, "s": 1624, "text": "To make the interaction plots, change the color of the line coordinate." }, { "code": null, "e": 1768, "s": 1696, "text": "To make the interaction plots, change the color of the line coordinate." }, { "code": null, "e": 1815, "s": 1768, "text": "Start the interaction, using plt.ion() method." }, { "code": null, "e": 1862, "s": 1815, "text": "Start the interaction, using plt.ion() method." }, { "code": null, "e": 1899, "s": 1862, "text": "To use interactive plot in Ipython -" }, { "code": null, "e": 2412, "s": 1899, "text": "In [1]: %matplotlib auto\n\nUsing matplotlib backend: GTK3Agg\n\nIn [2]: import matplotlib.pyplot as plt\n\nIn [3]: fig, ax = plt.subplots() # Diagram will get popped up, Let’s interact.\n\nIn [4]: ln, = ax.plot(range(5)) # Drawing a line\n\nIn [5]: ln.set_color('orange') # Changing drawn line to orange\n\nIn [6]: plt.ioff() # Stopped interaction\n\nIn [7]: ln.set_color('green')\n# Since we have stopped the interaction in the last step\n\nIn [8]: plt.ion() # Started interaction" } ]
How to filter datasets using SQL. How use SQL to filter data from a table... | by Kate Marie Lewis | Towards Data Science
For the last few weeks I have been helping a small group of my friends learn SQL. They wanted to learn data science since they are stuck inside social distancing and have a lot more free time on their hands. I thought it was a great idea and offered to help guide them through it. This is our third lesson using SQL. If you would like to join in learning, feel free to go back to the first lesson and get stuck into it. Or if you just want to learn how to filter data using SQL I hope that you find this lesson helpful. In the previous lesson, we focused on different ways to select data from a table. Using The Walking Dead as an example, we selected all the data from a table, selected specific columns, selected a limited number of records, selected distinct values and ordered the results. We did this using the SELECT, SELECT DISTINCT, LIMIT, ORDER BY keywords. This lesson we can really get into some of the more commonly used functions of SQL. Now that we know how to make a table, put some data into it and select that data back out, we can learn how to manipulate the data when we select it. We will focus on learning to filter the table. Most importantly we will learn what a WHERE statement does. In addition, we will practice using the keywords AND, OR, LIKE, IN, BETWEEN and NOT in conjunction with WHERE. Charmed was one of my absolute favourite TV shows growing up. I used to tape each episode and then watch it several times with my sister before we would get a new episode the following week. That is why I chose to use the characters from charmed as the example for this week. We have a table of data about some of the characters in charmed, but we only want to select part of the table. The problem we have is we only want information on the blood related sisters and only the information about their active powers that were revealed before the year 2001. Throughout this lesson we will learn the techniques we need in order to select the data of interest from the table of Charmed information. The table below contains data about characters in Charmed. Each character can have multiple rows in the table if they have multiple powers. Furthermore, we have additional information about those powers, like the type and when the power was revealed. Adding a WHERE statement to a query means that the table will be filtered so that only the records that satisfy the condition after the WHERE statement will be returned. I have previously written an article comparing WHERE and HAVING in SQL in case you want to read another example of how to use WHERE. Below you can see one of the simplest versions of a WHERE clause. SELECT *FROM name_of_tableWHERE name_column_one = value_of_interest; Equals is not the only operator that you can use for a WHERE statement. Other common operators include: So depending on what result you want to achieve, you can use whichever operator suits your purposes. You may want to filter your data so that it meets two or more conditions. In that case you could use AND. For example, if you want one column to be equal to a value of interest and another column to only contain values greater than another value of interest, you would separate the two conditions with AND. In this case only records that satisfy all the conditions in the query will be returned. SELECT *FROM name_of_tableWHERE name_column_one = value_of_interest AND name_column_five > second_value_of_interest; If you don’t need your filters to be quite as strict and only need either one condition or another to be met, then you would use OR. By replacing AND with OR, it means that if a record meets one of the available conditions then it will be returned, rather than it having to meet both the conditions in the query. SELECT *FROM name_of_tableWHERE name_column_one = value_of_interest OR name_column_five > second_value_of_interest; If you want to get a bit tricky, you can even use OR and AND together. You just need to add brackets around the OR section so that condition is met first and then the AND condition will also need to be met. SELECT *FROM name_of_tableWHERE (name_column_one = value_of_interest OR name_column_five > second_value_of_interest) AND name_column_two != third_value_of_interest; In the case where you don’t want an exact match to a value, but rather you would like the condition to look for a pattern match, you can use LIKE. SELECT *FROM name_of_tableWHERE name_column_one LIKE pattern_of_interest; There are many pattern variations that you can use. To write them you use wildcards that consist of % or _. % is used to represent one, multiple characters or no characters at all. The % wildcard is very versatile. In contrast, _ is used to represent only a single character. Thus it allows you to be more specific in your pattern creation. Below is a table showing some example patterns that you could create with wildcards: There are many occasions where you might like to filter data based on a list of values. That is where the SQL keyword IN comes into play. It works the same way as if you used the equals sign in the WHERE statement with multiple OR conditions. It is just a much cleaner and simpler way of writing the query. The records returned only need to match one of the values in the list within the IN statement. SELECT *FROM name_of_tableWHERE name_column_one IN (value_1, value_2, value_3, value_4, value_5); If you want to get really tricky you can even put another query into the brackets to select the list of values. This type of query within another query is known as a subquery. SELECT *FROM name_of_tableWHERE name_column_one IN ( SELECT name_column_two FROM name_of_table); If you have a large range of values that you are interested in and don’t want to make a list containing every single one you can use the keyword BETWEEN. In this case you would supply a start value and an end value inclusive. These two values are separated by the AND keyword. Many different data types can be used as start and end values for BETWEEN. For example, you could use integers, floats, dates or strings. SELECT *FROM name_of_tableWHERE name_column_one BETWEEN value_1 AND value_2; If you want to exclude rather than include specific values, you can use the keyword NOT. In this case I have put NOT in front of an IN clause. As you would expect, only the records that do not match any of the values in the list will be returned. SELECT *FROM name_of_tableWHERE name_column_one NOT IN (value_1, value_2, value_3, value_4, value_5); NOT can also be used with other conditions too, not just IN. But I think that this is one of the most useful examples of using NOT. go to http://sqlfiddle.com/ (or you can use https://www.db-fiddle.com/ as I have found SQL fiddle has had some downtime recently)In the left hand box put the CREATE TABLE and INSERT INTO queries below go to http://sqlfiddle.com/ (or you can use https://www.db-fiddle.com/ as I have found SQL fiddle has had some downtime recently) In the left hand box put the CREATE TABLE and INSERT INTO queries below CREATE TABLE charmed( first_name varchar(255), last_name varchar(255), power varchar(255), power_type varchar(255), power_revealed date);INSERT INTO charmed( first_name, last_name, power, power_type, power_revealed)VALUES ('Phoebe', 'Halliwell', 'premonition', 'passive', '1998-10-07'), ('Piper', 'Halliwell', 'freeze time', 'active', '1998-10-07'), ('Prue', 'Halliwell', 'telekenesis', 'active', '1998-10-07'), ('Prue', 'Halliwell', 'astral projection', 'active', '2000-01-13'), ('Leo', 'Wyatt', 'healing', 'active', '1999-02-17'), ('Leo', 'Wyatt', 'orbing', 'active', '1999-02-17'), ('Paige', 'Matthews', 'orbing', 'active', '2001-10-04'), ('Phoebe', 'Halliwell', 'levitation', 'active', '2000-10-05'), ('Piper', 'Halliwell', 'molecular combustion', 'active', '2001-05-03'); 3. Click the build schema button 4. In the right hand box put your queries 5. Run the query below and see if it returns what you would expect it to: SELECT *FROM charmedWHERE power_type = 'active'; 6. Run the query below and see if it returns what you would expect it to: SELECT *FROM charmedWHERE power_type = 'active'AND power_revealed!='1998-10-07'; 7. Run the query below and see if it returns what you would expect it to: SELECT *FROM charmedWHERE power_type = 'active'OR power_revealed!='1998-10-07'; Note: Compare the results of this query to the previous query. All that has been changed is that OR had been substituted for AND 8. Run the query below and see if it returns what you would expect it to: SELECT *FROM charmedWHERE first_name LIKE 'P%'; 9. Run the query below and see if it returns what you would expect it to: SELECT *FROM charmedWHERE power IN ('orbing', 'healing'); 10. Run the query below and see if it returns what you would expect it to: SELECT *FROM charmedWHERE first_name NOT IN (SELECT first_name FROM charmed WHERE first_name LIKE 'P%'); 11. Run the query below and see if it returns what you would expect it to: SELECT *FROM charmedWHERE first_name NOT LIKE 'P%'; Note: Compare the results of this query to that from the previous query 12. Run the query below and see if it returns what you would expect it to: SELECT *FROM charmedWHERE power_revealed BETWEEN '1999-01-01' AND '2000-12-31'; 13. Run the query below and see if it returns what you would expect it to: SELECT *FROM charmedWHERE power BETWEEN 'astral projection' AND 'healing'; Exercise 1: Write a query that filters the table to only include the blood relatives (Prue, Piper, Phobe, Paige), only include the active powers and only include powers that were revealed before 2001. Exercise 2: See if there are any other ways that you can write a different query to select the same data as in the first exercise. The more different ways you can think of, the better. Try to use as many different SQL keywords from this lesson as you can. I feel like in this lesson we are really getting into the meat of what SQL can do after the more introductory lessons for the last few weeks. Our study group has gotten a little spread out in our progress as people have many other commitments. So the whole group has not completed this lesson yet. However, those that have did a great job. People seemed to like the open ended nature of exercise 2 and the challenge of trying to solve the same problem several different ways. Hopefully the busy members of the group will be able to catch up to the rest so that we can all be working on the same lesson again soon. Now that we know how to filter data, next lesson we will learn how to aggregate data. We will use the keywords MIN, MAX, COUNT, AVERAGE and SUM and have fun with a Spice Girls example. In addition to data, my other passion is painting. You can find my wildlife art at www.katemarielewis.com
[ { "code": null, "e": 452, "s": 171, "text": "For the last few weeks I have been helping a small group of my friends learn SQL. They wanted to learn data science since they are stuck inside social distancing and have a lot more free time on their hands. I thought it was a great idea and offered to help guide them through it." }, { "code": null, "e": 691, "s": 452, "text": "This is our third lesson using SQL. If you would like to join in learning, feel free to go back to the first lesson and get stuck into it. Or if you just want to learn how to filter data using SQL I hope that you find this lesson helpful." }, { "code": null, "e": 1038, "s": 691, "text": "In the previous lesson, we focused on different ways to select data from a table. Using The Walking Dead as an example, we selected all the data from a table, selected specific columns, selected a limited number of records, selected distinct values and ordered the results. We did this using the SELECT, SELECT DISTINCT, LIMIT, ORDER BY keywords." }, { "code": null, "e": 1319, "s": 1038, "text": "This lesson we can really get into some of the more commonly used functions of SQL. Now that we know how to make a table, put some data into it and select that data back out, we can learn how to manipulate the data when we select it. We will focus on learning to filter the table." }, { "code": null, "e": 1490, "s": 1319, "text": "Most importantly we will learn what a WHERE statement does. In addition, we will practice using the keywords AND, OR, LIKE, IN, BETWEEN and NOT in conjunction with WHERE." }, { "code": null, "e": 1766, "s": 1490, "text": "Charmed was one of my absolute favourite TV shows growing up. I used to tape each episode and then watch it several times with my sister before we would get a new episode the following week. That is why I chose to use the characters from charmed as the example for this week." }, { "code": null, "e": 2046, "s": 1766, "text": "We have a table of data about some of the characters in charmed, but we only want to select part of the table. The problem we have is we only want information on the blood related sisters and only the information about their active powers that were revealed before the year 2001." }, { "code": null, "e": 2185, "s": 2046, "text": "Throughout this lesson we will learn the techniques we need in order to select the data of interest from the table of Charmed information." }, { "code": null, "e": 2436, "s": 2185, "text": "The table below contains data about characters in Charmed. Each character can have multiple rows in the table if they have multiple powers. Furthermore, we have additional information about those powers, like the type and when the power was revealed." }, { "code": null, "e": 2739, "s": 2436, "text": "Adding a WHERE statement to a query means that the table will be filtered so that only the records that satisfy the condition after the WHERE statement will be returned. I have previously written an article comparing WHERE and HAVING in SQL in case you want to read another example of how to use WHERE." }, { "code": null, "e": 2805, "s": 2739, "text": "Below you can see one of the simplest versions of a WHERE clause." }, { "code": null, "e": 2884, "s": 2805, "text": "SELECT *FROM name_of_tableWHERE name_column_one = value_of_interest;" }, { "code": null, "e": 2988, "s": 2884, "text": "Equals is not the only operator that you can use for a WHERE statement. Other common operators include:" }, { "code": null, "e": 3089, "s": 2988, "text": "So depending on what result you want to achieve, you can use whichever operator suits your purposes." }, { "code": null, "e": 3485, "s": 3089, "text": "You may want to filter your data so that it meets two or more conditions. In that case you could use AND. For example, if you want one column to be equal to a value of interest and another column to only contain values greater than another value of interest, you would separate the two conditions with AND. In this case only records that satisfy all the conditions in the query will be returned." }, { "code": null, "e": 3616, "s": 3485, "text": "SELECT *FROM name_of_tableWHERE name_column_one = value_of_interest AND name_column_five > second_value_of_interest;" }, { "code": null, "e": 3929, "s": 3616, "text": "If you don’t need your filters to be quite as strict and only need either one condition or another to be met, then you would use OR. By replacing AND with OR, it means that if a record meets one of the available conditions then it will be returned, rather than it having to meet both the conditions in the query." }, { "code": null, "e": 4059, "s": 3929, "text": "SELECT *FROM name_of_tableWHERE name_column_one = value_of_interest OR name_column_five > second_value_of_interest;" }, { "code": null, "e": 4266, "s": 4059, "text": "If you want to get a bit tricky, you can even use OR and AND together. You just need to add brackets around the OR section so that condition is met first and then the AND condition will also need to be met." }, { "code": null, "e": 4455, "s": 4266, "text": "SELECT *FROM name_of_tableWHERE (name_column_one = value_of_interest OR name_column_five > second_value_of_interest) AND name_column_two != third_value_of_interest;" }, { "code": null, "e": 4602, "s": 4455, "text": "In the case where you don’t want an exact match to a value, but rather you would like the condition to look for a pattern match, you can use LIKE." }, { "code": null, "e": 4686, "s": 4602, "text": "SELECT *FROM name_of_tableWHERE name_column_one LIKE pattern_of_interest;" }, { "code": null, "e": 5027, "s": 4686, "text": "There are many pattern variations that you can use. To write them you use wildcards that consist of % or _. % is used to represent one, multiple characters or no characters at all. The % wildcard is very versatile. In contrast, _ is used to represent only a single character. Thus it allows you to be more specific in your pattern creation." }, { "code": null, "e": 5112, "s": 5027, "text": "Below is a table showing some example patterns that you could create with wildcards:" }, { "code": null, "e": 5514, "s": 5112, "text": "There are many occasions where you might like to filter data based on a list of values. That is where the SQL keyword IN comes into play. It works the same way as if you used the equals sign in the WHERE statement with multiple OR conditions. It is just a much cleaner and simpler way of writing the query. The records returned only need to match one of the values in the list within the IN statement." }, { "code": null, "e": 5622, "s": 5514, "text": "SELECT *FROM name_of_tableWHERE name_column_one IN (value_1, value_2, value_3, value_4, value_5);" }, { "code": null, "e": 5798, "s": 5622, "text": "If you want to get really tricky you can even put another query into the brackets to select the list of values. This type of query within another query is known as a subquery." }, { "code": null, "e": 5944, "s": 5798, "text": "SELECT *FROM name_of_tableWHERE name_column_one IN ( SELECT name_column_two FROM name_of_table);" }, { "code": null, "e": 6221, "s": 5944, "text": "If you have a large range of values that you are interested in and don’t want to make a list containing every single one you can use the keyword BETWEEN. In this case you would supply a start value and an end value inclusive. These two values are separated by the AND keyword." }, { "code": null, "e": 6359, "s": 6221, "text": "Many different data types can be used as start and end values for BETWEEN. For example, you could use integers, floats, dates or strings." }, { "code": null, "e": 6446, "s": 6359, "text": "SELECT *FROM name_of_tableWHERE name_column_one BETWEEN value_1 AND value_2;" }, { "code": null, "e": 6693, "s": 6446, "text": "If you want to exclude rather than include specific values, you can use the keyword NOT. In this case I have put NOT in front of an IN clause. As you would expect, only the records that do not match any of the values in the list will be returned." }, { "code": null, "e": 6805, "s": 6693, "text": "SELECT *FROM name_of_tableWHERE name_column_one NOT IN (value_1, value_2, value_3, value_4, value_5);" }, { "code": null, "e": 6937, "s": 6805, "text": "NOT can also be used with other conditions too, not just IN. But I think that this is one of the most useful examples of using NOT." }, { "code": null, "e": 7138, "s": 6937, "text": "go to http://sqlfiddle.com/ (or you can use https://www.db-fiddle.com/ as I have found SQL fiddle has had some downtime recently)In the left hand box put the CREATE TABLE and INSERT INTO queries below" }, { "code": null, "e": 7268, "s": 7138, "text": "go to http://sqlfiddle.com/ (or you can use https://www.db-fiddle.com/ as I have found SQL fiddle has had some downtime recently)" }, { "code": null, "e": 7340, "s": 7268, "text": "In the left hand box put the CREATE TABLE and INSERT INTO queries below" }, { "code": null, "e": 8178, "s": 7340, "text": "CREATE TABLE charmed( first_name varchar(255), last_name varchar(255), power varchar(255), power_type varchar(255), power_revealed date);INSERT INTO charmed( first_name, last_name, power, power_type, power_revealed)VALUES ('Phoebe', 'Halliwell', 'premonition', 'passive', '1998-10-07'), ('Piper', 'Halliwell', 'freeze time', 'active', '1998-10-07'), ('Prue', 'Halliwell', 'telekenesis', 'active', '1998-10-07'), ('Prue', 'Halliwell', 'astral projection', 'active', '2000-01-13'), ('Leo', 'Wyatt', 'healing', 'active', '1999-02-17'), ('Leo', 'Wyatt', 'orbing', 'active', '1999-02-17'), ('Paige', 'Matthews', 'orbing', 'active', '2001-10-04'), ('Phoebe', 'Halliwell', 'levitation', 'active', '2000-10-05'), ('Piper', 'Halliwell', 'molecular combustion', 'active', '2001-05-03');" }, { "code": null, "e": 8211, "s": 8178, "text": "3. Click the build schema button" }, { "code": null, "e": 8253, "s": 8211, "text": "4. In the right hand box put your queries" }, { "code": null, "e": 8327, "s": 8253, "text": "5. Run the query below and see if it returns what you would expect it to:" }, { "code": null, "e": 8386, "s": 8327, "text": "SELECT *FROM charmedWHERE power_type = 'active';" }, { "code": null, "e": 8460, "s": 8386, "text": "6. Run the query below and see if it returns what you would expect it to:" }, { "code": null, "e": 8554, "s": 8460, "text": "SELECT *FROM charmedWHERE power_type = 'active'AND power_revealed!='1998-10-07';" }, { "code": null, "e": 8628, "s": 8554, "text": "7. Run the query below and see if it returns what you would expect it to:" }, { "code": null, "e": 8721, "s": 8628, "text": "SELECT *FROM charmedWHERE power_type = 'active'OR power_revealed!='1998-10-07';" }, { "code": null, "e": 8850, "s": 8721, "text": "Note: Compare the results of this query to the previous query. All that has been changed is that OR had been substituted for AND" }, { "code": null, "e": 8924, "s": 8850, "text": "8. Run the query below and see if it returns what you would expect it to:" }, { "code": null, "e": 8982, "s": 8924, "text": "SELECT *FROM charmedWHERE first_name LIKE 'P%';" }, { "code": null, "e": 9056, "s": 8982, "text": "9. Run the query below and see if it returns what you would expect it to:" }, { "code": null, "e": 9124, "s": 9056, "text": "SELECT *FROM charmedWHERE power IN ('orbing', 'healing');" }, { "code": null, "e": 9199, "s": 9124, "text": "10. Run the query below and see if it returns what you would expect it to:" }, { "code": null, "e": 9437, "s": 9199, "text": "SELECT *FROM charmedWHERE first_name NOT IN (SELECT first_name FROM charmed WHERE first_name LIKE 'P%');" }, { "code": null, "e": 9512, "s": 9437, "text": "11. Run the query below and see if it returns what you would expect it to:" }, { "code": null, "e": 9574, "s": 9512, "text": "SELECT *FROM charmedWHERE first_name NOT LIKE 'P%';" }, { "code": null, "e": 9646, "s": 9574, "text": "Note: Compare the results of this query to that from the previous query" }, { "code": null, "e": 9721, "s": 9646, "text": "12. Run the query below and see if it returns what you would expect it to:" }, { "code": null, "e": 9811, "s": 9721, "text": "SELECT *FROM charmedWHERE power_revealed BETWEEN '1999-01-01' AND '2000-12-31';" }, { "code": null, "e": 9886, "s": 9811, "text": "13. Run the query below and see if it returns what you would expect it to:" }, { "code": null, "e": 9971, "s": 9886, "text": "SELECT *FROM charmedWHERE power BETWEEN 'astral projection' AND 'healing';" }, { "code": null, "e": 10172, "s": 9971, "text": "Exercise 1: Write a query that filters the table to only include the blood relatives (Prue, Piper, Phobe, Paige), only include the active powers and only include powers that were revealed before 2001." }, { "code": null, "e": 10428, "s": 10172, "text": "Exercise 2: See if there are any other ways that you can write a different query to select the same data as in the first exercise. The more different ways you can think of, the better. Try to use as many different SQL keywords from this lesson as you can." }, { "code": null, "e": 10726, "s": 10428, "text": "I feel like in this lesson we are really getting into the meat of what SQL can do after the more introductory lessons for the last few weeks. Our study group has gotten a little spread out in our progress as people have many other commitments. So the whole group has not completed this lesson yet." }, { "code": null, "e": 10904, "s": 10726, "text": "However, those that have did a great job. People seemed to like the open ended nature of exercise 2 and the challenge of trying to solve the same problem several different ways." }, { "code": null, "e": 11042, "s": 10904, "text": "Hopefully the busy members of the group will be able to catch up to the rest so that we can all be working on the same lesson again soon." }, { "code": null, "e": 11227, "s": 11042, "text": "Now that we know how to filter data, next lesson we will learn how to aggregate data. We will use the keywords MIN, MAX, COUNT, AVERAGE and SUM and have fun with a Spice Girls example." } ]
An introduction to Flowcharts - GeeksforGeeks
18 Apr, 2022 What is a Flowchart? Flowchart is a graphical representation of an algorithm. Programmers often use it as a program-planning tool to solve a problem. It makes use of symbols which are connected among them to indicate the flow of information and processing. The process of drawing a flowchart for an algorithm is known as “flowcharting”. Basic Symbols used in Flowchart Designs Terminal: The oval symbol indicates Start, Stop and Halt in a program’s logic flow. A pause/halt is generally used in a program logic under some error conditions. Terminal is the first and last symbols in the flowchart. Terminal: The oval symbol indicates Start, Stop and Halt in a program’s logic flow. A pause/halt is generally used in a program logic under some error conditions. Terminal is the first and last symbols in the flowchart. Input/Output: A parallelogram denotes any function of input/output type. Program instructions that take input from input devices and display output on output devices are indicated with parallelogram in a flowchart. Processing: A box represents arithmetic instructions. All arithmetic processes such as adding, subtracting, multiplication and division are indicated by action or process symbol. Decision Diamond symbol represents a decision point. Decision based operations such as yes/no question or true/false are indicated by diamond in flowchart. Connectors: Whenever flowchart becomes complex or it spreads over more than one page, it is useful to use connectors to avoid any confusions. It is represented by a circle. Flow lines: Flow lines indicate the exact sequence in which instructions are executed. Arrows represent the direction of flow of control and relationship among different symbols of flowchart. Advantages of Flowchart: Flowcharts are a better way of communicating the logic of the system. Flowcharts act as a guide for blueprint during program designed. Flowcharts help in debugging process. With the help of flowcharts programs can be easily analyzed. It provides better documentation. Flowcharts serve as a good proper documentation. Disadvantages of Flowchart: It is difficult to draw flowcharts for large and complex programs. There is no standard to determine the amount of detail. Difficult to reproduce the flowcharts. It is very difficult to modify the Flowchart. Example : Draw a flowchart to input two numbers from the user and display the largest of two numbers C C++ Java C# // C program to find largest of two numbers #include <stdio.h> int main(){ int num1, num2, largest; /*Input two numbers*/ printf("Enter two numbers:\n"); scanf("%d%d", &num1, &num2); /*check if a is greater than b*/ if (num1 > num2) largest = num1; else largest = num2; /*Print the largest number*/ printf("%d", largest); return 0;} // C++ program to find largest of two numbers#include <iostream>using namespace std;int main(){ int num1, num2, largest; /*Input two numbers*/ cout << "Enter two numbers:\n"; cin >> num1; cin >> num2; /*check if a is greater than b*/ if (num1 > num2) largest = num1; else largest = num2; /*Print the largest number*/ cout << largest; return 0;} // Java program to find largest of two numbersimport java.util.Scanner;public class largest { public static void main(String args[]) { int num1, num2, max; /*Input two numbers*/ Scanner sc = new Scanner(System.in); System.out.println("Enter two numbers:"); num1 = sc.nextInt(); num2 = sc.nextInt(); /*check whether a is greater than b or not*/ if (num1 > num2) max = num1; else max = num2; /*Print the largest number*/ System.out.println(max); }} // C# program to find largest of two numbersusing System;using System.IO; class GFG{ static public void Main () { int num1, num2, max; /*Input two numbers*/ Console.WriteLine("Enter two numbers:"); num1 = Convert.ToInt32(Console.ReadLine()); num2 = Convert.ToInt32(Console.ReadLine()); /*check whether a is greater than b or not*/ if (num1 > num2) max = num1; else max = num2; /*Print the largest number*/ Console.WriteLine(max); }} // This code is contributed by NamrataSrivastava1 Output Enter two numbers: 10 30 30 References: Computer Fundamentals by Pradeep K. Sinha and Priti Sinha RishabhPrabhu srinam itskawal2000 yatindracr7 CBSE - Class 11 school-programming Design Pattern School Programming Technical Scripter Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Strategy Pattern | Set 1 (Introduction) Difference between Sequence diagram and Collaboration diagram Template Method Design Pattern State Design Pattern Visitor design pattern Python Dictionary Arrays in C/C++ Inheritance in C++ Reverse a string in Java C++ Classes and Objects
[ { "code": null, "e": 25934, "s": 25906, "text": "\n18 Apr, 2022" }, { "code": null, "e": 26272, "s": 25934, "text": "What is a Flowchart? Flowchart is a graphical representation of an algorithm. Programmers often use it as a program-planning tool to solve a problem. It makes use of symbols which are connected among them to indicate the flow of information and processing. The process of drawing a flowchart for an algorithm is known as “flowcharting”. " }, { "code": null, "e": 26312, "s": 26272, "text": "Basic Symbols used in Flowchart Designs" }, { "code": null, "e": 26534, "s": 26312, "text": "Terminal: The oval symbol indicates Start, Stop and Halt in a program’s logic flow. A pause/halt is generally used in a program logic under some error conditions. Terminal is the first and last symbols in the flowchart. " }, { "code": null, "e": 26756, "s": 26534, "text": "Terminal: The oval symbol indicates Start, Stop and Halt in a program’s logic flow. A pause/halt is generally used in a program logic under some error conditions. Terminal is the first and last symbols in the flowchart. " }, { "code": null, "e": 26973, "s": 26756, "text": "Input/Output: A parallelogram denotes any function of input/output type. Program instructions that take input from input devices and display output on output devices are indicated with parallelogram in a flowchart. " }, { "code": null, "e": 27154, "s": 26973, "text": "Processing: A box represents arithmetic instructions. All arithmetic processes such as adding, subtracting, multiplication and division are indicated by action or process symbol. " }, { "code": null, "e": 27312, "s": 27154, "text": "Decision Diamond symbol represents a decision point. Decision based operations such as yes/no question or true/false are indicated by diamond in flowchart. " }, { "code": null, "e": 27487, "s": 27312, "text": "Connectors: Whenever flowchart becomes complex or it spreads over more than one page, it is useful to use connectors to avoid any confusions. It is represented by a circle. " }, { "code": null, "e": 27681, "s": 27487, "text": "Flow lines: Flow lines indicate the exact sequence in which instructions are executed. Arrows represent the direction of flow of control and relationship among different symbols of flowchart. " }, { "code": null, "e": 27706, "s": 27681, "text": "Advantages of Flowchart:" }, { "code": null, "e": 27776, "s": 27706, "text": "Flowcharts are a better way of communicating the logic of the system." }, { "code": null, "e": 27841, "s": 27776, "text": "Flowcharts act as a guide for blueprint during program designed." }, { "code": null, "e": 27879, "s": 27841, "text": "Flowcharts help in debugging process." }, { "code": null, "e": 27940, "s": 27879, "text": "With the help of flowcharts programs can be easily analyzed." }, { "code": null, "e": 27974, "s": 27940, "text": "It provides better documentation." }, { "code": null, "e": 28023, "s": 27974, "text": "Flowcharts serve as a good proper documentation." }, { "code": null, "e": 28051, "s": 28023, "text": "Disadvantages of Flowchart:" }, { "code": null, "e": 28118, "s": 28051, "text": "It is difficult to draw flowcharts for large and complex programs." }, { "code": null, "e": 28174, "s": 28118, "text": "There is no standard to determine the amount of detail." }, { "code": null, "e": 28213, "s": 28174, "text": "Difficult to reproduce the flowcharts." }, { "code": null, "e": 28259, "s": 28213, "text": "It is very difficult to modify the Flowchart." }, { "code": null, "e": 28362, "s": 28259, "text": "Example : Draw a flowchart to input two numbers from the user and display the largest of two numbers " }, { "code": null, "e": 28366, "s": 28364, "text": "C" }, { "code": null, "e": 28370, "s": 28366, "text": "C++" }, { "code": null, "e": 28375, "s": 28370, "text": "Java" }, { "code": null, "e": 28378, "s": 28375, "text": "C#" }, { "code": "// C program to find largest of two numbers #include <stdio.h> int main(){ int num1, num2, largest; /*Input two numbers*/ printf(\"Enter two numbers:\\n\"); scanf(\"%d%d\", &num1, &num2); /*check if a is greater than b*/ if (num1 > num2) largest = num1; else largest = num2; /*Print the largest number*/ printf(\"%d\", largest); return 0;}", "e": 28759, "s": 28378, "text": null }, { "code": "// C++ program to find largest of two numbers#include <iostream>using namespace std;int main(){ int num1, num2, largest; /*Input two numbers*/ cout << \"Enter two numbers:\\n\"; cin >> num1; cin >> num2; /*check if a is greater than b*/ if (num1 > num2) largest = num1; else largest = num2; /*Print the largest number*/ cout << largest; return 0;}", "e": 29155, "s": 28759, "text": null }, { "code": "// Java program to find largest of two numbersimport java.util.Scanner;public class largest { public static void main(String args[]) { int num1, num2, max; /*Input two numbers*/ Scanner sc = new Scanner(System.in); System.out.println(\"Enter two numbers:\"); num1 = sc.nextInt(); num2 = sc.nextInt(); /*check whether a is greater than b or not*/ if (num1 > num2) max = num1; else max = num2; /*Print the largest number*/ System.out.println(max); }}", "e": 29714, "s": 29155, "text": null }, { "code": "// C# program to find largest of two numbersusing System;using System.IO; class GFG{ static public void Main () { int num1, num2, max; /*Input two numbers*/ Console.WriteLine(\"Enter two numbers:\"); num1 = Convert.ToInt32(Console.ReadLine()); num2 = Convert.ToInt32(Console.ReadLine()); /*check whether a is greater than b or not*/ if (num1 > num2) max = num1; else max = num2; /*Print the largest number*/ Console.WriteLine(max); }} // This code is contributed by NamrataSrivastava1", "e": 30311, "s": 29714, "text": null }, { "code": null, "e": 30318, "s": 30311, "text": "Output" }, { "code": null, "e": 30346, "s": 30318, "text": "Enter two numbers:\n10 30\n30" }, { "code": null, "e": 30417, "s": 30346, "text": "References: Computer Fundamentals by Pradeep K. Sinha and Priti Sinha " }, { "code": null, "e": 30431, "s": 30417, "text": "RishabhPrabhu" }, { "code": null, "e": 30438, "s": 30431, "text": "srinam" }, { "code": null, "e": 30451, "s": 30438, "text": "itskawal2000" }, { "code": null, "e": 30463, "s": 30451, "text": "yatindracr7" }, { "code": null, "e": 30479, "s": 30463, "text": "CBSE - Class 11" }, { "code": null, "e": 30498, "s": 30479, "text": "school-programming" }, { "code": null, "e": 30513, "s": 30498, "text": "Design Pattern" }, { "code": null, "e": 30532, "s": 30513, "text": "School Programming" }, { "code": null, "e": 30551, "s": 30532, "text": "Technical Scripter" }, { "code": null, "e": 30649, "s": 30551, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 30689, "s": 30649, "text": "Strategy Pattern | Set 1 (Introduction)" }, { "code": null, "e": 30751, "s": 30689, "text": "Difference between Sequence diagram and Collaboration diagram" }, { "code": null, "e": 30782, "s": 30751, "text": "Template Method Design Pattern" }, { "code": null, "e": 30803, "s": 30782, "text": "State Design Pattern" }, { "code": null, "e": 30826, "s": 30803, "text": "Visitor design pattern" }, { "code": null, "e": 30844, "s": 30826, "text": "Python Dictionary" }, { "code": null, "e": 30860, "s": 30844, "text": "Arrays in C/C++" }, { "code": null, "e": 30879, "s": 30860, "text": "Inheritance in C++" }, { "code": null, "e": 30904, "s": 30879, "text": "Reverse a string in Java" } ]
Foldable Binary Trees - GeeksforGeeks
13 Aug, 2021 Question: Given a binary tree, find out if the tree can be folded or not.A tree can be folded if left and right subtrees of the tree are structure wise mirror image of each other. An empty tree is considered as foldable. Consider the below trees: (a) and (b) can be folded. (c) and (d) cannot be folded. (a) 10 / \ 7 15 \ / 9 11 (b) 10 / \ 7 15 / \ 9 11 (c) 10 / \ 7 15 / / 5 11 (d) 10 / \ 7 15 / \ / 9 10 12 Method 1 (Change Left subtree to its Mirror and compare it with Right subtree) Algorithm: isFoldable(root) 1) If tree is empty, then return true. 2) Convert the left subtree to its mirror image mirror(root->left); /* See this post */ 3) Check if the structure of left subtree and right subtree is same and store the result. res = isStructSame(root->left, root->right); /*isStructSame() recursively compares structures of two subtrees and returns true if structures are same */ 4) Revert the changes made in step (2) to get the original tree. mirror(root->left); 5) Return result res stored in step 2. Thanks to ajaym for suggesting this approach. C++ C Java C# Javascript // C++ program to check foldable binary tree#include <bits/stdc++.h>using namespace std; /* You would want to remove below3 lines if your compiler supportsbool, true and false */#define bool int#define true 1#define false 0 /* A binary tree node has data,pointer to left child and apointer to right child */class node {public: int data; node* left; node* right;}; /* converts a tree to its mirror image */void mirror(node* node); /* returns true if structure oftwo trees a and b is same onlystructure is considered for comparison, not data! */bool isStructSame(node* a, node* b); /* Returns true if the given tree is foldable */bool isFoldable(node* root){ bool res; /* base case */ if (root == NULL) return true; /* convert left subtree to its mirror */ mirror(root->left); /* Compare the structures of the right subtree and mirrored left subtree */ res = isStructSame(root->left, root->right); /* Get the original tree back */ mirror(root->left); return res;} bool isStructSame(node* a, node* b){ if (a == NULL && b == NULL) { return true; } if (a != NULL && b != NULL && isStructSame(a->left, b->left) && isStructSame(a->right, b->right)) { return true; } return false;} /* UTILITY FUNCTIONS *//* Change a tree so that the roles of the left and right pointers are swapped at every node. See https:// www.geeksforgeeks.org/?p=662 for details */void mirror(node* Node){ if (Node == NULL) return; else { node* temp; /* do the subtrees */ mirror(Node->left); mirror(Node->right); /* swap the pointers in this node */ temp = Node->left; Node->left = Node->right; Node->right = temp; }} /* Helper function that allocates a new node with thegiven data and NULL left and right pointers. */node* newNode(int data){ node* Node = new node(); Node->data = data; Node->left = NULL; Node->right = NULL; return (Node);} /* Driver program to test mirror() */int main(void){ /* The constructed binary tree is 1 / \ 2 3 \ / 4 5 */ node* root = newNode(1); root->left = newNode(2); root->right = newNode(3); root->right->left = newNode(4); root->left->right = newNode(5); if (isFoldable(root) == 1) { cout << "tree is foldable"; } else { cout << "\ntree is not foldable"; } return 0;} // This code is contributed by rathbhupendra #include <stdio.h>#include <stdlib.h> /* You would want to remove below 3 lines if your compiler supports bool, true and false */#define bool int#define true 1#define false 0 /* A binary tree node has data, pointer to left child and a pointer to right child */struct node { int data; struct node* left; struct node* right;}; /* converts a tree to its mirror image */void mirror(struct node* node); /* returns true if structure of two trees a and b is same Only structure is considered for comparison, not data! */bool isStructSame(struct node* a, struct node* b); /* Returns true if the given tree is foldable */bool isFoldable(struct node* root){ bool res; /* base case */ if (root == NULL) return true; /* convert left subtree to its mirror */ mirror(root->left); /* Compare the structures of the right subtree and mirrored left subtree */ res = isStructSame(root->left, root->right); /* Get the original tree back */ mirror(root->left); return res;} bool isStructSame(struct node* a, struct node* b){ if (a == NULL && b == NULL) { return true; } if (a != NULL && b != NULL && isStructSame(a->left, b->left) && isStructSame(a->right, b->right)) { return true; } return false;} /* UTILITY FUNCTIONS *//* Change a tree so that the roles of the left and right pointers are swapped at every node. See https:// www.geeksforgeeks.org/?p=662 for details */void mirror(struct node* node){ if (node == NULL) return; else { struct node* temp; /* do the subtrees */ mirror(node->left); mirror(node->right); /* swap the pointers in this node */ temp = node->left; node->left = node->right; node->right = temp; }} /* Helper function that allocates a new node with the given data and NULL left and right pointers. */struct node* newNode(int data){ struct node* node = (struct node*) malloc(sizeof(struct node)); node->data = data; node->left = NULL; node->right = NULL; return (node);} /* Driver program to test mirror() */int main(void){ /* The constructed binary tree is 1 / \ 2 3 \ / 4 5 */ struct node* root = newNode(1); root->left = newNode(2); root->right = newNode(3); root->right->left = newNode(4); root->left->right = newNode(5); if (isFoldable(root) == 1) { printf("\n tree is foldable"); } else { printf("\n tree is not foldable"); } getchar(); return 0;} // Java program to check foldable binary tree /* A binary tree node has data, pointer to left child and a pointer to right child */class Node { int data; Node left, right; Node(int item) { data = item; left = right = null; }} class BinaryTree { Node root; /* Returns true if the given tree is foldable */ boolean isFoldable(Node node) { boolean res; /* base case */ if (node == null) return true; /* convert left subtree to its mirror */ mirror(node.left); /* Compare the structures of the right subtree and mirrored left subtree */ res = isStructSame(node.left, node.right); /* Get the original tree back */ mirror(node.left); return res; } boolean isStructSame(Node a, Node b) { if (a == null && b == null) return true; if (a != null && b != null && isStructSame(a.left, b.left) && isStructSame(a.right, b.right)) return true; return false; } /* UTILITY FUNCTIONS */ /* Change a tree so that the roles of the left and right pointers are swapped at every node. See https:// www.geeksforgeeks.org/?p=662 for details */ void mirror(Node node) { if (node == null) return; else { Node temp; /* do the subtrees */ mirror(node.left); mirror(node.right); /* swap the pointers in this node */ temp = node.left; node.left = node.right; node.right = temp; } } /* Driver program to test above functions */ public static void main(String args[]) { BinaryTree tree = new BinaryTree(); /* The constructed binary tree is 1 / \ 2 3 \ / 4 5 */ tree.root = new Node(1); tree.root.left = new Node(2); tree.root.right = new Node(3); tree.root.right.left = new Node(4); tree.root.left.right = new Node(5); if (tree.isFoldable(tree.root)) System.out.println("tree is foldable"); else System.out.println("Tree is not foldable"); }} // This code has been contributed by Mayank Jaiswal // C# program to check foldable// binary treeusing System; /* A binary tree node has data,pointer to left child anda pointer to right child */class Node { public int data; public Node left, right; public Node(int item) { data = item; left = right = null; }} class BinaryTree { Node root; /* Returns true if the given tree is foldable */ Boolean isFoldable(Node node) { Boolean res; /* base case */ if (node == null) return true; /* convert left subtree to its mirror */ mirror(node.left); /* Compare the structures of the right subtree and mirrored left subtree */ res = isStructSame(node.left, node.right); /* Get the original tree back */ mirror(node.left); return res; } Boolean isStructSame(Node a, Node b) { if (a == null && b == null) return true; if (a != null && b != null && isStructSame(a.left, b.left) && isStructSame(a.right, b.right)) return true; return false; } /* UTILITY FUNCTIONS */ /* Change a tree so that the rolesof the left and right pointers areswapped at every node.See https:// www.geeksforgeeks.org/?p=662for details */ void mirror(Node node) { if (node == null) return; else { Node temp; /* do the subtrees */ mirror(node.left); mirror(node.right); /* swap the pointers in this node */ temp = node.left; node.left = node.right; node.right = temp; } } // Driver Code static public void Main(String[] args) { BinaryTree tree = new BinaryTree(); /* The constructed binary tree is 1 / \ 2 3 \ / 4 5 */ tree.root = new Node(1); tree.root.left = new Node(2); tree.root.right = new Node(3); tree.root.right.left = new Node(4); tree.root.left.right = new Node(5); if (tree.isFoldable(tree.root)) Console.WriteLine("tree is foldable"); else Console.WriteLine("Tree is not foldable"); }} // This code is contributed by Arnab Kundu <script> class Node{ constructor(item) { this.data=item; this.left=this.right=null; }} function isFoldable(node){ let res; /* base case */ if (node == null) return true; /* convert left subtree to its mirror */ mirror(node.left); /* Compare the structures of the right subtree and mirrored left subtree */ res = isStructSame(node.left, node.right); /* Get the original tree back */ mirror(node.left); return res;} function isStructSame(a,b){ if (a == null && b == null) return true; if (a != null && b != null && isStructSame(a.left, b.left) && isStructSame(a.right, b.right)) return true; return false;} function mirror(node){ if (node == null) return; else { let temp; /* do the subtrees */ mirror(node.left); mirror(node.right); /* swap the pointers in this node */ temp = node.left; node.left = node.right; node.right = temp; }} /* The constructed binary tree is 1 / \ 2 3 \ / 4 5 */let root = new Node(1);root.left = new Node(2);root.right = new Node(3);root.right.left = new Node(4);root.left.right = new Node(5); if (isFoldable(root)) document.write("tree is foldable");else document.write("Tree is not foldable"); // This code is contributed by avanitrachhadiya2155 </script> tree is foldable Time complexity: O(n)Method 2 (Check if Left and Right subtrees are Mirror) There are mainly two functions:// Checks if tree can be folded or not IsFoldable(root) 1) If tree is empty then return true 2) Else check if left and right subtrees are structure wise mirrors of each other. Use utility function IsFoldableUtil(root->left, root->right) for this. // Checks if n1 and n2 are mirror of each other. IsFoldableUtil(n1, n2) 1) If both trees are empty then return true. 2) If one of them is empty and other is not then return false. 3) Return true if following conditions are met a) n1->left is mirror of n2->right b) n1->right is mirror of n2->left C++ C Java Python3 C# Javascript #include <bits/stdc++.h>using namespace std; /* You would want to remove below 3 lines if your compilersupports bool, true and false */#define bool int#define true 1#define false 0 /* A binary tree node has data, pointer to left childand a pointer to right child */class node {public: int data; node* left; node* right;}; /* A utility function that checksif trees with roots as n1 and n2are mirror of each other */bool IsFoldableUtil(node* n1, node* n2); /* Returns true if the given tree can be folded */bool IsFoldable(node* root){ if (root == NULL) { return true; } return IsFoldableUtil(root->left, root->right);} /* A utility function that checksif trees with roots as n1 and n2are mirror of each other */bool IsFoldableUtil(node* n1, node* n2){ /* If both left and right subtrees are NULL, then return true */ if (n1 == NULL && n2 == NULL) { return true; } /* If one of the trees is NULL and other is not, then return false */ if (n1 == NULL || n2 == NULL) { return false; } /* Otherwise check if left and right subtrees are mirrors of their counterparts */ return IsFoldableUtil(n1->left, n2->right) && IsFoldableUtil(n1->right, n2->left);} /*UTILITY FUNCTIONS *//* Helper function that allocates a new node with thegiven data and NULL left and right pointers. */node* newNode(int data){ node* Node = new node(); Node->data = data; Node->left = NULL; Node->right = NULL; return (Node);} /* Driver code */int main(void){ /* The constructed binary tree is 1 / \ 2 3 \ / 4 5 */ node* root = newNode(1); root->left = newNode(2); root->right = newNode(3); root->left->right = newNode(4); root->right->left = newNode(5); if (IsFoldable(root) == true) { cout << "Tree is foldable"; } else { cout << "Tree is not foldable"; } return 0;} // This is code is contributed by rathbhupendra #include <stdio.h>#include <stdlib.h> /* You would want to remove below 3 lines if your compiler supports bool, true and false */#define bool int#define true 1#define false 0 /* A binary tree node has data, pointer to left child and a pointer to right child */struct node { int data; struct node* left; struct node* right;}; /* A utility function that checks if trees with roots as n1 and n2 are mirror of each other */bool IsFoldableUtil(struct node* n1, struct node* n2); /* Returns true if the given tree can be folded */bool IsFoldable(struct node* root){ if (root == NULL) { return true; } return IsFoldableUtil(root->left, root->right);} /* A utility function that checks if trees with roots as n1 and n2 are mirror of each other */bool IsFoldableUtil(struct node* n1, struct node* n2){ /* If both left and right subtrees are NULL, then return true */ if (n1 == NULL && n2 == NULL) { return true; } /* If one of the trees is NULL and other is not, then return false */ if (n1 == NULL || n2 == NULL) { return false; } /* Otherwise check if left and right subtrees are mirrors of their counterparts */ return IsFoldableUtil(n1->left, n2->right) && IsFoldableUtil(n1->right, n2->left);} /*UTILITY FUNCTIONS *//* Helper function that allocates a new node with the given data and NULL left and right pointers. */struct node* newNode(int data){ struct node* node = (struct node*)malloc(sizeof(struct node)); node->data = data; node->left = NULL; node->right = NULL; return (node);} /* Driver program to test mirror() */int main(void){ /* The constructed binary tree is 1 / \ 2 3 \ / 4 5 */ struct node* root = newNode(1); root->left = newNode(2); root->right = newNode(3); root->left->right = newNode(4); root->right->left = newNode(5); if (IsFoldable(root) == true) { printf("\n tree is foldable"); } else { printf("\n tree is not foldable"); } getchar(); return 0;} // Java program to check foldable binary tree /* A binary tree node has data, pointer to left child and a pointer to right child */class Node { int data; Node left, right; Node(int item) { data = item; left = right = null; }} class BinaryTree { Node root; /* Returns true if the given tree can be folded */ boolean IsFoldable(Node node) { if (node == null) return true; return IsFoldableUtil(node.left, node.right); } /* A utility function that checks if trees with roots as n1 and n2 are mirror of each other */ boolean IsFoldableUtil(Node n1, Node n2) { /* If both left and right subtrees are NULL, then return true */ if (n1 == null && n2 == null) return true; /* If one of the trees is NULL and other is not, then return false */ if (n1 == null || n2 == null) return false; /* Otherwise check if left and right subtrees are mirrors of their counterparts */ return IsFoldableUtil(n1.left, n2.right) && IsFoldableUtil(n1.right, n2.left); } /* Driver program to test above functions */ public static void main(String args[]) { BinaryTree tree = new BinaryTree(); /* The constructed binary tree is 1 / \ 2 3 \ / 4 5 */ tree.root = new Node(1); tree.root.left = new Node(2); tree.root.right = new Node(3); tree.root.right.left = new Node(4); tree.root.left.right = new Node(5); if (tree.IsFoldable(tree.root)) System.out.println("tree is foldable"); else System.out.println("Tree is not foldable"); }} // This code has been contributed by Mayank Jaiswal # Python3 program to check# foldable binary tree # Utility function to create a new# tree node class newNode: def __init__(self, data): self.data = data self.left = self.right = None # Returns true if the given tree can be folded def IsFoldable(root): if (root == None): return True return IsFoldableUtil(root.left, root.right) # A utility function that checks# if trees with roots as n1 and n2# are mirror of each otherdef IsFoldableUtil(n1, n2): # If both left and right subtrees are NULL, # then return true if n1 == None and n2 == None: return True # If one of the trees is NULL and other is not, # then return false if n1 == None or n2 == None: return False # Otherwise check if left and # right subtrees are mirrors of # their counterparts d1 = IsFoldableUtil(n1.left, n2.right) d2 = IsFoldableUtil(n1.right, n2.left) return d1 and d2 # Driver codeif __name__ == "__main__": """ The constructed binary tree is 1 / \ 2 3 \ / 4 5 """ root = newNode(1) root.left = newNode(2) root.right = newNode(3) root.left.right = newNode(4) root.right.left = newNode(5) if IsFoldable(root): print("Tree is foldable") else: print("Tree is not foldable") # This code is contributed by# Anupam Baranwal(anupambaranwal) // C# program to check foldable binary treeusing System; /* A binary tree node has data, pointer to left childand a pointer to right child */public class Node { public int data; public Node left, right; public Node(int item) { data = item; left = right = null; }} public class BinaryTree { Node root; /* Returns true if the given tree can be folded */ bool IsFoldable(Node node) { if (node == null) return true; return IsFoldableUtil(node.left, node.right); } /* A utility function that checks if trees with roots as n1 and n2 are mirror of each other */ bool IsFoldableUtil(Node n1, Node n2) { /* If both left and right subtrees are NULL, then return true */ if (n1 == null && n2 == null) return true; /* If one of the trees is NULL and other is not, then return false */ if (n1 == null || n2 == null) return false; /* Otherwise check if left and right subtrees are mirrors of their counterparts */ return IsFoldableUtil(n1.left, n2.right) && IsFoldableUtil(n1.right, n2.left); } /* Driver code */ public static void Main(String[] args) { BinaryTree tree = new BinaryTree(); /* The constructed binary tree is 1 / \ 2 3 \ / 4 5 */ tree.root = new Node(1); tree.root.left = new Node(2); tree.root.right = new Node(3); tree.root.right.left = new Node(4); tree.root.left.right = new Node(5); if (tree.IsFoldable(tree.root)) Console.WriteLine("tree is foldable"); else Console.WriteLine("Tree is not foldable"); }} /* This code contributed by PrinciRaj1992 */ <script> // JavaScript program to check foldable binary tree class Node { constructor(data) { this.left = null; this.right = null; this.data = data; } } let root; /* Returns true if the given tree can be folded */ function IsFoldable(node) { if (node == null) return true; return IsFoldableUtil(node.left, node.right); } /* A utility function that checks if trees with roots as n1 and n2 are mirror of each other */ function IsFoldableUtil(n1, n2) { /* If both left and right subtrees are NULL, then return true */ if (n1 == null && n2 == null) return true; /* If one of the trees is NULL and other is not, then return false */ if (n1 == null || n2 == null) return false; /* Otherwise check if left and right subtrees are mirrors of their counterparts */ return IsFoldableUtil(n1.left, n2.right) && IsFoldableUtil(n1.right, n2.left); } /* The constructed binary tree is 1 / \ 2 3 \ / 4 5 */ root = new Node(1); root.left = new Node(2); root.right = new Node(3); root.right.left = new Node(4); root.left.right = new Node(5); if (IsFoldable(root)) document.write("tree is foldable"); else document.write("Tree is not foldable"); </script> tree is foldable Iterative Approach: The idea is to use Queue for traversing the tree and using the BFS approach. In order to prove it is a foldable tree, we need to check two conditions whether null or not. The left child of the left subtree = the right child of the right subtree. Both of them should be not null.The right child of left subtree = left child of right subtree. Both of them should be null or not null. The left child of the left subtree = the right child of the right subtree. Both of them should be not null. The right child of left subtree = left child of right subtree. Both of them should be null or not null. Below is the implementation of the above approach: Java C# Javascript // Java code for the above approach import java.util.Queue;import java.util.LinkedList; public class FoldableTrees { Node root = null; // Class Node to store the data and left and right pointers class Node { int key; Node left; Node right; Node(int key) { this.key = key; left = right = null; } } // Function to find whether the tree is foldable boolean isFoldable() { // Queue to store visited nodes Queue<Node> q = new LinkedList<>(); // Initially add the left and right nodes of root if (root != null) { q.add(root.left); q.add(root.right); } while (!q.isEmpty()) { // Remove the front 2 nodes to // check for null condition Node p = q.remove(); Node r = q.remove(); // If both are null, continue and check // the further elements if (p == null && r == null) continue; // If one of them is not null, then return false if ((p == null && r != null) || (p != null && r == null)) return false; /* Insert in the same order: 1. left of left subtree 2. right of right subtree 3.right of left subtree 4.left of right subtree */ q.add(p.left); q.add(r.right); q.add(p.right); q.add(r.left); } // Only if the tree is foldable return true; } // Driver code public static void main(String args[]) { FoldableTrees tree = new FoldableTrees(); // Insert data into the tree tree.root = tree.new Node(1); tree.root.left = tree.new Node(2); tree.root.right = tree.new Node(3); tree.root.right.left = tree.new Node(4); tree.root.left.right = tree.new Node(5); // Function call if(tree.isFoldable()) System.out.println("Tree is foldable"); else System.out.println("Tree is not foldable"); }} //This method is contributed by likhita AVL using System;using System.Collections.Generic; public class Node{ public int key; public Node left,right; public Node(int key) { this.key=key; this.left=this.right=null; }} public class FoldableTrees{ Node root = null; // Function to find whether the tree is foldable bool isFoldable() { // Queue to store visited nodes Queue<Node> q = new Queue<Node>(); // Initially add the left and right nodes of root if (root != null) { q.Enqueue(root.left); q.Enqueue(root.right); } while (q.Count!=0) { // Remove the front 2 nodes to // check for null condition Node p = q.Dequeue(); Node r = q.Dequeue(); // If both are null, continue and check // the further elements if (p == null && r == null) continue; // If one of them is not null, then return false if ((p == null && r != null) || (p != null && r == null)) return false; /* Insert in the same order: 1. left of left subtree 2. right of right subtree 3.right of left subtree 4.left of right subtree */ q.Enqueue(p.left); q.Enqueue(r.right); q.Enqueue(p.right); q.Enqueue(r.left); } // Only if the tree is foldable return true; } // Driver code static public void Main () { FoldableTrees tree = new FoldableTrees(); // Insert data into the tree tree.root = new Node(1); tree.root.left = new Node(2); tree.root.right = new Node(3); tree.root.right.left = new Node(4); tree.root.left.right = new Node(5); // Function call if(tree.isFoldable()) Console.WriteLine("Tree is foldable"); else Console.WriteLine("Tree is not foldable"); }} // This code is contributed by patel2127. <script>// Javascript code for the above approach let root = null; // Class Node to store the data and left and right pointersclass Node{ constructor(key) { this.key=key; this.left=this.right=null; }} // Function to find whether the tree is foldablefunction isFoldable(){ // Queue to store visited nodes let q = []; // Initially add the left and right nodes of root if (root != null) { q.push(root.left); q.push(root.right); } while (q.length!=0) { // Remove the front 2 nodes to // check for null condition let p = q.shift(); let r = q.shift(); // If both are null, continue and check // the further elements if (p == null && r == null) continue; // If one of them is not null, then return false if ((p == null && r != null) || (p != null && r == null)) return false; /* Insert in the same order: 1. left of left subtree 2. right of right subtree 3.right of left subtree 4.left of right subtree */ q.push(p.left); q.push(r.right); q.push(p.right); q.push(r.left); } // Only if the tree is foldable return true;} // Driver code// Insert data into the treeroot = new Node(1);root.left = new Node(2);root.right = new Node(3);root.right.left = new Node(4);root.left.right = new Node(5); // Function callif(isFoldable()) document.write("Tree is foldable");else document.write("Tree is not foldable"); // This code is contributed by avanitrachhadiya2155</script> Tree is foldable Please write comments if you find the above code/algorithm incorrect, or find other ways to solve the same problem. andrew1234 rathbhupendra princiraj1992 anupambaranwal avllikhita avanitrachhadiya2155 rameshtravel07 rag2127 patel2127 sagartomar9927 simranarora5sos Expedia Tree Expedia Tree Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Tree Traversals (Inorder, Preorder and Postorder) Binary Tree | Set 1 (Introduction) Level Order Binary Tree Traversal AVL Tree | Set 1 (Insertion) Inorder Tree Traversal without Recursion Binary Tree | Set 3 (Types of Binary Tree) Write a Program to Find the Maximum Depth or Height of a Tree Binary Tree | Set 2 (Properties) Decision Tree A program to check if a binary tree is BST or not
[ { "code": null, "e": 35768, "s": 35740, "text": "\n13 Aug, 2021" }, { "code": null, "e": 35990, "s": 35768, "text": "Question: Given a binary tree, find out if the tree can be folded or not.A tree can be folded if left and right subtrees of the tree are structure wise mirror image of each other. An empty tree is considered as foldable. " }, { "code": null, "e": 36347, "s": 35990, "text": "Consider the below trees:\n(a) and (b) can be folded.\n(c) and (d) cannot be folded.\n\n(a)\n 10\n / \\\n 7 15\n \\ /\n 9 11\n\n(b)\n 10\n / \\\n 7 15\n / \\\n 9 11\n\n(c)\n 10\n / \\\n 7 15\n / /\n 5 11\n\n(d)\n\n 10\n / \\\n 7 15\n / \\ /\n 9 10 12" }, { "code": null, "e": 36455, "s": 36347, "text": "Method 1 (Change Left subtree to its Mirror and compare it with Right subtree) Algorithm: isFoldable(root) " }, { "code": null, "e": 36980, "s": 36455, "text": "1) If tree is empty, then return true.\n2) Convert the left subtree to its mirror image\n mirror(root->left); /* See this post */\n3) Check if the structure of left subtree and right subtree is same\n and store the result.\n res = isStructSame(root->left, root->right); /*isStructSame()\n recursively compares structures of two subtrees and returns\n true if structures are same */\n4) Revert the changes made in step (2) to get the original tree.\n mirror(root->left);\n5) Return result res stored in step 2." }, { "code": null, "e": 37027, "s": 36980, "text": "Thanks to ajaym for suggesting this approach. " }, { "code": null, "e": 37031, "s": 37027, "text": "C++" }, { "code": null, "e": 37033, "s": 37031, "text": "C" }, { "code": null, "e": 37038, "s": 37033, "text": "Java" }, { "code": null, "e": 37041, "s": 37038, "text": "C#" }, { "code": null, "e": 37052, "s": 37041, "text": "Javascript" }, { "code": "// C++ program to check foldable binary tree#include <bits/stdc++.h>using namespace std; /* You would want to remove below3 lines if your compiler supportsbool, true and false */#define bool int#define true 1#define false 0 /* A binary tree node has data,pointer to left child and apointer to right child */class node {public: int data; node* left; node* right;}; /* converts a tree to its mirror image */void mirror(node* node); /* returns true if structure oftwo trees a and b is same onlystructure is considered for comparison, not data! */bool isStructSame(node* a, node* b); /* Returns true if the given tree is foldable */bool isFoldable(node* root){ bool res; /* base case */ if (root == NULL) return true; /* convert left subtree to its mirror */ mirror(root->left); /* Compare the structures of the right subtree and mirrored left subtree */ res = isStructSame(root->left, root->right); /* Get the original tree back */ mirror(root->left); return res;} bool isStructSame(node* a, node* b){ if (a == NULL && b == NULL) { return true; } if (a != NULL && b != NULL && isStructSame(a->left, b->left) && isStructSame(a->right, b->right)) { return true; } return false;} /* UTILITY FUNCTIONS *//* Change a tree so that the roles of the left and right pointers are swapped at every node. See https:// www.geeksforgeeks.org/?p=662 for details */void mirror(node* Node){ if (Node == NULL) return; else { node* temp; /* do the subtrees */ mirror(Node->left); mirror(Node->right); /* swap the pointers in this node */ temp = Node->left; Node->left = Node->right; Node->right = temp; }} /* Helper function that allocates a new node with thegiven data and NULL left and right pointers. */node* newNode(int data){ node* Node = new node(); Node->data = data; Node->left = NULL; Node->right = NULL; return (Node);} /* Driver program to test mirror() */int main(void){ /* The constructed binary tree is 1 / \\ 2 3 \\ / 4 5 */ node* root = newNode(1); root->left = newNode(2); root->right = newNode(3); root->right->left = newNode(4); root->left->right = newNode(5); if (isFoldable(root) == 1) { cout << \"tree is foldable\"; } else { cout << \"\\ntree is not foldable\"; } return 0;} // This code is contributed by rathbhupendra", "e": 39539, "s": 37052, "text": null }, { "code": "#include <stdio.h>#include <stdlib.h> /* You would want to remove below 3 lines if your compiler supports bool, true and false */#define bool int#define true 1#define false 0 /* A binary tree node has data, pointer to left child and a pointer to right child */struct node { int data; struct node* left; struct node* right;}; /* converts a tree to its mirror image */void mirror(struct node* node); /* returns true if structure of two trees a and b is same Only structure is considered for comparison, not data! */bool isStructSame(struct node* a, struct node* b); /* Returns true if the given tree is foldable */bool isFoldable(struct node* root){ bool res; /* base case */ if (root == NULL) return true; /* convert left subtree to its mirror */ mirror(root->left); /* Compare the structures of the right subtree and mirrored left subtree */ res = isStructSame(root->left, root->right); /* Get the original tree back */ mirror(root->left); return res;} bool isStructSame(struct node* a, struct node* b){ if (a == NULL && b == NULL) { return true; } if (a != NULL && b != NULL && isStructSame(a->left, b->left) && isStructSame(a->right, b->right)) { return true; } return false;} /* UTILITY FUNCTIONS *//* Change a tree so that the roles of the left and right pointers are swapped at every node. See https:// www.geeksforgeeks.org/?p=662 for details */void mirror(struct node* node){ if (node == NULL) return; else { struct node* temp; /* do the subtrees */ mirror(node->left); mirror(node->right); /* swap the pointers in this node */ temp = node->left; node->left = node->right; node->right = temp; }} /* Helper function that allocates a new node with the given data and NULL left and right pointers. */struct node* newNode(int data){ struct node* node = (struct node*) malloc(sizeof(struct node)); node->data = data; node->left = NULL; node->right = NULL; return (node);} /* Driver program to test mirror() */int main(void){ /* The constructed binary tree is 1 / \\ 2 3 \\ / 4 5 */ struct node* root = newNode(1); root->left = newNode(2); root->right = newNode(3); root->right->left = newNode(4); root->left->right = newNode(5); if (isFoldable(root) == 1) { printf(\"\\n tree is foldable\"); } else { printf(\"\\n tree is not foldable\"); } getchar(); return 0;}", "e": 42085, "s": 39539, "text": null }, { "code": "// Java program to check foldable binary tree /* A binary tree node has data, pointer to left child and a pointer to right child */class Node { int data; Node left, right; Node(int item) { data = item; left = right = null; }} class BinaryTree { Node root; /* Returns true if the given tree is foldable */ boolean isFoldable(Node node) { boolean res; /* base case */ if (node == null) return true; /* convert left subtree to its mirror */ mirror(node.left); /* Compare the structures of the right subtree and mirrored left subtree */ res = isStructSame(node.left, node.right); /* Get the original tree back */ mirror(node.left); return res; } boolean isStructSame(Node a, Node b) { if (a == null && b == null) return true; if (a != null && b != null && isStructSame(a.left, b.left) && isStructSame(a.right, b.right)) return true; return false; } /* UTILITY FUNCTIONS */ /* Change a tree so that the roles of the left and right pointers are swapped at every node. See https:// www.geeksforgeeks.org/?p=662 for details */ void mirror(Node node) { if (node == null) return; else { Node temp; /* do the subtrees */ mirror(node.left); mirror(node.right); /* swap the pointers in this node */ temp = node.left; node.left = node.right; node.right = temp; } } /* Driver program to test above functions */ public static void main(String args[]) { BinaryTree tree = new BinaryTree(); /* The constructed binary tree is 1 / \\ 2 3 \\ / 4 5 */ tree.root = new Node(1); tree.root.left = new Node(2); tree.root.right = new Node(3); tree.root.right.left = new Node(4); tree.root.left.right = new Node(5); if (tree.isFoldable(tree.root)) System.out.println(\"tree is foldable\"); else System.out.println(\"Tree is not foldable\"); }} // This code has been contributed by Mayank Jaiswal", "e": 44386, "s": 42085, "text": null }, { "code": "// C# program to check foldable// binary treeusing System; /* A binary tree node has data,pointer to left child anda pointer to right child */class Node { public int data; public Node left, right; public Node(int item) { data = item; left = right = null; }} class BinaryTree { Node root; /* Returns true if the given tree is foldable */ Boolean isFoldable(Node node) { Boolean res; /* base case */ if (node == null) return true; /* convert left subtree to its mirror */ mirror(node.left); /* Compare the structures of the right subtree and mirrored left subtree */ res = isStructSame(node.left, node.right); /* Get the original tree back */ mirror(node.left); return res; } Boolean isStructSame(Node a, Node b) { if (a == null && b == null) return true; if (a != null && b != null && isStructSame(a.left, b.left) && isStructSame(a.right, b.right)) return true; return false; } /* UTILITY FUNCTIONS */ /* Change a tree so that the rolesof the left and right pointers areswapped at every node.See https:// www.geeksforgeeks.org/?p=662for details */ void mirror(Node node) { if (node == null) return; else { Node temp; /* do the subtrees */ mirror(node.left); mirror(node.right); /* swap the pointers in this node */ temp = node.left; node.left = node.right; node.right = temp; } } // Driver Code static public void Main(String[] args) { BinaryTree tree = new BinaryTree(); /* The constructed binary tree is 1 / \\ 2 3 \\ / 4 5 */ tree.root = new Node(1); tree.root.left = new Node(2); tree.root.right = new Node(3); tree.root.right.left = new Node(4); tree.root.left.right = new Node(5); if (tree.isFoldable(tree.root)) Console.WriteLine(\"tree is foldable\"); else Console.WriteLine(\"Tree is not foldable\"); }} // This code is contributed by Arnab Kundu", "e": 46683, "s": 44386, "text": null }, { "code": "<script> class Node{ constructor(item) { this.data=item; this.left=this.right=null; }} function isFoldable(node){ let res; /* base case */ if (node == null) return true; /* convert left subtree to its mirror */ mirror(node.left); /* Compare the structures of the right subtree and mirrored left subtree */ res = isStructSame(node.left, node.right); /* Get the original tree back */ mirror(node.left); return res;} function isStructSame(a,b){ if (a == null && b == null) return true; if (a != null && b != null && isStructSame(a.left, b.left) && isStructSame(a.right, b.right)) return true; return false;} function mirror(node){ if (node == null) return; else { let temp; /* do the subtrees */ mirror(node.left); mirror(node.right); /* swap the pointers in this node */ temp = node.left; node.left = node.right; node.right = temp; }} /* The constructed binary tree is 1 / \\ 2 3 \\ / 4 5 */let root = new Node(1);root.left = new Node(2);root.right = new Node(3);root.right.left = new Node(4);root.left.right = new Node(5); if (isFoldable(root)) document.write(\"tree is foldable\");else document.write(\"Tree is not foldable\"); // This code is contributed by avanitrachhadiya2155 </script>", "e": 48254, "s": 46683, "text": null }, { "code": null, "e": 48271, "s": 48254, "text": "tree is foldable" }, { "code": null, "e": 48348, "s": 48271, "text": "Time complexity: O(n)Method 2 (Check if Left and Right subtrees are Mirror) " }, { "code": null, "e": 48419, "s": 48348, "text": "There are mainly two functions:// Checks if tree can be folded or not " }, { "code": null, "e": 48635, "s": 48419, "text": "IsFoldable(root)\n1) If tree is empty then return true\n2) Else check if left and right subtrees are structure wise mirrors of\n each other. Use utility function IsFoldableUtil(root->left,\n root->right) for this." }, { "code": null, "e": 48685, "s": 48635, "text": "// Checks if n1 and n2 are mirror of each other. " }, { "code": null, "e": 48939, "s": 48685, "text": "IsFoldableUtil(n1, n2)\n1) If both trees are empty then return true.\n2) If one of them is empty and other is not then return false.\n3) Return true if following conditions are met\n a) n1->left is mirror of n2->right\n b) n1->right is mirror of n2->left" }, { "code": null, "e": 48943, "s": 48939, "text": "C++" }, { "code": null, "e": 48945, "s": 48943, "text": "C" }, { "code": null, "e": 48950, "s": 48945, "text": "Java" }, { "code": null, "e": 48958, "s": 48950, "text": "Python3" }, { "code": null, "e": 48961, "s": 48958, "text": "C#" }, { "code": null, "e": 48972, "s": 48961, "text": "Javascript" }, { "code": "#include <bits/stdc++.h>using namespace std; /* You would want to remove below 3 lines if your compilersupports bool, true and false */#define bool int#define true 1#define false 0 /* A binary tree node has data, pointer to left childand a pointer to right child */class node {public: int data; node* left; node* right;}; /* A utility function that checksif trees with roots as n1 and n2are mirror of each other */bool IsFoldableUtil(node* n1, node* n2); /* Returns true if the given tree can be folded */bool IsFoldable(node* root){ if (root == NULL) { return true; } return IsFoldableUtil(root->left, root->right);} /* A utility function that checksif trees with roots as n1 and n2are mirror of each other */bool IsFoldableUtil(node* n1, node* n2){ /* If both left and right subtrees are NULL, then return true */ if (n1 == NULL && n2 == NULL) { return true; } /* If one of the trees is NULL and other is not, then return false */ if (n1 == NULL || n2 == NULL) { return false; } /* Otherwise check if left and right subtrees are mirrors of their counterparts */ return IsFoldableUtil(n1->left, n2->right) && IsFoldableUtil(n1->right, n2->left);} /*UTILITY FUNCTIONS *//* Helper function that allocates a new node with thegiven data and NULL left and right pointers. */node* newNode(int data){ node* Node = new node(); Node->data = data; Node->left = NULL; Node->right = NULL; return (Node);} /* Driver code */int main(void){ /* The constructed binary tree is 1 / \\ 2 3 \\ / 4 5 */ node* root = newNode(1); root->left = newNode(2); root->right = newNode(3); root->left->right = newNode(4); root->right->left = newNode(5); if (IsFoldable(root) == true) { cout << \"Tree is foldable\"; } else { cout << \"Tree is not foldable\"; } return 0;} // This is code is contributed by rathbhupendra", "e": 50944, "s": 48972, "text": null }, { "code": "#include <stdio.h>#include <stdlib.h> /* You would want to remove below 3 lines if your compiler supports bool, true and false */#define bool int#define true 1#define false 0 /* A binary tree node has data, pointer to left child and a pointer to right child */struct node { int data; struct node* left; struct node* right;}; /* A utility function that checks if trees with roots as n1 and n2 are mirror of each other */bool IsFoldableUtil(struct node* n1, struct node* n2); /* Returns true if the given tree can be folded */bool IsFoldable(struct node* root){ if (root == NULL) { return true; } return IsFoldableUtil(root->left, root->right);} /* A utility function that checks if trees with roots as n1 and n2 are mirror of each other */bool IsFoldableUtil(struct node* n1, struct node* n2){ /* If both left and right subtrees are NULL, then return true */ if (n1 == NULL && n2 == NULL) { return true; } /* If one of the trees is NULL and other is not, then return false */ if (n1 == NULL || n2 == NULL) { return false; } /* Otherwise check if left and right subtrees are mirrors of their counterparts */ return IsFoldableUtil(n1->left, n2->right) && IsFoldableUtil(n1->right, n2->left);} /*UTILITY FUNCTIONS *//* Helper function that allocates a new node with the given data and NULL left and right pointers. */struct node* newNode(int data){ struct node* node = (struct node*)malloc(sizeof(struct node)); node->data = data; node->left = NULL; node->right = NULL; return (node);} /* Driver program to test mirror() */int main(void){ /* The constructed binary tree is 1 / \\ 2 3 \\ / 4 5 */ struct node* root = newNode(1); root->left = newNode(2); root->right = newNode(3); root->left->right = newNode(4); root->right->left = newNode(5); if (IsFoldable(root) == true) { printf(\"\\n tree is foldable\"); } else { printf(\"\\n tree is not foldable\"); } getchar(); return 0;}", "e": 53028, "s": 50944, "text": null }, { "code": "// Java program to check foldable binary tree /* A binary tree node has data, pointer to left child and a pointer to right child */class Node { int data; Node left, right; Node(int item) { data = item; left = right = null; }} class BinaryTree { Node root; /* Returns true if the given tree can be folded */ boolean IsFoldable(Node node) { if (node == null) return true; return IsFoldableUtil(node.left, node.right); } /* A utility function that checks if trees with roots as n1 and n2 are mirror of each other */ boolean IsFoldableUtil(Node n1, Node n2) { /* If both left and right subtrees are NULL, then return true */ if (n1 == null && n2 == null) return true; /* If one of the trees is NULL and other is not, then return false */ if (n1 == null || n2 == null) return false; /* Otherwise check if left and right subtrees are mirrors of their counterparts */ return IsFoldableUtil(n1.left, n2.right) && IsFoldableUtil(n1.right, n2.left); } /* Driver program to test above functions */ public static void main(String args[]) { BinaryTree tree = new BinaryTree(); /* The constructed binary tree is 1 / \\ 2 3 \\ / 4 5 */ tree.root = new Node(1); tree.root.left = new Node(2); tree.root.right = new Node(3); tree.root.right.left = new Node(4); tree.root.left.right = new Node(5); if (tree.IsFoldable(tree.root)) System.out.println(\"tree is foldable\"); else System.out.println(\"Tree is not foldable\"); }} // This code has been contributed by Mayank Jaiswal", "e": 54843, "s": 53028, "text": null }, { "code": "# Python3 program to check# foldable binary tree # Utility function to create a new# tree node class newNode: def __init__(self, data): self.data = data self.left = self.right = None # Returns true if the given tree can be folded def IsFoldable(root): if (root == None): return True return IsFoldableUtil(root.left, root.right) # A utility function that checks# if trees with roots as n1 and n2# are mirror of each otherdef IsFoldableUtil(n1, n2): # If both left and right subtrees are NULL, # then return true if n1 == None and n2 == None: return True # If one of the trees is NULL and other is not, # then return false if n1 == None or n2 == None: return False # Otherwise check if left and # right subtrees are mirrors of # their counterparts d1 = IsFoldableUtil(n1.left, n2.right) d2 = IsFoldableUtil(n1.right, n2.left) return d1 and d2 # Driver codeif __name__ == \"__main__\": \"\"\" The constructed binary tree is 1 / \\ 2 3 \\ / 4 5 \"\"\" root = newNode(1) root.left = newNode(2) root.right = newNode(3) root.left.right = newNode(4) root.right.left = newNode(5) if IsFoldable(root): print(\"Tree is foldable\") else: print(\"Tree is not foldable\") # This code is contributed by# Anupam Baranwal(anupambaranwal)", "e": 56201, "s": 54843, "text": null }, { "code": "// C# program to check foldable binary treeusing System; /* A binary tree node has data, pointer to left childand a pointer to right child */public class Node { public int data; public Node left, right; public Node(int item) { data = item; left = right = null; }} public class BinaryTree { Node root; /* Returns true if the given tree can be folded */ bool IsFoldable(Node node) { if (node == null) return true; return IsFoldableUtil(node.left, node.right); } /* A utility function that checks if trees with roots as n1 and n2 are mirror of each other */ bool IsFoldableUtil(Node n1, Node n2) { /* If both left and right subtrees are NULL, then return true */ if (n1 == null && n2 == null) return true; /* If one of the trees is NULL and other is not, then return false */ if (n1 == null || n2 == null) return false; /* Otherwise check if left and right subtrees are mirrors of their counterparts */ return IsFoldableUtil(n1.left, n2.right) && IsFoldableUtil(n1.right, n2.left); } /* Driver code */ public static void Main(String[] args) { BinaryTree tree = new BinaryTree(); /* The constructed binary tree is 1 / \\ 2 3 \\ / 4 5 */ tree.root = new Node(1); tree.root.left = new Node(2); tree.root.right = new Node(3); tree.root.right.left = new Node(4); tree.root.left.right = new Node(5); if (tree.IsFoldable(tree.root)) Console.WriteLine(\"tree is foldable\"); else Console.WriteLine(\"Tree is not foldable\"); }} /* This code contributed by PrinciRaj1992 */", "e": 58001, "s": 56201, "text": null }, { "code": "<script> // JavaScript program to check foldable binary tree class Node { constructor(data) { this.left = null; this.right = null; this.data = data; } } let root; /* Returns true if the given tree can be folded */ function IsFoldable(node) { if (node == null) return true; return IsFoldableUtil(node.left, node.right); } /* A utility function that checks if trees with roots as n1 and n2 are mirror of each other */ function IsFoldableUtil(n1, n2) { /* If both left and right subtrees are NULL, then return true */ if (n1 == null && n2 == null) return true; /* If one of the trees is NULL and other is not, then return false */ if (n1 == null || n2 == null) return false; /* Otherwise check if left and right subtrees are mirrors of their counterparts */ return IsFoldableUtil(n1.left, n2.right) && IsFoldableUtil(n1.right, n2.left); } /* The constructed binary tree is 1 / \\ 2 3 \\ / 4 5 */ root = new Node(1); root.left = new Node(2); root.right = new Node(3); root.right.left = new Node(4); root.left.right = new Node(5); if (IsFoldable(root)) document.write(\"tree is foldable\"); else document.write(\"Tree is not foldable\"); </script>", "e": 59481, "s": 58001, "text": null }, { "code": null, "e": 59498, "s": 59481, "text": "tree is foldable" }, { "code": null, "e": 59596, "s": 59498, "text": "Iterative Approach: The idea is to use Queue for traversing the tree and using the BFS approach. " }, { "code": null, "e": 59690, "s": 59596, "text": "In order to prove it is a foldable tree, we need to check two conditions whether null or not." }, { "code": null, "e": 59901, "s": 59690, "text": "The left child of the left subtree = the right child of the right subtree. Both of them should be not null.The right child of left subtree = left child of right subtree. Both of them should be null or not null." }, { "code": null, "e": 60009, "s": 59901, "text": "The left child of the left subtree = the right child of the right subtree. Both of them should be not null." }, { "code": null, "e": 60113, "s": 60009, "text": "The right child of left subtree = left child of right subtree. Both of them should be null or not null." }, { "code": null, "e": 60164, "s": 60113, "text": "Below is the implementation of the above approach:" }, { "code": null, "e": 60169, "s": 60164, "text": "Java" }, { "code": null, "e": 60172, "s": 60169, "text": "C#" }, { "code": null, "e": 60183, "s": 60172, "text": "Javascript" }, { "code": "// Java code for the above approach import java.util.Queue;import java.util.LinkedList; public class FoldableTrees { Node root = null; // Class Node to store the data and left and right pointers class Node { int key; Node left; Node right; Node(int key) { this.key = key; left = right = null; } } // Function to find whether the tree is foldable boolean isFoldable() { // Queue to store visited nodes Queue<Node> q = new LinkedList<>(); // Initially add the left and right nodes of root if (root != null) { q.add(root.left); q.add(root.right); } while (!q.isEmpty()) { // Remove the front 2 nodes to // check for null condition Node p = q.remove(); Node r = q.remove(); // If both are null, continue and check // the further elements if (p == null && r == null) continue; // If one of them is not null, then return false if ((p == null && r != null) || (p != null && r == null)) return false; /* Insert in the same order: 1. left of left subtree 2. right of right subtree 3.right of left subtree 4.left of right subtree */ q.add(p.left); q.add(r.right); q.add(p.right); q.add(r.left); } // Only if the tree is foldable return true; } // Driver code public static void main(String args[]) { FoldableTrees tree = new FoldableTrees(); // Insert data into the tree tree.root = tree.new Node(1); tree.root.left = tree.new Node(2); tree.root.right = tree.new Node(3); tree.root.right.left = tree.new Node(4); tree.root.left.right = tree.new Node(5); // Function call if(tree.isFoldable()) System.out.println(\"Tree is foldable\"); else System.out.println(\"Tree is not foldable\"); }} //This method is contributed by likhita AVL", "e": 62411, "s": 60183, "text": null }, { "code": "using System;using System.Collections.Generic; public class Node{ public int key; public Node left,right; public Node(int key) { this.key=key; this.left=this.right=null; }} public class FoldableTrees{ Node root = null; // Function to find whether the tree is foldable bool isFoldable() { // Queue to store visited nodes Queue<Node> q = new Queue<Node>(); // Initially add the left and right nodes of root if (root != null) { q.Enqueue(root.left); q.Enqueue(root.right); } while (q.Count!=0) { // Remove the front 2 nodes to // check for null condition Node p = q.Dequeue(); Node r = q.Dequeue(); // If both are null, continue and check // the further elements if (p == null && r == null) continue; // If one of them is not null, then return false if ((p == null && r != null) || (p != null && r == null)) return false; /* Insert in the same order: 1. left of left subtree 2. right of right subtree 3.right of left subtree 4.left of right subtree */ q.Enqueue(p.left); q.Enqueue(r.right); q.Enqueue(p.right); q.Enqueue(r.left); } // Only if the tree is foldable return true; } // Driver code static public void Main () { FoldableTrees tree = new FoldableTrees(); // Insert data into the tree tree.root = new Node(1); tree.root.left = new Node(2); tree.root.right = new Node(3); tree.root.right.left = new Node(4); tree.root.left.right = new Node(5); // Function call if(tree.isFoldable()) Console.WriteLine(\"Tree is foldable\"); else Console.WriteLine(\"Tree is not foldable\"); }} // This code is contributed by patel2127.", "e": 64524, "s": 62411, "text": null }, { "code": "<script>// Javascript code for the above approach let root = null; // Class Node to store the data and left and right pointersclass Node{ constructor(key) { this.key=key; this.left=this.right=null; }} // Function to find whether the tree is foldablefunction isFoldable(){ // Queue to store visited nodes let q = []; // Initially add the left and right nodes of root if (root != null) { q.push(root.left); q.push(root.right); } while (q.length!=0) { // Remove the front 2 nodes to // check for null condition let p = q.shift(); let r = q.shift(); // If both are null, continue and check // the further elements if (p == null && r == null) continue; // If one of them is not null, then return false if ((p == null && r != null) || (p != null && r == null)) return false; /* Insert in the same order: 1. left of left subtree 2. right of right subtree 3.right of left subtree 4.left of right subtree */ q.push(p.left); q.push(r.right); q.push(p.right); q.push(r.left); } // Only if the tree is foldable return true;} // Driver code// Insert data into the treeroot = new Node(1);root.left = new Node(2);root.right = new Node(3);root.right.left = new Node(4);root.left.right = new Node(5); // Function callif(isFoldable()) document.write(\"Tree is foldable\");else document.write(\"Tree is not foldable\"); // This code is contributed by avanitrachhadiya2155</script>", "e": 66309, "s": 64524, "text": null }, { "code": null, "e": 66326, "s": 66309, "text": "Tree is foldable" }, { "code": null, "e": 66443, "s": 66326, "text": "Please write comments if you find the above code/algorithm incorrect, or find other ways to solve the same problem. " }, { "code": null, "e": 66454, "s": 66443, "text": "andrew1234" }, { "code": null, "e": 66468, "s": 66454, "text": "rathbhupendra" }, { "code": null, "e": 66482, "s": 66468, "text": "princiraj1992" }, { "code": null, "e": 66497, "s": 66482, "text": "anupambaranwal" }, { "code": null, "e": 66508, "s": 66497, "text": "avllikhita" }, { "code": null, "e": 66529, "s": 66508, "text": "avanitrachhadiya2155" }, { "code": null, "e": 66544, "s": 66529, "text": "rameshtravel07" }, { "code": null, "e": 66552, "s": 66544, "text": "rag2127" }, { "code": null, "e": 66562, "s": 66552, "text": "patel2127" }, { "code": null, "e": 66577, "s": 66562, "text": "sagartomar9927" }, { "code": null, "e": 66593, "s": 66577, "text": "simranarora5sos" }, { "code": null, "e": 66601, "s": 66593, "text": "Expedia" }, { "code": null, "e": 66606, "s": 66601, "text": "Tree" }, { "code": null, "e": 66614, "s": 66606, "text": "Expedia" }, { "code": null, "e": 66619, "s": 66614, "text": "Tree" }, { "code": null, "e": 66717, "s": 66619, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 66726, "s": 66717, "text": "Comments" }, { "code": null, "e": 66739, "s": 66726, "text": "Old Comments" }, { "code": null, "e": 66789, "s": 66739, "text": "Tree Traversals (Inorder, Preorder and Postorder)" }, { "code": null, "e": 66824, "s": 66789, "text": "Binary Tree | Set 1 (Introduction)" }, { "code": null, "e": 66858, "s": 66824, "text": "Level Order Binary Tree Traversal" }, { "code": null, "e": 66887, "s": 66858, "text": "AVL Tree | Set 1 (Insertion)" }, { "code": null, "e": 66928, "s": 66887, "text": "Inorder Tree Traversal without Recursion" }, { "code": null, "e": 66971, "s": 66928, "text": "Binary Tree | Set 3 (Types of Binary Tree)" }, { "code": null, "e": 67033, "s": 66971, "text": "Write a Program to Find the Maximum Depth or Height of a Tree" }, { "code": null, "e": 67066, "s": 67033, "text": "Binary Tree | Set 2 (Properties)" }, { "code": null, "e": 67080, "s": 67066, "text": "Decision Tree" } ]
Python - Every Kth Strings Uppercase - GeeksforGeeks
05 Sep, 2020 Given a String list, change every Kth string to uppercase. Input : test_list = [“gfg”, “is”, “best”, “for”, “geeks”], K = 3Output : [‘GFG’, ‘is’, ‘best’, ‘FOR’, ‘geeks’]Explanation : All Kth strings are uppercased. Input : test_list = [“gfg”, “is”, “best”, “for”, “geeks”], K = 4Output : [‘GFG’, ‘is’, ‘best’, ‘for’, ‘GEEKS’]Explanation : All Kth strings are uppercased. Method #1 : Using loop + upper() In this, we iterate for all strings using loop and upper is used to perform uppercase, Kth index is detected using modulo operator. Python3 # Python3 code to demonstrate working of # Every Kth Strings Uppercase# Using loop + upper() # initializing listtest_list = ["gfg", "is", "best", "for", "geeks", "and", "CS"] # printing original listprint("The original list is : " + str(test_list)) # initializing K K = 3 res = []for idx in range(len(test_list)): # checking for Kth index if idx % K == 0: res.append(test_list[idx].upper()) else : res.append(test_list[idx]) # printing result print("The resultant String list : " + str(res)) The original list is : ['gfg', 'is', 'best', 'for', 'geeks', 'and', 'CS'] The resultant String list : ['GFG', 'is', 'best', 'FOR', 'geeks', 'and', 'CS'] Method #2 : Using list comprehension This yet another way in which this task can be performed. In this we use list comprehension as shorthand, performs tasks similar to above method. Python3 # Python3 code to demonstrate working of # Every Kth Strings Uppercase# Using list comprehension # initializing listtest_list = ["gfg", "is", "best", "for", "geeks", "and", "CS"] # printing original listprint("The original list is : " + str(test_list)) # initializing K K = 3 # shorthand to perform this taskres = [test_list[idx].upper() if idx % K == 0 else test_list[idx] for idx in range(len(test_list))] # printing result print("The resultant String list : " + str(res)) The original list is : ['gfg', 'is', 'best', 'for', 'geeks', 'and', 'CS'] The resultant String list : ['GFG', 'is', 'best', 'FOR', 'geeks', 'and', 'CS'] Python string-programs Python Python Programs Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to Install PIP on Windows ? How To Convert Python Dictionary To JSON? Check if element exists in list in Python How to drop one or multiple columns in Pandas Dataframe Python Classes and Objects Defaultdict in Python Python | Get dictionary keys as a list Python | Split string into list of characters Python | Convert a list to dictionary How to print without newline in Python?
[ { "code": null, "e": 25647, "s": 25619, "text": "\n05 Sep, 2020" }, { "code": null, "e": 25706, "s": 25647, "text": "Given a String list, change every Kth string to uppercase." }, { "code": null, "e": 25862, "s": 25706, "text": "Input : test_list = [“gfg”, “is”, “best”, “for”, “geeks”], K = 3Output : [‘GFG’, ‘is’, ‘best’, ‘FOR’, ‘geeks’]Explanation : All Kth strings are uppercased." }, { "code": null, "e": 26018, "s": 25862, "text": "Input : test_list = [“gfg”, “is”, “best”, “for”, “geeks”], K = 4Output : [‘GFG’, ‘is’, ‘best’, ‘for’, ‘GEEKS’]Explanation : All Kth strings are uppercased." }, { "code": null, "e": 26051, "s": 26018, "text": "Method #1 : Using loop + upper()" }, { "code": null, "e": 26183, "s": 26051, "text": "In this, we iterate for all strings using loop and upper is used to perform uppercase, Kth index is detected using modulo operator." }, { "code": null, "e": 26191, "s": 26183, "text": "Python3" }, { "code": "# Python3 code to demonstrate working of # Every Kth Strings Uppercase# Using loop + upper() # initializing listtest_list = [\"gfg\", \"is\", \"best\", \"for\", \"geeks\", \"and\", \"CS\"] # printing original listprint(\"The original list is : \" + str(test_list)) # initializing K K = 3 res = []for idx in range(len(test_list)): # checking for Kth index if idx % K == 0: res.append(test_list[idx].upper()) else : res.append(test_list[idx]) # printing result print(\"The resultant String list : \" + str(res))", "e": 26718, "s": 26191, "text": null }, { "code": null, "e": 26872, "s": 26718, "text": "The original list is : ['gfg', 'is', 'best', 'for', 'geeks', 'and', 'CS']\nThe resultant String list : ['GFG', 'is', 'best', 'FOR', 'geeks', 'and', 'CS']\n" }, { "code": null, "e": 26909, "s": 26872, "text": "Method #2 : Using list comprehension" }, { "code": null, "e": 27055, "s": 26909, "text": "This yet another way in which this task can be performed. In this we use list comprehension as shorthand, performs tasks similar to above method." }, { "code": null, "e": 27063, "s": 27055, "text": "Python3" }, { "code": "# Python3 code to demonstrate working of # Every Kth Strings Uppercase# Using list comprehension # initializing listtest_list = [\"gfg\", \"is\", \"best\", \"for\", \"geeks\", \"and\", \"CS\"] # printing original listprint(\"The original list is : \" + str(test_list)) # initializing K K = 3 # shorthand to perform this taskres = [test_list[idx].upper() if idx % K == 0 else test_list[idx] for idx in range(len(test_list))] # printing result print(\"The resultant String list : \" + str(res))", "e": 27550, "s": 27063, "text": null }, { "code": null, "e": 27704, "s": 27550, "text": "The original list is : ['gfg', 'is', 'best', 'for', 'geeks', 'and', 'CS']\nThe resultant String list : ['GFG', 'is', 'best', 'FOR', 'geeks', 'and', 'CS']\n" }, { "code": null, "e": 27727, "s": 27704, "text": "Python string-programs" }, { "code": null, "e": 27734, "s": 27727, "text": "Python" }, { "code": null, "e": 27750, "s": 27734, "text": "Python Programs" }, { "code": null, "e": 27848, "s": 27750, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 27880, "s": 27848, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 27922, "s": 27880, "text": "How To Convert Python Dictionary To JSON?" }, { "code": null, "e": 27964, "s": 27922, "text": "Check if element exists in list in Python" }, { "code": null, "e": 28020, "s": 27964, "text": "How to drop one or multiple columns in Pandas Dataframe" }, { "code": null, "e": 28047, "s": 28020, "text": "Python Classes and Objects" }, { "code": null, "e": 28069, "s": 28047, "text": "Defaultdict in Python" }, { "code": null, "e": 28108, "s": 28069, "text": "Python | Get dictionary keys as a list" }, { "code": null, "e": 28154, "s": 28108, "text": "Python | Split string into list of characters" }, { "code": null, "e": 28192, "s": 28154, "text": "Python | Convert a list to dictionary" } ]
How to set priority to the test cases in TestNG?
We can set priority for test cases in order of their execution, by giving priority to each test method. A test method having lower priority runs first then the test methods with higher priority are executed. @Test (priority = 1) public void verifyTravel(){ System.out.println("Travel history successful "); } @Test (priority = 2) public verifyIncome(){ System.out.println ("Income history successful"); } In the Java class file, verifyTravel() will run first followed by verifyIncome().
[ { "code": null, "e": 1270, "s": 1062, "text": "We can set priority for test cases in order of their execution, by giving priority to each test method. A test method having lower priority runs first then the test methods with higher priority are executed." }, { "code": null, "e": 1473, "s": 1270, "text": "@Test (priority = 1)\npublic void verifyTravel(){\n System.out.println(\"Travel history successful \");\n}\n@Test (priority = 2)\npublic verifyIncome(){\n System.out.println (\"Income history successful\");\n}" }, { "code": null, "e": 1555, "s": 1473, "text": "In the Java class file, verifyTravel() will run first followed by verifyIncome()." } ]
How to extract part of a URL in MySQL?
You need to use SUBSTRING_INDEX() function from MySQL to extract part of a URL. Let us first create a table − mysql> create table DemoTable ( Id int NOT NULL AUTO_INCREMENT PRIMARY KEY, URL text ); Query OK, 0 rows affected (0.53 sec) Insert some records in the table using insert command − mysql> insert into DemoTable(URL) values('https:\\www.example.com\\homepage'); Query OK, 1 row affected (0.27 sec) mysql> insert into DemoTable(URL) values('https:\\www.onlinetest.com\\welcome\\indexpage'); Query OK, 1 row affected (0.12 sec) Following is the query to display all records from the table using select statement − mysql> select *from DemoTable; This will produce the following output. Here, we can only a slash is visible because internally MySQL removes one slash in result − +----+---------------------------------------------+ | Id | URL | +----+---------------------------------------------+ | 1 | https:\www.example.com\homepage | | 2 | https:\www.onlinetest.com\welcome\indexpage | +----+---------------------------------------------+ 2 rows in set (0.00 sec) Following is the query to extract part of a URL in MySQL − mysql> select substring_index(URL,'\\',-1) from DemoTable; This will produce the following output − +------------------------------+ | substring_index(URL,'\\',-1) | +------------------------------+ | homepage | | indexpage | +------------------------------+ 2 rows in set (0.00 sec)
[ { "code": null, "e": 1142, "s": 1062, "text": "You need to use SUBSTRING_INDEX() function from MySQL to extract part of a URL." }, { "code": null, "e": 1173, "s": 1142, "text": " Let us first create a table −" }, { "code": null, "e": 1304, "s": 1173, "text": "mysql> create table DemoTable\n(\n Id int NOT NULL AUTO_INCREMENT PRIMARY KEY,\n URL text\n);\nQuery OK, 0 rows affected (0.53 sec)" }, { "code": null, "e": 1360, "s": 1304, "text": "Insert some records in the table using insert command −" }, { "code": null, "e": 1603, "s": 1360, "text": "mysql> insert into DemoTable(URL) values('https:\\\\www.example.com\\\\homepage');\nQuery OK, 1 row affected (0.27 sec)\nmysql> insert into DemoTable(URL) values('https:\\\\www.onlinetest.com\\\\welcome\\\\indexpage');\nQuery OK, 1 row affected (0.12 sec)" }, { "code": null, "e": 1689, "s": 1603, "text": "Following is the query to display all records from the table using select statement −" }, { "code": null, "e": 1720, "s": 1689, "text": "mysql> select *from DemoTable;" }, { "code": null, "e": 1852, "s": 1720, "text": "This will produce the following output. Here, we can only a slash is visible because internally MySQL removes one slash in result −" }, { "code": null, "e": 2195, "s": 1852, "text": "+----+---------------------------------------------+\n| Id | URL |\n+----+---------------------------------------------+\n| 1 | https:\\www.example.com\\homepage |\n| 2 | https:\\www.onlinetest.com\\welcome\\indexpage |\n+----+---------------------------------------------+\n2 rows in set (0.00 sec)" }, { "code": null, "e": 2254, "s": 2195, "text": "Following is the query to extract part of a URL in MySQL −" }, { "code": null, "e": 2313, "s": 2254, "text": "mysql> select substring_index(URL,'\\\\',-1) from DemoTable;" }, { "code": null, "e": 2354, "s": 2313, "text": "This will produce the following output −" }, { "code": null, "e": 2577, "s": 2354, "text": "+------------------------------+\n| substring_index(URL,'\\\\',-1) |\n+------------------------------+\n| homepage |\n| indexpage |\n+------------------------------+\n2 rows in set (0.00 sec)" } ]
Python | Number to Words using num2words - GeeksforGeeks
19 Jul, 2019 num2words module in Python, which converts number (like 34) to words (like thirty-four). Also, this library has support for multiple languages. In this article, we will see how to convert number to words using num2words module. InstallationOne can easily install num2words using pip. pip install num2words Consider the following two excerpts from different files taken from 20 Newsgroups, a popular NLP database. Pre-processing 20 Newsgroups effectively has remained to be a matter of interest. In article, Martin Preston writes: Why not use the PD C library for reading/writing TIFF files? It took me a good 20 minutes to start using them in your own app.ISCIS VIII is the eighth of a series of meetings which have brought together computer scientists and engineers from about twenty countries. This year’s conference will be held in the beautiful Mediterranean resort city of Antalya, in a region rich in natural as well as historical sites. In the above two excerpts, one can observe that the number ’20’ appears in both numeric and alphabetical forms. Simply following the pre-processing steps, that involve tokenization, lemmatization and so on would not be able to map ’20’ and ‘twenty’ to the same stem, which is of contextual importance. Luckily, we have the in-built library, num2words which solves this problem in a single line. Below is the sample usage of the tool. from num2words import num2words # Most common usage.print(num2words(36)) # Other variants, according to the type of article.print(num2words(36, to = 'ordinal'))print(num2words(36, to = 'ordinal_num'))print(num2words(36, to = 'year'))print(num2words(36, to = 'currency')) # Language Support.print(num2words(36, lang ='es')) Output: thirty-six thirty-sixth 36th zero euro, thirty-six cents treinta y seis Therefore, in the pre-processing step, one could convert ALL numeric values to words for better accuracy in the further stages. References: https://pypi.org/project/num2words/ Natural-language-processing Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Python Dictionary Read a file line by line in Python Enumerate() in Python How to Install PIP on Windows ? Iterate over a list in Python Different ways to create Pandas Dataframe Python program to convert a list to string Python String | replace() Reading and Writing to text files in Python sum() function in Python
[ { "code": null, "e": 24278, "s": 24250, "text": "\n19 Jul, 2019" }, { "code": null, "e": 24506, "s": 24278, "text": "num2words module in Python, which converts number (like 34) to words (like thirty-four). Also, this library has support for multiple languages. In this article, we will see how to convert number to words using num2words module." }, { "code": null, "e": 24562, "s": 24506, "text": "InstallationOne can easily install num2words using pip." }, { "code": null, "e": 24585, "s": 24562, "text": "pip install num2words\n" }, { "code": null, "e": 24774, "s": 24585, "text": "Consider the following two excerpts from different files taken from 20 Newsgroups, a popular NLP database. Pre-processing 20 Newsgroups effectively has remained to be a matter of interest." }, { "code": null, "e": 25223, "s": 24774, "text": "In article, Martin Preston writes: Why not use the PD C library for reading/writing TIFF files? It took me a good 20 minutes to start using them in your own app.ISCIS VIII is the eighth of a series of meetings which have brought together computer scientists and engineers from about twenty countries. This year’s conference will be held in the beautiful Mediterranean resort city of Antalya, in a region rich in natural as well as historical sites." }, { "code": null, "e": 25618, "s": 25223, "text": "In the above two excerpts, one can observe that the number ’20’ appears in both numeric and alphabetical forms. Simply following the pre-processing steps, that involve tokenization, lemmatization and so on would not be able to map ’20’ and ‘twenty’ to the same stem, which is of contextual importance. Luckily, we have the in-built library, num2words which solves this problem in a single line." }, { "code": null, "e": 25657, "s": 25618, "text": "Below is the sample usage of the tool." }, { "code": "from num2words import num2words # Most common usage.print(num2words(36)) # Other variants, according to the type of article.print(num2words(36, to = 'ordinal'))print(num2words(36, to = 'ordinal_num'))print(num2words(36, to = 'year'))print(num2words(36, to = 'currency')) # Language Support.print(num2words(36, lang ='es'))", "e": 25983, "s": 25657, "text": null }, { "code": null, "e": 25991, "s": 25983, "text": "Output:" }, { "code": null, "e": 26064, "s": 25991, "text": "thirty-six\nthirty-sixth\n36th\nzero euro, thirty-six cents\ntreinta y seis\n" }, { "code": null, "e": 26192, "s": 26064, "text": "Therefore, in the pre-processing step, one could convert ALL numeric values to words for better accuracy in the further stages." }, { "code": null, "e": 26240, "s": 26192, "text": "References: https://pypi.org/project/num2words/" }, { "code": null, "e": 26268, "s": 26240, "text": "Natural-language-processing" }, { "code": null, "e": 26275, "s": 26268, "text": "Python" }, { "code": null, "e": 26373, "s": 26275, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 26382, "s": 26373, "text": "Comments" }, { "code": null, "e": 26395, "s": 26382, "text": "Old Comments" }, { "code": null, "e": 26413, "s": 26395, "text": "Python Dictionary" }, { "code": null, "e": 26448, "s": 26413, "text": "Read a file line by line in Python" }, { "code": null, "e": 26470, "s": 26448, "text": "Enumerate() in Python" }, { "code": null, "e": 26502, "s": 26470, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 26532, "s": 26502, "text": "Iterate over a list in Python" }, { "code": null, "e": 26574, "s": 26532, "text": "Different ways to create Pandas Dataframe" }, { "code": null, "e": 26617, "s": 26574, "text": "Python program to convert a list to string" }, { "code": null, "e": 26643, "s": 26617, "text": "Python String | replace()" }, { "code": null, "e": 26687, "s": 26643, "text": "Reading and Writing to text files in Python" } ]
numpy.remainder() in Python - GeeksforGeeks
10 Feb, 2019 numpy.remainder() is another function for doing mathematical operations in numpy.It returns element-wise remainder of division between two array arr1 and arr2 i.e. arr1 % arr2 .It returns 0 when arr2 is 0 and both arr1 and arr2 are (arrays of) integers. Syntax : numpy.remainder(arr1, arr2, /, out=None, *, where=True, casting=’same_kind’, order=’K’, dtype=None, subok=True[, signature, extobj], ufunc ‘remainder’) Parameters :arr1 : [array_like] Dividend array.arr2 : [array_like] Divisor array.dtype : The type of the returned array. By default, the dtype of arr is used.out : [ndarray, optional] A location into which the result is stored. -> If provided, it must have a shape that the inputs broadcast to. -> If not provided or None, a freshly-allocated array is returned.where : [array_like, optional] Values of True indicate to calculate the ufunc at that position, values of False indicate to leave the value in the output alone.**kwargs : Allows to pass keyword variable length of argument to a function. Used when we want to handle named argument in a function. Return : [ndarray] The element-wise remainder i.e arr1 % arr2 . Code #1 : # Python program explaining# numpy.remainder() function import numpy as geekin_num1 = 4in_num2 = 6 print ("Dividend : ", in_num1)print ("Divisor : ", in_num2) out_num = geek.remainder(in_num1, in_num2) print ("Remainder : ", out_num) Dividend : 4 Divisor : 6 Remainder : 4 Code #2 : # Python program explaining# numpy.remainder() function import numpy as geek in_arr1 = geek.array([5, -4, 8])in_arr2 = geek.array([2, 3, 4]) print ("Dividend array : ", in_arr1)print ("Divisor array : ", in_arr2) out_arr = geek.remainder(in_arr1, in_arr2) print ("Output remainder array: ", out_arr) Dividend array : [ 5 -4 8] Divisor array : [2 3 4] Output remainder array: [1 2 0] Python numpy-Mathematical Function Python-numpy Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments How to Install PIP on Windows ? How to drop one or multiple columns in Pandas Dataframe How To Convert Python Dictionary To JSON? Check if element exists in list in Python Python | Pandas dataframe.groupby() Defaultdict in Python Python | Get unique values from a list Python Classes and Objects Python | os.path.join() method Create a directory in Python
[ { "code": null, "e": 23901, "s": 23873, "text": "\n10 Feb, 2019" }, { "code": null, "e": 24155, "s": 23901, "text": "numpy.remainder() is another function for doing mathematical operations in numpy.It returns element-wise remainder of division between two array arr1 and arr2 i.e. arr1 % arr2 .It returns 0 when arr2 is 0 and both arr1 and arr2 are (arrays of) integers." }, { "code": null, "e": 24316, "s": 24155, "text": "Syntax : numpy.remainder(arr1, arr2, /, out=None, *, where=True, casting=’same_kind’, order=’K’, dtype=None, subok=True[, signature, extobj], ufunc ‘remainder’)" }, { "code": null, "e": 24974, "s": 24316, "text": "Parameters :arr1 : [array_like] Dividend array.arr2 : [array_like] Divisor array.dtype : The type of the returned array. By default, the dtype of arr is used.out : [ndarray, optional] A location into which the result is stored. -> If provided, it must have a shape that the inputs broadcast to. -> If not provided or None, a freshly-allocated array is returned.where : [array_like, optional] Values of True indicate to calculate the ufunc at that position, values of False indicate to leave the value in the output alone.**kwargs : Allows to pass keyword variable length of argument to a function. Used when we want to handle named argument in a function." }, { "code": null, "e": 25038, "s": 24974, "text": "Return : [ndarray] The element-wise remainder i.e arr1 % arr2 ." }, { "code": null, "e": 25048, "s": 25038, "text": "Code #1 :" }, { "code": "# Python program explaining# numpy.remainder() function import numpy as geekin_num1 = 4in_num2 = 6 print (\"Dividend : \", in_num1)print (\"Divisor : \", in_num2) out_num = geek.remainder(in_num1, in_num2) print (\"Remainder : \", out_num) ", "e": 25288, "s": 25048, "text": null }, { "code": null, "e": 25331, "s": 25288, "text": "Dividend : 4\nDivisor : 6\nRemainder : 4\n" }, { "code": null, "e": 25343, "s": 25333, "text": "Code #2 :" }, { "code": "# Python program explaining# numpy.remainder() function import numpy as geek in_arr1 = geek.array([5, -4, 8])in_arr2 = geek.array([2, 3, 4]) print (\"Dividend array : \", in_arr1)print (\"Divisor array : \", in_arr2) out_arr = geek.remainder(in_arr1, in_arr2) print (\"Output remainder array: \", out_arr) ", "e": 25654, "s": 25343, "text": null }, { "code": null, "e": 25742, "s": 25654, "text": "Dividend array : [ 5 -4 8]\nDivisor array : [2 3 4]\nOutput remainder array: [1 2 0]\n" }, { "code": null, "e": 25777, "s": 25742, "text": "Python numpy-Mathematical Function" }, { "code": null, "e": 25790, "s": 25777, "text": "Python-numpy" }, { "code": null, "e": 25797, "s": 25790, "text": "Python" }, { "code": null, "e": 25895, "s": 25797, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 25904, "s": 25895, "text": "Comments" }, { "code": null, "e": 25917, "s": 25904, "text": "Old Comments" }, { "code": null, "e": 25949, "s": 25917, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 26005, "s": 25949, "text": "How to drop one or multiple columns in Pandas Dataframe" }, { "code": null, "e": 26047, "s": 26005, "text": "How To Convert Python Dictionary To JSON?" }, { "code": null, "e": 26089, "s": 26047, "text": "Check if element exists in list in Python" }, { "code": null, "e": 26125, "s": 26089, "text": "Python | Pandas dataframe.groupby()" }, { "code": null, "e": 26147, "s": 26125, "text": "Defaultdict in Python" }, { "code": null, "e": 26186, "s": 26147, "text": "Python | Get unique values from a list" }, { "code": null, "e": 26213, "s": 26186, "text": "Python Classes and Objects" }, { "code": null, "e": 26244, "s": 26213, "text": "Python | os.path.join() method" } ]
Image Segmentation with Clustering | by Yağmur Çiğdem Aktaş | Towards Data Science
We overviewed Classical Image Segmentation methods in my previous post. Now it is time to examine AI-based Image Segmentation methods and we will start with Clustering. Before diving into Image Segmentation with Clustering, let’s go over the topics like “What is Clustering?” “How to implement a basic Clustering method with Python?” What is Clustering It is nothing more than grouping given data according to their similarities and obtains different clusters at the end. According to the clustering method we use, the way we group the data changes. Let’s examine 2 different most used in Image Segmentation type: Partitioning Clustering and Fuzzy Clustering Partitioning Clustering Partitioning Clustering methods subdivides the data into k groups, where k is a number predefined by the user. For K-means Clustering which is the most popular Partitioning Cluster method We choose k random points in the data as the center of clusters and assign each point to the nearest cluster by looking at the L2 distance between the point and the center.Compute the mean of each cluster, assign that mean value as the new center of the cluster.Reassign each data point to its closest cluster center. Repeat step 2. We choose k random points in the data as the center of clusters and assign each point to the nearest cluster by looking at the L2 distance between the point and the center. Compute the mean of each cluster, assign that mean value as the new center of the cluster. Reassign each data point to its closest cluster center. Repeat step 2. The process keeps going until no new assignment is performed (so the model is converged, there is nothing to go furthermore) or for a given number of iteration. Therefore, K-means Clustering is an iterative method where we can determine the iteration number too. Now let’s visualize some random data applying K-means clustering for 10 iterations for each. from sklearn.cluster import KMeansfrom sklearn.datasets import make_blobsimport numpy as npfrom matplotlib import pyplot as pltimport cv2""" Plot the data """data = np.array([[1, 2], [1, 4], [1, 0],[10, 2], [10, 4], [10, 0]])data = np.array([[1, 5], [3, 1], [10, 3], [10, 2], [10, 1], [1, 0], [2, 15], [0.5, 4.9], [5, 3], [7, 13], [18, 18], [1.9, 0.5]]) data = np.random.randint(100, size=(2,2))centers = [[1, 1], [-1, -1], [1, -1]]data, _ = make_blobs(n_samples=10000, centers=centers, cluster_std=0.6)# Plot the dataplt.scatter(data[:,0],data[:,1])plt.xlabel('x'),plt.ylabel('y')plt.show()""" Visualize K means for each iteration """""" create an empty list for each cluster, k is the cluster number """k = 2clusters = [[[0 for _ in range(2)] for _ in range(1)] for _ in range(k)]for i in range(k): clusters[i].pop() #if we dont do that, additional [0,0] points will be stayed added in our data """ Visualize each iteration. """for i in range(1,10): kmeans = KMeans(n_clusters=k, random_state = 0, max_iter=i).fit(data) for index,data_point in enumerate(data): clusters[kmeans.labels_[index]].append(list(data_point)) for i in range(k): clusters[i] = np.array(clusters[i]) plt.scatter(clusters[i][:,0],clusters[i][:,1]) clusters[i] = clusters[i].tolist() plt.show() We see even at the first iteration we obtain the final result. Because the data is pretty small and initial clustering works well. Let’s run the same code for the data randomly generated as below and group them into 5 clusters. centers = [[1, 1], [-1, -1], [1, -1]]data, _ = make_blobs(n_samples=10000, centers=centers, cluster_std=0.6) Now we see better how in each iteration the clusters get updated! Time to apply K-means Clustering on a real image and get segmented output! """ Image Segmentation """img = cv2.imread("bird1.jpg", cv2.IMREAD_UNCHANGED) img = cv2.imread("birds2.jpg", cv2.IMREAD_UNCHANGED) img = cv2.imread("peppers3.jpg", cv2.IMREAD_UNCHANGED) vectorized = img.reshape((-1,3))kmeans = KMeans(n_clusters=5, random_state = 0, n_init=5).fit(vectorized)centers = np.uint8(kmeans.cluster_centers_)segmented_data = centers[kmeans.labels_.flatten()] segmented_image = segmented_data.reshape((img.shape))plt.imshow(segmented_image)plt.pause(1) You can realize that I didn’t use max_iter which determined the iteration number parameter that time. I leave that decision to the model so segmentation stops when no change in clusters occurs. On the other hand, the n_init parameter determines how many different trials will be completed with different random cluster centers in the initial step. The algorithm chooses the best fit, which gives the best segmentation. We can realize with increasing k, the result gets better and more detailed! Here is the github link for the code used in that section : Fuzzy Clustering Fuzzy Clustering is a hard clustering type while Partitioning Clustering is called soft. The reason for that is while in Partitioning Clustering, 1 data point may have only in 1 cluster, in Fuzzy Clustering we have the probabilities of a data point for each cluster and they may belong to any cluster at this probability level. Not let’s examine the most common Fuzzy Clustering type Fuzzy C-Mean Clustering and see how to calculate the probabilities of points, the center of clusters, etc. [1] Initialize the probability matrix randomly. So, assign weights to each data — cluster pair which refers to the probability of being in cluster C for data X.Calculate the center of clusters (centroids),Calculate new probabilities according to the new center of clusters.Repeat 2. and 3. steps until the centers doesn’t change or for a given iteration number Initialize the probability matrix randomly. So, assign weights to each data — cluster pair which refers to the probability of being in cluster C for data X. Calculate the center of clusters (centroids), Calculate new probabilities according to the new center of clusters. Repeat 2. and 3. steps until the centers doesn’t change or for a given iteration number Let’s visualize an example case : We have 4 data points p1, p2, p3, p4 2-dimensional, so we have x and y coordinates of the points and we want to group them into 2 clusters. We initialize the weight matrix randomly: We initialize the weight matrix randomly: 2. We calculate the centroids of clusters according to that initial probabilities with the following formula: Note that fuzzy parameter is something we should choose like Cluster number and it can be chosen between 1 < m < ∞ Let’s apply the formula for our example case by choosing m = 2 : Since we have 2D points, the center of the cluster is 2D too. So we calculate C1x (x coordinate of the first cluster) using x coordinates of our points and C1y (y coordinate of the first cluster) using y coordinates of our points). When we apply the same formula for C2 too, we obtain the following We obtained our cluster centers, now it’s time to calculate the probabilities of points according to that new cluster centers. 3. We calculate new probabilities — weights using the following formula: Don’t forget m = 2 in our case, so 1/m-1 = 1. and so on! I didn’t calculate each weight for each point and cluster but wanted to show the logic manually for each step. I hope it was clear the fundamental logic and application of Fuzzy C Means Clustering. Now it’s time to do some experiments and examine the results. Choosing fuzzy parameter m too big causes the result to be distorted. Again we see with increasing cluster numbers we obtain a more detailed and better-segmented result. If you use Linux, you can try to use the fuzzy c means module from PyPI [1], I had some trouble installing it on windows even though I used pip install fuzzy-c-means[windows] command as suggested. Thanks to [2] for fuzzy c means implementation from scratch, I used that one while preparing that last part. See you in the Image Segmentation with Neural Networks part! 👐 [1] https://pypi.org/project/fuzzy-c-means/ [2]https://github.com/jeongHwarr/various_FCM_segmentation/blob/master/FCM.py In this post, all the images used for making experiments with different code parts are taken from unsplash.com
[ { "code": null, "e": 341, "s": 172, "text": "We overviewed Classical Image Segmentation methods in my previous post. Now it is time to examine AI-based Image Segmentation methods and we will start with Clustering." }, { "code": null, "e": 506, "s": 341, "text": "Before diving into Image Segmentation with Clustering, let’s go over the topics like “What is Clustering?” “How to implement a basic Clustering method with Python?”" }, { "code": null, "e": 525, "s": 506, "text": "What is Clustering" }, { "code": null, "e": 831, "s": 525, "text": "It is nothing more than grouping given data according to their similarities and obtains different clusters at the end. According to the clustering method we use, the way we group the data changes. Let’s examine 2 different most used in Image Segmentation type: Partitioning Clustering and Fuzzy Clustering" }, { "code": null, "e": 855, "s": 831, "text": "Partitioning Clustering" }, { "code": null, "e": 1043, "s": 855, "text": "Partitioning Clustering methods subdivides the data into k groups, where k is a number predefined by the user. For K-means Clustering which is the most popular Partitioning Cluster method" }, { "code": null, "e": 1376, "s": 1043, "text": "We choose k random points in the data as the center of clusters and assign each point to the nearest cluster by looking at the L2 distance between the point and the center.Compute the mean of each cluster, assign that mean value as the new center of the cluster.Reassign each data point to its closest cluster center. Repeat step 2." }, { "code": null, "e": 1549, "s": 1376, "text": "We choose k random points in the data as the center of clusters and assign each point to the nearest cluster by looking at the L2 distance between the point and the center." }, { "code": null, "e": 1640, "s": 1549, "text": "Compute the mean of each cluster, assign that mean value as the new center of the cluster." }, { "code": null, "e": 1711, "s": 1640, "text": "Reassign each data point to its closest cluster center. Repeat step 2." }, { "code": null, "e": 1974, "s": 1711, "text": "The process keeps going until no new assignment is performed (so the model is converged, there is nothing to go furthermore) or for a given number of iteration. Therefore, K-means Clustering is an iterative method where we can determine the iteration number too." }, { "code": null, "e": 2067, "s": 1974, "text": "Now let’s visualize some random data applying K-means clustering for 10 iterations for each." }, { "code": null, "e": 3390, "s": 2067, "text": "from sklearn.cluster import KMeansfrom sklearn.datasets import make_blobsimport numpy as npfrom matplotlib import pyplot as pltimport cv2\"\"\" Plot the data \"\"\"data = np.array([[1, 2], [1, 4], [1, 0],[10, 2], [10, 4], [10, 0]])data = np.array([[1, 5], [3, 1], [10, 3], [10, 2], [10, 1], [1, 0], [2, 15], [0.5, 4.9], [5, 3], [7, 13], [18, 18], [1.9, 0.5]]) data = np.random.randint(100, size=(2,2))centers = [[1, 1], [-1, -1], [1, -1]]data, _ = make_blobs(n_samples=10000, centers=centers, cluster_std=0.6)# Plot the dataplt.scatter(data[:,0],data[:,1])plt.xlabel('x'),plt.ylabel('y')plt.show()\"\"\" Visualize K means for each iteration \"\"\"\"\"\" create an empty list for each cluster, k is the cluster number \"\"\"k = 2clusters = [[[0 for _ in range(2)] for _ in range(1)] for _ in range(k)]for i in range(k): clusters[i].pop() #if we dont do that, additional [0,0] points will be stayed added in our data \"\"\" Visualize each iteration. \"\"\"for i in range(1,10): kmeans = KMeans(n_clusters=k, random_state = 0, max_iter=i).fit(data) for index,data_point in enumerate(data): clusters[kmeans.labels_[index]].append(list(data_point)) for i in range(k): clusters[i] = np.array(clusters[i]) plt.scatter(clusters[i][:,0],clusters[i][:,1]) clusters[i] = clusters[i].tolist() plt.show()" }, { "code": null, "e": 3618, "s": 3390, "text": "We see even at the first iteration we obtain the final result. Because the data is pretty small and initial clustering works well. Let’s run the same code for the data randomly generated as below and group them into 5 clusters." }, { "code": null, "e": 3727, "s": 3618, "text": "centers = [[1, 1], [-1, -1], [1, -1]]data, _ = make_blobs(n_samples=10000, centers=centers, cluster_std=0.6)" }, { "code": null, "e": 3793, "s": 3727, "text": "Now we see better how in each iteration the clusters get updated!" }, { "code": null, "e": 3868, "s": 3793, "text": "Time to apply K-means Clustering on a real image and get segmented output!" }, { "code": null, "e": 4348, "s": 3868, "text": "\"\"\" Image Segmentation \"\"\"img = cv2.imread(\"bird1.jpg\", cv2.IMREAD_UNCHANGED) img = cv2.imread(\"birds2.jpg\", cv2.IMREAD_UNCHANGED) img = cv2.imread(\"peppers3.jpg\", cv2.IMREAD_UNCHANGED) vectorized = img.reshape((-1,3))kmeans = KMeans(n_clusters=5, random_state = 0, n_init=5).fit(vectorized)centers = np.uint8(kmeans.cluster_centers_)segmented_data = centers[kmeans.labels_.flatten()] segmented_image = segmented_data.reshape((img.shape))plt.imshow(segmented_image)plt.pause(1)" }, { "code": null, "e": 4767, "s": 4348, "text": "You can realize that I didn’t use max_iter which determined the iteration number parameter that time. I leave that decision to the model so segmentation stops when no change in clusters occurs. On the other hand, the n_init parameter determines how many different trials will be completed with different random cluster centers in the initial step. The algorithm chooses the best fit, which gives the best segmentation." }, { "code": null, "e": 4843, "s": 4767, "text": "We can realize with increasing k, the result gets better and more detailed!" }, { "code": null, "e": 4903, "s": 4843, "text": "Here is the github link for the code used in that section :" }, { "code": null, "e": 4920, "s": 4903, "text": "Fuzzy Clustering" }, { "code": null, "e": 5248, "s": 4920, "text": "Fuzzy Clustering is a hard clustering type while Partitioning Clustering is called soft. The reason for that is while in Partitioning Clustering, 1 data point may have only in 1 cluster, in Fuzzy Clustering we have the probabilities of a data point for each cluster and they may belong to any cluster at this probability level." }, { "code": null, "e": 5415, "s": 5248, "text": "Not let’s examine the most common Fuzzy Clustering type Fuzzy C-Mean Clustering and see how to calculate the probabilities of points, the center of clusters, etc. [1]" }, { "code": null, "e": 5772, "s": 5415, "text": "Initialize the probability matrix randomly. So, assign weights to each data — cluster pair which refers to the probability of being in cluster C for data X.Calculate the center of clusters (centroids),Calculate new probabilities according to the new center of clusters.Repeat 2. and 3. steps until the centers doesn’t change or for a given iteration number" }, { "code": null, "e": 5929, "s": 5772, "text": "Initialize the probability matrix randomly. So, assign weights to each data — cluster pair which refers to the probability of being in cluster C for data X." }, { "code": null, "e": 5975, "s": 5929, "text": "Calculate the center of clusters (centroids)," }, { "code": null, "e": 6044, "s": 5975, "text": "Calculate new probabilities according to the new center of clusters." }, { "code": null, "e": 6132, "s": 6044, "text": "Repeat 2. and 3. steps until the centers doesn’t change or for a given iteration number" }, { "code": null, "e": 6166, "s": 6132, "text": "Let’s visualize an example case :" }, { "code": null, "e": 6306, "s": 6166, "text": "We have 4 data points p1, p2, p3, p4 2-dimensional, so we have x and y coordinates of the points and we want to group them into 2 clusters." }, { "code": null, "e": 6348, "s": 6306, "text": "We initialize the weight matrix randomly:" }, { "code": null, "e": 6390, "s": 6348, "text": "We initialize the weight matrix randomly:" }, { "code": null, "e": 6500, "s": 6390, "text": "2. We calculate the centroids of clusters according to that initial probabilities with the following formula:" }, { "code": null, "e": 6615, "s": 6500, "text": "Note that fuzzy parameter is something we should choose like Cluster number and it can be chosen between 1 < m < ∞" }, { "code": null, "e": 6680, "s": 6615, "text": "Let’s apply the formula for our example case by choosing m = 2 :" }, { "code": null, "e": 6912, "s": 6680, "text": "Since we have 2D points, the center of the cluster is 2D too. So we calculate C1x (x coordinate of the first cluster) using x coordinates of our points and C1y (y coordinate of the first cluster) using y coordinates of our points)." }, { "code": null, "e": 6979, "s": 6912, "text": "When we apply the same formula for C2 too, we obtain the following" }, { "code": null, "e": 7106, "s": 6979, "text": "We obtained our cluster centers, now it’s time to calculate the probabilities of points according to that new cluster centers." }, { "code": null, "e": 7179, "s": 7106, "text": "3. We calculate new probabilities — weights using the following formula:" }, { "code": null, "e": 7225, "s": 7179, "text": "Don’t forget m = 2 in our case, so 1/m-1 = 1." }, { "code": null, "e": 7347, "s": 7225, "text": "and so on! I didn’t calculate each weight for each point and cluster but wanted to show the logic manually for each step." }, { "code": null, "e": 7496, "s": 7347, "text": "I hope it was clear the fundamental logic and application of Fuzzy C Means Clustering. Now it’s time to do some experiments and examine the results." }, { "code": null, "e": 7666, "s": 7496, "text": "Choosing fuzzy parameter m too big causes the result to be distorted. Again we see with increasing cluster numbers we obtain a more detailed and better-segmented result." }, { "code": null, "e": 7972, "s": 7666, "text": "If you use Linux, you can try to use the fuzzy c means module from PyPI [1], I had some trouble installing it on windows even though I used pip install fuzzy-c-means[windows] command as suggested. Thanks to [2] for fuzzy c means implementation from scratch, I used that one while preparing that last part." }, { "code": null, "e": 8035, "s": 7972, "text": "See you in the Image Segmentation with Neural Networks part! 👐" }, { "code": null, "e": 8079, "s": 8035, "text": "[1] https://pypi.org/project/fuzzy-c-means/" }, { "code": null, "e": 8156, "s": 8079, "text": "[2]https://github.com/jeongHwarr/various_FCM_segmentation/blob/master/FCM.py" } ]
Case sensitive string comparison in Java.
You can compare two strings using either equals() method or compareTo() method. Where, The equals() method compares this string to the specified object. The compareTo() method compares two strings lexicographically. The comparison is based on the Unicode value of each character in the strings. These two methods compare the given strings with respective to Case i.e. String with the different case are treated differently. Following example demonstrates the comparison of two strings using the equals() method. Live Demo public class Sample{ public static void main(String args[]) { String str = "Hello World"; String anotherString = "hello world"; Object objStr = str; System.out.println( str.equals(anotherString) ); } } false
[ { "code": null, "e": 1142, "s": 1062, "text": "You can compare two strings using either equals() method or compareTo() method." }, { "code": null, "e": 1149, "s": 1142, "text": "Where," }, { "code": null, "e": 1215, "s": 1149, "text": "The equals() method compares this string to the specified object." }, { "code": null, "e": 1357, "s": 1215, "text": "The compareTo() method compares two strings lexicographically. The comparison is based on the Unicode value of each character in the strings." }, { "code": null, "e": 1486, "s": 1357, "text": "These two methods compare the given strings with respective to Case i.e. String with the different case are treated differently." }, { "code": null, "e": 1574, "s": 1486, "text": "Following example demonstrates the comparison of two strings using the equals() method." }, { "code": null, "e": 1584, "s": 1574, "text": "Live Demo" }, { "code": null, "e": 1816, "s": 1584, "text": "public class Sample{\n public static void main(String args[]) {\n String str = \"Hello World\";\n String anotherString = \"hello world\";\n Object objStr = str;\n System.out.println( str.equals(anotherString) );\n }\n}" }, { "code": null, "e": 1822, "s": 1816, "text": "false" } ]
Check if given number is perfect square in Python
Suppose we have a number n. We have to check whether the number n is perfect square or not. A number is said to be a perfect square number when its square root is an integer. So, if the input is like n = 36, then the output will be True as 36 = 6*6. To solve this, we will follow these steps − sq_root := integer part of (square root of n) return true when sq_root^2 is same as n otherwise false Let us see the following implementation to get better understanding − Live Demo from math import sqrt def solve(n): sq_root = int(sqrt(n)) return (sq_root*sq_root) == n n = 36 print (solve(n)) 36 True
[ { "code": null, "e": 1237, "s": 1062, "text": "Suppose we have a number n. We have to check whether the number n is perfect square or not. A number is said to be a perfect square number when its square root is an integer." }, { "code": null, "e": 1312, "s": 1237, "text": "So, if the input is like n = 36, then the output will be True as 36 = 6*6." }, { "code": null, "e": 1356, "s": 1312, "text": "To solve this, we will follow these steps −" }, { "code": null, "e": 1402, "s": 1356, "text": "sq_root := integer part of (square root of n)" }, { "code": null, "e": 1458, "s": 1402, "text": "return true when sq_root^2 is same as n otherwise false" }, { "code": null, "e": 1528, "s": 1458, "text": "Let us see the following implementation to get better understanding −" }, { "code": null, "e": 1539, "s": 1528, "text": " Live Demo" }, { "code": null, "e": 1658, "s": 1539, "text": "from math import sqrt\ndef solve(n):\n sq_root = int(sqrt(n))\n return (sq_root*sq_root) == n\nn = 36\nprint (solve(n))" }, { "code": null, "e": 1661, "s": 1658, "text": "36" }, { "code": null, "e": 1666, "s": 1661, "text": "True" } ]
Python - Filter dictionary key based on the values in selective list
Sometimes in a Python dictionary we may need to to filter out certain keys of the dictionary based on certain criteria. In this article we will see how to filter out keys from Python dictionary. In this approach we put the values of the keys to be filtered in a list. Then iterate through each element of the list and check for its presence in the given dictionary. We create a resulting dictionary containing these values which are found in the dictionary. Live Demo dictA= {'Mon':'Phy','Tue':'chem','Wed':'Math','Thu':'Bio'} key_list = ['Tue','Thu'] print("Given Dictionary:\n",dictA) print("Keys for filter:\n",key_list) res = [dictA[i] for i in key_list if i in dictA] print("Dictionary with filtered keys:\n",res) Running the above code gives us the following result − Given Dictionary: {'Mon': 'Phy', 'Tue': 'chem', 'Wed': 'Math', 'Thu': 'Bio'} Keys for filter: ['Tue', 'Thu'] Dictionary with filtered keys: ['chem', 'Bio'] We use intersection to find the common elements between the given dictionary and the list. Then apply the set function to get the distinct elements and convert the result to a list. Live Demo dictA= {'Mon':'Phy','Tue':'chem','Wed':'Math','Thu':'Bio'} key_list = ['Tue','Thu'] print("Given Dictionary:\n",dictA) print("Keys for filter:\n",key_list) temp = list(set(key_list).intersection(dictA)) res = [dictA[i] for i in temp] print("Dictionary with filtered keys:\n",res) Running the above code gives us the following result − Given Dictionary: {'Mon': 'Phy', 'Tue': 'chem', 'Wed': 'Math', 'Thu': 'Bio'} Keys for filter: ['Tue', 'Thu'] Dictionary with filtered keys: ['chem', 'Bio']
[ { "code": null, "e": 1257, "s": 1062, "text": "Sometimes in a Python dictionary we may need to to filter out certain keys of the dictionary based on certain criteria. In this article we will see how to filter out keys from Python dictionary." }, { "code": null, "e": 1520, "s": 1257, "text": "In this approach we put the values of the keys to be filtered in a list. Then iterate through each element of the list and check for its presence in the given dictionary. We create a resulting dictionary containing these values which are found in the dictionary." }, { "code": null, "e": 1531, "s": 1520, "text": " Live Demo" }, { "code": null, "e": 1784, "s": 1531, "text": "dictA= {'Mon':'Phy','Tue':'chem','Wed':'Math','Thu':'Bio'}\nkey_list = ['Tue','Thu']\n\nprint(\"Given Dictionary:\\n\",dictA)\nprint(\"Keys for filter:\\n\",key_list)\nres = [dictA[i] for i in key_list if i in dictA]\n\nprint(\"Dictionary with filtered keys:\\n\",res)" }, { "code": null, "e": 1839, "s": 1784, "text": "Running the above code gives us the following result −" }, { "code": null, "e": 2004, "s": 1839, "text": "Given Dictionary:\n {'Mon': 'Phy', 'Tue': 'chem', 'Wed': 'Math', 'Thu': 'Bio'}\nKeys for filter:\n ['Tue', 'Thu']\nDictionary with filtered keys:\n ['chem', 'Bio']" }, { "code": null, "e": 2186, "s": 2004, "text": "We use intersection to find the common elements between the given dictionary and the list. Then apply the set function to get the distinct elements and convert the result to a list." }, { "code": null, "e": 2197, "s": 2186, "text": " Live Demo" }, { "code": null, "e": 2481, "s": 2197, "text": "dictA= {'Mon':'Phy','Tue':'chem','Wed':'Math','Thu':'Bio'}\nkey_list = ['Tue','Thu']\n\nprint(\"Given Dictionary:\\n\",dictA)\nprint(\"Keys for filter:\\n\",key_list)\n\ntemp = list(set(key_list).intersection(dictA))\n\nres = [dictA[i] for i in temp]\n\nprint(\"Dictionary with filtered keys:\\n\",res)" }, { "code": null, "e": 2536, "s": 2481, "text": "Running the above code gives us the following result −" }, { "code": null, "e": 2701, "s": 2536, "text": "Given Dictionary:\n {'Mon': 'Phy', 'Tue': 'chem', 'Wed': 'Math', 'Thu': 'Bio'}\nKeys for filter:\n ['Tue', 'Thu']\nDictionary with filtered keys:\n ['chem', 'Bio']" } ]
How to move the ResultSet cursor to the first row in JDBC?
Whenever we execute SQL statements using the executeQuery() method, it returns a ResultSet object which holds the tabular data returned by the SELECT queries(in general). The ResultSet object contains a cursor/pointer which points to the current row. Initially this cursor is positioned before first row (default position). You can move the cursor of the ResultSet object to the first row from the current position, using the first() method of the ResultSet interface. rs.first() This method returns a boolean value specifying whether the cursor has been moved to the first row successfully. If there are no rows in the current ResultSet object this method returns false, else it returns true. Let us create a table with name tutorials_data in MySQL database using CREATE statement as shown below − CREATE TABLE tutorials_data ( tutorial_id INT, tutorial_title VARCHAR(100), tutorial_author VARCHAR(40), submission_date date, PRIMARY KEY (tutorial_id) ); Now, we will insert 5 records in tutorials_data table using INSERT statements − insert into tutorials_data values(1, 'Java', 'Krishna Kasyap', DATE('2019-09-01')); insert into tutorials_data values(2, 'JFreeCharts', 'Satish Kumar', DATE('2019-05-01 ')); insert into tutorials_data values(3, 'JavaSprings', 'Amit Tiwari', DATE(' 2019-05-01')); insert into tutorials_data values(4, 'Android', 'Sai Ram', DATE('2019-03-01')); insert into tutorials_data values(5, 'Cassandra', 'Pruthvi Raj', DATE(' 2019-04-06')); In the following JDBC program we have established connection with the database and retrieved the contents of the table named tutorials_data into a ResultSet object, initially the cursor in this object will be at the default position (before first row), using the first() method we have moved the cursor from default position to first row and, displayed the contents it. import java.sql.Connection; import java.sql.DriverManager; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; public class RSCursor_first { public static void main(String args[]) throws SQLException { //Registering the Driver DriverManager.registerDriver(new com.mysql.jdbc.Driver()); //Getting the connection String mysqlUrl = "jdbc:mysql://localhost/mydb"; Connection con = DriverManager.getConnection(mysqlUrl, "root", "password"); System.out.println("Connection established......"); //Creating the Statement Statement stmt = con.createStatement(); //Query to retrieve records String query = "Select * from tutorials_data"; //Executing the query ResultSet rs = stmt.executeQuery(query); //Moving the cursor from default position to 1st row. rs.first(); System.out.println("Contents of the first record: "); //Current record details. System.out.print("ID: "+rs.getInt("tutorial_id")+", "); System.out.print("Title: "+rs.getString("tutorial_title")+", "); System.out.print("Author: "+rs.getString("tutorial_author")+", "); System.out.print("Submission date: "+rs.getDate("submission_date")); } } Connection established...... Contents of the first record: ID: 1, Title: Java, Author: Krishna Kasyap, Submission date: 2019-09-01
[ { "code": null, "e": 1233, "s": 1062, "text": "Whenever we execute SQL statements using the executeQuery() method, it returns a ResultSet object which holds the tabular data returned by the SELECT queries(in general)." }, { "code": null, "e": 1386, "s": 1233, "text": "The ResultSet object contains a cursor/pointer which points to the current row. Initially this cursor is positioned before first row (default position)." }, { "code": null, "e": 1531, "s": 1386, "text": "You can move the cursor of the ResultSet object to the first row from the current position, using the first() method of the ResultSet interface." }, { "code": null, "e": 1542, "s": 1531, "text": "rs.first()" }, { "code": null, "e": 1654, "s": 1542, "text": "This method returns a boolean value specifying whether the cursor has been moved to the first row successfully." }, { "code": null, "e": 1756, "s": 1654, "text": "If there are no rows in the current ResultSet object this method returns false, else it returns true." }, { "code": null, "e": 1861, "s": 1756, "text": "Let us create a table with name tutorials_data in MySQL database using CREATE statement as shown below −" }, { "code": null, "e": 2032, "s": 1861, "text": "CREATE TABLE tutorials_data (\n tutorial_id INT,\n tutorial_title VARCHAR(100),\n tutorial_author VARCHAR(40),\n submission_date date,\n PRIMARY KEY (tutorial_id)\n);" }, { "code": null, "e": 2112, "s": 2032, "text": "Now, we will insert 5 records in tutorials_data table using INSERT statements −" }, { "code": null, "e": 2542, "s": 2112, "text": "insert into tutorials_data values(1, 'Java', 'Krishna Kasyap', DATE('2019-09-01'));\ninsert into tutorials_data values(2, 'JFreeCharts', 'Satish Kumar', DATE('2019-05-01 '));\ninsert into tutorials_data values(3, 'JavaSprings', 'Amit Tiwari', DATE(' 2019-05-01'));\ninsert into tutorials_data values(4, 'Android', 'Sai Ram', DATE('2019-03-01'));\ninsert into tutorials_data values(5, 'Cassandra', 'Pruthvi Raj', DATE(' 2019-04-06'));" }, { "code": null, "e": 2912, "s": 2542, "text": "In the following JDBC program we have established connection with the database and retrieved the contents of the table named tutorials_data into a ResultSet object, initially the cursor in this object will be at the default position (before first row), using the first() method we have moved the cursor from default position to first row and, displayed the contents it." }, { "code": null, "e": 4168, "s": 2912, "text": "import java.sql.Connection;\nimport java.sql.DriverManager;\nimport java.sql.ResultSet;\nimport java.sql.SQLException;\nimport java.sql.Statement;\npublic class RSCursor_first {\n public static void main(String args[]) throws SQLException {\n //Registering the Driver\n DriverManager.registerDriver(new com.mysql.jdbc.Driver());\n //Getting the connection\n String mysqlUrl = \"jdbc:mysql://localhost/mydb\";\n Connection con = DriverManager.getConnection(mysqlUrl, \"root\", \"password\");\n System.out.println(\"Connection established......\");\n //Creating the Statement\n Statement stmt = con.createStatement();\n //Query to retrieve records\n String query = \"Select * from tutorials_data\";\n //Executing the query\n ResultSet rs = stmt.executeQuery(query);\n //Moving the cursor from default position to 1st row.\n rs.first();\n System.out.println(\"Contents of the first record: \");\n //Current record details.\n System.out.print(\"ID: \"+rs.getInt(\"tutorial_id\")+\", \");\n System.out.print(\"Title: \"+rs.getString(\"tutorial_title\")+\", \");\n System.out.print(\"Author: \"+rs.getString(\"tutorial_author\")+\", \");\n System.out.print(\"Submission date: \"+rs.getDate(\"submission_date\"));\n }\n}" }, { "code": null, "e": 4299, "s": 4168, "text": "Connection established......\nContents of the first record:\nID: 1, Title: Java, Author: Krishna Kasyap, Submission date: 2019-09-01" } ]
Unary Operators Overloading in C++
The unary operators operate on a single operand and following are the examples of Unary operators − The increment (++) and decrement (--) operators. The unary minus (-) operator. The logical not (!) operator. The unary operators operate on the object for which they were called and normally, this operator appears on the left side of the object, as in !obj, -obj, and ++obj but sometime they can be used as postfix as well like obj++ or obj--. Following example explain how minus (-) operator can be overloaded for prefix as well as postfix usage. #include <iostream> using namespace std; class Distance { private: int feet; // 0 to infinite int inches; // 0 to 12 public: // required constructors Distance() { feet = 0; inches = 0; } Distance(int f, int i) { feet = f; inches = i; } // method to display distance void displayDistance() { cout << "F: " << feet << " I:" << inches <<endl; } // overloaded minus (-) operator Distance operator- () { feet = -feet; inches = -inches; return Distance(feet, inches); } }; int main() { Distance D1(11, 10), D2(-5, 11); -D1; // apply negation D1.displayDistance(); // display D1 -D2; // apply negation D2.displayDistance(); // display D2 return 0; } When the above code is compiled and executed, it produces the following result − F: -11 I:-10 F: 5 I:-11 Hope above example makes your concept clear and you can apply similar concept to overload Logical Not Operators (!). 154 Lectures 11.5 hours Arnab Chakraborty 14 Lectures 57 mins Kaushik Roy Chowdhury 30 Lectures 12.5 hours Frahaan Hussain 54 Lectures 3.5 hours Frahaan Hussain 77 Lectures 5.5 hours Frahaan Hussain 12 Lectures 3.5 hours Frahaan Hussain Print Add Notes Bookmark this page
[ { "code": null, "e": 2418, "s": 2318, "text": "The unary operators operate on a single operand and following are the examples of Unary operators −" }, { "code": null, "e": 2467, "s": 2418, "text": "The increment (++) and decrement (--) operators." }, { "code": null, "e": 2497, "s": 2467, "text": "The unary minus (-) operator." }, { "code": null, "e": 2527, "s": 2497, "text": "The logical not (!) operator." }, { "code": null, "e": 2762, "s": 2527, "text": "The unary operators operate on the object for which they were called and normally, this operator appears on the left side of the object, as in !obj, -obj, and ++obj but sometime they can be used as postfix as well like obj++ or obj--." }, { "code": null, "e": 2866, "s": 2762, "text": "Following example explain how minus (-) operator can be overloaded for prefix as well as postfix usage." }, { "code": null, "e": 3779, "s": 2866, "text": "#include <iostream>\nusing namespace std;\n \nclass Distance {\n private:\n int feet; // 0 to infinite\n int inches; // 0 to 12\n \n public:\n // required constructors\n Distance() {\n feet = 0;\n inches = 0;\n }\n Distance(int f, int i) {\n feet = f;\n inches = i;\n }\n \n // method to display distance\n void displayDistance() {\n cout << \"F: \" << feet << \" I:\" << inches <<endl;\n }\n \n // overloaded minus (-) operator\n Distance operator- () {\n feet = -feet;\n inches = -inches;\n return Distance(feet, inches);\n }\n};\n\nint main() {\n Distance D1(11, 10), D2(-5, 11);\n \n -D1; // apply negation\n D1.displayDistance(); // display D1\n\n -D2; // apply negation\n D2.displayDistance(); // display D2\n\n return 0;\n}" }, { "code": null, "e": 3860, "s": 3779, "text": "When the above code is compiled and executed, it produces the following result −" }, { "code": null, "e": 3885, "s": 3860, "text": "F: -11 I:-10\nF: 5 I:-11\n" }, { "code": null, "e": 4002, "s": 3885, "text": "Hope above example makes your concept clear and you can apply similar concept to overload Logical Not Operators (!)." }, { "code": null, "e": 4039, "s": 4002, "text": "\n 154 Lectures \n 11.5 hours \n" }, { "code": null, "e": 4058, "s": 4039, "text": " Arnab Chakraborty" }, { "code": null, "e": 4090, "s": 4058, "text": "\n 14 Lectures \n 57 mins\n" }, { "code": null, "e": 4113, "s": 4090, "text": " Kaushik Roy Chowdhury" }, { "code": null, "e": 4149, "s": 4113, "text": "\n 30 Lectures \n 12.5 hours \n" }, { "code": null, "e": 4166, "s": 4149, "text": " Frahaan Hussain" }, { "code": null, "e": 4201, "s": 4166, "text": "\n 54 Lectures \n 3.5 hours \n" }, { "code": null, "e": 4218, "s": 4201, "text": " Frahaan Hussain" }, { "code": null, "e": 4253, "s": 4218, "text": "\n 77 Lectures \n 5.5 hours \n" }, { "code": null, "e": 4270, "s": 4253, "text": " Frahaan Hussain" }, { "code": null, "e": 4305, "s": 4270, "text": "\n 12 Lectures \n 3.5 hours \n" }, { "code": null, "e": 4322, "s": 4305, "text": " Frahaan Hussain" }, { "code": null, "e": 4329, "s": 4322, "text": " Print" }, { "code": null, "e": 4340, "s": 4329, "text": " Add Notes" } ]
Unique BST's | Practice | GeeksforGeeks
Given an integer. Find how many structurally unique binary search trees are there that stores the values from 1 to that integer (inclusive). Example 1: Input: N = 2 Output: 2 Explanation:for N = 2, there are 2 unique BSTs 1 2 \ / 2 1 Example 2: Input: N = 3 Output: 5 Explanation: for N = 3, there are 5 possible BSTs 1 3 3 2 1 \ / / / \ \ 3 2 1 1 3 2 / / \ \ 2 1 2 3 Your Task: You don't need to read input or print anything. Your task is to complete the function numTrees() which takes the integer N as input and returns the total number of Binary Search Trees possible with keys [1.....N] inclusive. Since the answer can be very large, return the answer modulo 10e9 + 7. Expected Time Complexity: O(N2). Expected Auxiliary Space: O(N). Constraints: 1<=N<=1000 0 mohit negi3 days ago dp : bottom up O(N*N) idea : let n=4 1 2 3 4 root=1 (L: 0, R: 3) no of bst(0) * noof bst(3) + root=2 (1,2) bst(1)* bst(2); + .... sum( bst(i-1)*bst(n-i)) where i=1 to n; int numTrees(int n) { int dp[n+1]; dp[0]=1; dp[1]=1; for(int i=2;i<=n;i++) { long long sum=0; for(int j=1;j<=i;j++) { sum=((sum%mod)+((dp[j-1]%mod)*(dp[i-j]%mod))%mod)%mod; } dp[i]=sum%mod; } return dp[n]%mod; } 0 ambikagarg11011 week ago Using Memoization long long dp[1001]; long long MOD = 1e9+7; long long solve(int N) { if(dp[N]!=-1) { return dp[N]; } if(N==0 or N==1) { return dp[N] = 1; } else { long long sum=0; for(int i=1;i<=N;i++){ sum = (sum%MOD + ((solve(i-1)%MOD)*(solve(N-i)%MOD))%MOD)%MOD; } return dp[N] = sum; } } int numTrees(int N) { memset(dp,-1,sizeof(dp)); return (int)solve(N); } 0 vinamrajha1 week ago int numTrees(int N) { // Your code here // same as catalan number series long long d =1e9+7; int dp[N+1]; dp[0] =1; for(int i =1; i<=N; ++i){ dp[i] =0; for(int j =0; j<i; ++j)dp[i] =(dp[i]%d+(dp[j]%d*dp[i-j-1]%d))%d; } return dp[N]; } 0 shivam1706203 weeks ago //Function to return the total number of possible unique BST. long long mod=1e9+7; int numTrees(int n) { // Your code here vector<int> dp(n+1 , 0); // catalan number(n) = summation i=0 , n-1 ( c(i)*c(n-i-1)) // c(n)=c(0)*c(n-1) + c(1)*c(n-2) + c(2)*c(n-3) + ... + c(n-2)*c(1) + c(n-1)*c(0) dp[0]=1;// base case; for(int i=1 ;i<=n;i++) { for(int j=0;j<i;j++) { dp[i]=(dp[i]%mod + (dp[j]%mod * dp[i-j-1]%mod)%mod)%mod; } } return dp[n]; } 0 yugi20003 weeks ago Complete Java Solution: static int numTrees(int N) { // Your code goes here long[] dp = new long[N+1]; int mod = 1000000007; dp[0] = 1; for(int i = 1; i < N+1; ++i) { long bsts = 0; for(int low = 0, high = i-1; low < i; ++low, --high) { bsts += (dp[low]%mod * dp[high]%mod)%mod; } dp[i] = bsts%mod; } return (int)dp[N]; } 0 devashishbakare3 weeks ago Get better understanding of this cattlon number explanation 0 rohitjug19csPremium1 month ago Just needed to find nth catalan number : static int numTrees(int n) { int mod = 1000000007; long dp[] = new long[n+1]; dp[0] = 1; dp[1] = 1; for(int i=2; i<n+1; i++){ for(int j=0, k=i-1; j<i && k>=0; j++, k--) dp[i] = (dp[i] + (dp[j]*dp[k])%mod)%mod; } return (int)dp[n]; } 0 vishalpandey100220002 months ago static int mod = 1000000007; static int numTrees(int N) { // Your code goes here long dp[]=new long[N+1]; dp[0]=1; for (int i=1;i<=N;i++){ dp[i]=0; for (int j=0;j<i;j++){ dp[i]=(dp[i]+dp[j]*dp[i-j-1])%mod; } } return (int)dp[N]; } 0 lindan1232 months ago public: //Function to return the total number of possible unique BST. int numTrees(int n) { long long dp[n+1]; int sum=0; dp[0]=1; dp[1]=1; long long mod = 1000000007; for(int i=2;i<=n;i++) { sum=0; for(int j=1;j<=i;j++) { sum = (sum+(dp[i-j]*dp[j-1])%mod)%mod; } dp[i] = sum; } return dp[n]; } Time Taken : 0.1 Cpp +1 onibabahaha1234565 months ago Just use nth catalan number technique :) int numTrees(int N) { // Your code here long long mod=1000000007; long long dp[N+1]; dp[0]=1; dp[1]=1; for (int i=2;i<N+1;i++){ long long sum=0; for (int j=0, k=i-1;j<i,k>=0;j++,k--){ sum=(sum+(dp[j]*dp[k])%mod)%mod; } dp[i]=sum; } return dp[N]%mod; } 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": 380, "s": 238, "text": "Given an integer. Find how many structurally unique binary search trees are there that stores the values from 1 to that integer (inclusive). " }, { "code": null, "e": 391, "s": 380, "text": "Example 1:" }, { "code": null, "e": 527, "s": 391, "text": "Input:\nN = 2\nOutput: 2\nExplanation:for N = 2, there are 2 unique\nBSTs\n 1 2 \n \\ /\n 2 1\n" }, { "code": null, "e": 538, "s": 527, "text": "Example 2:" }, { "code": null, "e": 801, "s": 538, "text": "Input:\nN = 3\nOutput: 5\nExplanation: for N = 3, there are 5\npossible BSTs\n 1 3 3 2 1\n \\ / / / \\ \\\n 3 2 1 1 3 2\n / / \\ \\\n 2 1 2 3" }, { "code": null, "e": 1109, "s": 803, "text": "Your Task:\nYou don't need to read input or print anything. Your task is to complete the function numTrees() which takes the integer N as input and returns the total number of Binary Search Trees possible with keys [1.....N] inclusive. Since the answer can be very large, return the answer modulo 10e9 + 7." }, { "code": null, "e": 1174, "s": 1109, "text": "Expected Time Complexity: O(N2).\nExpected Auxiliary Space: O(N)." }, { "code": null, "e": 1198, "s": 1174, "text": "Constraints:\n1<=N<=1000" }, { "code": null, "e": 1200, "s": 1198, "text": "0" }, { "code": null, "e": 1221, "s": 1200, "text": "mohit negi3 days ago" }, { "code": null, "e": 1243, "s": 1221, "text": "dp : bottom up O(N*N)" }, { "code": null, "e": 1250, "s": 1243, "text": "idea :" }, { "code": null, "e": 1258, "s": 1250, "text": "let n=4" }, { "code": null, "e": 1266, "s": 1258, "text": "1 2 3 4" }, { "code": null, "e": 1313, "s": 1266, "text": "root=1 (L: 0, R: 3) no of bst(0) * noof bst(3)" }, { "code": null, "e": 1315, "s": 1313, "text": "+" }, { "code": null, "e": 1345, "s": 1315, "text": "root=2 (1,2) bst(1)* bst(2);" }, { "code": null, "e": 1347, "s": 1345, "text": "+" }, { "code": null, "e": 1352, "s": 1347, "text": "...." }, { "code": null, "e": 1392, "s": 1352, "text": "sum( bst(i-1)*bst(n-i)) where i=1 to n;" }, { "code": null, "e": 1728, "s": 1394, "text": "int numTrees(int n) { int dp[n+1]; dp[0]=1; dp[1]=1; for(int i=2;i<=n;i++) { long long sum=0; for(int j=1;j<=i;j++) { sum=((sum%mod)+((dp[j-1]%mod)*(dp[i-j]%mod))%mod)%mod; } dp[i]=sum%mod; } return dp[n]%mod; }" }, { "code": null, "e": 1730, "s": 1728, "text": "0" }, { "code": null, "e": 1755, "s": 1730, "text": "ambikagarg11011 week ago" }, { "code": null, "e": 1773, "s": 1755, "text": "Using Memoization" }, { "code": null, "e": 2257, "s": 1775, "text": "long long dp[1001]; long long MOD = 1e9+7; long long solve(int N) { if(dp[N]!=-1) { return dp[N]; } if(N==0 or N==1) { return dp[N] = 1; } else { long long sum=0; for(int i=1;i<=N;i++){ sum = (sum%MOD + ((solve(i-1)%MOD)*(solve(N-i)%MOD))%MOD)%MOD; } return dp[N] = sum; } } int numTrees(int N) { memset(dp,-1,sizeof(dp)); return (int)solve(N); }" }, { "code": null, "e": 2259, "s": 2257, "text": "0" }, { "code": null, "e": 2280, "s": 2259, "text": "vinamrajha1 week ago" }, { "code": null, "e": 2600, "s": 2280, "text": "int numTrees(int N) \n {\n // Your code here\n // same as catalan number series\n long long d =1e9+7;\n int dp[N+1];\n dp[0] =1;\n for(int i =1; i<=N; ++i){\n dp[i] =0;\n for(int j =0; j<i; ++j)dp[i] =(dp[i]%d+(dp[j]%d*dp[i-j-1]%d))%d;\n }\n return dp[N];\n }" }, { "code": null, "e": 2602, "s": 2600, "text": "0" }, { "code": null, "e": 2626, "s": 2602, "text": "shivam1706203 weeks ago" }, { "code": null, "e": 3200, "s": 2626, "text": " //Function to return the total number of possible unique BST. long long mod=1e9+7; int numTrees(int n) { // Your code here vector<int> dp(n+1 , 0); // catalan number(n) = summation i=0 , n-1 ( c(i)*c(n-i-1)) // c(n)=c(0)*c(n-1) + c(1)*c(n-2) + c(2)*c(n-3) + ... + c(n-2)*c(1) + c(n-1)*c(0) dp[0]=1;// base case; for(int i=1 ;i<=n;i++) { for(int j=0;j<i;j++) { dp[i]=(dp[i]%mod + (dp[j]%mod * dp[i-j-1]%mod)%mod)%mod; } } return dp[n]; }" }, { "code": null, "e": 3202, "s": 3200, "text": "0" }, { "code": null, "e": 3222, "s": 3202, "text": "yugi20003 weeks ago" }, { "code": null, "e": 3246, "s": 3222, "text": "Complete Java Solution:" }, { "code": null, "e": 3701, "s": 3248, "text": " static int numTrees(int N)\n {\n // Your code goes here\n long[] dp = new long[N+1];\n int mod = 1000000007;\n dp[0] = 1;\n \n for(int i = 1; i < N+1; ++i) {\n long bsts = 0;\n for(int low = 0, high = i-1; low < i; ++low, --high) {\n bsts += (dp[low]%mod * dp[high]%mod)%mod;\n }\n dp[i] = bsts%mod;\n }\n \n return (int)dp[N];\n }\n " }, { "code": null, "e": 3703, "s": 3701, "text": "0" }, { "code": null, "e": 3730, "s": 3703, "text": "devashishbakare3 weeks ago" }, { "code": null, "e": 3791, "s": 3730, "text": "Get better understanding of this cattlon number explanation" }, { "code": null, "e": 3793, "s": 3791, "text": "0" }, { "code": null, "e": 3824, "s": 3793, "text": "rohitjug19csPremium1 month ago" }, { "code": null, "e": 3865, "s": 3824, "text": "Just needed to find nth catalan number :" }, { "code": null, "e": 4227, "s": 3865, "text": "static int numTrees(int n)\n {\n int mod = 1000000007; \n long dp[] = new long[n+1];\n dp[0] = 1;\n dp[1] = 1;\n \n for(int i=2; i<n+1; i++){\n for(int j=0, k=i-1; j<i && k>=0; j++, k--)\n dp[i] = (dp[i] + (dp[j]*dp[k])%mod)%mod;\n \n \n }\n return (int)dp[n];\n \n }" }, { "code": null, "e": 4229, "s": 4227, "text": "0" }, { "code": null, "e": 4262, "s": 4229, "text": "vishalpandey100220002 months ago" }, { "code": null, "e": 4594, "s": 4262, "text": " static int mod = 1000000007; static int numTrees(int N) { // Your code goes here long dp[]=new long[N+1]; dp[0]=1; for (int i=1;i<=N;i++){ dp[i]=0; for (int j=0;j<i;j++){ dp[i]=(dp[i]+dp[j]*dp[i-j-1])%mod; } } return (int)dp[N]; }" }, { "code": null, "e": 4596, "s": 4594, "text": "0" }, { "code": null, "e": 4618, "s": 4596, "text": "lindan1232 months ago" }, { "code": null, "e": 5098, "s": 4618, "text": "public:\n //Function to return the total number of possible unique BST. \n int numTrees(int n) \n {\n long long dp[n+1];\n int sum=0;\n dp[0]=1;\n dp[1]=1;\n long long mod = 1000000007;\n for(int i=2;i<=n;i++)\n {\n sum=0;\n for(int j=1;j<=i;j++)\n {\n sum = (sum+(dp[i-j]*dp[j-1])%mod)%mod;\n }\n dp[i] = sum;\n }\n \n \n return dp[n];\n }" }, { "code": null, "e": 5115, "s": 5098, "text": "Time Taken : 0.1" }, { "code": null, "e": 5119, "s": 5115, "text": "Cpp" }, { "code": null, "e": 5122, "s": 5119, "text": "+1" }, { "code": null, "e": 5152, "s": 5122, "text": "onibabahaha1234565 months ago" }, { "code": null, "e": 5193, "s": 5152, "text": "Just use nth catalan number technique :)" }, { "code": null, "e": 5583, "s": 5193, "text": " int numTrees(int N) \n {\n // Your code here\n long long mod=1000000007;\n long long dp[N+1];\n dp[0]=1;\n dp[1]=1;\n for (int i=2;i<N+1;i++){\n long long sum=0;\n for (int j=0, k=i-1;j<i,k>=0;j++,k--){\n sum=(sum+(dp[j]*dp[k])%mod)%mod;\n }\n dp[i]=sum;\n }\n return dp[N]%mod;\n }" }, { "code": null, "e": 5729, "s": 5583, "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": 5765, "s": 5729, "text": " Login to access your submissions. " }, { "code": null, "e": 5775, "s": 5765, "text": "\nProblem\n" }, { "code": null, "e": 5785, "s": 5775, "text": "\nContest\n" }, { "code": null, "e": 5848, "s": 5785, "text": "Reset the IDE using the second button on the top right corner." }, { "code": null, "e": 5996, "s": 5848, "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": 6204, "s": 5996, "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": 6310, "s": 6204, "text": "You can access the hints to get an idea about what is expected of you as well as the final solution code." } ]
Java Program to center a JLabel in a JPanel with LayoutManager
Here, we are using the LayoutManager GridBagLayout to center the components. We have two components here including a label and we have set the layout as GridBagLayout − JLabel label = new JLabel("Name (Centered Label): "); JTextArea text = new JTextArea(); text.setText("Add name here..."); panel.setLayout(new GridBagLayout()); The following is an example to center a JLabel in a JPanel with LayoutManager − package my; import java.awt.GridBagLayout; import javax.swing.BorderFactory; import javax.swing.JFrame; import javax.swing.JLabel; import javax.swing.JPanel; import javax.swing.JTextArea; import javax.swing.WindowConstants; public class SwingDemo { public static void main(String[] args) { JFrame frame = new JFrame("Demo Frame"); JPanel panel = new JPanel(); JLabel label = new JLabel("Name (Centered Label): "); JTextArea text = new JTextArea(); text.setText("Add name here..."); panel.setLayout(new GridBagLayout()); panel.add(label); panel.add(text); panel.setBorder(BorderFactory.createEmptyBorder(10, 10, 10, 10)); frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE); frame.add(panel); frame.setSize(500, 300); frame.setVisible(true); } }
[ { "code": null, "e": 1231, "s": 1062, "text": "Here, we are using the LayoutManager GridBagLayout to center the components. We have two components here including a label and we have set the layout as GridBagLayout −" }, { "code": null, "e": 1391, "s": 1231, "text": "JLabel label = new JLabel(\"Name (Centered Label): \");\nJTextArea text = new JTextArea();\ntext.setText(\"Add name here...\");\npanel.setLayout(new GridBagLayout());" }, { "code": null, "e": 1471, "s": 1391, "text": "The following is an example to center a JLabel in a JPanel with LayoutManager −" }, { "code": null, "e": 2310, "s": 1471, "text": "package my;\nimport java.awt.GridBagLayout;\nimport javax.swing.BorderFactory;\nimport javax.swing.JFrame;\nimport javax.swing.JLabel;\nimport javax.swing.JPanel;\nimport javax.swing.JTextArea;\nimport javax.swing.WindowConstants;\npublic class SwingDemo {\n public static void main(String[] args) {\n JFrame frame = new JFrame(\"Demo Frame\");\n JPanel panel = new JPanel();\n JLabel label = new JLabel(\"Name (Centered Label): \");\n JTextArea text = new JTextArea();\n text.setText(\"Add name here...\");\n panel.setLayout(new GridBagLayout());\n panel.add(label);\n panel.add(text);\n panel.setBorder(BorderFactory.createEmptyBorder(10, 10, 10, 10));\n frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);\n frame.add(panel);\n frame.setSize(500, 300);\n frame.setVisible(true);\n }\n}" } ]
Every Complex DataFrame Manipulation, Explained and Visualized Intuitively | by Andre Ye | Towards Data Science
Pandas offers a wide range of DataFrame manipulations, but many of them are complex and may not seem approachable. This article will present 8 essential DataFrame manipulation methods which cover almost all of the manipulation functions a data scientist would need to know. Each method will include an explanation, visualization, code, and tricks to remember it. All images by author. Pivoting a table creates a new ‘pivoted table’ that projects existing columns in the data as elements of a new table, being the index, column, and the values. The columns in the initial DataFrame that will become the index and the columns are displayed as unique values, and combinations of these two columns will be displayed as the value. This means that pivots cannot handle duplicate values. The code to pivot a DataFrame named df is as follows: df.pivot(index='foo', columns='bar', values='baz') To memorize: A pivot is — outside the realm of data manipulation — a turn around some sort of object. In sports, one can ‘pivot’ around their foot to spin: pivots in pandas are similar. The state of the original DataFrame are pivoted around central elements of a DataFrame into a new one. Some elements very literally pivot in that they are rotated or transformed(like column ‘bar’). Melting can be thought of as an ‘unpivot’, in that it converts a matrix-based data (has two dimensions) into list-based data (columns represent values and rows indicate unique data points), whereas pivots do the opposite. Consider a two-dimensional matrix with one dimension ‘B’ and ‘C’ (column names), with the other dimension ‘a’, ‘b’, and ‘c’ (row indices). We select an ID, one of the dimensions, and a column/columns to contain values. The column(s) that contain values are transformed into two columns: one for the variable (the name of the value column) and another for the value (the number contained in it). The result is every combination of the ID column’s values (a, b, c) and the value columns (B, C), with its corresponding value, organized in list format. The melt operation can be performed like such on DataFrame df: df.melt(id_vars=['A'], value_vars=['B','C']) To memorize: Melting something like a candle is to turn a solidified and composite object into several much smaller, individual elements (wax droplets). Melting a two-dimensional DataFrame unpacks its solidified structure and records its pieces as individual entries in a list. Exploding is a helpful method to get rid of lists in the data. When a column is exploded, all lists inside of it are listed as new rows under the same index (to prevent this, simply call .reset_index() afterwards). Non-list items like strings or numbers are not affected, and empty lists are NaN values (you can cleanse these using .dropna()). Exploding a column ‘A’ in DataFrame df is very simple: df.explode(‘A’) To remember: Exploding something releases all its internal contents — exploding a list separates its elements. Stacking takes a DataFrame of any size and ‘stacks’ the columns as subindices of existing indices. Hence, the resulting DataFrame has only one column and two levels of indices. Stacking a table named df is as simple as df.stack(). In order to access the value of, say, the dog’s height, simply call an index-based retrieval twice, like df.loc[‘dog’].loc[‘height’]. To remember: Visually, stack takes the two-dimensionality of a table can stacks the columns into multi-level indices. Unstacking takes a multi-index DataFrame and unstacks it, converting the indices in a specified level into columns of a new DataFrame with its corresponding values. Calling a stack followed by an unstack on a table will not change it (excusing the existence of a ‘0’). A parameter in unstacking is its level. In list indexing, an index of -1 will return the last element; this is the same with levels. A level of -1 indicates that the last index level (the one rightmost) will be unstacked. As a further example, when the level is set to 0 (the first index level), values in it become columns and the following index level (the second) becomes the transformed DataFrame’s index. Unstacking can be performed the same as stacking, but with the level parameter: df.unstack(level=-1). To remember: Unstack means “to undo a stack”. To merge two DataFrames is to combine them column-wise (horizontally) among a shared ‘key’. This key allows for the tables to be combined, even if they are not ordered similarly. The finished merged DataFrame will add suffixes _x and _y to value columns by default. In order to merge two DataFrames df1 and df2 (where df1 contains the leftkey and df2 contains the rightkey), call: df1.merge(df2, left_on='leftkey', right_on='rightkey') Merges are not functions of pandas but attached to a DataFrame. It is always assumed that the DataFrame in which the merge is being attached to is the ‘left table’ and the DataFrame called as a parameter in the function is the ‘right table’, with corresponding keys. The merge function performs by default what is called an inner join: if each of the DataFrames have a key not listed in the other’s, it is not included in the merged DataFrame. On the other hand, if a key is listed twice in the same DataFrame, every combination of values for the same keys is listed in the merged table. For example, if df1 has 3 values for key foo and df2 had 2 values for the same key, there would be 6 entries with leftkey=foo and rightkey=foo in the final DataFrame. To remember: You merge DataFrames like you merge lanes when driving — horizontally. Imagine each of the columns as one lane on the highway; in order to merge, they must combine horizontally. Joins are generally preferred over merge because it has a cleaner syntax and a wider range of possibilities in joining two DataFrames horizontally. The syntax of a join is as follows: df1.join(other=df2, on='common_key', how='join_method') When using joins, the common key column (analogous to right_on and left_on in merge) must be named the same name. The how parameter is a string referring to one of four methods join can combine two DataFrames: ‘left’: Include all elements of df1, accompanied with elements of df2 only if their key is a key of df1. Otherwise, the missing portion of the merged DataFrame for df2 will be marked as NaN. ‘right’: ‘left’, but on the other DataFrame. Include all elements of df2, accompanied with elements of df1 only if their key is a key of df2. ‘outer’: Include all elements from both DataFrames, even if a key is not present in the other’s — missing elements are marked as NaN. ‘inner’: Include only elements whose keys are present in both DataFrame keys (intersection). Default for merge. To remember: If you’ve worked with SQL, the word ‘join’ should immediately by associated with column-wise addition. If not, ‘join’ and ‘merge’ have very similar meanings definition-wise. Whereas merges and joins work horizontally, concatenations, or concats for short, attach DataFrames row-wise (vertically). Consider, for example, two DataFrames df1 and df2 with the same column names, concatenated using pandas.concat([df1, df2]): Although you can use concat for column-wise joining by turning the axis parameter to 1, it would be easier just to use join. Note that concat is a pandas function and not one of a DataFrame. Hence, it takes in a list of DataFrames to be concatenated. If a DataFrame has a column not included in the other, by default it will be included, with missing values listed as NaN. To prevent this, add an additional parameter join=’inner’, which will only concatenate columns both DataFrames have in common. To remember: In lists and strings, additional items can be concatenated. Concatenation is the appendage of additional elements to an existing body, not the adding of new information (as is column-wise joining). Since each index/row is an individual item, concatenation adds additional items to a DataFrame, which can be thought of as a list of rows. Append is another method to combine two DataFrames, but it performs the same functionality as concat and is less efficient and versatile. Although these functions cover a wide range of what you may need to manipulate your data for, sometimes the data manipulation required is too complex for one or even a series of functions to perform. Explore complex data manipulation methods like parser functions, iterative projection, efficient parsing, and more here: medium.com If you’re interested in staying updated on new articles, consider subscribing. If you’d like to support my writing, joining Medium via my referral link is a great way. Cheers!
[ { "code": null, "e": 535, "s": 172, "text": "Pandas offers a wide range of DataFrame manipulations, but many of them are complex and may not seem approachable. This article will present 8 essential DataFrame manipulation methods which cover almost all of the manipulation functions a data scientist would need to know. Each method will include an explanation, visualization, code, and tricks to remember it." }, { "code": null, "e": 557, "s": 535, "text": "All images by author." }, { "code": null, "e": 953, "s": 557, "text": "Pivoting a table creates a new ‘pivoted table’ that projects existing columns in the data as elements of a new table, being the index, column, and the values. The columns in the initial DataFrame that will become the index and the columns are displayed as unique values, and combinations of these two columns will be displayed as the value. This means that pivots cannot handle duplicate values." }, { "code": null, "e": 1007, "s": 953, "text": "The code to pivot a DataFrame named df is as follows:" }, { "code": null, "e": 1058, "s": 1007, "text": "df.pivot(index='foo', columns='bar', values='baz')" }, { "code": null, "e": 1442, "s": 1058, "text": "To memorize: A pivot is — outside the realm of data manipulation — a turn around some sort of object. In sports, one can ‘pivot’ around their foot to spin: pivots in pandas are similar. The state of the original DataFrame are pivoted around central elements of a DataFrame into a new one. Some elements very literally pivot in that they are rotated or transformed(like column ‘bar’)." }, { "code": null, "e": 1803, "s": 1442, "text": "Melting can be thought of as an ‘unpivot’, in that it converts a matrix-based data (has two dimensions) into list-based data (columns represent values and rows indicate unique data points), whereas pivots do the opposite. Consider a two-dimensional matrix with one dimension ‘B’ and ‘C’ (column names), with the other dimension ‘a’, ‘b’, and ‘c’ (row indices)." }, { "code": null, "e": 2059, "s": 1803, "text": "We select an ID, one of the dimensions, and a column/columns to contain values. The column(s) that contain values are transformed into two columns: one for the variable (the name of the value column) and another for the value (the number contained in it)." }, { "code": null, "e": 2213, "s": 2059, "text": "The result is every combination of the ID column’s values (a, b, c) and the value columns (B, C), with its corresponding value, organized in list format." }, { "code": null, "e": 2276, "s": 2213, "text": "The melt operation can be performed like such on DataFrame df:" }, { "code": null, "e": 2321, "s": 2276, "text": "df.melt(id_vars=['A'], value_vars=['B','C'])" }, { "code": null, "e": 2599, "s": 2321, "text": "To memorize: Melting something like a candle is to turn a solidified and composite object into several much smaller, individual elements (wax droplets). Melting a two-dimensional DataFrame unpacks its solidified structure and records its pieces as individual entries in a list." }, { "code": null, "e": 2943, "s": 2599, "text": "Exploding is a helpful method to get rid of lists in the data. When a column is exploded, all lists inside of it are listed as new rows under the same index (to prevent this, simply call .reset_index() afterwards). Non-list items like strings or numbers are not affected, and empty lists are NaN values (you can cleanse these using .dropna())." }, { "code": null, "e": 2998, "s": 2943, "text": "Exploding a column ‘A’ in DataFrame df is very simple:" }, { "code": null, "e": 3014, "s": 2998, "text": "df.explode(‘A’)" }, { "code": null, "e": 3125, "s": 3014, "text": "To remember: Exploding something releases all its internal contents — exploding a list separates its elements." }, { "code": null, "e": 3302, "s": 3125, "text": "Stacking takes a DataFrame of any size and ‘stacks’ the columns as subindices of existing indices. Hence, the resulting DataFrame has only one column and two levels of indices." }, { "code": null, "e": 3356, "s": 3302, "text": "Stacking a table named df is as simple as df.stack()." }, { "code": null, "e": 3490, "s": 3356, "text": "In order to access the value of, say, the dog’s height, simply call an index-based retrieval twice, like df.loc[‘dog’].loc[‘height’]." }, { "code": null, "e": 3608, "s": 3490, "text": "To remember: Visually, stack takes the two-dimensionality of a table can stacks the columns into multi-level indices." }, { "code": null, "e": 3877, "s": 3608, "text": "Unstacking takes a multi-index DataFrame and unstacks it, converting the indices in a specified level into columns of a new DataFrame with its corresponding values. Calling a stack followed by an unstack on a table will not change it (excusing the existence of a ‘0’)." }, { "code": null, "e": 4287, "s": 3877, "text": "A parameter in unstacking is its level. In list indexing, an index of -1 will return the last element; this is the same with levels. A level of -1 indicates that the last index level (the one rightmost) will be unstacked. As a further example, when the level is set to 0 (the first index level), values in it become columns and the following index level (the second) becomes the transformed DataFrame’s index." }, { "code": null, "e": 4389, "s": 4287, "text": "Unstacking can be performed the same as stacking, but with the level parameter: df.unstack(level=-1)." }, { "code": null, "e": 4435, "s": 4389, "text": "To remember: Unstack means “to undo a stack”." }, { "code": null, "e": 4701, "s": 4435, "text": "To merge two DataFrames is to combine them column-wise (horizontally) among a shared ‘key’. This key allows for the tables to be combined, even if they are not ordered similarly. The finished merged DataFrame will add suffixes _x and _y to value columns by default." }, { "code": null, "e": 4816, "s": 4701, "text": "In order to merge two DataFrames df1 and df2 (where df1 contains the leftkey and df2 contains the rightkey), call:" }, { "code": null, "e": 4871, "s": 4816, "text": "df1.merge(df2, left_on='leftkey', right_on='rightkey')" }, { "code": null, "e": 5138, "s": 4871, "text": "Merges are not functions of pandas but attached to a DataFrame. It is always assumed that the DataFrame in which the merge is being attached to is the ‘left table’ and the DataFrame called as a parameter in the function is the ‘right table’, with corresponding keys." }, { "code": null, "e": 5626, "s": 5138, "text": "The merge function performs by default what is called an inner join: if each of the DataFrames have a key not listed in the other’s, it is not included in the merged DataFrame. On the other hand, if a key is listed twice in the same DataFrame, every combination of values for the same keys is listed in the merged table. For example, if df1 has 3 values for key foo and df2 had 2 values for the same key, there would be 6 entries with leftkey=foo and rightkey=foo in the final DataFrame." }, { "code": null, "e": 5817, "s": 5626, "text": "To remember: You merge DataFrames like you merge lanes when driving — horizontally. Imagine each of the columns as one lane on the highway; in order to merge, they must combine horizontally." }, { "code": null, "e": 6001, "s": 5817, "text": "Joins are generally preferred over merge because it has a cleaner syntax and a wider range of possibilities in joining two DataFrames horizontally. The syntax of a join is as follows:" }, { "code": null, "e": 6057, "s": 6001, "text": "df1.join(other=df2, on='common_key', how='join_method')" }, { "code": null, "e": 6267, "s": 6057, "text": "When using joins, the common key column (analogous to right_on and left_on in merge) must be named the same name. The how parameter is a string referring to one of four methods join can combine two DataFrames:" }, { "code": null, "e": 6458, "s": 6267, "text": "‘left’: Include all elements of df1, accompanied with elements of df2 only if their key is a key of df1. Otherwise, the missing portion of the merged DataFrame for df2 will be marked as NaN." }, { "code": null, "e": 6600, "s": 6458, "text": "‘right’: ‘left’, but on the other DataFrame. Include all elements of df2, accompanied with elements of df1 only if their key is a key of df2." }, { "code": null, "e": 6734, "s": 6600, "text": "‘outer’: Include all elements from both DataFrames, even if a key is not present in the other’s — missing elements are marked as NaN." }, { "code": null, "e": 6846, "s": 6734, "text": "‘inner’: Include only elements whose keys are present in both DataFrame keys (intersection). Default for merge." }, { "code": null, "e": 7033, "s": 6846, "text": "To remember: If you’ve worked with SQL, the word ‘join’ should immediately by associated with column-wise addition. If not, ‘join’ and ‘merge’ have very similar meanings definition-wise." }, { "code": null, "e": 7280, "s": 7033, "text": "Whereas merges and joins work horizontally, concatenations, or concats for short, attach DataFrames row-wise (vertically). Consider, for example, two DataFrames df1 and df2 with the same column names, concatenated using pandas.concat([df1, df2]):" }, { "code": null, "e": 7405, "s": 7280, "text": "Although you can use concat for column-wise joining by turning the axis parameter to 1, it would be easier just to use join." }, { "code": null, "e": 7531, "s": 7405, "text": "Note that concat is a pandas function and not one of a DataFrame. Hence, it takes in a list of DataFrames to be concatenated." }, { "code": null, "e": 7780, "s": 7531, "text": "If a DataFrame has a column not included in the other, by default it will be included, with missing values listed as NaN. To prevent this, add an additional parameter join=’inner’, which will only concatenate columns both DataFrames have in common." }, { "code": null, "e": 8130, "s": 7780, "text": "To remember: In lists and strings, additional items can be concatenated. Concatenation is the appendage of additional elements to an existing body, not the adding of new information (as is column-wise joining). Since each index/row is an individual item, concatenation adds additional items to a DataFrame, which can be thought of as a list of rows." }, { "code": null, "e": 8268, "s": 8130, "text": "Append is another method to combine two DataFrames, but it performs the same functionality as concat and is less efficient and versatile." }, { "code": null, "e": 8589, "s": 8268, "text": "Although these functions cover a wide range of what you may need to manipulate your data for, sometimes the data manipulation required is too complex for one or even a series of functions to perform. Explore complex data manipulation methods like parser functions, iterative projection, efficient parsing, and more here:" }, { "code": null, "e": 8600, "s": 8589, "text": "medium.com" } ]
Delegates in C#
A delegate in C# is a reference to the method. A delegate is a reference type variable that holds the reference to a method. The reference can be changed at runtime. Delegates are especially used for implementing events and the call-back methods. All delegates are implicitly derived from the System.Delegate class. Let us see how to declare delegates in C#. delegate <return type> <delegate-name> <parameter list> Let us see an example to learn how to work with Delegates in C#. Live Demo using System; using System.IO; namespace DelegateAppl { class PrintString { static FileStream fs; static StreamWriter sw; // delegate declaration public delegate void printString(string s); // this method prints to the console public static void WriteToScreen(string str) { Console.WriteLine("The String is: {0}", str); } // this method prints to a file public static void WriteToFile(string s) { fs = new FileStream("c:\\message.txt", FileMode.Append, FileAccess.Write); sw = new StreamWriter(fs); sw.WriteLine(s); sw.Flush(); sw.Close(); fs.Close(); } // this method takes the delegate as parameter and uses it to // call the methods as required public static void sendString(printString ps) { ps("Hello World"); } static void Main(string[] args) { printString ps1 = new printString(WriteToScreen); printString ps2 = new printString(WriteToFile); sendString(ps1); sendString(ps2); Console.ReadKey(); } } } The String is: Hello World
[ { "code": null, "e": 1228, "s": 1062, "text": "A delegate in C# is a reference to the method. A delegate is a reference type variable that holds the reference to a method. The reference can be changed at runtime." }, { "code": null, "e": 1378, "s": 1228, "text": "Delegates are especially used for implementing events and the call-back methods. All delegates are implicitly derived from the System.Delegate class." }, { "code": null, "e": 1421, "s": 1378, "text": "Let us see how to declare delegates in C#." }, { "code": null, "e": 1477, "s": 1421, "text": "delegate <return type> <delegate-name> <parameter list>" }, { "code": null, "e": 1542, "s": 1477, "text": "Let us see an example to learn how to work with Delegates in C#." }, { "code": null, "e": 1553, "s": 1542, "text": " Live Demo" }, { "code": null, "e": 2689, "s": 1553, "text": "using System;\nusing System.IO;\nnamespace DelegateAppl {\n class PrintString {\n static FileStream fs;\n static StreamWriter sw;\n // delegate declaration\n public delegate void printString(string s);\n // this method prints to the console\n public static void WriteToScreen(string str) {\n Console.WriteLine(\"The String is: {0}\", str);\n }\n // this method prints to a file\n public static void WriteToFile(string s) {\n fs = new FileStream(\"c:\\\\message.txt\",\n FileMode.Append, FileAccess.Write);\n sw = new StreamWriter(fs);\n sw.WriteLine(s);\n sw.Flush();\n sw.Close();\n fs.Close();\n }\n // this method takes the delegate as parameter and uses it to\n // call the methods as required\n public static void sendString(printString ps) {\n ps(\"Hello World\");\n }\n static void Main(string[] args) {\n printString ps1 = new printString(WriteToScreen);\n printString ps2 = new printString(WriteToFile);\n sendString(ps1);\n sendString(ps2);\n Console.ReadKey();\n }\n }\n}" }, { "code": null, "e": 2716, "s": 2689, "text": "The String is: Hello World" } ]
Time series classification using Dynamic Time Warping | by Nikos Kafritsas | Towards Data Science
Time series classification is a common task, having many applications in numerous domains like IOT (Internet of things), signal processing, human activity recognition and so on. The goal is to train a model that can accurately predict the class of a time series, given a dataset with labeled time sequences. A popular approach to tackle this problem is to use the K-Nearest Neighbors algorithm, but instead of using the classic Euclidean distance, the implementation is adapted to utilize the Dynamic Time Warping (DTW) metric. DTW takes into consideration the fact that the two time series being compared may vary in length and speed. This approach, while simple and efficient in practice, is in fact quite elusive, something which is mainly attributed to the DTW. The most common beginner mistake is to perform hyperparameter tuning on the KNN and completely overlook the DTW part. The main disadvantage of DTW is time complexity: for large datasets with lengthy sequences, it may be impossible to train the model in reasonable time. Fortunately, by understanding the underlying notion of DTW, it is possible to perform the necessary tweaks in order to significantly speed up the algorithm. DTW: How it works Essentially, DTW is a dynamic programming algorithm. These algorithms break the problem recursively into subproblems (if applicable), store the results, and later use those results when needed, instead of recomputing them. A trick to help you remember the benefits of using dynamic programming is a quote by George Santayana (this is also what my professor said in the class during the respective course) : Those who forget the past are condemned to repeat it. To further delve into the world of dynamic programming and time warping, these resources [1], [2] are a good starting point. Since this article focuses on the data science part, we will use Python to quickly get a grasp of how the algorithm works. As a starter example, we will use the dtaidistance library and compute the distance between 2 phase-shifted sine waves: from dtaidistance import dtwfrom dtaidistance import dtw_visualisation as dtwvisimport randomimport numpy as npx = np.arange(0, 20, .5)s1 = np.sin(x)s2 = np.sin(x - 1)path = dtw.warping_path(s1, s2)dtwvis.plot_warping(s1, s2, path)distance = dtw.distance(s1, s2) Figure 1 shows the optimal distances between all points of the 2 sine waves. We can also plot the dynamic programming matrix (or accumulated cost matrix) which shows all the warping paths. This is shown in Figure 2: If this type of matrix is familiar, you are right! A similar matrix is constructed when implementing the Needleman–Wunsch algorithm (alignment of nucleotide sequences) and Levenshtein distance, both of which belong to the family of dynamic programming algorithms. Each cell in Figure 2 is actually a number, representing the distance between the 2 respective data points being compared, one for each sequence. The darker the color, the lower the distance. After constructing the matrix, the optimal warping path is extracted (red line). On the other hand, the time complexity is O(M,N) where M,N are the lengths of the respective sequences -a quadratic cost! Considering that the sequences may be large (not uncommon in real-world examples) as well as the fact that KNN would still have to run afterwards, it is very likely that the model may take too long to get trained. Fortunately, now that we know how DTW works as well as the context of the problem, it is possible to optimize the total execution. One key observation in Figure 2, is that the optimal warping path mostly follows the main diagonal. This happens in most cases. For a cell in row i, as the index moves through columns j further from the diagonal, the cost starts to rack up. Intuitively, it is highly unlikely that a massive phase-shift exists in a real world dataset. As part of dataset exploration, one could also extract important frequencies with Fourier Transform and make sure there is not any problem. The aforementioned library via the window argument gives us this capability. We also add use_pruning=True : d, paths = dtw.warping_paths(s1, s2, window=20, use_pruning=True )best_path = dtw.best_path(paths)dtwvis.plot_warpingpaths(s1, s2, paths, best_path) The blank cells in Figure 3 are skipped by the algorithm because the maximum shift is 20. To better demonstrate this optimisation though, we will use a real dataset. Real case scenario We will use the popular HAR (Human activity recognition) dataset from UCI, which contains labeled time series. Specifically, an instance of this dataset is a person wearing a smartphone which captures the linear acceleration and angle velocity while performing one of the following activities (WALKING, WALKING_UPSTAIRS, WALKING_DOWNSTAIRS, SITTING, STANDING, LAYING). Therefore, each observation is a 561-feature vector with time/frequency domain variables and a label describing the person’s activity, and the goal is to build a model that accurately predicts the activity using the transformed feed from the smartphone. x_train_file = open(r'UCI HAR Dataset/train/X_train.txt', 'r')y_train_file = open(r'UCI HAR Dataset/train/y_train.txt', 'r')x_test_file = open(r'UCI HAR Dataset/test/X_test.txt', 'r')y_test_file = open(r'UCI HAR Dataset/test/y_test.txt', 'r')# Create empty listsx_train = []y_train = []x_test = []y_test = []# Mapping table for classeslabels = {1:'WALKING', 2:'WALKING UPSTAIRS', 3:'WALKING DOWNSTAIRS', 4:'SITTING', 5:'STANDING', 6:'LAYING'}# Loop through datasetsfor x in x_train_file: x_train.append([float(ts) for ts in x.split()]) for y in y_train_file: y_train.append(int(y.rstrip('\n'))) for x in x_test_file: x_test.append([float(ts) for ts in x.split()]) for y in y_test_file: y_test.append(int(y.rstrip('\n'))) # Convert to numpy for efficiencyx_train = np.array(x_train)y_train = np.array(y_train)x_test = np.array(x_test)y_test = np.array(y_test)colors = ['#D62728','#2C9F2C','#FD7F23','#1F77B4','#9467BD', '#8C564A','#7F7F7F','#1FBECF','#E377C2','#BCBD27'] Let’s calculate the time it takes to compute the distance between the first time series of the train set and all of the series in the test set: %%timeidx=0for r in range(len(x_test)): distance = dtw.distance(x_train[idx], x_test[r], window=20, use_pruning='True')#OutputWall time: 1min 42sfor r in range(len(x_test)): distance = dtw.distance(x_train[idx], x_test[r])#OutputWall time: 25min 16s Obviously, the speedup is significant! Finally, we conclude the example by applying the KNN algorithm. All of the above examples use k=20 for the KNN and window size=20 for the DTW function. The idx variable is simply the index of the time series in the test set: # function that takes as input the number of neigbors of KNN and the # index of the time series in the test set, and returns one of the # labels: WALKING, WALKING_UPSTAIRS, WALKING_DOWNSTAIRS, SITTING, # STANDING, LAYINGdef classifyNN(k:int, idx:int) -> str: idxs=range(0,x_train.shape[0]) n=x_train.shape[0] distances=[] counters={} c=1; max_value=0for r in range(n): distances.append(dtw.distance(x_test[idx], x_train[idxs[r]],window=10,use_pruning=True))NN=sorted(range(len(distances)), key=lambda i: distances[i], reverse=False)[:k] for l in labels.values(): counters[l]=0for r in NN: l=labels[y_train[r]] counters[l]+=1 if (counters[l])>max_value: max_value=counters[l] #print('NN(%d) has label %s' % (c,l)) c+=1 # find the label(s) with the highest frequency keys = [k for k in counters if counters[k] == max_value] # in case of a tie, return one at random return (sample(keys,1)[0]) Then, we test a few cases: Example 1: Class ‘Standing’ k=20idx=3plt.plot(x_test[idx], label=labels[y_test[idx]], color=colors[y_test[idx]-1], linewidth=2)plt.xlabel('Samples @50Hz')plt.legend(loc='upper left')plt.tight_layout() Example 2: Class ‘Sitting’ k=20idx=200plt.plot(x_test[idx], label=labels[y_test[idx]], color=colors[y_test[idx]-1], linewidth=2)plt.xlabel('Samples @50Hz')plt.legend(loc='upper left')plt.tight_layout() Example 3: Class ‘Walking’ k=20idx=401plt.plot(x_test[idx], label=labels[y_test[idx]], color=colors[y_test[idx]-1], linewidth=2)plt.xlabel('Samples @50Hz')plt.legend(loc='upper left')plt.tight_layout() Evidently, all examples were correctly classified. In general, the algorithm performs very well. It is worth mentioning that if we hadn’t add the window argument which enables pruning, the model would take days to train! (Change the window argument inside the classifyNN() function and see for yourself) What about parallelisation? The next thing that comes to mind is if it’s possible to further speed up the execution of DTW by applying parallelisation. Unfortunately, with the current form of DTW it is quite tricky, however there are a few other implementations where by applying some modifications to the algorithm, the time complexity come even become linear. These implementations do not always provide the optimal solution though. On the other hand, it is possible to speed up the execution as a whole by calculating the DTW pairwise distances of all time-series in a dataset in parallel. This would be also extremely helpful when we want to construct a distance matrix fast. As you might have guessed by now, this technique finds application in time-series clustering by employing hierarchical clustering.The dtaidistance library contains the function distance_matrix_fast( list of sequences) which returns a distance matrix and runs in parallel. Closing remarks The combination of DTW with KNN is pretty effective for time series classification. There is a caveat though regarding time complexity, but we have shown how to optimize the search space and speed up the execution. Apart from classification, DTW is also used as a distance metric when applying clustering in time series, so it is imperative to know how this technique works. Finally, regarding classification, there are other algorithms in this domain, like Time Series Forest Classifier which are mostly used when explainability is required (feature importances extraction, like Random Forest).
[ { "code": null, "e": 480, "s": 172, "text": "Time series classification is a common task, having many applications in numerous domains like IOT (Internet of things), signal processing, human activity recognition and so on. The goal is to train a model that can accurately predict the class of a time series, given a dataset with labeled time sequences." }, { "code": null, "e": 808, "s": 480, "text": "A popular approach to tackle this problem is to use the K-Nearest Neighbors algorithm, but instead of using the classic Euclidean distance, the implementation is adapted to utilize the Dynamic Time Warping (DTW) metric. DTW takes into consideration the fact that the two time series being compared may vary in length and speed." }, { "code": null, "e": 1365, "s": 808, "text": "This approach, while simple and efficient in practice, is in fact quite elusive, something which is mainly attributed to the DTW. The most common beginner mistake is to perform hyperparameter tuning on the KNN and completely overlook the DTW part. The main disadvantage of DTW is time complexity: for large datasets with lengthy sequences, it may be impossible to train the model in reasonable time. Fortunately, by understanding the underlying notion of DTW, it is possible to perform the necessary tweaks in order to significantly speed up the algorithm." }, { "code": null, "e": 1383, "s": 1365, "text": "DTW: How it works" }, { "code": null, "e": 1790, "s": 1383, "text": "Essentially, DTW is a dynamic programming algorithm. These algorithms break the problem recursively into subproblems (if applicable), store the results, and later use those results when needed, instead of recomputing them. A trick to help you remember the benefits of using dynamic programming is a quote by George Santayana (this is also what my professor said in the class during the respective course) :" }, { "code": null, "e": 1844, "s": 1790, "text": "Those who forget the past are condemned to repeat it." }, { "code": null, "e": 2212, "s": 1844, "text": "To further delve into the world of dynamic programming and time warping, these resources [1], [2] are a good starting point. Since this article focuses on the data science part, we will use Python to quickly get a grasp of how the algorithm works. As a starter example, we will use the dtaidistance library and compute the distance between 2 phase-shifted sine waves:" }, { "code": null, "e": 2475, "s": 2212, "text": "from dtaidistance import dtwfrom dtaidistance import dtw_visualisation as dtwvisimport randomimport numpy as npx = np.arange(0, 20, .5)s1 = np.sin(x)s2 = np.sin(x - 1)path = dtw.warping_path(s1, s2)dtwvis.plot_warping(s1, s2, path)distance = dtw.distance(s1, s2)" }, { "code": null, "e": 2691, "s": 2475, "text": "Figure 1 shows the optimal distances between all points of the 2 sine waves. We can also plot the dynamic programming matrix (or accumulated cost matrix) which shows all the warping paths. This is shown in Figure 2:" }, { "code": null, "e": 2955, "s": 2691, "text": "If this type of matrix is familiar, you are right! A similar matrix is constructed when implementing the Needleman–Wunsch algorithm (alignment of nucleotide sequences) and Levenshtein distance, both of which belong to the family of dynamic programming algorithms." }, { "code": null, "e": 3228, "s": 2955, "text": "Each cell in Figure 2 is actually a number, representing the distance between the 2 respective data points being compared, one for each sequence. The darker the color, the lower the distance. After constructing the matrix, the optimal warping path is extracted (red line)." }, { "code": null, "e": 3564, "s": 3228, "text": "On the other hand, the time complexity is O(M,N) where M,N are the lengths of the respective sequences -a quadratic cost! Considering that the sequences may be large (not uncommon in real-world examples) as well as the fact that KNN would still have to run afterwards, it is very likely that the model may take too long to get trained." }, { "code": null, "e": 4170, "s": 3564, "text": "Fortunately, now that we know how DTW works as well as the context of the problem, it is possible to optimize the total execution. One key observation in Figure 2, is that the optimal warping path mostly follows the main diagonal. This happens in most cases. For a cell in row i, as the index moves through columns j further from the diagonal, the cost starts to rack up. Intuitively, it is highly unlikely that a massive phase-shift exists in a real world dataset. As part of dataset exploration, one could also extract important frequencies with Fourier Transform and make sure there is not any problem." }, { "code": null, "e": 4278, "s": 4170, "text": "The aforementioned library via the window argument gives us this capability. We also add use_pruning=True :" }, { "code": null, "e": 4427, "s": 4278, "text": "d, paths = dtw.warping_paths(s1, s2, window=20, use_pruning=True )best_path = dtw.best_path(paths)dtwvis.plot_warpingpaths(s1, s2, paths, best_path)" }, { "code": null, "e": 4593, "s": 4427, "text": "The blank cells in Figure 3 are skipped by the algorithm because the maximum shift is 20. To better demonstrate this optimisation though, we will use a real dataset." }, { "code": null, "e": 4612, "s": 4593, "text": "Real case scenario" }, { "code": null, "e": 5235, "s": 4612, "text": "We will use the popular HAR (Human activity recognition) dataset from UCI, which contains labeled time series. Specifically, an instance of this dataset is a person wearing a smartphone which captures the linear acceleration and angle velocity while performing one of the following activities (WALKING, WALKING_UPSTAIRS, WALKING_DOWNSTAIRS, SITTING, STANDING, LAYING). Therefore, each observation is a 561-feature vector with time/frequency domain variables and a label describing the person’s activity, and the goal is to build a model that accurately predicts the activity using the transformed feed from the smartphone." }, { "code": null, "e": 6247, "s": 5235, "text": "x_train_file = open(r'UCI HAR Dataset/train/X_train.txt', 'r')y_train_file = open(r'UCI HAR Dataset/train/y_train.txt', 'r')x_test_file = open(r'UCI HAR Dataset/test/X_test.txt', 'r')y_test_file = open(r'UCI HAR Dataset/test/y_test.txt', 'r')# Create empty listsx_train = []y_train = []x_test = []y_test = []# Mapping table for classeslabels = {1:'WALKING', 2:'WALKING UPSTAIRS', 3:'WALKING DOWNSTAIRS', 4:'SITTING', 5:'STANDING', 6:'LAYING'}# Loop through datasetsfor x in x_train_file: x_train.append([float(ts) for ts in x.split()]) for y in y_train_file: y_train.append(int(y.rstrip('\\n'))) for x in x_test_file: x_test.append([float(ts) for ts in x.split()]) for y in y_test_file: y_test.append(int(y.rstrip('\\n'))) # Convert to numpy for efficiencyx_train = np.array(x_train)y_train = np.array(y_train)x_test = np.array(x_test)y_test = np.array(y_test)colors = ['#D62728','#2C9F2C','#FD7F23','#1F77B4','#9467BD', '#8C564A','#7F7F7F','#1FBECF','#E377C2','#BCBD27']" }, { "code": null, "e": 6391, "s": 6247, "text": "Let’s calculate the time it takes to compute the distance between the first time series of the train set and all of the series in the test set:" }, { "code": null, "e": 6647, "s": 6391, "text": "%%timeidx=0for r in range(len(x_test)): distance = dtw.distance(x_train[idx], x_test[r], window=20, use_pruning='True')#OutputWall time: 1min 42sfor r in range(len(x_test)): distance = dtw.distance(x_train[idx], x_test[r])#OutputWall time: 25min 16s" }, { "code": null, "e": 6911, "s": 6647, "text": "Obviously, the speedup is significant! Finally, we conclude the example by applying the KNN algorithm. All of the above examples use k=20 for the KNN and window size=20 for the DTW function. The idx variable is simply the index of the time series in the test set:" }, { "code": null, "e": 7910, "s": 6911, "text": "# function that takes as input the number of neigbors of KNN and the # index of the time series in the test set, and returns one of the # labels: WALKING, WALKING_UPSTAIRS, WALKING_DOWNSTAIRS, SITTING, # STANDING, LAYINGdef classifyNN(k:int, idx:int) -> str: idxs=range(0,x_train.shape[0]) n=x_train.shape[0] distances=[] counters={} c=1; max_value=0for r in range(n): distances.append(dtw.distance(x_test[idx], x_train[idxs[r]],window=10,use_pruning=True))NN=sorted(range(len(distances)), key=lambda i: distances[i], reverse=False)[:k] for l in labels.values(): counters[l]=0for r in NN: l=labels[y_train[r]] counters[l]+=1 if (counters[l])>max_value: max_value=counters[l] #print('NN(%d) has label %s' % (c,l)) c+=1 # find the label(s) with the highest frequency keys = [k for k in counters if counters[k] == max_value] # in case of a tie, return one at random return (sample(keys,1)[0])" }, { "code": null, "e": 7937, "s": 7910, "text": "Then, we test a few cases:" }, { "code": null, "e": 7965, "s": 7937, "text": "Example 1: Class ‘Standing’" }, { "code": null, "e": 8138, "s": 7965, "text": "k=20idx=3plt.plot(x_test[idx], label=labels[y_test[idx]], color=colors[y_test[idx]-1], linewidth=2)plt.xlabel('Samples @50Hz')plt.legend(loc='upper left')plt.tight_layout()" }, { "code": null, "e": 8165, "s": 8138, "text": "Example 2: Class ‘Sitting’" }, { "code": null, "e": 8340, "s": 8165, "text": "k=20idx=200plt.plot(x_test[idx], label=labels[y_test[idx]], color=colors[y_test[idx]-1], linewidth=2)plt.xlabel('Samples @50Hz')plt.legend(loc='upper left')plt.tight_layout()" }, { "code": null, "e": 8367, "s": 8340, "text": "Example 3: Class ‘Walking’" }, { "code": null, "e": 8542, "s": 8367, "text": "k=20idx=401plt.plot(x_test[idx], label=labels[y_test[idx]], color=colors[y_test[idx]-1], linewidth=2)plt.xlabel('Samples @50Hz')plt.legend(loc='upper left')plt.tight_layout()" }, { "code": null, "e": 8846, "s": 8542, "text": "Evidently, all examples were correctly classified. In general, the algorithm performs very well. It is worth mentioning that if we hadn’t add the window argument which enables pruning, the model would take days to train! (Change the window argument inside the classifyNN() function and see for yourself)" }, { "code": null, "e": 8874, "s": 8846, "text": "What about parallelisation?" }, { "code": null, "e": 9798, "s": 8874, "text": "The next thing that comes to mind is if it’s possible to further speed up the execution of DTW by applying parallelisation. Unfortunately, with the current form of DTW it is quite tricky, however there are a few other implementations where by applying some modifications to the algorithm, the time complexity come even become linear. These implementations do not always provide the optimal solution though. On the other hand, it is possible to speed up the execution as a whole by calculating the DTW pairwise distances of all time-series in a dataset in parallel. This would be also extremely helpful when we want to construct a distance matrix fast. As you might have guessed by now, this technique finds application in time-series clustering by employing hierarchical clustering.The dtaidistance library contains the function distance_matrix_fast( list of sequences) which returns a distance matrix and runs in parallel." }, { "code": null, "e": 9814, "s": 9798, "text": "Closing remarks" } ]
Machine learning and recommender systems using your own Spotify data | by Anthony Li | Towards Data Science
As someone who uses Spotify on the daily I was interested in what analysis I could do with my own music data. Spotify does a great job of recommending tracks via both daily mixes and track radios, but how do we build something like this ourselves? The aim here was to use machine learning and recommender system techniques to recommend new tracks based on tracks in my favourite playlists. This article gives a higher level overview of this project. The code and results can be found on GitHub here. Any good data science project first needs data, and lots of it. In order to get started with our music data we first need to access the Spotify API: Create a Spotify for Developers accountFrom the dashboard setup a project (needed for API access)Retrieve the client ID, client secret, and setup the redirect URI (as a local projects I set this to http://localhost:9001/callback)Review the API documentation Create a Spotify for Developers account From the dashboard setup a project (needed for API access) Retrieve the client ID, client secret, and setup the redirect URI (as a local projects I set this to http://localhost:9001/callback) Review the API documentation Once the developer account is setup, we can access the API to pull music data. We can use the spotipy Python package for this, which needs the developer details which we setup earlier to grant permissions via OAuth. with open("spotify/spotify_details.yml", 'r') as stream: spotify_details = yaml.safe_load(stream)# https://developer.spotify.com/web-api/using-scopes/scope = "user-library-read user-follow-read user-top-read playlist-read-private" sp = spotipy.Spotify(auth_manager=SpotifyOAuth( client_id=spotify_details['client_id'], client_secret=spotify_details['client_secret'], redirect_uri=spotify_details['redirect_uri'], scope=scope,)) We can now pull data from a variety of sources in our Spotify library. The sp class has the functions to cover this such as sp.current_user_playlists() and sp.current_user_top_tracks() . From these API calls we need to pull the track details such as unique id, name, duration and genres, as well as associated artist, album, and playlist properties. I saved these as pandas dataframes for ease of analysis. Spotify can also provide the audio features for a track. These are numerical values (mostly normalised between 0 and 1) which are useful for analysis but especially as features for traditional machine learning methods. With the above tabular data set it’s fairly straightforwards to formulate this as a classic regression problem by rating songs in the training set from 1–10, or as a classification problem by trying to recommend tracks similar to our favourite songs (a fairly simple approach if you have a playlist of favourite songs). Remember to remove duplicate track ids from the train and test datasets to avoid data leakage! The XGBoost and RandomForest classifiers performed well for me here. However, the above approach is heavily reliant on both feature engineering and on users to provide the labelling. It suffers from both mislabelling inaccuracies and the cold-start problem when a user has a fresh account or doesn’t provide any ratings, and recommender system approaches are therefore often used instead. A popularity recommender recommends songs ranked by their popularity regardless of user’s preferences. This is of course dependent upon the methodology used to determine the popularity metric (usually some function of time, user interactions, and user ratings). As it doesn’t take user activity into account, solely recommending by popularity is a poor way to recommend tracks. However, as we will see later it is a good method to mix in for variety and to avoid the cold-start problem. A content-based recommender leverages attributes from items the user has interacted with to recommend similar items. Here the popular TF-IDF method is used to convert unstructured text (unigrams and bigrams of genres and song/artist/album/playlist name) into a sparse matrix. The cosine similarity between the user vector and the initial matrix (all users) then gives a metric to recommend new tracks. Looks like genre tends to be the strongest form of content to base track recommendations on. A collaborative recommender can be either memory-based (based on past user interactions) or model-based (e.g. clustering). Here an items×users matrix is then used to recommend items to users based on the interactions of similar users. The collaborative approach can suffer from the sparsity problem if the user set is too small or the number of interactions is too low. A hybrid recommender combines the content-based and collaborative approaches and has been shown to perform better in many studies. It avoids high variance and enables variety and weighting (e.g. genre weighting). We can also incorporate the popularity approach to give a hybrid + popularity recommender. Subjectively this recommender appears to give the best recommendations in practice! We can now add our tracks to a Spotify playlist to listen to! Create the tracks_to_add array of track ids where the recommendation strength is above a certain value. # Create a new playlist for tracks to addnew_playlist = sp.user_playlist_create( user=spotify_details['user'], name="spotify-recommender-playlists", public=False, collaborative=False, description="Created by https://github.com/anthonyli358/spotify- recommender-systems",)# Add tracks to the new playlistfor id in tracks_to_add: sp.user_playlist_add_tracks(user=spotify_details['user'], playlist_id=new_playlist['id'], tracks=[id], ) Hopefully the playlist is 🔥. To improve the recommendations even more we could: Expand the dataset to include other users Develop other evaluation metrics (here the Top-N accuracy metric was used)
[ { "code": null, "e": 562, "s": 172, "text": "As someone who uses Spotify on the daily I was interested in what analysis I could do with my own music data. Spotify does a great job of recommending tracks via both daily mixes and track radios, but how do we build something like this ourselves? The aim here was to use machine learning and recommender system techniques to recommend new tracks based on tracks in my favourite playlists." }, { "code": null, "e": 672, "s": 562, "text": "This article gives a higher level overview of this project. The code and results can be found on GitHub here." }, { "code": null, "e": 736, "s": 672, "text": "Any good data science project first needs data, and lots of it." }, { "code": null, "e": 821, "s": 736, "text": "In order to get started with our music data we first need to access the Spotify API:" }, { "code": null, "e": 1079, "s": 821, "text": "Create a Spotify for Developers accountFrom the dashboard setup a project (needed for API access)Retrieve the client ID, client secret, and setup the redirect URI (as a local projects I set this to http://localhost:9001/callback)Review the API documentation" }, { "code": null, "e": 1119, "s": 1079, "text": "Create a Spotify for Developers account" }, { "code": null, "e": 1178, "s": 1119, "text": "From the dashboard setup a project (needed for API access)" }, { "code": null, "e": 1311, "s": 1178, "text": "Retrieve the client ID, client secret, and setup the redirect URI (as a local projects I set this to http://localhost:9001/callback)" }, { "code": null, "e": 1340, "s": 1311, "text": "Review the API documentation" }, { "code": null, "e": 1556, "s": 1340, "text": "Once the developer account is setup, we can access the API to pull music data. We can use the spotipy Python package for this, which needs the developer details which we setup earlier to grant permissions via OAuth." }, { "code": null, "e": 2005, "s": 1556, "text": "with open(\"spotify/spotify_details.yml\", 'r') as stream: spotify_details = yaml.safe_load(stream)# https://developer.spotify.com/web-api/using-scopes/scope = \"user-library-read user-follow-read user-top-read playlist-read-private\" sp = spotipy.Spotify(auth_manager=SpotifyOAuth( client_id=spotify_details['client_id'], client_secret=spotify_details['client_secret'], redirect_uri=spotify_details['redirect_uri'], scope=scope,))" }, { "code": null, "e": 2412, "s": 2005, "text": "We can now pull data from a variety of sources in our Spotify library. The sp class has the functions to cover this such as sp.current_user_playlists() and sp.current_user_top_tracks() . From these API calls we need to pull the track details such as unique id, name, duration and genres, as well as associated artist, album, and playlist properties. I saved these as pandas dataframes for ease of analysis." }, { "code": null, "e": 2631, "s": 2412, "text": "Spotify can also provide the audio features for a track. These are numerical values (mostly normalised between 0 and 1) which are useful for analysis but especially as features for traditional machine learning methods." }, { "code": null, "e": 3046, "s": 2631, "text": "With the above tabular data set it’s fairly straightforwards to formulate this as a classic regression problem by rating songs in the training set from 1–10, or as a classification problem by trying to recommend tracks similar to our favourite songs (a fairly simple approach if you have a playlist of favourite songs). Remember to remove duplicate track ids from the train and test datasets to avoid data leakage!" }, { "code": null, "e": 3115, "s": 3046, "text": "The XGBoost and RandomForest classifiers performed well for me here." }, { "code": null, "e": 3435, "s": 3115, "text": "However, the above approach is heavily reliant on both feature engineering and on users to provide the labelling. It suffers from both mislabelling inaccuracies and the cold-start problem when a user has a fresh account or doesn’t provide any ratings, and recommender system approaches are therefore often used instead." }, { "code": null, "e": 3697, "s": 3435, "text": "A popularity recommender recommends songs ranked by their popularity regardless of user’s preferences. This is of course dependent upon the methodology used to determine the popularity metric (usually some function of time, user interactions, and user ratings)." }, { "code": null, "e": 3922, "s": 3697, "text": "As it doesn’t take user activity into account, solely recommending by popularity is a poor way to recommend tracks. However, as we will see later it is a good method to mix in for variety and to avoid the cold-start problem." }, { "code": null, "e": 4324, "s": 3922, "text": "A content-based recommender leverages attributes from items the user has interacted with to recommend similar items. Here the popular TF-IDF method is used to convert unstructured text (unigrams and bigrams of genres and song/artist/album/playlist name) into a sparse matrix. The cosine similarity between the user vector and the initial matrix (all users) then gives a metric to recommend new tracks." }, { "code": null, "e": 4417, "s": 4324, "text": "Looks like genre tends to be the strongest form of content to base track recommendations on." }, { "code": null, "e": 4652, "s": 4417, "text": "A collaborative recommender can be either memory-based (based on past user interactions) or model-based (e.g. clustering). Here an items×users matrix is then used to recommend items to users based on the interactions of similar users." }, { "code": null, "e": 4787, "s": 4652, "text": "The collaborative approach can suffer from the sparsity problem if the user set is too small or the number of interactions is too low." }, { "code": null, "e": 5091, "s": 4787, "text": "A hybrid recommender combines the content-based and collaborative approaches and has been shown to perform better in many studies. It avoids high variance and enables variety and weighting (e.g. genre weighting). We can also incorporate the popularity approach to give a hybrid + popularity recommender." }, { "code": null, "e": 5175, "s": 5091, "text": "Subjectively this recommender appears to give the best recommendations in practice!" }, { "code": null, "e": 5341, "s": 5175, "text": "We can now add our tracks to a Spotify playlist to listen to! Create the tracks_to_add array of track ids where the recommendation strength is above a certain value." }, { "code": null, "e": 5889, "s": 5341, "text": "# Create a new playlist for tracks to addnew_playlist = sp.user_playlist_create( user=spotify_details['user'], name=\"spotify-recommender-playlists\", public=False, collaborative=False, description=\"Created by https://github.com/anthonyli358/spotify- recommender-systems\",)# Add tracks to the new playlistfor id in tracks_to_add: sp.user_playlist_add_tracks(user=spotify_details['user'], playlist_id=new_playlist['id'], tracks=[id], )" }, { "code": null, "e": 5969, "s": 5889, "text": "Hopefully the playlist is 🔥. To improve the recommendations even more we could:" }, { "code": null, "e": 6011, "s": 5969, "text": "Expand the dataset to include other users" } ]
Model-Based Recommendation System | Towards Data Science
This post is the last piece of my Python Surprise recommendation series in which I present the techniques I used in my boardgame recommendation engine project. (See my GitHub repo for the whole project.) Previous posts in the series: Part 1: How to Build a Memory-Based Recommendation System using Python Surprise: I recommend reading this post first if you are not familiar with the topic, especially the Data Import and Data Preparation steps since they are identical for the memory-based and model-based approach. Part 2: My Python Code for Flexible Recommendations: This post contains the additional code I wrote for the recommendation framework that enables one to create predictions without re-training the whole model. However, the approach only works for the KNN-style, simpler models. I also foolishly started an analogy on cupcakes, backed by the cover pictures. In the first post, we had many cupcakes, didn’t know how to choose, in the second, we had an odd newcomer cupcake to the party, struggled with integrating it, and now... well I guess now the cupcakes are in a row, representing matrix factorisation. That’s the best I can come up with. In this post, we are going to discuss how latent factor models work, how to train such a model in Surprise with hyperparameter tuning, and what other conclusions we can draw from the results. A quick recap on where we are. Within recommendation systems, there is a group of models called collaborative-filtering, which tries to find similarities between users or between items based on recorded user-item preferences or ratings. In my previous posts, we discussed a subgroup of collaborative systems called memory-based models. They are called memory-based because the algorithm is not complicated, but requires a lot of memory to keep track of the results. In this post, we are discussing another subgroup of collaborative-filtering models: model-based models (which is a rather silly name). As opposed to the memory-based approaches, this uses some sort of machine learning algorithm. There are many different variations within this group, what we are going to concentrate on is the singular value decomposition methods. In Surprise, there are three such models: SVD, SVDpp, and NMF, out of which I am only going to discuss SVD. NMF is a simplified version, ignoring user and item biases. SVDpp adds a very cool feature where you also separately keep track of whether the user rated the item or not, which should also be relevant information of course, but I found that it does not improve my efficiency while adding a lot of computation time. In the SVD model, an estimated rating of user u on item i is calculated as: where μ is the overall average rating, and every other parameter is calculated from the model with a gradient descent method. So the model will try to fit this estimated rating on all the known ratings, minimise the MSE, and return the closest fit. bu and bi are scalars, they represent the biases of the user u or item i. For example, user u tends to be bu off from from the grand average rating. These biases can be switched off when fitting the model, that is basically what the NMF model is. pu and qi are vectors, and their length is a hyperparameter of the model, n. They are the actual matrix-factorisation part of the model, that is where the magic happens. Each user and item will be represented by their vector, that tries to capture their essence in n numbers. And we get the rating by multiplying the item — user pairs (and adding averages and biases of course). It might be tempting to think of these n dimensions as something humanly comprehensible. For example, if we deal with boardgames, the first dimension could measure how complex the rulebook is. Now a user that places a high emphasis on complexity (which means they have a large number at qi [1]) will give a high rating to a game that has a high complexity (which means a high pu[1]). However, in my experience, this is rarely the case, it is quite difficult to match meaning with the individual coordinates that come out of the model. Assuming you already have the database imported and set up (once again, if you are not sure how to do that, please refer to my previous post), working with SVD is similar to how you work with other models in Surprise. First, you need to import the model: from surprise import SVD Then you can fit the model on the trainset and test the model performance using the RMSE score (which stands for Root Mean Squared Error, the lower the better): SVD_model = SVD()SVD_model.fit(trainset)predictions = SVD_model.test(testset)accuracy.rmse(predictions) Similar to the memory-based models, in order to predict a rating for a specific user, you can use the predict method, but the user needs to be in your database: SVD_model.predict(uid = 'TestUser1', iid = '161936') As you saw, fitting an SVD model is simple, but analysing the result is a bit more complicated. Using the pu, qi, bu and bi methods of an SVD object, you can get the corresponding values from the math formula. In my project, I found qi to be the most interesting: calling the qi method on the already fit SVD model will return a 2-dimensional array, where height is the number of items, width is the n_factor parameter of the model (we will discuss the parameters in the next section). Each row represents an item with n_factor number of factors, these are the so-called latent factors that the model found, and they represent the item in the rating calculations. As I mentioned before, it is tempting to try to find easily comprehensible meaning in these coordinates, but in my experience, it doesn’t really happen. However, I think one really interesting way to take this analysis one step further would be to use these latent factors as a basis for a cluster analysis, and see if anything interesting comes up from that. You can use the n_factor latent factors as features, and calculate the item’s distances based on them, like you would do in any regular cluster analysis. An important part of any machine learning process is tuning the hyperparameters. In this section, we are going to have a look at the SVD parameters in Surprise. Before we start, please note that the RMSE score with the default parameters was 1.332 for my project, and after my GCP Virtual Machine ran for hours, I managed to bring RMSE down to 1.3210. Which is not a lot of improvement... Might just be my database, might be because the default parameters in Surprise were set up efficiently. Regardless of that, I think it’s still important to consider the hyperparameters. There are four hyperparameters I tuned: n_factors: We have briefly touched upon this in the previous section, this parameter determines the size of your pu and qi vectors. This determines how many latent factors the model will try to find. The higher the number is, the more power the model has, but it also comes with a higher chance of overfitting. n_epochs: This factor determines how many times the gradient descent calculations are repeated. Increasing this number makes predictions more accurate, but requires longer to calculate. lr_all: Learning rate factor for all of the parameters. These are the step sizes the model will use to minimise the cost function, see more on this in the Surprise documentation. reg_all: Regularisation factor for all of the parameters. Surprise uses an L2 regularisation, which roughly means that it will try to minimise the differences between the squared value of the parameters. (The parameters being all the bu, bi, pu and qi.) There are numerous other parameters you can play with, most of them are different setups of learning rate or and regularisation parameters. You can technically set a different learning rate or regularisation for each four types of the model parameters, and the ..._all parameters cover them all. I did not find it necessary to go into such details. We are going to use GridSearchCV to tune the hyperparameters in Surprise. It works mostly like its counterpart in scikit-learn, as the name suggests, it will search all the possible combinations on the hyperparameter grid, using Cross-Validation. First, we need a dictionary in which the keys are hyperparameter names, and the values are lists of different items you want to check: param_grid = { 'n_factors':[5, 10,20], 'n_epochs': [5, 10, 20], 'lr_all': [0.002, 0.005], 'reg_all': [0.4, 0.6]} You have to be careful about how you set up these parameters, as each of the possible combinations will be checked. In our cases, that is 3 * 3 * 2 * 2 = 36 different combinations, and for every one of these, the model will run multiple times, depending on the Cross-Validation you choose. I left the cv parameter at 5-fold, which means 36 * 5 = 180 model runs in total. That can take a long time, and this might be the time to start thinking about using cloud computing. I wrote a post recently about how to quickly set up a free Virtual Machine on the Google Cloud Platform. Once you have your parameter grid, you can set up the GridSearchCV object like so: gs_model = GridSearchCV( algo_class = SVD, param_grid = param_grid, n_jobs = -1, joblib_verbose = 5) The first parameter, algo_class, is the type of model you want to use. n_jobs = -1 simply tells the model that it can use all available processors, which is highly desirable when you have a parallelisable operation. One other parameter that you might want to change is cv, I just left it at the default, which does a 5-Fold Cross-Validation. Then you can simply fit on the data: gs_model.fit(data) Please note that once again, surprise handles databases a bit differently, you can only fit your GridSearchCV on the whole dataset, can’t split it into train and test. Finally, you can get a list of the parameters from the parameter grid that resulted in the best RMSE score: gs_model.best_params My process when working with GridSearchCV was the following: Fit a GridSearchCV model on the whole data, with a parameter grid that covered a wide range Calculated the Cross-Validated RMSE score Repeated the process for a different parameter grid that either drilled down to a lower level if the optimal parameter seemed to be in the middle, or explored higher / lower parameters if the optimal parameter seemed to be at a boundary of the previous parameter grid Once the decrease in RMSE score was minimal, saved the best hyperparameters and used them in the SVD models in the next steps Because I wanted to compare the results with my KNN-type models from earlier, I ran the SVD model on the trainset, and calculated the test RMSE score on the testset An alternative approach would have been to simply rely on the GSCV scores, and fit the final model only once on the full trainset. This concludes my series on recommendation system project. It was interesting to work with all these different approaches, especially how close their performance turned out to be. I spent a lot of time identifying the best model, but the truth is, even the simplest KNN models performed relatively well. I think that is partly because my data was not nearly as sparse as it usually is with recommendation systems. 10% of the possible user - item ratings were populated, which is considered to be an extremely high ratio. Imagine if people on average bought 10% of all the products on Amazon! The high ratio is because I limited my focus on the top 100 boardgames of all time, which are naturally popular titles. As an additional bonus, average ratings were pretty close and high, since these are all universally considered to be good games. Surprise documentation: surprise.readthedocs.io My previous posts in the series:
[ { "code": null, "e": 376, "s": 172, "text": "This post is the last piece of my Python Surprise recommendation series in which I present the techniques I used in my boardgame recommendation engine project. (See my GitHub repo for the whole project.)" }, { "code": null, "e": 406, "s": 376, "text": "Previous posts in the series:" }, { "code": null, "e": 689, "s": 406, "text": "Part 1: How to Build a Memory-Based Recommendation System using Python Surprise: I recommend reading this post first if you are not familiar with the topic, especially the Data Import and Data Preparation steps since they are identical for the memory-based and model-based approach." }, { "code": null, "e": 966, "s": 689, "text": "Part 2: My Python Code for Flexible Recommendations: This post contains the additional code I wrote for the recommendation framework that enables one to create predictions without re-training the whole model. However, the approach only works for the KNN-style, simpler models." }, { "code": null, "e": 1330, "s": 966, "text": "I also foolishly started an analogy on cupcakes, backed by the cover pictures. In the first post, we had many cupcakes, didn’t know how to choose, in the second, we had an odd newcomer cupcake to the party, struggled with integrating it, and now... well I guess now the cupcakes are in a row, representing matrix factorisation. That’s the best I can come up with." }, { "code": null, "e": 1522, "s": 1330, "text": "In this post, we are going to discuss how latent factor models work, how to train such a model in Surprise with hyperparameter tuning, and what other conclusions we can draw from the results." }, { "code": null, "e": 1988, "s": 1522, "text": "A quick recap on where we are. Within recommendation systems, there is a group of models called collaborative-filtering, which tries to find similarities between users or between items based on recorded user-item preferences or ratings. In my previous posts, we discussed a subgroup of collaborative systems called memory-based models. They are called memory-based because the algorithm is not complicated, but requires a lot of memory to keep track of the results." }, { "code": null, "e": 2353, "s": 1988, "text": "In this post, we are discussing another subgroup of collaborative-filtering models: model-based models (which is a rather silly name). As opposed to the memory-based approaches, this uses some sort of machine learning algorithm. There are many different variations within this group, what we are going to concentrate on is the singular value decomposition methods." }, { "code": null, "e": 2776, "s": 2353, "text": "In Surprise, there are three such models: SVD, SVDpp, and NMF, out of which I am only going to discuss SVD. NMF is a simplified version, ignoring user and item biases. SVDpp adds a very cool feature where you also separately keep track of whether the user rated the item or not, which should also be relevant information of course, but I found that it does not improve my efficiency while adding a lot of computation time." }, { "code": null, "e": 2852, "s": 2776, "text": "In the SVD model, an estimated rating of user u on item i is calculated as:" }, { "code": null, "e": 3101, "s": 2852, "text": "where μ is the overall average rating, and every other parameter is calculated from the model with a gradient descent method. So the model will try to fit this estimated rating on all the known ratings, minimise the MSE, and return the closest fit." }, { "code": null, "e": 3348, "s": 3101, "text": "bu and bi are scalars, they represent the biases of the user u or item i. For example, user u tends to be bu off from from the grand average rating. These biases can be switched off when fitting the model, that is basically what the NMF model is." }, { "code": null, "e": 3727, "s": 3348, "text": "pu and qi are vectors, and their length is a hyperparameter of the model, n. They are the actual matrix-factorisation part of the model, that is where the magic happens. Each user and item will be represented by their vector, that tries to capture their essence in n numbers. And we get the rating by multiplying the item — user pairs (and adding averages and biases of course)." }, { "code": null, "e": 4262, "s": 3727, "text": "It might be tempting to think of these n dimensions as something humanly comprehensible. For example, if we deal with boardgames, the first dimension could measure how complex the rulebook is. Now a user that places a high emphasis on complexity (which means they have a large number at qi [1]) will give a high rating to a game that has a high complexity (which means a high pu[1]). However, in my experience, this is rarely the case, it is quite difficult to match meaning with the individual coordinates that come out of the model." }, { "code": null, "e": 4517, "s": 4262, "text": "Assuming you already have the database imported and set up (once again, if you are not sure how to do that, please refer to my previous post), working with SVD is similar to how you work with other models in Surprise. First, you need to import the model:" }, { "code": null, "e": 4542, "s": 4517, "text": "from surprise import SVD" }, { "code": null, "e": 4703, "s": 4542, "text": "Then you can fit the model on the trainset and test the model performance using the RMSE score (which stands for Root Mean Squared Error, the lower the better):" }, { "code": null, "e": 4807, "s": 4703, "text": "SVD_model = SVD()SVD_model.fit(trainset)predictions = SVD_model.test(testset)accuracy.rmse(predictions)" }, { "code": null, "e": 4968, "s": 4807, "text": "Similar to the memory-based models, in order to predict a rating for a specific user, you can use the predict method, but the user needs to be in your database:" }, { "code": null, "e": 5021, "s": 4968, "text": "SVD_model.predict(uid = 'TestUser1', iid = '161936')" }, { "code": null, "e": 5117, "s": 5021, "text": "As you saw, fitting an SVD model is simple, but analysing the result is a bit more complicated." }, { "code": null, "e": 5685, "s": 5117, "text": "Using the pu, qi, bu and bi methods of an SVD object, you can get the corresponding values from the math formula. In my project, I found qi to be the most interesting: calling the qi method on the already fit SVD model will return a 2-dimensional array, where height is the number of items, width is the n_factor parameter of the model (we will discuss the parameters in the next section). Each row represents an item with n_factor number of factors, these are the so-called latent factors that the model found, and they represent the item in the rating calculations." }, { "code": null, "e": 6199, "s": 5685, "text": "As I mentioned before, it is tempting to try to find easily comprehensible meaning in these coordinates, but in my experience, it doesn’t really happen. However, I think one really interesting way to take this analysis one step further would be to use these latent factors as a basis for a cluster analysis, and see if anything interesting comes up from that. You can use the n_factor latent factors as features, and calculate the item’s distances based on them, like you would do in any regular cluster analysis." }, { "code": null, "e": 6360, "s": 6199, "text": "An important part of any machine learning process is tuning the hyperparameters. In this section, we are going to have a look at the SVD parameters in Surprise." }, { "code": null, "e": 6774, "s": 6360, "text": "Before we start, please note that the RMSE score with the default parameters was 1.332 for my project, and after my GCP Virtual Machine ran for hours, I managed to bring RMSE down to 1.3210. Which is not a lot of improvement... Might just be my database, might be because the default parameters in Surprise were set up efficiently. Regardless of that, I think it’s still important to consider the hyperparameters." }, { "code": null, "e": 6814, "s": 6774, "text": "There are four hyperparameters I tuned:" }, { "code": null, "e": 7125, "s": 6814, "text": "n_factors: We have briefly touched upon this in the previous section, this parameter determines the size of your pu and qi vectors. This determines how many latent factors the model will try to find. The higher the number is, the more power the model has, but it also comes with a higher chance of overfitting." }, { "code": null, "e": 7311, "s": 7125, "text": "n_epochs: This factor determines how many times the gradient descent calculations are repeated. Increasing this number makes predictions more accurate, but requires longer to calculate." }, { "code": null, "e": 7490, "s": 7311, "text": "lr_all: Learning rate factor for all of the parameters. These are the step sizes the model will use to minimise the cost function, see more on this in the Surprise documentation." }, { "code": null, "e": 7744, "s": 7490, "text": "reg_all: Regularisation factor for all of the parameters. Surprise uses an L2 regularisation, which roughly means that it will try to minimise the differences between the squared value of the parameters. (The parameters being all the bu, bi, pu and qi.)" }, { "code": null, "e": 8093, "s": 7744, "text": "There are numerous other parameters you can play with, most of them are different setups of learning rate or and regularisation parameters. You can technically set a different learning rate or regularisation for each four types of the model parameters, and the ..._all parameters cover them all. I did not find it necessary to go into such details." }, { "code": null, "e": 8340, "s": 8093, "text": "We are going to use GridSearchCV to tune the hyperparameters in Surprise. It works mostly like its counterpart in scikit-learn, as the name suggests, it will search all the possible combinations on the hyperparameter grid, using Cross-Validation." }, { "code": null, "e": 8475, "s": 8340, "text": "First, we need a dictionary in which the keys are hyperparameter names, and the values are lists of different items you want to check:" }, { "code": null, "e": 8601, "s": 8475, "text": "param_grid = { 'n_factors':[5, 10,20], 'n_epochs': [5, 10, 20], 'lr_all': [0.002, 0.005], 'reg_all': [0.4, 0.6]}" }, { "code": null, "e": 8972, "s": 8601, "text": "You have to be careful about how you set up these parameters, as each of the possible combinations will be checked. In our cases, that is 3 * 3 * 2 * 2 = 36 different combinations, and for every one of these, the model will run multiple times, depending on the Cross-Validation you choose. I left the cv parameter at 5-fold, which means 36 * 5 = 180 model runs in total." }, { "code": null, "e": 9178, "s": 8972, "text": "That can take a long time, and this might be the time to start thinking about using cloud computing. I wrote a post recently about how to quickly set up a free Virtual Machine on the Google Cloud Platform." }, { "code": null, "e": 9261, "s": 9178, "text": "Once you have your parameter grid, you can set up the GridSearchCV object like so:" }, { "code": null, "e": 9374, "s": 9261, "text": "gs_model = GridSearchCV( algo_class = SVD, param_grid = param_grid, n_jobs = -1, joblib_verbose = 5)" }, { "code": null, "e": 9716, "s": 9374, "text": "The first parameter, algo_class, is the type of model you want to use. n_jobs = -1 simply tells the model that it can use all available processors, which is highly desirable when you have a parallelisable operation. One other parameter that you might want to change is cv, I just left it at the default, which does a 5-Fold Cross-Validation." }, { "code": null, "e": 9753, "s": 9716, "text": "Then you can simply fit on the data:" }, { "code": null, "e": 9772, "s": 9753, "text": "gs_model.fit(data)" }, { "code": null, "e": 9940, "s": 9772, "text": "Please note that once again, surprise handles databases a bit differently, you can only fit your GridSearchCV on the whole dataset, can’t split it into train and test." }, { "code": null, "e": 10048, "s": 9940, "text": "Finally, you can get a list of the parameters from the parameter grid that resulted in the best RMSE score:" }, { "code": null, "e": 10069, "s": 10048, "text": "gs_model.best_params" }, { "code": null, "e": 10130, "s": 10069, "text": "My process when working with GridSearchCV was the following:" }, { "code": null, "e": 10222, "s": 10130, "text": "Fit a GridSearchCV model on the whole data, with a parameter grid that covered a wide range" }, { "code": null, "e": 10264, "s": 10222, "text": "Calculated the Cross-Validated RMSE score" }, { "code": null, "e": 10532, "s": 10264, "text": "Repeated the process for a different parameter grid that either drilled down to a lower level if the optimal parameter seemed to be in the middle, or explored higher / lower parameters if the optimal parameter seemed to be at a boundary of the previous parameter grid" }, { "code": null, "e": 10658, "s": 10532, "text": "Once the decrease in RMSE score was minimal, saved the best hyperparameters and used them in the SVD models in the next steps" }, { "code": null, "e": 10823, "s": 10658, "text": "Because I wanted to compare the results with my KNN-type models from earlier, I ran the SVD model on the trainset, and calculated the test RMSE score on the testset" }, { "code": null, "e": 10954, "s": 10823, "text": "An alternative approach would have been to simply rely on the GSCV scores, and fit the final model only once on the full trainset." }, { "code": null, "e": 11013, "s": 10954, "text": "This concludes my series on recommendation system project." }, { "code": null, "e": 11258, "s": 11013, "text": "It was interesting to work with all these different approaches, especially how close their performance turned out to be. I spent a lot of time identifying the best model, but the truth is, even the simplest KNN models performed relatively well." }, { "code": null, "e": 11795, "s": 11258, "text": "I think that is partly because my data was not nearly as sparse as it usually is with recommendation systems. 10% of the possible user - item ratings were populated, which is considered to be an extremely high ratio. Imagine if people on average bought 10% of all the products on Amazon! The high ratio is because I limited my focus on the top 100 boardgames of all time, which are naturally popular titles. As an additional bonus, average ratings were pretty close and high, since these are all universally considered to be good games." }, { "code": null, "e": 11819, "s": 11795, "text": "Surprise documentation:" }, { "code": null, "e": 11843, "s": 11819, "text": "surprise.readthedocs.io" } ]
DAX Logical - IF function
Checks a condition given as the first argument of the function and returns one value if the condition is TRUE and returns another value if the condition is FALSE. IF (<logical_test>, <value_if_true>, [<value_if_false>]) logical_test Any value or expression that can be evaluated to TRUE or FALSE. value_if_true The value that is returned if the logical test is TRUE. value_if_false Optional. The value that is returned if the logical test is FALSE. If omitted, FALSE is returned. Any type of value that can be returned by an expression. If value_if_false is omitted, IF treats it as an empty string value (""). If value_if_false is omitted, IF treats it as an empty string value (""). If the value referenced in the logical_test is a column, IF returns the value that corresponds to the current row. Thus, the IF function returns a column of all the values resulting from the logical test corresponding to each of the rows. If the value referenced in the logical_test is a column, IF returns the value that corresponds to the current row. Thus, the IF function returns a column of all the values resulting from the logical test corresponding to each of the rows. If you have 3 values to return, then you can nest the IF functions. If you have 3 values to return, then you can nest the IF functions. =IF([Country]="USA",1,0) Returns a calculated column of 1’s and 0’s. These values can be summed up. If you name the column as USA Medals, then you can write the following − then you can write the following - 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": 2164, "s": 2001, "text": "Checks a condition given as the first argument of the function and returns one value if the condition is TRUE and returns another value if the condition is FALSE." }, { "code": null, "e": 2222, "s": 2164, "text": "IF (<logical_test>, <value_if_true>, [<value_if_false>])\n" }, { "code": null, "e": 2235, "s": 2222, "text": "logical_test" }, { "code": null, "e": 2299, "s": 2235, "text": "Any value or expression that can be evaluated to TRUE or FALSE." }, { "code": null, "e": 2313, "s": 2299, "text": "value_if_true" }, { "code": null, "e": 2369, "s": 2313, "text": "The value that is returned if the logical test is TRUE." }, { "code": null, "e": 2384, "s": 2369, "text": "value_if_false" }, { "code": null, "e": 2394, "s": 2384, "text": "Optional." }, { "code": null, "e": 2451, "s": 2394, "text": "The value that is returned if the logical test is FALSE." }, { "code": null, "e": 2482, "s": 2451, "text": "If omitted, FALSE is returned." }, { "code": null, "e": 2539, "s": 2482, "text": "Any type of value that can be returned by an expression." }, { "code": null, "e": 2613, "s": 2539, "text": "If value_if_false is omitted, IF treats it as an empty string value (\"\")." }, { "code": null, "e": 2687, "s": 2613, "text": "If value_if_false is omitted, IF treats it as an empty string value (\"\")." }, { "code": null, "e": 2926, "s": 2687, "text": "If the value referenced in the logical_test is a column, IF returns the value that corresponds to the current row. Thus, the IF function returns a column of all the values resulting from the logical test corresponding to each of the rows." }, { "code": null, "e": 3165, "s": 2926, "text": "If the value referenced in the logical_test is a column, IF returns the value that corresponds to the current row. Thus, the IF function returns a column of all the values resulting from the logical test corresponding to each of the rows." }, { "code": null, "e": 3233, "s": 3165, "text": "If you have 3 values to return, then you can nest the IF functions." }, { "code": null, "e": 3301, "s": 3233, "text": "If you have 3 values to return, then you can nest the IF functions." }, { "code": null, "e": 3326, "s": 3301, "text": "=IF([Country]=\"USA\",1,0)" }, { "code": null, "e": 3401, "s": 3326, "text": "Returns a calculated column of 1’s and 0’s. These values can be summed up." }, { "code": null, "e": 3474, "s": 3401, "text": "If you name the column as USA Medals, then you can write the following −" }, { "code": null, "e": 3509, "s": 3474, "text": "then you can write the following -" }, { "code": null, "e": 3544, "s": 3509, "text": "\n 53 Lectures \n 5.5 hours \n" }, { "code": null, "e": 3558, "s": 3544, "text": " Abhay Gadiya" }, { "code": null, "e": 3591, "s": 3558, "text": "\n 24 Lectures \n 2 hours \n" }, { "code": null, "e": 3605, "s": 3591, "text": " Randy Minder" }, { "code": null, "e": 3640, "s": 3605, "text": "\n 26 Lectures \n 4.5 hours \n" }, { "code": null, "e": 3654, "s": 3640, "text": " Randy Minder" }, { "code": null, "e": 3661, "s": 3654, "text": " Print" }, { "code": null, "e": 3672, "s": 3661, "text": " Add Notes" } ]
C++ program to implement Inverse Interpolation using Lagrange Formula
In this tutorial, we will be discussing a program to implement Inverse Interpolation using Lagrange formula. Inverse Interpolation is defined as the method of finding the value of an independent variable from the given value of dependent value lying between two tabulated set of values for an unknown function. #include <bits/stdc++.h> using namespace std; //structuring the values of x and y struct Data { double x, y; }; //calculating inverse interpolation double calc_invinter(Data d[], int n, double y){ double x = 0; int i, j; for (i = 0; i < n; i++) { double xi = d[i].x; for (j = 0; j < n; j++) { if (j != i) { xi = xi * (y - d[j].y) / (d[i].y - d[j].y); } } x += xi; } return x; } int main(){ Data d[] = { { 1.27, 2.3 }, { 2.25, 2.95 }, { 2.5, 3.5 }, { 3.6, 5.1 } }; int n = 6; double y = 4.5; cout << "Value of x (y = 4.5) : " << calc_invinter(d, n, y) << endl; return 0; } Value of x (y = 4.5) : 2.51602
[ { "code": null, "e": 1171, "s": 1062, "text": "In this tutorial, we will be discussing a program to implement Inverse Interpolation using Lagrange formula." }, { "code": null, "e": 1373, "s": 1171, "text": "Inverse Interpolation is defined as the method of finding the value of an independent variable from the given value of dependent value lying between two tabulated set of values for an unknown function." }, { "code": null, "e": 2059, "s": 1373, "text": "#include <bits/stdc++.h>\nusing namespace std;\n//structuring the values of x and y\nstruct Data {\n double x, y;\n};\n//calculating inverse interpolation\ndouble calc_invinter(Data d[], int n, double y){\n double x = 0;\n int i, j;\n for (i = 0; i < n; i++) {\n double xi = d[i].x;\n for (j = 0; j < n; j++) {\n if (j != i) {\n xi = xi * (y - d[j].y) / (d[i].y - d[j].y);\n }\n }\n x += xi;\n }\n return x;\n}\nint main(){\n Data d[] = {\n { 1.27, 2.3 },\n { 2.25, 2.95 },\n { 2.5, 3.5 },\n { 3.6, 5.1 }\n };\n int n = 6;\n double y = 4.5;\n cout << \"Value of x (y = 4.5) : \" << calc_invinter(d, n, y) << endl;\n return 0;\n}" }, { "code": null, "e": 2090, "s": 2059, "text": "Value of x (y = 4.5) : 2.51602" } ]
Fortran - Procedures
A procedure is a group of statements that perform a well-defined task and can be invoked from your program. Information (or data) is passed to the calling program, to the procedure as arguments. There are two types of procedures − Functions Subroutines A function is a procedure that returns a single quantity. A function should not modify its arguments. The returned quantity is known as function value, and it is denoted by the function name. Syntax Syntax for a function is as follows − function name(arg1, arg2, ....) [declarations, including those for the arguments] [executable statements] end function [name] The following example demonstrates a function named area_of_circle. It calculates the area of a circle with radius r. program calling_func real :: a a = area_of_circle(2.0) Print *, "The area of a circle with radius 2.0 is" Print *, a end program calling_func ! this function computes the area of a circle with radius r function area_of_circle (r) ! function result implicit none ! dummy arguments real :: area_of_circle ! local variables real :: r real :: pi pi = 4 * atan (1.0) area_of_circle = pi * r**2 end function area_of_circle When you compile and execute the above program, it produces the following result − The area of a circle with radius 2.0 is 12.5663710 Please note that − You must specify implicit none in both the main program as well as the procedure. You must specify implicit none in both the main program as well as the procedure. The argument r in the called function is called dummy argument. The argument r in the called function is called dummy argument. If you want the returned value to be stored in some other name than the function name, you can use the result option. You can specify the return variable name as − function name(arg1, arg2, ....) result (return_var_name) [declarations, including those for the arguments] [executable statements] end function [name] A subroutine does not return a value, however it can modify its arguments. Syntax subroutine name(arg1, arg2, ....) [declarations, including those for the arguments] [executable statements] end subroutine [name] You need to invoke a subroutine using the call statement. The following example demonstrates the definition and use of a subroutine swap, that changes the values of its arguments. program calling_func implicit none real :: a, b a = 2.0 b = 3.0 Print *, "Before calling swap" Print *, "a = ", a Print *, "b = ", b call swap(a, b) Print *, "After calling swap" Print *, "a = ", a Print *, "b = ", b end program calling_func subroutine swap(x, y) implicit none real :: x, y, temp temp = x x = y y = temp end subroutine swap When you compile and execute the above program, it produces the following result − Before calling swap a = 2.00000000 b = 3.00000000 After calling swap a = 3.00000000 b = 2.00000000 The intent attribute allows you to specify the intention with which arguments are used in the procedure. The following table provides the values of the intent attribute − The following example demonstrates the concept − program calling_func implicit none real :: x, y, z, disc x = 1.0 y = 5.0 z = 2.0 call intent_example(x, y, z, disc) Print *, "The value of the discriminant is" Print *, disc end program calling_func subroutine intent_example (a, b, c, d) implicit none ! dummy arguments real, intent (in) :: a real, intent (in) :: b real, intent (in) :: c real, intent (out) :: d d = b * b - 4.0 * a * c end subroutine intent_example When you compile and execute the above program, it produces the following result − The value of the discriminant is 17.0000000 Recursion occurs when a programming languages allows you to call a function inside the same function. It is called recursive call of the function. When a procedure calls itself, directly or indirectly, is called a recursive procedure. You should declare this type of procedures by preceding the word recursive before its declaration. When a function is used recursively, the result option has to be used. Following is an example, which calculates factorial for a given number using a recursive procedure − program calling_func implicit none integer :: i, f i = 15 Print *, "The value of factorial 15 is" f = myfactorial(15) Print *, f end program calling_func ! computes the factorial of n (n!) recursive function myfactorial (n) result (fac) ! function result implicit none ! dummy arguments integer :: fac integer, intent (in) :: n select case (n) case (0:1) fac = 1 case default fac = n * myfactorial (n-1) end select end function myfactorial When a procedure is contained within a program, it is called the internal procedure of the program. The syntax for containing an internal procedure is as follows − program program_name implicit none ! type declaration statements ! executable statements . . . contains ! internal procedures . . . end program program_name The following example demonstrates the concept − program mainprog implicit none real :: a, b a = 2.0 b = 3.0 Print *, "Before calling swap" Print *, "a = ", a Print *, "b = ", b call swap(a, b) Print *, "After calling swap" Print *, "a = ", a Print *, "b = ", b contains subroutine swap(x, y) real :: x, y, temp temp = x x = y y = temp end subroutine swap end program mainprog When you compile and execute the above program, it produces the following result − Before calling swap a = 2.00000000 b = 3.00000000 After calling swap a = 3.00000000 b = 2.00000000 Print Add Notes Bookmark this page
[ { "code": null, "e": 2341, "s": 2146, "text": "A procedure is a group of statements that perform a well-defined task and can be invoked from your program. Information (or data) is passed to the calling program, to the procedure as arguments." }, { "code": null, "e": 2377, "s": 2341, "text": "There are two types of procedures −" }, { "code": null, "e": 2387, "s": 2377, "text": "Functions" }, { "code": null, "e": 2399, "s": 2387, "text": "Subroutines" }, { "code": null, "e": 2501, "s": 2399, "text": "A function is a procedure that returns a single quantity. A function should not modify its arguments." }, { "code": null, "e": 2591, "s": 2501, "text": "The returned quantity is known as function value, and it is denoted by the function name." }, { "code": null, "e": 2598, "s": 2591, "text": "Syntax" }, { "code": null, "e": 2636, "s": 2598, "text": "Syntax for a function is as follows −" }, { "code": null, "e": 2775, "s": 2636, "text": "function name(arg1, arg2, ....) \n [declarations, including those for the arguments] \n [executable statements] \nend function [name]\n" }, { "code": null, "e": 2893, "s": 2775, "text": "The following example demonstrates a function named area_of_circle. It calculates the area of a circle with radius r." }, { "code": null, "e": 3408, "s": 2893, "text": "program calling_func\n\n real :: a\n a = area_of_circle(2.0) \n \n Print *, \"The area of a circle with radius 2.0 is\"\n Print *, a\n \nend program calling_func\n\n\n! this function computes the area of a circle with radius r \nfunction area_of_circle (r) \n\n! function result \nimplicit none \n\n ! dummy arguments \n real :: area_of_circle \n \n ! local variables \n real :: r \n real :: pi\n \n pi = 4 * atan (1.0) \n area_of_circle = pi * r**2 \n \nend function area_of_circle" }, { "code": null, "e": 3491, "s": 3408, "text": "When you compile and execute the above program, it produces the following result −" }, { "code": null, "e": 3549, "s": 3491, "text": "The area of a circle with radius 2.0 is\n 12.5663710 \n" }, { "code": null, "e": 3568, "s": 3549, "text": "Please note that −" }, { "code": null, "e": 3650, "s": 3568, "text": "You must specify implicit none in both the main program as well as the procedure." }, { "code": null, "e": 3732, "s": 3650, "text": "You must specify implicit none in both the main program as well as the procedure." }, { "code": null, "e": 3796, "s": 3732, "text": "The argument r in the called function is called dummy argument." }, { "code": null, "e": 3860, "s": 3796, "text": "The argument r in the called function is called dummy argument." }, { "code": null, "e": 3978, "s": 3860, "text": "If you want the returned value to be stored in some other name than the function name, you can use the result option." }, { "code": null, "e": 4024, "s": 3978, "text": "You can specify the return variable name as −" }, { "code": null, "e": 4188, "s": 4024, "text": "function name(arg1, arg2, ....) result (return_var_name) \n [declarations, including those for the arguments] \n [executable statements] \nend function [name]\n" }, { "code": null, "e": 4263, "s": 4188, "text": "A subroutine does not return a value, however it can modify its arguments." }, { "code": null, "e": 4270, "s": 4263, "text": "Syntax" }, { "code": null, "e": 4417, "s": 4270, "text": "subroutine name(arg1, arg2, ....) \n [declarations, including those for the arguments] \n [executable statements] \nend subroutine [name]\n" }, { "code": null, "e": 4475, "s": 4417, "text": "You need to invoke a subroutine using the call statement." }, { "code": null, "e": 4597, "s": 4475, "text": "The following example demonstrates the definition and use of a subroutine swap, that changes the values of its arguments." }, { "code": null, "e": 5017, "s": 4597, "text": "program calling_func\nimplicit none\n\n real :: a, b\n a = 2.0\n b = 3.0\n \n Print *, \"Before calling swap\"\n Print *, \"a = \", a\n Print *, \"b = \", b\n \n call swap(a, b)\n \n Print *, \"After calling swap\"\n Print *, \"a = \", a\n Print *, \"b = \", b\n \nend program calling_func\n\n\nsubroutine swap(x, y) \nimplicit none\n\n real :: x, y, temp \n \n temp = x \n x = y \n y = temp \n \nend subroutine swap" }, { "code": null, "e": 5100, "s": 5017, "text": "When you compile and execute the above program, it produces the following result −" }, { "code": null, "e": 5215, "s": 5100, "text": "Before calling swap\na = 2.00000000 \nb = 3.00000000 \nAfter calling swap\na = 3.00000000 \nb = 2.00000000 \n" }, { "code": null, "e": 5386, "s": 5215, "text": "The intent attribute allows you to specify the intention with which arguments are used in the procedure. The following table provides the values of the intent attribute −" }, { "code": null, "e": 5435, "s": 5386, "text": "The following example demonstrates the concept −" }, { "code": null, "e": 5954, "s": 5435, "text": "program calling_func\nimplicit none\n\n real :: x, y, z, disc\n \n x = 1.0\n y = 5.0\n z = 2.0\n \n call intent_example(x, y, z, disc)\n \n Print *, \"The value of the discriminant is\"\n Print *, disc\n \nend program calling_func\n\n\nsubroutine intent_example (a, b, c, d) \nimplicit none \n\n ! dummy arguments \n real, intent (in) :: a \n real, intent (in) :: b \n real, intent (in) :: c \n real, intent (out) :: d \n \n d = b * b - 4.0 * a * c \n \nend subroutine intent_example" }, { "code": null, "e": 6037, "s": 5954, "text": "When you compile and execute the above program, it produces the following result −" }, { "code": null, "e": 6089, "s": 6037, "text": "The value of the discriminant is\n 17.0000000 \n" }, { "code": null, "e": 6236, "s": 6089, "text": "Recursion occurs when a programming languages allows you to call a function inside the same function. It is called recursive call of the function." }, { "code": null, "e": 6423, "s": 6236, "text": "When a procedure calls itself, directly or indirectly, is called a recursive procedure. You should declare this type of procedures by preceding the word recursive before its declaration." }, { "code": null, "e": 6494, "s": 6423, "text": "When a function is used recursively, the result option has to be used." }, { "code": null, "e": 6595, "s": 6494, "text": "Following is an example, which calculates factorial for a given number using a recursive procedure −" }, { "code": null, "e": 7181, "s": 6595, "text": "program calling_func\nimplicit none\n\n integer :: i, f\n i = 15\n \n Print *, \"The value of factorial 15 is\"\n f = myfactorial(15)\n Print *, f\n \nend program calling_func\n\n! computes the factorial of n (n!) \nrecursive function myfactorial (n) result (fac) \n! function result \nimplicit none \n\n ! dummy arguments \n integer :: fac \n integer, intent (in) :: n \n \n select case (n) \n case (0:1) \n fac = 1 \n case default \n fac = n * myfactorial (n-1) \n end select \n \nend function myfactorial" }, { "code": null, "e": 7345, "s": 7181, "text": "When a procedure is contained within a program, it is called the internal procedure of the program. The syntax for containing an internal procedure is as follows −" }, { "code": null, "e": 7573, "s": 7345, "text": "program program_name \n implicit none \n ! type declaration statements \n ! executable statements \n . . . \n contains \n ! internal procedures \n . . . \nend program program_name\n" }, { "code": null, "e": 7622, "s": 7573, "text": "The following example demonstrates the concept −" }, { "code": null, "e": 8057, "s": 7622, "text": "program mainprog \nimplicit none \n\n real :: a, b \n a = 2.0\n b = 3.0\n \n Print *, \"Before calling swap\"\n Print *, \"a = \", a\n Print *, \"b = \", b\n \n call swap(a, b)\n \n Print *, \"After calling swap\"\n Print *, \"a = \", a\n Print *, \"b = \", b\n \ncontains \n subroutine swap(x, y) \n real :: x, y, temp \n temp = x \n x = y \n y = temp \n end subroutine swap \n \nend program mainprog " }, { "code": null, "e": 8140, "s": 8057, "text": "When you compile and execute the above program, it produces the following result −" }, { "code": null, "e": 8255, "s": 8140, "text": "Before calling swap\na = 2.00000000 \nb = 3.00000000 \nAfter calling swap\na = 3.00000000 \nb = 2.00000000 \n" }, { "code": null, "e": 8262, "s": 8255, "text": " Print" }, { "code": null, "e": 8273, "s": 8262, "text": " Add Notes" } ]
Python Program for cube sum of first n natural numbers
In this article, we will learn about the solution and approach to solve the given problem statement. Problem statement −Given an input n, we need to print the sum of series 13 + 23 + 33 + 43 + .......+ n3 till n-th term. Here we will discuss two approach to reach the solution of the problem statement − Brute-force approach using loops. Mathematical solution of sum of n numbers. Approach 1 −Computing sum of each term by adding by iterating over the numbers Live Demo def sumOfSeries(n): sum = 0 for i in range(1, n+1): sum +=i*i*i return sum # Driver Function n = 3 print(sumOfSeries(n)) 36 Approach 2 −Computation using mathematical formula Here we will be using mathematical sum formulae which is aldready derived for the cubic sum of natural numbers. Sum = ( n * (n + 1) / 2 ) ** 2 Live Demo def sumOfSeries(n): x = (n * (n + 1) / 2) return (int)(x * x) # main n = 3 print(sumOfSeries(n)) 36 In this article, we learned about the approach to compute the cube sum of first n natural numbers.
[ { "code": null, "e": 1163, "s": 1062, "text": "In this article, we will learn about the solution and approach to solve the given problem statement." }, { "code": null, "e": 1283, "s": 1163, "text": "Problem statement −Given an input n, we need to print the sum of series 13 + 23 + 33 + 43 + .......+ n3 till n-th term." }, { "code": null, "e": 1366, "s": 1283, "text": "Here we will discuss two approach to reach the solution of the problem statement −" }, { "code": null, "e": 1400, "s": 1366, "text": "Brute-force approach using loops." }, { "code": null, "e": 1443, "s": 1400, "text": "Mathematical solution of sum of n numbers." }, { "code": null, "e": 1522, "s": 1443, "text": "Approach 1 −Computing sum of each term by adding by iterating over the numbers" }, { "code": null, "e": 1533, "s": 1522, "text": " Live Demo" }, { "code": null, "e": 1669, "s": 1533, "text": "def sumOfSeries(n):\n sum = 0\n for i in range(1, n+1):\n sum +=i*i*i\n return sum\n# Driver Function\nn = 3\nprint(sumOfSeries(n))" }, { "code": null, "e": 1672, "s": 1669, "text": "36" }, { "code": null, "e": 1723, "s": 1672, "text": "Approach 2 −Computation using mathematical formula" }, { "code": null, "e": 1835, "s": 1723, "text": "Here we will be using mathematical sum formulae which is aldready derived for the cubic sum of natural numbers." }, { "code": null, "e": 1866, "s": 1835, "text": "Sum = ( n * (n + 1) / 2 ) ** 2" }, { "code": null, "e": 1877, "s": 1866, "text": " Live Demo" }, { "code": null, "e": 1980, "s": 1877, "text": "def sumOfSeries(n):\n x = (n * (n + 1) / 2)\n return (int)(x * x)\n# main\nn = 3\nprint(sumOfSeries(n))" }, { "code": null, "e": 1983, "s": 1980, "text": "36" }, { "code": null, "e": 2082, "s": 1983, "text": "In this article, we learned about the approach to compute the cube sum of first n natural numbers." } ]
How to invoke the Firefox browser in Selenium with python?
We can invoke any browsers with the help of the webdriver package. From this package we get access to numerous classes. Next we have to import the selenium.webdriver package. Then we shall be exposed to all the browsers belonging to that package. For invoking the Firefox browser, we have to select the Firefox class. Then create the driver object of that class. This is the most important and mandatory step for browser invocation. Every firefox browser gives an executable file. Through Selenium we need to invoke this executable file which is responsible for invoking the actual chrome browser. Next we need to download the gecko driver version as per our browser version. The path of the geckodriver.exe file needs to be added in the executable file. Then we need to use the get () method to launch our application in that particular browser. Code Implementation from selenium import webdriver #browser exposes an executable file #Through Selenium test we will invoke the executable file which will then #invoke actual browser driver = webdriver.Firefox(executable_path="C:\\geckodriver.exe") # to maximize the browser window driver.maximize_window() #get method to launch the URL driver.get("https://www.tutorialspoint.com/index.htm") #to refresh the browser driver.refresh() #to close the browser driver.close()
[ { "code": null, "e": 1309, "s": 1062, "text": "We can invoke any browsers with the help of the webdriver package. From this package we get access to numerous classes. Next we have to import the selenium.webdriver package. Then we shall be exposed to all the browsers belonging to that package." }, { "code": null, "e": 1495, "s": 1309, "text": "For invoking the Firefox browser, we have to select the Firefox class. Then create the driver object of that class. This is the most important and mandatory step for browser invocation." }, { "code": null, "e": 1660, "s": 1495, "text": "Every firefox browser gives an executable file. Through Selenium we need to invoke this executable file which is responsible for invoking the actual chrome browser." }, { "code": null, "e": 1909, "s": 1660, "text": "Next we need to download the gecko driver version as per our browser version. The path of the geckodriver.exe file needs to be added in the executable file. Then we need to use the get () method to launch our application in that particular browser." }, { "code": null, "e": 1929, "s": 1909, "text": "Code Implementation" }, { "code": null, "e": 2380, "s": 1929, "text": "from selenium import webdriver\n#browser exposes an executable file\n#Through Selenium test we will invoke the executable file which will then #invoke actual browser\ndriver = webdriver.Firefox(executable_path=\"C:\\\\geckodriver.exe\")\n# to maximize the browser window\ndriver.maximize_window()\n#get method to launch the URL\ndriver.get(\"https://www.tutorialspoint.com/index.htm\")\n#to refresh the browser\ndriver.refresh()\n#to close the browser\ndriver.close()" } ]
How to center an image in canvas Python Tkinter
Let us consider that we are creating a GUI-based application using Tkinter and we want to load an image in the Tkinter canvas. By default, the canvas loads the images according to its width and height. However, we can manipulate the position of an image in any direction (N,S,E,W,NS, EW, etc.) by passing the ‘Direction’ value in the anchor parameter. An anchor is a parameter which is invoked along with the image function; it defines the direction or position of the image in the canvas. By using anchor parameters, we can align the text and images in any direction. For now, we will create an image label by using the Label function such that, Label(root, text= " ", other Options(color, width,height,..)) After creating the image label using the above function, we will adjust its position using the ‘anchor’ property. Since we have to place the image at the center, we will pass the value of anchor as “CENTER”. #import the tkinter library in the notebook from tkinter import * #creating an instance of the tkinter canvas win= Tk() #define the size of the window win.geometry("700x150") #define the image label having some properties label_img= Label(win, text= "Hello World", font= "sans-serif",relief= "solid",width= 20, height= 8, anchor= CENTER) label_img.pack() #displaying the canvas without closing the window win.mainloop() Running the above snippet will generate the output and place the image at the center of the canvas.
[ { "code": null, "e": 1189, "s": 1062, "text": "Let us consider that we are creating a GUI-based application using Tkinter and we\nwant to load an image in the Tkinter canvas." }, { "code": null, "e": 1552, "s": 1189, "text": "By default, the canvas loads the images according to its width and height.\nHowever, we can manipulate the position of an image in any direction\n(N,S,E,W,NS, EW, etc.) by passing the ‘Direction’ value in the anchor parameter.\nAn anchor is a parameter which is invoked along with the image function; it defines\nthe direction or position of the image in the canvas." }, { "code": null, "e": 1709, "s": 1552, "text": "By using anchor parameters, we can align the text and images in any direction. For now, we will create an image label by using the Label function such that," }, { "code": null, "e": 1771, "s": 1709, "text": "Label(root, text= \" \", other Options(color, width,height,..))" }, { "code": null, "e": 1979, "s": 1771, "text": "After creating the image label using the above function, we will adjust its position\nusing the ‘anchor’ property. Since we have to place the image at the center, we will pass the value of anchor as “CENTER”." }, { "code": null, "e": 2402, "s": 1979, "text": "#import the tkinter library in the notebook\n\nfrom tkinter import *\n#creating an instance of the tkinter canvas\nwin= Tk()\n#define the size of the window\nwin.geometry(\"700x150\")\n\n#define the image label having some properties\n\nlabel_img= Label(win, text= \"Hello World\", font= \"sans-serif\",relief=\n\"solid\",width= 20, height= 8, anchor= CENTER)\nlabel_img.pack()\n#displaying the canvas without closing the window\nwin.mainloop()" }, { "code": null, "e": 2502, "s": 2402, "text": "Running the above snippet will generate the output and place the image at the\ncenter of the canvas." } ]
C program to demonstrate fork() and pipe()
In this problem, we will demonstrate fork() and pipe(). Here we will create a C program for Linux that will concatenate two string, using 2 processes one will take input and send it to others which will concatenate the string with a predefined string and return the concatenated string. First lets recap fork() and pipe() fork() − it creates a child process, this child process ahs a new PID and PPID. pipe() is a Unix, Linux system call that is used for inter-process communication. Let’s take an example for understanding the problem, Learn programming Predefined string: at tutorialspoint Learn programming at tutorialspoint P1 take input of string “learn programming” Sends it to P2 using the pipe. P2 concatenates the strings and sends back to p1 which prints it. In the program, we will create two processes, say P1 and P2 using the fork() function. It has the following three return values which show the state of the program. return value < 0, process creation failed. return value = 0, child process. return value > 0, which will be the process ID of the child process to the parent process i.e. The parent process will be executed. We will create two pipes one for communicating from P1 to P2 and other from P2 to P1 as the pipe is one way. C program to demonstrate fork() and pipe() #include<stdio.h> #include<stdlib.h> #include<unistd.h> #include<sys/types.h> #include<string.h> #include<sys/wait.h> int main(){ int p12[2]; int p21[2]; char fixed_str[] = " at tutorialspoint"; char input_str[100]; pid_t P; if (pipe(p12)==-1 || pipe(p21)==-1 ){ fprintf(stderr, "Filed to create pipe" ); return 1; } scanf("%s", input_str); P = fork(); if (P < 0){ fprintf(stderr, "fork Failed" ); return 1; } else if (P > 0){ char concat_str[100]; close(p12[0]); write(p12[1], input_str, strlen(input_str)+1); close(p12[1]); wait(NULL); close(p21[1]); read(p21[0], concat_str, 100); printf("Concatenated string %s\n", concat_str); close(p21[0]); } else{ close(p12[1]); char concat_str[100]; read(p12[0], concat_str, 100); int k = strlen(concat_str); int i; for (i=0; i<strlen(fixed_str); i++) concat_str[k++] = fixed_str[i]; concat_str[k] = '\0'; close(p12[0]); close(p21[0]); write(p21[1], concat_str, strlen(concat_str)+1); close(p21[1]); exit(0); } } Concatenated string Learn at tutorialspoint
[ { "code": null, "e": 1349, "s": 1062, "text": "In this problem, we will demonstrate fork() and pipe(). Here we will create a C program for Linux that will concatenate two string, using 2 processes one will take input and send it to others which will concatenate the string with a predefined string and return the concatenated string." }, { "code": null, "e": 1384, "s": 1349, "text": "First lets recap fork() and pipe()" }, { "code": null, "e": 1464, "s": 1384, "text": "fork() − it creates a child process, this child process ahs a new PID and PPID." }, { "code": null, "e": 1546, "s": 1464, "text": "pipe() is a Unix, Linux system call that is used for inter-process communication." }, { "code": null, "e": 1599, "s": 1546, "text": "Let’s take an example for understanding the problem," }, { "code": null, "e": 1654, "s": 1599, "text": "Learn programming\nPredefined string: at tutorialspoint" }, { "code": null, "e": 1690, "s": 1654, "text": "Learn programming at tutorialspoint" }, { "code": null, "e": 1734, "s": 1690, "text": "P1 take input of string “learn programming”" }, { "code": null, "e": 1765, "s": 1734, "text": "Sends it to P2 using the pipe." }, { "code": null, "e": 1831, "s": 1765, "text": "P2 concatenates the strings and sends back to p1 which prints it." }, { "code": null, "e": 1996, "s": 1831, "text": "In the program, we will create two processes, say P1 and P2 using the fork() function. It has the following three return values which show the state of the program." }, { "code": null, "e": 2039, "s": 1996, "text": "return value < 0, process creation failed." }, { "code": null, "e": 2072, "s": 2039, "text": "return value = 0, child process." }, { "code": null, "e": 2204, "s": 2072, "text": "return value > 0, which will be the process ID of the child process to the parent process i.e. The parent process will be executed." }, { "code": null, "e": 2313, "s": 2204, "text": "We will create two pipes one for communicating from P1 to P2 and other from P2 to P1 as the pipe is one way." }, { "code": null, "e": 2356, "s": 2313, "text": "C program to demonstrate fork() and pipe()" }, { "code": null, "e": 3512, "s": 2356, "text": "#include<stdio.h>\n#include<stdlib.h>\n#include<unistd.h>\n#include<sys/types.h>\n#include<string.h>\n#include<sys/wait.h>\nint main(){\n int p12[2];\n int p21[2];\n char fixed_str[] = \" at tutorialspoint\";\n char input_str[100];\n pid_t P;\n if (pipe(p12)==-1 || pipe(p21)==-1 ){\n fprintf(stderr, \"Filed to create pipe\" );\n return 1;\n }\n scanf(\"%s\", input_str);\n P = fork();\n if (P < 0){\n fprintf(stderr, \"fork Failed\" );\n return 1;\n }\n else if (P > 0){\n char concat_str[100];\n close(p12[0]);\n write(p12[1], input_str, strlen(input_str)+1);\n close(p12[1]);\n wait(NULL);\n close(p21[1]);\n read(p21[0], concat_str, 100);\n printf(\"Concatenated string %s\\n\", concat_str);\n close(p21[0]);\n }\n else{\n close(p12[1]);\n char concat_str[100];\n read(p12[0], concat_str, 100);\n int k = strlen(concat_str);\n int i;\n for (i=0; i<strlen(fixed_str); i++)\n concat_str[k++] = fixed_str[i];\n concat_str[k] = '\\0';\n close(p12[0]);\n close(p21[0]);\n write(p21[1], concat_str, strlen(concat_str)+1);\n close(p21[1]);\n exit(0);\n }\n}" }, { "code": null, "e": 3556, "s": 3512, "text": "Concatenated string Learn at tutorialspoint" } ]
How to set the height of an element with JavaScript?
Use the height property to set the height of an element. You can try to run the following code to set the height of a button with JavaScript − Live Demo <!DOCTYPE html> <html> <body> <h1>Heading 1</h1> <p>This is Demo Text.</p> <button type="button" id="myID" onclick="display()">Update Height</button> <script> function display() { document.getElementById("myID").style.height = "100px"; } </script> </body> </html>
[ { "code": null, "e": 1205, "s": 1062, "text": "Use the height property to set the height of an element. You can try to run the following code to set the height of a button with JavaScript −" }, { "code": null, "e": 1215, "s": 1205, "text": "Live Demo" }, { "code": null, "e": 1545, "s": 1215, "text": "<!DOCTYPE html>\n<html>\n <body>\n <h1>Heading 1</h1>\n <p>This is Demo Text.</p>\n <button type=\"button\" id=\"myID\" onclick=\"display()\">Update Height</button>\n <script>\n function display() {\n document.getElementById(\"myID\").style.height = \"100px\";\n }\n </script>\n </body>\n</html>" } ]
How to loop through arrays in JavaScript objects?
Looping through arrays inside objects is the same as looping through objects. We have to use 'for...in' loop to loop through arrays inside objects. In the following example, an object "obj" is defined. This object has an array in it. Using 'for...in' loop, the elements in that array are displayed as shown in the output. Live Demo <html> <body> <script> var res = "" var obj = { "name":"Elon musk", "age":48, "companies": [ {"location":"Newyork", "name":["Tesla", "Spacex", "Neuralink"]}, {"location":"Florida", "name":["paypal", "solarcity"]}, ] } for (var i in obj.companies) { res += "The companies in " + " "+ obj.companies[i].location + "</br>"; for (var j in obj.companies[i].name) { res += obj.companies[i].name[j] + "</br>"; } } document.write(res); </script> </body> </html> The companies in Newyork Tesla Spacex Neuralink The companies in Florida paypal solarcity
[ { "code": null, "e": 1210, "s": 1062, "text": "Looping through arrays inside objects is the same as looping through objects. We have to use 'for...in' loop to loop through arrays inside objects." }, { "code": null, "e": 1385, "s": 1210, "text": "In the following example, an object \"obj\" is defined. This object has an array in it. Using 'for...in' loop, the elements in that array are displayed as shown in the output. " }, { "code": null, "e": 1395, "s": 1385, "text": "Live Demo" }, { "code": null, "e": 2066, "s": 1395, "text": "<html>\n<body>\n <script>\n var res = \"\"\n var obj = {\n \"name\":\"Elon musk\",\n \"age\":48,\n \"companies\": [\n {\"location\":\"Newyork\", \"name\":[\"Tesla\", \"Spacex\", \"Neuralink\"]}, \n {\"location\":\"Florida\", \"name\":[\"paypal\", \"solarcity\"]},\n ]\n }\n for (var i in obj.companies) {\n res += \"The companies in \" + \" \"+ obj.companies[i].location + \"</br>\";\n for (var j in obj.companies[i].name) {\n res += obj.companies[i].name[j] + \"</br>\";\n }\n }\n document.write(res);\n </script>\n</body>\n</html>" }, { "code": null, "e": 2156, "s": 2066, "text": "The companies in Newyork\nTesla\nSpacex\nNeuralink\nThe companies in Florida\npaypal\nsolarcity" } ]
How is Session Management done in JSP?
JSP makes use of the servlet provided HttpSession Interface. This interface provides a way to identify a user across. a one-page request or visit to a website or store information about that user By default, JSPs have session tracking enabled and a new HttpSession object is instantiated for each new client automatically. Disabling session tracking requires explicitly turning it off by setting the page directive session attribute to false as follows − <%@ page session = "false" %> The JSP engine exposes the HttpSession object to the JSP author through the implicit session object. Since session object is already provided to the JSP programmer, the programmer can immediately begin storing and retrieving data from the object without any initialization or getSession().
[ { "code": null, "e": 1180, "s": 1062, "text": "JSP makes use of the servlet provided HttpSession Interface. This interface provides a way to identify a user across." }, { "code": null, "e": 1202, "s": 1180, "text": "a one-page request or" }, { "code": null, "e": 1224, "s": 1202, "text": "visit to a website or" }, { "code": null, "e": 1258, "s": 1224, "text": "store information about that user" }, { "code": null, "e": 1517, "s": 1258, "text": "By default, JSPs have session tracking enabled and a new HttpSession object is instantiated for each new client automatically. Disabling session tracking requires explicitly turning it off by setting the page directive session attribute to false as follows −" }, { "code": null, "e": 1547, "s": 1517, "text": "<%@ page session = \"false\" %>" }, { "code": null, "e": 1837, "s": 1547, "text": "The JSP engine exposes the HttpSession object to the JSP author through the implicit session object. Since session object is already provided to the JSP programmer, the programmer can immediately begin storing and retrieving data from the object without any initialization or getSession()." } ]
DurationField - Django forms - GeeksforGeeks
13 Feb, 2020 DurationField in Django Forms is used for input of particular durations for example from 12 am to 1 pm. The default widget for this input is TextInput. It Normalizes to: A Python datetime.date object. It validates that the given value is a string which can be converted into a timedelta. DurationField has one optional arguments: input_formats :- Accepts any format understood by parse_duration(). Expects data in the format “DD HH:MM:SS.uuuuuu” or as specified by ISO 8601 (e.g. P4DT1H15M20S which is equivalent to 4 1:15:20) or PostgreSQL’s day-time interval format (e.g. 3 days 04:05:06). Syntax field_name = forms.DurationField(**options) Illustration of DurationField using an Example. Consider a project named geeksforgeeks having an app named geeks. Refer to the following articles to check how to create a project and an app in Django. How to Create a Basic Project using MVT in Django? How to Create an App in Django ? Enter the following code into forms.py file of geeks app. from django import forms # creating a form class GeeksForm(forms.Form): geeks_field = forms.DurationField( ) Add the geeks app to INSTALLED_APPS # Application definition INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'geeks',] Now to render this form into a view we need a view and a URL mapped to that URL. Let’s create a view first in views.py of geeks app, from django.shortcuts import renderfrom .forms import GeeksForm # Create your views here.def home_view(request): context = {} context['form'] = GeeksForm() return render( request, "home.html", context) Here we are importing that particular form from forms.py and creating an object of it in the view so that it can be rendered in a template.Now, to initiate a Django form you need to create home.html where one would be designing the stuff as they like. Let’s create a form in home.html. <form method = "GET"> {{ form }} <input type = "submit" value = "Submit"></form> Finally, a URL to map to this view in urls.py from django.urls import path # importing views from views..pyfrom .views import home_view urlpatterns = [ path('', home_view ),] Let’s run the server and check what has actually happened, Run Python manage.py runserver Thus, an geeks_field DurationField is created by replacing “_” with ” “. It is a field to input duration accepted by Python’s timedelta function from the user. Check here for more. DurationField is used for input of a particular duration in the database. One can input date of submission, birthdate, etc. Till now we have discussed how to implement DurationField but how to use it in the view for performing the logical part. To perform some logic we would need to get the value entered into field into a python string instance.In views.py, from django.shortcuts import renderfrom .forms import GeeksForm # Create your views here.def home_view(request): context ={} form = GeeksForm() context['form']= form if request.GET: temp = request.GET['geeks_field'] print(type(temp)) return render(request, "home.html", context) Let’s try something other than a duration in a DurationField. So it accepts a duration input only otherwise validation errors will be seen. Now let’s try entering a valid duration into the field.Date data can be fetched using corresponding request dictionary. If method is GET, data would be available in request.GET and if post, request.POST correspondingly. In above example we have the value in temp which we can use for any purpose. Core Field arguments are the arguments given to each field for applying some constraint or imparting a particular characteristic to a particular Field. For example, adding an argument required = False to DurationField will enable it to be left blank by the user. Each Field class constructor takes at least these arguments. Some Field classes take additional, field-specific arguments, but the following should always be accepted: NaveenArora Django-forms Python Django Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Python Dictionary How to Install PIP on Windows ? Read a file line by line in Python Enumerate() in Python Iterate over a list in Python Different ways to create Pandas Dataframe Python program to convert a list to string Create a Pandas DataFrame from Lists Python String | replace() Reading and Writing to text files in Python
[ { "code": null, "e": 23992, "s": 23964, "text": "\n13 Feb, 2020" }, { "code": null, "e": 24280, "s": 23992, "text": "DurationField in Django Forms is used for input of particular durations for example from 12 am to 1 pm. The default widget for this input is TextInput. It Normalizes to: A Python datetime.date object. It validates that the given value is a string which can be converted into a timedelta." }, { "code": null, "e": 24322, "s": 24280, "text": "DurationField has one optional arguments:" }, { "code": null, "e": 24390, "s": 24322, "text": "input_formats :- Accepts any format understood by parse_duration()." }, { "code": null, "e": 24584, "s": 24390, "text": "Expects data in the format “DD HH:MM:SS.uuuuuu” or as specified by ISO 8601 (e.g. P4DT1H15M20S which is equivalent to 4 1:15:20) or PostgreSQL’s day-time interval format (e.g. 3 days 04:05:06)." }, { "code": null, "e": 24591, "s": 24584, "text": "Syntax" }, { "code": null, "e": 24635, "s": 24591, "text": "field_name = forms.DurationField(**options)" }, { "code": null, "e": 24749, "s": 24635, "text": "Illustration of DurationField using an Example. Consider a project named geeksforgeeks having an app named geeks." }, { "code": null, "e": 24836, "s": 24749, "text": "Refer to the following articles to check how to create a project and an app in Django." }, { "code": null, "e": 24887, "s": 24836, "text": "How to Create a Basic Project using MVT in Django?" }, { "code": null, "e": 24920, "s": 24887, "text": "How to Create an App in Django ?" }, { "code": null, "e": 24978, "s": 24920, "text": "Enter the following code into forms.py file of geeks app." }, { "code": "from django import forms # creating a form class GeeksForm(forms.Form): geeks_field = forms.DurationField( )", "e": 25091, "s": 24978, "text": null }, { "code": null, "e": 25127, "s": 25091, "text": "Add the geeks app to INSTALLED_APPS" }, { "code": "# Application definition INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'geeks',]", "e": 25365, "s": 25127, "text": null }, { "code": null, "e": 25498, "s": 25365, "text": "Now to render this form into a view we need a view and a URL mapped to that URL. Let’s create a view first in views.py of geeks app," }, { "code": "from django.shortcuts import renderfrom .forms import GeeksForm # Create your views here.def home_view(request): context = {} context['form'] = GeeksForm() return render( request, \"home.html\", context)", "e": 25710, "s": 25498, "text": null }, { "code": null, "e": 25996, "s": 25710, "text": "Here we are importing that particular form from forms.py and creating an object of it in the view so that it can be rendered in a template.Now, to initiate a Django form you need to create home.html where one would be designing the stuff as they like. Let’s create a form in home.html." }, { "code": "<form method = \"GET\"> {{ form }} <input type = \"submit\" value = \"Submit\"></form>", "e": 26083, "s": 25996, "text": null }, { "code": null, "e": 26129, "s": 26083, "text": "Finally, a URL to map to this view in urls.py" }, { "code": "from django.urls import path # importing views from views..pyfrom .views import home_view urlpatterns = [ path('', home_view ),]", "e": 26263, "s": 26129, "text": null }, { "code": null, "e": 26326, "s": 26263, "text": "Let’s run the server and check what has actually happened, Run" }, { "code": null, "e": 26353, "s": 26326, "text": "Python manage.py runserver" }, { "code": null, "e": 26534, "s": 26353, "text": "Thus, an geeks_field DurationField is created by replacing “_” with ” “. It is a field to input duration accepted by Python’s timedelta function from the user. Check here for more." }, { "code": null, "e": 26894, "s": 26534, "text": "DurationField is used for input of a particular duration in the database. One can input date of submission, birthdate, etc. Till now we have discussed how to implement DurationField but how to use it in the view for performing the logical part. To perform some logic we would need to get the value entered into field into a python string instance.In views.py," }, { "code": "from django.shortcuts import renderfrom .forms import GeeksForm # Create your views here.def home_view(request): context ={} form = GeeksForm() context['form']= form if request.GET: temp = request.GET['geeks_field'] print(type(temp)) return render(request, \"home.html\", context)", "e": 27203, "s": 26894, "text": null }, { "code": null, "e": 27265, "s": 27203, "text": "Let’s try something other than a duration in a DurationField." }, { "code": null, "e": 27640, "s": 27265, "text": "So it accepts a duration input only otherwise validation errors will be seen. Now let’s try entering a valid duration into the field.Date data can be fetched using corresponding request dictionary. If method is GET, data would be available in request.GET and if post, request.POST correspondingly. In above example we have the value in temp which we can use for any purpose." }, { "code": null, "e": 28071, "s": 27640, "text": "Core Field arguments are the arguments given to each field for applying some constraint or imparting a particular characteristic to a particular Field. For example, adding an argument required = False to DurationField will enable it to be left blank by the user. Each Field class constructor takes at least these arguments. Some Field classes take additional, field-specific arguments, but the following should always be accepted:" }, { "code": null, "e": 28083, "s": 28071, "text": "NaveenArora" }, { "code": null, "e": 28096, "s": 28083, "text": "Django-forms" }, { "code": null, "e": 28110, "s": 28096, "text": "Python Django" }, { "code": null, "e": 28117, "s": 28110, "text": "Python" }, { "code": null, "e": 28215, "s": 28117, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 28224, "s": 28215, "text": "Comments" }, { "code": null, "e": 28237, "s": 28224, "text": "Old Comments" }, { "code": null, "e": 28255, "s": 28237, "text": "Python Dictionary" }, { "code": null, "e": 28287, "s": 28255, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 28322, "s": 28287, "text": "Read a file line by line in Python" }, { "code": null, "e": 28344, "s": 28322, "text": "Enumerate() in Python" }, { "code": null, "e": 28374, "s": 28344, "text": "Iterate over a list in Python" }, { "code": null, "e": 28416, "s": 28374, "text": "Different ways to create Pandas Dataframe" }, { "code": null, "e": 28459, "s": 28416, "text": "Python program to convert a list to string" }, { "code": null, "e": 28496, "s": 28459, "text": "Create a Pandas DataFrame from Lists" }, { "code": null, "e": 28522, "s": 28496, "text": "Python String | replace()" } ]
Node.js Buffer.subarray() Method
17 Feb, 2022 The buffer.subarray() method is an inbuilt application programming interface of the buffer module which is used to crop a part of array i.e. create sub-array from an array.Syntax: Buffer.subarray( starting_index, ending_index ) Parameters: This method has two parameters as mentioned above and described below: starting_index: This parameter specifies an integer value that denotes the starting address of the buffer from where new buffer to start. Its default value is 0. ending_index: It specifies an integer value that denotes ending address of the buffer up to which the new buffer to be created. The default value is the length of the buffer. Return Value: This method returns the cropped array. This buffer points to the same memory but with cropped starting and ending indices. If ending_index in the parameter is greater than buffer length then buffer length is taken as ending index.Note: If the new buffer is modified then the same will be reflected in the original buffer as they point to the same memory.Below examples illustrate the use of buffer.subarray() method in Node.js:Example 1: javascript // Node.js program to demonstrate the // Buffer.subarray() method // Allocating bufferconst buf = Buffer.from('GeeksforGeeks', 'ascii'); // Printing original bufferconsole.log("Original buffer is: " + buf); // Cropping buffer, here starting index// is 5 and ending index is 10cropped_buf = buf.subarray(5, 10); // Printing cropped bufferconsole.log("Cropped buffer is: " + cropped_buf); // Modifying cropped buffercropped_buf[0] = 70; // Fcropped_buf[1] = 79; // Ocropped_buf[2] = 82; // R // Printing cropped bufferconsole.log("Cropped buffer after modification is: " + cropped_buf); // Printing original bufferconsole.log("Original buffer after modification is: " + buf); Output: Original buffer is: GeeksforGeeks Cropped buffer is: forGe Cropped buffer after modification is: FORGe Original buffer after modification is: GeeksFORGeeks Example 2: javascript // Node.js program to demonstrate the // Buffer.subarray() method // Allocating bufferconst buf = Buffer.from('GeeksforGeeks', 'ascii'); // Printing original bufferconsole.log("Original buffer is: " + buf); // Cropping buffer, here starting index// is -10 and ending index is -1cropped_buf = buf.subarray(-12, -1); // Printing cropped bufferconsole.log("Cropped buffer is:" + cropped_buf); // Cropping buffer again, here starting// index is -10 and ending index is -5cropped_buf = buf.subarray(-10, -5); // Printing cropped bufferconsole.log("Cropped buffer is: " + cropped_buf); // Cropping buffer again with no parametercropped_buf = buf.subarray(); // Printing cropped bufferconsole.log("Cropped buffer is: " + cropped_buf); Output: Original buffer is: GeeksforGeeks Cropped buffer is:eeksforGeek Cropped buffer is: ksfor Cropped buffer is: GeeksforGeeks Note: The above program will compile and run by using the node index.js command.Reference: https://nodejs.org/api/buffer.html#buffer_buf_subarray_start_end simranarora5sos Node.js-Buffer-module Node.js Web Technologies Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n17 Feb, 2022" }, { "code": null, "e": 210, "s": 28, "text": "The buffer.subarray() method is an inbuilt application programming interface of the buffer module which is used to crop a part of array i.e. create sub-array from an array.Syntax: " }, { "code": null, "e": 258, "s": 210, "text": "Buffer.subarray( starting_index, ending_index )" }, { "code": null, "e": 343, "s": 258, "text": "Parameters: This method has two parameters as mentioned above and described below: " }, { "code": null, "e": 505, "s": 343, "text": "starting_index: This parameter specifies an integer value that denotes the starting address of the buffer from where new buffer to start. Its default value is 0." }, { "code": null, "e": 680, "s": 505, "text": "ending_index: It specifies an integer value that denotes ending address of the buffer up to which the new buffer to be created. The default value is the length of the buffer." }, { "code": null, "e": 1134, "s": 680, "text": "Return Value: This method returns the cropped array. This buffer points to the same memory but with cropped starting and ending indices. If ending_index in the parameter is greater than buffer length then buffer length is taken as ending index.Note: If the new buffer is modified then the same will be reflected in the original buffer as they point to the same memory.Below examples illustrate the use of buffer.subarray() method in Node.js:Example 1: " }, { "code": null, "e": 1145, "s": 1134, "text": "javascript" }, { "code": "// Node.js program to demonstrate the // Buffer.subarray() method // Allocating bufferconst buf = Buffer.from('GeeksforGeeks', 'ascii'); // Printing original bufferconsole.log(\"Original buffer is: \" + buf); // Cropping buffer, here starting index// is 5 and ending index is 10cropped_buf = buf.subarray(5, 10); // Printing cropped bufferconsole.log(\"Cropped buffer is: \" + cropped_buf); // Modifying cropped buffercropped_buf[0] = 70; // Fcropped_buf[1] = 79; // Ocropped_buf[2] = 82; // R // Printing cropped bufferconsole.log(\"Cropped buffer after modification is: \" + cropped_buf); // Printing original bufferconsole.log(\"Original buffer after modification is: \" + buf);", "e": 1824, "s": 1145, "text": null }, { "code": null, "e": 1834, "s": 1824, "text": "Output: " }, { "code": null, "e": 1990, "s": 1834, "text": "Original buffer is: GeeksforGeeks\nCropped buffer is: forGe\nCropped buffer after modification is: FORGe\nOriginal buffer after modification is: GeeksFORGeeks" }, { "code": null, "e": 2003, "s": 1990, "text": "Example 2: " }, { "code": null, "e": 2014, "s": 2003, "text": "javascript" }, { "code": "// Node.js program to demonstrate the // Buffer.subarray() method // Allocating bufferconst buf = Buffer.from('GeeksforGeeks', 'ascii'); // Printing original bufferconsole.log(\"Original buffer is: \" + buf); // Cropping buffer, here starting index// is -10 and ending index is -1cropped_buf = buf.subarray(-12, -1); // Printing cropped bufferconsole.log(\"Cropped buffer is:\" + cropped_buf); // Cropping buffer again, here starting// index is -10 and ending index is -5cropped_buf = buf.subarray(-10, -5); // Printing cropped bufferconsole.log(\"Cropped buffer is: \" + cropped_buf); // Cropping buffer again with no parametercropped_buf = buf.subarray(); // Printing cropped bufferconsole.log(\"Cropped buffer is: \" + cropped_buf);", "e": 2746, "s": 2014, "text": null }, { "code": null, "e": 2756, "s": 2746, "text": "Output: " }, { "code": null, "e": 2878, "s": 2756, "text": "Original buffer is: GeeksforGeeks\nCropped buffer is:eeksforGeek\nCropped buffer is: ksfor\nCropped buffer is: GeeksforGeeks" }, { "code": null, "e": 3035, "s": 2878, "text": "Note: The above program will compile and run by using the node index.js command.Reference: https://nodejs.org/api/buffer.html#buffer_buf_subarray_start_end " }, { "code": null, "e": 3051, "s": 3035, "text": "simranarora5sos" }, { "code": null, "e": 3073, "s": 3051, "text": "Node.js-Buffer-module" }, { "code": null, "e": 3081, "s": 3073, "text": "Node.js" }, { "code": null, "e": 3098, "s": 3081, "text": "Web Technologies" } ]
Python – Spelling checker using Enchant
23 Jun, 2021 Enchant is a module in Python, which is used to check the spelling of a word, gives suggestions to correct words. Also, gives antonym and synonym of words. It checks whether a word exists in the dictionary or not. Enchant can also be used to check the spelling of words. The check() method returns True if the passed word is present in the language dictionary, else it returns False. This functionality of the check() method can be used to spell check words. The suggest() method is used to suggest the correct spelling of the incorrectly spelled word. Python3 # import the enchant moduleimport enchant # create dictionary for the language# in use(en_US here)dict = enchant.Dict("en_US") # list of wordswords = ["cmputr", "watr", "study", "wrte"] # find those words that may be misspelledmisspelled =[]for word in words: if dict.check(word) == False: misspelled.append(word)print("The misspelled words are : " + str(misspelled)) # suggest the correct spelling of# the misspelled wordsfor word in misspelled: print("Suggestion for " + word + " : " + str(dict.suggest(word))) Output : The misspelled words are : ['cmputr', 'watr', 'wrte'] Suggestion for cmputr : ['computer'] Suggestion for watr : ['wart', 'watt', 'wat', 'war', 'water', 'wat r'] Suggestion for wrte : ['rte', 'write', 'wrote', 'wert', 'wite', 'w rte'] ysachin2314 arorakashish0911 Python Enchant-module Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Python Dictionary Different ways to create Pandas Dataframe Read a file line by line in Python Python String | replace() How to Install PIP on Windows ? *args and **kwargs in Python Python Classes and Objects Python OOPs Concepts Convert integer to string in Python Introduction To PYTHON
[ { "code": null, "e": 28, "s": 0, "text": "\n23 Jun, 2021" }, { "code": null, "e": 242, "s": 28, "text": "Enchant is a module in Python, which is used to check the spelling of a word, gives suggestions to correct words. Also, gives antonym and synonym of words. It checks whether a word exists in the dictionary or not." }, { "code": null, "e": 487, "s": 242, "text": "Enchant can also be used to check the spelling of words. The check() method returns True if the passed word is present in the language dictionary, else it returns False. This functionality of the check() method can be used to spell check words." }, { "code": null, "e": 583, "s": 487, "text": "The suggest() method is used to suggest the correct spelling of the incorrectly spelled word. " }, { "code": null, "e": 591, "s": 583, "text": "Python3" }, { "code": "# import the enchant moduleimport enchant # create dictionary for the language# in use(en_US here)dict = enchant.Dict(\"en_US\") # list of wordswords = [\"cmputr\", \"watr\", \"study\", \"wrte\"] # find those words that may be misspelledmisspelled =[]for word in words: if dict.check(word) == False: misspelled.append(word)print(\"The misspelled words are : \" + str(misspelled)) # suggest the correct spelling of# the misspelled wordsfor word in misspelled: print(\"Suggestion for \" + word + \" : \" + str(dict.suggest(word)))", "e": 1117, "s": 591, "text": null }, { "code": null, "e": 1128, "s": 1117, "text": "Output : " }, { "code": null, "e": 1363, "s": 1128, "text": "The misspelled words are : ['cmputr', 'watr', 'wrte']\nSuggestion for cmputr : ['computer']\nSuggestion for watr : ['wart', 'watt', 'wat', 'war', 'water', 'wat r']\nSuggestion for wrte : ['rte', 'write', 'wrote', 'wert', 'wite', 'w rte']" }, { "code": null, "e": 1377, "s": 1365, "text": "ysachin2314" }, { "code": null, "e": 1394, "s": 1377, "text": "arorakashish0911" }, { "code": null, "e": 1416, "s": 1394, "text": "Python Enchant-module" }, { "code": null, "e": 1423, "s": 1416, "text": "Python" }, { "code": null, "e": 1521, "s": 1423, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 1539, "s": 1521, "text": "Python Dictionary" }, { "code": null, "e": 1581, "s": 1539, "text": "Different ways to create Pandas Dataframe" }, { "code": null, "e": 1616, "s": 1581, "text": "Read a file line by line in Python" }, { "code": null, "e": 1642, "s": 1616, "text": "Python String | replace()" }, { "code": null, "e": 1674, "s": 1642, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 1703, "s": 1674, "text": "*args and **kwargs in Python" }, { "code": null, "e": 1730, "s": 1703, "text": "Python Classes and Objects" }, { "code": null, "e": 1751, "s": 1730, "text": "Python OOPs Concepts" }, { "code": null, "e": 1787, "s": 1751, "text": "Convert integer to string in Python" } ]
std::min_element in C++
24 Jul, 2017 For calculating the smallest of all the elements in a given list, we have std::min, but what if we want to find the smallest not in the whole list, but in a sub-section of the list. To serve this purpose, we have std::min_element in C++. std::min_element is defined inside the header file <algorithm> and it returns an iterator pointing to the element with the smallest value in the range [first, last). Unlike std::min, which can be used in three ways, std::min_element can be used in two ways. The comparisons can be performed using either operator < (first version), or using a pre-defined function (second version). If more than one element satisfies the condition of being the smallest, the iterator returned points to the first of such elements.The two versions are defined as given below: For comparing elements using “<":Syntax:template ForwardIterator min_element (ForwardIterator first, ForwardIterator last); first: Forward iterator pointing to the beginning of the range. last: Forward iterator pointing to the end of the range. Return Value: It return a pointer to the smallest element in the range, and in case if there are more than one such element, then it points to the first one. It points to the last in case the range is empty. // C++ program to demonstrate the use of std::min_element#include <iostream>#include <algorithm>using namespace std;int main(){ int v[] = { 9, 4, 7, 2, 5, 10, 11, 12, 1, 3, 6 }; // Finding the minimum value between the third and the // fifth element int* i1; i1 = std::min_element(v + 2, v + 5); cout << *i1 << "\n"; return 0;}Output:2 For comparison based on a pre-defined function:Syntax:template ForwardIterator min_element (ForwardIterator first, ForwardIterator last, Compare comp); Here, first and last are the same as previous case. comp: Binary function that accepts two elements in the range as arguments, and returns a value convertible to bool. The value returned indicates whether the element passed as first argument is considered less than the second. The function shall not modify any of its arguments. This can either be a function pointer or a function object. Return Value: It return a pointer to the smallest element in the range, and in case if there are more than one such element, then it points to the first one. It points to the last in case the range is empty. // C++ program to demonstrate the use of std::min_element#include <iostream>#include <algorithm>using namespace std; // Defining the BinaryFunctionbool comp(int a, int b){ return (a < b);} int main(){ int v[] = { 9, 4, 7, 2, 5, 10, 11, 12, 1, 3, 6 }; // Finding the minimum value between the third and the // ninth element int* i1; i1 = std::min_element(v + 2, v + 9, comp); cout << *i1 << "\n"; return 0;}Output:1 For comparing elements using “<":Syntax:template ForwardIterator min_element (ForwardIterator first, ForwardIterator last); first: Forward iterator pointing to the beginning of the range. last: Forward iterator pointing to the end of the range. Return Value: It return a pointer to the smallest element in the range, and in case if there are more than one such element, then it points to the first one. It points to the last in case the range is empty. // C++ program to demonstrate the use of std::min_element#include <iostream>#include <algorithm>using namespace std;int main(){ int v[] = { 9, 4, 7, 2, 5, 10, 11, 12, 1, 3, 6 }; // Finding the minimum value between the third and the // fifth element int* i1; i1 = std::min_element(v + 2, v + 5); cout << *i1 << "\n"; return 0;}Output:2 template ForwardIterator min_element (ForwardIterator first, ForwardIterator last); first: Forward iterator pointing to the beginning of the range. last: Forward iterator pointing to the end of the range. Return Value: It return a pointer to the smallest element in the range, and in case if there are more than one such element, then it points to the first one. It points to the last in case the range is empty. // C++ program to demonstrate the use of std::min_element#include <iostream>#include <algorithm>using namespace std;int main(){ int v[] = { 9, 4, 7, 2, 5, 10, 11, 12, 1, 3, 6 }; // Finding the minimum value between the third and the // fifth element int* i1; i1 = std::min_element(v + 2, v + 5); cout << *i1 << "\n"; return 0;} Output: 2 For comparison based on a pre-defined function:Syntax:template ForwardIterator min_element (ForwardIterator first, ForwardIterator last, Compare comp); Here, first and last are the same as previous case. comp: Binary function that accepts two elements in the range as arguments, and returns a value convertible to bool. The value returned indicates whether the element passed as first argument is considered less than the second. The function shall not modify any of its arguments. This can either be a function pointer or a function object. Return Value: It return a pointer to the smallest element in the range, and in case if there are more than one such element, then it points to the first one. It points to the last in case the range is empty. // C++ program to demonstrate the use of std::min_element#include <iostream>#include <algorithm>using namespace std; // Defining the BinaryFunctionbool comp(int a, int b){ return (a < b);} int main(){ int v[] = { 9, 4, 7, 2, 5, 10, 11, 12, 1, 3, 6 }; // Finding the minimum value between the third and the // ninth element int* i1; i1 = std::min_element(v + 2, v + 9, comp); cout << *i1 << "\n"; return 0;}Output:1 Syntax: template ForwardIterator min_element (ForwardIterator first, ForwardIterator last, Compare comp); Here, first and last are the same as previous case. comp: Binary function that accepts two elements in the range as arguments, and returns a value convertible to bool. The value returned indicates whether the element passed as first argument is considered less than the second. The function shall not modify any of its arguments. This can either be a function pointer or a function object. Return Value: It return a pointer to the smallest element in the range, and in case if there are more than one such element, then it points to the first one. It points to the last in case the range is empty. // C++ program to demonstrate the use of std::min_element#include <iostream>#include <algorithm>using namespace std; // Defining the BinaryFunctionbool comp(int a, int b){ return (a < b);} int main(){ int v[] = { 9, 4, 7, 2, 5, 10, 11, 12, 1, 3, 6 }; // Finding the minimum value between the third and the // ninth element int* i1; i1 = std::min_element(v + 2, v + 9, comp); cout << *i1 << "\n"; return 0;} Output: 1 Related Articles: std::max_element std::max std::min std::equal This article is contributed by Mrigendra Singh. 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. cpp-algorithm-library STL C++ STL CPP Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 54, "s": 26, "text": "\n24 Jul, 2017" }, { "code": null, "e": 292, "s": 54, "text": "For calculating the smallest of all the elements in a given list, we have std::min, but what if we want to find the smallest not in the whole list, but in a sub-section of the list. To serve this purpose, we have std::min_element in C++." }, { "code": null, "e": 458, "s": 292, "text": "std::min_element is defined inside the header file <algorithm> and it returns an iterator pointing to the element with the smallest value in the range [first, last)." }, { "code": null, "e": 850, "s": 458, "text": "Unlike std::min, which can be used in three ways, std::min_element can be used in two ways. The comparisons can be performed using either operator < (first version), or using a pre-defined function (second version). If more than one element satisfies the condition of being the smallest, the iterator returned points to the first of such elements.The two versions are defined as given below:" }, { "code": null, "e": 2902, "s": 850, "text": "For comparing elements using “<\":Syntax:template \nForwardIterator min_element (ForwardIterator first, ForwardIterator last);\n\nfirst: Forward iterator pointing to the beginning of the range.\nlast: Forward iterator pointing to the end of the range.\n\nReturn Value: It return a pointer to the smallest \nelement in the range, and in case if there are more than one such element,\nthen it points to the first one.\nIt points to the last in case the range is empty.\n// C++ program to demonstrate the use of std::min_element#include <iostream>#include <algorithm>using namespace std;int main(){ int v[] = { 9, 4, 7, 2, 5, 10, 11, 12, 1, 3, 6 }; // Finding the minimum value between the third and the // fifth element int* i1; i1 = std::min_element(v + 2, v + 5); cout << *i1 << \"\\n\"; return 0;}Output:2\nFor comparison based on a pre-defined function:Syntax:template \nForwardIterator min_element (ForwardIterator first, ForwardIterator last,\n Compare comp);\nHere, first and last are the same as previous case.\ncomp: Binary function that accepts two elements \nin the range as arguments, and returns a value convertible to bool.\nThe value returned indicates whether the element passed as first \nargument is considered less than the second.\nThe function shall not modify any of its arguments.\nThis can either be a function pointer or a function object.\n\nReturn Value: It return a pointer to the smallest element \nin the range, and in case if there are more than one such element,\nthen it points to the first one.\nIt points to the last in case the range is empty.\n// C++ program to demonstrate the use of std::min_element#include <iostream>#include <algorithm>using namespace std; // Defining the BinaryFunctionbool comp(int a, int b){ return (a < b);} int main(){ int v[] = { 9, 4, 7, 2, 5, 10, 11, 12, 1, 3, 6 }; // Finding the minimum value between the third and the // ninth element int* i1; i1 = std::min_element(v + 2, v + 9, comp); cout << *i1 << \"\\n\"; return 0;}Output:1\n" }, { "code": null, "e": 3723, "s": 2902, "text": "For comparing elements using “<\":Syntax:template \nForwardIterator min_element (ForwardIterator first, ForwardIterator last);\n\nfirst: Forward iterator pointing to the beginning of the range.\nlast: Forward iterator pointing to the end of the range.\n\nReturn Value: It return a pointer to the smallest \nelement in the range, and in case if there are more than one such element,\nthen it points to the first one.\nIt points to the last in case the range is empty.\n// C++ program to demonstrate the use of std::min_element#include <iostream>#include <algorithm>using namespace std;int main(){ int v[] = { 9, 4, 7, 2, 5, 10, 11, 12, 1, 3, 6 }; // Finding the minimum value between the third and the // fifth element int* i1; i1 = std::min_element(v + 2, v + 5); cout << *i1 << \"\\n\"; return 0;}Output:2\n" }, { "code": null, "e": 4141, "s": 3723, "text": "template \nForwardIterator min_element (ForwardIterator first, ForwardIterator last);\n\nfirst: Forward iterator pointing to the beginning of the range.\nlast: Forward iterator pointing to the end of the range.\n\nReturn Value: It return a pointer to the smallest \nelement in the range, and in case if there are more than one such element,\nthen it points to the first one.\nIt points to the last in case the range is empty.\n" }, { "code": "// C++ program to demonstrate the use of std::min_element#include <iostream>#include <algorithm>using namespace std;int main(){ int v[] = { 9, 4, 7, 2, 5, 10, 11, 12, 1, 3, 6 }; // Finding the minimum value between the third and the // fifth element int* i1; i1 = std::min_element(v + 2, v + 5); cout << *i1 << \"\\n\"; return 0;}", "e": 4496, "s": 4141, "text": null }, { "code": null, "e": 4504, "s": 4496, "text": "Output:" }, { "code": null, "e": 4507, "s": 4504, "text": "2\n" }, { "code": null, "e": 5739, "s": 4507, "text": "For comparison based on a pre-defined function:Syntax:template \nForwardIterator min_element (ForwardIterator first, ForwardIterator last,\n Compare comp);\nHere, first and last are the same as previous case.\ncomp: Binary function that accepts two elements \nin the range as arguments, and returns a value convertible to bool.\nThe value returned indicates whether the element passed as first \nargument is considered less than the second.\nThe function shall not modify any of its arguments.\nThis can either be a function pointer or a function object.\n\nReturn Value: It return a pointer to the smallest element \nin the range, and in case if there are more than one such element,\nthen it points to the first one.\nIt points to the last in case the range is empty.\n// C++ program to demonstrate the use of std::min_element#include <iostream>#include <algorithm>using namespace std; // Defining the BinaryFunctionbool comp(int a, int b){ return (a < b);} int main(){ int v[] = { 9, 4, 7, 2, 5, 10, 11, 12, 1, 3, 6 }; // Finding the minimum value between the third and the // ninth element int* i1; i1 = std::min_element(v + 2, v + 9, comp); cout << *i1 << \"\\n\"; return 0;}Output:1\n" }, { "code": null, "e": 5747, "s": 5739, "text": "Syntax:" }, { "code": null, "e": 6478, "s": 5747, "text": "template \nForwardIterator min_element (ForwardIterator first, ForwardIterator last,\n Compare comp);\nHere, first and last are the same as previous case.\ncomp: Binary function that accepts two elements \nin the range as arguments, and returns a value convertible to bool.\nThe value returned indicates whether the element passed as first \nargument is considered less than the second.\nThe function shall not modify any of its arguments.\nThis can either be a function pointer or a function object.\n\nReturn Value: It return a pointer to the smallest element \nin the range, and in case if there are more than one such element,\nthen it points to the first one.\nIt points to the last in case the range is empty.\n" }, { "code": "// C++ program to demonstrate the use of std::min_element#include <iostream>#include <algorithm>using namespace std; // Defining the BinaryFunctionbool comp(int a, int b){ return (a < b);} int main(){ int v[] = { 9, 4, 7, 2, 5, 10, 11, 12, 1, 3, 6 }; // Finding the minimum value between the third and the // ninth element int* i1; i1 = std::min_element(v + 2, v + 9, comp); cout << *i1 << \"\\n\"; return 0;}", "e": 6917, "s": 6478, "text": null }, { "code": null, "e": 6925, "s": 6917, "text": "Output:" }, { "code": null, "e": 6928, "s": 6925, "text": "1\n" }, { "code": null, "e": 6946, "s": 6928, "text": "Related Articles:" }, { "code": null, "e": 6963, "s": 6946, "text": "std::max_element" }, { "code": null, "e": 6972, "s": 6963, "text": "std::max" }, { "code": null, "e": 6981, "s": 6972, "text": "std::min" }, { "code": null, "e": 6992, "s": 6981, "text": "std::equal" }, { "code": null, "e": 7295, "s": 6992, "text": "This article is contributed by Mrigendra Singh. 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": 7420, "s": 7295, "text": "Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above." }, { "code": null, "e": 7442, "s": 7420, "text": "cpp-algorithm-library" }, { "code": null, "e": 7446, "s": 7442, "text": "STL" }, { "code": null, "e": 7450, "s": 7446, "text": "C++" }, { "code": null, "e": 7454, "s": 7450, "text": "STL" }, { "code": null, "e": 7458, "s": 7454, "text": "CPP" } ]
Program for Simpson’s 1/3 Rule
18 Aug, 2021 In numerical analysis, Simpson’s 1/3 rule is a method for numerical approximation of definite integrals. Specifically, it is the following approximation: In Simpson’s 1/3 Rule, we use parabolas to approximate each part of the curve.We divide the area into n equal segments of width Δx. Simpson’s rule can be derived by approximating the integrand f (x) (in blue) by the quadratic interpolant P(x) (in red). In order to integrate any function f(x) in the interval (a, b), follow the steps given below:1.Select a value for n, which is the number of parts the interval is divided into. 2.Calculate the width, h = (b-a)/n 3.Calculate the values of x0 to xn as x0 = a, x1 = x0 + h, .....xn-1 = xn-2 + h, xn = b. Consider y = f(x). Now find the values of y(y0 to yn) for the corresponding x(x0 to xn) values. 4.Substitute all the above found values in the Simpson’s Rule Formula to calculate the integral value.Approximate value of the integral can be given by Simpson’s Rule: Note : In this rule, n must be EVEN.Application : It is used when it is very difficult to solve the given integral mathematically. This rule gives approximation easily without actually knowing the integration rules.Example : Evaluate logx dx within limit 4 to 5.2. First we will divide interval into six equal parts as number of interval should be even. x : 4 4.2 4.4 4.6 4.8 5.0 5.2 logx : 1.38 1.43 1.48 1.52 1.56 1.60 1.64 Now we can calculate approximate value of integral using above formula: = h/3[( 1.38 + 1.64) + 4 * (1.43 + 1.52 + 1.60 ) +2 *(1.48 + 1.56)] = 1.84 Hence the approximation of above integral is 1.827 using Simpson's 1/3 rule. C++ Java Python3 C# PHP Javascript // CPP program for simpson's 1/3 rule#include <iostream>#include <math.h>using namespace std; // Function to calculate f(x)float func(float x){ return log(x);} // Function for approximate integralfloat simpsons_(float ll, float ul, int n){ // Calculating the value of h float h = (ul - ll) / n; // Array for storing value of x and f(x) float x[10], fx[10]; // Calculating values of x and f(x) for (int i = 0; i <= n; i++) { x[i] = ll + i * h; fx[i] = func(x[i]); } // Calculating result float res = 0; for (int i = 0; i <= n; i++) { if (i == 0 || i == n) res += fx[i]; else if (i % 2 != 0) res += 4 * fx[i]; else res += 2 * fx[i]; } res = res * (h / 3); return res;} // Driver programint main(){ float lower_limit = 4; // Lower limit float upper_limit = 5.2; // Upper limit int n = 6; // Number of interval cout << simpsons_(lower_limit, upper_limit, n); return 0;} // Java program for simpson's 1/3 rule public class GfG{ // Function to calculate f(x) static float func(float x) { return (float)Math.log(x); } // Function for approximate integral static float simpsons_(float ll, float ul, int n) { // Calculating the value of h float h = (ul - ll) / n; // Array for storing value of x // and f(x) float[] x = new float[10]; float[] fx= new float[10]; // Calculating values of x and f(x) for (int i = 0; i <= n; i++) { x[i] = ll + i * h; fx[i] = func(x[i]); } // Calculating result float res = 0; for (int i = 0; i <= n; i++) { if (i == 0 || i == n) res += fx[i]; else if (i % 2 != 0) res += 4 * fx[i]; else res += 2 * fx[i]; } res = res * (h / 3); return res; } // Driver Code public static void main(String s[]) { // Lower limit float lower_limit = 4; // Upper limit float upper_limit = (float)5.2; // Number of interval int n = 6; System.out.println(simpsons_(lower_limit, upper_limit, n)); }} // This code is contributed by Gitanjali # Python code for simpson's 1 / 3 ruleimport math # Function to calculate f(x)def func( x ): return math.log(x) # Function for approximate integraldef simpsons_( ll, ul, n ): # Calculating the value of h h = ( ul - ll )/n # List for storing value of x and f(x) x = list() fx = list() # Calculating values of x and f(x) i = 0 while i<= n: x.append(ll + i * h) fx.append(func(x[i])) i += 1 # Calculating result res = 0 i = 0 while i<= n: if i == 0 or i == n: res+= fx[i] elif i % 2 != 0: res+= 4 * fx[i] else: res+= 2 * fx[i] i+= 1 res = res * (h / 3) return res # Driver codelower_limit = 4 # Lower limitupper_limit = 5.2 # Upper limitn = 6 # Number of intervalprint("%.6f"% simpsons_(lower_limit, upper_limit, n)) // C# program for simpson's 1/3 ruleusing System; public class GfG{ // Function to calculate f(x) static float func(float x) { return (float)Math.Log(x); } // Function for approximate integral static float simpsons_(float ll, float ul, int n) { // Calculating the value of h float h = (ul - ll) / n; // Array for storing value of x // and f(x) float[] x = new float[10]; float[] fx= new float[10]; // Calculating values of x and f(x) for (int i = 0; i <= n; i++) { x[i] = ll + i * h; fx[i] = func(x[i]); } // Calculating result float res = 0; for (int i = 0; i <= n; i++) { if (i == 0 || i == n) res += fx[i]; else if (i % 2 != 0) res += 4 * fx[i]; else res += 2 * fx[i]; } res = res * (h / 3); return res; } // Driver Code public static void Main() { // Lower limit float lower_limit = 4; // Upper limit float upper_limit = (float)5.2; // Number of interval int n = 6; Console.WriteLine(simpsons_(lower_limit, upper_limit, n)); }} // This code is contributed by vt_m <?php// PhP program for simpson's 1/3 rule // Function to calculate f(x)function func($x){ return log($x);} // Function for approximate integralfunction simpsons_($ll, $ul, $n){ // Calculating the value of h $h = ($ul - $ll) / $n; // Calculating values of x and f(x) for ($i = 0; $i <= $n; $i++) { $x[$i] = $ll + $i * $h; $fx[$i] = func($x[$i]); } // Calculating result $res = 0; for ($i = 0; $i <= $n; $i++) { if ($i == 0 || $i == $n) $res += $fx[$i]; else if ($i % 2 != 0) $res += 4 * $fx[$i]; else $res += 2 * $fx[$i]; } $res = $res * ($h / 3); return $res;} // Driver program $lower_limit = 4; // Lower limit $upper_limit = 5.2; // Upper limit $n = 6; // Number of interval echo simpsons_($lower_limit, $upper_limit, $n); // This code is contributed by ajit.?> <script> // JavaScriptprogram for simpson's 1/3 rule // Function to calculate f(x) function func(x) { return Math.log(x); } // Function for approximate integral function simpsons_(ll, ul, n) { // Calculating the value of h let h = (ul - ll) / n; // Array for storing value of x // and f(x) let x = []; let fx= []; // Calculating values of x and f(x) for (let i = 0; i <= n; i++) { x[i] = ll + i * h; fx[i] = func(x[i]); } // Calculating result let res = 0; for (let i = 0; i <= n; i++) { if (i == 0 || i == n) res += fx[i]; else if (i % 2 != 0) res += 4 * fx[i]; else res += 2 * fx[i]; } res = res * (h / 3); return res; } // Driver code // Lower limit let lower_limit = 4; // Upper limit let upper_limit = 5.2; // Number of interval let n = 6; document.write(simpsons_(lower_limit, upper_limit, n)); // This code is contributed by code_hunt.</script> Output: 1.827847 jit_t code_hunt sweetyty Algebra 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++ Prime Numbers Find minimum number of coins that make a given value Algorithm to solve Rubik's Cube Minimum number of jumps to reach end Modulo 10^9+7 (1000000007) Modulo Operator (%) in C/C++ with Examples The Knight's tour problem | Backtracking-1 Program for Decimal to Binary Conversion
[ { "code": null, "e": 52, "s": 24, "text": "\n18 Aug, 2021" }, { "code": null, "e": 207, "s": 52, "text": "In numerical analysis, Simpson’s 1/3 rule is a method for numerical approximation of definite integrals. Specifically, it is the following approximation: " }, { "code": null, "e": 467, "s": 212, "text": "In Simpson’s 1/3 Rule, we use parabolas to approximate each part of the curve.We divide the area into n equal segments of width Δx. Simpson’s rule can be derived by approximating the integrand f (x) (in blue) by the quadratic interpolant P(x) (in red). " }, { "code": null, "e": 1032, "s": 467, "text": "In order to integrate any function f(x) in the interval (a, b), follow the steps given below:1.Select a value for n, which is the number of parts the interval is divided into. 2.Calculate the width, h = (b-a)/n 3.Calculate the values of x0 to xn as x0 = a, x1 = x0 + h, .....xn-1 = xn-2 + h, xn = b. Consider y = f(x). Now find the values of y(y0 to yn) for the corresponding x(x0 to xn) values. 4.Substitute all the above found values in the Simpson’s Rule Formula to calculate the integral value.Approximate value of the integral can be given by Simpson’s Rule: " }, { "code": null, "e": 1264, "s": 1037, "text": "Note : In this rule, n must be EVEN.Application : It is used when it is very difficult to solve the given integral mathematically. This rule gives approximation easily without actually knowing the integration rules.Example : " }, { "code": null, "e": 1761, "s": 1264, "text": "Evaluate logx dx within limit 4 to 5.2.\n\nFirst we will divide interval into six equal \nparts as number of interval should be even.\n\nx : 4 4.2 4.4 4.6 4.8 5.0 5.2\nlogx : 1.38 1.43 1.48 1.52 1.56 1.60 1.64\n\nNow we can calculate approximate value of integral\nusing above formula:\n = h/3[( 1.38 + 1.64) + 4 * (1.43 + 1.52 + \n 1.60 ) +2 *(1.48 + 1.56)]\n = 1.84\nHence the approximation of above integral is \n1.827 using Simpson's 1/3 rule. \n " }, { "code": null, "e": 1767, "s": 1763, "text": "C++" }, { "code": null, "e": 1772, "s": 1767, "text": "Java" }, { "code": null, "e": 1780, "s": 1772, "text": "Python3" }, { "code": null, "e": 1783, "s": 1780, "text": "C#" }, { "code": null, "e": 1787, "s": 1783, "text": "PHP" }, { "code": null, "e": 1798, "s": 1787, "text": "Javascript" }, { "code": "// CPP program for simpson's 1/3 rule#include <iostream>#include <math.h>using namespace std; // Function to calculate f(x)float func(float x){ return log(x);} // Function for approximate integralfloat simpsons_(float ll, float ul, int n){ // Calculating the value of h float h = (ul - ll) / n; // Array for storing value of x and f(x) float x[10], fx[10]; // Calculating values of x and f(x) for (int i = 0; i <= n; i++) { x[i] = ll + i * h; fx[i] = func(x[i]); } // Calculating result float res = 0; for (int i = 0; i <= n; i++) { if (i == 0 || i == n) res += fx[i]; else if (i % 2 != 0) res += 4 * fx[i]; else res += 2 * fx[i]; } res = res * (h / 3); return res;} // Driver programint main(){ float lower_limit = 4; // Lower limit float upper_limit = 5.2; // Upper limit int n = 6; // Number of interval cout << simpsons_(lower_limit, upper_limit, n); return 0;}", "e": 2792, "s": 1798, "text": null }, { "code": "// Java program for simpson's 1/3 rule public class GfG{ // Function to calculate f(x) static float func(float x) { return (float)Math.log(x); } // Function for approximate integral static float simpsons_(float ll, float ul, int n) { // Calculating the value of h float h = (ul - ll) / n; // Array for storing value of x // and f(x) float[] x = new float[10]; float[] fx= new float[10]; // Calculating values of x and f(x) for (int i = 0; i <= n; i++) { x[i] = ll + i * h; fx[i] = func(x[i]); } // Calculating result float res = 0; for (int i = 0; i <= n; i++) { if (i == 0 || i == n) res += fx[i]; else if (i % 2 != 0) res += 4 * fx[i]; else res += 2 * fx[i]; } res = res * (h / 3); return res; } // Driver Code public static void main(String s[]) { // Lower limit float lower_limit = 4; // Upper limit float upper_limit = (float)5.2; // Number of interval int n = 6; System.out.println(simpsons_(lower_limit, upper_limit, n)); }} // This code is contributed by Gitanjali", "e": 4175, "s": 2792, "text": null }, { "code": "# Python code for simpson's 1 / 3 ruleimport math # Function to calculate f(x)def func( x ): return math.log(x) # Function for approximate integraldef simpsons_( ll, ul, n ): # Calculating the value of h h = ( ul - ll )/n # List for storing value of x and f(x) x = list() fx = list() # Calculating values of x and f(x) i = 0 while i<= n: x.append(ll + i * h) fx.append(func(x[i])) i += 1 # Calculating result res = 0 i = 0 while i<= n: if i == 0 or i == n: res+= fx[i] elif i % 2 != 0: res+= 4 * fx[i] else: res+= 2 * fx[i] i+= 1 res = res * (h / 3) return res # Driver codelower_limit = 4 # Lower limitupper_limit = 5.2 # Upper limitn = 6 # Number of intervalprint(\"%.6f\"% simpsons_(lower_limit, upper_limit, n))", "e": 5030, "s": 4175, "text": null }, { "code": "// C# program for simpson's 1/3 ruleusing System; public class GfG{ // Function to calculate f(x) static float func(float x) { return (float)Math.Log(x); } // Function for approximate integral static float simpsons_(float ll, float ul, int n) { // Calculating the value of h float h = (ul - ll) / n; // Array for storing value of x // and f(x) float[] x = new float[10]; float[] fx= new float[10]; // Calculating values of x and f(x) for (int i = 0; i <= n; i++) { x[i] = ll + i * h; fx[i] = func(x[i]); } // Calculating result float res = 0; for (int i = 0; i <= n; i++) { if (i == 0 || i == n) res += fx[i]; else if (i % 2 != 0) res += 4 * fx[i]; else res += 2 * fx[i]; } res = res * (h / 3); return res; } // Driver Code public static void Main() { // Lower limit float lower_limit = 4; // Upper limit float upper_limit = (float)5.2; // Number of interval int n = 6; Console.WriteLine(simpsons_(lower_limit, upper_limit, n)); }} // This code is contributed by vt_m", "e": 6407, "s": 5030, "text": null }, { "code": "<?php// PhP program for simpson's 1/3 rule // Function to calculate f(x)function func($x){ return log($x);} // Function for approximate integralfunction simpsons_($ll, $ul, $n){ // Calculating the value of h $h = ($ul - $ll) / $n; // Calculating values of x and f(x) for ($i = 0; $i <= $n; $i++) { $x[$i] = $ll + $i * $h; $fx[$i] = func($x[$i]); } // Calculating result $res = 0; for ($i = 0; $i <= $n; $i++) { if ($i == 0 || $i == $n) $res += $fx[$i]; else if ($i % 2 != 0) $res += 4 * $fx[$i]; else $res += 2 * $fx[$i]; } $res = $res * ($h / 3); return $res;} // Driver program $lower_limit = 4; // Lower limit $upper_limit = 5.2; // Upper limit $n = 6; // Number of interval echo simpsons_($lower_limit, $upper_limit, $n); // This code is contributed by ajit.?>", "e": 7315, "s": 6407, "text": null }, { "code": "<script> // JavaScriptprogram for simpson's 1/3 rule // Function to calculate f(x) function func(x) { return Math.log(x); } // Function for approximate integral function simpsons_(ll, ul, n) { // Calculating the value of h let h = (ul - ll) / n; // Array for storing value of x // and f(x) let x = []; let fx= []; // Calculating values of x and f(x) for (let i = 0; i <= n; i++) { x[i] = ll + i * h; fx[i] = func(x[i]); } // Calculating result let res = 0; for (let i = 0; i <= n; i++) { if (i == 0 || i == n) res += fx[i]; else if (i % 2 != 0) res += 4 * fx[i]; else res += 2 * fx[i]; } res = res * (h / 3); return res; } // Driver code // Lower limit let lower_limit = 4; // Upper limit let upper_limit = 5.2; // Number of interval let n = 6; document.write(simpsons_(lower_limit, upper_limit, n)); // This code is contributed by code_hunt.</script>", "e": 8586, "s": 7315, "text": null }, { "code": null, "e": 8596, "s": 8586, "text": "Output: " }, { "code": null, "e": 8605, "s": 8596, "text": "1.827847" }, { "code": null, "e": 8613, "s": 8607, "text": "jit_t" }, { "code": null, "e": 8623, "s": 8613, "text": "code_hunt" }, { "code": null, "e": 8632, "s": 8623, "text": "sweetyty" }, { "code": null, "e": 8640, "s": 8632, "text": "Algebra" }, { "code": null, "e": 8653, "s": 8640, "text": "Mathematical" }, { "code": null, "e": 8666, "s": 8653, "text": "Mathematical" }, { "code": null, "e": 8764, "s": 8666, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 8788, "s": 8764, "text": "Merge two sorted arrays" }, { "code": null, "e": 8809, "s": 8788, "text": "Operators in C / C++" }, { "code": null, "e": 8823, "s": 8809, "text": "Prime Numbers" }, { "code": null, "e": 8876, "s": 8823, "text": "Find minimum number of coins that make a given value" }, { "code": null, "e": 8908, "s": 8876, "text": "Algorithm to solve Rubik's Cube" }, { "code": null, "e": 8945, "s": 8908, "text": "Minimum number of jumps to reach end" }, { "code": null, "e": 8972, "s": 8945, "text": "Modulo 10^9+7 (1000000007)" }, { "code": null, "e": 9015, "s": 8972, "text": "Modulo Operator (%) in C/C++ with Examples" }, { "code": null, "e": 9058, "s": 9015, "text": "The Knight's tour problem | Backtracking-1" } ]
What is the max size of localStorage values?
28 Jan, 2022 Currently localStorage only supports strings as values, and the objects need to be converted to JSON strings before they are stored in the localStorage. Data stored using local storage isn’t sent back to the server (unlike cookies, ). All the data stays on the client-side, thus there is a defined limitation regarding the length of the values, and we can currently store from 2 MB to 10 MB size of data depending upon the browser we use. Syntax: localStorage.setItem ( 'abc', 10 ); // this integer 10 gets converted to a string "10" // and then stored in localStorage variable named "abc". Code: This code is to calculate the size of localStorage variable. javascript <!DOCTYPE html><html><head><title>Page Title</title> <script> //this script is to find the size of localStorage function func1(num) { return new Array((num * 1024) + 1).join('a') } // Determine the size of localStorage if it's not set if (!localStorage.getItem('size')) { var i = 0; try { // Test up to 10 MB for (i = 0; i <= 10000; i += 250) { localStorage.setItem('test', func1(i)); } } catch (e) { localStorage.removeItem('test'); localStorage.setItem('size', i ? i - 250 : 0); } } // when window is loaded this function is// called and the size of localStorage is calculated window.onload = function calculate(){ var el = document.getElementById('size'); el.innerHTML = localStorage.getItem('size');} </script></head><body><div > localStorage limit in your Browser is <span id="size">...</span> KBs.</div></body></html> Output: localStorage limit in your Browser is 5000 KBs. Explanation: This javascript code will run by adding continuously increasing length strings until the browser engine throws an exception. After this point, it will clear the test data and will set a size key in localStorage that will store the size of localStorage in kilobytes (KBs). Reference: https://www.geeksforgeeks.org/html-dom-storage-setitem-method/ adnanirshad158 HTML5 JavaScript-Misc JavaScript Web Technologies Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Difference between var, let and const keywords in JavaScript Differences between Functional Components and Class Components in React Remove elements from a JavaScript Array Difference Between PUT and PATCH Request How to append HTML code to a div using JavaScript ? Installation of Node.js on Linux Top 10 Projects For Beginners To Practice HTML and CSS Skills Difference between var, let and const keywords in JavaScript How to insert spaces/tabs in text using HTML/CSS? How to fetch data from an API in ReactJS ?
[ { "code": null, "e": 28, "s": 0, "text": "\n28 Jan, 2022" }, { "code": null, "e": 467, "s": 28, "text": "Currently localStorage only supports strings as values, and the objects need to be converted to JSON strings before they are stored in the localStorage. Data stored using local storage isn’t sent back to the server (unlike cookies, ). All the data stays on the client-side, thus there is a defined limitation regarding the length of the values, and we can currently store from 2 MB to 10 MB size of data depending upon the browser we use." }, { "code": null, "e": 475, "s": 467, "text": "Syntax:" }, { "code": null, "e": 621, "s": 475, "text": "localStorage.setItem ( 'abc', 10 ); \n// this integer 10 gets converted to a string \"10\" \n// and then stored in localStorage variable named \"abc\"." }, { "code": null, "e": 627, "s": 621, "text": "Code:" }, { "code": null, "e": 688, "s": 627, "text": "This code is to calculate the size of localStorage variable." }, { "code": null, "e": 699, "s": 688, "text": "javascript" }, { "code": "<!DOCTYPE html><html><head><title>Page Title</title> <script> //this script is to find the size of localStorage function func1(num) { return new Array((num * 1024) + 1).join('a') } // Determine the size of localStorage if it's not set if (!localStorage.getItem('size')) { var i = 0; try { // Test up to 10 MB for (i = 0; i <= 10000; i += 250) { localStorage.setItem('test', func1(i)); } } catch (e) { localStorage.removeItem('test'); localStorage.setItem('size', i ? i - 250 : 0); } } // when window is loaded this function is// called and the size of localStorage is calculated window.onload = function calculate(){ var el = document.getElementById('size'); el.innerHTML = localStorage.getItem('size');} </script></head><body><div > localStorage limit in your Browser is <span id=\"size\">...</span> KBs.</div></body></html>", "e": 1658, "s": 699, "text": null }, { "code": null, "e": 1666, "s": 1658, "text": "Output:" }, { "code": null, "e": 1714, "s": 1666, "text": "localStorage limit in your Browser is 5000 KBs." }, { "code": null, "e": 1727, "s": 1714, "text": "Explanation:" }, { "code": null, "e": 1999, "s": 1727, "text": "This javascript code will run by adding continuously increasing length strings until the browser engine throws an exception. After this point, it will clear the test data and will set a size key in localStorage that will store the size of localStorage in kilobytes (KBs)." }, { "code": null, "e": 2075, "s": 1999, "text": "Reference: https://www.geeksforgeeks.org/html-dom-storage-setitem-method/ " }, { "code": null, "e": 2090, "s": 2075, "text": "adnanirshad158" }, { "code": null, "e": 2096, "s": 2090, "text": "HTML5" }, { "code": null, "e": 2112, "s": 2096, "text": "JavaScript-Misc" }, { "code": null, "e": 2123, "s": 2112, "text": "JavaScript" }, { "code": null, "e": 2140, "s": 2123, "text": "Web Technologies" }, { "code": null, "e": 2238, "s": 2140, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 2299, "s": 2238, "text": "Difference between var, let and const keywords in JavaScript" }, { "code": null, "e": 2371, "s": 2299, "text": "Differences between Functional Components and Class Components in React" }, { "code": null, "e": 2411, "s": 2371, "text": "Remove elements from a JavaScript Array" }, { "code": null, "e": 2452, "s": 2411, "text": "Difference Between PUT and PATCH Request" }, { "code": null, "e": 2504, "s": 2452, "text": "How to append HTML code to a div using JavaScript ?" }, { "code": null, "e": 2537, "s": 2504, "text": "Installation of Node.js on Linux" }, { "code": null, "e": 2599, "s": 2537, "text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills" }, { "code": null, "e": 2660, "s": 2599, "text": "Difference between var, let and const keywords in JavaScript" }, { "code": null, "e": 2710, "s": 2660, "text": "How to insert spaces/tabs in text using HTML/CSS?" } ]
Python PIL | Kernel() method
14 Jul, 2019 PIL is the Python Imaging Library which provides the python interpreter with image editing capabilities. The ImageFilter module contains definitions for a pre-defined set of filters, which can be used with the Image.filter() method. PIL.ImageFilter.Kernel() Create a convolution kernel. The current version only supports 3×3 and 5×5 integer and floating point kernels. Syntax: PIL.ImageFilter.Kernel(size, kernel, scale=None, offset=0) Parameters:size – Kernel size, given as (width, height). In the current version, this must be (3, 3) or (5, 5).kernel – A sequence containing kernel weights.scale – Scale factor. If given, the result for each pixel is divided by this value. the default is the sum of the kernel weights.offset – Offset. If given, this value is added to the result, after it has been divided by the scale factor. Returns type: An image. Image Used: # Importing Image and ImageFilter module from PIL package from PIL import Image, ImageFilter # creating a image object im1 = Image.open(r"C:\Users\System-Pc\Desktop\leave.JPG") # applying the Kernel filterim2 = im1.filter(ImageFilter.Kernel((3, 3), (-1, -1, -1, -1, 9, -1, -1, -1, -1), 1, 0)) im2 = im2.show() Output: Another example: Here change kernel value to obtain output, we can change other parameters as well. # Importing Image and ImageFilter module from PIL package from PIL import Image, ImageFilter # Importing Image and ImageFilter module from PIL package from PIL import Image, ImageFilter # creating a image object im1 = Image.open(r"C:\Users\System-Pc\Desktop\leave.JPG") # applying the Kernel filterim2 = im1.filter(ImageFilter.Kernel((3, 3), (-1, -1, -1, -1, 11, -2, -2, -2, -2), 1, 0)) im2 = im2.show() Output: Python-pil Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n14 Jul, 2019" }, { "code": null, "e": 261, "s": 28, "text": "PIL is the Python Imaging Library which provides the python interpreter with image editing capabilities. The ImageFilter module contains definitions for a pre-defined set of filters, which can be used with the Image.filter() method." }, { "code": null, "e": 397, "s": 261, "text": "PIL.ImageFilter.Kernel() Create a convolution kernel. The current version only supports 3×3 and 5×5 integer and floating point kernels." }, { "code": null, "e": 464, "s": 397, "text": "Syntax: PIL.ImageFilter.Kernel(size, kernel, scale=None, offset=0)" }, { "code": null, "e": 859, "s": 464, "text": "Parameters:size – Kernel size, given as (width, height). In the current version, this must be (3, 3) or (5, 5).kernel – A sequence containing kernel weights.scale – Scale factor. If given, the result for each pixel is divided by this value. the default is the sum of the kernel weights.offset – Offset. If given, this value is added to the result, after it has been divided by the scale factor." }, { "code": null, "e": 883, "s": 859, "text": "Returns type: An image." }, { "code": null, "e": 895, "s": 883, "text": "Image Used:" }, { "code": " # Importing Image and ImageFilter module from PIL package from PIL import Image, ImageFilter # creating a image object im1 = Image.open(r\"C:\\Users\\System-Pc\\Desktop\\leave.JPG\") # applying the Kernel filterim2 = im1.filter(ImageFilter.Kernel((3, 3), (-1, -1, -1, -1, 9, -1, -1, -1, -1), 1, 0)) im2 = im2.show() ", "e": 1237, "s": 895, "text": null }, { "code": null, "e": 1245, "s": 1237, "text": "Output:" }, { "code": null, "e": 1345, "s": 1245, "text": "Another example: Here change kernel value to obtain output, we can change other parameters as well." }, { "code": "# Importing Image and ImageFilter module from PIL package from PIL import Image, ImageFilter # Importing Image and ImageFilter module from PIL package from PIL import Image, ImageFilter # creating a image object im1 = Image.open(r\"C:\\Users\\System-Pc\\Desktop\\leave.JPG\") # applying the Kernel filterim2 = im1.filter(ImageFilter.Kernel((3, 3), (-1, -1, -1, -1, 11, -2, -2, -2, -2), 1, 0)) im2 = im2.show() ", "e": 1782, "s": 1345, "text": null }, { "code": null, "e": 1790, "s": 1782, "text": "Output:" }, { "code": null, "e": 1801, "s": 1790, "text": "Python-pil" }, { "code": null, "e": 1808, "s": 1801, "text": "Python" } ]
How to Change Password of User in Android using Firebase?
15 Jun, 2022 In many apps, we got a feature to login using our email and password. Sometimes it happens that we forget the password and most of the time there reset our password. Here we are going to implement the same feature to Reset our password using Firebase Authentication. You may refer to the following article User authentication using Firebase in Android. A sample video is given below to get an idea about what we are going to do in this article. Note that we are going to implement this project using the Java language. Step 1: Working with the UI part Go to the activity_login.xml file and refer to the following code. Below is the code for the activity_login.xml file. XML <?xml version="1.0" encoding="utf-8"?><RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical" tools:context=".LoginActivity"> <include android:id="@+id/login_toolbar" layout="@layout/app_bar_layout" /> <TextView android:id="@+id/textView2" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_alignParentStart="true" android:layout_alignParentTop="true" android:layout_marginStart="19dp" android:layout_marginTop="96dp" android:textSize="25dp" android:text="Login to Your Account" /> <EditText android:id="@+id/logemail" android:layout_width="267dp" android:layout_height="wrap_content" android:layout_alignParentStart="true" android:layout_alignParentTop="true" android:layout_marginStart="36dp" android:layout_marginTop="198dp" android:ems="10" android:hint="Email" android:inputType="textEmailAddress" /> <EditText android:id="@+id/logpass" android:layout_width="259dp" android:layout_height="58dp" android:layout_alignParentStart="true" android:layout_alignParentTop="true" android:layout_marginStart="32dp" android:layout_marginTop="261dp" android:ems="10" android:hint="Password" android:inputType="textPassword" /> <TextView android:layout_width="match_parent" android:layout_height="wrap_content" android:id="@+id/forgetpass" android:layout_alignParentStart="true" android:layout_alignParentTop="true" android:layout_marginStart="132dp" android:layout_marginTop="351dp" android:text="Forget Password"/> <Button android:id="@+id/logbut" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_alignParentStart="true" android:layout_alignParentTop="true" android:layout_marginStart="222dp" android:layout_marginTop="387dp" android:background="@color/colorPrimary" android:text="Login" android:textSize="15dp" /> </RelativeLayout> Step 2: Working with the LoginActivity.java file 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. Go to the LoginActivity.java file and refer to the following code. Below is the code for the LoginActivity.java file Java import androidx.annotation.NonNull;import androidx.appcompat.app.AppCompatActivity;import androidx.appcompat.widget.Toolbar; import android.app.AlertDialog;import android.app.ProgressDialog;import android.content.DialogInterface;import android.content.Intent;import android.os.Bundle;import android.text.InputType;import android.text.TextUtils;import android.view.View;import android.widget.Button;import android.widget.EditText;import android.widget.LinearLayout;import android.widget.TextView;import android.widget.Toast; import com.google.android.gms.tasks.OnCompleteListener;import com.google.android.gms.tasks.OnFailureListener;import com.google.android.gms.tasks.Task;import com.google.firebase.auth.AuthResult;import com.google.firebase.auth.FirebaseAuth; public class LoginActivity extends AppCompatActivity { private EditText memail; private EditText mpass; private FirebaseAuth mAuth; private Toolbar mtoolbar; private Button login; TextView forgetpass; public ProgressDialog loginprogress; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_login); mtoolbar=(Toolbar)findViewById(R.id.login_toolbar); setSupportActionBar(mtoolbar); mAuth = FirebaseAuth.getInstance(); getSupportActionBar().setTitle("Login"); forgetpass=findViewById(R.id.forgetpass); getSupportActionBar().setDisplayHomeAsUpEnabled(true); loginprogress=new ProgressDialog(this); memail=(EditText)findViewById(R.id.logemail); mpass=(EditText)findViewById(R.id.logpass); // click on forget password text forgetpass.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { showRecoverPasswordDialog(); } }); login=(Button)findViewById(R.id.logbut); login.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { String email=memail.getText().toString(); String password =mpass.getText().toString(); if(!TextUtils.isEmpty(email)||!TextUtils.isEmpty(password)){ loginprogress.setTitle("Logging In"); loginprogress.setMessage("Please Wait "); loginprogress.setCanceledOnTouchOutside(false); loginprogress.show(); loginUser(email,password); } } }); } ProgressDialog loadingBar; private void showRecoverPasswordDialog() { AlertDialog.Builder builder=new AlertDialog.Builder(this); builder.setTitle("Recover Password"); LinearLayout linearLayout=new LinearLayout(this); final EditText emailet= new EditText(this); // write the email using which you registered emailet.setText("Email"); emailet.setMinEms(16); emailet.setInputType(InputType.TYPE_TEXT_VARIATION_EMAIL_ADDRESS); linearLayout.addView(emailet); linearLayout.setPadding(10,10,10,10); builder.setView(linearLayout); // Click on Recover and a email will be sent to your registered email id builder.setPositiveButton("Recover", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { String email=emailet.getText().toString().trim(); beginRecovery(email); } }); builder.setNegativeButton("Cancel", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { dialog.dismiss(); } }); builder.create().show(); } private void beginRecovery(String email) { loadingBar=new ProgressDialog(this); loadingBar.setMessage("Sending Email...."); loadingBar.setCanceledOnTouchOutside(false); loadingBar.show(); // calling sendPasswordResetEmail // open your email and write the new // password and then you can login mAuth.sendPasswordResetEmail(email).addOnCompleteListener(new OnCompleteListener<Void>() { @Override public void onComplete(@NonNull Task<Void> task) { loadingBar.dismiss(); if(task.isSuccessful()) { // if isSuccessful then done message will be shown // and you can change the password Toast.makeText(LoginActivity.this,"Done sent",Toast.LENGTH_LONG).show(); } else { Toast.makeText(LoginActivity.this,"Error Occurred",Toast.LENGTH_LONG).show(); } } }).addOnFailureListener(new OnFailureListener() { @Override public void onFailure(@NonNull Exception e) { loadingBar.dismiss(); Toast.makeText(LoginActivity.this,"Error Failed",Toast.LENGTH_LONG).show(); } }); } public void loginUser(String email,String password){ mAuth.signInWithEmailAndPassword(email,password).addOnCompleteListener(new OnCompleteListener<AuthResult>() { @Override public void onComplete(@NonNull Task<AuthResult> task) { if(task.isSuccessful()){ loginprogress.dismiss(); Intent mainIntent = new Intent(LoginActivity.this,MainActivity.class); mainIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK|Intent.FLAG_ACTIVITY_CLEAR_TASK); startActivity(mainIntent); finish(); } else { loginprogress.hide(); Toast.makeText(LoginActivity.this,"Cannot Sign In..Please Try Again",Toast.LENGTH_LONG); } } }); }} Output: GitHub link: https://github.com/Anni1123/LoginDemo surindertarika1234 simmytarika5 avtarkumar719 nikhatkhan11 Firebase Android Java Java Android Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Difference Between Implicit Intent and Explicit Intent in Android How to Create and Add Data to SQLite Database in Android? Retrofit with Kotlin Coroutine in Android Navigation Drawer in Android Broadcast Receiver in Android With Example Arrays in Java Arrays.sort() in Java with examples Split() String method in Java with examples For-each loop in Java Reverse a string in Java
[ { "code": null, "e": 52, "s": 24, "text": "\n15 Jun, 2022" }, { "code": null, "e": 572, "s": 52, "text": "In many apps, we got a feature to login using our email and password. Sometimes it happens that we forget the password and most of the time there reset our password. Here we are going to implement the same feature to Reset our password using Firebase Authentication. You may refer to the following article User authentication using Firebase in Android. A sample video is given below to get an idea about what we are going to do in this article. Note that we are going to implement this project using the Java language. " }, { "code": null, "e": 605, "s": 572, "text": "Step 1: Working with the UI part" }, { "code": null, "e": 723, "s": 605, "text": "Go to the activity_login.xml file and refer to the following code. Below is the code for the activity_login.xml file." }, { "code": null, "e": 727, "s": 723, "text": "XML" }, { "code": "<?xml version=\"1.0\" encoding=\"utf-8\"?><RelativeLayout xmlns:android=\"http://schemas.android.com/apk/res/android\" xmlns:app=\"http://schemas.android.com/apk/res-auto\" xmlns:tools=\"http://schemas.android.com/tools\" android:layout_width=\"match_parent\" android:layout_height=\"match_parent\" android:orientation=\"vertical\" tools:context=\".LoginActivity\"> <include android:id=\"@+id/login_toolbar\" layout=\"@layout/app_bar_layout\" /> <TextView android:id=\"@+id/textView2\" android:layout_width=\"wrap_content\" android:layout_height=\"wrap_content\" android:layout_alignParentStart=\"true\" android:layout_alignParentTop=\"true\" android:layout_marginStart=\"19dp\" android:layout_marginTop=\"96dp\" android:textSize=\"25dp\" android:text=\"Login to Your Account\" /> <EditText android:id=\"@+id/logemail\" android:layout_width=\"267dp\" android:layout_height=\"wrap_content\" android:layout_alignParentStart=\"true\" android:layout_alignParentTop=\"true\" android:layout_marginStart=\"36dp\" android:layout_marginTop=\"198dp\" android:ems=\"10\" android:hint=\"Email\" android:inputType=\"textEmailAddress\" /> <EditText android:id=\"@+id/logpass\" android:layout_width=\"259dp\" android:layout_height=\"58dp\" android:layout_alignParentStart=\"true\" android:layout_alignParentTop=\"true\" android:layout_marginStart=\"32dp\" android:layout_marginTop=\"261dp\" android:ems=\"10\" android:hint=\"Password\" android:inputType=\"textPassword\" /> <TextView android:layout_width=\"match_parent\" android:layout_height=\"wrap_content\" android:id=\"@+id/forgetpass\" android:layout_alignParentStart=\"true\" android:layout_alignParentTop=\"true\" android:layout_marginStart=\"132dp\" android:layout_marginTop=\"351dp\" android:text=\"Forget Password\"/> <Button android:id=\"@+id/logbut\" android:layout_width=\"wrap_content\" android:layout_height=\"wrap_content\" android:layout_alignParentStart=\"true\" android:layout_alignParentTop=\"true\" android:layout_marginStart=\"222dp\" android:layout_marginTop=\"387dp\" android:background=\"@color/colorPrimary\" android:text=\"Login\" android:textSize=\"15dp\" /> </RelativeLayout>", "e": 3139, "s": 727, "text": null }, { "code": null, "e": 3188, "s": 3139, "text": "Step 2: Working with the LoginActivity.java file" }, { "code": null, "e": 3197, "s": 3188, "text": "Chapters" }, { "code": null, "e": 3224, "s": 3197, "text": "descriptions off, selected" }, { "code": null, "e": 3274, "s": 3224, "text": "captions settings, opens captions settings dialog" }, { "code": null, "e": 3297, "s": 3274, "text": "captions off, selected" }, { "code": null, "e": 3305, "s": 3297, "text": "English" }, { "code": null, "e": 3329, "s": 3305, "text": "This is a modal window." }, { "code": null, "e": 3398, "s": 3329, "text": "Beginning of dialog window. Escape will cancel and close the window." }, { "code": null, "e": 3420, "s": 3398, "text": "End of dialog window." }, { "code": null, "e": 3538, "s": 3420, "text": "Go to the LoginActivity.java file and refer to the following code. Below is the code for the LoginActivity.java file " }, { "code": null, "e": 3543, "s": 3538, "text": "Java" }, { "code": "import androidx.annotation.NonNull;import androidx.appcompat.app.AppCompatActivity;import androidx.appcompat.widget.Toolbar; import android.app.AlertDialog;import android.app.ProgressDialog;import android.content.DialogInterface;import android.content.Intent;import android.os.Bundle;import android.text.InputType;import android.text.TextUtils;import android.view.View;import android.widget.Button;import android.widget.EditText;import android.widget.LinearLayout;import android.widget.TextView;import android.widget.Toast; import com.google.android.gms.tasks.OnCompleteListener;import com.google.android.gms.tasks.OnFailureListener;import com.google.android.gms.tasks.Task;import com.google.firebase.auth.AuthResult;import com.google.firebase.auth.FirebaseAuth; public class LoginActivity extends AppCompatActivity { private EditText memail; private EditText mpass; private FirebaseAuth mAuth; private Toolbar mtoolbar; private Button login; TextView forgetpass; public ProgressDialog loginprogress; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_login); mtoolbar=(Toolbar)findViewById(R.id.login_toolbar); setSupportActionBar(mtoolbar); mAuth = FirebaseAuth.getInstance(); getSupportActionBar().setTitle(\"Login\"); forgetpass=findViewById(R.id.forgetpass); getSupportActionBar().setDisplayHomeAsUpEnabled(true); loginprogress=new ProgressDialog(this); memail=(EditText)findViewById(R.id.logemail); mpass=(EditText)findViewById(R.id.logpass); // click on forget password text forgetpass.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { showRecoverPasswordDialog(); } }); login=(Button)findViewById(R.id.logbut); login.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { String email=memail.getText().toString(); String password =mpass.getText().toString(); if(!TextUtils.isEmpty(email)||!TextUtils.isEmpty(password)){ loginprogress.setTitle(\"Logging In\"); loginprogress.setMessage(\"Please Wait \"); loginprogress.setCanceledOnTouchOutside(false); loginprogress.show(); loginUser(email,password); } } }); } ProgressDialog loadingBar; private void showRecoverPasswordDialog() { AlertDialog.Builder builder=new AlertDialog.Builder(this); builder.setTitle(\"Recover Password\"); LinearLayout linearLayout=new LinearLayout(this); final EditText emailet= new EditText(this); // write the email using which you registered emailet.setText(\"Email\"); emailet.setMinEms(16); emailet.setInputType(InputType.TYPE_TEXT_VARIATION_EMAIL_ADDRESS); linearLayout.addView(emailet); linearLayout.setPadding(10,10,10,10); builder.setView(linearLayout); // Click on Recover and a email will be sent to your registered email id builder.setPositiveButton(\"Recover\", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { String email=emailet.getText().toString().trim(); beginRecovery(email); } }); builder.setNegativeButton(\"Cancel\", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { dialog.dismiss(); } }); builder.create().show(); } private void beginRecovery(String email) { loadingBar=new ProgressDialog(this); loadingBar.setMessage(\"Sending Email....\"); loadingBar.setCanceledOnTouchOutside(false); loadingBar.show(); // calling sendPasswordResetEmail // open your email and write the new // password and then you can login mAuth.sendPasswordResetEmail(email).addOnCompleteListener(new OnCompleteListener<Void>() { @Override public void onComplete(@NonNull Task<Void> task) { loadingBar.dismiss(); if(task.isSuccessful()) { // if isSuccessful then done message will be shown // and you can change the password Toast.makeText(LoginActivity.this,\"Done sent\",Toast.LENGTH_LONG).show(); } else { Toast.makeText(LoginActivity.this,\"Error Occurred\",Toast.LENGTH_LONG).show(); } } }).addOnFailureListener(new OnFailureListener() { @Override public void onFailure(@NonNull Exception e) { loadingBar.dismiss(); Toast.makeText(LoginActivity.this,\"Error Failed\",Toast.LENGTH_LONG).show(); } }); } public void loginUser(String email,String password){ mAuth.signInWithEmailAndPassword(email,password).addOnCompleteListener(new OnCompleteListener<AuthResult>() { @Override public void onComplete(@NonNull Task<AuthResult> task) { if(task.isSuccessful()){ loginprogress.dismiss(); Intent mainIntent = new Intent(LoginActivity.this,MainActivity.class); mainIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK|Intent.FLAG_ACTIVITY_CLEAR_TASK); startActivity(mainIntent); finish(); } else { loginprogress.hide(); Toast.makeText(LoginActivity.this,\"Cannot Sign In..Please Try Again\",Toast.LENGTH_LONG); } } }); }}", "e": 9554, "s": 3543, "text": null }, { "code": null, "e": 9562, "s": 9554, "text": "Output:" }, { "code": null, "e": 9613, "s": 9562, "text": "GitHub link: https://github.com/Anni1123/LoginDemo" }, { "code": null, "e": 9632, "s": 9613, "text": "surindertarika1234" }, { "code": null, "e": 9645, "s": 9632, "text": "simmytarika5" }, { "code": null, "e": 9659, "s": 9645, "text": "avtarkumar719" }, { "code": null, "e": 9672, "s": 9659, "text": "nikhatkhan11" }, { "code": null, "e": 9681, "s": 9672, "text": "Firebase" }, { "code": null, "e": 9689, "s": 9681, "text": "Android" }, { "code": null, "e": 9694, "s": 9689, "text": "Java" }, { "code": null, "e": 9699, "s": 9694, "text": "Java" }, { "code": null, "e": 9707, "s": 9699, "text": "Android" }, { "code": null, "e": 9805, "s": 9707, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 9871, "s": 9805, "text": "Difference Between Implicit Intent and Explicit Intent in Android" }, { "code": null, "e": 9929, "s": 9871, "text": "How to Create and Add Data to SQLite Database in Android?" }, { "code": null, "e": 9971, "s": 9929, "text": "Retrofit with Kotlin Coroutine in Android" }, { "code": null, "e": 10000, "s": 9971, "text": "Navigation Drawer in Android" }, { "code": null, "e": 10043, "s": 10000, "text": "Broadcast Receiver in Android With Example" }, { "code": null, "e": 10058, "s": 10043, "text": "Arrays in Java" }, { "code": null, "e": 10094, "s": 10058, "text": "Arrays.sort() in Java with examples" }, { "code": null, "e": 10138, "s": 10094, "text": "Split() String method in Java with examples" }, { "code": null, "e": 10160, "s": 10138, "text": "For-each loop in Java" } ]
XSLT <if>
<xsl:if> tag specifies a conditional test against the content of nodes. Following is the syntax declaration of <xsl:if> element. <xsl:if test = boolean-expression > </xsl:if> test The condition in the xml data to test. Parent elements xsl:attribute, xsl:comment, xsl:copy, xsl:element, xsl:fallback, xsl:for-each, xsl:if, xsl:message, xsl:otherwise, xsl:param, xsl:processing-instruction, xsl:template, xsl:variable, xsl:when, xsl:with-param, output elements Child elements xsl:apply-templates, xsl:attribute, xsl:call-template, xsl:choose, xsl:comment, xsl:copy, xsl:copy-of, xsl:element, xsl:for-each, xsl:if, xsl:processing-instruction, xsl:text, xsl:value-of, xsl:variable, output elements This example creates a table of <student> element with its attribute rollno and its child <firstname>, <lastname>, <nickname>, and <marks> by iterating over each student. It checks marks to be greater than 90 and then prints the student(s) details. students.xml <?xml version = "1.0"?> <?xml-stylesheet type = "text/xsl" href = "students.xsl"?> <class> <student rollno = "393"> <firstname>Dinkar</firstname> <lastname>Kad</lastname> <nickname>Dinkar</nickname> <marks>85</marks> </student> <student rollno = "493"> <firstname>Vaneet</firstname> <lastname>Gupta</lastname> <nickname>Vinni</nickname> <marks>95</marks> </student> <student rollno = "593"> <firstname>Jasvir</firstname> <lastname>Singh</lastname> <nickname>Jazz</nickname> <marks>90</marks> </student> </class> students.xsl <?xml version = "1.0" encoding = "UTF-8"?> <xsl:stylesheet version = "1.0" xmlns:xsl = "http://www.w3.org/1999/XSL/Transform"> <xsl:template match = "/"> <html> <body> <h2>Students</h2> <table border = "1"> <tr bgcolor = "#9acd32"> <th>Roll No</th> <th>First Name</th> <th>Last Name</th> <th>Nick Name</th> <th>Marks</th> </tr> <xsl:for-each select = "class/student"> <xsl:if test = "marks > 90"> <tr> <td><xsl:value-of select = "@rollno"/></td> <td><xsl:value-of select = "firstname"/></td> <td><xsl:value-of select = "lastname"/></td> <td><xsl:value-of select = "nickname"/></td> <td><xsl:value-of select = "marks"/></td>
[ { "code": null, "e": 1965, "s": 1893, "text": "<xsl:if> tag specifies a conditional test against the content of nodes." }, { "code": null, "e": 2022, "s": 1965, "text": "Following is the syntax declaration of <xsl:if> element." }, { "code": null, "e": 2074, "s": 2022, "text": "<xsl:if \n test = boolean-expression > \n</xsl:if> \n" }, { "code": null, "e": 2079, "s": 2074, "text": "test" }, { "code": null, "e": 2118, "s": 2079, "text": "The condition in the xml data to test." }, { "code": null, "e": 2134, "s": 2118, "text": "Parent elements" }, { "code": null, "e": 2358, "s": 2134, "text": "xsl:attribute, xsl:comment, xsl:copy, xsl:element, xsl:fallback, xsl:for-each, xsl:if, xsl:message, xsl:otherwise, xsl:param, xsl:processing-instruction, xsl:template, xsl:variable, xsl:when, xsl:with-param, output elements" }, { "code": null, "e": 2373, "s": 2358, "text": "Child elements" }, { "code": null, "e": 2593, "s": 2373, "text": "xsl:apply-templates, xsl:attribute, xsl:call-template, xsl:choose, xsl:comment, xsl:copy, xsl:copy-of, xsl:element, xsl:for-each, xsl:if, xsl:processing-instruction, xsl:text, xsl:value-of, xsl:variable, output elements" }, { "code": null, "e": 2842, "s": 2593, "text": "This example creates a table of <student> element with its attribute rollno and its child <firstname>, <lastname>, <nickname>, and <marks> by iterating over each student. It checks marks to be greater than 90 and then prints the student(s) details." }, { "code": null, "e": 2855, "s": 2842, "text": "students.xml" }, { "code": null, "e": 3478, "s": 2855, "text": "<?xml version = \"1.0\"?> \n<?xml-stylesheet type = \"text/xsl\" href = \"students.xsl\"?> \n<class> \n <student rollno = \"393\"> \n <firstname>Dinkar</firstname> \n <lastname>Kad</lastname> \n <nickname>Dinkar</nickname> \n <marks>85</marks> \n </student> \n <student rollno = \"493\"> \n <firstname>Vaneet</firstname> \n <lastname>Gupta</lastname> \n <nickname>Vinni</nickname> \n <marks>95</marks> \n </student> \n <student rollno = \"593\"> \n <firstname>Jasvir</firstname> \n <lastname>Singh</lastname> \n <nickname>Jazz</nickname> \n <marks>90</marks> \n </student> \n</class>" }, { "code": null, "e": 3491, "s": 3478, "text": "students.xsl" } ]
Find the character in first string that is present at minimum index in second string
01 May, 2021 Given a string str and another string patt. Find the character in patt that is present at the minimum index in str. If no character of patt is present in str then print ‘No character present’. Examples: Input: str = “geeksforgeeks”, patt = “set” Output: e Both e and s of patt are present in str, but e is present at minimum index, which is 1. Input: str = “adcffaet”, patt = “onkl” Output: No character present Source: OLA Interview Experience | Set 12. Naive Approach: Using two loops, find the first index of each character of patt in str. Print the character having the minimum index. If no character of patt is present in str then print “No character present”. C++ Java Python3 C# Javascript // C++ implementation to find the character in// first string that is present at minimum index// in second string#include <bits/stdc++.h>using namespace std; // function to find the minimum index charactervoid printMinIndexChar(string str, string patt){ // to store the index of character having // minimum index int minIndex = INT_MAX; // lengths of the two strings int m = str.size(); int n = patt.size(); // traverse 'patt' for (int i = 0; i < n; i++) { // for each character of 'patt' traverse 'str' for (int j = 0; j < m; j++) { // if patt[i] is found in 'str', check if // it has the minimum index or not. If yes, // then update 'minIndex' and break if (patt[i] == str[j] && j < minIndex) { minIndex = j; break; } } } // print the minimum index character if (minIndex != INT_MAX) cout << "Minimum Index Character = " << str[minIndex]; // if no character of 'patt' is present in 'str' else cout << "No character present";} // Driver program to test aboveint main(){ string str = "geeksforgeeks"; string patt = "set"; printMinIndexChar(str, patt); return 0;} // Java implementation to find the character in// first string that is present at minimum index// in second string public class GFG{ // method to find the minimum index character static void printMinIndexChar(String str, String patt) { // to store the index of character having // minimum index int minIndex = Integer.MAX_VALUE; // lengths of the two strings int m = str.length(); int n = patt.length(); // traverse 'patt' for (int i = 0; i < n; i++) { // for each character of 'patt' traverse 'str' for (int j = 0; j < m; j++) { // if patt.charAt(i)is found in 'str', check if // it has the minimum index or not. If yes, // then update 'minIndex' and break if (patt.charAt(i)== str.charAt(j) && j < minIndex) { minIndex = j; break; } } } // print the minimum index character if (minIndex != Integer.MAX_VALUE) System.out.println("Minimum Index Character = " + str.charAt(minIndex)); // if no character of 'patt' is present in 'str' else System.out.println("No character present"); } // Driver Method public static void main(String[] args) { String str = "geeksforgeeks"; String patt = "set"; printMinIndexChar(str, patt); }} # Python3 implementation to find the character in# first that is present at minimum index# in second String # function to find the minimum index characterdef printMinIndexChar(Str, patt): # to store the index of character having # minimum index minIndex = 10**9 # lengths of the two Strings m =len(Str) n =len(patt) # traverse 'patt' for i in range(n): # for each character of 'patt' traverse 'Str' for j in range(m): # if patt[i] is found in 'Str', check if # it has the minimum index or not. If yes, # then update 'minIndex' and break if (patt[i] == Str[j] and j < minIndex): minIndex = j break # print the minimum index character if (minIndex != 10**9): print("Minimum Index Character = ",Str[minIndex]) # if no character of 'patt' is present in 'Str' else: print("No character present") # Driver code Str = "geeksforgeeks"patt = "set"printMinIndexChar(Str, patt) # This code is contributed by mohit kumar 29 // C# implementation to find the character in// first string that is present at minimum index// in second stringusing System; class GFG{ // method to find the minimum index character static void printMinIndexChar(String str, String patt) { // to store the index of character having // minimum index int minIndex = int.MaxValue; // lengths of the two strings int m = str.Length; int n = patt.Length; // traverse 'patt' for (int i = 0; i < n; i++) { // for each character of 'patt' traverse 'str' for (int j = 0; j < m; j++) { // if patt.charAt(i)is found in 'str', check if // it has the minimum index or not. If yes, // then update 'minIndex' and break if (patt[i]== str[j] && j < minIndex) { minIndex = j; break; } } } // print the minimum index character if (minIndex != int.MaxValue) Console.WriteLine("Minimum Index Character = " + str[minIndex]); // if no character of 'patt' is present in 'str' else Console.WriteLine("No character present"); } // Driver Methoda public static void Main() { String str = "geeksforgeeks"; String patt = "set"; printMinIndexChar(str, patt); }}// This code is contributed by Sam007 <script>// Javascript implementation to find the character in// first string that is present at minimum index// in second string // method to find the minimum index character function printMinIndexChar(str,patt) { // to store the index of character having // minimum index let minIndex = Number.MAX_VALUE; // lengths of the two strings let m = str.length; let n = patt.length; // traverse 'patt' for (let i = 0; i < n; i++) { // for each character of 'patt' traverse 'str' for (let j = 0; j < m; j++) { // if patt.charAt(i)is found in 'str', check if // it has the minimum index or not. If yes, // then update 'minIndex' and break if (patt[i]== str[j] && j < minIndex) { minIndex = j; break; } } } // print the minimum index character if (minIndex != Number.MAX_VALUE) document.write("Minimum Index Character = " + str[minIndex]); // if no character of 'patt' is present in 'str' else document.write("No character present"); } // Driver Method let str = "geeksforgeeks"; let patt = "set"; printMinIndexChar(str, patt); //This code is contributed by rag2127 </script> Output: Minimum Index Character = e Time Complexity: O(mn), where m and n are the lengths of the two strings. Auxiliary Space: O(1) Method 2 Efficient Approach(Hashing): Create a hash table with (key, value) tuple represented as (character, index) tuple. Store the first index of each character of str in the hash table. Now, for each character of patt check if it is present in the hash table or not. If present then get its index from the hash table and update minIndex(minimum index encountered so far).For no matching character print “No character present”. If present then get its index from the hash table and update minIndex(minimum index encountered so far). For no matching character print “No character present”. Hash table is implemented using unordered_set in C++.The below image is a dry run of the above approach: Below is the implementation of the above approach: C++ Java Python3 C# Javascript // C++ implementation to find the character in first// string that is present at minimum index in second// string#include <bits/stdc++.h>using namespace std; // function to find the minimum index charactervoid printMinIndexChar(string str, string patt){ // unordered_map 'um' implemented as hash table unordered_map<char, int> um; // to store the index of character having // minimum index int minIndex = INT_MAX; // lengths of the two strings int m = str.size(); int n = patt.size();- // store the first index of each character of 'str' for (int i = 0; i < m; i++) if (um.find(str[i]) == um.end()) um[str[i]] = i; // traverse the string 'patt' for (int i = 0; i < n; i++) // if patt[i] is found in 'um', check if // it has the minimum index or not accordingly // update 'minIndex' if (um.find(patt[i]) != um.end() && um[patt[i]] < minIndex) minIndex = um[patt[i]]; // print the minimum index character if (minIndex != INT_MAX) cout << "Minimum Index Character = " << str[minIndex]; // if no character of 'patt' is present in 'str' else cout << "No character present";} // Driver program to test aboveint main(){ string str = "geeksforgeeks"; string patt = "set"; printMinIndexChar(str, patt); return 0;} // Java implementation to find the character in// first string that is present at minimum index// in second string import java.util.HashMap; public class GFG{ // method to find the minimum index character static void printMinIndexChar(String str, String patt) { // map to store the first index of each character of 'str' HashMap<Character, Integer> hm = new HashMap<>(); // to store the index of character having // minimum index int minIndex = Integer.MAX_VALUE; // lengths of the two strings int m = str.length(); int n = patt.length(); // store the first index of each character of 'str' for (int i = 0; i < m; i++) if(!hm.containsKey(str.charAt(i))) hm.put(str.charAt(i),i); // traverse the string 'patt' for (int i = 0; i < n; i++) // if patt[i] is found in 'um', check if // it has the minimum index or not accordingly // update 'minIndex' if (hm.containsKey(patt.charAt(i)) && hm.get(patt.charAt(i)) < minIndex) minIndex = hm.get(patt.charAt(i)); // print the minimum index character if (minIndex != Integer.MAX_VALUE) System.out.println("Minimum Index Character = " + str.charAt(minIndex)); // if no character of 'patt' is present in 'str' else System.out.println("No character present"); } // Driver Method public static void main(String[] args) { String str = "geeksforgeeks"; String patt = "set"; printMinIndexChar(str, patt); }} # Python3 implementation to# find the character in first# string that is present at# minimum index in second stringimport sys # Function to find the# minimum index characterdef printMinIndexChar(st, patt): # unordered_map 'um' # implemented as hash table um = {} # to store the index of # character having minimum index minIndex = sys.maxsize # Lengths of the two strings m = len(st) n = len(patt) # Store the first index of # each character of 'str' for i in range (m): if (st[i] not in um): um[st[i]] = i # traverse the string 'patt' for i in range(n): # If patt[i] is found in 'um', # check if it has the minimum # index or not accordingly # update 'minIndex' if (patt[i] in um and um[patt[i]] < minIndex): minIndex = um[patt[i]] # Print the minimum index character if (minIndex != sys.maxsize): print ("Minimum Index Character = ", st[minIndex]) # If no character of 'patt' # is present in 'str' else: print ("No character present") # Driver program to test aboveif __name__ == "__main__": st = "geeksforgeeks" patt = "set" printMinIndexChar(st, patt) # This code is contributed by Chitranayal // C# implementation to find the character in// first string that is present at minimum index// in second stringusing System;using System.Collections.Generic; class GFG{ // method to find the minimum index character static void printMinIndexChar(String str, String patt) { // map to store the first index of // each character of 'str' Dictionary<char, int> hm = new Dictionary<char, int>(); // to store the index of character having // minimum index int minIndex = int.MaxValue; // lengths of the two strings int m = str.Length; int n = patt.Length; // store the first index of // each character of 'str' for (int i = 0; i < m; i++) if(!hm.ContainsKey(str[i])) hm.Add(str[i], i); // traverse the string 'patt' for (int i = 0; i < n; i++) // if patt[i] is found in 'um', // check if it has the minimum index // or not, accordingly update 'minIndex' if (hm.ContainsKey(patt[i]) && hm[patt[i]] < minIndex) minIndex = hm[patt[i]]; // print the minimum index character if (minIndex != int.MaxValue) Console.WriteLine("Minimum Index Character = " + str[minIndex]); // if no character of 'patt' is present in 'str' else Console.WriteLine("No character present"); } // Driver Code public static void Main(String[] args) { String str = "geeksforgeeks"; String patt = "set"; printMinIndexChar(str, patt); }} // This code is contributed by Princi Singh <script> // Javascript implementation to find the// character in first string that is// present at minimum index in second// string // Method to find the minimum index characterfunction printMinIndexChar(str, patt){ // map to store the first index of // each character of 'str' let hm = new Map(); // To store the index of character having // minimum index let minIndex = Number.MAX_VALUE; // Lengths of the two strings let m = str.length; let n = patt.length; // Store the first index of // each character of 'str' for(let i = 0; i < m; i++) if (!hm.has(str[i])) hm.set(str[i], i); // Traverse the string 'patt' for(let i = 0; i < n; i++) // If patt[i] is found in 'um', check // if it has the minimum index or not // accordingly update 'minIndex' if (hm.has(patt[i]) && hm.get(patt[i]) < minIndex) minIndex = hm.get(patt[i]); // Print the minimum index character if (minIndex != Number.MAX_VALUE) document.write("Minimum Index Character = " + str[minIndex]); // If no character of 'patt' is // present in 'str' else document.write("No character present");} // Driver Codelet str = "geeksforgeeks";let patt = "set"; printMinIndexChar(str, patt); // This code is contributed by avanitrachhadiya2155 </script> Output: Minimum Index Character = e Time Complexity: O(m + n), where m and n are the lengths of the two strings. Auxiliary Space: O(d), where d is the size of hash table, which is the count of distinct characters in str. Minimum Index Character | Data Structures & Algorithms | Programming Tutorials | GeeksforGeeks - YouTubeGeeksforGeeks529K subscribersMinimum Index Character | Data Structures & Algorithms | Programming Tutorials | GeeksforGeeksWatch laterShareCopy linkInfoShoppingTap to unmuteIf playback doesn't begin shortly, try restarting your device.More videosMore videosYou're signed outVideos you watch may be added to the TV's watch history and influence TV recommendations. To avoid this, cancel and sign in to YouTube on your computer.CancelConfirmSwitch cameraShareInclude playlistAn error occurred while retrieving sharing information. Please try again later.Watch on0:000:000:00 / 10:24•Live•<div class="player-unavailable"><h1 class="message">An error occurred.</h1><div class="submessage"><a href="https://www.youtube.com/watch?v=6nWWUYNnpXM" target="_blank">Try watching this video on www.youtube.com</a>, or enable JavaScript if it is disabled in your browser.</div></div> This article is contributed by Ayush Jauhari. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to review-team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. mohit kumar 29 princi singh ManasChhabra2 nidhi_biet ukasp rag2127 avanitrachhadiya2155 Ola Cabs STL Hash Strings Ola Cabs Hash Strings STL Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. What is Hashing | A Complete Tutorial Find k numbers with most occurrences in the given array Real-time application of Data Structures Non-Repeating Element Find the length of largest subarray with 0 sum 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": 52, "s": 24, "text": "\n01 May, 2021" }, { "code": null, "e": 245, "s": 52, "text": "Given a string str and another string patt. Find the character in patt that is present at the minimum index in str. If no character of patt is present in str then print ‘No character present’." }, { "code": null, "e": 256, "s": 245, "text": "Examples: " }, { "code": null, "e": 397, "s": 256, "text": "Input: str = “geeksforgeeks”, patt = “set” Output: e Both e and s of patt are present in str, but e is present at minimum index, which is 1." }, { "code": null, "e": 465, "s": 397, "text": "Input: str = “adcffaet”, patt = “onkl” Output: No character present" }, { "code": null, "e": 508, "s": 465, "text": "Source: OLA Interview Experience | Set 12." }, { "code": null, "e": 719, "s": 508, "text": "Naive Approach: Using two loops, find the first index of each character of patt in str. Print the character having the minimum index. If no character of patt is present in str then print “No character present”." }, { "code": null, "e": 723, "s": 719, "text": "C++" }, { "code": null, "e": 728, "s": 723, "text": "Java" }, { "code": null, "e": 736, "s": 728, "text": "Python3" }, { "code": null, "e": 739, "s": 736, "text": "C#" }, { "code": null, "e": 750, "s": 739, "text": "Javascript" }, { "code": "// C++ implementation to find the character in// first string that is present at minimum index// in second string#include <bits/stdc++.h>using namespace std; // function to find the minimum index charactervoid printMinIndexChar(string str, string patt){ // to store the index of character having // minimum index int minIndex = INT_MAX; // lengths of the two strings int m = str.size(); int n = patt.size(); // traverse 'patt' for (int i = 0; i < n; i++) { // for each character of 'patt' traverse 'str' for (int j = 0; j < m; j++) { // if patt[i] is found in 'str', check if // it has the minimum index or not. If yes, // then update 'minIndex' and break if (patt[i] == str[j] && j < minIndex) { minIndex = j; break; } } } // print the minimum index character if (minIndex != INT_MAX) cout << \"Minimum Index Character = \" << str[minIndex]; // if no character of 'patt' is present in 'str' else cout << \"No character present\";} // Driver program to test aboveint main(){ string str = \"geeksforgeeks\"; string patt = \"set\"; printMinIndexChar(str, patt); return 0;}", "e": 2002, "s": 750, "text": null }, { "code": "// Java implementation to find the character in// first string that is present at minimum index// in second string public class GFG{ // method to find the minimum index character static void printMinIndexChar(String str, String patt) { // to store the index of character having // minimum index int minIndex = Integer.MAX_VALUE; // lengths of the two strings int m = str.length(); int n = patt.length(); // traverse 'patt' for (int i = 0; i < n; i++) { // for each character of 'patt' traverse 'str' for (int j = 0; j < m; j++) { // if patt.charAt(i)is found in 'str', check if // it has the minimum index or not. If yes, // then update 'minIndex' and break if (patt.charAt(i)== str.charAt(j) && j < minIndex) { minIndex = j; break; } } } // print the minimum index character if (minIndex != Integer.MAX_VALUE) System.out.println(\"Minimum Index Character = \" + str.charAt(minIndex)); // if no character of 'patt' is present in 'str' else System.out.println(\"No character present\"); } // Driver Method public static void main(String[] args) { String str = \"geeksforgeeks\"; String patt = \"set\"; printMinIndexChar(str, patt); }}", "e": 3504, "s": 2002, "text": null }, { "code": "# Python3 implementation to find the character in# first that is present at minimum index# in second String # function to find the minimum index characterdef printMinIndexChar(Str, patt): # to store the index of character having # minimum index minIndex = 10**9 # lengths of the two Strings m =len(Str) n =len(patt) # traverse 'patt' for i in range(n): # for each character of 'patt' traverse 'Str' for j in range(m): # if patt[i] is found in 'Str', check if # it has the minimum index or not. If yes, # then update 'minIndex' and break if (patt[i] == Str[j] and j < minIndex): minIndex = j break # print the minimum index character if (minIndex != 10**9): print(\"Minimum Index Character = \",Str[minIndex]) # if no character of 'patt' is present in 'Str' else: print(\"No character present\") # Driver code Str = \"geeksforgeeks\"patt = \"set\"printMinIndexChar(Str, patt) # This code is contributed by mohit kumar 29", "e": 4565, "s": 3504, "text": null }, { "code": "// C# implementation to find the character in// first string that is present at minimum index// in second stringusing System; class GFG{ // method to find the minimum index character static void printMinIndexChar(String str, String patt) { // to store the index of character having // minimum index int minIndex = int.MaxValue; // lengths of the two strings int m = str.Length; int n = patt.Length; // traverse 'patt' for (int i = 0; i < n; i++) { // for each character of 'patt' traverse 'str' for (int j = 0; j < m; j++) { // if patt.charAt(i)is found in 'str', check if // it has the minimum index or not. If yes, // then update 'minIndex' and break if (patt[i]== str[j] && j < minIndex) { minIndex = j; break; } } } // print the minimum index character if (minIndex != int.MaxValue) Console.WriteLine(\"Minimum Index Character = \" + str[minIndex]); // if no character of 'patt' is present in 'str' else Console.WriteLine(\"No character present\"); } // Driver Methoda public static void Main() { String str = \"geeksforgeeks\"; String patt = \"set\"; printMinIndexChar(str, patt); }}// This code is contributed by Sam007", "e": 6053, "s": 4565, "text": null }, { "code": "<script>// Javascript implementation to find the character in// first string that is present at minimum index// in second string // method to find the minimum index character function printMinIndexChar(str,patt) { // to store the index of character having // minimum index let minIndex = Number.MAX_VALUE; // lengths of the two strings let m = str.length; let n = patt.length; // traverse 'patt' for (let i = 0; i < n; i++) { // for each character of 'patt' traverse 'str' for (let j = 0; j < m; j++) { // if patt.charAt(i)is found in 'str', check if // it has the minimum index or not. If yes, // then update 'minIndex' and break if (patt[i]== str[j] && j < minIndex) { minIndex = j; break; } } } // print the minimum index character if (minIndex != Number.MAX_VALUE) document.write(\"Minimum Index Character = \" + str[minIndex]); // if no character of 'patt' is present in 'str' else document.write(\"No character present\"); } // Driver Method let str = \"geeksforgeeks\"; let patt = \"set\"; printMinIndexChar(str, patt); //This code is contributed by rag2127 </script>", "e": 7504, "s": 6053, "text": null }, { "code": null, "e": 7514, "s": 7504, "text": "Output: " }, { "code": null, "e": 7542, "s": 7514, "text": "Minimum Index Character = e" }, { "code": null, "e": 7678, "s": 7542, "text": "Time Complexity: O(mn), where m and n are the lengths of the two strings. Auxiliary Space: O(1) Method 2 Efficient Approach(Hashing): " }, { "code": null, "e": 7763, "s": 7678, "text": "Create a hash table with (key, value) tuple represented as (character, index) tuple." }, { "code": null, "e": 7829, "s": 7763, "text": "Store the first index of each character of str in the hash table." }, { "code": null, "e": 8070, "s": 7829, "text": "Now, for each character of patt check if it is present in the hash table or not. If present then get its index from the hash table and update minIndex(minimum index encountered so far).For no matching character print “No character present”." }, { "code": null, "e": 8175, "s": 8070, "text": "If present then get its index from the hash table and update minIndex(minimum index encountered so far)." }, { "code": null, "e": 8231, "s": 8175, "text": "For no matching character print “No character present”." }, { "code": null, "e": 8337, "s": 8231, "text": "Hash table is implemented using unordered_set in C++.The below image is a dry run of the above approach: " }, { "code": null, "e": 8388, "s": 8337, "text": "Below is the implementation of the above approach:" }, { "code": null, "e": 8392, "s": 8388, "text": "C++" }, { "code": null, "e": 8397, "s": 8392, "text": "Java" }, { "code": null, "e": 8405, "s": 8397, "text": "Python3" }, { "code": null, "e": 8408, "s": 8405, "text": "C#" }, { "code": null, "e": 8419, "s": 8408, "text": "Javascript" }, { "code": "// C++ implementation to find the character in first// string that is present at minimum index in second// string#include <bits/stdc++.h>using namespace std; // function to find the minimum index charactervoid printMinIndexChar(string str, string patt){ // unordered_map 'um' implemented as hash table unordered_map<char, int> um; // to store the index of character having // minimum index int minIndex = INT_MAX; // lengths of the two strings int m = str.size(); int n = patt.size();- // store the first index of each character of 'str' for (int i = 0; i < m; i++) if (um.find(str[i]) == um.end()) um[str[i]] = i; // traverse the string 'patt' for (int i = 0; i < n; i++) // if patt[i] is found in 'um', check if // it has the minimum index or not accordingly // update 'minIndex' if (um.find(patt[i]) != um.end() && um[patt[i]] < minIndex) minIndex = um[patt[i]]; // print the minimum index character if (minIndex != INT_MAX) cout << \"Minimum Index Character = \" << str[minIndex]; // if no character of 'patt' is present in 'str' else cout << \"No character present\";} // Driver program to test aboveint main(){ string str = \"geeksforgeeks\"; string patt = \"set\"; printMinIndexChar(str, patt); return 0;}", "e": 9785, "s": 8419, "text": null }, { "code": "// Java implementation to find the character in// first string that is present at minimum index// in second string import java.util.HashMap; public class GFG{ // method to find the minimum index character static void printMinIndexChar(String str, String patt) { // map to store the first index of each character of 'str' HashMap<Character, Integer> hm = new HashMap<>(); // to store the index of character having // minimum index int minIndex = Integer.MAX_VALUE; // lengths of the two strings int m = str.length(); int n = patt.length(); // store the first index of each character of 'str' for (int i = 0; i < m; i++) if(!hm.containsKey(str.charAt(i))) hm.put(str.charAt(i),i); // traverse the string 'patt' for (int i = 0; i < n; i++) // if patt[i] is found in 'um', check if // it has the minimum index or not accordingly // update 'minIndex' if (hm.containsKey(patt.charAt(i)) && hm.get(patt.charAt(i)) < minIndex) minIndex = hm.get(patt.charAt(i)); // print the minimum index character if (minIndex != Integer.MAX_VALUE) System.out.println(\"Minimum Index Character = \" + str.charAt(minIndex)); // if no character of 'patt' is present in 'str' else System.out.println(\"No character present\"); } // Driver Method public static void main(String[] args) { String str = \"geeksforgeeks\"; String patt = \"set\"; printMinIndexChar(str, patt); }}", "e": 11480, "s": 9785, "text": null }, { "code": "# Python3 implementation to# find the character in first# string that is present at# minimum index in second stringimport sys # Function to find the# minimum index characterdef printMinIndexChar(st, patt): # unordered_map 'um' # implemented as hash table um = {} # to store the index of # character having minimum index minIndex = sys.maxsize # Lengths of the two strings m = len(st) n = len(patt) # Store the first index of # each character of 'str' for i in range (m): if (st[i] not in um): um[st[i]] = i # traverse the string 'patt' for i in range(n): # If patt[i] is found in 'um', # check if it has the minimum # index or not accordingly # update 'minIndex' if (patt[i] in um and um[patt[i]] < minIndex): minIndex = um[patt[i]] # Print the minimum index character if (minIndex != sys.maxsize): print (\"Minimum Index Character = \", st[minIndex]) # If no character of 'patt' # is present in 'str' else: print (\"No character present\") # Driver program to test aboveif __name__ == \"__main__\": st = \"geeksforgeeks\" patt = \"set\" printMinIndexChar(st, patt) # This code is contributed by Chitranayal", "e": 12752, "s": 11480, "text": null }, { "code": "// C# implementation to find the character in// first string that is present at minimum index// in second stringusing System;using System.Collections.Generic; class GFG{ // method to find the minimum index character static void printMinIndexChar(String str, String patt) { // map to store the first index of // each character of 'str' Dictionary<char, int> hm = new Dictionary<char, int>(); // to store the index of character having // minimum index int minIndex = int.MaxValue; // lengths of the two strings int m = str.Length; int n = patt.Length; // store the first index of // each character of 'str' for (int i = 0; i < m; i++) if(!hm.ContainsKey(str[i])) hm.Add(str[i], i); // traverse the string 'patt' for (int i = 0; i < n; i++) // if patt[i] is found in 'um', // check if it has the minimum index // or not, accordingly update 'minIndex' if (hm.ContainsKey(patt[i]) && hm[patt[i]] < minIndex) minIndex = hm[patt[i]]; // print the minimum index character if (minIndex != int.MaxValue) Console.WriteLine(\"Minimum Index Character = \" + str[minIndex]); // if no character of 'patt' is present in 'str' else Console.WriteLine(\"No character present\"); } // Driver Code public static void Main(String[] args) { String str = \"geeksforgeeks\"; String patt = \"set\"; printMinIndexChar(str, patt); }} // This code is contributed by Princi Singh", "e": 14540, "s": 12752, "text": null }, { "code": "<script> // Javascript implementation to find the// character in first string that is// present at minimum index in second// string // Method to find the minimum index characterfunction printMinIndexChar(str, patt){ // map to store the first index of // each character of 'str' let hm = new Map(); // To store the index of character having // minimum index let minIndex = Number.MAX_VALUE; // Lengths of the two strings let m = str.length; let n = patt.length; // Store the first index of // each character of 'str' for(let i = 0; i < m; i++) if (!hm.has(str[i])) hm.set(str[i], i); // Traverse the string 'patt' for(let i = 0; i < n; i++) // If patt[i] is found in 'um', check // if it has the minimum index or not // accordingly update 'minIndex' if (hm.has(patt[i]) && hm.get(patt[i]) < minIndex) minIndex = hm.get(patt[i]); // Print the minimum index character if (minIndex != Number.MAX_VALUE) document.write(\"Minimum Index Character = \" + str[minIndex]); // If no character of 'patt' is // present in 'str' else document.write(\"No character present\");} // Driver Codelet str = \"geeksforgeeks\";let patt = \"set\"; printMinIndexChar(str, patt); // This code is contributed by avanitrachhadiya2155 </script>", "e": 15950, "s": 14540, "text": null }, { "code": null, "e": 15959, "s": 15950, "text": "Output: " }, { "code": null, "e": 15987, "s": 15959, "text": "Minimum Index Character = e" }, { "code": null, "e": 16174, "s": 15987, "text": "Time Complexity: O(m + n), where m and n are the lengths of the two strings. Auxiliary Space: O(d), where d is the size of hash table, which is the count of distinct characters in str. " }, { "code": null, "e": 17149, "s": 16174, "text": "Minimum Index Character | Data Structures & Algorithms | Programming Tutorials | GeeksforGeeks - YouTubeGeeksforGeeks529K subscribersMinimum Index Character | Data Structures & Algorithms | Programming Tutorials | GeeksforGeeksWatch laterShareCopy linkInfoShoppingTap to unmuteIf playback doesn't begin shortly, try restarting your device.More videosMore videosYou're signed outVideos you watch may be added to the TV's watch history and influence TV recommendations. To avoid this, cancel and sign in to YouTube on your computer.CancelConfirmSwitch cameraShareInclude playlistAn error occurred while retrieving sharing information. Please try again later.Watch on0:000:000:00 / 10:24•Live•<div class=\"player-unavailable\"><h1 class=\"message\">An error occurred.</h1><div class=\"submessage\"><a href=\"https://www.youtube.com/watch?v=6nWWUYNnpXM\" target=\"_blank\">Try watching this video on www.youtube.com</a>, or enable JavaScript if it is disabled in your browser.</div></div>" }, { "code": null, "e": 17571, "s": 17149, "text": "This article is contributed by Ayush Jauhari. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to review-team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. " }, { "code": null, "e": 17588, "s": 17573, "text": "mohit kumar 29" }, { "code": null, "e": 17601, "s": 17588, "text": "princi singh" }, { "code": null, "e": 17615, "s": 17601, "text": "ManasChhabra2" }, { "code": null, "e": 17626, "s": 17615, "text": "nidhi_biet" }, { "code": null, "e": 17632, "s": 17626, "text": "ukasp" }, { "code": null, "e": 17640, "s": 17632, "text": "rag2127" }, { "code": null, "e": 17661, "s": 17640, "text": "avanitrachhadiya2155" }, { "code": null, "e": 17670, "s": 17661, "text": "Ola Cabs" }, { "code": null, "e": 17674, "s": 17670, "text": "STL" }, { "code": null, "e": 17679, "s": 17674, "text": "Hash" }, { "code": null, "e": 17687, "s": 17679, "text": "Strings" }, { "code": null, "e": 17696, "s": 17687, "text": "Ola Cabs" }, { "code": null, "e": 17701, "s": 17696, "text": "Hash" }, { "code": null, "e": 17709, "s": 17701, "text": "Strings" }, { "code": null, "e": 17713, "s": 17709, "text": "STL" }, { "code": null, "e": 17811, "s": 17713, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 17849, "s": 17811, "text": "What is Hashing | A Complete Tutorial" }, { "code": null, "e": 17905, "s": 17849, "text": "Find k numbers with most occurrences in the given array" }, { "code": null, "e": 17946, "s": 17905, "text": "Real-time application of Data Structures" }, { "code": null, "e": 17968, "s": 17946, "text": "Non-Repeating Element" }, { "code": null, "e": 18015, "s": 17968, "text": "Find the length of largest subarray with 0 sum" }, { "code": null, "e": 18061, "s": 18015, "text": "Write a program to reverse an array or string" }, { "code": null, "e": 18086, "s": 18061, "text": "Reverse a string in Java" }, { "code": null, "e": 18146, "s": 18086, "text": "Write a program to print all permutations of a given string" }, { "code": null, "e": 18161, "s": 18146, "text": "C++ Data Types" } ]
LocalTime format() method in Java with Examples
03 Dec, 2018 The format() method of a LocalTime class is used to format this time using the specified formatter passed as a parameter. This method formats this time based on passed formatter to a string. Syntax: public String format(DateTimeFormatter formatter) Parameters: This method accepts a single parameter formatter which is the specified formatter. It should not be null. Return value: This method returns the formatted time string. Exception: This method throws a DateTimeException if an error occurs during printing. Below programs illustrate the format() method: Program 1: // Java program to demonstrate// LocalTime.format() method import java.time.*;import java.time.format.DateTimeFormatter; public class GFG { public static void main(String[] args) { // create a LocalTime Objects LocalTime time = LocalTime.parse("03:18:23"); // create formatter Object DateTimeFormatter formatter = DateTimeFormatter.ISO_TIME; // apply format String value = time.format(formatter); // print result System.out.println("value : " + value); }} value : 03:18:23 Program 2: // Java program to demonstrate// LocalTime.format() method import java.time.*;import java.time.format.DateTimeFormatter; public class GFG { public static void main(String[] args) { // create a LocalTime Objects LocalTime time = LocalTime.parse("23:59:59"); // create formatter Object for ISO_LOCAL_TIME DateTimeFormatter formatter = DateTimeFormatter.ISO_LOCAL_TIME; // apply format String value = time.format(formatter); // print result System.out.println("value : " + value); }} value : 23:59:59 Reference: https://docs.oracle.com/javase/10/docs/api/java/time/LocalTime.html#format(java.time.format.DateTimeFormatter) Java-Functions Java-LocalTime Java-time package Java Java Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Interfaces in Java HashMap in Java with Examples ArrayList in Java Stream In Java Collections in Java Singleton Class in Java Multidimensional Arrays in Java Set in Java Stack Class in Java Introduction to Java
[ { "code": null, "e": 28, "s": 0, "text": "\n03 Dec, 2018" }, { "code": null, "e": 219, "s": 28, "text": "The format() method of a LocalTime class is used to format this time using the specified formatter passed as a parameter. This method formats this time based on passed formatter to a string." }, { "code": null, "e": 227, "s": 219, "text": "Syntax:" }, { "code": null, "e": 278, "s": 227, "text": "public String format(DateTimeFormatter formatter)\n" }, { "code": null, "e": 396, "s": 278, "text": "Parameters: This method accepts a single parameter formatter which is the specified formatter. It should not be null." }, { "code": null, "e": 457, "s": 396, "text": "Return value: This method returns the formatted time string." }, { "code": null, "e": 543, "s": 457, "text": "Exception: This method throws a DateTimeException if an error occurs during printing." }, { "code": null, "e": 590, "s": 543, "text": "Below programs illustrate the format() method:" }, { "code": null, "e": 601, "s": 590, "text": "Program 1:" }, { "code": "// Java program to demonstrate// LocalTime.format() method import java.time.*;import java.time.format.DateTimeFormatter; public class GFG { public static void main(String[] args) { // create a LocalTime Objects LocalTime time = LocalTime.parse(\"03:18:23\"); // create formatter Object DateTimeFormatter formatter = DateTimeFormatter.ISO_TIME; // apply format String value = time.format(formatter); // print result System.out.println(\"value : \" + value); }}", "e": 1180, "s": 601, "text": null }, { "code": null, "e": 1198, "s": 1180, "text": "value : 03:18:23\n" }, { "code": null, "e": 1209, "s": 1198, "text": "Program 2:" }, { "code": "// Java program to demonstrate// LocalTime.format() method import java.time.*;import java.time.format.DateTimeFormatter; public class GFG { public static void main(String[] args) { // create a LocalTime Objects LocalTime time = LocalTime.parse(\"23:59:59\"); // create formatter Object for ISO_LOCAL_TIME DateTimeFormatter formatter = DateTimeFormatter.ISO_LOCAL_TIME; // apply format String value = time.format(formatter); // print result System.out.println(\"value : \" + value); }}", "e": 1813, "s": 1209, "text": null }, { "code": null, "e": 1831, "s": 1813, "text": "value : 23:59:59\n" }, { "code": null, "e": 1953, "s": 1831, "text": "Reference: https://docs.oracle.com/javase/10/docs/api/java/time/LocalTime.html#format(java.time.format.DateTimeFormatter)" }, { "code": null, "e": 1968, "s": 1953, "text": "Java-Functions" }, { "code": null, "e": 1983, "s": 1968, "text": "Java-LocalTime" }, { "code": null, "e": 2001, "s": 1983, "text": "Java-time package" }, { "code": null, "e": 2006, "s": 2001, "text": "Java" }, { "code": null, "e": 2011, "s": 2006, "text": "Java" }, { "code": null, "e": 2109, "s": 2011, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 2128, "s": 2109, "text": "Interfaces in Java" }, { "code": null, "e": 2158, "s": 2128, "text": "HashMap in Java with Examples" }, { "code": null, "e": 2176, "s": 2158, "text": "ArrayList in Java" }, { "code": null, "e": 2191, "s": 2176, "text": "Stream In Java" }, { "code": null, "e": 2211, "s": 2191, "text": "Collections in Java" }, { "code": null, "e": 2235, "s": 2211, "text": "Singleton Class in Java" }, { "code": null, "e": 2267, "s": 2235, "text": "Multidimensional Arrays in Java" }, { "code": null, "e": 2279, "s": 2267, "text": "Set in Java" }, { "code": null, "e": 2299, "s": 2279, "text": "Stack Class in Java" } ]
Find a pair with given sum in BST
20 Jun, 2022 Given a BST and a sum, find if there is a pair with given sum. Example: Input : sum = 28 Root of below tree Output : Pair is found (16, 12) We have discussed different approaches to find a pair with given sum in below post.Find a pair with given sum in a Balanced BSTIn this post, hashing based solution is discussed. We traverse binary search tree by inorder way and insert node’s value into a set. Also check for any node, difference between given sum and node’s value in set, if it is found then pair exists otherwise it doesn’t exist. C++ Java Python3 C# Javascript // CPP program to find a pair with// given sum using hashing#include <bits/stdc++.h>using namespace std; struct Node { int data; struct Node *left, *right;}; Node* NewNode(int data){ Node* temp = (Node*)malloc(sizeof(Node)); temp->data = data; temp->left = NULL; temp->right = NULL; return temp;} Node* insert(Node* root, int key){ if (root == NULL) return NewNode(key); if (key < root->data) root->left = insert(root->left, key); else root->right = insert(root->right, key); return root;} bool findpairUtil(Node* root, int sum, unordered_set<int>& set){ if (root == NULL) return false; if (findpairUtil(root->left, sum, set)) return true; if (set.find(sum - root->data) != set.end()) { cout << "Pair is found (" << sum - root->data << ", " << root->data << ")" << endl; return true; } else set.insert(root->data); return findpairUtil(root->right, sum, set);} void findPair(Node* root, int sum){ unordered_set<int> set; if (!findpairUtil(root, sum, set)) cout << "Pairs do not exit" << endl;} // Driver codeint main(){ Node* root = NULL; root = insert(root, 15); root = insert(root, 10); root = insert(root, 20); root = insert(root, 8); root = insert(root, 12); root = insert(root, 16); root = insert(root, 25); root = insert(root, 10); int sum = 33; findPair(root, sum); return 0;} // JAVA program to find a pair with// given sum using hashing import java.util.*; class GFG { static class Node { int data; Node left, right; }; static Node NewNode(int data) { Node temp = new Node(); temp.data = data; temp.left = null; temp.right = null; return temp; } static Node insert(Node root, int key) { if (root == null) return NewNode(key); if (key < root.data) root.left = insert(root.left, key); else root.right = insert(root.right, key); return root; } static boolean findpairUtil(Node root, int sum, HashSet<Integer> set) { if (root == null) return false; if (findpairUtil(root.left, sum, set)) return true; if (set.contains(sum - root.data)) { System.out.println("Pair is found (" + (sum - root.data) + ", " + root.data + ")"); return true; } else set.add(root.data); return findpairUtil(root.right, sum, set); } static void findPair(Node root, int sum) { HashSet<Integer> set = new HashSet<Integer>(); if (!findpairUtil(root, sum, set)) System.out.print("Pairs do not exit" + "\n"); } // Driver code public static void main(String[] args) { Node root = null; root = insert(root, 15); root = insert(root, 10); root = insert(root, 20); root = insert(root, 8); root = insert(root, 12); root = insert(root, 16); root = insert(root, 25); root = insert(root, 10); int sum = 33; findPair(root, sum); }} // This code is contributed by PrinciRaj1992 # Python3 program to find a pair with# given sum using hashingimport sysimport math class Node: def __init__(self, data): self.data = data self.left = None self.right = None def insert(root, data): if root is None: return Node(data) if(data < root.data): root.left = insert(root.left, data) if(data > root.data): root.right = insert(root.right, data) return root def findPairUtil(root, summ, unsorted_set): if root is None: return False if findPairUtil(root.left, summ, unsorted_set): return True if unsorted_set and (summ-root.data) in unsorted_set: print("Pair is Found ({},{})".format(summ-root.data, root.data)) return True else: unsorted_set.add(root.data) return findPairUtil(root.right, summ, unsorted_set) def findPair(root, summ): unsorted_set = set() if(not findPairUtil(root, summ, unsorted_set)): print("Pair do not exist!") # Driver codeif __name__ == '__main__': root = None root = insert(root, 15) root = insert(root, 10) root = insert(root, 20) root = insert(root, 8) root = insert(root, 12) root = insert(root, 16) root = insert(root, 25) root = insert(root, 10) summ = 33 findPair(root, summ) # This code is contributed by Vikash Kumar 37 // C# program to find a pair with// given sum using hashingusing System;using System.Collections.Generic; class GFG { class Node { public int data; public Node left, right; }; static Node NewNode(int data) { Node temp = new Node(); temp.data = data; temp.left = null; temp.right = null; return temp; } static Node insert(Node root, int key) { if (root == null) return NewNode(key); if (key < root.data) root.left = insert(root.left, key); else root.right = insert(root.right, key); return root; } static bool findpairUtil(Node root, int sum, HashSet<int> set) { if (root == null) return false; if (findpairUtil(root.left, sum, set)) return true; if (set.Contains(sum - root.data)) { Console.WriteLine("Pair is found (" + (sum - root.data) + ", " + root.data + ")"); return true; } else set.Add(root.data); return findpairUtil(root.right, sum, set); } static void findPair(Node root, int sum) { HashSet<int> set = new HashSet<int>(); if (!findpairUtil(root, sum, set)) Console.Write("Pairs do not exit" + "\n"); } // Driver code public static void Main(String[] args) { Node root = null; root = insert(root, 15); root = insert(root, 10); root = insert(root, 20); root = insert(root, 8); root = insert(root, 12); root = insert(root, 16); root = insert(root, 25); root = insert(root, 10); int sum = 33; findPair(root, sum); }} // This code is contributed by Rajput-Ji <script> // JavaScript program to find a pair with// given sum using hashingclass Node { constructor() { this.data = 0; this.left = null; this.right = null; }};function NewNode(data){ var temp = new Node(); temp.data = data; temp.left = null; temp.right = null; return temp;}function insert(root, key){ if (root == null) return NewNode(key); if (key < root.data) root.left = insert(root.left, key); else root.right = insert(root.right, key); return root;}function findpairUtil(root, sum, set){ if (root == null) return false; if (findpairUtil(root.left, sum, set)) return true; if (set.has(sum - root.data)) { document.write("Pair is found (" + (sum - root.data) + ", " + root.data + ")<br>"); return true; } else set.add(root.data); return findpairUtil(root.right, sum, set);}function findPair(root, sum){ var set = new Set(); if (!findpairUtil(root, sum, set)) document.write("Pairs do not exit" + "\n");}// Driver codevar root = null;root = insert(root, 15);root = insert(root, 10);root = insert(root, 20);root = insert(root, 8);root = insert(root, 12);root = insert(root, 16);root = insert(root, 25);root = insert(root, 10);var sum = 33;findPair(root, sum); </script> Output: 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. Pair is found (8, 25) Time Complexity :O(n). Space Complexity: O(n) for call stack since using recursion Vikash Kumar 37 princiraj1992 Rajput-Ji rishabhjain259 rutvik_56 technophpfij Amazon Binary Search Tree Hash Amazon Hash Binary Search Tree Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 54, "s": 26, "text": "\n20 Jun, 2022" }, { "code": null, "e": 117, "s": 54, "text": "Given a BST and a sum, find if there is a pair with given sum." }, { "code": null, "e": 126, "s": 117, "text": "Example:" }, { "code": null, "e": 170, "s": 126, "text": "Input : sum = 28\n Root of below tree" }, { "code": null, "e": 202, "s": 170, "text": "Output : Pair is found (16, 12)" }, { "code": null, "e": 602, "s": 202, "text": "We have discussed different approaches to find a pair with given sum in below post.Find a pair with given sum in a Balanced BSTIn this post, hashing based solution is discussed. We traverse binary search tree by inorder way and insert node’s value into a set. Also check for any node, difference between given sum and node’s value in set, if it is found then pair exists otherwise it doesn’t exist. " }, { "code": null, "e": 606, "s": 602, "text": "C++" }, { "code": null, "e": 611, "s": 606, "text": "Java" }, { "code": null, "e": 619, "s": 611, "text": "Python3" }, { "code": null, "e": 622, "s": 619, "text": "C#" }, { "code": null, "e": 633, "s": 622, "text": "Javascript" }, { "code": "// CPP program to find a pair with// given sum using hashing#include <bits/stdc++.h>using namespace std; struct Node { int data; struct Node *left, *right;}; Node* NewNode(int data){ Node* temp = (Node*)malloc(sizeof(Node)); temp->data = data; temp->left = NULL; temp->right = NULL; return temp;} Node* insert(Node* root, int key){ if (root == NULL) return NewNode(key); if (key < root->data) root->left = insert(root->left, key); else root->right = insert(root->right, key); return root;} bool findpairUtil(Node* root, int sum, unordered_set<int>& set){ if (root == NULL) return false; if (findpairUtil(root->left, sum, set)) return true; if (set.find(sum - root->data) != set.end()) { cout << \"Pair is found (\" << sum - root->data << \", \" << root->data << \")\" << endl; return true; } else set.insert(root->data); return findpairUtil(root->right, sum, set);} void findPair(Node* root, int sum){ unordered_set<int> set; if (!findpairUtil(root, sum, set)) cout << \"Pairs do not exit\" << endl;} // Driver codeint main(){ Node* root = NULL; root = insert(root, 15); root = insert(root, 10); root = insert(root, 20); root = insert(root, 8); root = insert(root, 12); root = insert(root, 16); root = insert(root, 25); root = insert(root, 10); int sum = 33; findPair(root, sum); return 0;}", "e": 2106, "s": 633, "text": null }, { "code": "// JAVA program to find a pair with// given sum using hashing import java.util.*; class GFG { static class Node { int data; Node left, right; }; static Node NewNode(int data) { Node temp = new Node(); temp.data = data; temp.left = null; temp.right = null; return temp; } static Node insert(Node root, int key) { if (root == null) return NewNode(key); if (key < root.data) root.left = insert(root.left, key); else root.right = insert(root.right, key); return root; } static boolean findpairUtil(Node root, int sum, HashSet<Integer> set) { if (root == null) return false; if (findpairUtil(root.left, sum, set)) return true; if (set.contains(sum - root.data)) { System.out.println(\"Pair is found (\" + (sum - root.data) + \", \" + root.data + \")\"); return true; } else set.add(root.data); return findpairUtil(root.right, sum, set); } static void findPair(Node root, int sum) { HashSet<Integer> set = new HashSet<Integer>(); if (!findpairUtil(root, sum, set)) System.out.print(\"Pairs do not exit\" + \"\\n\"); } // Driver code public static void main(String[] args) { Node root = null; root = insert(root, 15); root = insert(root, 10); root = insert(root, 20); root = insert(root, 8); root = insert(root, 12); root = insert(root, 16); root = insert(root, 25); root = insert(root, 10); int sum = 33; findPair(root, sum); }} // This code is contributed by PrinciRaj1992", "e": 3955, "s": 2106, "text": null }, { "code": "# Python3 program to find a pair with# given sum using hashingimport sysimport math class Node: def __init__(self, data): self.data = data self.left = None self.right = None def insert(root, data): if root is None: return Node(data) if(data < root.data): root.left = insert(root.left, data) if(data > root.data): root.right = insert(root.right, data) return root def findPairUtil(root, summ, unsorted_set): if root is None: return False if findPairUtil(root.left, summ, unsorted_set): return True if unsorted_set and (summ-root.data) in unsorted_set: print(\"Pair is Found ({},{})\".format(summ-root.data, root.data)) return True else: unsorted_set.add(root.data) return findPairUtil(root.right, summ, unsorted_set) def findPair(root, summ): unsorted_set = set() if(not findPairUtil(root, summ, unsorted_set)): print(\"Pair do not exist!\") # Driver codeif __name__ == '__main__': root = None root = insert(root, 15) root = insert(root, 10) root = insert(root, 20) root = insert(root, 8) root = insert(root, 12) root = insert(root, 16) root = insert(root, 25) root = insert(root, 10) summ = 33 findPair(root, summ) # This code is contributed by Vikash Kumar 37", "e": 5271, "s": 3955, "text": null }, { "code": "// C# program to find a pair with// given sum using hashingusing System;using System.Collections.Generic; class GFG { class Node { public int data; public Node left, right; }; static Node NewNode(int data) { Node temp = new Node(); temp.data = data; temp.left = null; temp.right = null; return temp; } static Node insert(Node root, int key) { if (root == null) return NewNode(key); if (key < root.data) root.left = insert(root.left, key); else root.right = insert(root.right, key); return root; } static bool findpairUtil(Node root, int sum, HashSet<int> set) { if (root == null) return false; if (findpairUtil(root.left, sum, set)) return true; if (set.Contains(sum - root.data)) { Console.WriteLine(\"Pair is found (\" + (sum - root.data) + \", \" + root.data + \")\"); return true; } else set.Add(root.data); return findpairUtil(root.right, sum, set); } static void findPair(Node root, int sum) { HashSet<int> set = new HashSet<int>(); if (!findpairUtil(root, sum, set)) Console.Write(\"Pairs do not exit\" + \"\\n\"); } // Driver code public static void Main(String[] args) { Node root = null; root = insert(root, 15); root = insert(root, 10); root = insert(root, 20); root = insert(root, 8); root = insert(root, 12); root = insert(root, 16); root = insert(root, 25); root = insert(root, 10); int sum = 33; findPair(root, sum); }} // This code is contributed by Rajput-Ji", "e": 7120, "s": 5271, "text": null }, { "code": "<script> // JavaScript program to find a pair with// given sum using hashingclass Node { constructor() { this.data = 0; this.left = null; this.right = null; }};function NewNode(data){ var temp = new Node(); temp.data = data; temp.left = null; temp.right = null; return temp;}function insert(root, key){ if (root == null) return NewNode(key); if (key < root.data) root.left = insert(root.left, key); else root.right = insert(root.right, key); return root;}function findpairUtil(root, sum, set){ if (root == null) return false; if (findpairUtil(root.left, sum, set)) return true; if (set.has(sum - root.data)) { document.write(\"Pair is found (\" + (sum - root.data) + \", \" + root.data + \")<br>\"); return true; } else set.add(root.data); return findpairUtil(root.right, sum, set);}function findPair(root, sum){ var set = new Set(); if (!findpairUtil(root, sum, set)) document.write(\"Pairs do not exit\" + \"\\n\");}// Driver codevar root = null;root = insert(root, 15);root = insert(root, 10);root = insert(root, 20);root = insert(root, 8);root = insert(root, 12);root = insert(root, 16);root = insert(root, 25);root = insert(root, 10);var sum = 33;findPair(root, sum); </script>", "e": 8507, "s": 7120, "text": null }, { "code": null, "e": 8516, "s": 8507, "text": "Output: " }, { "code": null, "e": 8525, "s": 8516, "text": "Chapters" }, { "code": null, "e": 8552, "s": 8525, "text": "descriptions off, selected" }, { "code": null, "e": 8602, "s": 8552, "text": "captions settings, opens captions settings dialog" }, { "code": null, "e": 8625, "s": 8602, "text": "captions off, selected" }, { "code": null, "e": 8633, "s": 8625, "text": "English" }, { "code": null, "e": 8657, "s": 8633, "text": "This is a modal window." }, { "code": null, "e": 8726, "s": 8657, "text": "Beginning of dialog window. Escape will cancel and close the window." }, { "code": null, "e": 8748, "s": 8726, "text": "End of dialog window." }, { "code": null, "e": 8770, "s": 8748, "text": "Pair is found (8, 25)" }, { "code": null, "e": 8793, "s": 8770, "text": "Time Complexity :O(n)." }, { "code": null, "e": 8853, "s": 8793, "text": "Space Complexity: O(n) for call stack since using recursion" }, { "code": null, "e": 8871, "s": 8855, "text": "Vikash Kumar 37" }, { "code": null, "e": 8885, "s": 8871, "text": "princiraj1992" }, { "code": null, "e": 8895, "s": 8885, "text": "Rajput-Ji" }, { "code": null, "e": 8910, "s": 8895, "text": "rishabhjain259" }, { "code": null, "e": 8920, "s": 8910, "text": "rutvik_56" }, { "code": null, "e": 8933, "s": 8920, "text": "technophpfij" }, { "code": null, "e": 8940, "s": 8933, "text": "Amazon" }, { "code": null, "e": 8959, "s": 8940, "text": "Binary Search Tree" }, { "code": null, "e": 8964, "s": 8959, "text": "Hash" }, { "code": null, "e": 8971, "s": 8964, "text": "Amazon" }, { "code": null, "e": 8976, "s": 8971, "text": "Hash" }, { "code": null, "e": 8995, "s": 8976, "text": "Binary Search Tree" } ]
Replace all occurrences of string AB with C without using extra space
08 Jul, 2022 Given a string str that may contain one more occurrences of “AB”. Replace all occurrences of “AB” with “C” in str. Examples: Input : str = "helloABworld" Output : str = "helloCworld" Input : str = "fghABsdfABysu" Output : str = "fghCsdfCysu" A simple solution is to find all occurrences of “AB”. For every occurrence, replace it with C and move all characters one position back. Implementation: C++ Java Python3 C# PHP Javascript // C++ program to replace all occurrences of "AB"// with "C"#include <bits/stdc++.h> void translate(char* str){ if (str[0] == '') return; // Start traversing from second character for (int i=1; str[i] != ''; i++) { // If previous character is 'A' and // current character is 'B" if (str[i-1]=='A' && str[i]=='B') { // Replace previous character with // 'C' and move all subsequent // characters one position back str[i-1] = 'C'; for (int j=i; str[j]!=''; j++) str[j] = str[j+1]; } } return;} // Driver codeint main(){ char str[] = "helloABworldABGfG"; translate(str); printf("The modified string is :\n"); printf("%s", str);} // Java program to replace all// occurrences of "AB" with "C"import java.io.*; class GFG { static void translate(char str[]) { // Start traversing from second character for (int i = 1; i < str.length; i++) { // If previous character is 'A' and // current character is 'B" if (str[i - 1] == 'A' && str[i] == 'B') { // Replace previous character with // 'C' and move all subsequent // characters one position back str[i - 1] = 'C'; int j; for (j = i; j < str.length - 1; j++) str[j] = str[j + 1]; str[j] = ' '; } } return; } // Driver code public static void main(String args[]) { String st = "helloABworldABGfG"; char str[] = st.toCharArray(); translate(str); System.out.println("The modified string is :"); System.out.println(str); }} // This code is contributed by Nikita Tiwari. # Python 3 program to replace all# occurrences of "AB" with "C" def translate(st) : # Start traversing from second character for i in range(1, len(st)) : # If previous character is 'A' # and current character is 'B" if (st[i - 1] == 'A' and st[i] == 'B') : # Replace previous character with # 'C' and move all subsequent # characters one position back st[i - 1] = 'C' for j in range(i, len(st) - 1) : st[j] = st[j + 1] st[len(st) - 1] = ' ' return # Driver codest = list("helloABworldABGfG")translate(st) print("The modified string is :")print(''.join(st)) # This code is contributed by Nikita Tiwari. // C# program to replace all// occurrences of "AB" with "C"using System; class GFG { static void translate(char []str) { // Start traversing from second character for (int i = 1; i < str.Length; i++) { // If previous character is 'A' and // current character is 'B" if (str[i - 1] == 'A' && str[i] == 'B') { // Replace previous character with // 'C' and move all subsequent // characters one position back str[i - 1] = 'C'; int j; for (j = i; j < str.Length - 1; j++) str[j] = str[j + 1]; str[j] = ' '; } } return; } // Driver code public static void Main() { String st = "helloABworldABGfG"; char []str = st.ToCharArray(); translate(str); Console.WriteLine("The modified string is :"); Console.Write(str); }} // This code is contributed by Nitin Mittal. <?php// PHP program to replace all// occurrences of "AB" with "C" function translate(&$str){ if ($str[0] == '') return; // Start traversing from second character for ($i = 1; $i < strlen($str); $i++) { // If previous character is 'A' and // current character is 'B" if ($str[$i - 1] == 'A' && $str[$i] == 'B') { // Replace previous character with // 'C' and move all subsequent // characters one position back $str[$i - 1] = 'C'; for ($j = $i; $j < strlen($str) ; $j++) $str[$j] = $str[$j + 1]; } } return;} // Driver code$str = "helloABworldABGfG";translate($str);echo "The modified string is :\n";echo $str; // This code is contributed// by ChitraNayal?> <script> // Javascript program to replace all// occurrences of "AB" with "C"function translate(str){ // Start traversing from second character for(let i = 1; i < str.length; i++) { // If previous character is 'A' and // current character is 'B" if (str[i - 1] == 'A' && str[i] == 'B') { // Replace previous character with // 'C' and move all subsequent // characters one position back str[i - 1] = 'C'; let j; for(j = i; j < str.length - 1; j++) str[j] = str[j + 1]; str[j] = ' '; } } return;} // Driver codelet st = "helloABworldABGfG";let str = st.split("");translate(str); document.write("The modified string is :<br>");document.write(str.join("")); // This code is contributed by avanitrachhadiya2155 </script> Output : The modified string is : helloCworldCGfG Time Complexity : O(n2) Auxiliary Space : O(1) An efficient solution is to keep track of two indexes, one for modified string (i in below code) and other for original string (j in below code). If we find “AB” at current index j, we increment j by 2 and i by 1. Otherwise, we increment both and copy character from j to i. Below is implementation of above idea. C++ Java Python3 C# Javascript // Efficient C++ program to replace all occurrences// of "AB" with "C"#include <bits/stdc++.h>using namespace std; void translate(string &str){ int len = str.size(); if (len < 2) return; // Index in modified string int i = 0; // Index in original string int j = 0; // Traverse string while (j < len - 1) { // Replace occurrence of "AB" with "C" if (str[j] == 'A' && str[j + 1] == 'B') { // Increment j by 2 j = j + 2; str[i++] = 'C'; continue; } str[i++] = str[j++]; } if (j == len - 1) str[i++] = str[j]; // add a null character to terminate string str[i] = ' '; str[len - 1] = ' ';} // Driver codeint main(){ string str = "helloABworldABGfG"; translate(str); cout << "The modified string is:" << endl << str;} // Efficient Java program to replace// all occurrences of "AB" with "C"import java.io.*; class GFG { static void translate(char str[]) { int len = str.length; if (len < 2) return; // Index in modified string int i = 0; // Index in original string int j = 0; // Traverse string while (j < len - 1) { // Replace occurrence of "AB" with "C" if (str[j] == 'A' && str[j + 1] == 'B') { // Increment j by 2 j = j + 2; str[i++] = 'C'; continue; } str[i++] = str[j++]; } if (j == len - 1) str[i++] = str[j]; // add a null character to terminate string str[i] = ' '; str[len - 1]=' '; } // Driver code public static void main(String args[]) { String st="helloABworldABGfG"; char str[] = st.toCharArray(); translate(str); System.out.println("The modified string is :"); System.out.println(str); }} // This code is contributed// by Nikita Tiwari. # Python 3 program to replace all# occurrences of "AB" with "C" def translate(st) : l = len(st) if (l < 2) : return i = 0 # Index in modified string j = 0 # Index in original string # Traverse string while (j < l - 1) : # Replace occurrence of "AB" with "C" if (st[j] == 'A' and st[j + 1] == 'B') : # Increment j by 2 j += 2 st[i] = 'C' i += 1 continue st[i] = st[j] i += 1 j += 1 if (j == l - 1) : st[i] = st[j] i += 1 # add a null character to # terminate string st[i] = ' ' st[l-1] = ' ' # Driver codest = list("helloABworldABGfG")translate(st) print("The modified string is :")print(''.join(st)) # This code is contributed by Nikita Tiwari. // Efficient C# program to replace// all occurrences of "AB" with "C"using System; class GFG { static void translate(char []str) { int len = str.Length; if (len < 2) return; // Index in modified string int i = 0; // Index in original string int j = 0; // Traverse string while (j < len - 1) { // Replace occurrence of "AB" with "C" if (str[j] == 'A' && str[j + 1] == 'B') { // Increment j by 2 j = j + 2; str[i++] = 'C'; continue; } str[i++] = str[j++]; } if (j == len - 1) str[i++] = str[j]; // add a null character to // terminate string str[i] = ' '; str[len - 1]=' '; } // Driver code public static void Main() { String st="helloABworldABGfG"; char []str = st.ToCharArray(); translate(str); Console.Write("The modified string is :"); Console.Write(str); }} // This code is contributed by nitin mittal. <script> // Efficient javascript program to replace// all occurrences of "AB" with "C"function translate(str){ var len = str.length; if (len < 2) return; // Index in modified string var i = 0; // Index in original string var j = 0; // Traverse string while (j < len - 1) { // Replace occurrence of "AB" with "C" if (str[j] == 'A' && str[j + 1] == 'B') { // Increment j by 2 j = j + 2; let firstPart = str.substr(0, i); let lastPart = str.substr(i + 1); str = firstPart + 'C' + lastPart; i += 1; continue; } let firstPart = str.substr(0, i); let lastPart = str.substr(i + 1); str = firstPart + str[j] + lastPart; i += 1; j += 1; } if (j == len - 1) { let firstPart = str.substr(0, i); let lastPart = str.substr(i + 1); str = firstPart + str[j] + lastPart; i += 1; } // Add a null character to terminate string let firstPart = str.substr(0, i); let lastPart = str.substr(i + 1); str = firstPart + ' ' + lastPart; firstPart = str.substr(0, len - 1); lastPart = str.substr(len); str = firstPart + ' ' + lastPart; // str[len - 1]=' '; return str;} // Driver codevar str = "helloABworldABGfG";document.write("The modified string is :" + "<br>" + translate(str)); // This code is contributed by ipg2016107 </script> The modified string is: helloCworldCGfG Time Complexity : O(n) Auxiliary Space : O(1) This article is contributed by Roshni Agarwal. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks. nitin mittal ukasp shubham_singh avanitrachhadiya2155 ipg2016107 atulnitk20081 hardikkoriintern Pattern Searching Strings Strings Pattern Searching Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 52, "s": 24, "text": "\n08 Jul, 2022" }, { "code": null, "e": 167, "s": 52, "text": "Given a string str that may contain one more occurrences of “AB”. Replace all occurrences of “AB” with “C” in str." }, { "code": null, "e": 178, "s": 167, "text": "Examples: " }, { "code": null, "e": 298, "s": 178, "text": "Input : str = \"helloABworld\"\nOutput : str = \"helloCworld\"\n\nInput : str = \"fghABsdfABysu\"\nOutput : str = \"fghCsdfCysu\"" }, { "code": null, "e": 437, "s": 298, "text": "A simple solution is to find all occurrences of “AB”. For every occurrence, replace it with C and move all characters one position back. " }, { "code": null, "e": 453, "s": 437, "text": "Implementation:" }, { "code": null, "e": 457, "s": 453, "text": "C++" }, { "code": null, "e": 462, "s": 457, "text": "Java" }, { "code": null, "e": 470, "s": 462, "text": "Python3" }, { "code": null, "e": 473, "s": 470, "text": "C#" }, { "code": null, "e": 477, "s": 473, "text": "PHP" }, { "code": null, "e": 488, "s": 477, "text": "Javascript" }, { "code": "// C++ program to replace all occurrences of \"AB\"// with \"C\"#include <bits/stdc++.h> void translate(char* str){ if (str[0] == '') return; // Start traversing from second character for (int i=1; str[i] != ''; i++) { // If previous character is 'A' and // current character is 'B\" if (str[i-1]=='A' && str[i]=='B') { // Replace previous character with // 'C' and move all subsequent // characters one position back str[i-1] = 'C'; for (int j=i; str[j]!=''; j++) str[j] = str[j+1]; } } return;} // Driver codeint main(){ char str[] = \"helloABworldABGfG\"; translate(str); printf(\"The modified string is :\\n\"); printf(\"%s\", str);}", "e": 1257, "s": 488, "text": null }, { "code": "// Java program to replace all// occurrences of \"AB\" with \"C\"import java.io.*; class GFG { static void translate(char str[]) { // Start traversing from second character for (int i = 1; i < str.length; i++) { // If previous character is 'A' and // current character is 'B\" if (str[i - 1] == 'A' && str[i] == 'B') { // Replace previous character with // 'C' and move all subsequent // characters one position back str[i - 1] = 'C'; int j; for (j = i; j < str.length - 1; j++) str[j] = str[j + 1]; str[j] = ' '; } } return; } // Driver code public static void main(String args[]) { String st = \"helloABworldABGfG\"; char str[] = st.toCharArray(); translate(str); System.out.println(\"The modified string is :\"); System.out.println(str); }} // This code is contributed by Nikita Tiwari.", "e": 2336, "s": 1257, "text": null }, { "code": "# Python 3 program to replace all# occurrences of \"AB\" with \"C\" def translate(st) : # Start traversing from second character for i in range(1, len(st)) : # If previous character is 'A' # and current character is 'B\" if (st[i - 1] == 'A' and st[i] == 'B') : # Replace previous character with # 'C' and move all subsequent # characters one position back st[i - 1] = 'C' for j in range(i, len(st) - 1) : st[j] = st[j + 1] st[len(st) - 1] = ' ' return # Driver codest = list(\"helloABworldABGfG\")translate(st) print(\"The modified string is :\")print(''.join(st)) # This code is contributed by Nikita Tiwari.", "e": 3123, "s": 2336, "text": null }, { "code": "// C# program to replace all// occurrences of \"AB\" with \"C\"using System; class GFG { static void translate(char []str) { // Start traversing from second character for (int i = 1; i < str.Length; i++) { // If previous character is 'A' and // current character is 'B\" if (str[i - 1] == 'A' && str[i] == 'B') { // Replace previous character with // 'C' and move all subsequent // characters one position back str[i - 1] = 'C'; int j; for (j = i; j < str.Length - 1; j++) str[j] = str[j + 1]; str[j] = ' '; } } return; } // Driver code public static void Main() { String st = \"helloABworldABGfG\"; char []str = st.ToCharArray(); translate(str); Console.WriteLine(\"The modified string is :\"); Console.Write(str); }} // This code is contributed by Nitin Mittal.", "e": 4185, "s": 3123, "text": null }, { "code": "<?php// PHP program to replace all// occurrences of \"AB\" with \"C\" function translate(&$str){ if ($str[0] == '') return; // Start traversing from second character for ($i = 1; $i < strlen($str); $i++) { // If previous character is 'A' and // current character is 'B\" if ($str[$i - 1] == 'A' && $str[$i] == 'B') { // Replace previous character with // 'C' and move all subsequent // characters one position back $str[$i - 1] = 'C'; for ($j = $i; $j < strlen($str) ; $j++) $str[$j] = $str[$j + 1]; } } return;} // Driver code$str = \"helloABworldABGfG\";translate($str);echo \"The modified string is :\\n\";echo $str; // This code is contributed// by ChitraNayal?>", "e": 4973, "s": 4185, "text": null }, { "code": "<script> // Javascript program to replace all// occurrences of \"AB\" with \"C\"function translate(str){ // Start traversing from second character for(let i = 1; i < str.length; i++) { // If previous character is 'A' and // current character is 'B\" if (str[i - 1] == 'A' && str[i] == 'B') { // Replace previous character with // 'C' and move all subsequent // characters one position back str[i - 1] = 'C'; let j; for(j = i; j < str.length - 1; j++) str[j] = str[j + 1]; str[j] = ' '; } } return;} // Driver codelet st = \"helloABworldABGfG\";let str = st.split(\"\");translate(str); document.write(\"The modified string is :<br>\");document.write(str.join(\"\")); // This code is contributed by avanitrachhadiya2155 </script>", "e": 5887, "s": 4973, "text": null }, { "code": null, "e": 5897, "s": 5887, "text": "Output : " }, { "code": null, "e": 5938, "s": 5897, "text": "The modified string is :\nhelloCworldCGfG" }, { "code": null, "e": 5985, "s": 5938, "text": "Time Complexity : O(n2) Auxiliary Space : O(1)" }, { "code": null, "e": 6261, "s": 5985, "text": "An efficient solution is to keep track of two indexes, one for modified string (i in below code) and other for original string (j in below code). If we find “AB” at current index j, we increment j by 2 and i by 1. Otherwise, we increment both and copy character from j to i. " }, { "code": null, "e": 6302, "s": 6261, "text": "Below is implementation of above idea. " }, { "code": null, "e": 6306, "s": 6302, "text": "C++" }, { "code": null, "e": 6311, "s": 6306, "text": "Java" }, { "code": null, "e": 6319, "s": 6311, "text": "Python3" }, { "code": null, "e": 6322, "s": 6319, "text": "C#" }, { "code": null, "e": 6333, "s": 6322, "text": "Javascript" }, { "code": "// Efficient C++ program to replace all occurrences// of \"AB\" with \"C\"#include <bits/stdc++.h>using namespace std; void translate(string &str){ int len = str.size(); if (len < 2) return; // Index in modified string int i = 0; // Index in original string int j = 0; // Traverse string while (j < len - 1) { // Replace occurrence of \"AB\" with \"C\" if (str[j] == 'A' && str[j + 1] == 'B') { // Increment j by 2 j = j + 2; str[i++] = 'C'; continue; } str[i++] = str[j++]; } if (j == len - 1) str[i++] = str[j]; // add a null character to terminate string str[i] = ' '; str[len - 1] = ' ';} // Driver codeint main(){ string str = \"helloABworldABGfG\"; translate(str); cout << \"The modified string is:\" << endl << str;}", "e": 7184, "s": 6333, "text": null }, { "code": "// Efficient Java program to replace// all occurrences of \"AB\" with \"C\"import java.io.*; class GFG { static void translate(char str[]) { int len = str.length; if (len < 2) return; // Index in modified string int i = 0; // Index in original string int j = 0; // Traverse string while (j < len - 1) { // Replace occurrence of \"AB\" with \"C\" if (str[j] == 'A' && str[j + 1] == 'B') { // Increment j by 2 j = j + 2; str[i++] = 'C'; continue; } str[i++] = str[j++]; } if (j == len - 1) str[i++] = str[j]; // add a null character to terminate string str[i] = ' '; str[len - 1]=' '; } // Driver code public static void main(String args[]) { String st=\"helloABworldABGfG\"; char str[] = st.toCharArray(); translate(str); System.out.println(\"The modified string is :\"); System.out.println(str); }} // This code is contributed// by Nikita Tiwari.", "e": 8342, "s": 7184, "text": null }, { "code": "# Python 3 program to replace all# occurrences of \"AB\" with \"C\" def translate(st) : l = len(st) if (l < 2) : return i = 0 # Index in modified string j = 0 # Index in original string # Traverse string while (j < l - 1) : # Replace occurrence of \"AB\" with \"C\" if (st[j] == 'A' and st[j + 1] == 'B') : # Increment j by 2 j += 2 st[i] = 'C' i += 1 continue st[i] = st[j] i += 1 j += 1 if (j == l - 1) : st[i] = st[j] i += 1 # add a null character to # terminate string st[i] = ' ' st[l-1] = ' ' # Driver codest = list(\"helloABworldABGfG\")translate(st) print(\"The modified string is :\")print(''.join(st)) # This code is contributed by Nikita Tiwari.", "e": 9176, "s": 8342, "text": null }, { "code": "// Efficient C# program to replace// all occurrences of \"AB\" with \"C\"using System; class GFG { static void translate(char []str) { int len = str.Length; if (len < 2) return; // Index in modified string int i = 0; // Index in original string int j = 0; // Traverse string while (j < len - 1) { // Replace occurrence of \"AB\" with \"C\" if (str[j] == 'A' && str[j + 1] == 'B') { // Increment j by 2 j = j + 2; str[i++] = 'C'; continue; } str[i++] = str[j++]; } if (j == len - 1) str[i++] = str[j]; // add a null character to // terminate string str[i] = ' '; str[len - 1]=' '; } // Driver code public static void Main() { String st=\"helloABworldABGfG\"; char []str = st.ToCharArray(); translate(str); Console.Write(\"The modified string is :\"); Console.Write(str); }} // This code is contributed by nitin mittal.", "e": 10332, "s": 9176, "text": null }, { "code": "<script> // Efficient javascript program to replace// all occurrences of \"AB\" with \"C\"function translate(str){ var len = str.length; if (len < 2) return; // Index in modified string var i = 0; // Index in original string var j = 0; // Traverse string while (j < len - 1) { // Replace occurrence of \"AB\" with \"C\" if (str[j] == 'A' && str[j + 1] == 'B') { // Increment j by 2 j = j + 2; let firstPart = str.substr(0, i); let lastPart = str.substr(i + 1); str = firstPart + 'C' + lastPart; i += 1; continue; } let firstPart = str.substr(0, i); let lastPart = str.substr(i + 1); str = firstPart + str[j] + lastPart; i += 1; j += 1; } if (j == len - 1) { let firstPart = str.substr(0, i); let lastPart = str.substr(i + 1); str = firstPart + str[j] + lastPart; i += 1; } // Add a null character to terminate string let firstPart = str.substr(0, i); let lastPart = str.substr(i + 1); str = firstPart + ' ' + lastPart; firstPart = str.substr(0, len - 1); lastPart = str.substr(len); str = firstPart + ' ' + lastPart; // str[len - 1]=' '; return str;} // Driver codevar str = \"helloABworldABGfG\";document.write(\"The modified string is :\" + \"<br>\" + translate(str)); // This code is contributed by ipg2016107 </script>", "e": 11844, "s": 10332, "text": null }, { "code": null, "e": 11886, "s": 11844, "text": "The modified string is:\nhelloCworldCGfG " }, { "code": null, "e": 11932, "s": 11886, "text": "Time Complexity : O(n) Auxiliary Space : O(1)" }, { "code": null, "e": 12229, "s": 11932, "text": "This article is contributed by Roshni Agarwal. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks." }, { "code": null, "e": 12242, "s": 12229, "text": "nitin mittal" }, { "code": null, "e": 12248, "s": 12242, "text": "ukasp" }, { "code": null, "e": 12262, "s": 12248, "text": "shubham_singh" }, { "code": null, "e": 12283, "s": 12262, "text": "avanitrachhadiya2155" }, { "code": null, "e": 12294, "s": 12283, "text": "ipg2016107" }, { "code": null, "e": 12308, "s": 12294, "text": "atulnitk20081" }, { "code": null, "e": 12325, "s": 12308, "text": "hardikkoriintern" }, { "code": null, "e": 12343, "s": 12325, "text": "Pattern Searching" }, { "code": null, "e": 12351, "s": 12343, "text": "Strings" }, { "code": null, "e": 12359, "s": 12351, "text": "Strings" }, { "code": null, "e": 12377, "s": 12359, "text": "Pattern Searching" } ]
Maximize count of distinct elements in a subsequence of size K in given array
14 Dec, 2021 Given an array arr[] of N integers and an integer K, the task is to find the maximum count of distinct elements over all the subsequences of K integers. Example: Input: arr[]={1, 1, 2, 2}, K=3Output: 2Explanation: The subsequence {1, 1, 2} has 3 integers and the number of distinct integers in it are 2 which is the maximum possible. Other possible subsequence is {1, 2, 2}. Input: arr[]={1, 2, 3, 4}, K=3Output: 3 Approach: The given problem can be solved using a greedy approach using the observation that the required answer is the minimum of the count of the unique elements in the given array or K. Now, to solve this problem, follow the below steps: Create a set S, which stores the distinct integers present in the array arr[].Traverse the array arr[] and insert each number in the set S.Return the minimum of K and the size of S which is the required answer. Create a set S, which stores the distinct integers present in the array arr[]. Traverse the array arr[] and insert each number in the set S. Return the minimum of K and the size of S which is the required answer. Below is the implementation of the above approach: C++ Java Python3 C# Javascript // C++ code for the above approach#include <bits/stdc++.h>using namespace std; // Function to find count of maximum// distinct elements in a subsequence// of size K of the given array arr[]int maxUnique(vector<int>& arr, int K){ // Set data structure to // store the unique elements unordered_set<int> S; // Loop to traverse the given array for (auto x : arr) { // Insert into the set S.insert(x); } // Returning the minimum out of the two return min(K, (int)S.size());} // Driver Codeint main(){ vector<int> arr = { 1, 1, 2, 2 }; int K = 3; cout << maxUnique(arr, K);} // Java code for the above approachimport java.util.*; class GFG{ // Function to find count of maximum// distinct elements in a subsequence// of size K of the given array arr[]static int maxUnique(int []arr, int K){ // Set data structure to // store the unique elements HashSet<Integer> S = new HashSet<Integer>(); // Loop to traverse the given array for (int x : arr) { // Insert into the set S.add(x); } // Returning the minimum out of the two return Math.min(K, (int)S.size());} // Driver Codepublic static void main(String[] args){ int[] arr = { 1, 1, 2, 2 }; int K = 3; System.out.print(maxUnique(arr, K));}} // This code is contributed by 29AjayKumar # Python Program to implement# the above approach # Function to find count of maximum# distinct elements in a subsequence# of size K of the given array arr[]def maxUnique(arr, K): # Set data structure to # store the unique elements S = set() # Loop to traverse the given array for x in arr: # Insert into the set S.add(x) # Returning the minimum out of the two return min(K, len(S)) # Driver Codearr = [1, 1, 2, 2]K = 3print(maxUnique(arr, K)) # This code is contributed by gfgking // C# implementation for the above approachusing System;using System.Collections;using System.Collections.Generic; class GFG{ // Function to find count of maximum// distinct elements in a subsequence// of size K of the given array arr[]static int maxUnique(int []arr, int K){ // Set data structure to // store the unique elements HashSet<int> S = new HashSet<int>(); // Loop to traverse the given array foreach (int x in arr) { // Insert into the set S.Add(x); } // Returning the minimum out of the two return Math.Min(K, (int)S.Count);} // Driver Codepublic static void Main(){ int []arr = { 1, 1, 2, 2 }; int K = 3; Console.Write(maxUnique(arr, K));}} // This code is contributed by Samim Hossain Mondal. <script> // JavaScript Program to implement // the above approach // Function to find count of maximum // distinct elements in a subsequence // of size K of the given array arr[] function maxUnique(arr, K) { // Set data structure to // store the unique elements let S = new Set(); // Loop to traverse the given array for (let x of arr) { // Insert into the set S.add(x); } // Returning the minimum out of the two return Math.min(K, S.size); } // Driver Code let arr = [1, 1, 2, 2]; let K = 3; document.write(maxUnique(arr, K)); // This code is contributed by Potta Lokesh </script> 2 Time Complexity: O(N)Auxiliary Space: O(N) lokeshpotta20 samim2000 29AjayKumar gfgking subsequence Arrays Greedy Mathematical Arrays Greedy Mathematical Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 54, "s": 26, "text": "\n14 Dec, 2021" }, { "code": null, "e": 207, "s": 54, "text": "Given an array arr[] of N integers and an integer K, the task is to find the maximum count of distinct elements over all the subsequences of K integers." }, { "code": null, "e": 216, "s": 207, "text": "Example:" }, { "code": null, "e": 429, "s": 216, "text": "Input: arr[]={1, 1, 2, 2}, K=3Output: 2Explanation: The subsequence {1, 1, 2} has 3 integers and the number of distinct integers in it are 2 which is the maximum possible. Other possible subsequence is {1, 2, 2}." }, { "code": null, "e": 469, "s": 429, "text": "Input: arr[]={1, 2, 3, 4}, K=3Output: 3" }, { "code": null, "e": 710, "s": 469, "text": "Approach: The given problem can be solved using a greedy approach using the observation that the required answer is the minimum of the count of the unique elements in the given array or K. Now, to solve this problem, follow the below steps:" }, { "code": null, "e": 921, "s": 710, "text": "Create a set S, which stores the distinct integers present in the array arr[].Traverse the array arr[] and insert each number in the set S.Return the minimum of K and the size of S which is the required answer." }, { "code": null, "e": 1000, "s": 921, "text": "Create a set S, which stores the distinct integers present in the array arr[]." }, { "code": null, "e": 1062, "s": 1000, "text": "Traverse the array arr[] and insert each number in the set S." }, { "code": null, "e": 1134, "s": 1062, "text": "Return the minimum of K and the size of S which is the required answer." }, { "code": null, "e": 1185, "s": 1134, "text": "Below is the implementation of the above approach:" }, { "code": null, "e": 1189, "s": 1185, "text": "C++" }, { "code": null, "e": 1194, "s": 1189, "text": "Java" }, { "code": null, "e": 1202, "s": 1194, "text": "Python3" }, { "code": null, "e": 1205, "s": 1202, "text": "C#" }, { "code": null, "e": 1216, "s": 1205, "text": "Javascript" }, { "code": "// C++ code for the above approach#include <bits/stdc++.h>using namespace std; // Function to find count of maximum// distinct elements in a subsequence// of size K of the given array arr[]int maxUnique(vector<int>& arr, int K){ // Set data structure to // store the unique elements unordered_set<int> S; // Loop to traverse the given array for (auto x : arr) { // Insert into the set S.insert(x); } // Returning the minimum out of the two return min(K, (int)S.size());} // Driver Codeint main(){ vector<int> arr = { 1, 1, 2, 2 }; int K = 3; cout << maxUnique(arr, K);}", "e": 1836, "s": 1216, "text": null }, { "code": "// Java code for the above approachimport java.util.*; class GFG{ // Function to find count of maximum// distinct elements in a subsequence// of size K of the given array arr[]static int maxUnique(int []arr, int K){ // Set data structure to // store the unique elements HashSet<Integer> S = new HashSet<Integer>(); // Loop to traverse the given array for (int x : arr) { // Insert into the set S.add(x); } // Returning the minimum out of the two return Math.min(K, (int)S.size());} // Driver Codepublic static void main(String[] args){ int[] arr = { 1, 1, 2, 2 }; int K = 3; System.out.print(maxUnique(arr, K));}} // This code is contributed by 29AjayKumar", "e": 2546, "s": 1836, "text": null }, { "code": "# Python Program to implement# the above approach # Function to find count of maximum# distinct elements in a subsequence# of size K of the given array arr[]def maxUnique(arr, K): # Set data structure to # store the unique elements S = set() # Loop to traverse the given array for x in arr: # Insert into the set S.add(x) # Returning the minimum out of the two return min(K, len(S)) # Driver Codearr = [1, 1, 2, 2]K = 3print(maxUnique(arr, K)) # This code is contributed by gfgking", "e": 3067, "s": 2546, "text": null }, { "code": "// C# implementation for the above approachusing System;using System.Collections;using System.Collections.Generic; class GFG{ // Function to find count of maximum// distinct elements in a subsequence// of size K of the given array arr[]static int maxUnique(int []arr, int K){ // Set data structure to // store the unique elements HashSet<int> S = new HashSet<int>(); // Loop to traverse the given array foreach (int x in arr) { // Insert into the set S.Add(x); } // Returning the minimum out of the two return Math.Min(K, (int)S.Count);} // Driver Codepublic static void Main(){ int []arr = { 1, 1, 2, 2 }; int K = 3; Console.Write(maxUnique(arr, K));}} // This code is contributed by Samim Hossain Mondal.", "e": 3824, "s": 3067, "text": null }, { "code": "<script> // JavaScript Program to implement // the above approach // Function to find count of maximum // distinct elements in a subsequence // of size K of the given array arr[] function maxUnique(arr, K) { // Set data structure to // store the unique elements let S = new Set(); // Loop to traverse the given array for (let x of arr) { // Insert into the set S.add(x); } // Returning the minimum out of the two return Math.min(K, S.size); } // Driver Code let arr = [1, 1, 2, 2]; let K = 3; document.write(maxUnique(arr, K)); // This code is contributed by Potta Lokesh </script>", "e": 4555, "s": 3824, "text": null }, { "code": null, "e": 4560, "s": 4558, "text": "2" }, { "code": null, "e": 4605, "s": 4562, "text": "Time Complexity: O(N)Auxiliary Space: O(N)" }, { "code": null, "e": 4621, "s": 4607, "text": "lokeshpotta20" }, { "code": null, "e": 4631, "s": 4621, "text": "samim2000" }, { "code": null, "e": 4643, "s": 4631, "text": "29AjayKumar" }, { "code": null, "e": 4651, "s": 4643, "text": "gfgking" }, { "code": null, "e": 4663, "s": 4651, "text": "subsequence" }, { "code": null, "e": 4670, "s": 4663, "text": "Arrays" }, { "code": null, "e": 4677, "s": 4670, "text": "Greedy" }, { "code": null, "e": 4690, "s": 4677, "text": "Mathematical" }, { "code": null, "e": 4697, "s": 4690, "text": "Arrays" }, { "code": null, "e": 4704, "s": 4697, "text": "Greedy" }, { "code": null, "e": 4717, "s": 4704, "text": "Mathematical" } ]
std::clamp in C++ 17
07 Aug, 2017 Clamps a variable to a given range[high – low]. If num > high, num is assigned high. If num < low, num is assigned low. If num is already clamped, no modifications. Note : This function is defined in header from C++17 onwards. Examples: Input : num = 100, Range : 10 - 90 Output : num = 90 Input : num = 5, Range : 10 - 90 Output : num = 10 Input : num = 50, Range : 10 - 90 Output : num = 50 Syntax : templateconstexpr const T& clamp( const T& num, const T& low, const T& high ); template constexpr const T& clamp( const T& v, const T& lo, const T& hi, Compare comp ); Parameters num - the value to clamp low, high - the boundaries to clamp num to comp - comparison function object which returns ?true if low is less than num and num is less than high. Return value Reference to low if num is less than low, Reference to high if high is less than num, otherwise reference to num. Applications : To keep a list of inputs specified to a given range. Preventing size overflow. // CPP program to illustrate// std::clamp#include <bits/stdc++.h> // Driver codeint main(){ // range [10 - 100] int high = 100, low = 10; // num1 higher than range int num1 = 120; // num2 lower than range int num2 = 5; // num3 in range int num3 = 50; // clamping all variables num1 = std::clamp(num1, low, high); num2 = std::clamp(num2, low, high); num3 = std::clamp(num3, low, high); // printing result std::cout << num1 << " " << num2 << " " << num3;} Output: 100 10 50 // CPP program to illustrate clamping// array elements in given range#include <iostream>#include <algorithm> // Range [30 - 60]int low = 30, high = 60; // Function to clamp the elements in given rangevoid clamp_arr_in_range(int arr[], int n){ // Clamping the array elements for (int i = 0; i < n; i++) { arr[i] = std::clamp(arr[i], low, high); }} // Driver codeint main(){ // Array having elements to be clamped int arr[] = { 10, 20, 30, 40, 50, 60, 70, 80 }; // Size of array int n = sizeof(arr) / sizeof(arr[0]); // Function call to clamp the elements clamp_arr_in_range(arr, n); // Printing the array for (int i = 0; i < n; i++) std::cout << arr[i] << " ";} Output : 30 30 30 40 50 60 60 60 With Binary Predicate // C++ program to implement std::clamp// with Binary Predicate #include <bits/stdc++.h> // Binary predicatebool comp(int a, int b){ return (a < b);} // Driver codeint main(){ // range [10 - 100] int high = 100, low = 10; // num1 higher than range int num1 = 120; // num2 lower than range int num2 = 5; // num3 in range int num3 = 50; // clamping all variables num1 = std::clamp(num1, low, high, comp); num2 = std::clamp(num2, low, high, comp); num3 = std::clamp(num3, low, high, comp); // printing result std::cout << num1 << " " << num2 << " " << num3;} Output: 100 10 50 This article is contributed by Rohit Thapliyal. 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. cpp-algorithm-library STL C++ STL CPP Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Bitwise Operators in C/C++ Set in C++ Standard Template Library (STL) vector erase() and clear() in C++ unordered_map in C++ STL Inheritance in C++ Substring in C++ Priority Queue in C++ Standard Template Library (STL) The C++ Standard Template Library (STL) C++ Classes and Objects Object Oriented Programming in C++
[ { "code": null, "e": 52, "s": 24, "text": "\n07 Aug, 2017" }, { "code": null, "e": 100, "s": 52, "text": "Clamps a variable to a given range[high – low]." }, { "code": null, "e": 217, "s": 100, "text": "If num > high, num is assigned high.\nIf num < low, num is assigned low.\nIf num is already clamped, no modifications." }, { "code": null, "e": 279, "s": 217, "text": "Note : This function is defined in header from C++17 onwards." }, { "code": null, "e": 289, "s": 279, "text": "Examples:" }, { "code": null, "e": 448, "s": 289, "text": "Input : num = 100, Range : 10 - 90\nOutput : num = 90\n\nInput : num = 5, Range : 10 - 90\nOutput : num = 10\n\nInput : num = 50, Range : 10 - 90\nOutput : num = 50\n" }, { "code": null, "e": 457, "s": 448, "text": "Syntax :" }, { "code": null, "e": 1071, "s": 457, "text": "templateconstexpr const T& clamp( const T& num, const T& low, const T& high );\ntemplate\nconstexpr const T& clamp( const T& v, const T& lo, const T& hi, Compare comp );\nParameters\nnum - the value to clamp\nlow, high - the boundaries to clamp num to\ncomp - comparison function object which returns ?true if low is less than num\n and num is less than high. \n\nReturn value\nReference to low if num is less than low,\nReference to high if high is less than num,\notherwise reference to num.\n\nApplications :\nTo keep a list of inputs specified to a given range. \nPreventing size overflow.\n" }, { "code": "// CPP program to illustrate// std::clamp#include <bits/stdc++.h> // Driver codeint main(){ // range [10 - 100] int high = 100, low = 10; // num1 higher than range int num1 = 120; // num2 lower than range int num2 = 5; // num3 in range int num3 = 50; // clamping all variables num1 = std::clamp(num1, low, high); num2 = std::clamp(num2, low, high); num3 = std::clamp(num3, low, high); // printing result std::cout << num1 << \" \" << num2 << \" \" << num3;}", "e": 1578, "s": 1071, "text": null }, { "code": null, "e": 1586, "s": 1578, "text": "Output:" }, { "code": null, "e": 1596, "s": 1586, "text": "100 10 50" }, { "code": "// CPP program to illustrate clamping// array elements in given range#include <iostream>#include <algorithm> // Range [30 - 60]int low = 30, high = 60; // Function to clamp the elements in given rangevoid clamp_arr_in_range(int arr[], int n){ // Clamping the array elements for (int i = 0; i < n; i++) { arr[i] = std::clamp(arr[i], low, high); }} // Driver codeint main(){ // Array having elements to be clamped int arr[] = { 10, 20, 30, 40, 50, 60, 70, 80 }; // Size of array int n = sizeof(arr) / sizeof(arr[0]); // Function call to clamp the elements clamp_arr_in_range(arr, n); // Printing the array for (int i = 0; i < n; i++) std::cout << arr[i] << \" \";}", "e": 2313, "s": 1596, "text": null }, { "code": null, "e": 2322, "s": 2313, "text": "Output :" }, { "code": null, "e": 2347, "s": 2322, "text": "30 30 30 40 50 60 60 60\n" }, { "code": null, "e": 2369, "s": 2347, "text": "With Binary Predicate" }, { "code": "// C++ program to implement std::clamp// with Binary Predicate #include <bits/stdc++.h> // Binary predicatebool comp(int a, int b){ return (a < b);} // Driver codeint main(){ // range [10 - 100] int high = 100, low = 10; // num1 higher than range int num1 = 120; // num2 lower than range int num2 = 5; // num3 in range int num3 = 50; // clamping all variables num1 = std::clamp(num1, low, high, comp); num2 = std::clamp(num2, low, high, comp); num3 = std::clamp(num3, low, high, comp); // printing result std::cout << num1 << \" \" << num2 << \" \" << num3;}", "e": 2982, "s": 2369, "text": null }, { "code": null, "e": 2990, "s": 2982, "text": "Output:" }, { "code": null, "e": 3000, "s": 2990, "text": "100 10 50" }, { "code": null, "e": 3303, "s": 3000, "text": "This article is contributed by Rohit Thapliyal. 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": 3428, "s": 3303, "text": "Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above." }, { "code": null, "e": 3450, "s": 3428, "text": "cpp-algorithm-library" }, { "code": null, "e": 3454, "s": 3450, "text": "STL" }, { "code": null, "e": 3458, "s": 3454, "text": "C++" }, { "code": null, "e": 3462, "s": 3458, "text": "STL" }, { "code": null, "e": 3466, "s": 3462, "text": "CPP" }, { "code": null, "e": 3564, "s": 3466, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 3591, "s": 3564, "text": "Bitwise Operators in C/C++" }, { "code": null, "e": 3634, "s": 3591, "text": "Set in C++ Standard Template Library (STL)" }, { "code": null, "e": 3668, "s": 3634, "text": "vector erase() and clear() in C++" }, { "code": null, "e": 3693, "s": 3668, "text": "unordered_map in C++ STL" }, { "code": null, "e": 3712, "s": 3693, "text": "Inheritance in C++" }, { "code": null, "e": 3729, "s": 3712, "text": "Substring in C++" }, { "code": null, "e": 3783, "s": 3729, "text": "Priority Queue in C++ Standard Template Library (STL)" }, { "code": null, "e": 3823, "s": 3783, "text": "The C++ Standard Template Library (STL)" }, { "code": null, "e": 3847, "s": 3823, "text": "C++ Classes and Objects" } ]
Java Program to Find the Volume and Surface Area of Cuboid
01 Dec, 2020 A Cuboid is a 3-dimensional box-like figure represented in the 3-dimensional plane. A cuboid has 6 rectangle-shaped faces. Each face meets another face at 90 degrees each. Three sides of cuboid meet at the same vertex. Since it is made up of 6 rectangle faces, it has length, width and height of different dimension. Given the dimensions of the cuboid, find the Surface area and Volume of a cuboid. The formula’s to calculate the area and volume are given below. Examples: Input : 20 15 10 Output : Surface Area = 1300 Volume = 3000 Input : 30 5 10 Output : Surface Area = 1000 Volume = 1500 Formulas: Volume = length * breadth * height Surface Area of Cuboid = 2(length * breadth + breadth * height + height * length) Approach : Given the dimensions of the cone, say length L, height H and breadth B of a cuboid. Calculate Volume and Surface Area Example 1: Java // Java Program to Find the Volume and Surface Area of// Cuboids import java.io.*; class GFG { public static void main(String[] args) { // specify L,B and H double L = 20, B = 15, H = 10; // calculate SurfaceArea double SurfaceArea = 2 * (L * B + B * H + H * L); // calculate Volume double Volume = L * B * H; System.out.println( "The Surface area of cuboid is : " + SurfaceArea); System.out.println("The Volume of the cuboid is : " + Volume); }} The Surface area of cuboid is : 1300.0 The Volume of the cuboid is : 3000.0 Example 2: Java import java.io.*; class GFG { public static void main(String[] args) { // specify L,B and H double L = 30, B = 5, H = 10; // calculate SurfaceArea double SurfaceArea = 2 * (L * B + B * H + H * L); // calculate Volume double Volume = L * B * H; System.out.println( "The Surface area of cuboid is : " + SurfaceArea); System.out.println("The Volume of the cuboid is : " + Volume); }} The Surface area of cuboid is : 1000.0 The Volume of the cuboid is : 1500.0 Time Complexity = O(n) Picked Java Java Programs Java Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Stream In Java Introduction to Java Constructors in Java Exceptions in Java Generics in Java Java Programming Examples Convert Double to Integer in Java Implementing a Linked List in Java using Class Factory method design pattern in Java Java Program to Remove Duplicate Elements From the Array
[ { "code": null, "e": 53, "s": 25, "text": "\n01 Dec, 2020" }, { "code": null, "e": 516, "s": 53, "text": "A Cuboid is a 3-dimensional box-like figure represented in the 3-dimensional plane. A cuboid has 6 rectangle-shaped faces. Each face meets another face at 90 degrees each. Three sides of cuboid meet at the same vertex. Since it is made up of 6 rectangle faces, it has length, width and height of different dimension. Given the dimensions of the cuboid, find the Surface area and Volume of a cuboid. The formula’s to calculate the area and volume are given below." }, { "code": null, "e": 526, "s": 516, "text": "Examples:" }, { "code": null, "e": 668, "s": 526, "text": "Input : 20 15 10\nOutput : Surface Area = 1300\n Volume = 3000 \n \n\nInput : 30 5 10\nOutput : Surface Area = 1000\n Volume = 1500" }, { "code": null, "e": 678, "s": 668, "text": "Formulas:" }, { "code": null, "e": 713, "s": 678, "text": "Volume = length * breadth * height" }, { "code": null, "e": 795, "s": 713, "text": "Surface Area of Cuboid = 2(length * breadth + breadth * height + height * length)" }, { "code": null, "e": 806, "s": 795, "text": "Approach :" }, { "code": null, "e": 890, "s": 806, "text": "Given the dimensions of the cone, say length L, height H and breadth B of a cuboid." }, { "code": null, "e": 924, "s": 890, "text": "Calculate Volume and Surface Area" }, { "code": null, "e": 935, "s": 924, "text": "Example 1:" }, { "code": null, "e": 940, "s": 935, "text": "Java" }, { "code": "// Java Program to Find the Volume and Surface Area of// Cuboids import java.io.*; class GFG { public static void main(String[] args) { // specify L,B and H double L = 20, B = 15, H = 10; // calculate SurfaceArea double SurfaceArea = 2 * (L * B + B * H + H * L); // calculate Volume double Volume = L * B * H; System.out.println( \"The Surface area of cuboid is : \" + SurfaceArea); System.out.println(\"The Volume of the cuboid is : \" + Volume); }}", "e": 1534, "s": 940, "text": null }, { "code": null, "e": 1610, "s": 1534, "text": "The Surface area of cuboid is : 1300.0\nThe Volume of the cuboid is : 3000.0" }, { "code": null, "e": 1621, "s": 1610, "text": "Example 2:" }, { "code": null, "e": 1626, "s": 1621, "text": "Java" }, { "code": "import java.io.*; class GFG { public static void main(String[] args) { // specify L,B and H double L = 30, B = 5, H = 10; // calculate SurfaceArea double SurfaceArea = 2 * (L * B + B * H + H * L); // calculate Volume double Volume = L * B * H; System.out.println( \"The Surface area of cuboid is : \" + SurfaceArea); System.out.println(\"The Volume of the cuboid is : \" + Volume); }}", "e": 2153, "s": 1626, "text": null }, { "code": null, "e": 2229, "s": 2153, "text": "The Surface area of cuboid is : 1000.0\nThe Volume of the cuboid is : 1500.0" }, { "code": null, "e": 2252, "s": 2229, "text": "Time Complexity = O(n)" }, { "code": null, "e": 2259, "s": 2252, "text": "Picked" }, { "code": null, "e": 2264, "s": 2259, "text": "Java" }, { "code": null, "e": 2278, "s": 2264, "text": "Java Programs" }, { "code": null, "e": 2283, "s": 2278, "text": "Java" }, { "code": null, "e": 2381, "s": 2283, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 2396, "s": 2381, "text": "Stream In Java" }, { "code": null, "e": 2417, "s": 2396, "text": "Introduction to Java" }, { "code": null, "e": 2438, "s": 2417, "text": "Constructors in Java" }, { "code": null, "e": 2457, "s": 2438, "text": "Exceptions in Java" }, { "code": null, "e": 2474, "s": 2457, "text": "Generics in Java" }, { "code": null, "e": 2500, "s": 2474, "text": "Java Programming Examples" }, { "code": null, "e": 2534, "s": 2500, "text": "Convert Double to Integer in Java" }, { "code": null, "e": 2581, "s": 2534, "text": "Implementing a Linked List in Java using Class" }, { "code": null, "e": 2619, "s": 2581, "text": "Factory method design pattern in Java" } ]