title
stringlengths
3
221
text
stringlengths
17
477k
parsed
listlengths
0
3.17k
Java Examples - Search a file in a directory
How to search for a file in a directory ? Following example shows how to search for a particular file in a directory by making a Filefiter. Following example displays all the files having file names starting with 'b'. import java.io.*; public class Main { public static void main(String[] args) { File dir = new File("C:"); FilenameFilter filter = new FilenameFilter() { public boolean accept (File dir, String name) { return name.startsWith("b"); } }; String[] children = dir.list(filter); if (children == null) { System.out.println("Either dir does not exist or is not a directory"); } else { for (int i = 0; i< children.length; i++) { String filename = children[i]; System.out.println(filename); } } } } The above code sample will produce the following result. build build.xml Print Add Notes Bookmark this page
[ { "code": null, "e": 2110, "s": 2068, "text": "How to search for a file in a directory ?" }, { "code": null, "e": 2286, "s": 2110, "text": "Following example shows how to search for a particular file in a directory by making a Filefiter. Following example displays all the files having file names starting with 'b'." }, { "code": null, "e": 2914, "s": 2286, "text": "import java.io.*;\n\npublic class Main { \n public static void main(String[] args) {\n File dir = new File(\"C:\");\n FilenameFilter filter = new FilenameFilter() {\n public boolean accept (File dir, String name) { \n return name.startsWith(\"b\");\n } \n }; \n String[] children = dir.list(filter);\n if (children == null) {\n System.out.println(\"Either dir does not exist or is not a directory\"); \n } else { \n for (int i = 0; i< children.length; i++) {\n String filename = children[i];\n System.out.println(filename);\n } \n } \n } \n}" }, { "code": null, "e": 2971, "s": 2914, "text": "The above code sample will produce the following result." }, { "code": null, "e": 2988, "s": 2971, "text": "build\nbuild.xml\n" }, { "code": null, "e": 2995, "s": 2988, "text": " Print" }, { "code": null, "e": 3006, "s": 2995, "text": " Add Notes" } ]
Find a triplet such that sum of two equals to third element - GeeksforGeeks
06 Apr, 2022 Given an array of integers, you have to find three numbers such that the sum of two elements equals the third element. Examples: Input : {5, 32, 1, 7, 10, 50, 19, 21, 2} Output : 21, 2, 19 Input : {5, 32, 1, 7, 10, 50, 19, 21, 0} Output : no such triplet exist Question source: Arcesium Interview Experience | Set 7 (On campus for Internship) Simple approach: Run three loops and check if there exists a triplet such that sum of two elements equals the third element.Time complexity: O(n^3) Efficient approach: The idea is similar to Find a triplet that sum to a given value. Sort the given array first. Start fixing the greatest element of three from the back and traverse the array to find the other two numbers which sum up to the third element. Take two pointers j(from front) and k(initially i-1) to find the smallest of the two number and from i-1 to find the largest of the two remaining numbers If the addition of both the numbers is still less than A[i], then we need to increase the value of the summation of two numbers, thereby increasing the j pointer, so as to increase the value of A[j] + A[k]. If the addition of both the numbers is more than A[i], then we need to decrease the value of the summation of two numbers, thereby decrease the k pointer so as to decrease the overall value of A[j] + A[k]. Below image is a dry run of the above approach: Below is the implementation of the above approach: C++ Java Python C# PHP Javascript // CPP program to find three numbers// such that sum of two makes the// third element in array#include <bits/stdc++.h>using namespace std; // Utility function for finding// triplet in arrayvoid findTriplet(int arr[], int n){ // sort the array sort(arr, arr + n); // for every element in arr // check if a pair exist(in array) whose // sum is equal to arr element for (int i = n - 1; i >= 0; i--) { int j = 0; int k = i - 1; // Iterate forward and backward to find // the other two elements while (j < k) { // If the two elements sum is // equal to the third element if (arr[i] == arr[j] + arr[k]) { // pair found cout << "numbers are " << arr[i] << " " << arr[j] << " " << arr[k] << endl; return; } // If the element is greater than // sum of both the elements, then try // adding a smaller number to reach the // equality else if (arr[i] > arr[j] + arr[k]) j += 1; // If the element is smaller, then // try with a smaller number // to reach equality, so decrease K else k -= 1; } } // No such triplet is found in array cout << "No such triplet exists";} // driver programint main(){ int arr[] = { 5, 32, 1, 7, 10, 50, 19, 21, 2 }; int n = sizeof(arr) / sizeof(arr[0]); findTriplet(arr, n); return 0;} // Java program to find three numbers// such that sum of two makes the// third element in arrayimport java.util.Arrays; public class GFG { // utility function for finding // triplet in array static void findTriplet(int arr[], int n) { // sort the array Arrays.sort(arr); // for every element in arr // check if a pair exist(in array) whose // sum is equal to arr element for (int i = n - 1; i >= 0; i--) { int j = 0; int k = i - 1; while (j < k) { if (arr[i] == arr[j] + arr[k]) { // pair found System.out.println("numbers are " + arr[i] + " " + arr[j] + " " + arr[k]); return; } else if (arr[i] > arr[j] + arr[k]) j += 1; else k -= 1; } } // no such triplet is found in array System.out.println("No such triplet exists"); } // driver program public static void main(String args[]) { int arr[] = { 5, 32, 1, 7, 10, 50, 19, 21, 2 }; int n = arr.length; findTriplet(arr, n); }}// This code is contributed by Sumit Ghosh # Python program to find three numbers# such that sum of two makes the# third element in array # utility function for finding# triplet in arraydef findTriplet(arr, n): # sort the array arr.sort() # for every element in arr # check if a pair exist(in array) whose # sum is equal to arr element i = n - 1 while(i >= 0): j = 0 k = i - 1 while (j < k): if (arr[i] == arr[j] + arr[k]): # pair found print "numbers are ", arr[i], arr[j], arr[k] return elif (arr[i] > arr[j] + arr[k]): j += 1 else: k -= 1 i -= 1 # no such triplet is found in array print "No such triplet exists" # driver programarr = [ 5, 32, 1, 7, 10, 50, 19, 21, 2 ]n = len(arr)findTriplet(arr, n) # This code is contributed by Sachin Bisht // C# program to find three numbers// such that sum of two makes the// third element in arrayusing System; public class GFG { // utility function for finding // triplet in array static void findTriplet(int[] arr, int n) { // sort the array Array.Sort(arr); // for every element in arr // check if a pair exist(in // array) whose sum is equal // to arr element for (int i = n - 1; i >= 0; i--) { int j = 0; int k = i - 1; while (j < k) { if (arr[i] == arr[j] + arr[k]) { // pair found Console.WriteLine("numbers are " + arr[i] + " " + arr[j] + " " + arr[k]); return; } else if (arr[i] > arr[j] + arr[k]) j += 1; else k -= 1; } } // no such triplet is found in array Console.WriteLine("No such triplet exists"); } // driver program public static void Main() { int[] arr = { 5, 32, 1, 7, 10, 50, 19, 21, 2 }; int n = arr.Length; findTriplet(arr, n); }} // This code is contributed by vt_m. <?php// PHP program to find three// numbers such that sum of// two makes the third// element in array // utility function for// finding triplet in arrayfunction findTriplet($arr, $n){ // sort the array sort($arr); // for every element in // arr check if a pair // exist(in array) whose // sum is equal to arr element for ($i = $n - 1; $i >= 0; $i--) { $j = 0; $k = $i - 1; while ($j < $k) { if ($arr[$i] == $arr[$j] + $arr[$k]) { // pair found echo "numbers are ", $arr[$i], " ", $arr[$j], " ", $arr[$k]; return; } else if ($arr[$i] > $arr[$j] + $arr[$k]) $j += 1; else $k -= 1; } } // no such triplet // is found in array echo "No such triplet exists";} // Driver Code$arr = array(5, 32, 1, 7, 10, 50, 19, 21, 2 );$n = count($arr); findTriplet($arr, $n); // This code is contributed by anuj_67.?> <script> // Javascript program to find three numbers// such that sum of two makes the// third element in array // Utility function for finding// triplet in arrayfunction findTriplet(arr, n){ // sort the array arr.sort((a,b) => a-b); // for every element in arr // check if a pair exist(in array) whose // sum is equal to arr element for (let i = n - 1; i >= 0; i--) { let j = 0; let k = i - 1; // Iterate forward and backward to find // the other two elements while (j < k) { // If the two elements sum is // equal to the third element if (arr[i] == arr[j] + arr[k]) { // pair found document.write("numbers are " + arr[i] + " " + arr[j] + " " + arr[k] + "<br>"); return; } // If the element is greater than // sum of both the elements, then try // adding a smaller number to reach the // equality else if (arr[i] > arr[j] + arr[k]) j += 1; // If the element is smaller, then // try with a smaller number // to reach equality, so decrease K else k -= 1; } } // No such triplet is found in array document.write("No such triplet exists");} // driver program let arr = [ 5, 32, 1, 7, 10, 50, 19, 21, 2 ]; let n = arr.length; findTriplet(arr, n); // This code is contributed by Mayank Tyagi </script> Output: numbers are 21 2 19 Time complexity: O(N^2) Another Approach: The idea is similar to previous approach. Sort the given array.Start a nested loop, fixing the first element i(from 0 to n-1) and moving the other one j (from i+1 to n-1).Take the sum of both the elements and search it in the remaining array using Binary Search. Sort the given array. Start a nested loop, fixing the first element i(from 0 to n-1) and moving the other one j (from i+1 to n-1). Take the sum of both the elements and search it in the remaining array using Binary Search. C++ Java Python3 Javascript // CPP program to find three numbers// such that sum of two makes the// third element in array#include <bits/stdc++.h>#include <iostream>using namespace std; // function to perform binary searchbool search(int sum, int start, int end, int arr[]){ while (start <= end) { int mid = (start + end) / 2; if (arr[mid] == sum) { return true; } else if (arr[mid] > sum) { end = mid - 1; } else { start = mid + 1; } } return false;} // function to find the tripletsvoid findTriplet(int arr[], int n){ // sorting the array sort(arr, arr + n); // initialising nested loops for (int i = 0; i < n; i++) { for (int j = i + 1; j < n; j++) { // finding the sum of the numbers if (search((arr[i] + arr[j]), j, n - 1, arr)) { // printing out the first triplet cout << "Numbers are: " << arr[i] << " " << arr[j] << " " << (arr[i] + arr[j]); return; } } } // if no such triplets are found cout << "No such numbers exist" << endl;} int main(){ int arr[] = { 5, 32, 1, 7, 10, 50, 19, 21, 2 }; int n = sizeof(arr) / sizeof(arr[0]); findTriplet(arr, n); return 0;} // This code is contributed by Sarthak Delori // Java program to find three numbers// such that sum of two makes the// third element in arrayimport java.util.*; class GFG{ // Function to perform binary searchstatic boolean search(int sum, int start, int end, int arr[]){ while (start <= end) { int mid = (start + end) / 2; if (arr[mid] == sum) { return true; } else if (arr[mid] > sum) { end = mid - 1; } else { start = mid + 1; } } return false;} // Function to find the tripletsstatic void findTriplet(int arr[], int n){ // Sorting the array Arrays.sort(arr); // Initialising nested loops for(int i = 0; i < n; i++) { for(int j = i + 1; j < n; j++) { // Finding the sum of the numbers if (search((arr[i] + arr[j]), j, n - 1, arr)) { // Printing out the first triplet System.out.print("Numbers are: " + arr[i] + " " + arr[j] + " " + (arr[i] + arr[j])); return; } } } // If no such triplets are found System.out.print("No such numbers exist");} // Driver codepublic static void main(String args[]){ int arr[] = { 5, 32, 1, 7, 10, 50, 19, 21, 2 }; int n = arr.length; findTriplet(arr, n);}} // This code is contributed by target_2 # Python program to find three numbers# such that sum of two makes the# third element in arrayfrom functools import cmp_to_key def mycmp(a, b): return a - b def search(sum, start, end, arr): while (start <= end): mid = (start + end) // 2 if (arr[mid] == sum): return True elif (arr[mid] > sum): end = mid - 1 else: start = mid + 1 return False # Utility function for finding# triplet in arraydef findTriplet(arr, n): # sort the array arr.sort(key = cmp_to_key(mycmp)) # initialising nested loops for i in range(n): for j in range(i + 1,n): if (search((arr[i] + arr[j]), j, n - 1, arr)): print(f"numbers are {arr[i]} {arr[j]} {( arr[i] + arr[j] )}") return # No such triplet is found in array print("No such triplet exists") # driver programarr = [ 5, 32, 1, 7, 10, 50, 19, 21, 2 ]n = len(arr) findTriplet(arr, n) # This code is contributed by shinjanpatra <script> // Javascript program to find three numbers// such that sum of two makes the// third element in arraybool search(sum, start, end, arr){ while (start <= end) { let mid = (start + end) / 2; if (arr[mid] == sum) { return true; } else if (arr[mid] > sum) { end = mid - 1; } else { start = mid + 1; } } return false;} // Utility function for finding// triplet in arrayfunction findTriplet(arr, n){ // sort the array arr.sort((a,b) => a-b); // initialising nested loops for (let i = 0; i < n; i++) { for (let j = i + 1; j < n; j++) { if (search((arr[i] + arr[j]), j, n - 1, arr)) { document.write("numbers are " + arr[i] + " " + arr[j] + " " + ( arr[i] + arr[j] ) + "<br>"); } } } // No such triplet is found in array document.write("No such triplet exists");} // driver program let arr = [ 5, 32, 1, 7, 10, 50, 19, 21, 2 ]; let n = arr.length; findTriplet(arr, n); // This code is contributed by Sarthak Delori</script> Time Complexity: O(N^2*log N) Space Complexity: O(1) This article is contributed by Mandeep 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 [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. vt_m mayanktyagi1709 sarthakdelori10 target_2 shinjanpatra Amazon Arcesium two-pointer-algorithm Arrays Searching Amazon Arcesium two-pointer-algorithm Arrays Searching Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Maximum and minimum of an array using minimum number of comparisons Stack Data Structure (Introduction and Program) Top 50 Array Coding Problems for Interviews Multidimensional Arrays in Java Introduction to Arrays Binary Search Maximum and minimum of an array using minimum number of comparisons Linear Search Find the Missing Number K'th Smallest/Largest Element in Unsorted Array | Set 1
[ { "code": null, "e": 25164, "s": 25136, "text": "\n06 Apr, 2022" }, { "code": null, "e": 25283, "s": 25164, "text": "Given an array of integers, you have to find three numbers such that the sum of two elements equals the third element." }, { "code": null, "e": 25294, "s": 25283, "text": "Examples: " }, { "code": null, "e": 25427, "s": 25294, "text": "Input : {5, 32, 1, 7, 10, 50, 19, 21, 2}\nOutput : 21, 2, 19\n\nInput : {5, 32, 1, 7, 10, 50, 19, 21, 0}\nOutput : no such triplet exist" }, { "code": null, "e": 25509, "s": 25427, "text": "Question source: Arcesium Interview Experience | Set 7 (On campus for Internship)" }, { "code": null, "e": 25657, "s": 25509, "text": "Simple approach: Run three loops and check if there exists a triplet such that sum of two elements equals the third element.Time complexity: O(n^3)" }, { "code": null, "e": 25744, "s": 25657, "text": "Efficient approach: The idea is similar to Find a triplet that sum to a given value. " }, { "code": null, "e": 25772, "s": 25744, "text": "Sort the given array first." }, { "code": null, "e": 25917, "s": 25772, "text": "Start fixing the greatest element of three from the back and traverse the array to find the other two numbers which sum up to the third element." }, { "code": null, "e": 26071, "s": 25917, "text": "Take two pointers j(from front) and k(initially i-1) to find the smallest of the two number and from i-1 to find the largest of the two remaining numbers" }, { "code": null, "e": 26278, "s": 26071, "text": "If the addition of both the numbers is still less than A[i], then we need to increase the value of the summation of two numbers, thereby increasing the j pointer, so as to increase the value of A[j] + A[k]." }, { "code": null, "e": 26484, "s": 26278, "text": "If the addition of both the numbers is more than A[i], then we need to decrease the value of the summation of two numbers, thereby decrease the k pointer so as to decrease the overall value of A[j] + A[k]." }, { "code": null, "e": 26533, "s": 26484, "text": "Below image is a dry run of the above approach: " }, { "code": null, "e": 26585, "s": 26533, "text": "Below is the implementation of the above approach: " }, { "code": null, "e": 26589, "s": 26585, "text": "C++" }, { "code": null, "e": 26594, "s": 26589, "text": "Java" }, { "code": null, "e": 26601, "s": 26594, "text": "Python" }, { "code": null, "e": 26604, "s": 26601, "text": "C#" }, { "code": null, "e": 26608, "s": 26604, "text": "PHP" }, { "code": null, "e": 26619, "s": 26608, "text": "Javascript" }, { "code": "// CPP program to find three numbers// such that sum of two makes the// third element in array#include <bits/stdc++.h>using namespace std; // Utility function for finding// triplet in arrayvoid findTriplet(int arr[], int n){ // sort the array sort(arr, arr + n); // for every element in arr // check if a pair exist(in array) whose // sum is equal to arr element for (int i = n - 1; i >= 0; i--) { int j = 0; int k = i - 1; // Iterate forward and backward to find // the other two elements while (j < k) { // If the two elements sum is // equal to the third element if (arr[i] == arr[j] + arr[k]) { // pair found cout << \"numbers are \" << arr[i] << \" \" << arr[j] << \" \" << arr[k] << endl; return; } // If the element is greater than // sum of both the elements, then try // adding a smaller number to reach the // equality else if (arr[i] > arr[j] + arr[k]) j += 1; // If the element is smaller, then // try with a smaller number // to reach equality, so decrease K else k -= 1; } } // No such triplet is found in array cout << \"No such triplet exists\";} // driver programint main(){ int arr[] = { 5, 32, 1, 7, 10, 50, 19, 21, 2 }; int n = sizeof(arr) / sizeof(arr[0]); findTriplet(arr, n); return 0;}", "e": 28148, "s": 26619, "text": null }, { "code": "// Java program to find three numbers// such that sum of two makes the// third element in arrayimport java.util.Arrays; public class GFG { // utility function for finding // triplet in array static void findTriplet(int arr[], int n) { // sort the array Arrays.sort(arr); // for every element in arr // check if a pair exist(in array) whose // sum is equal to arr element for (int i = n - 1; i >= 0; i--) { int j = 0; int k = i - 1; while (j < k) { if (arr[i] == arr[j] + arr[k]) { // pair found System.out.println(\"numbers are \" + arr[i] + \" \" + arr[j] + \" \" + arr[k]); return; } else if (arr[i] > arr[j] + arr[k]) j += 1; else k -= 1; } } // no such triplet is found in array System.out.println(\"No such triplet exists\"); } // driver program public static void main(String args[]) { int arr[] = { 5, 32, 1, 7, 10, 50, 19, 21, 2 }; int n = arr.length; findTriplet(arr, n); }}// This code is contributed by Sumit Ghosh", "e": 29420, "s": 28148, "text": null }, { "code": "# Python program to find three numbers# such that sum of two makes the# third element in array # utility function for finding# triplet in arraydef findTriplet(arr, n): # sort the array arr.sort() # for every element in arr # check if a pair exist(in array) whose # sum is equal to arr element i = n - 1 while(i >= 0): j = 0 k = i - 1 while (j < k): if (arr[i] == arr[j] + arr[k]): # pair found print \"numbers are \", arr[i], arr[j], arr[k] return elif (arr[i] > arr[j] + arr[k]): j += 1 else: k -= 1 i -= 1 # no such triplet is found in array print \"No such triplet exists\" # driver programarr = [ 5, 32, 1, 7, 10, 50, 19, 21, 2 ]n = len(arr)findTriplet(arr, n) # This code is contributed by Sachin Bisht", "e": 30320, "s": 29420, "text": null }, { "code": "// C# program to find three numbers// such that sum of two makes the// third element in arrayusing System; public class GFG { // utility function for finding // triplet in array static void findTriplet(int[] arr, int n) { // sort the array Array.Sort(arr); // for every element in arr // check if a pair exist(in // array) whose sum is equal // to arr element for (int i = n - 1; i >= 0; i--) { int j = 0; int k = i - 1; while (j < k) { if (arr[i] == arr[j] + arr[k]) { // pair found Console.WriteLine(\"numbers are \" + arr[i] + \" \" + arr[j] + \" \" + arr[k]); return; } else if (arr[i] > arr[j] + arr[k]) j += 1; else k -= 1; } } // no such triplet is found in array Console.WriteLine(\"No such triplet exists\"); } // driver program public static void Main() { int[] arr = { 5, 32, 1, 7, 10, 50, 19, 21, 2 }; int n = arr.Length; findTriplet(arr, n); }} // This code is contributed by vt_m.", "e": 31627, "s": 30320, "text": null }, { "code": "<?php// PHP program to find three// numbers such that sum of// two makes the third// element in array // utility function for// finding triplet in arrayfunction findTriplet($arr, $n){ // sort the array sort($arr); // for every element in // arr check if a pair // exist(in array) whose // sum is equal to arr element for ($i = $n - 1; $i >= 0; $i--) { $j = 0; $k = $i - 1; while ($j < $k) { if ($arr[$i] == $arr[$j] + $arr[$k]) { // pair found echo \"numbers are \", $arr[$i], \" \", $arr[$j], \" \", $arr[$k]; return; } else if ($arr[$i] > $arr[$j] + $arr[$k]) $j += 1; else $k -= 1; } } // no such triplet // is found in array echo \"No such triplet exists\";} // Driver Code$arr = array(5, 32, 1, 7, 10, 50, 19, 21, 2 );$n = count($arr); findTriplet($arr, $n); // This code is contributed by anuj_67.?>", "e": 32762, "s": 31627, "text": null }, { "code": "<script> // Javascript program to find three numbers// such that sum of two makes the// third element in array // Utility function for finding// triplet in arrayfunction findTriplet(arr, n){ // sort the array arr.sort((a,b) => a-b); // for every element in arr // check if a pair exist(in array) whose // sum is equal to arr element for (let i = n - 1; i >= 0; i--) { let j = 0; let k = i - 1; // Iterate forward and backward to find // the other two elements while (j < k) { // If the two elements sum is // equal to the third element if (arr[i] == arr[j] + arr[k]) { // pair found document.write(\"numbers are \" + arr[i] + \" \" + arr[j] + \" \" + arr[k] + \"<br>\"); return; } // If the element is greater than // sum of both the elements, then try // adding a smaller number to reach the // equality else if (arr[i] > arr[j] + arr[k]) j += 1; // If the element is smaller, then // try with a smaller number // to reach equality, so decrease K else k -= 1; } } // No such triplet is found in array document.write(\"No such triplet exists\");} // driver program let arr = [ 5, 32, 1, 7, 10, 50, 19, 21, 2 ]; let n = arr.length; findTriplet(arr, n); // This code is contributed by Mayank Tyagi </script>", "e": 34279, "s": 32762, "text": null }, { "code": null, "e": 34289, "s": 34279, "text": "Output: " }, { "code": null, "e": 34309, "s": 34289, "text": "numbers are 21 2 19" }, { "code": null, "e": 34333, "s": 34309, "text": "Time complexity: O(N^2)" }, { "code": null, "e": 34393, "s": 34333, "text": "Another Approach: The idea is similar to previous approach." }, { "code": null, "e": 34614, "s": 34393, "text": "Sort the given array.Start a nested loop, fixing the first element i(from 0 to n-1) and moving the other one j (from i+1 to n-1).Take the sum of both the elements and search it in the remaining array using Binary Search." }, { "code": null, "e": 34636, "s": 34614, "text": "Sort the given array." }, { "code": null, "e": 34745, "s": 34636, "text": "Start a nested loop, fixing the first element i(from 0 to n-1) and moving the other one j (from i+1 to n-1)." }, { "code": null, "e": 34837, "s": 34745, "text": "Take the sum of both the elements and search it in the remaining array using Binary Search." }, { "code": null, "e": 34841, "s": 34837, "text": "C++" }, { "code": null, "e": 34846, "s": 34841, "text": "Java" }, { "code": null, "e": 34854, "s": 34846, "text": "Python3" }, { "code": null, "e": 34865, "s": 34854, "text": "Javascript" }, { "code": "// CPP program to find three numbers// such that sum of two makes the// third element in array#include <bits/stdc++.h>#include <iostream>using namespace std; // function to perform binary searchbool search(int sum, int start, int end, int arr[]){ while (start <= end) { int mid = (start + end) / 2; if (arr[mid] == sum) { return true; } else if (arr[mid] > sum) { end = mid - 1; } else { start = mid + 1; } } return false;} // function to find the tripletsvoid findTriplet(int arr[], int n){ // sorting the array sort(arr, arr + n); // initialising nested loops for (int i = 0; i < n; i++) { for (int j = i + 1; j < n; j++) { // finding the sum of the numbers if (search((arr[i] + arr[j]), j, n - 1, arr)) { // printing out the first triplet cout << \"Numbers are: \" << arr[i] << \" \" << arr[j] << \" \" << (arr[i] + arr[j]); return; } } } // if no such triplets are found cout << \"No such numbers exist\" << endl;} int main(){ int arr[] = { 5, 32, 1, 7, 10, 50, 19, 21, 2 }; int n = sizeof(arr) / sizeof(arr[0]); findTriplet(arr, n); return 0;} // This code is contributed by Sarthak Delori", "e": 36191, "s": 34865, "text": null }, { "code": "// Java program to find three numbers// such that sum of two makes the// third element in arrayimport java.util.*; class GFG{ // Function to perform binary searchstatic boolean search(int sum, int start, int end, int arr[]){ while (start <= end) { int mid = (start + end) / 2; if (arr[mid] == sum) { return true; } else if (arr[mid] > sum) { end = mid - 1; } else { start = mid + 1; } } return false;} // Function to find the tripletsstatic void findTriplet(int arr[], int n){ // Sorting the array Arrays.sort(arr); // Initialising nested loops for(int i = 0; i < n; i++) { for(int j = i + 1; j < n; j++) { // Finding the sum of the numbers if (search((arr[i] + arr[j]), j, n - 1, arr)) { // Printing out the first triplet System.out.print(\"Numbers are: \" + arr[i] + \" \" + arr[j] + \" \" + (arr[i] + arr[j])); return; } } } // If no such triplets are found System.out.print(\"No such numbers exist\");} // Driver codepublic static void main(String args[]){ int arr[] = { 5, 32, 1, 7, 10, 50, 19, 21, 2 }; int n = arr.length; findTriplet(arr, n);}} // This code is contributed by target_2", "e": 37634, "s": 36191, "text": null }, { "code": "# Python program to find three numbers# such that sum of two makes the# third element in arrayfrom functools import cmp_to_key def mycmp(a, b): return a - b def search(sum, start, end, arr): while (start <= end): mid = (start + end) // 2 if (arr[mid] == sum): return True elif (arr[mid] > sum): end = mid - 1 else: start = mid + 1 return False # Utility function for finding# triplet in arraydef findTriplet(arr, n): # sort the array arr.sort(key = cmp_to_key(mycmp)) # initialising nested loops for i in range(n): for j in range(i + 1,n): if (search((arr[i] + arr[j]), j, n - 1, arr)): print(f\"numbers are {arr[i]} {arr[j]} {( arr[i] + arr[j] )}\") return # No such triplet is found in array print(\"No such triplet exists\") # driver programarr = [ 5, 32, 1, 7, 10, 50, 19, 21, 2 ]n = len(arr) findTriplet(arr, n) # This code is contributed by shinjanpatra", "e": 38631, "s": 37634, "text": null }, { "code": "<script> // Javascript program to find three numbers// such that sum of two makes the// third element in arraybool search(sum, start, end, arr){ while (start <= end) { let mid = (start + end) / 2; if (arr[mid] == sum) { return true; } else if (arr[mid] > sum) { end = mid - 1; } else { start = mid + 1; } } return false;} // Utility function for finding// triplet in arrayfunction findTriplet(arr, n){ // sort the array arr.sort((a,b) => a-b); // initialising nested loops for (let i = 0; i < n; i++) { for (let j = i + 1; j < n; j++) { if (search((arr[i] + arr[j]), j, n - 1, arr)) { document.write(\"numbers are \" + arr[i] + \" \" + arr[j] + \" \" + ( arr[i] + arr[j] ) + \"<br>\"); } } } // No such triplet is found in array document.write(\"No such triplet exists\");} // driver program let arr = [ 5, 32, 1, 7, 10, 50, 19, 21, 2 ]; let n = arr.length; findTriplet(arr, n); // This code is contributed by Sarthak Delori</script>", "e": 39744, "s": 38631, "text": null }, { "code": null, "e": 39774, "s": 39744, "text": "Time Complexity: O(N^2*log N)" }, { "code": null, "e": 39798, "s": 39774, "text": "Space Complexity: O(1)" }, { "code": null, "e": 40220, "s": 39798, "text": "This article is contributed by Mandeep 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 [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. " }, { "code": null, "e": 40225, "s": 40220, "text": "vt_m" }, { "code": null, "e": 40241, "s": 40225, "text": "mayanktyagi1709" }, { "code": null, "e": 40257, "s": 40241, "text": "sarthakdelori10" }, { "code": null, "e": 40266, "s": 40257, "text": "target_2" }, { "code": null, "e": 40279, "s": 40266, "text": "shinjanpatra" }, { "code": null, "e": 40286, "s": 40279, "text": "Amazon" }, { "code": null, "e": 40295, "s": 40286, "text": "Arcesium" }, { "code": null, "e": 40317, "s": 40295, "text": "two-pointer-algorithm" }, { "code": null, "e": 40324, "s": 40317, "text": "Arrays" }, { "code": null, "e": 40334, "s": 40324, "text": "Searching" }, { "code": null, "e": 40341, "s": 40334, "text": "Amazon" }, { "code": null, "e": 40350, "s": 40341, "text": "Arcesium" }, { "code": null, "e": 40372, "s": 40350, "text": "two-pointer-algorithm" }, { "code": null, "e": 40379, "s": 40372, "text": "Arrays" }, { "code": null, "e": 40389, "s": 40379, "text": "Searching" }, { "code": null, "e": 40487, "s": 40389, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 40555, "s": 40487, "text": "Maximum and minimum of an array using minimum number of comparisons" }, { "code": null, "e": 40603, "s": 40555, "text": "Stack Data Structure (Introduction and Program)" }, { "code": null, "e": 40647, "s": 40603, "text": "Top 50 Array Coding Problems for Interviews" }, { "code": null, "e": 40679, "s": 40647, "text": "Multidimensional Arrays in Java" }, { "code": null, "e": 40702, "s": 40679, "text": "Introduction to Arrays" }, { "code": null, "e": 40716, "s": 40702, "text": "Binary Search" }, { "code": null, "e": 40784, "s": 40716, "text": "Maximum and minimum of an array using minimum number of comparisons" }, { "code": null, "e": 40798, "s": 40784, "text": "Linear Search" }, { "code": null, "e": 40822, "s": 40798, "text": "Find the Missing Number" } ]
PHP | Superglobals - GeeksforGeeks
29 Jun, 2021 We already have discussed about variables and global variables in PHP in the post PHP | Variables and Data Types. In this article, we will learn about superglobals in PHP. These are specially-defined array variables in PHP that make it easy for you to get information about a request or its context. The superglobals are available throughout your script. These variables can be accessed from any function, class or any file without doing any special task such as declaring any global variable etc. They are mainly used to store and get information from one page to another etc in an application. Below is the list of superglobal variables available in PHP: $GLOBALS$_SERVER$_REQUEST$_GET$_POST$_SESSION$_COOKIE$_FILES$_ENV $GLOBALS $_SERVER $_REQUEST $_GET $_POST $_SESSION $_COOKIE $_FILES $_ENV Let us now learn about some of these superglobals in detail: $GLOBALS : It is a superglobal variable which is used to access global variables from anywhere in the PHP script. PHP stores all the global variables in array $GLOBALS[] where index holds the global variable name, which can be accessed.Below program illustrates the use of $GLOBALS in PHP: PHP <?php$x = 300;$y = 200; function multiplication(){ $GLOBALS['z'] = $GLOBALS['x'] * $GLOBALS['y'];} multiplication();echo $z;?> Output : 60000 In the above code two global variables are declared $x and $y which are assigned some value to them. Then a function multiplication() is defined to multiply the values of $x and $y and store in another variable $z defined in the GLOBAL array. $_SERVER : It is a PHP super global variable that stores the information about headers, paths and script locations. Some of these elements are used to get the information from the superglobal variable $_SERVER.Below program illustrates the use of $_SERVER in PHP: PHP <?phpecho $_SERVER['PHP_SELF'];echo "<br>";echo $_SERVER['SERVER_NAME'];echo "<br>";echo $_SERVER['HTTP_HOST'];echo "<br>";echo $_SERVER['HTTP_USER_AGENT'];echo "<br>";echo $_SERVER['SCRIPT_NAME'];echo "<br>"?> Output : In the above code we used the $_SERVER elements to get some information. We get the current file name which is worked on using ‘PHP_SELF’ element. Then we get server name used currently using ‘SERVER_NAME’ element. And then we get the host name through ‘HTTP_HOST’. $_REQUEST : It is a superglobal variable which is used to collect the data after submitting a HTML form. $_REQUEST is not used mostly, because $_POST and $_GET perform the same task and are widely used.Below is the HTML and PHP code to explain how $_REQUEST works: HTML <!DOCTYPE html><html><body> <form method="post" action="<?php echo $_SERVER['PHP_SELF'];?>"> NAME: <input type="text" name="fname"> <button type="submit">SUBMIT</button></form><?phpif ($_SERVER["REQUEST_METHOD"] == "POST") { $name = htmlspecialchars($_REQUEST['fname']); if(empty($name)){ echo "Name is empty"; } else { echo $name; }}?></body></html> Output : In the above code we have created a form that takes the name as input from the user and prints it’s name on clicking of submit button. We transport the data accepted in the form to the same page using $_SERVER[‘PHP_SELF’] element as specified in the action attribute, because we manipulate the data in the same page using the PHP code. The data is retrieved using the $_REQUEST superglobal array variable $_POST : It is a super global variable used to collect data from the HTML form after submitting it. When form uses method post to transfer data, the data is not visible in the query string, because of which security levels are maintained in this method.Below is the HTML and PHP code to explain how $_POST works: HTML <!DOCTYPE html><html><body> <form method="post" action="<?php echo $_SERVER['PHP_SELF'];?>"> <label for="name">Please enter your name: </label> <input name="name" type="text"><br> <label for="age">Please enter your age: </label> <input name="age" type="text"><br> <input type="submit" value="Submit"> <button type="submit">SUBMIT</button></form><?php$nm=$_POST['name'];$age=$_POST['age'];echo "<strong>".$nm." is $age years old.</strong>";?></body></html> Output : In the above code we have created a form that takes name and age of the user and accesses the data using $_POST super global variable when they submit the data. Since each superglobal variable is an array it can store more than one values. Hence we retrieved name and age from the $_POST variable and stored them in $nm and $age variables. $_GET : $_GET is a super global variable used to collect data from the HTML form after submitting it. When form uses method get to transfer data, the data is visible in the query string, therefore the values are not hidden. $_GET super global array variable stores the values that come in the URL.Below is the HTML and PHP code to explain how $_GET works: HTML <!DOCTYPE html><html><head><title></title></head><body bgcolor="cyan"> <?php $name = $_GET['name']; $city = $_GET['city']; echo "<h1>This is ".$name." of ".$city."</h1><br>"; ?> <img src = "2.jpg" alt = "nanilake" height = "400" width="500" /></body></html> We are actually seeing half of the logic just now. In the above code we have created a hyperlink image of Nainital Lake which will take us to picture.php page and with it will also take the parameters name=”Nainilake” and city=”Nainital”.That is when we click on the small image of Nainital Lake we will be taken to the next page picture.php along with the parameters. As the default method is get, these parameters will be passed to the next page using get method and they will be visible in the address bar. When we want to pass values to an address they are attached to the address using a question mark (?). Here the parameter name=Nainilake is attached to the address. If we want to add more values, we can add them using ampersand (&) after every key-value pair similarly as city=Nainital is added using ampersand after the name parameter. Now after clicking on the image of Nainital Lake we want the picture.php page to be displayed with the value of parameter displayed along with it. AbhinayTiwari surindertarika1234 PHP-basics 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 Insert Form Data into Database using PHP ? How to execute PHP code using command line ? PHP in_array() Function How to convert array to string in PHP ? How to pop an alert message box using PHP ? Roadmap to Become a Web Developer in 2022 Installation of Node.js on Linux How to fetch data from an API in ReactJS ? Top 10 Projects For Beginners To Practice HTML and CSS Skills How to insert spaces/tabs in text using HTML/CSS?
[ { "code": null, "e": 40920, "s": 40892, "text": "\n29 Jun, 2021" }, { "code": null, "e": 41092, "s": 40920, "text": "We already have discussed about variables and global variables in PHP in the post PHP | Variables and Data Types. In this article, we will learn about superglobals in PHP." }, { "code": null, "e": 41517, "s": 41092, "text": "These are specially-defined array variables in PHP that make it easy for you to get information about a request or its context. The superglobals are available throughout your script. These variables can be accessed from any function, class or any file without doing any special task such as declaring any global variable etc. They are mainly used to store and get information from one page to another etc in an application. " }, { "code": null, "e": 41579, "s": 41517, "text": "Below is the list of superglobal variables available in PHP: " }, { "code": null, "e": 41645, "s": 41579, "text": "$GLOBALS$_SERVER$_REQUEST$_GET$_POST$_SESSION$_COOKIE$_FILES$_ENV" }, { "code": null, "e": 41654, "s": 41645, "text": "$GLOBALS" }, { "code": null, "e": 41663, "s": 41654, "text": "$_SERVER" }, { "code": null, "e": 41673, "s": 41663, "text": "$_REQUEST" }, { "code": null, "e": 41679, "s": 41673, "text": "$_GET" }, { "code": null, "e": 41686, "s": 41679, "text": "$_POST" }, { "code": null, "e": 41696, "s": 41686, "text": "$_SESSION" }, { "code": null, "e": 41705, "s": 41696, "text": "$_COOKIE" }, { "code": null, "e": 41713, "s": 41705, "text": "$_FILES" }, { "code": null, "e": 41719, "s": 41713, "text": "$_ENV" }, { "code": null, "e": 41782, "s": 41719, "text": "Let us now learn about some of these superglobals in detail: " }, { "code": null, "e": 42073, "s": 41782, "text": "$GLOBALS : It is a superglobal variable which is used to access global variables from anywhere in the PHP script. PHP stores all the global variables in array $GLOBALS[] where index holds the global variable name, which can be accessed.Below program illustrates the use of $GLOBALS in PHP: " }, { "code": null, "e": 42077, "s": 42073, "text": "PHP" }, { "code": "<?php$x = 300;$y = 200; function multiplication(){ $GLOBALS['z'] = $GLOBALS['x'] * $GLOBALS['y'];} multiplication();echo $z;?>", "e": 42207, "s": 42077, "text": null }, { "code": null, "e": 42217, "s": 42207, "text": "Output : " }, { "code": null, "e": 42223, "s": 42217, "text": "60000" }, { "code": null, "e": 42466, "s": 42223, "text": "In the above code two global variables are declared $x and $y which are assigned some value to them. Then a function multiplication() is defined to multiply the values of $x and $y and store in another variable $z defined in the GLOBAL array." }, { "code": null, "e": 42731, "s": 42466, "text": "$_SERVER : It is a PHP super global variable that stores the information about headers, paths and script locations. Some of these elements are used to get the information from the superglobal variable $_SERVER.Below program illustrates the use of $_SERVER in PHP: " }, { "code": null, "e": 42735, "s": 42731, "text": "PHP" }, { "code": "<?phpecho $_SERVER['PHP_SELF'];echo \"<br>\";echo $_SERVER['SERVER_NAME'];echo \"<br>\";echo $_SERVER['HTTP_HOST'];echo \"<br>\";echo $_SERVER['HTTP_USER_AGENT'];echo \"<br>\";echo $_SERVER['SCRIPT_NAME'];echo \"<br>\"?>", "e": 42946, "s": 42735, "text": null }, { "code": null, "e": 42956, "s": 42946, "text": "Output : " }, { "code": null, "e": 43222, "s": 42956, "text": "In the above code we used the $_SERVER elements to get some information. We get the current file name which is worked on using ‘PHP_SELF’ element. Then we get server name used currently using ‘SERVER_NAME’ element. And then we get the host name through ‘HTTP_HOST’." }, { "code": null, "e": 43488, "s": 43222, "text": "$_REQUEST : It is a superglobal variable which is used to collect the data after submitting a HTML form. $_REQUEST is not used mostly, because $_POST and $_GET perform the same task and are widely used.Below is the HTML and PHP code to explain how $_REQUEST works: " }, { "code": null, "e": 43493, "s": 43488, "text": "HTML" }, { "code": "<!DOCTYPE html><html><body> <form method=\"post\" action=\"<?php echo $_SERVER['PHP_SELF'];?>\"> NAME: <input type=\"text\" name=\"fname\"> <button type=\"submit\">SUBMIT</button></form><?phpif ($_SERVER[\"REQUEST_METHOD\"] == \"POST\") { $name = htmlspecialchars($_REQUEST['fname']); if(empty($name)){ echo \"Name is empty\"; } else { echo $name; }}?></body></html>", "e": 43870, "s": 43493, "text": null }, { "code": null, "e": 43880, "s": 43870, "text": "Output : " }, { "code": null, "e": 44285, "s": 43880, "text": "In the above code we have created a form that takes the name as input from the user and prints it’s name on clicking of submit button. We transport the data accepted in the form to the same page using $_SERVER[‘PHP_SELF’] element as specified in the action attribute, because we manipulate the data in the same page using the PHP code. The data is retrieved using the $_REQUEST superglobal array variable" }, { "code": null, "e": 44599, "s": 44285, "text": "$_POST : It is a super global variable used to collect data from the HTML form after submitting it. When form uses method post to transfer data, the data is not visible in the query string, because of which security levels are maintained in this method.Below is the HTML and PHP code to explain how $_POST works: " }, { "code": null, "e": 44604, "s": 44599, "text": "HTML" }, { "code": "<!DOCTYPE html><html><body> <form method=\"post\" action=\"<?php echo $_SERVER['PHP_SELF'];?>\"> <label for=\"name\">Please enter your name: </label> <input name=\"name\" type=\"text\"><br> <label for=\"age\">Please enter your age: </label> <input name=\"age\" type=\"text\"><br> <input type=\"submit\" value=\"Submit\"> <button type=\"submit\">SUBMIT</button></form><?php$nm=$_POST['name'];$age=$_POST['age'];echo \"<strong>\".$nm.\" is $age years old.</strong>\";?></body></html>", "e": 45061, "s": 44604, "text": null }, { "code": null, "e": 45071, "s": 45061, "text": "Output : " }, { "code": null, "e": 45411, "s": 45071, "text": "In the above code we have created a form that takes name and age of the user and accesses the data using $_POST super global variable when they submit the data. Since each superglobal variable is an array it can store more than one values. Hence we retrieved name and age from the $_POST variable and stored them in $nm and $age variables." }, { "code": null, "e": 45768, "s": 45411, "text": "$_GET : $_GET is a super global variable used to collect data from the HTML form after submitting it. When form uses method get to transfer data, the data is visible in the query string, therefore the values are not hidden. $_GET super global array variable stores the values that come in the URL.Below is the HTML and PHP code to explain how $_GET works: " }, { "code": null, "e": 45773, "s": 45768, "text": "HTML" }, { "code": "<!DOCTYPE html><html><head><title></title></head><body bgcolor=\"cyan\"> <?php $name = $_GET['name']; $city = $_GET['city']; echo \"<h1>This is \".$name.\" of \".$city.\"</h1><br>\"; ?> <img src = \"2.jpg\" alt = \"nanilake\" height = \"400\" width=\"500\" /></body></html>", "e": 46064, "s": 45773, "text": null }, { "code": null, "e": 46676, "s": 46064, "text": "We are actually seeing half of the logic just now. In the above code we have created a hyperlink image of Nainital Lake which will take us to picture.php page and with it will also take the parameters name=”Nainilake” and city=”Nainital”.That is when we click on the small image of Nainital Lake we will be taken to the next page picture.php along with the parameters. As the default method is get, these parameters will be passed to the next page using get method and they will be visible in the address bar. When we want to pass values to an address they are attached to the address using a question mark (?)." }, { "code": null, "e": 47058, "s": 46676, "text": "Here the parameter name=Nainilake is attached to the address. If we want to add more values, we can add them using ampersand (&) after every key-value pair similarly as city=Nainital is added using ampersand after the name parameter. Now after clicking on the image of Nainital Lake we want the picture.php page to be displayed with the value of parameter displayed along with it. " }, { "code": null, "e": 47074, "s": 47060, "text": "AbhinayTiwari" }, { "code": null, "e": 47093, "s": 47074, "text": "surindertarika1234" }, { "code": null, "e": 47104, "s": 47093, "text": "PHP-basics" }, { "code": null, "e": 47108, "s": 47104, "text": "PHP" }, { "code": null, "e": 47125, "s": 47108, "text": "Web Technologies" }, { "code": null, "e": 47129, "s": 47125, "text": "PHP" }, { "code": null, "e": 47227, "s": 47129, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 47236, "s": 47227, "text": "Comments" }, { "code": null, "e": 47249, "s": 47236, "text": "Old Comments" }, { "code": null, "e": 47299, "s": 47249, "text": "How to Insert Form Data into Database using PHP ?" }, { "code": null, "e": 47344, "s": 47299, "text": "How to execute PHP code using command line ?" }, { "code": null, "e": 47368, "s": 47344, "text": "PHP in_array() Function" }, { "code": null, "e": 47408, "s": 47368, "text": "How to convert array to string in PHP ?" }, { "code": null, "e": 47452, "s": 47408, "text": "How to pop an alert message box using PHP ?" }, { "code": null, "e": 47494, "s": 47452, "text": "Roadmap to Become a Web Developer in 2022" }, { "code": null, "e": 47527, "s": 47494, "text": "Installation of Node.js on Linux" }, { "code": null, "e": 47570, "s": 47527, "text": "How to fetch data from an API in ReactJS ?" }, { "code": null, "e": 47632, "s": 47570, "text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills" } ]
How to convert a Python csv string to array?
Easiest way is to use the str.split method to split on every occurance of ',' and map every string to the strip method to remove any leading/trailing whitespace. For example, >>> s = "1, John Doe, Boston, USA" >>> print map(str.strip, s.split(',')) ['1', 'John Doe', 'Boston', 'USA'] If you have a multi-line string with multiple lines of csv, you can split on \n and then split and strip each line. For example, >>> s = "1, John Doe, Boston, USA\n2, Jane Doe, Chicago, USA" >>> print [map(str.strip, s_inner.split(',')) for s_inner in s.splitlines()] [['1', 'John Doe', 'Boston', 'USA'], ['2', 'Jane Doe', 'Chicago', 'USA']] The csv module in Python also has a helper function, reader for achieving the same result. For example, >>> s = "1, John Doe, Boston, USA\n2, Jane Doe, Chicago, USA".splitlines() >>> import csv >>> x = csv.reader(s) >>> list(x) [['1', ' John Doe', ' Boston', ' USA'], ['2', ' Jane Doe', ' Chicago', ' USA']]
[ { "code": null, "e": 1237, "s": 1062, "text": "Easiest way is to use the str.split method to split on every occurance of ',' and map every string to the strip method to remove any leading/trailing whitespace. For example," }, { "code": null, "e": 1346, "s": 1237, "text": ">>> s = \"1, John Doe, Boston, USA\"\n>>> print map(str.strip, s.split(','))\n['1', 'John Doe', 'Boston', 'USA']" }, { "code": null, "e": 1475, "s": 1346, "text": "If you have a multi-line string with multiple lines of csv, you can split on \\n and then split and strip each line. For example," }, { "code": null, "e": 1688, "s": 1475, "text": ">>> s = \"1, John Doe, Boston, USA\\n2, Jane Doe, Chicago, USA\"\n>>> print [map(str.strip, s_inner.split(',')) for s_inner in s.splitlines()]\n[['1', 'John Doe', 'Boston', 'USA'], ['2', 'Jane Doe', 'Chicago', 'USA']]" }, { "code": null, "e": 1792, "s": 1688, "text": "The csv module in Python also has a helper function, reader for achieving the same result. For example," }, { "code": null, "e": 1996, "s": 1792, "text": ">>> s = \"1, John Doe, Boston, USA\\n2, Jane Doe, Chicago, USA\".splitlines()\n>>> import csv\n>>> x = csv.reader(s)\n>>> list(x)\n[['1', ' John Doe', ' Boston', ' USA'], ['2', ' Jane Doe', ' Chicago', ' USA']]" } ]
C++ Program to Find GCD
The Greatest Common Divisor (GCD) of two numbers is the largest number that divides both of them. For example: Let’s say we have two numbers are 45 and 27. 45 = 5 * 3 * 3 27 = 3 * 3 * 3 So, the GCD of 45 and 27 is 9. A program to find the GCD of two numbers is given as follows. Live Demo #include <iostream> using namespace std; int gcd(int a, int b) { if (b == 0) return a; return gcd(b, a % b); } int main() { int a = 105, b = 30; cout<<"GCD of "<< a <<" and "<< b <<" is "<< gcd(a, b); return 0; } GCD of 105 and 30 is 15 In the above program, gcd() is a recursive function. It has two parameters i.e. a and b. If b is greater than 0, then a is returned to the main() function. Otherwise the gcd() function recursively calls itself with the values b and a%b. This is demonstrated by the following code snippet − int gcd(int a, int b) { if (b == 0) return a; return gcd(b, a % b); } Another program to find the GCD of two numbers is as follows − Live Demo #include<iostream> using namespace std; int gcd(int a, int b) { if (a == 0 || b == 0) return 0; else if (a == b) return a; else if (a > b) return gcd(a-b, b); else return gcd(a, b-a); } int main() { int a = 105, b =30; cout<<"GCD of "<< a <<" and "<< b <<" is "<< gcd(a, b); return 0; } GCD of 105 and 30 is 15 In the above program, gcd() is a recursive function. It has two parameters i.e. a and b. If a or b is 0, the function returns 0. If a or b are equal, the function returns a. If a is greater than b, the function recursively calls itself with the values a-b and b. If b is greater than a, the function recursively calls itself with the values a and (b - a). This is demonstrated by the following code snippet. int gcd(int a, int b) { if (a == 0 || b == 0) return 0; else if (a == b) return a; else if (a > b) return gcd(a - b, b); else return gcd(a, b - a); }
[ { "code": null, "e": 1160, "s": 1062, "text": "The Greatest Common Divisor (GCD) of two numbers is the largest number that divides both of them." }, { "code": null, "e": 1218, "s": 1160, "text": "For example: Let’s say we have two numbers are 45 and 27." }, { "code": null, "e": 1248, "s": 1218, "text": "45 = 5 * 3 * 3\n27 = 3 * 3 * 3" }, { "code": null, "e": 1279, "s": 1248, "text": "So, the GCD of 45 and 27 is 9." }, { "code": null, "e": 1341, "s": 1279, "text": "A program to find the GCD of two numbers is given as follows." }, { "code": null, "e": 1352, "s": 1341, "text": " Live Demo" }, { "code": null, "e": 1583, "s": 1352, "text": "#include <iostream>\nusing namespace std;\nint gcd(int a, int b) {\n if (b == 0)\n return a;\n return gcd(b, a % b);\n}\nint main() {\n int a = 105, b = 30;\n cout<<\"GCD of \"<< a <<\" and \"<< b <<\" is \"<< gcd(a, b);\n return 0;\n}" }, { "code": null, "e": 1607, "s": 1583, "text": "GCD of 105 and 30 is 15" }, { "code": null, "e": 1897, "s": 1607, "text": "In the above program, gcd() is a recursive function. It has two parameters i.e. a and b. If b is greater than 0, then a is returned to the main() function. Otherwise the gcd() function recursively calls itself with the values b and a%b. This is demonstrated by the following code snippet −" }, { "code": null, "e": 1976, "s": 1897, "text": "int gcd(int a, int b) {\n if (b == 0)\n return a;\n return gcd(b, a % b);\n}" }, { "code": null, "e": 2039, "s": 1976, "text": "Another program to find the GCD of two numbers is as follows −" }, { "code": null, "e": 2050, "s": 2039, "text": " Live Demo" }, { "code": null, "e": 2367, "s": 2050, "text": "#include<iostream>\nusing namespace std;\nint gcd(int a, int b) {\n if (a == 0 || b == 0)\n return 0;\n else if (a == b)\n return a;\n else if (a > b)\n return gcd(a-b, b);\n else return gcd(a, b-a);\n}\nint main() {\n int a = 105, b =30;\n cout<<\"GCD of \"<< a <<\" and \"<< b <<\" is \"<< gcd(a, b);\n return 0;\n}" }, { "code": null, "e": 2391, "s": 2367, "text": "GCD of 105 and 30 is 15" }, { "code": null, "e": 2799, "s": 2391, "text": "In the above program, gcd() is a recursive function. It has two parameters i.e. a and b. If a or b is 0, the function returns 0. If a or b are equal, the function returns a. If a is greater than b, the function recursively calls itself with the values a-b and b. If b is greater than a, the function recursively calls itself with the values a and (b - a). This is demonstrated by the following code snippet." }, { "code": null, "e": 2970, "s": 2799, "text": "int gcd(int a, int b) {\n if (a == 0 || b == 0)\n return 0;\n else if (a == b)\n return a;\n else if (a > b)\n return gcd(a - b, b);\n else return gcd(a, b - a);\n}" } ]
Diameter of a Binary Tree | Practice | GeeksforGeeks
The diameter of a tree (sometimes called the width) is the number of nodes on the longest path between two end nodes. The diagram below shows two trees each with diameter nine, the leaves that form the ends of the longest path are shaded (note that there is more than one path in each tree of length nine, but no path longer than nine nodes). Example 1: Input: 1 / \ 2 3 Output: 3 Example 2: Input: 10 / \ 20 30 / \ 40 60 Output: 4 Your Task: You need to complete the function diameter() that takes root as parameter and returns the diameter. Expected Time Complexity: O(N). Expected Auxiliary Space: O(Height of the Tree). Constraints: 1 <= Number of nodes <= 10000 1 <= Data of a node <= 1000 0 ruchitchudasama1232 hours ago public: // Function to return the diameter of a Binary Tree. int dHelper(Node* root,int &diameter){ if(root==NULL){ return -1; } int lh=1+dHelper(root->left,diameter); int rh=1+dHelper(root->right,diameter); diameter=max(diameter,lh+rh); return max(lh,rh); } int diameter(Node* root) { if(root==NULL){ return -1; } int diameter=0; dHelper(root,diameter); return diameter+1; } 0 utkarshagarwal10111 hours ago class Solution { public: // Function to return the diameter of a Binary Tree. int height(Node* root){ if(!root){ return 0; } int hl = height(root->left); int hr = height(root->right); return max(hr,hl)+1; } int diameter(Node* root) { // Your code here if(!root){ return 0; } int hl = height(root->left); int hr = height(root->right); int dia = hl+hr+1; int dl = diameter(root->left); int dr = diameter(root->right); return (max(max(dr,dl),dia)); } }; -1 1ashishchauhan200215 hours ago int height(Node*root){ if(root==NULL){ return 0; } int l=height(root->left); int r=height(root->right); return max(l,r)+1; } int diameter(Node* root) { if(root==NULL) return 0; int x=diameter(root->left); int y=diameter(root->right); int h=height(root->left)+height(root->right)+1; return max(h, max(x,y)); } 0 phantom_cs2 days ago int find(Node *root,int &ma) { if(root==NULL) return 0; int lh=find(root->left,ma); int rh=find(root->right,ma); ma=max(ma,lh+rh+1); return 1+max(lh,rh); } int diameter(Node* root) { if(root==NULL) return 0; int ma=1; find(root,ma); return ma; } 0 prateek_jakhar4 days ago JAVA SOLUTION class Solution { // Function to return the diameter of a Binary Tree. int diameter(Node root) { // Your code here if(root==null) return 0; int lheight = height(root.left); int rheight = height(root.right); int ldiameter = diameter(root.left); int rdiameter = diameter(root.right); return Math.max(lheight+rheight+1, Math.max(ldiameter,rdiameter)); } static int height(Node root){ if(root==null) return 0; return Math.max(height(root.left),height(root.right))+1; } } +2 reyansh4 days ago this problem should not be in easy problem. +1 bipulharsh1236 days ago time complexity: O(n^2) space complexity: O(1) void maxRad(Node *ptr, int &frad, int rad=0){ if(!ptr) return; rad++; if(rad>frad) frad = rad; maxRad(ptr->left, frad, rad); maxRad(ptr->right, frad, rad); } int diameter(Node* root) { // Your code here if(!root) return 0; int count = 1; int leftRad=0; int rightRad=0; maxRad(root->left, leftRad); maxRad(root->right, rightRad); int total = (leftRad+rightRad+1); int leftTotal = diameter(root->left); int rightTotal = diameter(root->right); return total>leftTotal?(total>rightTotal?total:rightTotal):(leftTotal>rightTotal?leftTotal:rightTotal); } 0 pikaspark2 weeks ago C++ Solution: class Solution { public: // Function to return the diameter of a Binary Tree. int height(Node* root){ if(root == NULL) return 0; int ans1 = height(root->left); int ans2 = height(root->right); return max(1+ans1,1+ans2); } int diameter(Node* root) { // Your code here if(root == NULL) return 0; int ans1 = diameter(root->left); int ans2 = diameter(root->right); int d = 1 + height(root->left) + height(root->right); return max(d,max(ans1,ans2)); }}; 0 sikkusaurav1232 weeks ago eassy but little bit tricky in return --- class Solution { public: int solve(Node*root ,int &result) { if(root==NULL) { return 0; } int l=solve(root->left,result); int r=solve(root->right,result); int temp=1+max(l,r); int ans=max(temp,l+r+1); result=max(result,ans); return temp; } // Function to return the diameter of a Binary Tree. int diameter(Node* root) { int result=INT_MIN; solve(root,result); return result; }}; 0 moonviprant2 weeks ago pair<int,int> diameterFast(Node* root) { //base case if(root==NULL) { pair<int , int> p=make_pair(0,0); return p; } pair<int,int> left=diameterFast(root->left); pair<int,int> right=diameterFast(root->right); int op1=left.first; int op2=right.second; int op3=left.second+right.second+1; pair<int, int> ans; ans.first=max(op1,max(op2,op3)); ans.second=max(left.second, right.second)+1; return ans; } int diameter(Node* root) { return diameterFast(root).first; } 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": 634, "s": 290, "text": "The diameter of a tree (sometimes called the width) is the number of nodes on the longest path between two end nodes. The diagram below shows two trees each with diameter nine, the leaves that form the ends of the longest path are shaded (note that there is more than one path in each tree of length nine, but no path longer than nine nodes). " }, { "code": null, "e": 645, "s": 634, "text": "Example 1:" }, { "code": null, "e": 693, "s": 645, "text": "Input:\n 1\n / \\\n 2 3\nOutput: 3\n" }, { "code": null, "e": 704, "s": 693, "text": "Example 2:" }, { "code": null, "e": 785, "s": 704, "text": "Input:\n 10\n / \\\n 20 30\n / \\ \n 40 60\nOutput: 4\n" }, { "code": null, "e": 978, "s": 785, "text": "Your Task:\nYou need to complete the function diameter() that takes root as parameter and returns the diameter.\n\nExpected Time Complexity: O(N).\nExpected Auxiliary Space: O(Height of the Tree)." }, { "code": null, "e": 1049, "s": 978, "text": "Constraints:\n1 <= Number of nodes <= 10000\n1 <= Data of a node <= 1000" }, { "code": null, "e": 1053, "s": 1051, "text": "0" }, { "code": null, "e": 1083, "s": 1053, "text": "ruchitchudasama1232 hours ago" }, { "code": null, "e": 1591, "s": 1083, "text": "public:\n // Function to return the diameter of a Binary Tree.\n int dHelper(Node* root,int &diameter){\n if(root==NULL){\n return -1;\n }\n int lh=1+dHelper(root->left,diameter);\n int rh=1+dHelper(root->right,diameter);\n diameter=max(diameter,lh+rh);\n return max(lh,rh);\n }\n int diameter(Node* root) {\n if(root==NULL){\n return -1;\n }\n int diameter=0;\n dHelper(root,diameter);\n return diameter+1;\n }" }, { "code": null, "e": 1593, "s": 1591, "text": "0" }, { "code": null, "e": 1623, "s": 1593, "text": "utkarshagarwal10111 hours ago" }, { "code": null, "e": 2232, "s": 1623, "text": "class Solution {\n public:\n // Function to return the diameter of a Binary Tree.\n int height(Node* root){\n if(!root){\n return 0;\n }\n int hl = height(root->left);\n int hr = height(root->right);\n return max(hr,hl)+1;\n }\n int diameter(Node* root) {\n // Your code here\n if(!root){\n return 0;\n }\n int hl = height(root->left);\n int hr = height(root->right);\n int dia = hl+hr+1;\n int dl = diameter(root->left);\n int dr = diameter(root->right);\n return (max(max(dr,dl),dia));\n }\n};" }, { "code": null, "e": 2235, "s": 2232, "text": "-1" }, { "code": null, "e": 2266, "s": 2235, "text": "1ashishchauhan200215 hours ago" }, { "code": null, "e": 2659, "s": 2266, "text": "int height(Node*root){ if(root==NULL){ return 0; } int l=height(root->left); int r=height(root->right); return max(l,r)+1; } int diameter(Node* root) { if(root==NULL) return 0; int x=diameter(root->left); int y=diameter(root->right); int h=height(root->left)+height(root->right)+1; return max(h, max(x,y)); }" }, { "code": null, "e": 2661, "s": 2659, "text": "0" }, { "code": null, "e": 2682, "s": 2661, "text": "phantom_cs2 days ago" }, { "code": null, "e": 3040, "s": 2682, "text": "int find(Node *root,int &ma)\n {\n if(root==NULL)\n return 0;\n int lh=find(root->left,ma);\n int rh=find(root->right,ma);\n ma=max(ma,lh+rh+1);\n return 1+max(lh,rh);\n }\n int diameter(Node* root) {\n if(root==NULL)\n return 0;\n int ma=1;\n find(root,ma);\n return ma;\n }" }, { "code": null, "e": 3042, "s": 3040, "text": "0" }, { "code": null, "e": 3067, "s": 3042, "text": "prateek_jakhar4 days ago" }, { "code": null, "e": 3081, "s": 3067, "text": "JAVA SOLUTION" }, { "code": null, "e": 3666, "s": 3081, "text": "class Solution {\n // Function to return the diameter of a Binary Tree.\n int diameter(Node root) {\n // Your code here\n if(root==null) return 0;\n int lheight = height(root.left);\n int rheight = height(root.right);\n \n int ldiameter = diameter(root.left);\n int rdiameter = diameter(root.right);\n \n return Math.max(lheight+rheight+1, Math.max(ldiameter,rdiameter));\n \n }\n static int height(Node root){\n if(root==null) return 0;\n return Math.max(height(root.left),height(root.right))+1;\n }\n}" }, { "code": null, "e": 3669, "s": 3666, "text": "+2" }, { "code": null, "e": 3687, "s": 3669, "text": "reyansh4 days ago" }, { "code": null, "e": 3731, "s": 3687, "text": "this problem should not be in easy problem." }, { "code": null, "e": 3734, "s": 3731, "text": "+1" }, { "code": null, "e": 3758, "s": 3734, "text": "bipulharsh1236 days ago" }, { "code": null, "e": 3782, "s": 3758, "text": "time complexity: O(n^2)" }, { "code": null, "e": 3805, "s": 3782, "text": "space complexity: O(1)" }, { "code": null, "e": 4486, "s": 3807, "text": "void maxRad(Node *ptr, int &frad, int rad=0){ if(!ptr) return; rad++; if(rad>frad) frad = rad; maxRad(ptr->left, frad, rad); maxRad(ptr->right, frad, rad); } int diameter(Node* root) { // Your code here if(!root) return 0; int count = 1; int leftRad=0; int rightRad=0; maxRad(root->left, leftRad); maxRad(root->right, rightRad); int total = (leftRad+rightRad+1); int leftTotal = diameter(root->left); int rightTotal = diameter(root->right); return total>leftTotal?(total>rightTotal?total:rightTotal):(leftTotal>rightTotal?leftTotal:rightTotal); }" }, { "code": null, "e": 4488, "s": 4486, "text": "0" }, { "code": null, "e": 4509, "s": 4488, "text": "pikaspark2 weeks ago" }, { "code": null, "e": 4523, "s": 4509, "text": "C++ Solution:" }, { "code": null, "e": 5077, "s": 4525, "text": "class Solution { public: // Function to return the diameter of a Binary Tree. int height(Node* root){ if(root == NULL) return 0; int ans1 = height(root->left); int ans2 = height(root->right); return max(1+ans1,1+ans2); } int diameter(Node* root) { // Your code here if(root == NULL) return 0; int ans1 = diameter(root->left); int ans2 = diameter(root->right); int d = 1 + height(root->left) + height(root->right); return max(d,max(ans1,ans2)); }};" }, { "code": null, "e": 5079, "s": 5077, "text": "0" }, { "code": null, "e": 5105, "s": 5079, "text": "sikkusaurav1232 weeks ago" }, { "code": null, "e": 5147, "s": 5105, "text": "eassy but little bit tricky in return ---" }, { "code": null, "e": 5602, "s": 5147, "text": "class Solution { public: int solve(Node*root ,int &result) { if(root==NULL) { return 0; } int l=solve(root->left,result); int r=solve(root->right,result); int temp=1+max(l,r); int ans=max(temp,l+r+1); result=max(result,ans); return temp; } // Function to return the diameter of a Binary Tree. int diameter(Node* root) { int result=INT_MIN; solve(root,result); return result; }};" }, { "code": null, "e": 5604, "s": 5602, "text": "0" }, { "code": null, "e": 5627, "s": 5604, "text": "moonviprant2 weeks ago" }, { "code": null, "e": 6236, "s": 5627, "text": " pair<int,int> diameterFast(Node* root) {\n //base case\n if(root==NULL)\n {\n pair<int , int> p=make_pair(0,0);\n return p;\n }\n pair<int,int> left=diameterFast(root->left);\n pair<int,int> right=diameterFast(root->right);\n \n int op1=left.first;\n int op2=right.second;\n int op3=left.second+right.second+1;\n pair<int, int> ans;\n ans.first=max(op1,max(op2,op3));\n ans.second=max(left.second, right.second)+1;\n return ans;\n \n }\n int diameter(Node* root) {\n \n return diameterFast(root).first;\n \n }" }, { "code": null, "e": 6382, "s": 6236, "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": 6418, "s": 6382, "text": " Login to access your submissions. " }, { "code": null, "e": 6428, "s": 6418, "text": "\nProblem\n" }, { "code": null, "e": 6438, "s": 6428, "text": "\nContest\n" }, { "code": null, "e": 6501, "s": 6438, "text": "Reset the IDE using the second button on the top right corner." }, { "code": null, "e": 6649, "s": 6501, "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": 6857, "s": 6649, "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": 6963, "s": 6857, "text": "You can access the hints to get an idea about what is expected of you as well as the final solution code." } ]
Python program to right rotate n-numbers by 1 - GeeksforGeeks
31 Dec, 2020 Given a number n. The task is to print n-integers n-times (starting from 1) and right rotate the integers by after each iteration.Examples: Input : 6 Output : 1 2 3 4 5 6 2 3 4 5 6 1 3 4 5 6 1 2 4 5 6 1 2 3 5 6 1 2 3 4 6 1 2 3 4 5 Input : 3 Output : 1 2 3 2 3 1 3 1 2 Below is the implementation. Python3 def print_pattern(n): for i in range(1, n+1, 1): for j in range(1, n+1, 1): # check that if index i is # equal to j if i == j: print(j, end=" ") # if index i is less than j if i <= j: for k in range(j+1, n+1, 1): print(k, end=" ") for p in range(1, j, 1): print(p, end=" ") # print new line print() # Driver's codeprint_pattern(3) Output: 1 2 3 2 3 1 3 1 2 krishna_6431 pattern-printing Python Pattern-printing Python Python Programs pattern-printing 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 Selecting rows in pandas DataFrame based on conditions How To Convert Python Dictionary To JSON? Check if element exists in list in Python Defaultdict in Python Python | Split string into list of characters Python | Get dictionary keys as a list Python | Convert a list to dictionary Python program to check whether a number is Prime or not
[ { "code": null, "e": 24317, "s": 24289, "text": "\n31 Dec, 2020" }, { "code": null, "e": 24459, "s": 24317, "text": "Given a number n. The task is to print n-integers n-times (starting from 1) and right rotate the integers by after each iteration.Examples: " }, { "code": null, "e": 24593, "s": 24459, "text": "Input : 6\nOutput :\n1 2 3 4 5 6\n2 3 4 5 6 1\n3 4 5 6 1 2\n4 5 6 1 2 3\n5 6 1 2 3 4\n6 1 2 3 4 5\n\nInput : 3\nOutput :\n1 2 3 \n2 3 1 \n3 1 2\n\n\n" }, { "code": null, "e": 24623, "s": 24593, "text": "Below is the implementation. " }, { "code": null, "e": 24631, "s": 24623, "text": "Python3" }, { "code": "def print_pattern(n): for i in range(1, n+1, 1): for j in range(1, n+1, 1): # check that if index i is # equal to j if i == j: print(j, end=\" \") # if index i is less than j if i <= j: for k in range(j+1, n+1, 1): print(k, end=\" \") for p in range(1, j, 1): print(p, end=\" \") # print new line print() # Driver's codeprint_pattern(3)", "e": 25145, "s": 24631, "text": null }, { "code": null, "e": 25154, "s": 25145, "text": "Output: " }, { "code": null, "e": 25177, "s": 25154, "text": "1 2 3 \n2 3 1 \n3 1 2 \n\n" }, { "code": null, "e": 25192, "s": 25179, "text": "krishna_6431" }, { "code": null, "e": 25209, "s": 25192, "text": "pattern-printing" }, { "code": null, "e": 25233, "s": 25209, "text": "Python Pattern-printing" }, { "code": null, "e": 25240, "s": 25233, "text": "Python" }, { "code": null, "e": 25256, "s": 25240, "text": "Python Programs" }, { "code": null, "e": 25273, "s": 25256, "text": "pattern-printing" }, { "code": null, "e": 25371, "s": 25273, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 25380, "s": 25371, "text": "Comments" }, { "code": null, "e": 25393, "s": 25380, "text": "Old Comments" }, { "code": null, "e": 25425, "s": 25393, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 25481, "s": 25425, "text": "How to drop one or multiple columns in Pandas Dataframe" }, { "code": null, "e": 25536, "s": 25481, "text": "Selecting rows in pandas DataFrame based on conditions" }, { "code": null, "e": 25578, "s": 25536, "text": "How To Convert Python Dictionary To JSON?" }, { "code": null, "e": 25620, "s": 25578, "text": "Check if element exists in list in Python" }, { "code": null, "e": 25642, "s": 25620, "text": "Defaultdict in Python" }, { "code": null, "e": 25688, "s": 25642, "text": "Python | Split string into list of characters" }, { "code": null, "e": 25727, "s": 25688, "text": "Python | Get dictionary keys as a list" }, { "code": null, "e": 25765, "s": 25727, "text": "Python | Convert a list to dictionary" } ]
Count of triplets in an array that satisfy the given conditions - GeeksforGeeks
14 May, 2021 Given an array arr[] of N elements, the task is to find the count of triplets (arr[i], arr[j], arr[k]) such that (arr[i] + arr[j] + arr[k] = L) and (L % arr[i] = L % arr[j] = L % arr[k] = 0.Examples: Input: arr[] = {2, 4, 5, 6, 7} Output: 1 Only possible triplet is {2, 4, 6}Input: arr[] = {4, 4, 4, 4, 4} Output: 10 Approach: Consider the equations below: L = a * arr[i], L = b * arr[j] and L = c * arr[k]. Thus, arr[i] = L / a, arr[j] = L / b and arr[k] = L / c. So, using this in arr[i] + arr[j] + arr[k] = L gives L / a + L / b + L / c = L or 1 / a + 1 / b + 1 / c = 1. Now, there can only be 10 possible solutions of the above equation, which are {2, 3, 6} {2, 4, 4} {2, 6, 3} {3, 2, 6} {3, 3, 3} {3, 6, 2} {4, 2, 4} {4, 4, 2} {6, 2, 3} {6, 3, 2}All possible triplets (arr[i], arr[j], arr[k]) will satisfy these solutions. So, all these solutions can be stored in a 2D array say test[][3]. So, that all the triplets which satisfy these solutions can be found. For all i from 1 to N. Consider arr[i] as the middle element of the triplet. And find corresponding first and third elements of the triplet for all possible solutions of the equation 1 / a + 1 / b + 1 / c = 1. Find the answer for all the cases and add them to the final answer. Maintain the indices where arr[i] occurs in the array. For a given possible solution of equation X and for every number arr[i] keep the number as middle element of triplet and find the first and the third element. Apply binary search on the available set of indices for the first and the third element to find the number of occurrence of the first element from 1 to i – 1 and the number of occurrences of the third element from i + 1 to N. Multiply both the values and add it to the final answer. 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;#define ll long long int#define MAX 100001#define ROW 10#define COl 3 vector<int> indices[MAX]; // All possible solutions of the// equation 1/a + 1/b + 1/c = 1int test[ROW][COl] = { { 2, 3, 6 }, { 2, 4, 4 }, { 2, 6, 3 }, { 3, 2, 6 }, { 3, 3, 3 }, { 3, 6, 2 }, { 4, 2, 4 }, { 4, 4, 2 }, { 6, 2, 3 }, { 6, 3, 2 } }; // Function to find the tripletsint find_triplet(int array[], int n){ int answer = 0; // Storing indices of the elements for (int i = 0; i < n; i++) { indices[array[i]].push_back(i); } for (int i = 0; i < n; i++) { int y = array[i]; for (int j = 0; j < ROW; j++) { int s = test[j][1] * y; // Check if y can act as the middle // element of triplet with the given // solution of 1/a + 1/b + 1/c = 1 if (s % test[j][0] != 0) continue; if (s % test[j][2] != 0) continue; int x = s / test[j][0]; ll z = s / test[j][2]; if (x > MAX || z > MAX) continue; int l = 0; int r = indices[x].size() - 1; int first = -1; // Binary search to find the number of // possible values of the first element while (l <= r) { int m = (l + r) / 2; if (indices[x][m] < i) { first = m; l = m + 1; } else { r = m - 1; } } l = 0; r = indices[z].size() - 1; int third = -1; // Binary search to find the number of // possible values of the third element while (l <= r) { int m = (l + r) / 2; if (indices[z][m] > i) { third = m; r = m - 1; } else { l = m + 1; } } if (first != -1 && third != -1) { // Contribution to the answer would // be the multiplication of the possible // values for the first and the third element answer += (first + 1) * (indices[z].size() - third); } } } return answer;} // Driver codeint main(){ int array[] = { 2, 4, 5, 6, 7 }; int n = sizeof(array) / sizeof(array[0]); cout << find_triplet(array, n); return 0;} // Java implementation of the approachimport java.util.*; class GFG{ static int MAX = 100001;static int ROW = 10;static int COl = 3; static Vector<Integer> []indices = new Vector[MAX]; // All possible solutions of the// equation 1/a + 1/b + 1/c = 1static int test[][] = { { 2, 3, 6 }, { 2, 4, 4 }, { 2, 6, 3 }, { 3, 2, 6 }, { 3, 3, 3 }, { 3, 6, 2 }, { 4, 2, 4 }, { 4, 4, 2 }, { 6, 2, 3 }, { 6, 3, 2 } }; // Function to find the tripletsstatic int find_triplet(int array[], int n){ int answer = 0; for (int i = 0; i < MAX; i++) { indices[i] = new Vector<>(); } // Storing indices of the elements for (int i = 0; i < n; i++) { indices[array[i]].add(i); } for (int i = 0; i < n; i++) { int y = array[i]; for (int j = 0; j < ROW; j++) { int s = test[j][1] * y; // Check if y can act as the middle // element of triplet with the given // solution of 1/a + 1/b + 1/c = 1 if (s % test[j][0] != 0) continue; if (s % test[j][2] != 0) continue; int x = s / test[j][0]; int z = s / test[j][2]; if (x > MAX || z > MAX) continue; int l = 0; int r = indices[x].size() - 1; int first = -1; // Binary search to find the number of // possible values of the first element while (l <= r) { int m = (l + r) / 2; if (indices[x].get(m) < i) { first = m; l = m + 1; } else { r = m - 1; } } l = 0; r = indices[z].size() - 1; int third = -1; // Binary search to find the number of // possible values of the third element while (l <= r) { int m = (l + r) / 2; if (indices[z].get(m) > i) { third = m; r = m - 1; } else { l = m + 1; } } if (first != -1 && third != -1) { // Contribution to the answer would // be the multiplication of the possible // values for the first and the third element answer += (first + 1) * (indices[z].size() - third); } } } return answer;} // Driver codepublic static void main(String []args){ int array[] = { 2, 4, 5, 6, 7 }; int n = array.length; System.out.println(find_triplet(array, n));}} // This code is contributed by Rajput-Ji # Python3 implementation of the approachMAX = 100001ROW = 10COL = 3 indices = [0] * MAX # All possible solutions of the# equation 1/a + 1/b + 1/c = 1test = [[2, 3, 6], [2, 4, 4], [2, 6, 3], [3, 2, 6], [3, 3, 3], [3, 6, 2], [4, 2, 4], [4, 4, 2], [6, 2, 3], [6, 3, 2]] # Function to find the tripletsdef find_triplet(array, n): answer = 0 for i in range(MAX): indices[i] = [] # Storing indices of the elements for i in range(n): indices[array[i]].append(i) for i in range(n): y = array[i] for j in range(ROW): s = test[j][1] * y # Check if y can act as the middle # element of triplet with the given # solution of 1/a + 1/b + 1/c = 1 if s % test[j][0] != 0: continue if s % test[j][2] != 0: continue x = s // test[j][0] z = s // test[j][2] if x > MAX or z > MAX: continue l = 0 r = len(indices[x]) - 1 first = -1 # Binary search to find the number of # possible values of the first element while l <= r: m = (l + r) // 2 if indices[x][m] < i: first = m l = m + 1 else: r = m - 1 l = 0 r = len(indices[z]) - 1 third = -1 # Binary search to find the number of # possible values of the third element while l <= r: m = (l + r) // 2 if indices[z][m] > i: third = m r = m - 1 else: l = m + 1 if first != -1 and third != -1: # Contribution to the answer would # be the multiplication of the possible # values for the first and the third element answer += (first + 1) * (len(indices[z]) - third) return answer # Driver Codeif __name__ == "__main__": array = [2, 4, 5, 6, 7] n = len(array) print(find_triplet(array, n)) # This code is contributed by# sanjeev2552 // C# implementation of the approachusing System;using System.Collections.Generic; class GFG{ static int MAX = 100001;static int ROW = 10;static int COl = 3; static List<int> []indices = new List<int>[MAX]; // All possible solutions of the// equation 1/a + 1/b + 1/c = 1static int [,]test = { { 2, 3, 6 }, { 2, 4, 4 }, { 2, 6, 3 }, { 3, 2, 6 }, { 3, 3, 3 }, { 3, 6, 2 }, { 4, 2, 4 }, { 4, 4, 2 }, { 6, 2, 3 }, { 6, 3, 2 } }; // Function to find the tripletsstatic int find_triplet(int []array, int n){ int answer = 0; for (int i = 0; i < MAX; i++) { indices[i] = new List<int>(); } // Storing indices of the elements for (int i = 0; i < n; i++) { indices[array[i]].Add(i); } for (int i = 0; i < n; i++) { int y = array[i]; for (int j = 0; j < ROW; j++) { int s = test[j, 1] * y; // Check if y can act as the middle // element of triplet with the given // solution of 1/a + 1/b + 1/c = 1 if (s % test[j, 0] != 0) continue; if (s % test[j, 2] != 0) continue; int x = s / test[j, 0]; int z = s / test[j, 2]; if (x > MAX || z > MAX) continue; int l = 0; int r = indices[x].Count - 1; int first = -1; // Binary search to find the number of // possible values of the first element while (l <= r) { int m = (l + r) / 2; if (indices[x][m] < i) { first = m; l = m + 1; } else { r = m - 1; } } l = 0; r = indices[z].Count - 1; int third = -1; // Binary search to find the number of // possible values of the third element while (l <= r) { int m = (l + r) / 2; if (indices[z][m] > i) { third = m; r = m - 1; } else { l = m + 1; } } if (first != -1 && third != -1) { // Contribution to the answer would // be the multiplication of the possible // values for the first and the third element answer += (first + 1) * (indices[z].Count - third); } } } return answer;} // Driver codepublic static void Main(String []args){ int []array = { 2, 4, 5, 6, 7 }; int n = array.Length; Console.WriteLine(find_triplet(array, n));}} // This code is contributed by Rajput-Ji <script> // Javascript implementation of the approach var MAX = 100001var ROW = 10var COl = 3 var indices = Array.from(Array(MAX), ()=>new Array()); // All possible solutions of the// equation 1/a + 1/b + 1/c = 1var test = [ [ 2, 3, 6 ], [ 2, 4, 4 ], [ 2, 6, 3 ], [ 3, 2, 6 ], [ 3, 3, 3 ], [ 3, 6, 2 ], [ 4, 2, 4 ], [ 4, 4, 2 ], [ 6, 2, 3 ], [ 6, 3, 2 ] ]; // Function to find the tripletsfunction find_triplet(array, n){ var answer = 0; // Storing indices of the elements for (var i = 0; i < n; i++) { indices[array[i]].push(i); } for (var i = 0; i < n; i++) { var y = array[i]; for (var j = 0; j < ROW; j++) { var s = test[j][1] * y; // Check if y can act as the middle // element of triplet with the given // solution of 1/a + 1/b + 1/c = 1 if (s % test[j][0] != 0) continue; if (s % test[j][2] != 0) continue; var x = s / test[j][0]; var z = s / test[j][2]; if (x > MAX || z > MAX) continue; var l = 0; var r = indices[x].length - 1; var first = -1; // Binary search to find the number of // possible values of the first element while (l <= r) { var m = (l + r) / 2; if (indices[x][m] < i) { first = m; l = m + 1; } else { r = m - 1; } } l = 0; r = indices[z].length - 1; var third = -1; // Binary search to find the number of // possible values of the third element while (l <= r) { var m = (l + r) / 2; if (indices[z][m] > i) { third = m; r = m - 1; } else { l = m + 1; } } if (first != -1 && third != -1) { // Contribution to the answer would // be the multiplication of the possible // values for the first and the third element answer += (first + 1) * (indices[z].length - third); } } } return answer;} // Driver codevar array = [2, 4, 5, 6, 7];var n = array.length;document.write( find_triplet(array, n)); </script> 1 Rajput-Ji sanjeev2552 noob2000 Arrays Pattern Searching Searching Arrays Searching Pattern Searching Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Window Sliding Technique Trapping Rain Water Building Heap from Array Program to find sum of elements in a given array Reversal algorithm for array rotation KMP Algorithm for Pattern Searching Rabin-Karp Algorithm for Pattern Searching Naive algorithm for Pattern Searching Check if a string is substring of another Boyer Moore Algorithm for Pattern Searching
[ { "code": null, "e": 24796, "s": 24768, "text": "\n14 May, 2021" }, { "code": null, "e": 24998, "s": 24796, "text": "Given an array arr[] of N elements, the task is to find the count of triplets (arr[i], arr[j], arr[k]) such that (arr[i] + arr[j] + arr[k] = L) and (L % arr[i] = L % arr[j] = L % arr[k] = 0.Examples: " }, { "code": null, "e": 25117, "s": 24998, "text": "Input: arr[] = {2, 4, 5, 6, 7} Output: 1 Only possible triplet is {2, 4, 6}Input: arr[] = {4, 4, 4, 4, 4} Output: 10 " }, { "code": null, "e": 25131, "s": 25119, "text": "Approach: " }, { "code": null, "e": 25163, "s": 25131, "text": "Consider the equations below: " }, { "code": null, "e": 25773, "s": 25163, "text": "L = a * arr[i], L = b * arr[j] and L = c * arr[k]. Thus, arr[i] = L / a, arr[j] = L / b and arr[k] = L / c. So, using this in arr[i] + arr[j] + arr[k] = L gives L / a + L / b + L / c = L or 1 / a + 1 / b + 1 / c = 1. Now, there can only be 10 possible solutions of the above equation, which are {2, 3, 6} {2, 4, 4} {2, 6, 3} {3, 2, 6} {3, 3, 3} {3, 6, 2} {4, 2, 4} {4, 4, 2} {6, 2, 3} {6, 3, 2}All possible triplets (arr[i], arr[j], arr[k]) will satisfy these solutions. So, all these solutions can be stored in a 2D array say test[][3]. So, that all the triplets which satisfy these solutions can be found. " }, { "code": null, "e": 26053, "s": 25775, "text": "For all i from 1 to N. Consider arr[i] as the middle element of the triplet. And find corresponding first and third elements of the triplet for all possible solutions of the equation 1 / a + 1 / b + 1 / c = 1. Find the answer for all the cases and add them to the final answer." }, { "code": null, "e": 26550, "s": 26053, "text": "Maintain the indices where arr[i] occurs in the array. For a given possible solution of equation X and for every number arr[i] keep the number as middle element of triplet and find the first and the third element. Apply binary search on the available set of indices for the first and the third element to find the number of occurrence of the first element from 1 to i – 1 and the number of occurrences of the third element from i + 1 to N. Multiply both the values and add it to the final answer." }, { "code": null, "e": 26603, "s": 26550, "text": "Below is the implementation of the above approach: " }, { "code": null, "e": 26607, "s": 26603, "text": "C++" }, { "code": null, "e": 26612, "s": 26607, "text": "Java" }, { "code": null, "e": 26620, "s": 26612, "text": "Python3" }, { "code": null, "e": 26623, "s": 26620, "text": "C#" }, { "code": null, "e": 26634, "s": 26623, "text": "Javascript" }, { "code": "// C++ implementation of the approach#include <bits/stdc++.h>using namespace std;#define ll long long int#define MAX 100001#define ROW 10#define COl 3 vector<int> indices[MAX]; // All possible solutions of the// equation 1/a + 1/b + 1/c = 1int test[ROW][COl] = { { 2, 3, 6 }, { 2, 4, 4 }, { 2, 6, 3 }, { 3, 2, 6 }, { 3, 3, 3 }, { 3, 6, 2 }, { 4, 2, 4 }, { 4, 4, 2 }, { 6, 2, 3 }, { 6, 3, 2 } }; // Function to find the tripletsint find_triplet(int array[], int n){ int answer = 0; // Storing indices of the elements for (int i = 0; i < n; i++) { indices[array[i]].push_back(i); } for (int i = 0; i < n; i++) { int y = array[i]; for (int j = 0; j < ROW; j++) { int s = test[j][1] * y; // Check if y can act as the middle // element of triplet with the given // solution of 1/a + 1/b + 1/c = 1 if (s % test[j][0] != 0) continue; if (s % test[j][2] != 0) continue; int x = s / test[j][0]; ll z = s / test[j][2]; if (x > MAX || z > MAX) continue; int l = 0; int r = indices[x].size() - 1; int first = -1; // Binary search to find the number of // possible values of the first element while (l <= r) { int m = (l + r) / 2; if (indices[x][m] < i) { first = m; l = m + 1; } else { r = m - 1; } } l = 0; r = indices[z].size() - 1; int third = -1; // Binary search to find the number of // possible values of the third element while (l <= r) { int m = (l + r) / 2; if (indices[z][m] > i) { third = m; r = m - 1; } else { l = m + 1; } } if (first != -1 && third != -1) { // Contribution to the answer would // be the multiplication of the possible // values for the first and the third element answer += (first + 1) * (indices[z].size() - third); } } } return answer;} // Driver codeint main(){ int array[] = { 2, 4, 5, 6, 7 }; int n = sizeof(array) / sizeof(array[0]); cout << find_triplet(array, n); return 0;}", "e": 29358, "s": 26634, "text": null }, { "code": "// Java implementation of the approachimport java.util.*; class GFG{ static int MAX = 100001;static int ROW = 10;static int COl = 3; static Vector<Integer> []indices = new Vector[MAX]; // All possible solutions of the// equation 1/a + 1/b + 1/c = 1static int test[][] = { { 2, 3, 6 }, { 2, 4, 4 }, { 2, 6, 3 }, { 3, 2, 6 }, { 3, 3, 3 }, { 3, 6, 2 }, { 4, 2, 4 }, { 4, 4, 2 }, { 6, 2, 3 }, { 6, 3, 2 } }; // Function to find the tripletsstatic int find_triplet(int array[], int n){ int answer = 0; for (int i = 0; i < MAX; i++) { indices[i] = new Vector<>(); } // Storing indices of the elements for (int i = 0; i < n; i++) { indices[array[i]].add(i); } for (int i = 0; i < n; i++) { int y = array[i]; for (int j = 0; j < ROW; j++) { int s = test[j][1] * y; // Check if y can act as the middle // element of triplet with the given // solution of 1/a + 1/b + 1/c = 1 if (s % test[j][0] != 0) continue; if (s % test[j][2] != 0) continue; int x = s / test[j][0]; int z = s / test[j][2]; if (x > MAX || z > MAX) continue; int l = 0; int r = indices[x].size() - 1; int first = -1; // Binary search to find the number of // possible values of the first element while (l <= r) { int m = (l + r) / 2; if (indices[x].get(m) < i) { first = m; l = m + 1; } else { r = m - 1; } } l = 0; r = indices[z].size() - 1; int third = -1; // Binary search to find the number of // possible values of the third element while (l <= r) { int m = (l + r) / 2; if (indices[z].get(m) > i) { third = m; r = m - 1; } else { l = m + 1; } } if (first != -1 && third != -1) { // Contribution to the answer would // be the multiplication of the possible // values for the first and the third element answer += (first + 1) * (indices[z].size() - third); } } } return answer;} // Driver codepublic static void main(String []args){ int array[] = { 2, 4, 5, 6, 7 }; int n = array.length; System.out.println(find_triplet(array, n));}} // This code is contributed by Rajput-Ji", "e": 32231, "s": 29358, "text": null }, { "code": "# Python3 implementation of the approachMAX = 100001ROW = 10COL = 3 indices = [0] * MAX # All possible solutions of the# equation 1/a + 1/b + 1/c = 1test = [[2, 3, 6], [2, 4, 4], [2, 6, 3], [3, 2, 6], [3, 3, 3], [3, 6, 2], [4, 2, 4], [4, 4, 2], [6, 2, 3], [6, 3, 2]] # Function to find the tripletsdef find_triplet(array, n): answer = 0 for i in range(MAX): indices[i] = [] # Storing indices of the elements for i in range(n): indices[array[i]].append(i) for i in range(n): y = array[i] for j in range(ROW): s = test[j][1] * y # Check if y can act as the middle # element of triplet with the given # solution of 1/a + 1/b + 1/c = 1 if s % test[j][0] != 0: continue if s % test[j][2] != 0: continue x = s // test[j][0] z = s // test[j][2] if x > MAX or z > MAX: continue l = 0 r = len(indices[x]) - 1 first = -1 # Binary search to find the number of # possible values of the first element while l <= r: m = (l + r) // 2 if indices[x][m] < i: first = m l = m + 1 else: r = m - 1 l = 0 r = len(indices[z]) - 1 third = -1 # Binary search to find the number of # possible values of the third element while l <= r: m = (l + r) // 2 if indices[z][m] > i: third = m r = m - 1 else: l = m + 1 if first != -1 and third != -1: # Contribution to the answer would # be the multiplication of the possible # values for the first and the third element answer += (first + 1) * (len(indices[z]) - third) return answer # Driver Codeif __name__ == \"__main__\": array = [2, 4, 5, 6, 7] n = len(array) print(find_triplet(array, n)) # This code is contributed by# sanjeev2552", "e": 34432, "s": 32231, "text": null }, { "code": "// C# implementation of the approachusing System;using System.Collections.Generic; class GFG{ static int MAX = 100001;static int ROW = 10;static int COl = 3; static List<int> []indices = new List<int>[MAX]; // All possible solutions of the// equation 1/a + 1/b + 1/c = 1static int [,]test = { { 2, 3, 6 }, { 2, 4, 4 }, { 2, 6, 3 }, { 3, 2, 6 }, { 3, 3, 3 }, { 3, 6, 2 }, { 4, 2, 4 }, { 4, 4, 2 }, { 6, 2, 3 }, { 6, 3, 2 } }; // Function to find the tripletsstatic int find_triplet(int []array, int n){ int answer = 0; for (int i = 0; i < MAX; i++) { indices[i] = new List<int>(); } // Storing indices of the elements for (int i = 0; i < n; i++) { indices[array[i]].Add(i); } for (int i = 0; i < n; i++) { int y = array[i]; for (int j = 0; j < ROW; j++) { int s = test[j, 1] * y; // Check if y can act as the middle // element of triplet with the given // solution of 1/a + 1/b + 1/c = 1 if (s % test[j, 0] != 0) continue; if (s % test[j, 2] != 0) continue; int x = s / test[j, 0]; int z = s / test[j, 2]; if (x > MAX || z > MAX) continue; int l = 0; int r = indices[x].Count - 1; int first = -1; // Binary search to find the number of // possible values of the first element while (l <= r) { int m = (l + r) / 2; if (indices[x][m] < i) { first = m; l = m + 1; } else { r = m - 1; } } l = 0; r = indices[z].Count - 1; int third = -1; // Binary search to find the number of // possible values of the third element while (l <= r) { int m = (l + r) / 2; if (indices[z][m] > i) { third = m; r = m - 1; } else { l = m + 1; } } if (first != -1 && third != -1) { // Contribution to the answer would // be the multiplication of the possible // values for the first and the third element answer += (first + 1) * (indices[z].Count - third); } } } return answer;} // Driver codepublic static void Main(String []args){ int []array = { 2, 4, 5, 6, 7 }; int n = array.Length; Console.WriteLine(find_triplet(array, n));}} // This code is contributed by Rajput-Ji", "e": 37311, "s": 34432, "text": null }, { "code": "<script> // Javascript implementation of the approach var MAX = 100001var ROW = 10var COl = 3 var indices = Array.from(Array(MAX), ()=>new Array()); // All possible solutions of the// equation 1/a + 1/b + 1/c = 1var test = [ [ 2, 3, 6 ], [ 2, 4, 4 ], [ 2, 6, 3 ], [ 3, 2, 6 ], [ 3, 3, 3 ], [ 3, 6, 2 ], [ 4, 2, 4 ], [ 4, 4, 2 ], [ 6, 2, 3 ], [ 6, 3, 2 ] ]; // Function to find the tripletsfunction find_triplet(array, n){ var answer = 0; // Storing indices of the elements for (var i = 0; i < n; i++) { indices[array[i]].push(i); } for (var i = 0; i < n; i++) { var y = array[i]; for (var j = 0; j < ROW; j++) { var s = test[j][1] * y; // Check if y can act as the middle // element of triplet with the given // solution of 1/a + 1/b + 1/c = 1 if (s % test[j][0] != 0) continue; if (s % test[j][2] != 0) continue; var x = s / test[j][0]; var z = s / test[j][2]; if (x > MAX || z > MAX) continue; var l = 0; var r = indices[x].length - 1; var first = -1; // Binary search to find the number of // possible values of the first element while (l <= r) { var m = (l + r) / 2; if (indices[x][m] < i) { first = m; l = m + 1; } else { r = m - 1; } } l = 0; r = indices[z].length - 1; var third = -1; // Binary search to find the number of // possible values of the third element while (l <= r) { var m = (l + r) / 2; if (indices[z][m] > i) { third = m; r = m - 1; } else { l = m + 1; } } if (first != -1 && third != -1) { // Contribution to the answer would // be the multiplication of the possible // values for the first and the third element answer += (first + 1) * (indices[z].length - third); } } } return answer;} // Driver codevar array = [2, 4, 5, 6, 7];var n = array.length;document.write( find_triplet(array, n)); </script>", "e": 39944, "s": 37311, "text": null }, { "code": null, "e": 39946, "s": 39944, "text": "1" }, { "code": null, "e": 39958, "s": 39948, "text": "Rajput-Ji" }, { "code": null, "e": 39970, "s": 39958, "text": "sanjeev2552" }, { "code": null, "e": 39979, "s": 39970, "text": "noob2000" }, { "code": null, "e": 39986, "s": 39979, "text": "Arrays" }, { "code": null, "e": 40004, "s": 39986, "text": "Pattern Searching" }, { "code": null, "e": 40014, "s": 40004, "text": "Searching" }, { "code": null, "e": 40021, "s": 40014, "text": "Arrays" }, { "code": null, "e": 40031, "s": 40021, "text": "Searching" }, { "code": null, "e": 40049, "s": 40031, "text": "Pattern Searching" }, { "code": null, "e": 40147, "s": 40049, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 40156, "s": 40147, "text": "Comments" }, { "code": null, "e": 40169, "s": 40156, "text": "Old Comments" }, { "code": null, "e": 40194, "s": 40169, "text": "Window Sliding Technique" }, { "code": null, "e": 40214, "s": 40194, "text": "Trapping Rain Water" }, { "code": null, "e": 40239, "s": 40214, "text": "Building Heap from Array" }, { "code": null, "e": 40288, "s": 40239, "text": "Program to find sum of elements in a given array" }, { "code": null, "e": 40326, "s": 40288, "text": "Reversal algorithm for array rotation" }, { "code": null, "e": 40362, "s": 40326, "text": "KMP Algorithm for Pattern Searching" }, { "code": null, "e": 40405, "s": 40362, "text": "Rabin-Karp Algorithm for Pattern Searching" }, { "code": null, "e": 40443, "s": 40405, "text": "Naive algorithm for Pattern Searching" }, { "code": null, "e": 40485, "s": 40443, "text": "Check if a string is substring of another" } ]
Count Unique Values in R - GeeksforGeeks
30 May, 2021 In this article, we will see how we can count unique values in R programming language. Example: Input: 1 2 3 2 4 5 1 6 8 9 8 6 6 6 6 Output: 8 Unique() function when provided with a list will give out only the unique ones from it. Later length() function can calculate the frequency. Syntax: length(unique( object ) Example 1: R # Sample vectorv<-c(1,2,3,2,4,5,1,6,8,9,8,6,6,6,6)v print("Unique values") # count unique elementslength(unique(v)) Output: [1] 1 2 3 2 4 5 1 6 8 9 8 6 6 6 6 [1] “Unique values” [1] 8 With a list with multiple NA value, it will be counted as 1 separate entity. Example 2: R # Sample vectorv<-c(NA,2,NA,3,2,4,5,1,6,8,9,8,6,6,6,6)v print("Unique values") # count unique elementslength(unique(v)) Output: [1] NA 2 NA 3 2 4 5 1 6 8 9 8 6 6 6 6 [1] “Unique values” [1] 9 Example 3: R # Sample dataframedf<-data.frame(c1=c(NA,2,NA,3,2,4),c2=c(5,1,6,6,6,6))df print("Unique values") # count unique elementslength(unique(df$c1)) Output: c1 c2 1 NA 5 2 2 1 3 NA 6 4 3 6 5 2 6 6 4 6 [1] “Unique values” [1] 4 This method is not applicable for matrices Example 4: R # Sample matrixmat<-matrix(c(NA,2,NA,3,2,4,5,1,6,6,6,6),ncol=3)mat print("Unique values") # count unique elementslength(unique(mat)) Output: [,1] [,2] [,3] [1,] NA 2 6 [2,] 2 4 6 [3,] NA 5 6 [4,] 3 1 6 [1] “Unique values” [1] 12 We will be using the table() function to get the count of unique values. The table() function in R Language is used to create a categorical representation of data with the variable name and the frequency in the form of a table. Syntax: table(object) Example 1: R v <- c(5,NA,NA,2,3,4,5,3,7,8,9,5)v print("Count of unique values")table(v) Output: [1] 5 NA NA 2 3 4 5 3 7 8 9 5 [1] “Count of unique values” v 2 3 4 5 7 8 9 1 2 1 3 1 1 1 Example 2: R # Sample dataframedf<-data.frame(c1=c(NA,2,NA,3,2,4),c2=c(5,1,6,6,6,6))df print("Unique values") # count unique elementstable(df$c2) Output: c1 c2 1 NA 5 2 2 1 3 NA 6 4 3 6 5 2 6 6 4 6 [1] “Unique values” 1 5 6 1 1 4 Example 3: R # Sample matrixmat<-matrix(c(NA,2,NA,3,2,4,5,1,6,6,6,6),ncol=3)mat print("Unique values") # count unique elementstable(mat) Output: [,1] [,2] [,3] [1,] NA 2 6 [2,] 2 4 6 [3,] NA 5 6 [4,] 3 1 6 [1] “Unique values” mat 1 2 3 4 5 6 1 2 1 1 1 4 This method will return the individual frequency of each element. Syntax: as.data.frame(table(v)) Example: R # Sample vectorv<-c(1,2,3,2,4,5,1,6,8,9,8,6,6,6,6)v print("Count of Unique values") as.data.frame(table(v)) Output: [1] 1 2 3 2 4 5 1 6 8 9 8 6 6 6 6 [1] “Count of Unique values” v Freq 1 1 2 2 2 2 3 3 1 4 4 1 5 5 1 6 6 5 7 8 2 8 9 1 The aggregate() function will always return a data frame that contains all unique values from the input data frame after applying the specific function. We can only apply a single function inside an aggregate function Syntax: aggregate(data.frame(count = v), list(value = v), length) Parameters: formula: the variable(s) of the input data frame we want to apply functions on. data: the data that we want to use for group by operation. function: the function or calculation to be applied. Example: R # Sample vectorv<-c(1,2,3,2,4,5,1,6,8,9,8,6,6,6,6)v print("Count of Unique values using aggregate() function") aggregate(data.frame(count = v), list(value = v), length) Output: [1] 1 2 3 2 4 5 1 6 8 9 8 6 6 6 6 [1] “Count of Unique values using aggregate() function” value count 1 1 2 2 2 2 3 3 1 4 4 1 5 5 1 6 6 5 7 8 2 8 9 1 Picked R Object-Function R Language R Programs Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Change Color of Bars in Barchart using ggplot2 in R How to Change Axis Scales in R Plots? Group by function in R using Dplyr How to Split Column Into Multiple Columns in R DataFrame? How to filter R DataFrame by values in a column? How to Split Column Into Multiple Columns in R DataFrame? How to filter R DataFrame by values in a column? How to filter R dataframe by multiple conditions? Replace Specific Characters in String in R Convert Matrix to Dataframe in R
[ { "code": null, "e": 25242, "s": 25214, "text": "\n30 May, 2021" }, { "code": null, "e": 25329, "s": 25242, "text": "In this article, we will see how we can count unique values in R programming language." }, { "code": null, "e": 25338, "s": 25329, "text": "Example:" }, { "code": null, "e": 25376, "s": 25338, "text": "Input: 1 2 3 2 4 5 1 6 8 9 8 6 6 6 6" }, { "code": null, "e": 25386, "s": 25376, "text": "Output: 8" }, { "code": null, "e": 25527, "s": 25386, "text": "Unique() function when provided with a list will give out only the unique ones from it. Later length() function can calculate the frequency." }, { "code": null, "e": 25536, "s": 25527, "text": "Syntax: " }, { "code": null, "e": 25560, "s": 25536, "text": "length(unique( object )" }, { "code": null, "e": 25571, "s": 25560, "text": "Example 1:" }, { "code": null, "e": 25573, "s": 25571, "text": "R" }, { "code": "# Sample vectorv<-c(1,2,3,2,4,5,1,6,8,9,8,6,6,6,6)v print(\"Unique values\") # count unique elementslength(unique(v))", "e": 25691, "s": 25573, "text": null }, { "code": null, "e": 25699, "s": 25691, "text": "Output:" }, { "code": null, "e": 25734, "s": 25699, "text": " [1] 1 2 3 2 4 5 1 6 8 9 8 6 6 6 6" }, { "code": null, "e": 25754, "s": 25734, "text": "[1] “Unique values”" }, { "code": null, "e": 25760, "s": 25754, "text": "[1] 8" }, { "code": null, "e": 25837, "s": 25760, "text": "With a list with multiple NA value, it will be counted as 1 separate entity." }, { "code": null, "e": 25848, "s": 25837, "text": "Example 2:" }, { "code": null, "e": 25850, "s": 25848, "text": "R" }, { "code": "# Sample vectorv<-c(NA,2,NA,3,2,4,5,1,6,8,9,8,6,6,6,6)v print(\"Unique values\") # count unique elementslength(unique(v))", "e": 25972, "s": 25850, "text": null }, { "code": null, "e": 25980, "s": 25972, "text": "Output:" }, { "code": null, "e": 26033, "s": 25980, "text": " [1] NA 2 NA 3 2 4 5 1 6 8 9 8 6 6 6 6" }, { "code": null, "e": 26053, "s": 26033, "text": "[1] “Unique values”" }, { "code": null, "e": 26059, "s": 26053, "text": "[1] 9" }, { "code": null, "e": 26070, "s": 26059, "text": "Example 3:" }, { "code": null, "e": 26072, "s": 26070, "text": "R" }, { "code": "# Sample dataframedf<-data.frame(c1=c(NA,2,NA,3,2,4),c2=c(5,1,6,6,6,6))df print(\"Unique values\") # count unique elementslength(unique(df$c1))", "e": 26216, "s": 26072, "text": null }, { "code": null, "e": 26224, "s": 26216, "text": "Output:" }, { "code": null, "e": 26231, "s": 26224, "text": " c1 c2" }, { "code": null, "e": 26239, "s": 26231, "text": "1 NA 5" }, { "code": null, "e": 26247, "s": 26239, "text": "2 2 1" }, { "code": null, "e": 26255, "s": 26247, "text": "3 NA 6" }, { "code": null, "e": 26263, "s": 26255, "text": "4 3 6" }, { "code": null, "e": 26271, "s": 26263, "text": "5 2 6" }, { "code": null, "e": 26279, "s": 26271, "text": "6 4 6" }, { "code": null, "e": 26299, "s": 26279, "text": "[1] “Unique values”" }, { "code": null, "e": 26305, "s": 26299, "text": "[1] 4" }, { "code": null, "e": 26348, "s": 26305, "text": "This method is not applicable for matrices" }, { "code": null, "e": 26359, "s": 26348, "text": "Example 4:" }, { "code": null, "e": 26361, "s": 26359, "text": "R" }, { "code": "# Sample matrixmat<-matrix(c(NA,2,NA,3,2,4,5,1,6,6,6,6),ncol=3)mat print(\"Unique values\") # count unique elementslength(unique(mat))", "e": 26496, "s": 26361, "text": null }, { "code": null, "e": 26504, "s": 26496, "text": "Output:" }, { "code": null, "e": 26520, "s": 26504, "text": " [,1] [,2] [,3]" }, { "code": null, "e": 26540, "s": 26520, "text": "[1,] NA 2 6" }, { "code": null, "e": 26560, "s": 26540, "text": "[2,] 2 4 6" }, { "code": null, "e": 26580, "s": 26560, "text": "[3,] NA 5 6" }, { "code": null, "e": 26600, "s": 26580, "text": "[4,] 3 1 6" }, { "code": null, "e": 26620, "s": 26600, "text": "[1] “Unique values”" }, { "code": null, "e": 26627, "s": 26620, "text": "[1] 12" }, { "code": null, "e": 26855, "s": 26627, "text": "We will be using the table() function to get the count of unique values. The table() function in R Language is used to create a categorical representation of data with the variable name and the frequency in the form of a table." }, { "code": null, "e": 26864, "s": 26855, "text": "Syntax: " }, { "code": null, "e": 26878, "s": 26864, "text": "table(object)" }, { "code": null, "e": 26889, "s": 26878, "text": "Example 1:" }, { "code": null, "e": 26891, "s": 26889, "text": "R" }, { "code": "v <- c(5,NA,NA,2,3,4,5,3,7,8,9,5)v print(\"Count of unique values\")table(v)", "e": 26967, "s": 26891, "text": null }, { "code": null, "e": 26975, "s": 26967, "text": "Output:" }, { "code": null, "e": 27016, "s": 26975, "text": " [1] 5 NA NA 2 3 4 5 3 7 8 9 5" }, { "code": null, "e": 27045, "s": 27016, "text": "[1] “Count of unique values”" }, { "code": null, "e": 27047, "s": 27045, "text": "v" }, { "code": null, "e": 27061, "s": 27047, "text": "2 3 4 5 7 8 9" }, { "code": null, "e": 27076, "s": 27061, "text": "1 2 1 3 1 1 1 " }, { "code": null, "e": 27087, "s": 27076, "text": "Example 2:" }, { "code": null, "e": 27089, "s": 27087, "text": "R" }, { "code": "# Sample dataframedf<-data.frame(c1=c(NA,2,NA,3,2,4),c2=c(5,1,6,6,6,6))df print(\"Unique values\") # count unique elementstable(df$c2)", "e": 27224, "s": 27089, "text": null }, { "code": null, "e": 27232, "s": 27224, "text": "Output:" }, { "code": null, "e": 27239, "s": 27232, "text": " c1 c2" }, { "code": null, "e": 27247, "s": 27239, "text": "1 NA 5" }, { "code": null, "e": 27255, "s": 27247, "text": "2 2 1" }, { "code": null, "e": 27263, "s": 27255, "text": "3 NA 6" }, { "code": null, "e": 27271, "s": 27263, "text": "4 3 6" }, { "code": null, "e": 27279, "s": 27271, "text": "5 2 6" }, { "code": null, "e": 27287, "s": 27279, "text": "6 4 6" }, { "code": null, "e": 27307, "s": 27287, "text": "[1] “Unique values”" }, { "code": null, "e": 27313, "s": 27307, "text": "1 5 6" }, { "code": null, "e": 27320, "s": 27313, "text": "1 1 4 " }, { "code": null, "e": 27331, "s": 27320, "text": "Example 3:" }, { "code": null, "e": 27333, "s": 27331, "text": "R" }, { "code": "# Sample matrixmat<-matrix(c(NA,2,NA,3,2,4,5,1,6,6,6,6),ncol=3)mat print(\"Unique values\") # count unique elementstable(mat)", "e": 27459, "s": 27333, "text": null }, { "code": null, "e": 27467, "s": 27459, "text": "Output:" }, { "code": null, "e": 27487, "s": 27467, "text": " [,1] [,2] [,3]" }, { "code": null, "e": 27507, "s": 27487, "text": "[1,] NA 2 6" }, { "code": null, "e": 27527, "s": 27507, "text": "[2,] 2 4 6" }, { "code": null, "e": 27547, "s": 27527, "text": "[3,] NA 5 6" }, { "code": null, "e": 27567, "s": 27547, "text": "[4,] 3 1 6" }, { "code": null, "e": 27587, "s": 27567, "text": "[1] “Unique values”" }, { "code": null, "e": 27591, "s": 27587, "text": "mat" }, { "code": null, "e": 27603, "s": 27591, "text": "1 2 3 4 5 6" }, { "code": null, "e": 27616, "s": 27603, "text": "1 2 1 1 1 4 " }, { "code": null, "e": 27682, "s": 27616, "text": "This method will return the individual frequency of each element." }, { "code": null, "e": 27691, "s": 27682, "text": "Syntax: " }, { "code": null, "e": 27718, "s": 27691, "text": "as.data.frame(table(v)) " }, { "code": null, "e": 27727, "s": 27718, "text": "Example:" }, { "code": null, "e": 27729, "s": 27727, "text": "R" }, { "code": "# Sample vectorv<-c(1,2,3,2,4,5,1,6,8,9,8,6,6,6,6)v print(\"Count of Unique values\") as.data.frame(table(v))", "e": 27839, "s": 27729, "text": null }, { "code": null, "e": 27847, "s": 27839, "text": "Output:" }, { "code": null, "e": 27882, "s": 27847, "text": " [1] 1 2 3 2 4 5 1 6 8 9 8 6 6 6 6" }, { "code": null, "e": 27911, "s": 27882, "text": "[1] “Count of Unique values”" }, { "code": null, "e": 27920, "s": 27911, "text": " v Freq" }, { "code": null, "e": 27929, "s": 27920, "text": "1 1 2" }, { "code": null, "e": 27938, "s": 27929, "text": "2 2 2" }, { "code": null, "e": 27947, "s": 27938, "text": "3 3 1" }, { "code": null, "e": 27956, "s": 27947, "text": "4 4 1" }, { "code": null, "e": 27965, "s": 27956, "text": "5 5 1" }, { "code": null, "e": 27974, "s": 27965, "text": "6 6 5" }, { "code": null, "e": 27983, "s": 27974, "text": "7 8 2" }, { "code": null, "e": 27992, "s": 27983, "text": "8 9 1" }, { "code": null, "e": 28210, "s": 27992, "text": "The aggregate() function will always return a data frame that contains all unique values from the input data frame after applying the specific function. We can only apply a single function inside an aggregate function" }, { "code": null, "e": 28276, "s": 28210, "text": "Syntax: aggregate(data.frame(count = v), list(value = v), length)" }, { "code": null, "e": 28288, "s": 28276, "text": "Parameters:" }, { "code": null, "e": 28368, "s": 28288, "text": "formula: the variable(s) of the input data frame we want to apply functions on." }, { "code": null, "e": 28427, "s": 28368, "text": "data: the data that we want to use for group by operation." }, { "code": null, "e": 28480, "s": 28427, "text": "function: the function or calculation to be applied." }, { "code": null, "e": 28489, "s": 28480, "text": "Example:" }, { "code": null, "e": 28491, "s": 28489, "text": "R" }, { "code": "# Sample vectorv<-c(1,2,3,2,4,5,1,6,8,9,8,6,6,6,6)v print(\"Count of Unique values using aggregate() function\") aggregate(data.frame(count = v), list(value = v), length)", "e": 28662, "s": 28491, "text": null }, { "code": null, "e": 28670, "s": 28662, "text": "Output:" }, { "code": null, "e": 28705, "s": 28670, "text": " [1] 1 2 3 2 4 5 1 6 8 9 8 6 6 6 6" }, { "code": null, "e": 28761, "s": 28705, "text": "[1] “Count of Unique values using aggregate() function”" }, { "code": null, "e": 28775, "s": 28761, "text": " value count" }, { "code": null, "e": 28789, "s": 28775, "text": "1 1 2" }, { "code": null, "e": 28803, "s": 28789, "text": "2 2 2" }, { "code": null, "e": 28817, "s": 28803, "text": "3 3 1" }, { "code": null, "e": 28831, "s": 28817, "text": "4 4 1" }, { "code": null, "e": 28845, "s": 28831, "text": "5 5 1" }, { "code": null, "e": 28859, "s": 28845, "text": "6 6 5" }, { "code": null, "e": 28873, "s": 28859, "text": "7 8 2" }, { "code": null, "e": 28887, "s": 28873, "text": "8 9 1" }, { "code": null, "e": 28894, "s": 28887, "text": "Picked" }, { "code": null, "e": 28912, "s": 28894, "text": "R Object-Function" }, { "code": null, "e": 28923, "s": 28912, "text": "R Language" }, { "code": null, "e": 28934, "s": 28923, "text": "R Programs" }, { "code": null, "e": 29032, "s": 28934, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 29041, "s": 29032, "text": "Comments" }, { "code": null, "e": 29054, "s": 29041, "text": "Old Comments" }, { "code": null, "e": 29106, "s": 29054, "text": "Change Color of Bars in Barchart using ggplot2 in R" }, { "code": null, "e": 29144, "s": 29106, "text": "How to Change Axis Scales in R Plots?" }, { "code": null, "e": 29179, "s": 29144, "text": "Group by function in R using Dplyr" }, { "code": null, "e": 29237, "s": 29179, "text": "How to Split Column Into Multiple Columns in R DataFrame?" }, { "code": null, "e": 29286, "s": 29237, "text": "How to filter R DataFrame by values in a column?" }, { "code": null, "e": 29344, "s": 29286, "text": "How to Split Column Into Multiple Columns in R DataFrame?" }, { "code": null, "e": 29393, "s": 29344, "text": "How to filter R DataFrame by values in a column?" }, { "code": null, "e": 29443, "s": 29393, "text": "How to filter R dataframe by multiple conditions?" }, { "code": null, "e": 29486, "s": 29443, "text": "Replace Specific Characters in String in R" } ]
Program to find first positive missing integer in range in Python
Suppose we have a list of sorted list of distinct integers of size n, we have to find the first positive number in range [1 to n+1] that is not present in the array. So, if the input is like nums = [0,5,1], then the output will be 2, as 2 is the first missing number in range 1 to 5. To solve this, we will follow these steps − target := 1 target := 1 for each i in arr, doif i is same as target, thentarget := target + 1 for each i in arr, do if i is same as target, thentarget := target + 1 if i is same as target, then target := target + 1 target := target + 1 return target return target Let us see the following implementation to get better understanding − Live Demo class Solution: def solve(self, arr): target = 1 for i in arr: if i == target: target += 1 return target ob = Solution() nums = [0,5,1] print(ob.solve(nums)) [0,5,1] 2
[ { "code": null, "e": 1228, "s": 1062, "text": "Suppose we have a list of sorted list of distinct integers of size n, we have to find the first positive number in range [1 to n+1] that is not present in the array." }, { "code": null, "e": 1346, "s": 1228, "text": "So, if the input is like nums = [0,5,1], then the output will be 2, as 2 is the first missing number in range 1 to 5." }, { "code": null, "e": 1390, "s": 1346, "text": "To solve this, we will follow these steps −" }, { "code": null, "e": 1402, "s": 1390, "text": "target := 1" }, { "code": null, "e": 1414, "s": 1402, "text": "target := 1" }, { "code": null, "e": 1484, "s": 1414, "text": "for each i in arr, doif i is same as target, thentarget := target + 1" }, { "code": null, "e": 1506, "s": 1484, "text": "for each i in arr, do" }, { "code": null, "e": 1555, "s": 1506, "text": "if i is same as target, thentarget := target + 1" }, { "code": null, "e": 1584, "s": 1555, "text": "if i is same as target, then" }, { "code": null, "e": 1605, "s": 1584, "text": "target := target + 1" }, { "code": null, "e": 1626, "s": 1605, "text": "target := target + 1" }, { "code": null, "e": 1640, "s": 1626, "text": "return target" }, { "code": null, "e": 1654, "s": 1640, "text": "return target" }, { "code": null, "e": 1724, "s": 1654, "text": "Let us see the following implementation to get better understanding −" }, { "code": null, "e": 1735, "s": 1724, "text": " Live Demo" }, { "code": null, "e": 1938, "s": 1735, "text": "class Solution:\n def solve(self, arr):\n target = 1\n for i in arr:\n if i == target:\n target += 1\n return target\nob = Solution()\nnums = [0,5,1]\nprint(ob.solve(nums))" }, { "code": null, "e": 1946, "s": 1938, "text": "[0,5,1]" }, { "code": null, "e": 1948, "s": 1946, "text": "2" } ]
Difference between Virtual function and Pure virtual function in C++ - GeeksforGeeks
16 Jun, 2021 Virtual Function in C++A virtual function is a member function which is declared within a base class and is re-defined(Overriden) by a derived class. When you refer to a derived class object using a pointer or a reference to the base class, you can call a virtual function for that object and execute the derived class’s version of the function. Pure Virtual Functions in C++A pure virtual function (or abstract function) in C++ is a virtual function for which we don’t have an implementation, we only declare it. A pure virtual function is declared by assigning 0 in the declaration. Similarities between virtual function and pure virtual function These are the concepts of Run-time polymorphism.Prototype i.e. Declaration of both the functions remains the same throughout the program.These functions can’t be global or static. These are the concepts of Run-time polymorphism. Prototype i.e. Declaration of both the functions remains the same throughout the program. These functions can’t be global or static. Difference between virtual function and pure virtual function in C++ virtual<func_type><func_name>(){ // code} virtual<func_type><func_name>() = 0; sudeea mohak327 C++-Virtual Functions cpp-virtual Technical Scripter 2019 Virtual Functions C++ Difference Between Technical Scripter CPP Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Operator Overloading in C++ Polymorphism in C++ Sorting a vector in C++ Friend class and function in C++ Pair in C++ Standard Template Library (STL) Difference between BFS and DFS Class method vs Static method in Python Differences between TCP and UDP Difference between var, let and const keywords in JavaScript Difference between Process and Thread
[ { "code": null, "e": 24122, "s": 24094, "text": "\n16 Jun, 2021" }, { "code": null, "e": 24468, "s": 24122, "text": "Virtual Function in C++A virtual function is a member function which is declared within a base class and is re-defined(Overriden) by a derived class. When you refer to a derived class object using a pointer or a reference to the base class, you can call a virtual function for that object and execute the derived class’s version of the function." }, { "code": null, "e": 24707, "s": 24468, "text": "Pure Virtual Functions in C++A pure virtual function (or abstract function) in C++ is a virtual function for which we don’t have an implementation, we only declare it. A pure virtual function is declared by assigning 0 in the declaration." }, { "code": null, "e": 24771, "s": 24707, "text": "Similarities between virtual function and pure virtual function" }, { "code": null, "e": 24951, "s": 24771, "text": "These are the concepts of Run-time polymorphism.Prototype i.e. Declaration of both the functions remains the same throughout the program.These functions can’t be global or static." }, { "code": null, "e": 25000, "s": 24951, "text": "These are the concepts of Run-time polymorphism." }, { "code": null, "e": 25090, "s": 25000, "text": "Prototype i.e. Declaration of both the functions remains the same throughout the program." }, { "code": null, "e": 25133, "s": 25090, "text": "These functions can’t be global or static." }, { "code": null, "e": 25202, "s": 25133, "text": "Difference between virtual function and pure virtual function in C++" }, { "code": "virtual<func_type><func_name>(){ // code}", "e": 25247, "s": 25202, "text": null }, { "code": "virtual<func_type><func_name>() = 0;", "e": 25287, "s": 25247, "text": null }, { "code": null, "e": 25294, "s": 25287, "text": "sudeea" }, { "code": null, "e": 25303, "s": 25294, "text": "mohak327" }, { "code": null, "e": 25325, "s": 25303, "text": "C++-Virtual Functions" }, { "code": null, "e": 25337, "s": 25325, "text": "cpp-virtual" }, { "code": null, "e": 25361, "s": 25337, "text": "Technical Scripter 2019" }, { "code": null, "e": 25379, "s": 25361, "text": "Virtual Functions" }, { "code": null, "e": 25383, "s": 25379, "text": "C++" }, { "code": null, "e": 25402, "s": 25383, "text": "Difference Between" }, { "code": null, "e": 25421, "s": 25402, "text": "Technical Scripter" }, { "code": null, "e": 25425, "s": 25421, "text": "CPP" }, { "code": null, "e": 25523, "s": 25425, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 25551, "s": 25523, "text": "Operator Overloading in C++" }, { "code": null, "e": 25571, "s": 25551, "text": "Polymorphism in C++" }, { "code": null, "e": 25595, "s": 25571, "text": "Sorting a vector in C++" }, { "code": null, "e": 25628, "s": 25595, "text": "Friend class and function in C++" }, { "code": null, "e": 25672, "s": 25628, "text": "Pair in C++ Standard Template Library (STL)" }, { "code": null, "e": 25703, "s": 25672, "text": "Difference between BFS and DFS" }, { "code": null, "e": 25743, "s": 25703, "text": "Class method vs Static method in Python" }, { "code": null, "e": 25775, "s": 25743, "text": "Differences between TCP and UDP" }, { "code": null, "e": 25836, "s": 25775, "text": "Difference between var, let and const keywords in JavaScript" } ]
PL/SQL - Comparison Operators
Comparison operators are used for comparing one expression to another. The result is always either TRUE, FALSE or NULL. This program tests the LIKE operator. Here, we will use a small procedure() to show the functionality of the LIKE operator − DECLARE PROCEDURE compare (value varchar2, pattern varchar2 ) is BEGIN IF value LIKE pattern THEN dbms_output.put_line ('True'); ELSE dbms_output.put_line ('False'); END IF; END; BEGIN compare('Zara Ali', 'Z%A_i'); compare('Nuha Ali', 'Z%A_i'); END; / When the above code is executed at the SQL prompt, it produces the following result − True False PL/SQL procedure successfully completed. The following program shows the usage of the BETWEEN operator − DECLARE x number(2) := 10; BEGIN IF (x between 5 and 20) THEN dbms_output.put_line('True'); ELSE dbms_output.put_line('False'); END IF; IF (x BETWEEN 5 AND 10) THEN dbms_output.put_line('True'); ELSE dbms_output.put_line('False'); END IF; IF (x BETWEEN 11 AND 20) THEN dbms_output.put_line('True'); ELSE dbms_output.put_line('False'); END IF; END; / When the above code is executed at the SQL prompt, it produces the following result − True True False PL/SQL procedure successfully completed. The following program shows the usage of IN and IS NULL operators − ECLARE letter varchar2(1) := 'm'; BEGIN IF (letter in ('a', 'b', 'c')) THEN dbms_output.put_line('True'); ELSE dbms_output.put_line('False'); END IF; IF (letter in ('m', 'n', 'o')) THEN dbms_output.put_line('True'); ELSE dbms_output.put_line('False'); END IF; IF (letter is null) THEN dbms_output.put_line('True'); ELSE dbms_output.put_line('False'); END IF; END; / When the above code is executed at SQL prompt, it produces the following result: False True False PL/SQL procedure successfully completed. Print Add Notes Bookmark this page
[ { "code": null, "e": 2185, "s": 2065, "text": "Comparison operators are used for comparing one expression to another. The result is always either TRUE, FALSE or NULL." }, { "code": null, "e": 2310, "s": 2185, "text": "This program tests the LIKE operator. Here, we will use a small procedure() to show the functionality of the LIKE operator −" }, { "code": null, "e": 2605, "s": 2310, "text": "DECLARE \nPROCEDURE compare (value varchar2, pattern varchar2 ) is \nBEGIN \n IF value LIKE pattern THEN \n dbms_output.put_line ('True'); \n ELSE \n dbms_output.put_line ('False'); \n END IF; \nEND; \nBEGIN \n compare('Zara Ali', 'Z%A_i'); \n compare('Nuha Ali', 'Z%A_i'); \nEND; \n/" }, { "code": null, "e": 2691, "s": 2605, "text": "When the above code is executed at the SQL prompt, it produces the following result −" }, { "code": null, "e": 2748, "s": 2691, "text": "True \nFalse \n\nPL/SQL procedure successfully completed.\n" }, { "code": null, "e": 2812, "s": 2748, "text": "The following program shows the usage of the BETWEEN operator −" }, { "code": null, "e": 3257, "s": 2812, "text": "DECLARE \n x number(2) := 10; \nBEGIN \n IF (x between 5 and 20) THEN \n dbms_output.put_line('True'); \n ELSE \n dbms_output.put_line('False'); \n END IF; \n \n IF (x BETWEEN 5 AND 10) THEN \n dbms_output.put_line('True'); \n ELSE \n dbms_output.put_line('False'); \n END IF; \n \n IF (x BETWEEN 11 AND 20) THEN \n dbms_output.put_line('True'); \n ELSE \n dbms_output.put_line('False'); \n END IF; \nEND; \n/" }, { "code": null, "e": 3343, "s": 3257, "text": "When the above code is executed at the SQL prompt, it produces the following result −" }, { "code": null, "e": 3406, "s": 3343, "text": "True \nTrue \nFalse \n \nPL/SQL procedure successfully completed.\n" }, { "code": null, "e": 3474, "s": 3406, "text": "The following program shows the usage of IN and IS NULL operators −" }, { "code": null, "e": 3933, "s": 3474, "text": "ECLARE \n letter varchar2(1) := 'm'; \nBEGIN \n IF (letter in ('a', 'b', 'c')) THEN \n dbms_output.put_line('True'); \n ELSE \n dbms_output.put_line('False'); \n END IF; \n \n IF (letter in ('m', 'n', 'o')) THEN \n dbms_output.put_line('True'); \n ELSE \n dbms_output.put_line('False'); \n END IF; \n \n IF (letter is null) THEN \n dbms_output.put_line('True'); \n ELSE \n dbms_output.put_line('False'); \n END IF; \nEND; \n/ " }, { "code": null, "e": 4014, "s": 3933, "text": "When the above code is executed at SQL prompt, it produces the following result:" }, { "code": null, "e": 4074, "s": 4014, "text": "False\nTrue\nFalse\n\nPL/SQL procedure successfully completed.\n" }, { "code": null, "e": 4081, "s": 4074, "text": " Print" }, { "code": null, "e": 4092, "s": 4081, "text": " Add Notes" } ]
How to find the raise to the power of all values in an R vector?
Often, we need to find the power of a value or the power of all values in an R vector, especially in cases when we are dealing with polynomial models. This can be done by using ^ sign as we do in Excel. For example, if we have a vector x then the square of all values in x can be found as x^2. Live Demo x1<-1:10 x1 [1] 1 2 3 4 5 6 7 8 9 10 square_x1<-x1^2 square_x1 [1] 1 4 9 16 25 36 49 64 81 100 Live Demo x2<-rpois(50,2) x2 [1] 5 3 4 2 1 8 1 4 0 2 3 5 2 3 4 6 3 3 4 2 4 3 2 1 1 0 1 0 2 1 1 0 1 1 4 2 3 4 [39] 1 2 2 2 1 1 6 0 4 1 3 2 square_x2 [1] 25 9 16 4 1 64 1 16 0 4 9 25 4 9 16 36 9 9 16 4 16 9 4 1 1 [26] 0 1 0 4 1 1 0 1 1 16 4 9 16 1 4 4 4 1 1 36 0 16 1 9 4 Live Demo x3<-rpois(100,10) x3 [1] 9 10 12 15 12 7 10 11 9 9 13 7 8 11 7 12 11 12 7 10 9 4 12 11 8 [26] 9 10 16 12 9 11 8 9 8 8 10 7 11 7 11 16 9 10 10 11 14 11 12 7 9 [51] 4 14 4 13 11 13 9 9 13 6 15 11 11 7 10 19 12 6 11 14 11 7 7 16 8 [76] 9 9 5 15 12 7 9 10 10 9 14 3 9 12 12 13 9 11 9 9 15 10 15 5 8 x3_power_3<-x3^3 x3_power_3 [1] 729 1000 1728 3375 1728 343 1000 1331 729 729 2197 343 512 1331 343 [16] 1728 1331 1728 343 1000 729 64 1728 1331 512 729 1000 4096 1728 729 [31] 1331 512 729 512 512 1000 343 1331 343 1331 4096 729 1000 1000 1331 [46] 2744 1331 1728 343 729 64 2744 64 2197 1331 2197 729 729 2197 216 [61] 3375 1331 1331 343 1000 6859 1728 216 1331 2744 1331 343 343 4096 512 [76] 729 729 125 3375 1728 343 729 1000 1000 729 2744 27 729 1728 1728 [91] 2197 729 1331 729 729 3375 1000 3375 125 512 Live Demo x4<-rpois(100,10) x4 [1] 13 10 11 8 12 12 7 11 6 11 8 13 9 11 8 3 4 7 11 14 7 9 8 12 8 [26] 6 11 8 12 6 9 5 11 9 10 12 9 5 6 10 9 13 13 8 14 6 9 14 12 10 [51] 8 9 9 4 11 11 11 8 12 9 9 6 9 7 9 6 5 13 8 10 8 4 10 10 7 [76] 16 8 13 11 8 6 13 12 8 7 11 9 8 14 8 5 9 12 7 6 9 11 14 14 8 x4_power_1_by_4<-x4^(1/4) x4_power_1_by_4 [1] 1.898829 1.778279 1.821160 1.681793 1.861210 1.861210 1.626577 1.821160 [9] 1.565085 1.821160 1.681793 1.898829 1.732051 1.821160 1.681793 1.316074 [17] 1.414214 1.626577 1.821160 1.934336 1.626577 1.732051 1.681793 1.861210 [25] 1.681793 1.565085 1.821160 1.681793 1.861210 1.565085 1.732051 1.495349 [33] 1.821160 1.732051 1.778279 1.861210 1.732051 1.495349 1.565085 1.778279 [41] 1.732051 1.898829 1.898829 1.681793 1.934336 1.565085 1.732051 1.934336 [49] 1.861210 1.778279 1.681793 1.732051 1.732051 1.414214 1.821160 1.821160 [57] 1.821160 1.681793 1.861210 1.732051 1.732051 1.565085 1.732051 1.626577 [65] 1.732051 1.565085 1.495349 1.898829 1.681793 1.778279 1.681793 1.414214 [73] 1.778279 1.778279 1.626577 2.000000 1.681793 1.898829 1.821160 1.681793 [81] 1.565085 1.898829 1.861210 1.681793 1.626577 1.821160 1.732051 1.681793 [89] 1.934336 1.681793 1.495349 1.732051 1.861210 1.626577 1.565085 1.732051 [97] 1.821160 1.934336 1.934336 1.681793 Live Demo x5<-rpois(100,10) x5 [1] 12 9 16 11 10 6 12 16 15 14 7 5 6 14 6 8 10 11 14 10 10 6 9 11 13 [26] 12 11 20 7 7 5 18 11 13 7 15 15 6 9 10 13 6 6 7 8 8 16 10 7 9 [51] 12 4 8 9 7 9 10 14 13 21 7 14 5 9 9 13 7 6 12 11 10 12 6 14 8 [76] 11 7 9 8 10 9 12 15 8 6 7 8 4 12 10 9 11 11 11 15 7 10 12 16 12 x5_power_3_by_4<-x5^(3/4) x5_power_3_by_4 [1] 6.447420 5.196152 8.000000 6.040105 5.623413 3.833659 6.447420 8.000000 [9] 7.621991 7.237624 4.303517 3.343702 3.833659 7.237624 3.833659 4.756828 [17] 5.623413 6.040105 7.237624 5.623413 5.623413 3.833659 5.196152 6.040105 [25] 6.846325 6.447420 6.040105 9.457416 4.303517 4.303517 3.343702 8.738852 [33] 6.040105 6.846325 4.303517 7.621991 7.621991 3.833659 5.196152 5.623413 [41] 6.846325 3.833659 3.833659 4.303517 4.756828 4.756828 8.000000 5.623413 [49] 4.303517 5.196152 6.447420 2.828427 4.756828 5.196152 4.303517 5.196152 [57] 5.623413 7.237624 6.846325 9.809898 4.303517 7.237624 3.343702 5.196152 [65] 5.196152 6.846325 4.303517 3.833659 6.447420 6.040105 5.623413 6.447420 [73] 3.833659 7.237624 4.756828 6.040105 4.303517 5.196152 4.756828 5.623413 [81] 5.196152 6.447420 7.621991 4.756828 3.833659 4.303517 4.756828 2.828427 [89] 6.447420 5.623413 5.196152 6.040105 6.040105 6.040105 7.621991 4.303517 [97] 5.623413 6.447420 8.000000 6.447420 Live Demo x6<-sample(1:10,100,replace=TRUE) x6 [1] 5 5 9 8 2 9 5 4 7 10 6 5 1 2 7 3 6 1 3 4 3 10 4 3 6 [26] 8 8 2 8 4 1 8 4 8 2 3 4 1 8 10 8 8 6 3 7 2 9 9 6 10 [51] 7 8 1 9 5 2 5 2 8 3 1 6 2 3 5 1 2 4 5 1 5 4 6 9 7 [76] 2 4 3 2 7 6 5 1 9 10 6 7 1 2 5 10 5 5 6 4 6 1 4 8 9 x6_2<-x6^2 x6_2 [1] 25 25 81 64 4 81 25 16 49 100 36 25 1 4 49 9 36 1 [19] 9 16 9 100 16 9 36 64 64 4 64 16 1 64 16 64 4 9 [37] 16 1 64 100 64 64 36 9 49 4 81 81 36 100 49 64 1 81 [55] 25 4 25 4 64 9 1 36 4 9 25 1 4 16 25 1 25 16 [73] 36 81 49 4 16 9 4 49 36 25 1 81 100 36 49 1 4 25 [91] 100 25 25 36 16 36 1 16 64 81 Live Demo x7<-rnorm(50,5,10) x7 [1] 3.2380130 -5.5553674 17.3906895 16.2782636 -1.8551276 22.5405542 [7] 7.8591889 4.0376126 10.3603525 -2.0983122 7.7640085 8.0753874 [13] -3.2625302 9.4534281 -0.4951846 -9.4298196 2.7521265 8.0154121 [19] 6.7455055 -0.8284140 2.7099639 14.9538382 12.0254986 -5.6911766 [25] 3.8437799 11.9242421 -11.7194797 6.6024536 -2.7468949 6.1553066 [31] -5.3897772 6.7756489 21.8886362 16.7859536 1.1068733 -5.7264846 [37] 1.0465364 -3.4498760 -1.5594048 -20.0699144 6.6783996 17.1561048 [43] 7.5514595 21.1906289 4.9587869 8.1482000 6.6485102 -2.1266452 [49] -7.7655759 15.6812337 x7_power_3<-x7^3 x7_power_3 [1] 33.9496856 -171.4503457 5259.5720057 4313.4446351 -6.3844187 [6] 11452.3277148 485.4373498 65.8224351 1112.0481567 -9.2386881 [11] 468.0130992 526.6112109 -34.7267073 844.8273724 -0.1214232 [16] -838.5136714 20.8451568 514.9648182 306.9329436 -0.5685154 [21] 19.9017160 3343.9365954 1739.0388326 -184.3343100 56.7904796 [26] 1695.4787867 -1609.6260698 287.8167592 -20.7265065 233.2110260 [31] -156.5714026 311.0660965 10487.1169231 4729.7485860 1.3561062 [36] -187.7864627 1.1462069 -41.0591968 -3.7920724 -8084.1908915 [41] 297.8634392 5049.5894784 430.6185016 9515.4983018 121.9344257 [46] 540.9847640 293.8820194 -9.6180080 -468.2966028 3856.0324360
[ { "code": null, "e": 1356, "s": 1062, "text": "Often, we need to find the power of a value or the power of all values in an R vector, especially in cases when we are dealing with polynomial models. This can be done by using ^ sign as we do in Excel. For example, if we have a vector x then the square of all values in x can be found as x^2." }, { "code": null, "e": 1367, "s": 1356, "text": " Live Demo" }, { "code": null, "e": 1379, "s": 1367, "text": "x1<-1:10\nx1" }, { "code": null, "e": 1405, "s": 1379, "text": "[1] 1 2 3 4 5 6 7 8 9 10\n" }, { "code": null, "e": 1431, "s": 1405, "text": "square_x1<-x1^2\nsquare_x1" }, { "code": null, "e": 1464, "s": 1431, "text": "[1] 1 4 9 16 25 36 49 64 81 100\n" }, { "code": null, "e": 1475, "s": 1464, "text": " Live Demo" }, { "code": null, "e": 1494, "s": 1475, "text": "x2<-rpois(50,2)\nx2" }, { "code": null, "e": 1603, "s": 1494, "text": "[1] 5 3 4 2 1 8 1 4 0 2 3 5 2 3 4 6 3 3 4 2 4 3 2 1 1 0 1 0 2 1 1 0 1 1 4 2 3 4\n[39] 1 2 2 2 1 1 6 0 4 1 3 2" }, { "code": null, "e": 1613, "s": 1603, "text": "square_x2" }, { "code": null, "e": 1735, "s": 1613, "text": "[1] 25 9 16 4 1 64 1 16 0 4 9 25 4 9 16 36 9 9 16 4 16 9 4 1 1\n[26] 0 1 0 4 1 1 0 1 1 16 4 9 16 1 4 4 4 1 1 36 0 16 1 9 4" }, { "code": null, "e": 1746, "s": 1735, "text": " Live Demo" }, { "code": null, "e": 1767, "s": 1746, "text": "x3<-rpois(100,10)\nx3" }, { "code": null, "e": 2041, "s": 1767, "text": "[1] 9 10 12 15 12 7 10 11 9 9 13 7 8 11 7 12 11 12 7 10 9 4 12 11 8\n[26] 9 10 16 12 9 11 8 9 8 8 10 7 11 7 11 16 9 10 10 11 14 11 12 7 9\n[51] 4 14 4 13 11 13 9 9 13 6 15 11 11 7 10 19 12 6 11 14 11 7 7 16 8\n[76] 9 9 5 15 12 7 9 10 10 9 14 3 9 12 12 13 9 11 9 9 15 10 15 5 8" }, { "code": null, "e": 2069, "s": 2041, "text": "x3_power_3<-x3^3\nx3_power_3" }, { "code": null, "e": 2554, "s": 2069, "text": "[1] 729 1000 1728 3375 1728 343 1000 1331 729 729 2197 343 512 1331 343\n[16] 1728 1331 1728 343 1000 729 64 1728 1331 512 729 1000 4096 1728 729\n[31] 1331 512 729 512 512 1000 343 1331 343 1331 4096 729 1000 1000 1331\n[46] 2744 1331 1728 343 729 64 2744 64 2197 1331 2197 729 729 2197 216\n[61] 3375 1331 1331 343 1000 6859 1728 216 1331 2744 1331 343 343 4096 512\n[76] 729 729 125 3375 1728 343 729 1000 1000 729 2744 27 729 1728 1728\n[91] 2197 729 1331 729 729 3375 1000 3375 125 512" }, { "code": null, "e": 2565, "s": 2554, "text": " Live Demo" }, { "code": null, "e": 2586, "s": 2565, "text": "x4<-rpois(100,10)\nx4" }, { "code": null, "e": 2848, "s": 2586, "text": "[1] 13 10 11 8 12 12 7 11 6 11 8 13 9 11 8 3 4 7 11 14 7 9 8 12 8\n[26] 6 11 8 12 6 9 5 11 9 10 12 9 5 6 10 9 13 13 8 14 6 9 14 12 10\n[51] 8 9 9 4 11 11 11 8 12 9 9 6 9 7 9 6 5 13 8 10 8 4 10 10 7\n[76] 16 8 13 11 8 6 13 12 8 7 11 9 8 14 8 5 9 12 7 6 9 11 14 14 8" }, { "code": null, "e": 2890, "s": 2848, "text": "x4_power_1_by_4<-x4^(1/4)\nx4_power_1_by_4" }, { "code": null, "e": 3853, "s": 2890, "text": "[1] 1.898829 1.778279 1.821160 1.681793 1.861210 1.861210 1.626577 1.821160\n[9] 1.565085 1.821160 1.681793 1.898829 1.732051 1.821160 1.681793 1.316074\n[17] 1.414214 1.626577 1.821160 1.934336 1.626577 1.732051 1.681793 1.861210\n[25] 1.681793 1.565085 1.821160 1.681793 1.861210 1.565085 1.732051 1.495349\n[33] 1.821160 1.732051 1.778279 1.861210 1.732051 1.495349 1.565085 1.778279\n[41] 1.732051 1.898829 1.898829 1.681793 1.934336 1.565085 1.732051 1.934336\n[49] 1.861210 1.778279 1.681793 1.732051 1.732051 1.414214 1.821160 1.821160\n[57] 1.821160 1.681793 1.861210 1.732051 1.732051 1.565085 1.732051 1.626577\n[65] 1.732051 1.565085 1.495349 1.898829 1.681793 1.778279 1.681793 1.414214\n[73] 1.778279 1.778279 1.626577 2.000000 1.681793 1.898829 1.821160 1.681793\n[81] 1.565085 1.898829 1.861210 1.681793 1.626577 1.821160 1.732051 1.681793\n[89] 1.934336 1.681793 1.495349 1.732051 1.861210 1.626577 1.565085 1.732051\n[97] 1.821160 1.934336 1.934336 1.681793" }, { "code": null, "e": 3864, "s": 3853, "text": " Live Demo" }, { "code": null, "e": 3885, "s": 3864, "text": "x5<-rpois(100,10)\nx5" }, { "code": null, "e": 4158, "s": 3885, "text": "[1] 12 9 16 11 10 6 12 16 15 14 7 5 6 14 6 8 10 11 14 10 10 6 9 11 13\n[26] 12 11 20 7 7 5 18 11 13 7 15 15 6 9 10 13 6 6 7 8 8 16 10 7 9\n[51] 12 4 8 9 7 9 10 14 13 21 7 14 5 9 9 13 7 6 12 11 10 12 6 14 8\n[76] 11 7 9 8 10 9 12 15 8 6 7 8 4 12 10 9 11 11 11 15 7 10 12 16 12" }, { "code": null, "e": 4200, "s": 4158, "text": "x5_power_3_by_4<-x5^(3/4)\nx5_power_3_by_4" }, { "code": null, "e": 5163, "s": 4200, "text": "[1] 6.447420 5.196152 8.000000 6.040105 5.623413 3.833659 6.447420 8.000000\n[9] 7.621991 7.237624 4.303517 3.343702 3.833659 7.237624 3.833659 4.756828\n[17] 5.623413 6.040105 7.237624 5.623413 5.623413 3.833659 5.196152 6.040105\n[25] 6.846325 6.447420 6.040105 9.457416 4.303517 4.303517 3.343702 8.738852\n[33] 6.040105 6.846325 4.303517 7.621991 7.621991 3.833659 5.196152 5.623413\n[41] 6.846325 3.833659 3.833659 4.303517 4.756828 4.756828 8.000000 5.623413\n[49] 4.303517 5.196152 6.447420 2.828427 4.756828 5.196152 4.303517 5.196152\n[57] 5.623413 7.237624 6.846325 9.809898 4.303517 7.237624 3.343702 5.196152\n[65] 5.196152 6.846325 4.303517 3.833659 6.447420 6.040105 5.623413 6.447420\n[73] 3.833659 7.237624 4.756828 6.040105 4.303517 5.196152 4.756828 5.623413\n[81] 5.196152 6.447420 7.621991 4.756828 3.833659 4.303517 4.756828 2.828427\n[89] 6.447420 5.623413 5.196152 6.040105 6.040105 6.040105 7.621991 4.303517\n[97] 5.623413 6.447420 8.000000 6.447420" }, { "code": null, "e": 5174, "s": 5163, "text": " Live Demo" }, { "code": null, "e": 5211, "s": 5174, "text": "x6<-sample(1:10,100,replace=TRUE)\nx6" }, { "code": null, "e": 5436, "s": 5211, "text": "[1] 5 5 9 8 2 9 5 4 7 10 6 5 1 2 7 3 6 1 3 4 3 10 4 3 6\n[26] 8 8 2 8 4 1 8 4 8 2 3 4 1 8 10 8 8 6 3 7 2 9 9 6 10\n[51] 7 8 1 9 5 2 5 2 8 3 1 6 2 3 5 1 2 4 5 1 5 4 6 9 7\n[76] 2 4 3 2 7 6 5 1 9 10 6 7 1 2 5 10 5 5 6 4 6 1 4 8 9" }, { "code": null, "e": 5452, "s": 5436, "text": "x6_2<-x6^2\nx6_2" }, { "code": null, "e": 5755, "s": 5452, "text": "[1] 25 25 81 64 4 81 25 16 49 100 36 25 1 4 49 9 36 1\n[19] 9 16 9 100 16 9 36 64 64 4 64 16 1 64 16 64 4 9\n[37] 16 1 64 100 64 64 36 9 49 4 81 81 36 100 49 64 1 81\n[55] 25 4 25 4 64 9 1 36 4 9 25 1 4 16 25 1 25 16\n[73] 36 81 49 4 16 9 4 49 36 25 1 81 100 36 49 1 4 25\n[91] 100 25 25 36 16 36 1 16 64 81" }, { "code": null, "e": 5766, "s": 5755, "text": " Live Demo" }, { "code": null, "e": 5788, "s": 5766, "text": "x7<-rnorm(50,5,10)\nx7" }, { "code": null, "e": 6362, "s": 5788, "text": "[1] 3.2380130 -5.5553674 17.3906895 16.2782636 -1.8551276 22.5405542\n[7] 7.8591889 4.0376126 10.3603525 -2.0983122 7.7640085 8.0753874\n[13] -3.2625302 9.4534281 -0.4951846 -9.4298196 2.7521265 8.0154121\n[19] 6.7455055 -0.8284140 2.7099639 14.9538382 12.0254986 -5.6911766\n[25] 3.8437799 11.9242421 -11.7194797 6.6024536 -2.7468949 6.1553066\n[31] -5.3897772 6.7756489 21.8886362 16.7859536 1.1068733 -5.7264846\n[37] 1.0465364 -3.4498760 -1.5594048 -20.0699144 6.6783996 17.1561048\n[43] 7.5514595 21.1906289 4.9587869 8.1482000 6.6485102 -2.1266452\n[49] -7.7655759 15.6812337" }, { "code": null, "e": 6390, "s": 6362, "text": "x7_power_3<-x7^3\nx7_power_3" }, { "code": null, "e": 7047, "s": 6390, "text": "[1] 33.9496856 -171.4503457 5259.5720057 4313.4446351 -6.3844187\n[6] 11452.3277148 485.4373498 65.8224351 1112.0481567 -9.2386881\n[11] 468.0130992 526.6112109 -34.7267073 844.8273724 -0.1214232\n[16] -838.5136714 20.8451568 514.9648182 306.9329436 -0.5685154\n[21] 19.9017160 3343.9365954 1739.0388326 -184.3343100 56.7904796\n[26] 1695.4787867 -1609.6260698 287.8167592 -20.7265065 233.2110260\n[31] -156.5714026 311.0660965 10487.1169231 4729.7485860 1.3561062\n[36] -187.7864627 1.1462069 -41.0591968 -3.7920724 -8084.1908915\n[41] 297.8634392 5049.5894784 430.6185016 9515.4983018 121.9344257\n[46] 540.9847640 293.8820194 -9.6180080 -468.2966028 3856.0324360" } ]
p5.js | storeItem() Function - GeeksforGeeks
17 Jan, 2020 The storeItem() function is used to store a given value under a key name in the local storage of the browser. The local storage persists between browsing sessions and can store values even after reloading the page. It can be used to save non-sensitive information, such as user preferences. Sensitive data like personal information should not be stored as this storage is easily accessible. Syntax: storeItem(key, value) Parameters: This function accepts two parameters as mentioned above and described below: key: This is a string which denotes the key under which the value would be stored. value: This is any value that can be stored under the key. It can be a String, Number, Boolean, Object, p5.Color or a p5.Vector. Below example illustrates the storeItem() function in p5.js: Example: function setup() { createCanvas(400, 300); fill("green"); text("Click anywhere to draw a circle", 10, 20); text("The last circle would be redrawn when page is refreshed", 10, 40); // get the coordinates // from localStorage oldX = getItem('xpos'); oldY = getItem('ypos'); // check if the values are // actually present (not null) if (oldX != null && oldY != null) circle(oldX, oldY, 100); } function mouseClicked() { clear(); fill("green"); text("Click anywhere to draw a circle", 10, 20); text("The last circle would be redrawn when page is refreshed", 10, 40); posX = mouseX; posY = mouseY; circle(posX, posY, 100); // set the coordinates // to localStorage storeItem('xpos', posX); storeItem('ypos', posY);} Output: Local storage of the browserOnline editor: https://editor.p5js.org/Environment Setup: https://www.geeksforgeeks.org/p5-js-soundfile-object-installation-and-methods/Reference: https://p5js.org/reference/#/p5/storeItemMy Personal Notes arrow_drop_upSave Online editor: https://editor.p5js.org/Environment Setup: https://www.geeksforgeeks.org/p5-js-soundfile-object-installation-and-methods/ Reference: https://p5js.org/reference/#/p5/storeItem JavaScript-p5.js JavaScript Web Technologies Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Convert a string to an integer in JavaScript How to calculate the number of days between two dates in javascript? Difference between var, let and const keywords in JavaScript Differences between Functional Components and Class Components in React File uploading in React.js Roadmap to Become a Web Developer in 2022 Installation of Node.js on Linux How to insert spaces/tabs in text using HTML/CSS? Top 10 Projects For Beginners To Practice HTML and CSS Skills How to fetch data from an API in ReactJS ?
[ { "code": null, "e": 43692, "s": 43664, "text": "\n17 Jan, 2020" }, { "code": null, "e": 43907, "s": 43692, "text": "The storeItem() function is used to store a given value under a key name in the local storage of the browser. The local storage persists between browsing sessions and can store values even after reloading the page." }, { "code": null, "e": 44083, "s": 43907, "text": "It can be used to save non-sensitive information, such as user preferences. Sensitive data like personal information should not be stored as this storage is easily accessible." }, { "code": null, "e": 44091, "s": 44083, "text": "Syntax:" }, { "code": null, "e": 44113, "s": 44091, "text": "storeItem(key, value)" }, { "code": null, "e": 44202, "s": 44113, "text": "Parameters: This function accepts two parameters as mentioned above and described below:" }, { "code": null, "e": 44285, "s": 44202, "text": "key: This is a string which denotes the key under which the value would be stored." }, { "code": null, "e": 44414, "s": 44285, "text": "value: This is any value that can be stored under the key. It can be a String, Number, Boolean, Object, p5.Color or a p5.Vector." }, { "code": null, "e": 44475, "s": 44414, "text": "Below example illustrates the storeItem() function in p5.js:" }, { "code": null, "e": 44484, "s": 44475, "text": "Example:" }, { "code": "function setup() { createCanvas(400, 300); fill(\"green\"); text(\"Click anywhere to draw a circle\", 10, 20); text(\"The last circle would be redrawn when page is refreshed\", 10, 40); // get the coordinates // from localStorage oldX = getItem('xpos'); oldY = getItem('ypos'); // check if the values are // actually present (not null) if (oldX != null && oldY != null) circle(oldX, oldY, 100); } function mouseClicked() { clear(); fill(\"green\"); text(\"Click anywhere to draw a circle\", 10, 20); text(\"The last circle would be redrawn when page is refreshed\", 10, 40); posX = mouseX; posY = mouseY; circle(posX, posY, 100); // set the coordinates // to localStorage storeItem('xpos', posX); storeItem('ypos', posY);}", "e": 45233, "s": 44484, "text": null }, { "code": null, "e": 45241, "s": 45233, "text": "Output:" }, { "code": null, "e": 45493, "s": 45241, "text": "Local storage of the browserOnline editor: https://editor.p5js.org/Environment Setup: https://www.geeksforgeeks.org/p5-js-soundfile-object-installation-and-methods/Reference: https://p5js.org/reference/#/p5/storeItemMy Personal Notes\narrow_drop_upSave" }, { "code": null, "e": 45630, "s": 45493, "text": "Online editor: https://editor.p5js.org/Environment Setup: https://www.geeksforgeeks.org/p5-js-soundfile-object-installation-and-methods/" }, { "code": null, "e": 45683, "s": 45630, "text": "Reference: https://p5js.org/reference/#/p5/storeItem" }, { "code": null, "e": 45700, "s": 45683, "text": "JavaScript-p5.js" }, { "code": null, "e": 45711, "s": 45700, "text": "JavaScript" }, { "code": null, "e": 45728, "s": 45711, "text": "Web Technologies" }, { "code": null, "e": 45826, "s": 45728, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 45835, "s": 45826, "text": "Comments" }, { "code": null, "e": 45848, "s": 45835, "text": "Old Comments" }, { "code": null, "e": 45893, "s": 45848, "text": "Convert a string to an integer in JavaScript" }, { "code": null, "e": 45962, "s": 45893, "text": "How to calculate the number of days between two dates in javascript?" }, { "code": null, "e": 46023, "s": 45962, "text": "Difference between var, let and const keywords in JavaScript" }, { "code": null, "e": 46095, "s": 46023, "text": "Differences between Functional Components and Class Components in React" }, { "code": null, "e": 46122, "s": 46095, "text": "File uploading in React.js" }, { "code": null, "e": 46164, "s": 46122, "text": "Roadmap to Become a Web Developer in 2022" }, { "code": null, "e": 46197, "s": 46164, "text": "Installation of Node.js on Linux" }, { "code": null, "e": 46247, "s": 46197, "text": "How to insert spaces/tabs in text using HTML/CSS?" }, { "code": null, "e": 46309, "s": 46247, "text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills" } ]
How to establish a connection with the database using the properties file in JDBC?
One of the variant of the getConnection() method of the DriverManager class accepts url of the database, (String format) a properties file and establishes connection with the database. Connection con = DriverManager.getConnection(url, properties); To establish a connection with a database using this method − Set the Driver class name as a system property − System.setProperty("Jdbc.drivers", "com.mysql.jdbc.Driver"); Create a properties object as − Properties properties = new Properties(); Add the user name and password to the above created Properties object as − properties.put("user", "root"); properties.put("password", "password"); Finally invoke the getConnection() method of the DriverManager class by passing the URL and, properties object as parameters. //Getting the connection String url = "jdbc:mysql://localhost/mydatabase"; Connection con = DriverManager.getConnection(url, properties); Following JDBC program establishes connection with the MYSQL database using a properties file. import java.sql.Connection; import java.sql.DriverManager; import java.sql.SQLException; import java.util.Properties; public class EstablishingConnectionUsingProperties { public static void main(String args[]) throws SQLException { //Registering the Driver System.setProperty("Jdbc.drivers", "com.mysql.jdbc.Driver"); Properties properties = new Properties(); properties.put("user", "root"); properties.put("password", "password"); //Getting the connection String url = "jdbc:mysql://localhost/mydatabase"; Connection con = DriverManager.getConnection(url, properties); System.out.println("Connection established: "+ con); } } Connection established: com.mysql.jdbc.JDBC4Connection@2db0f6b2
[ { "code": null, "e": 1247, "s": 1062, "text": "One of the variant of the getConnection() method of the DriverManager class accepts url of the database, (String format) a properties file and establishes connection with the database." }, { "code": null, "e": 1310, "s": 1247, "text": "Connection con = DriverManager.getConnection(url, properties);" }, { "code": null, "e": 1372, "s": 1310, "text": "To establish a connection with a database using this method −" }, { "code": null, "e": 1421, "s": 1372, "text": "Set the Driver class name as a system property −" }, { "code": null, "e": 1482, "s": 1421, "text": "System.setProperty(\"Jdbc.drivers\", \"com.mysql.jdbc.Driver\");" }, { "code": null, "e": 1514, "s": 1482, "text": "Create a properties object as −" }, { "code": null, "e": 1556, "s": 1514, "text": "Properties properties = new Properties();" }, { "code": null, "e": 1631, "s": 1556, "text": "Add the user name and password to the above created Properties object as −" }, { "code": null, "e": 1703, "s": 1631, "text": "properties.put(\"user\", \"root\");\nproperties.put(\"password\", \"password\");" }, { "code": null, "e": 1829, "s": 1703, "text": "Finally invoke the getConnection() method of the DriverManager class by passing the URL and, properties object as parameters." }, { "code": null, "e": 1967, "s": 1829, "text": "//Getting the connection\nString url = \"jdbc:mysql://localhost/mydatabase\";\nConnection con = DriverManager.getConnection(url, properties);" }, { "code": null, "e": 2062, "s": 1967, "text": "Following JDBC program establishes connection with the MYSQL database using a properties file." }, { "code": null, "e": 2749, "s": 2062, "text": "import java.sql.Connection;\nimport java.sql.DriverManager;\nimport java.sql.SQLException;\nimport java.util.Properties;\npublic class EstablishingConnectionUsingProperties {\n public static void main(String args[]) throws SQLException {\n //Registering the Driver\n System.setProperty(\"Jdbc.drivers\", \"com.mysql.jdbc.Driver\");\n Properties properties = new Properties();\n properties.put(\"user\", \"root\");\n properties.put(\"password\", \"password\");\n //Getting the connection\n String url = \"jdbc:mysql://localhost/mydatabase\";\n Connection con = DriverManager.getConnection(url, properties);\n System.out.println(\"Connection established: \"+ con);\n }\n}" }, { "code": null, "e": 2813, "s": 2749, "text": "Connection established: com.mysql.jdbc.JDBC4Connection@2db0f6b2" } ]
Network Programming in Python - DNS Look-up - GeeksforGeeks
25 Oct, 2020 Domain Name System also known as DNS is a phonebook of the internet, which has related to the domain name. DNS translates the domain names to the respective IP address so that browsers can access the resources. Python provides DNS module which is used to handle this translation of domain names to IP addresses. The dnspython module provides dns.resolver() helps to find out various records of a domain name. The function takes two important parameters, the domain name, and the record type. Some of the record types with examples are listed below : A Record: It is fundamental type of DNS record, here A stands for address. It shows the IP address of the domain. Python3 # Import librariesimport dns.resolver # Finding A recordresult = dns.resolver.query('geeksforgeeks.org', 'A') # Printing recordfor val in result: print('A Record : ', val.to_text()) Output: A Record : 34.218.62.116 AAAA Record: This is an IP address record, used to find the IP of the computer connected to the domain. It is conceptually similar to A record but specifies only the IPv6 address of the server rather than IPv4. Python3 # Import librariesimport dns.resolver # Finding AAAA recordresult = dns.resolver.query('geeksforgeeks.org', 'AAAA') # Printing recordfor val in result: print('AAAA Record : ', ipval.to_text()) Output: NoAnswer: The DNS response does not contain an answer to the question: geeksforgeeks.org. IN AAAA PTR Record: PTR stands for pointer record, used to translate IP addresses to the domain name or hostname. It is used to reverse the DNS lookup. Python3 # Import librariesimport dns.resolver # Finding PTR recordresult = dns.resolver.query('116.62.218.34.in-addr.arpa', 'PTR') # Printing recordfor val in result: print('PTR Record : ', val.to_text()) Output: PTR Record : ec2-34-218-62-116.us-west-2.compute.amazonaws.com. NS Record: Nameserver(NS) record gives information that which server is authoritative for the given domain i.e. which server has the actual DNS records. Multiple NS records are possible for a domain including the primary and the backup name servers. Python3 # Import librariesimport dns.resolver # Finding NS recordresult = dns.resolver.query('geeksforgeeks.org', 'NS') # Printing recordfor val in result: print('NS Record : ', val.to_text()) Output: NS Record : ns-1520.awsdns-62.org. NS Record : ns-1569.awsdns-04.co.uk. NS Record : ns-245.awsdns-30.com. NS Record : ns-869.awsdns-44.net. MX Records: MX stands for Mail Exchanger record, which is a resource record that specifies the mail server which is responsible for accepting emails on behalf of the domain. It has preference values according to the prioritizing mail if multiple mail servers are present for load balancing and redundancy. Python3 # Import librariesimport dns.resolver # Finding MX recordresult = dns.resolver.query('geeksforgeeks.org', 'MX') # Printing recordfor val in result: print('MX Record : ', val.to_text()) Output: MX Record : 1 aspmx.l.google.com. MX Record : 10 alt3.aspmx.l.google.com. MX Record : 10 alt4.aspmx.l.google.com. MX Record : 5 alt1.aspmx.l.google.com. MX Record : 5 alt2.aspmx.l.google.com. SOA Records: SOA stands for Start of Authority records, which is a type of resource record that contains information regarding the administration of the zone especially related to zone transfers defined by the zone administrator. Python3 # Import librariesimport dns.resolver # Finding SOA recordresult = dns.resolver.query('geeksforgeeks.org', 'SOA') # Printing recordfor val in result: print('SOA Record : ', val.to_text()) Output: SOA Record : ns-869.awsdns-44.net. awsdns-hostmaster.amazon.com. 1 7200 900 1209600 86400 CNAME Record: CNAME stands for Canonical Name record, which is used in mapping the domain name as an alias for the other domain. It always points to another domain and never directly points to an IP. Python3 # Import librariesimport dns.resolver # Finding CNAME recordresult = dns.resolver.query('geeksforgeeks.org', 'CNAME') # Printing recordfor val in result: print('CNAME Record : ', val.target) Output: NoAnswer: The DNS response does not contain an answer to the question: geeksforgeeks.org. IN CNAME TXT Record: These records contain the text information of the sources which are outside of the domain. TXT records can be used for various purposes like google use them to verify the domain ownership and to ensure email security. Python3 # Import librariesimport dns.resolver # Finding TXT recordresult = dns.resolver.query('geeksforgeeks.org', 'TXT') # Printing recordfor val in result: print('TXT Record : ', val.to_text()) Output: TXT Record : “fob1m1abcdp777bf2ncvnjm08n”TXT Record : “v=spf1 include:amazonses.com include:_spf.google.com ip4:167.89.66.115 -all” Python-Networking Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to Install PIP on Windows ? How To Convert Python Dictionary To JSON? How to drop one or multiple columns in Pandas Dataframe Check if element exists in list in Python Python | os.path.join() method Defaultdict in Python Selecting rows in pandas DataFrame based on conditions Python | Get unique values from a list Create a directory in Python Python | Pandas dataframe.groupby()
[ { "code": null, "e": 24292, "s": 24264, "text": "\n25 Oct, 2020" }, { "code": null, "e": 24604, "s": 24292, "text": "Domain Name System also known as DNS is a phonebook of the internet, which has related to the domain name. DNS translates the domain names to the respective IP address so that browsers can access the resources. Python provides DNS module which is used to handle this translation of domain names to IP addresses." }, { "code": null, "e": 24842, "s": 24604, "text": "The dnspython module provides dns.resolver() helps to find out various records of a domain name. The function takes two important parameters, the domain name, and the record type. Some of the record types with examples are listed below :" }, { "code": null, "e": 24956, "s": 24842, "text": "A Record: It is fundamental type of DNS record, here A stands for address. It shows the IP address of the domain." }, { "code": null, "e": 24964, "s": 24956, "text": "Python3" }, { "code": "# Import librariesimport dns.resolver # Finding A recordresult = dns.resolver.query('geeksforgeeks.org', 'A') # Printing recordfor val in result: print('A Record : ', val.to_text())", "e": 25151, "s": 24964, "text": null }, { "code": null, "e": 25159, "s": 25151, "text": "Output:" }, { "code": null, "e": 25186, "s": 25159, "text": "A Record : 34.218.62.116\n" }, { "code": null, "e": 25397, "s": 25186, "text": "AAAA Record: This is an IP address record, used to find the IP of the computer connected to the domain. It is conceptually similar to A record but specifies only the IPv6 address of the server rather than IPv4." }, { "code": null, "e": 25405, "s": 25397, "text": "Python3" }, { "code": "# Import librariesimport dns.resolver # Finding AAAA recordresult = dns.resolver.query('geeksforgeeks.org', 'AAAA') # Printing recordfor val in result: print('AAAA Record : ', ipval.to_text())", "e": 25603, "s": 25405, "text": null }, { "code": null, "e": 25611, "s": 25603, "text": "Output:" }, { "code": null, "e": 25709, "s": 25611, "text": "NoAnswer: The DNS response does not contain an answer to the question: geeksforgeeks.org. IN AAAA" }, { "code": null, "e": 25853, "s": 25709, "text": "PTR Record: PTR stands for pointer record, used to translate IP addresses to the domain name or hostname. It is used to reverse the DNS lookup." }, { "code": null, "e": 25861, "s": 25853, "text": "Python3" }, { "code": "# Import librariesimport dns.resolver # Finding PTR recordresult = dns.resolver.query('116.62.218.34.in-addr.arpa', 'PTR') # Printing recordfor val in result: print('PTR Record : ', val.to_text())", "e": 26063, "s": 25861, "text": null }, { "code": null, "e": 26071, "s": 26063, "text": "Output:" }, { "code": null, "e": 26136, "s": 26071, "text": "PTR Record : ec2-34-218-62-116.us-west-2.compute.amazonaws.com." }, { "code": null, "e": 26386, "s": 26136, "text": "NS Record: Nameserver(NS) record gives information that which server is authoritative for the given domain i.e. which server has the actual DNS records. Multiple NS records are possible for a domain including the primary and the backup name servers." }, { "code": null, "e": 26394, "s": 26386, "text": "Python3" }, { "code": "# Import librariesimport dns.resolver # Finding NS recordresult = dns.resolver.query('geeksforgeeks.org', 'NS') # Printing recordfor val in result: print('NS Record : ', val.to_text())", "e": 26584, "s": 26394, "text": null }, { "code": null, "e": 26592, "s": 26584, "text": "Output:" }, { "code": null, "e": 26737, "s": 26592, "text": "NS Record : ns-1520.awsdns-62.org.\nNS Record : ns-1569.awsdns-04.co.uk.\nNS Record : ns-245.awsdns-30.com.\nNS Record : ns-869.awsdns-44.net.\n" }, { "code": null, "e": 27043, "s": 26737, "text": "MX Records: MX stands for Mail Exchanger record, which is a resource record that specifies the mail server which is responsible for accepting emails on behalf of the domain. It has preference values according to the prioritizing mail if multiple mail servers are present for load balancing and redundancy." }, { "code": null, "e": 27051, "s": 27043, "text": "Python3" }, { "code": "# Import librariesimport dns.resolver # Finding MX recordresult = dns.resolver.query('geeksforgeeks.org', 'MX') # Printing recordfor val in result: print('MX Record : ', val.to_text())", "e": 27241, "s": 27051, "text": null }, { "code": null, "e": 27249, "s": 27241, "text": "Output:" }, { "code": null, "e": 27447, "s": 27249, "text": "MX Record : 1 aspmx.l.google.com.\nMX Record : 10 alt3.aspmx.l.google.com.\nMX Record : 10 alt4.aspmx.l.google.com.\nMX Record : 5 alt1.aspmx.l.google.com.\nMX Record : 5 alt2.aspmx.l.google.com.\n" }, { "code": null, "e": 27677, "s": 27447, "text": "SOA Records: SOA stands for Start of Authority records, which is a type of resource record that contains information regarding the administration of the zone especially related to zone transfers defined by the zone administrator." }, { "code": null, "e": 27685, "s": 27677, "text": "Python3" }, { "code": "# Import librariesimport dns.resolver # Finding SOA recordresult = dns.resolver.query('geeksforgeeks.org', 'SOA') # Printing recordfor val in result: print('SOA Record : ', val.to_text())", "e": 27878, "s": 27685, "text": null }, { "code": null, "e": 27886, "s": 27878, "text": "Output:" }, { "code": null, "e": 27977, "s": 27886, "text": "SOA Record : ns-869.awsdns-44.net. awsdns-hostmaster.amazon.com. 1 7200 900 1209600 86400" }, { "code": null, "e": 28178, "s": 27977, "text": "CNAME Record: CNAME stands for Canonical Name record, which is used in mapping the domain name as an alias for the other domain. It always points to another domain and never directly points to an IP." }, { "code": null, "e": 28186, "s": 28178, "text": "Python3" }, { "code": "# Import librariesimport dns.resolver # Finding CNAME recordresult = dns.resolver.query('geeksforgeeks.org', 'CNAME') # Printing recordfor val in result: print('CNAME Record : ', val.target)", "e": 28382, "s": 28186, "text": null }, { "code": null, "e": 28390, "s": 28382, "text": "Output:" }, { "code": null, "e": 28489, "s": 28390, "text": "NoAnswer: The DNS response does not contain an answer to the question: geeksforgeeks.org. IN CNAME" }, { "code": null, "e": 28719, "s": 28489, "text": "TXT Record: These records contain the text information of the sources which are outside of the domain. TXT records can be used for various purposes like google use them to verify the domain ownership and to ensure email security." }, { "code": null, "e": 28727, "s": 28719, "text": "Python3" }, { "code": "# Import librariesimport dns.resolver # Finding TXT recordresult = dns.resolver.query('geeksforgeeks.org', 'TXT') # Printing recordfor val in result: print('TXT Record : ', val.to_text())", "e": 28920, "s": 28727, "text": null }, { "code": null, "e": 28928, "s": 28920, "text": "Output:" }, { "code": null, "e": 29062, "s": 28928, "text": "TXT Record : “fob1m1abcdp777bf2ncvnjm08n”TXT Record : “v=spf1 include:amazonses.com include:_spf.google.com ip4:167.89.66.115 -all”" }, { "code": null, "e": 29080, "s": 29062, "text": "Python-Networking" }, { "code": null, "e": 29087, "s": 29080, "text": "Python" }, { "code": null, "e": 29185, "s": 29087, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 29217, "s": 29185, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 29259, "s": 29217, "text": "How To Convert Python Dictionary To JSON?" }, { "code": null, "e": 29315, "s": 29259, "text": "How to drop one or multiple columns in Pandas Dataframe" }, { "code": null, "e": 29357, "s": 29315, "text": "Check if element exists in list in Python" }, { "code": null, "e": 29388, "s": 29357, "text": "Python | os.path.join() method" }, { "code": null, "e": 29410, "s": 29388, "text": "Defaultdict in Python" }, { "code": null, "e": 29465, "s": 29410, "text": "Selecting rows in pandas DataFrame based on conditions" }, { "code": null, "e": 29504, "s": 29465, "text": "Python | Get unique values from a list" }, { "code": null, "e": 29533, "s": 29504, "text": "Create a directory in Python" } ]
SLF4J - Hello world
In this chapter, we will see a simple basic logger program using SLF4J. Follow the steps described below to write a simple logger. Since the slf4j.Logger is the entry point of the SLF4J API, first, you need to get/create its object The getLogger() method of the LoggerFactory class accepts a string value representing a name and returns a Logger object with the specified name. Logger logger = LoggerFactory.getLogger("SampleLogger"); The info() method of the slf4j.Logger interface accepts a string value representing the required message and logs it at the info level. logger.info("Hi This is my first SLF4J program"); Following is the program that demonstrates how to write a sample logger in Java using SLF4J. import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class SLF4JExample { public static void main(String[] args) { //Creating the Logger object Logger logger = LoggerFactory.getLogger("SampleLogger"); //Logging the information logger.info("Hi This is my first SLF4J program"); } } On running the following program initially, you will get the following output instead of the desired message. SLF4J: Failed to load class "org.slf4j.impl.StaticLoggerBinder". SLF4J: Defaulting to no-operation (NOP) logger implementation SLF4J: See http://www.slf4j.org/codes.html#StaticLoggerBinder for further details. Since we have not set the classpath to any binding representing a logging framework, as mentioned earlier in this tutorial, SLF4J defaulted to a no-operation implementation. So, to see the message you need to add the desired binding in the project classpath. Since we are using eclipse, set build path for respective JAR file or, add its dependency in the pom.xml file. For example, if we need to use JUL (Java.util.logging framework), we need to set build path for the jar file slf4j-jdk14-x.x.jar. And if we want to use log4J logging framework, we need to set build path or, add dependencies for the jar files slf4j-log4j12-x.x.jar and log4j.jar. After adding the binding representing any of the logging frameworks except slf4j-nopx.x.jar to the project (classpath), you will get the following output. Dec 06, 2018 5:29:44 PM SLF4JExample main INFO: Hi Welcome to Tutorialspoint Print Add Notes Bookmark this page
[ { "code": null, "e": 1916, "s": 1785, "text": "In this chapter, we will see a simple basic logger program using SLF4J. Follow the steps described below to write a simple logger." }, { "code": null, "e": 2017, "s": 1916, "text": "Since the slf4j.Logger is the entry point of the SLF4J API, first, you need to get/create its object" }, { "code": null, "e": 2163, "s": 2017, "text": "The getLogger() method of the LoggerFactory class accepts a string value representing a name and returns a Logger object with the specified name." }, { "code": null, "e": 2221, "s": 2163, "text": "Logger logger = LoggerFactory.getLogger(\"SampleLogger\");\n" }, { "code": null, "e": 2357, "s": 2221, "text": "The info() method of the slf4j.Logger interface accepts a string value representing the required message and logs it at the info level." }, { "code": null, "e": 2408, "s": 2357, "text": "logger.info(\"Hi This is my first SLF4J program\");\n" }, { "code": null, "e": 2501, "s": 2408, "text": "Following is the program that demonstrates how to write a sample logger in Java using SLF4J." }, { "code": null, "e": 2824, "s": 2501, "text": "import org.slf4j.Logger;\nimport org.slf4j.LoggerFactory;\npublic class SLF4JExample {\n public static void main(String[] args) {\n //Creating the Logger object\n Logger logger = LoggerFactory.getLogger(\"SampleLogger\");\n\n //Logging the information\n logger.info(\"Hi This is my first SLF4J program\");\n }\n}" }, { "code": null, "e": 2934, "s": 2824, "text": "On running the following program initially, you will get the following output instead of the desired message." }, { "code": null, "e": 3145, "s": 2934, "text": "SLF4J: Failed to load class \"org.slf4j.impl.StaticLoggerBinder\".\nSLF4J: Defaulting to no-operation (NOP) logger implementation\nSLF4J: See http://www.slf4j.org/codes.html#StaticLoggerBinder for further\ndetails.\n" }, { "code": null, "e": 3515, "s": 3145, "text": "Since we have not set the classpath to any binding representing a logging framework, as mentioned earlier in this tutorial, SLF4J defaulted to a no-operation implementation. So, to see the message you need to add the desired binding in the project classpath. Since we are using eclipse, set build path for respective JAR file or, add its dependency in the pom.xml file." }, { "code": null, "e": 3794, "s": 3515, "text": "For example, if we need to use JUL (Java.util.logging framework), we need to set build path for the jar file slf4j-jdk14-x.x.jar. And if we want to use log4J logging framework, we need to set build path or, add dependencies for the jar files slf4j-log4j12-x.x.jar and log4j.jar." }, { "code": null, "e": 3949, "s": 3794, "text": "After adding the binding representing any of the logging frameworks except slf4j-nopx.x.jar to the project (classpath), you will get the following output." }, { "code": null, "e": 4027, "s": 3949, "text": "Dec 06, 2018 5:29:44 PM SLF4JExample main\nINFO: Hi Welcome to Tutorialspoint\n" }, { "code": null, "e": 4034, "s": 4027, "text": " Print" }, { "code": null, "e": 4045, "s": 4034, "text": " Add Notes" } ]
HTML | <input type="file"> - GeeksforGeeks
29 May, 2019 The HTML <input type=”file”> is used to specify the file select field and add a button to choose a file for upload to the form. Syntax: <input type="file"> Example: <!DOCTYPE html> <html> <head> <title> HTML input type file </title> <style> h1 { color: green; } h3 { font-family: Impact; } body { text-align: center; } </style> </head> <body> <h1> GeeksforGeeks </h1> <h3> HTML <Input Type = "File"> </h3> <input type="file" id="myFile"> <p id="submit_text"></p></body> </html> Output: Supported Browsers: The browsers supported by <input type=”file”> are listed below: Google Chrome 1.0 Internet Explorer Firefox 1.0 Safari 1.0 Opera 1.0 Attention reader! Don’t stop learning now. Get hold of all the important HTML concepts with the Web Design for Beginners | HTML course. HTML-Attributes HTML Web Technologies HTML Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Types of CSS (Cascading Style Sheet) How to Insert Form Data into Database using PHP ? REST API (Introduction) Design a web page using HTML and CSS Form validation using HTML and JavaScript Top 10 Front End Developer Skills That You Need in 2022 Installation of Node.js on Linux How to fetch data from an API in ReactJS ? Difference between var, let and const keywords in JavaScript Convert a string to an integer in JavaScript
[ { "code": null, "e": 24545, "s": 24517, "text": "\n29 May, 2019" }, { "code": null, "e": 24673, "s": 24545, "text": "The HTML <input type=”file”> is used to specify the file select field and add a button to choose a file for upload to the form." }, { "code": null, "e": 24681, "s": 24673, "text": "Syntax:" }, { "code": null, "e": 24702, "s": 24681, "text": "<input type=\"file\"> " }, { "code": null, "e": 24711, "s": 24702, "text": "Example:" }, { "code": "<!DOCTYPE html> <html> <head> <title> HTML input type file </title> <style> h1 { color: green; } h3 { font-family: Impact; } body { text-align: center; } </style> </head> <body> <h1> GeeksforGeeks </h1> <h3> HTML <Input Type = \"File\"> </h3> <input type=\"file\" id=\"myFile\"> <p id=\"submit_text\"></p></body> </html> ", "e": 25217, "s": 24711, "text": null }, { "code": null, "e": 25225, "s": 25217, "text": "Output:" }, { "code": null, "e": 25309, "s": 25225, "text": "Supported Browsers: The browsers supported by <input type=”file”> are listed below:" }, { "code": null, "e": 25327, "s": 25309, "text": "Google Chrome 1.0" }, { "code": null, "e": 25345, "s": 25327, "text": "Internet Explorer" }, { "code": null, "e": 25357, "s": 25345, "text": "Firefox 1.0" }, { "code": null, "e": 25368, "s": 25357, "text": "Safari 1.0" }, { "code": null, "e": 25378, "s": 25368, "text": "Opera 1.0" }, { "code": null, "e": 25515, "s": 25378, "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": 25531, "s": 25515, "text": "HTML-Attributes" }, { "code": null, "e": 25536, "s": 25531, "text": "HTML" }, { "code": null, "e": 25553, "s": 25536, "text": "Web Technologies" }, { "code": null, "e": 25558, "s": 25553, "text": "HTML" }, { "code": null, "e": 25656, "s": 25558, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 25665, "s": 25656, "text": "Comments" }, { "code": null, "e": 25678, "s": 25665, "text": "Old Comments" }, { "code": null, "e": 25715, "s": 25678, "text": "Types of CSS (Cascading Style Sheet)" }, { "code": null, "e": 25765, "s": 25715, "text": "How to Insert Form Data into Database using PHP ?" }, { "code": null, "e": 25789, "s": 25765, "text": "REST API (Introduction)" }, { "code": null, "e": 25826, "s": 25789, "text": "Design a web page using HTML and CSS" }, { "code": null, "e": 25868, "s": 25826, "text": "Form validation using HTML and JavaScript" }, { "code": null, "e": 25924, "s": 25868, "text": "Top 10 Front End Developer Skills That You Need in 2022" }, { "code": null, "e": 25957, "s": 25924, "text": "Installation of Node.js on Linux" }, { "code": null, "e": 26000, "s": 25957, "text": "How to fetch data from an API in ReactJS ?" }, { "code": null, "e": 26061, "s": 26000, "text": "Difference between var, let and const keywords in JavaScript" } ]
Python | Image Registration using OpenCV
06 Sep, 2021 Image registration is a digital image processing technique that helps us align different images of the same scene. For instance, one may click the picture of a book from various angles. Below are a few instances that show the diversity of camera angles.Now, we may want to “align” a particular image to the same angle as a reference image. In the images above, one may consider the first image to be an “ideal” cover photo, while the second and third images do not serve well for book cover photo purposes. The image registration algorithm helps us align the second and third pictures to the same plane as the first one. How does image registration work? Alignment can be looked at as a simple coordinate transform. The algorithm works as follows: Convert both images to grayscale. Match features from the image to be aligned, to the reference image and store the coordinates of the corresponding key points. Keypoints are simply the selected few points that are used to compute the transform (generally points that stand out), and descriptors are histograms of the image gradients to characterize the appearance of a keypoint. In this post, we use ORB (Oriented FAST and Rotated BRIEF) implementation in the OpenCV library, which provides us with both key points as well as their associated descriptors. Match the key points between the two images. In this post, we use BFMatcher, which is a brute force matcher. BFMatcher.match() retrieves the best match, while BFMatcher.knnMatch() retrieves top K matches, where K is specified by the user. Pick the top matches, and remove the noisy matches. Find the homomorphy transform. Apply this transform to the original unaligned image to get the output image. Applications of Image Registration – Some of the useful applications of image registration include: Stitching various scenes (which may or may not have the same camera alignment) together to form a continuous panoramic shot. Aligning camera images of documents to a standard alignment to create realistic scanned documents. Aligning medical images for better observation and analysis. Below is the code for image registration. We have aligned the second image with reference to the third image. Python import cv2import numpy as np # Open the image files.img1_color = cv2.imread("align.jpg") # Image to be aligned.img2_color = cv2.imread("ref.jpg") # Reference image. # Convert to grayscale.img1 = cv2.cvtColor(img1_color, cv2.COLOR_BGR2GRAY)img2 = cv2.cvtColor(img2_color, cv2.COLOR_BGR2GRAY)height, width = img2.shape # Create ORB detector with 5000 features.orb_detector = cv2.ORB_create(5000) # Find keypoints and descriptors.# The first arg is the image, second arg is the mask# (which is not required in this case).kp1, d1 = orb_detector.detectAndCompute(img1, None)kp2, d2 = orb_detector.detectAndCompute(img2, None) # Match features between the two images.# We create a Brute Force matcher with# Hamming distance as measurement mode.matcher = cv2.BFMatcher(cv2.NORM_HAMMING, crossCheck = True) # Match the two sets of descriptors.matches = matcher.match(d1, d2) # Sort matches on the basis of their Hamming distance.matches.sort(key = lambda x: x.distance) # Take the top 90 % matches forward.matches = matches[:int(len(matches)*0.9)]no_of_matches = len(matches) # Define empty matrices of shape no_of_matches * 2.p1 = np.zeros((no_of_matches, 2))p2 = np.zeros((no_of_matches, 2)) for i in range(len(matches)): p1[i, :] = kp1[matches[i].queryIdx].pt p2[i, :] = kp2[matches[i].trainIdx].pt # Find the homography matrix.homography, mask = cv2.findHomography(p1, p2, cv2.RANSAC) # Use this matrix to transform the# colored image wrt the reference image.transformed_img = cv2.warpPerspective(img1_color, homography, (width, height)) # Save the output.cv2.imwrite('output.jpg', transformed_img) Output: marlenabetzner varshagumber28 Image-Processing OpenCV Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 52, "s": 24, "text": "\n06 Sep, 2021" }, { "code": null, "e": 673, "s": 52, "text": "Image registration is a digital image processing technique that helps us align different images of the same scene. For instance, one may click the picture of a book from various angles. Below are a few instances that show the diversity of camera angles.Now, we may want to “align” a particular image to the same angle as a reference image. In the images above, one may consider the first image to be an “ideal” cover photo, while the second and third images do not serve well for book cover photo purposes. The image registration algorithm helps us align the second and third pictures to the same plane as the first one." }, { "code": null, "e": 806, "s": 677, "text": "How does image registration work? Alignment can be looked at as a simple coordinate transform. The algorithm works as follows: " }, { "code": null, "e": 840, "s": 806, "text": "Convert both images to grayscale." }, { "code": null, "e": 1363, "s": 840, "text": "Match features from the image to be aligned, to the reference image and store the coordinates of the corresponding key points. Keypoints are simply the selected few points that are used to compute the transform (generally points that stand out), and descriptors are histograms of the image gradients to characterize the appearance of a keypoint. In this post, we use ORB (Oriented FAST and Rotated BRIEF) implementation in the OpenCV library, which provides us with both key points as well as their associated descriptors." }, { "code": null, "e": 1602, "s": 1363, "text": "Match the key points between the two images. In this post, we use BFMatcher, which is a brute force matcher. BFMatcher.match() retrieves the best match, while BFMatcher.knnMatch() retrieves top K matches, where K is specified by the user." }, { "code": null, "e": 1654, "s": 1602, "text": "Pick the top matches, and remove the noisy matches." }, { "code": null, "e": 1685, "s": 1654, "text": "Find the homomorphy transform." }, { "code": null, "e": 1763, "s": 1685, "text": "Apply this transform to the original unaligned image to get the output image." }, { "code": null, "e": 1864, "s": 1763, "text": "Applications of Image Registration – Some of the useful applications of image registration include: " }, { "code": null, "e": 1989, "s": 1864, "text": "Stitching various scenes (which may or may not have the same camera alignment) together to form a continuous panoramic shot." }, { "code": null, "e": 2088, "s": 1989, "text": "Aligning camera images of documents to a standard alignment to create realistic scanned documents." }, { "code": null, "e": 2149, "s": 2088, "text": "Aligning medical images for better observation and analysis." }, { "code": null, "e": 2260, "s": 2149, "text": "Below is the code for image registration. We have aligned the second image with reference to the third image. " }, { "code": null, "e": 2267, "s": 2260, "text": "Python" }, { "code": "import cv2import numpy as np # Open the image files.img1_color = cv2.imread(\"align.jpg\") # Image to be aligned.img2_color = cv2.imread(\"ref.jpg\") # Reference image. # Convert to grayscale.img1 = cv2.cvtColor(img1_color, cv2.COLOR_BGR2GRAY)img2 = cv2.cvtColor(img2_color, cv2.COLOR_BGR2GRAY)height, width = img2.shape # Create ORB detector with 5000 features.orb_detector = cv2.ORB_create(5000) # Find keypoints and descriptors.# The first arg is the image, second arg is the mask# (which is not required in this case).kp1, d1 = orb_detector.detectAndCompute(img1, None)kp2, d2 = orb_detector.detectAndCompute(img2, None) # Match features between the two images.# We create a Brute Force matcher with# Hamming distance as measurement mode.matcher = cv2.BFMatcher(cv2.NORM_HAMMING, crossCheck = True) # Match the two sets of descriptors.matches = matcher.match(d1, d2) # Sort matches on the basis of their Hamming distance.matches.sort(key = lambda x: x.distance) # Take the top 90 % matches forward.matches = matches[:int(len(matches)*0.9)]no_of_matches = len(matches) # Define empty matrices of shape no_of_matches * 2.p1 = np.zeros((no_of_matches, 2))p2 = np.zeros((no_of_matches, 2)) for i in range(len(matches)): p1[i, :] = kp1[matches[i].queryIdx].pt p2[i, :] = kp2[matches[i].trainIdx].pt # Find the homography matrix.homography, mask = cv2.findHomography(p1, p2, cv2.RANSAC) # Use this matrix to transform the# colored image wrt the reference image.transformed_img = cv2.warpPerspective(img1_color, homography, (width, height)) # Save the output.cv2.imwrite('output.jpg', transformed_img)", "e": 3888, "s": 2267, "text": null }, { "code": null, "e": 3897, "s": 3888, "text": "Output: " }, { "code": null, "e": 3914, "s": 3899, "text": "marlenabetzner" }, { "code": null, "e": 3929, "s": 3914, "text": "varshagumber28" }, { "code": null, "e": 3946, "s": 3929, "text": "Image-Processing" }, { "code": null, "e": 3953, "s": 3946, "text": "OpenCV" }, { "code": null, "e": 3960, "s": 3953, "text": "Python" } ]
Program to print DNA sequence
22 Jun, 2022 Given the value of n i.e, the number of lobes. Print the double-helix structure of Deoxyribonucleic acid(DNA). Input: n = 8 Output: AT T--A A----T T------A T------A G----C T--A GC CG C--G A----T A------T T------A A----T A--T GC AT C--G T----A C------G C------G T----A G--C AT AT T--A A----T T------A T------A G----C T--A GC Explanation : DNA primarily consists of 4 hydrocarbons i.e. cytosine [C], guanine [G], adenine[A], thymine [T].DNA bases pair up with each other, A with T and C with G, to form units called base pairs.Below is the implementation to print the double-helix DNA sequence : CPP Java Python3 C# PHP Javascript // CPP Program to print the// 'n' lobes of DNA pattern#include <bits/stdc++.h>using namespace std; // Function to print upper half// of the DNA or the upper lobevoid printUpperHalf(string str){ char first, second; int pos = 0; // Each half of the DNA is made of // combination of two compounds for (int i = 1; i <= 4; i++) { // Taking the two carbon // compounds from the string first = str[pos]; second = str[pos + 1]; pos += 2; for (int j = 4 - i; j >= 1; j--) cout << " "; cout << first; for (int j = 1; j < i; j++) cout << "--"; cout << second << endl; }} // Function to print lower half// of the DNA or the lower lobevoid printLowerHalf(string str){ char first, second; int pos = 0; for (int i = 1; i <= 4; i++) { first = str[pos]; second = str[pos + 1]; pos += 2; for (int j = 1; j < i; j++) cout << " "; cout << first; for (int j = 4 - i; j >= 1; j--) cout << "--"; cout << second << endl; }} // Function to print 'n' parts of DNAvoid printDNA(string str[], int n){ for (int i = 0; i < n; i++) { int x = i % 6; // Calling for upperhalf if (x % 2 == 0) printUpperHalf(str[x]); else // Calling for lowerhalf printLowerHalf(str[x]); }} // Driver functionint main(){ int n = 8; // combinations stored in the array string DNA[] = { "ATTAATTA", "TAGCTAGC", "CGCGATAT", "TAATATGC", "ATCGTACG", "CGTAGCAT" }; printDNA(DNA, n); return 0;} // Java Program to print the// 'n' lobes of DNA pattern import java.io.*; class GFG { // Function to print upper half// of the DNA or the upper lobestatic void printUpperHalf(String str){ char first, second; int pos = 0; // Each half of the DNA is made of // combination of two compounds for (int i = 1; i <= 4; i++) { // Taking the two carbon // compounds from the string first = str.charAt(pos); second = str.charAt(pos+1); pos += 2; for (int j = 4 - i; j >= 1; j--) System.out.print(" "); System.out.print(first); for (int j = 1; j < i; j++) System.out.print("--"); System.out.println(second); }} // Function to print lower half// of the DNA or the lower lobestatic void printLowerHalf(String str){ char first, second; int pos = 0; for (int i = 1; i <= 4; i++) { first = str.charAt(pos); second = str.charAt(pos+1); pos += 2; for (int j = 1; j < i; j++) System.out.print(" "); System.out.print(first); for (int j = 4 - i; j >= 1; j--) System.out.print("--"); System.out.println(second); }} // Function to print 'n' parts of DNAstatic void printDNA(String str[], int n){ for (int i = 0; i < n; i++) { int x = i % 6; // Calling for upperhalf if (x % 2 == 0) printUpperHalf(str[x]); else // Calling for lowerhalf printLowerHalf(str[x]); }}public static void main (String[] args) { int n = 8; // combinations stored in the array String DNA[] = { "ATTAATTA", "TAGCTAGC", "CGCGATAT", "TAATATGC", "ATCGTACG", "CGTAGCAT" }; printDNA(DNA, n); }} // This code is contributed by Gitanjali # Python Program to print the# 'n' lobes of DNA patternimport math # Function to print upper half# of the DNA or the upper lobedef printUpperHalf(str): first=0 second=0 pos = 0 # Each half of the DNA is made of # combination of two compounds for i in range(1,5): # Taking the two carbon # compounds from the string first = str[pos] second = str[pos+1] pos += 2 for j in range ( 4 - i, 0,-1): print(" ",end="") print(first,end="") for j in range (1, i): print("--",end="") print(second) # Function to print lower half# of the DNA or the lower lobedef printLowerHalf(str): first=0 second=0 pos = 0 for i in range(1,5): first = str[pos] second = str[pos+1] pos += 2 for j in range(1,i): print(" ",end="") print(first,end="") for j in range (4 - i, 0,-1): print("--",end="") print(second) # Function to print 'n' parts of DNAdef printDNA( str, n): for i in range(0,n): x = i % 6 # Calling for upperhalf if (x % 2 == 0): printUpperHalf(str[x]) else: # Calling for lowerhalf printLowerHalf(str[x]) # driver coden = 8 # combinations stored in the arrayDNA = [ "ATTAATTA", "TAGCTAGC", "CGCGATAT", "TAATATGC", "ATCGTACG", "CGTAGCAT" ] printDNA(DNA, n) # This code is contributed by Gitanjali. // C# Program to print the 'n' lobes of// DNA patternusing System; class GFG { // Function to print upper half // of the DNA or the upper lobe static void printUpperHalf(string str) { char first, second; int pos = 0; // Each half of the DNA is made of // combination of two compounds for (int i = 1; i <= 4; i++) { // Taking the two carbon // compounds from the string first = str[pos]; second = str[pos+1]; pos += 2; for (int j = 4 - i; j >= 1; j--) Console.Write(" "); Console.Write(first); for (int j = 1; j < i; j++) Console.Write("--"); Console.WriteLine(second); } } // Function to print lower half // of the DNA or the lower lobe static void printLowerHalf(string str) { char first, second; int pos = 0; for (int i = 1; i <= 4; i++) { first = str[pos]; second = str[pos+1]; pos += 2; for (int j = 1; j < i; j++) Console.Write(" "); Console.Write(first); for (int j = 4 - i; j >= 1; j--) Console.Write("--"); Console.WriteLine(second); } } // Function to print 'n' parts of DNA static void printDNA(string []str, int n) { for (int i = 0; i < n; i++) { int x = i % 6; // Calling for upperhalf if (x % 2 == 0) printUpperHalf(str[x]); else // Calling for lowerhalf printLowerHalf(str[x]); } } public static void Main () { int n = 8; // combinations stored in the array string []DNA = { "ATTAATTA", "TAGCTAGC", "CGCGATAT", "TAATATGC", "ATCGTACG", "CGTAGCAT" }; printDNA(DNA, n); }} // This code is contributed by vt_m. <?php// PHP implementation to print the// 'n' lobes of DNA pattern // Function to print upper half// of the DNA or the upper lobefunction printUpperHalf($str){ $pos = 0; // Each half of the DNA is made of // combination of two compounds for($i = 1; $i <= 4; $i++) { // Taking the two carbon // compounds from the string $first = $str[$pos]; $second = $str[$pos + 1]; $pos += 2; for ($j = 4 - $i; $j >= 1; $j--) echo " "; echo $first; for ($j = 1; $j < $i; $j++) echo "--"; echo $second."\n"; }} // Function to print lower half// of the DNA or the lower lobefunction printLowerHalf($str){ $pos = 0; for ($i = 1; $i <= 4; $i++) { $first = $str[$pos]; $second = $str[$pos + 1]; $pos += 2; for ($j = 1; $j < $i; $j++) echo " "; echo $first; for ($j = 4 - $i; $j >= 1; $j--) echo"--"; echo $second."\n"; }} // Function to print 'n' parts of DNAfunction printDNA($str, $n){ for ($i = 0; $i < $n; $i++) { $x = $i % 6; // Calling for upperhalf if ($x % 2 == 0) printUpperHalf($str[$x]); else // Calling for lowerhalf printLowerHalf($str[$x]); }} // Driver code$n = 8;$DNA = array( "ATTAATTA", "TAGCTAGC", "CGCGATAT", "TAATATGC", "ATCGTACG", "CGTAGCAT" );printDNA($DNA, $n); // This code is contributed by mits.?> <script> // javascript Program to print the// 'n' lobes of DNA pattern// Function to print upper half// of the DNA or the upper lobefunction printUpperHalf(str){ var first, second; var pos = 0; // Each half of the DNA is made of // combination of two compounds for (var i = 1; i <= 4; i++) { // Taking the two carbon // compounds from the string first = str.charAt(pos); second = str.charAt(pos+1); pos += 2; for (var j = 4 - i; j >= 1; j--) document.write(" "); document.write(first); for (var j = 1; j < i; j++) document.write("--"); document.write(second+"<br>"); }} // Function to print lower half// of the DNA or the lower lobefunction printLowerHalf(str){ var first, second; var pos = 0; for (var i = 1; i <= 4; i++) { first = str.charAt(pos); second = str.charAt(pos+1); pos += 2; for (var j = 1; j < i; j++) document.write(" "); document.write(first); for (var j = 4 - i; j >= 1; j--) document.write("--"); document.write(second+"<br>"); }} // Function to print 'n' parts of DNAfunction printDNA(str , n){ for (var i = 0; i < n; i++) { var x = i % 6; // Calling for upperhalf if (x % 2 == 0) printUpperHalf(str[x]); else // Calling for lowerhalf printLowerHalf(str[x]); }}var n = 8; // combinations stored in the arrayvar DNA = [ "ATTAATTA", "TAGCTAGC", "CGCGATAT", "TAATATGC", "ATCGTACG", "CGTAGCAT" ];printDNA(DNA, n); // This code contributed by Princi Singh</script> Output : AT T--A A----T T------A T------A G----C T--A GC CG C--G A----T A------T T------A A----T A--T GC AT C--G T----A C------G C------G T----A G--C AT AT T--A A----T T------A T------A G----C T--A GC Time Complexity: O(N), as we are using a loop to traverse N times. Where N is the input given. Auxiliary Space: O(1), as we are not using any extra space. Mithun Kumar princi singh Kirti_Mangal rohitsingh57 pattern-printing School Programming pattern-printing Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 54, "s": 26, "text": "\n22 Jun, 2022" }, { "code": null, "e": 166, "s": 54, "text": "Given the value of n i.e, the number of lobes. Print the double-helix structure of Deoxyribonucleic acid(DNA). " }, { "code": null, "e": 427, "s": 166, "text": "Input: n = 8\nOutput:\n AT\n T--A\n A----T\nT------A\nT------A\n G----C\n T--A\n GC\n CG\n C--G\n A----T\nA------T\nT------A\n A----T\n A--T\n GC\n AT\n C--G\n T----A\nC------G\nC------G\n T----A\n G--C\n AT\n AT\n T--A\n A----T\nT------A\nT------A\n G----C\n T--A\n GC" }, { "code": null, "e": 700, "s": 429, "text": "Explanation : DNA primarily consists of 4 hydrocarbons i.e. cytosine [C], guanine [G], adenine[A], thymine [T].DNA bases pair up with each other, A with T and C with G, to form units called base pairs.Below is the implementation to print the double-helix DNA sequence : " }, { "code": null, "e": 704, "s": 700, "text": "CPP" }, { "code": null, "e": 709, "s": 704, "text": "Java" }, { "code": null, "e": 717, "s": 709, "text": "Python3" }, { "code": null, "e": 720, "s": 717, "text": "C#" }, { "code": null, "e": 724, "s": 720, "text": "PHP" }, { "code": null, "e": 735, "s": 724, "text": "Javascript" }, { "code": "// CPP Program to print the// 'n' lobes of DNA pattern#include <bits/stdc++.h>using namespace std; // Function to print upper half// of the DNA or the upper lobevoid printUpperHalf(string str){ char first, second; int pos = 0; // Each half of the DNA is made of // combination of two compounds for (int i = 1; i <= 4; i++) { // Taking the two carbon // compounds from the string first = str[pos]; second = str[pos + 1]; pos += 2; for (int j = 4 - i; j >= 1; j--) cout << \" \"; cout << first; for (int j = 1; j < i; j++) cout << \"--\"; cout << second << endl; }} // Function to print lower half// of the DNA or the lower lobevoid printLowerHalf(string str){ char first, second; int pos = 0; for (int i = 1; i <= 4; i++) { first = str[pos]; second = str[pos + 1]; pos += 2; for (int j = 1; j < i; j++) cout << \" \"; cout << first; for (int j = 4 - i; j >= 1; j--) cout << \"--\"; cout << second << endl; }} // Function to print 'n' parts of DNAvoid printDNA(string str[], int n){ for (int i = 0; i < n; i++) { int x = i % 6; // Calling for upperhalf if (x % 2 == 0) printUpperHalf(str[x]); else // Calling for lowerhalf printLowerHalf(str[x]); }} // Driver functionint main(){ int n = 8; // combinations stored in the array string DNA[] = { \"ATTAATTA\", \"TAGCTAGC\", \"CGCGATAT\", \"TAATATGC\", \"ATCGTACG\", \"CGTAGCAT\" }; printDNA(DNA, n); return 0;}", "e": 2413, "s": 735, "text": null }, { "code": "// Java Program to print the// 'n' lobes of DNA pattern import java.io.*; class GFG { // Function to print upper half// of the DNA or the upper lobestatic void printUpperHalf(String str){ char first, second; int pos = 0; // Each half of the DNA is made of // combination of two compounds for (int i = 1; i <= 4; i++) { // Taking the two carbon // compounds from the string first = str.charAt(pos); second = str.charAt(pos+1); pos += 2; for (int j = 4 - i; j >= 1; j--) System.out.print(\" \"); System.out.print(first); for (int j = 1; j < i; j++) System.out.print(\"--\"); System.out.println(second); }} // Function to print lower half// of the DNA or the lower lobestatic void printLowerHalf(String str){ char first, second; int pos = 0; for (int i = 1; i <= 4; i++) { first = str.charAt(pos); second = str.charAt(pos+1); pos += 2; for (int j = 1; j < i; j++) System.out.print(\" \"); System.out.print(first); for (int j = 4 - i; j >= 1; j--) System.out.print(\"--\"); System.out.println(second); }} // Function to print 'n' parts of DNAstatic void printDNA(String str[], int n){ for (int i = 0; i < n; i++) { int x = i % 6; // Calling for upperhalf if (x % 2 == 0) printUpperHalf(str[x]); else // Calling for lowerhalf printLowerHalf(str[x]); }}public static void main (String[] args) { int n = 8; // combinations stored in the array String DNA[] = { \"ATTAATTA\", \"TAGCTAGC\", \"CGCGATAT\", \"TAATATGC\", \"ATCGTACG\", \"CGTAGCAT\" }; printDNA(DNA, n); }} // This code is contributed by Gitanjali", "e": 4252, "s": 2413, "text": null }, { "code": "# Python Program to print the# 'n' lobes of DNA patternimport math # Function to print upper half# of the DNA or the upper lobedef printUpperHalf(str): first=0 second=0 pos = 0 # Each half of the DNA is made of # combination of two compounds for i in range(1,5): # Taking the two carbon # compounds from the string first = str[pos] second = str[pos+1] pos += 2 for j in range ( 4 - i, 0,-1): print(\" \",end=\"\") print(first,end=\"\") for j in range (1, i): print(\"--\",end=\"\") print(second) # Function to print lower half# of the DNA or the lower lobedef printLowerHalf(str): first=0 second=0 pos = 0 for i in range(1,5): first = str[pos] second = str[pos+1] pos += 2 for j in range(1,i): print(\" \",end=\"\") print(first,end=\"\") for j in range (4 - i, 0,-1): print(\"--\",end=\"\") print(second) # Function to print 'n' parts of DNAdef printDNA( str, n): for i in range(0,n): x = i % 6 # Calling for upperhalf if (x % 2 == 0): printUpperHalf(str[x]) else: # Calling for lowerhalf printLowerHalf(str[x]) # driver coden = 8 # combinations stored in the arrayDNA = [ \"ATTAATTA\", \"TAGCTAGC\", \"CGCGATAT\", \"TAATATGC\", \"ATCGTACG\", \"CGTAGCAT\" ] printDNA(DNA, n) # This code is contributed by Gitanjali.", "e": 5764, "s": 4252, "text": null }, { "code": "// C# Program to print the 'n' lobes of// DNA patternusing System; class GFG { // Function to print upper half // of the DNA or the upper lobe static void printUpperHalf(string str) { char first, second; int pos = 0; // Each half of the DNA is made of // combination of two compounds for (int i = 1; i <= 4; i++) { // Taking the two carbon // compounds from the string first = str[pos]; second = str[pos+1]; pos += 2; for (int j = 4 - i; j >= 1; j--) Console.Write(\" \"); Console.Write(first); for (int j = 1; j < i; j++) Console.Write(\"--\"); Console.WriteLine(second); } } // Function to print lower half // of the DNA or the lower lobe static void printLowerHalf(string str) { char first, second; int pos = 0; for (int i = 1; i <= 4; i++) { first = str[pos]; second = str[pos+1]; pos += 2; for (int j = 1; j < i; j++) Console.Write(\" \"); Console.Write(first); for (int j = 4 - i; j >= 1; j--) Console.Write(\"--\"); Console.WriteLine(second); } } // Function to print 'n' parts of DNA static void printDNA(string []str, int n) { for (int i = 0; i < n; i++) { int x = i % 6; // Calling for upperhalf if (x % 2 == 0) printUpperHalf(str[x]); else // Calling for lowerhalf printLowerHalf(str[x]); } } public static void Main () { int n = 8; // combinations stored in the array string []DNA = { \"ATTAATTA\", \"TAGCTAGC\", \"CGCGATAT\", \"TAATATGC\", \"ATCGTACG\", \"CGTAGCAT\" }; printDNA(DNA, n); }} // This code is contributed by vt_m.", "e": 7910, "s": 5764, "text": null }, { "code": "<?php// PHP implementation to print the// 'n' lobes of DNA pattern // Function to print upper half// of the DNA or the upper lobefunction printUpperHalf($str){ $pos = 0; // Each half of the DNA is made of // combination of two compounds for($i = 1; $i <= 4; $i++) { // Taking the two carbon // compounds from the string $first = $str[$pos]; $second = $str[$pos + 1]; $pos += 2; for ($j = 4 - $i; $j >= 1; $j--) echo \" \"; echo $first; for ($j = 1; $j < $i; $j++) echo \"--\"; echo $second.\"\\n\"; }} // Function to print lower half// of the DNA or the lower lobefunction printLowerHalf($str){ $pos = 0; for ($i = 1; $i <= 4; $i++) { $first = $str[$pos]; $second = $str[$pos + 1]; $pos += 2; for ($j = 1; $j < $i; $j++) echo \" \"; echo $first; for ($j = 4 - $i; $j >= 1; $j--) echo\"--\"; echo $second.\"\\n\"; }} // Function to print 'n' parts of DNAfunction printDNA($str, $n){ for ($i = 0; $i < $n; $i++) { $x = $i % 6; // Calling for upperhalf if ($x % 2 == 0) printUpperHalf($str[$x]); else // Calling for lowerhalf printLowerHalf($str[$x]); }} // Driver code$n = 8;$DNA = array( \"ATTAATTA\", \"TAGCTAGC\", \"CGCGATAT\", \"TAATATGC\", \"ATCGTACG\", \"CGTAGCAT\" );printDNA($DNA, $n); // This code is contributed by mits.?>", "e": 9440, "s": 7910, "text": null }, { "code": "<script> // javascript Program to print the// 'n' lobes of DNA pattern// Function to print upper half// of the DNA or the upper lobefunction printUpperHalf(str){ var first, second; var pos = 0; // Each half of the DNA is made of // combination of two compounds for (var i = 1; i <= 4; i++) { // Taking the two carbon // compounds from the string first = str.charAt(pos); second = str.charAt(pos+1); pos += 2; for (var j = 4 - i; j >= 1; j--) document.write(\" \"); document.write(first); for (var j = 1; j < i; j++) document.write(\"--\"); document.write(second+\"<br>\"); }} // Function to print lower half// of the DNA or the lower lobefunction printLowerHalf(str){ var first, second; var pos = 0; for (var i = 1; i <= 4; i++) { first = str.charAt(pos); second = str.charAt(pos+1); pos += 2; for (var j = 1; j < i; j++) document.write(\" \"); document.write(first); for (var j = 4 - i; j >= 1; j--) document.write(\"--\"); document.write(second+\"<br>\"); }} // Function to print 'n' parts of DNAfunction printDNA(str , n){ for (var i = 0; i < n; i++) { var x = i % 6; // Calling for upperhalf if (x % 2 == 0) printUpperHalf(str[x]); else // Calling for lowerhalf printLowerHalf(str[x]); }}var n = 8; // combinations stored in the arrayvar DNA = [ \"ATTAATTA\", \"TAGCTAGC\", \"CGCGATAT\", \"TAATATGC\", \"ATCGTACG\", \"CGTAGCAT\" ];printDNA(DNA, n); // This code contributed by Princi Singh</script>", "e": 11140, "s": 9440, "text": null }, { "code": null, "e": 11151, "s": 11140, "text": "Output : " }, { "code": null, "e": 11391, "s": 11151, "text": " AT\n T--A\n A----T\nT------A\nT------A\n G----C\n T--A\n GC\n CG\n C--G\n A----T\nA------T\nT------A\n A----T\n A--T\n GC\n AT\n C--G\n T----A\nC------G\nC------G\n T----A\n G--C\n AT\n AT\n T--A\n A----T\nT------A\nT------A\n G----C\n T--A\n GC" }, { "code": null, "e": 11487, "s": 11391, "text": " Time Complexity: O(N), as we are using a loop to traverse N times. Where N is the input given." }, { "code": null, "e": 11547, "s": 11487, "text": "Auxiliary Space: O(1), as we are not using any extra space." }, { "code": null, "e": 11560, "s": 11547, "text": "Mithun Kumar" }, { "code": null, "e": 11573, "s": 11560, "text": "princi singh" }, { "code": null, "e": 11586, "s": 11573, "text": "Kirti_Mangal" }, { "code": null, "e": 11599, "s": 11586, "text": "rohitsingh57" }, { "code": null, "e": 11616, "s": 11599, "text": "pattern-printing" }, { "code": null, "e": 11635, "s": 11616, "text": "School Programming" }, { "code": null, "e": 11652, "s": 11635, "text": "pattern-printing" } ]
Java Program to Sort LinkedHashMap By Values
09 Jun, 2021 The LinkedHashMap is just like HashMap with an additional feature of maintaining an order of elements inserted into it. HashMap provided the advantage of quick insertion, search, and deletion, but it never maintained the track and order of insertion which the LinkedHashMap provides where the elements can be accessed in their insertion order. Hence LinkedHashMap Is the child class of HashMap. Now, in LinkedHashMap insertion order has to be maintained, so convert the LinkedHashMap into a list and after that print the list in which values are in sorted order. Illustration: Input : LinkedHashMap = {{“for”, 2}, {“Geek”, 3}, {“Geeks”, 1}} Output: Key -> Geeks : value -> 1 Key -> for : value -> 2 Key -> Geek : value ->3 Procedure: Create an object of LinkedHashMap Class where the object is declared of type Integer and String.Add elements to the above object created of the map using the put() method. Elements here are key-value pairs.Retrieve above all entries from the map and convert them to a list using entrySet() method.Sort the value of the list using the custom comparator.Now use the Collections class sort method inside which we are using a custom comparator to compare the value of a map.Print the above list object using for each loop. Create an object of LinkedHashMap Class where the object is declared of type Integer and String. Add elements to the above object created of the map using the put() method. Elements here are key-value pairs. Retrieve above all entries from the map and convert them to a list using entrySet() method. Sort the value of the list using the custom comparator. Now use the Collections class sort method inside which we are using a custom comparator to compare the value of a map. Print the above list object using for each loop. Implementation: Example Java // java Program to Sort LinkedHashMap by Values // Importing all classes// from java.util packageimport java.util.*;import java.util.Collections;import java.util.Comparator;import java.util.LinkedHashMap; // Main Classclass GFG { // Main driver method public static void main(String[] args) { // Creating an object of LinkedHashMap Class // Declaring object of Integer and String type LinkedHashMap<String, Integer> map = new LinkedHashMap<>(); // Adding elements to the object of Map // using the put() method // Elements here are key-value pairs map.put("for", 2); map.put("Geek", 3); map.put("Geeks", 1); // Now, getting all entries from map and // convert it to a list using entrySet() method List<Map.Entry<String, Integer> > list = new ArrayList<Map.Entry<String, Integer> >( map.entrySet()); // Using collections class sort method // and inside which we are using // custom comparator to compare value of map Collections.sort( list, new Comparator<Map.Entry<String, Integer> >() { // Comparing two entries by value public int compare( Map.Entry<String, Integer> entry1, Map.Entry<String, Integer> entry2) { // Substracting the entries return entry1.getValue() - entry2.getValue(); } }); // Iterating over the sorted map // using the for each method for (Map.Entry<String, Integer> l : list) { // Printing the sorted map // using getKey() and getValue() methods System.out.println("Key ->" + " " + l.getKey() + ": Value ->" + l.getValue()); } }} Key -> Geeks: Value ->1 Key -> for: Value ->2 Key -> Geek: Value ->3 saurabh1990aror Java-Collections Java-LinkedHashMap Picked Java Java Programs Java Java-Collections Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n09 Jun, 2021" }, { "code": null, "e": 373, "s": 28, "text": "The LinkedHashMap is just like HashMap with an additional feature of maintaining an order of elements inserted into it. HashMap provided the advantage of quick insertion, search, and deletion, but it never maintained the track and order of insertion which the LinkedHashMap provides where the elements can be accessed in their insertion order. " }, { "code": null, "e": 592, "s": 373, "text": "Hence LinkedHashMap Is the child class of HashMap. Now, in LinkedHashMap insertion order has to be maintained, so convert the LinkedHashMap into a list and after that print the list in which values are in sorted order." }, { "code": null, "e": 606, "s": 592, "text": "Illustration:" }, { "code": null, "e": 670, "s": 606, "text": "Input : LinkedHashMap = {{“for”, 2}, {“Geek”, 3}, {“Geeks”, 1}}" }, { "code": null, "e": 680, "s": 670, "text": "Output: " }, { "code": null, "e": 706, "s": 680, "text": "Key -> Geeks : value -> 1" }, { "code": null, "e": 730, "s": 706, "text": "Key -> for : value -> 2" }, { "code": null, "e": 755, "s": 730, "text": "Key -> Geek : value ->3 " }, { "code": null, "e": 766, "s": 755, "text": "Procedure:" }, { "code": null, "e": 1285, "s": 766, "text": "Create an object of LinkedHashMap Class where the object is declared of type Integer and String.Add elements to the above object created of the map using the put() method. Elements here are key-value pairs.Retrieve above all entries from the map and convert them to a list using entrySet() method.Sort the value of the list using the custom comparator.Now use the Collections class sort method inside which we are using a custom comparator to compare the value of a map.Print the above list object using for each loop." }, { "code": null, "e": 1382, "s": 1285, "text": "Create an object of LinkedHashMap Class where the object is declared of type Integer and String." }, { "code": null, "e": 1493, "s": 1382, "text": "Add elements to the above object created of the map using the put() method. Elements here are key-value pairs." }, { "code": null, "e": 1585, "s": 1493, "text": "Retrieve above all entries from the map and convert them to a list using entrySet() method." }, { "code": null, "e": 1641, "s": 1585, "text": "Sort the value of the list using the custom comparator." }, { "code": null, "e": 1760, "s": 1641, "text": "Now use the Collections class sort method inside which we are using a custom comparator to compare the value of a map." }, { "code": null, "e": 1809, "s": 1760, "text": "Print the above list object using for each loop." }, { "code": null, "e": 1825, "s": 1809, "text": "Implementation:" }, { "code": null, "e": 1834, "s": 1825, "text": "Example " }, { "code": null, "e": 1839, "s": 1834, "text": "Java" }, { "code": "// java Program to Sort LinkedHashMap by Values // Importing all classes// from java.util packageimport java.util.*;import java.util.Collections;import java.util.Comparator;import java.util.LinkedHashMap; // Main Classclass GFG { // Main driver method public static void main(String[] args) { // Creating an object of LinkedHashMap Class // Declaring object of Integer and String type LinkedHashMap<String, Integer> map = new LinkedHashMap<>(); // Adding elements to the object of Map // using the put() method // Elements here are key-value pairs map.put(\"for\", 2); map.put(\"Geek\", 3); map.put(\"Geeks\", 1); // Now, getting all entries from map and // convert it to a list using entrySet() method List<Map.Entry<String, Integer> > list = new ArrayList<Map.Entry<String, Integer> >( map.entrySet()); // Using collections class sort method // and inside which we are using // custom comparator to compare value of map Collections.sort( list, new Comparator<Map.Entry<String, Integer> >() { // Comparing two entries by value public int compare( Map.Entry<String, Integer> entry1, Map.Entry<String, Integer> entry2) { // Substracting the entries return entry1.getValue() - entry2.getValue(); } }); // Iterating over the sorted map // using the for each method for (Map.Entry<String, Integer> l : list) { // Printing the sorted map // using getKey() and getValue() methods System.out.println(\"Key ->\" + \" \" + l.getKey() + \": Value ->\" + l.getValue()); } }}", "e": 3803, "s": 1839, "text": null }, { "code": null, "e": 3872, "s": 3803, "text": "Key -> Geeks: Value ->1\nKey -> for: Value ->2\nKey -> Geek: Value ->3" }, { "code": null, "e": 3890, "s": 3874, "text": "saurabh1990aror" }, { "code": null, "e": 3907, "s": 3890, "text": "Java-Collections" }, { "code": null, "e": 3926, "s": 3907, "text": "Java-LinkedHashMap" }, { "code": null, "e": 3933, "s": 3926, "text": "Picked" }, { "code": null, "e": 3938, "s": 3933, "text": "Java" }, { "code": null, "e": 3952, "s": 3938, "text": "Java Programs" }, { "code": null, "e": 3957, "s": 3952, "text": "Java" }, { "code": null, "e": 3974, "s": 3957, "text": "Java-Collections" } ]
Laplacian Filter using Matlab
17 Mar, 2022 Laplacian filter is a second-order derivate filter used in edge detection, in digital image processing. In 1st order derivative filters, we detect the edge along with horizontal and vertical directions separately and then combine both. But using the Laplacian filter we detect the edges in the whole image at once. The Laplacian Operator/Filter is = [0 1 0; 1 -4 1; 0 1 0] here the central value of filter is negative. Or Filter is = [0 -1 0; -1 4 -1; 0 -1 0], here the central value of filter is positive. Note:The sum of all values of the filter is always 0. Steps: Read the image in Matlab, using imread() function. If the image is colored then convert it into RGB format. Define the Laplacian filter. Convolve the image with the filter. Display the binary edge-detected image. Syntax: var_name = imread(” name of image . extension “); //Read the image in variable ar_name = rgb2gray ( old_image_var); //Convert into grayscale “conv2( )” //Convolution is performed “imtool( )” is used for displaying image. Example: Matlab % MATLAB code for% Edge detection using Laplacian Filter.k=imread("logo.png"); % Convert rgb image to grayscale.k1=rgb2gray(k); % Convert into double format.k1=double(k1); % Define the Laplacian filter.Laplacian=[0 1 0; 1 -4 1; 0 1 0]; % Convolve the image using Laplacian Filterk2=conv2(k1, Laplacian, 'same'); % Display the image.imtool(k1, []);imtool(abs(k2,[]); Output: Figure: Input Image Figure: Output image after Edge detection Disadvantages: We should note that first derivative operators exaggerate the effects of noise. Second derivatives will exaggerate noise twice as much. No directional information about the edge is given. sweetyty MATLAB image-processing MATLAB Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 54, "s": 26, "text": "\n17 Mar, 2022" }, { "code": null, "e": 369, "s": 54, "text": "Laplacian filter is a second-order derivate filter used in edge detection, in digital image processing. In 1st order derivative filters, we detect the edge along with horizontal and vertical directions separately and then combine both. But using the Laplacian filter we detect the edges in the whole image at once." }, { "code": null, "e": 716, "s": 369, "text": "The Laplacian Operator/Filter is = [0 1 0; \n 1 -4 1;\n 0 1 0]\nhere the central value of filter is negative.\n Or\nFilter is = [0 -1 0;\n -1 4 -1; \n 0 -1 0],\nhere the central value of filter is positive.\nNote:The sum of all values of the filter is always 0." }, { "code": null, "e": 723, "s": 716, "text": "Steps:" }, { "code": null, "e": 774, "s": 723, "text": "Read the image in Matlab, using imread() function." }, { "code": null, "e": 831, "s": 774, "text": "If the image is colored then convert it into RGB format." }, { "code": null, "e": 860, "s": 831, "text": "Define the Laplacian filter." }, { "code": null, "e": 896, "s": 860, "text": "Convolve the image with the filter." }, { "code": null, "e": 936, "s": 896, "text": "Display the binary edge-detected image." }, { "code": null, "e": 944, "s": 936, "text": "Syntax:" }, { "code": null, "e": 1025, "s": 944, "text": " var_name = imread(” name of image . extension “); //Read the image in variable" }, { "code": null, "e": 1087, "s": 1025, "text": "ar_name = rgb2gray ( old_image_var); //Convert into grayscale" }, { "code": null, "e": 1127, "s": 1087, "text": " “conv2( )” //Convolution is performed " }, { "code": null, "e": 1169, "s": 1127, "text": "“imtool( )” is used for displaying image." }, { "code": null, "e": 1178, "s": 1169, "text": "Example:" }, { "code": null, "e": 1185, "s": 1178, "text": "Matlab" }, { "code": "% MATLAB code for% Edge detection using Laplacian Filter.k=imread(\"logo.png\"); % Convert rgb image to grayscale.k1=rgb2gray(k); % Convert into double format.k1=double(k1); % Define the Laplacian filter.Laplacian=[0 1 0; 1 -4 1; 0 1 0]; % Convolve the image using Laplacian Filterk2=conv2(k1, Laplacian, 'same'); % Display the image.imtool(k1, []);imtool(abs(k2,[]);", "e": 1551, "s": 1185, "text": null }, { "code": null, "e": 1563, "s": 1554, "text": "Output: " }, { "code": null, "e": 1589, "s": 1569, "text": "Figure: Input Image" }, { "code": null, "e": 1635, "s": 1593, "text": "Figure: Output image after Edge detection" }, { "code": null, "e": 1652, "s": 1637, "text": "Disadvantages:" }, { "code": null, "e": 1790, "s": 1654, "text": "We should note that first derivative operators exaggerate the effects of noise. Second derivatives will exaggerate noise twice as much." }, { "code": null, "e": 1842, "s": 1790, "text": "No directional information about the edge is given." }, { "code": null, "e": 1855, "s": 1846, "text": "sweetyty" }, { "code": null, "e": 1879, "s": 1855, "text": "MATLAB image-processing" }, { "code": null, "e": 1886, "s": 1879, "text": "MATLAB" } ]
Program to cyclically rotate an array by one
12 Jul, 2022 Given an array, cyclically rotate the array clockwise by one. Examples: Input: arr[] = {1, 2, 3, 4, 5} Output: arr[] = {5, 1, 2, 3, 4} Following are steps. 1) Store last element in a variable say x. 2) Shift all elements one position ahead. 3) Replace first element of array with x. C++ C Java Python3 C# PHP Javascript // C++ code for program // to cyclically rotate// an array by one# include <iostream>using namespace std; void rotate(int arr[], int n){ int x = arr[n - 1], i; for (i = n - 1; i > 0; i--) arr[i] = arr[i - 1]; arr[0] = x;} // Driver codeint main() { int arr[] = {1, 2, 3, 4, 5}, i; int n = sizeof(arr) / sizeof(arr[0]); cout << "Given array is \n"; for (i = 0; i < n; i++) cout << arr[i] << ' '; rotate(arr, n); cout << "\nRotated array is\n"; for (i = 0; i < n; i++) cout << arr[i] << ' '; return 0;} // This code is contributed by jit_t #include <stdio.h> void rotate(int arr[], int n){ int x = arr[n-1], i; for (i = n-1; i > 0; i--) arr[i] = arr[i-1]; arr[0] = x;} int main(){ int arr[] = {1, 2, 3, 4, 5}, i; int n = sizeof(arr)/sizeof(arr[0]); printf("Given array is\n"); for (i = 0; i < n; i++) printf("%d ", arr[i]); rotate(arr, n); printf("\nRotated array is\n"); for (i = 0; i < n; i++) printf("%d ", arr[i]); return 0;} import java.util.Arrays; public class Test{ static int arr[] = new int[]{1, 2, 3, 4, 5}; // Method for rotation static void rotate() { int x = arr[arr.length-1], i; for (i = arr.length-1; i > 0; i--) arr[i] = arr[i-1]; arr[0] = x; } /* Driver program */ public static void main(String[] args) { System.out.println("Given Array is"); System.out.println(Arrays.toString(arr)); rotate(); System.out.println("Rotated Array is"); System.out.println(Arrays.toString(arr)); }} # Python3 code for program to # cyclically rotate an array by one # Method for rotationdef rotate(arr, n): x = arr[n - 1] for i in range(n - 1, 0, -1): arr[i] = arr[i - 1]; arr[0] = x; # Driver functionarr= [1, 2, 3, 4, 5]n = len(arr)print ("Given array is")for i in range(0, n): print (arr[i], end = ' ') rotate(arr, n) print ("\nRotated array is")for i in range(0, n): print (arr[i], end = ' ') # This article is contributed # by saloni1297 // C# code for program to cyclically// rotate an array by oneusing System; public class Test{ static int []arr = new int[]{1, 2, 3, 4, 5}; // Method for rotation static void rotate() { int x = arr[arr.Length - 1], i; for (i = arr.Length - 1; i > 0; i--) arr[i] = arr[i-1]; arr[0] = x; } // Driver Code public static void Main() { Console.WriteLine("Given Array is"); string Original_array = string.Join(" ", arr); Console.WriteLine(Original_array); rotate(); Console.WriteLine("Rotated Array is"); string Rotated_array = string.Join(" ", arr); Console.WriteLine(Rotated_array); }} // This code is contributed by vt_m. <?php// PHP code for program // to cyclically rotate// an array by one function rotate(&$arr, $n){ $x = $arr[$n - 1]; for ($i = $n - 1; $i > 0; $i--) $arr[$i] = $arr[$i - 1]; $arr[0] = $x;} // Driver code$arr = array(1, 2, 3, 4, 5);$n = sizeof($arr); echo "Given array is \n";for ($i = 0; $i < $n; $i++) echo $arr[$i] . " "; rotate($arr, $n); echo "\nRotated array is\n";for ($i = 0; $i < $n; $i++) echo $arr[$i] . " "; // This code is contributed// by ChitraNayal?> <script> // JavaScript code for program // to cyclically rotate// an array by onefunction rotate(arr, n){ var x = arr[n-1], i; for(i = n-1; i > 0; i--) arr[i] = arr[i-1]; arr[0] = x; } var arr = [1, 2, 3, 4, 5];var n = arr.length; document.write("Given array is <br>");for(var i = 0; i< n; i++) document.write(arr[i] + " "); rotate(arr, n); document.write("<br>Rotated array is <br>");for(var i = 0; i < n; i++) document.write(arr[i] + " "); </script> Given array is 1 2 3 4 5 Rotated array is 5 1 2 3 4 Time Complexity: O(n) As we need to iterate through all the elements Auxiliary Space: O(1)The above question can also be solved by using reversal algorithm. Another approach: We can use two pointers, say i and j which point to first and last element of array respectively. As we know in cyclic rotation we will bring last element to first and shift rest in forward direction, so start swaping arr[i] and arr[j] and keep j fixed and i moving towards j. Repeat till i is not equal to j. C++ C Java Python3 C# Javascript #include <iostream>using namespace std; void rotate(int arr[], int n){ int i = 0, j = n-1; // i and j pointing to first and last element respectively while(i != j){ swap(arr[i], arr[j]); i++; }} // Driver codeint main() { int arr[] = {1, 2, 3, 4, 5}, i; int n = sizeof(arr) / sizeof(arr[0]); cout << "Given array is \n"; for (i = 0; i < n; i++) cout << arr[i] << " "; rotate(arr, n); cout << "\nRotated array is\n"; for (i = 0; i < n; i++) cout << arr[i] << " "; return 0;} #include <stdio.h> void swap(int *x, int *y){ int temp = *x; *x = *y; *y = temp;}void rotate(int arr[], int n){ int i = 0, j = n - 1; while(i != j) { swap(&arr[i], &arr[j]); i++; }} int main(){ int arr[] = {1, 2, 3, 4, 5}, i; int n = sizeof(arr)/sizeof(arr[0]); printf("Given array is\n"); for (i = 0; i < n; i++) printf("%d ", arr[i]); rotate(arr, n); printf("\nRotated array is\n"); for (i = 0; i < n; i++) printf("%d ", arr[i]); return 0;} import java.util.Arrays; public class Test{ static int arr[] = new int[]{1, 2, 3, 4, 5}; static void rotate() { int i = 0, j = arr.length - 1; while(i != j) { int temp = arr[i]; arr[i] = arr[j]; arr[j] = temp; i++; } } /* Driver program */ public static void main(String[] args) { System.out.println("Given Array is"); System.out.println(Arrays.toString(arr)); rotate(); System.out.println("Rotated Array is"); System.out.println(Arrays.toString(arr)); }} def rotate(arr, n): i = 0 j = n - 1 while i != j: arr[i], arr[j] = arr[j], arr[i] i = i + 1 pass # Driver functionarr= [1, 2, 3, 4, 5]n = len(arr)print ("Given array is")for i in range(0, n): print (arr[i], end = ' ') rotate(arr, n) print ("\nRotated array is")for i in range(0, n): print (arr[i], end = ' ') // C# code for program to cyclically// rotate an array by oneusing System; class GFG{ static int []arr = new int[]{ 1, 2, 3, 4, 5 }; // Method for rotationstatic void rotate(){ int n = arr[arr.Length - 1]; // i and j pointing to first and // last element respectively int i = 0, j = n - 1; while(i != j) { { int temp = arr[i]; arr[i] = arr[j]; arr[j] = temp; } i++; }} // Driver Codepublic static void Main() { Console.WriteLine("Given Array is"); string Original_array = string.Join(" ", arr); Console.WriteLine(Original_array); rotate(); Console.WriteLine("Rotated Array is"); string Rotated_array = string.Join(" ", arr); Console.WriteLine(Rotated_array);}} // This code is contributed by annianni <script>// JavaScript code for program// to cyclically rotate// an array by one using pointers i,j function rotate(arr, n){ var i = 0 var j = n-1 while(i != j){ let temp; temp = arr[i]; arr[i] = arr[j]; arr[j]= temp; i =i+1 }} var arr = [1, 2, 3, 4, 5];var n = arr.length; document.write("Given array is <br>");for(var i = 0; i< n; i++) document.write(arr[i] + " "); rotate(arr, n); document.write("<br>Rotated array is <br>");for(var i = 0; i < n; i++) document.write(arr[i] + " ");</script> Given array is 1 2 3 4 5 Rotated array is 5 1 2 3 4 Time Complexity: O(n) Auxiliary Space: O(1) Another approach(Using Slicing ): We can also solve this problem using slicing in python. Implementation for the above approach:- Python3 def rotateArray(array): ''' array[-1:] taking last element array[:-1] taking elements from start to last second element array[:] changing array from starting to end ''' array[:] = array[-1:]+array[:-1] # create arrayarray = [1, 2, 3, 4, 5]# send array to rotateArray functionrotateArray(array) print(*array) # 5 1 2 3 4 5 1 2 3 4 Time Complexity : O(n) Auxiliary Space: O(1) 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. jit_t ukasp Shiva_Chandel nitinshivanandmesta PavanKumar47 probinsah piyushpande0405 humphreykibet annianni gvktrail _shinchancode rotation Arrays School Programming Arrays Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 53, "s": 25, "text": "\n12 Jul, 2022" }, { "code": null, "e": 116, "s": 53, "text": "Given an array, cyclically rotate the array clockwise by one. " }, { "code": null, "e": 128, "s": 116, "text": "Examples: " }, { "code": null, "e": 192, "s": 128, "text": "Input: arr[] = {1, 2, 3, 4, 5}\nOutput: arr[] = {5, 1, 2, 3, 4}" }, { "code": null, "e": 341, "s": 192, "text": "Following are steps. 1) Store last element in a variable say x. 2) Shift all elements one position ahead. 3) Replace first element of array with x. " }, { "code": null, "e": 345, "s": 341, "text": "C++" }, { "code": null, "e": 347, "s": 345, "text": "C" }, { "code": null, "e": 352, "s": 347, "text": "Java" }, { "code": null, "e": 360, "s": 352, "text": "Python3" }, { "code": null, "e": 363, "s": 360, "text": "C#" }, { "code": null, "e": 367, "s": 363, "text": "PHP" }, { "code": null, "e": 378, "s": 367, "text": "Javascript" }, { "code": "// C++ code for program // to cyclically rotate// an array by one# include <iostream>using namespace std; void rotate(int arr[], int n){ int x = arr[n - 1], i; for (i = n - 1; i > 0; i--) arr[i] = arr[i - 1]; arr[0] = x;} // Driver codeint main() { int arr[] = {1, 2, 3, 4, 5}, i; int n = sizeof(arr) / sizeof(arr[0]); cout << \"Given array is \\n\"; for (i = 0; i < n; i++) cout << arr[i] << ' '; rotate(arr, n); cout << \"\\nRotated array is\\n\"; for (i = 0; i < n; i++) cout << arr[i] << ' '; return 0;} // This code is contributed by jit_t", "e": 990, "s": 378, "text": null }, { "code": "#include <stdio.h> void rotate(int arr[], int n){ int x = arr[n-1], i; for (i = n-1; i > 0; i--) arr[i] = arr[i-1]; arr[0] = x;} int main(){ int arr[] = {1, 2, 3, 4, 5}, i; int n = sizeof(arr)/sizeof(arr[0]); printf(\"Given array is\\n\"); for (i = 0; i < n; i++) printf(\"%d \", arr[i]); rotate(arr, n); printf(\"\\nRotated array is\\n\"); for (i = 0; i < n; i++) printf(\"%d \", arr[i]); return 0;}", "e": 1439, "s": 990, "text": null }, { "code": "import java.util.Arrays; public class Test{ static int arr[] = new int[]{1, 2, 3, 4, 5}; // Method for rotation static void rotate() { int x = arr[arr.length-1], i; for (i = arr.length-1; i > 0; i--) arr[i] = arr[i-1]; arr[0] = x; } /* Driver program */ public static void main(String[] args) { System.out.println(\"Given Array is\"); System.out.println(Arrays.toString(arr)); rotate(); System.out.println(\"Rotated Array is\"); System.out.println(Arrays.toString(arr)); }}", "e": 2032, "s": 1439, "text": null }, { "code": "# Python3 code for program to # cyclically rotate an array by one # Method for rotationdef rotate(arr, n): x = arr[n - 1] for i in range(n - 1, 0, -1): arr[i] = arr[i - 1]; arr[0] = x; # Driver functionarr= [1, 2, 3, 4, 5]n = len(arr)print (\"Given array is\")for i in range(0, n): print (arr[i], end = ' ') rotate(arr, n) print (\"\\nRotated array is\")for i in range(0, n): print (arr[i], end = ' ') # This article is contributed # by saloni1297", "e": 2520, "s": 2032, "text": null }, { "code": "// C# code for program to cyclically// rotate an array by oneusing System; public class Test{ static int []arr = new int[]{1, 2, 3, 4, 5}; // Method for rotation static void rotate() { int x = arr[arr.Length - 1], i; for (i = arr.Length - 1; i > 0; i--) arr[i] = arr[i-1]; arr[0] = x; } // Driver Code public static void Main() { Console.WriteLine(\"Given Array is\"); string Original_array = string.Join(\" \", arr); Console.WriteLine(Original_array); rotate(); Console.WriteLine(\"Rotated Array is\"); string Rotated_array = string.Join(\" \", arr); Console.WriteLine(Rotated_array); }} // This code is contributed by vt_m.", "e": 3272, "s": 2520, "text": null }, { "code": "<?php// PHP code for program // to cyclically rotate// an array by one function rotate(&$arr, $n){ $x = $arr[$n - 1]; for ($i = $n - 1; $i > 0; $i--) $arr[$i] = $arr[$i - 1]; $arr[0] = $x;} // Driver code$arr = array(1, 2, 3, 4, 5);$n = sizeof($arr); echo \"Given array is \\n\";for ($i = 0; $i < $n; $i++) echo $arr[$i] . \" \"; rotate($arr, $n); echo \"\\nRotated array is\\n\";for ($i = 0; $i < $n; $i++) echo $arr[$i] . \" \"; // This code is contributed// by ChitraNayal?>", "e": 3772, "s": 3272, "text": null }, { "code": "<script> // JavaScript code for program // to cyclically rotate// an array by onefunction rotate(arr, n){ var x = arr[n-1], i; for(i = n-1; i > 0; i--) arr[i] = arr[i-1]; arr[0] = x; } var arr = [1, 2, 3, 4, 5];var n = arr.length; document.write(\"Given array is <br>\");for(var i = 0; i< n; i++) document.write(arr[i] + \" \"); rotate(arr, n); document.write(\"<br>Rotated array is <br>\");for(var i = 0; i < n; i++) document.write(arr[i] + \" \"); </script>", "e": 4255, "s": 3772, "text": null }, { "code": null, "e": 4311, "s": 4255, "text": "Given array is \n1 2 3 4 5 \n\nRotated array is\n5 1 2 3 4 " }, { "code": null, "e": 4468, "s": 4311, "text": "Time Complexity: O(n) As we need to iterate through all the elements Auxiliary Space: O(1)The above question can also be solved by using reversal algorithm." }, { "code": null, "e": 4486, "s": 4468, "text": "Another approach:" }, { "code": null, "e": 4797, "s": 4486, "text": "We can use two pointers, say i and j which point to first and last element of array respectively. As we know in cyclic rotation we will bring last element to first and shift rest in forward direction, so start swaping arr[i] and arr[j] and keep j fixed and i moving towards j. Repeat till i is not equal to j." }, { "code": null, "e": 4801, "s": 4797, "text": "C++" }, { "code": null, "e": 4803, "s": 4801, "text": "C" }, { "code": null, "e": 4808, "s": 4803, "text": "Java" }, { "code": null, "e": 4816, "s": 4808, "text": "Python3" }, { "code": null, "e": 4819, "s": 4816, "text": "C#" }, { "code": null, "e": 4830, "s": 4819, "text": "Javascript" }, { "code": "#include <iostream>using namespace std; void rotate(int arr[], int n){ int i = 0, j = n-1; // i and j pointing to first and last element respectively while(i != j){ swap(arr[i], arr[j]); i++; }} // Driver codeint main() { int arr[] = {1, 2, 3, 4, 5}, i; int n = sizeof(arr) / sizeof(arr[0]); cout << \"Given array is \\n\"; for (i = 0; i < n; i++) cout << arr[i] << \" \"; rotate(arr, n); cout << \"\\nRotated array is\\n\"; for (i = 0; i < n; i++) cout << arr[i] << \" \"; return 0;}", "e": 5385, "s": 4830, "text": null }, { "code": "#include <stdio.h> void swap(int *x, int *y){ int temp = *x; *x = *y; *y = temp;}void rotate(int arr[], int n){ int i = 0, j = n - 1; while(i != j) { swap(&arr[i], &arr[j]); i++; }} int main(){ int arr[] = {1, 2, 3, 4, 5}, i; int n = sizeof(arr)/sizeof(arr[0]); printf(\"Given array is\\n\"); for (i = 0; i < n; i++) printf(\"%d \", arr[i]); rotate(arr, n); printf(\"\\nRotated array is\\n\"); for (i = 0; i < n; i++) printf(\"%d \", arr[i]); return 0;}", "e": 5889, "s": 5385, "text": null }, { "code": "import java.util.Arrays; public class Test{ static int arr[] = new int[]{1, 2, 3, 4, 5}; static void rotate() { int i = 0, j = arr.length - 1; while(i != j) { int temp = arr[i]; arr[i] = arr[j]; arr[j] = temp; i++; } } /* Driver program */ public static void main(String[] args) { System.out.println(\"Given Array is\"); System.out.println(Arrays.toString(arr)); rotate(); System.out.println(\"Rotated Array is\"); System.out.println(Arrays.toString(arr)); }}", "e": 6499, "s": 5889, "text": null }, { "code": "def rotate(arr, n): i = 0 j = n - 1 while i != j: arr[i], arr[j] = arr[j], arr[i] i = i + 1 pass # Driver functionarr= [1, 2, 3, 4, 5]n = len(arr)print (\"Given array is\")for i in range(0, n): print (arr[i], end = ' ') rotate(arr, n) print (\"\\nRotated array is\")for i in range(0, n): print (arr[i], end = ' ')", "e": 6842, "s": 6499, "text": null }, { "code": "// C# code for program to cyclically// rotate an array by oneusing System; class GFG{ static int []arr = new int[]{ 1, 2, 3, 4, 5 }; // Method for rotationstatic void rotate(){ int n = arr[arr.Length - 1]; // i and j pointing to first and // last element respectively int i = 0, j = n - 1; while(i != j) { { int temp = arr[i]; arr[i] = arr[j]; arr[j] = temp; } i++; }} // Driver Codepublic static void Main() { Console.WriteLine(\"Given Array is\"); string Original_array = string.Join(\" \", arr); Console.WriteLine(Original_array); rotate(); Console.WriteLine(\"Rotated Array is\"); string Rotated_array = string.Join(\" \", arr); Console.WriteLine(Rotated_array);}} // This code is contributed by annianni", "e": 7665, "s": 6842, "text": null }, { "code": "<script>// JavaScript code for program// to cyclically rotate// an array by one using pointers i,j function rotate(arr, n){ var i = 0 var j = n-1 while(i != j){ let temp; temp = arr[i]; arr[i] = arr[j]; arr[j]= temp; i =i+1 }} var arr = [1, 2, 3, 4, 5];var n = arr.length; document.write(\"Given array is <br>\");for(var i = 0; i< n; i++) document.write(arr[i] + \" \"); rotate(arr, n); document.write(\"<br>Rotated array is <br>\");for(var i = 0; i < n; i++) document.write(arr[i] + \" \");</script>", "e": 8222, "s": 7665, "text": null }, { "code": null, "e": 8277, "s": 8222, "text": "Given array is \n1 2 3 4 5 \nRotated array is\n5 1 2 3 4 " }, { "code": null, "e": 8321, "s": 8277, "text": "Time Complexity: O(n) Auxiliary Space: O(1)" }, { "code": null, "e": 8355, "s": 8321, "text": "Another approach(Using Slicing ):" }, { "code": null, "e": 8413, "s": 8355, "text": "We can also solve this problem using slicing in python. " }, { "code": null, "e": 8453, "s": 8413, "text": "Implementation for the above approach:-" }, { "code": null, "e": 8461, "s": 8453, "text": "Python3" }, { "code": "def rotateArray(array): ''' array[-1:] taking last element array[:-1] taking elements from start to last second element array[:] changing array from starting to end ''' array[:] = array[-1:]+array[:-1] # create arrayarray = [1, 2, 3, 4, 5]# send array to rotateArray functionrotateArray(array) print(*array) # 5 1 2 3 4", "e": 8804, "s": 8461, "text": null }, { "code": null, "e": 8814, "s": 8804, "text": "5 1 2 3 4" }, { "code": null, "e": 8837, "s": 8814, "text": "Time Complexity : O(n)" }, { "code": null, "e": 8859, "s": 8837, "text": "Auxiliary Space: O(1)" }, { "code": null, "e": 8868, "s": 8859, "text": "Chapters" }, { "code": null, "e": 8895, "s": 8868, "text": "descriptions off, selected" }, { "code": null, "e": 8945, "s": 8895, "text": "captions settings, opens captions settings dialog" }, { "code": null, "e": 8968, "s": 8945, "text": "captions off, selected" }, { "code": null, "e": 8976, "s": 8968, "text": "English" }, { "code": null, "e": 9000, "s": 8976, "text": "This is a modal window." }, { "code": null, "e": 9069, "s": 9000, "text": "Beginning of dialog window. Escape will cancel and close the window." }, { "code": null, "e": 9091, "s": 9069, "text": "End of dialog window." }, { "code": null, "e": 9097, "s": 9091, "text": "jit_t" }, { "code": null, "e": 9103, "s": 9097, "text": "ukasp" }, { "code": null, "e": 9117, "s": 9103, "text": "Shiva_Chandel" }, { "code": null, "e": 9137, "s": 9117, "text": "nitinshivanandmesta" }, { "code": null, "e": 9150, "s": 9137, "text": "PavanKumar47" }, { "code": null, "e": 9160, "s": 9150, "text": "probinsah" }, { "code": null, "e": 9176, "s": 9160, "text": "piyushpande0405" }, { "code": null, "e": 9190, "s": 9176, "text": "humphreykibet" }, { "code": null, "e": 9199, "s": 9190, "text": "annianni" }, { "code": null, "e": 9208, "s": 9199, "text": "gvktrail" }, { "code": null, "e": 9222, "s": 9208, "text": "_shinchancode" }, { "code": null, "e": 9231, "s": 9222, "text": "rotation" }, { "code": null, "e": 9238, "s": 9231, "text": "Arrays" }, { "code": null, "e": 9257, "s": 9238, "text": "School Programming" }, { "code": null, "e": 9264, "s": 9257, "text": "Arrays" } ]
How to convert Excel column to vector in R ?
17 Jun, 2021 In this article, we will be looking at the different approaches to convert the Excel columns to vector in R Programming language. The approaches to convert Excel column to vector in the R language are listed as follows: Using $-Operator with the column name.Using the method of Subsetting column.Using pull function from dplyr library from the R language Using $-Operator with the column name. Using the method of Subsetting column. Using pull function from dplyr library from the R language Method 1: Using $-Operator with the column name In this method, we will be simply using the $-operator with the column name and the name of the data read from the Excel file. Here, the name of the column name which has to be converted in the vector would be written at the end of the $-operator and the name of the data read from the Excel file will be written before the $-operator. Syntax: dataframe$column Example: In this example, we will be using the $-Operator with the column name to convert the first column of the excel file in the form of a vector. The used Excel file: Below is the implementation: R library(readxl)gfg_data <- read_excel("R/Data_gfg.xlsx") # $-Operatorv1<-gfg_data$A print(v1) Output: [1] 1 4 9 8 1 7 7 1 4 4 4 3 4 7 4 8 Method 2: Using the method of Subsetting column Under this approach user just need to enter the column name inside the brackets columns with the data to convert that excel column into vector form. This will only be converting the column to the vector which the user has passed with the brackets along with its data. Syntax: dataframe[row_name,column_name] Example: In this example, we will be using the method of Subsetting column name to convert the second column of the Excel file in the form of a vector. Below is the implementation: R library(readxl)gfg_data <- read_excel("R/Data_gfg.xlsx") # Subsetting columnv2 <- gfg_data[ , "B"] print(v2) Output: Method 3: Using pull function from dplyr library from the R language: Here, the user has to call the pull() function from the dplyr library of R language and pass the column name which is needed to be converted into the vector form and the name of the datafile read variable. pull function: This function pull selects a column in a data frame and transforms it into a vector. Syntax: pull(.data, j) Parameters: .data:-name of the data j:-The column to be extracted. Returns: A vector of the provided column. Example: In this example, we will be using the method of Subsetting column name to convert the last column of the Excel file in the form of a vector. Below is the implementation: R library(readxl)gfg_data <- read_excel("R/Data_gfg.xlsx") # Load dplyrlibrary("dplyr") # pull functionv3 <- pull(gfg_data,C) print(v3) Output: [1] 5 2 5 2 2 1 1 8 5 5 8 1 9 7 1 2 abhishek0719kadiyan Picked R-Excel R Language R Programs Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to Split Column Into Multiple Columns in R DataFrame? 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 import an Excel File into R ? How to Split Column Into Multiple Columns in R DataFrame? How to filter R DataFrame by values in a column? Replace Specific Characters in String in R Extract First or Last n Characters from String in R Merge DataFrames by Column Names in R
[ { "code": null, "e": 28, "s": 0, "text": "\n17 Jun, 2021" }, { "code": null, "e": 158, "s": 28, "text": "In this article, we will be looking at the different approaches to convert the Excel columns to vector in R Programming language." }, { "code": null, "e": 248, "s": 158, "text": "The approaches to convert Excel column to vector in the R language are listed as follows:" }, { "code": null, "e": 384, "s": 248, "text": "Using $-Operator with the column name.Using the method of Subsetting column.Using pull function from dplyr library from the R language" }, { "code": null, "e": 423, "s": 384, "text": "Using $-Operator with the column name." }, { "code": null, "e": 462, "s": 423, "text": "Using the method of Subsetting column." }, { "code": null, "e": 522, "s": 462, "text": "Using pull function from dplyr library from the R language" }, { "code": null, "e": 570, "s": 522, "text": "Method 1: Using $-Operator with the column name" }, { "code": null, "e": 906, "s": 570, "text": "In this method, we will be simply using the $-operator with the column name and the name of the data read from the Excel file. Here, the name of the column name which has to be converted in the vector would be written at the end of the $-operator and the name of the data read from the Excel file will be written before the $-operator." }, { "code": null, "e": 931, "s": 906, "text": "Syntax: dataframe$column" }, { "code": null, "e": 940, "s": 931, "text": "Example:" }, { "code": null, "e": 1081, "s": 940, "text": "In this example, we will be using the $-Operator with the column name to convert the first column of the excel file in the form of a vector." }, { "code": null, "e": 1102, "s": 1081, "text": "The used Excel file:" }, { "code": null, "e": 1131, "s": 1102, "text": "Below is the implementation:" }, { "code": null, "e": 1133, "s": 1131, "text": "R" }, { "code": "library(readxl)gfg_data <- read_excel(\"R/Data_gfg.xlsx\") # $-Operatorv1<-gfg_data$A print(v1)", "e": 1250, "s": 1133, "text": null }, { "code": null, "e": 1258, "s": 1250, "text": "Output:" }, { "code": null, "e": 1294, "s": 1258, "text": "[1] 1 4 9 8 1 7 7 1 4 4 4 3 4 7 4 8" }, { "code": null, "e": 1342, "s": 1294, "text": "Method 2: Using the method of Subsetting column" }, { "code": null, "e": 1610, "s": 1342, "text": "Under this approach user just need to enter the column name inside the brackets columns with the data to convert that excel column into vector form. This will only be converting the column to the vector which the user has passed with the brackets along with its data." }, { "code": null, "e": 1650, "s": 1610, "text": "Syntax: dataframe[row_name,column_name]" }, { "code": null, "e": 1659, "s": 1650, "text": "Example:" }, { "code": null, "e": 1802, "s": 1659, "text": "In this example, we will be using the method of Subsetting column name to convert the second column of the Excel file in the form of a vector." }, { "code": null, "e": 1831, "s": 1802, "text": "Below is the implementation:" }, { "code": null, "e": 1833, "s": 1831, "text": "R" }, { "code": "library(readxl)gfg_data <- read_excel(\"R/Data_gfg.xlsx\") # Subsetting columnv2 <- gfg_data[ , \"B\"] print(v2)", "e": 1959, "s": 1833, "text": null }, { "code": null, "e": 1967, "s": 1959, "text": "Output:" }, { "code": null, "e": 2037, "s": 1967, "text": "Method 3: Using pull function from dplyr library from the R language:" }, { "code": null, "e": 2243, "s": 2037, "text": "Here, the user has to call the pull() function from the dplyr library of R language and pass the column name which is needed to be converted into the vector form and the name of the datafile read variable." }, { "code": null, "e": 2344, "s": 2243, "text": "pull function: This function pull selects a column in a data frame and transforms it into a vector. " }, { "code": null, "e": 2367, "s": 2344, "text": "Syntax: pull(.data, j)" }, { "code": null, "e": 2380, "s": 2367, "text": "Parameters: " }, { "code": null, "e": 2404, "s": 2380, "text": ".data:-name of the data" }, { "code": null, "e": 2435, "s": 2404, "text": "j:-The column to be extracted." }, { "code": null, "e": 2477, "s": 2435, "text": "Returns: A vector of the provided column." }, { "code": null, "e": 2486, "s": 2477, "text": "Example:" }, { "code": null, "e": 2627, "s": 2486, "text": "In this example, we will be using the method of Subsetting column name to convert the last column of the Excel file in the form of a vector." }, { "code": null, "e": 2656, "s": 2627, "text": "Below is the implementation:" }, { "code": null, "e": 2658, "s": 2656, "text": "R" }, { "code": "library(readxl)gfg_data <- read_excel(\"R/Data_gfg.xlsx\") # Load dplyrlibrary(\"dplyr\") # pull functionv3 <- pull(gfg_data,C) print(v3)", "e": 2830, "s": 2658, "text": null }, { "code": null, "e": 2838, "s": 2830, "text": "Output:" }, { "code": null, "e": 2874, "s": 2838, "text": "[1] 5 2 5 2 2 1 1 8 5 5 8 1 9 7 1 2" }, { "code": null, "e": 2896, "s": 2876, "text": "abhishek0719kadiyan" }, { "code": null, "e": 2903, "s": 2896, "text": "Picked" }, { "code": null, "e": 2911, "s": 2903, "text": "R-Excel" }, { "code": null, "e": 2922, "s": 2911, "text": "R Language" }, { "code": null, "e": 2933, "s": 2922, "text": "R Programs" }, { "code": null, "e": 3031, "s": 2933, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 3089, "s": 3031, "text": "How to Split Column Into Multiple Columns in R DataFrame?" }, { "code": null, "e": 3141, "s": 3089, "text": "Change Color of Bars in Barchart using ggplot2 in R" }, { "code": null, "e": 3176, "s": 3141, "text": "Group by function in R using Dplyr" }, { "code": null, "e": 3214, "s": 3176, "text": "How to Change Axis Scales in R Plots?" }, { "code": null, "e": 3251, "s": 3214, "text": "How to import an Excel File into R ?" }, { "code": null, "e": 3309, "s": 3251, "text": "How to Split Column Into Multiple Columns in R DataFrame?" }, { "code": null, "e": 3358, "s": 3309, "text": "How to filter R DataFrame by values in a column?" }, { "code": null, "e": 3401, "s": 3358, "text": "Replace Specific Characters in String in R" }, { "code": null, "e": 3453, "s": 3401, "text": "Extract First or Last n Characters from String in R" } ]
How to Remove the Last Character From a Table in SQL?
18 Oct, 2021 Here we will see, how to remove the last characters from a table in SQL. We can do this task using the SUBSTRING() function. SUBSTRING(): This function is used to find a part of the given string from the given position. It takes three parameters: String: It is a required parameter. It is the string on which function is to be applied. Start: It gives the starting position of the string. It is also the required parameter. Length: It is an optional parameter. By default, it takes the length of the substring to be returned. Query: SELECT SUBSTRING('HELLO GEEKS', 1, 5); Output: To delete the last character from the field, pass the length parameter to be 1 less than the total length. For the purpose of demonstration let’s create a demo_table in a database named ‘geeks’. Step 1: Creating the Database Use the below SQL statement to create a database called geeks. Query: CREATE DATABASE geeks; Step 2: Using the Database Use the below SQL statement to switch the database context to geeks. Query: USE geeks; Step 3: Table definition We have the following demo_table in our geek’s database. Query: CREATE TABLE demo_table (FIRSTNAME VARCHAR(20), LASTNAME VARCHAR(20), AGE INT); Step 4: Insert data Query: INSERT INTO demo_table VALUES ('Romy', 'Kumari', 22 ), ('Pushkar', 'Jha', 23), ('Meenakshi', 'Jha', 20), ('Shalini', 'Jha', 22), ('Nikhil', 'Kalra', 23), ('Akanksha', 'Gupta', 23); Step 5: View the content Query: SELECT * FROM demo_table; Output: Step 6: Use of SUBSTRING() function We will remove the last character of entries in the LASTNAME column. Syntax: SELECT SUBSTRING(column_name,1,LEN(column_name)-1) FROM table_name; Query: SELECT FIRSTNAME, SUBSTRING(LASTNAME,1,LEN(LASTNAME)-1) AS LASTNAME, AGE FROM demo_table; Output: We can see in the image that the last character from the LASTNAME column is removed now. We will remove the last character of entries in the FIRSTNAME column. Query: SELECT SUBSTRING(FIRSTNAME,1,LEN(FIRSTNAME)-1) AS FIRSTNAME, LASTNAME, AGE FROM demo_table; Output: Picked SQL-Query TrueGeek-2021 SQL TrueGeek SQL Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n18 Oct, 2021" }, { "code": null, "e": 153, "s": 28, "text": "Here we will see, how to remove the last characters from a table in SQL. We can do this task using the SUBSTRING() function." }, { "code": null, "e": 277, "s": 153, "text": "SUBSTRING(): This function is used to find a part of the given string from the given position. It takes three parameters: " }, { "code": null, "e": 366, "s": 277, "text": "String: It is a required parameter. It is the string on which function is to be applied." }, { "code": null, "e": 454, "s": 366, "text": "Start: It gives the starting position of the string. It is also the required parameter." }, { "code": null, "e": 556, "s": 454, "text": "Length: It is an optional parameter. By default, it takes the length of the substring to be returned." }, { "code": null, "e": 563, "s": 556, "text": "Query:" }, { "code": null, "e": 602, "s": 563, "text": "SELECT SUBSTRING('HELLO GEEKS', 1, 5);" }, { "code": null, "e": 610, "s": 602, "text": "Output:" }, { "code": null, "e": 717, "s": 610, "text": "To delete the last character from the field, pass the length parameter to be 1 less than the total length." }, { "code": null, "e": 805, "s": 717, "text": "For the purpose of demonstration let’s create a demo_table in a database named ‘geeks’." }, { "code": null, "e": 835, "s": 805, "text": "Step 1: Creating the Database" }, { "code": null, "e": 898, "s": 835, "text": "Use the below SQL statement to create a database called geeks." }, { "code": null, "e": 905, "s": 898, "text": "Query:" }, { "code": null, "e": 928, "s": 905, "text": "CREATE DATABASE geeks;" }, { "code": null, "e": 955, "s": 928, "text": "Step 2: Using the Database" }, { "code": null, "e": 1024, "s": 955, "text": "Use the below SQL statement to switch the database context to geeks." }, { "code": null, "e": 1031, "s": 1024, "text": "Query:" }, { "code": null, "e": 1042, "s": 1031, "text": "USE geeks;" }, { "code": null, "e": 1067, "s": 1042, "text": "Step 3: Table definition" }, { "code": null, "e": 1124, "s": 1067, "text": "We have the following demo_table in our geek’s database." }, { "code": null, "e": 1131, "s": 1124, "text": "Query:" }, { "code": null, "e": 1212, "s": 1131, "text": " CREATE TABLE demo_table\n(FIRSTNAME VARCHAR(20),\nLASTNAME VARCHAR(20),\nAGE INT);" }, { "code": null, "e": 1232, "s": 1212, "text": "Step 4: Insert data" }, { "code": null, "e": 1239, "s": 1232, "text": "Query:" }, { "code": null, "e": 1422, "s": 1239, "text": "INSERT INTO demo_table VALUES\n('Romy', 'Kumari', 22 ),\n('Pushkar', 'Jha', 23), \n('Meenakshi', 'Jha', 20),\n('Shalini', 'Jha', 22),\n('Nikhil', 'Kalra', 23),\n('Akanksha', 'Gupta', 23);" }, { "code": null, "e": 1447, "s": 1422, "text": "Step 5: View the content" }, { "code": null, "e": 1454, "s": 1447, "text": "Query:" }, { "code": null, "e": 1480, "s": 1454, "text": "SELECT * FROM demo_table;" }, { "code": null, "e": 1488, "s": 1480, "text": "Output:" }, { "code": null, "e": 1524, "s": 1488, "text": "Step 6: Use of SUBSTRING() function" }, { "code": null, "e": 1593, "s": 1524, "text": "We will remove the last character of entries in the LASTNAME column." }, { "code": null, "e": 1601, "s": 1593, "text": "Syntax:" }, { "code": null, "e": 1670, "s": 1601, "text": "SELECT SUBSTRING(column_name,1,LEN(column_name)-1) \nFROM table_name;" }, { "code": null, "e": 1677, "s": 1670, "text": "Query:" }, { "code": null, "e": 1768, "s": 1677, "text": "SELECT FIRSTNAME, SUBSTRING(LASTNAME,1,LEN(LASTNAME)-1)\n AS LASTNAME, AGE FROM demo_table;" }, { "code": null, "e": 1776, "s": 1768, "text": "Output:" }, { "code": null, "e": 1865, "s": 1776, "text": "We can see in the image that the last character from the LASTNAME column is removed now." }, { "code": null, "e": 1935, "s": 1865, "text": "We will remove the last character of entries in the FIRSTNAME column." }, { "code": null, "e": 1942, "s": 1935, "text": "Query:" }, { "code": null, "e": 2035, "s": 1942, "text": "SELECT SUBSTRING(FIRSTNAME,1,LEN(FIRSTNAME)-1)\n AS FIRSTNAME, LASTNAME, AGE FROM demo_table;" }, { "code": null, "e": 2043, "s": 2035, "text": "Output:" }, { "code": null, "e": 2050, "s": 2043, "text": "Picked" }, { "code": null, "e": 2060, "s": 2050, "text": "SQL-Query" }, { "code": null, "e": 2074, "s": 2060, "text": "TrueGeek-2021" }, { "code": null, "e": 2078, "s": 2074, "text": "SQL" }, { "code": null, "e": 2087, "s": 2078, "text": "TrueGeek" }, { "code": null, "e": 2091, "s": 2087, "text": "SQL" } ]
Integrating TinyMCE with Django
05 Sep, 2020 TinyMCE is a online rich text editor which is fully flexible and provides customisation. mostly used to get dynamic data such as articles in GFG and much more, their is no static database for posts Installation – To integrate it with Django web app or website you need to first install its pip library pip install django-tinymce Integrate with Django Project – add tinyMCE as individual app in setting.py INSTALLED_APPS = [ ... 'tinymce', ... ] Also add default configuration for tinyMCE editor in settings.py TINYMCE_DEFAULT_CONFIG = { 'cleanup_on_startup': True, 'custom_undo_redo_levels': 20, 'selector': 'textarea', 'theme': 'silver', 'plugins': ''' textcolor save link image media preview codesample contextmenu table code lists fullscreen insertdatetime nonbreaking contextmenu directionality searchreplace wordcount visualblocks visualchars code fullscreen autolink lists charmap print hr anchor pagebreak ''', 'toolbar1': ''' fullscreen preview bold italic underline | fontselect, fontsizeselect | forecolor backcolor | alignleft alignright | aligncenter alignjustify | indent outdent | bullist numlist table | | link image media | codesample | ''', 'toolbar2': ''' visualblocks visualchars | charmap hr pagebreak nonbreaking anchor | code | ''', 'contextmenu': 'formats | link image', 'menubar': True, 'statusbar': True, } here in configuration dictionary you can customise editor by changing values like theme and many more. setting TinyMCE is done now to bring it into actions we need forms.py file with some required values like needed size of input field it is used by displaying content on html page from django import formsfrom tinymce import TinyMCEfrom .models import _your_model_ class TinyMCEWidget(TinyMCE): def use_required_attribute(self, *args): return False class PostForm(forms.ModelForm): content = forms.CharField( widget=TinyMCEWidget( attrs={'required': False, 'cols': 30, 'rows': 10} ) ) class Meta: model = _your_model_ fields = '__all__' Last step is to add htmlfield to your model you can also use different field check out them on their official website ...from tinymce.models import HTMLField class article(models.Model): ... content = HTMLField() And its all set just make migrations for see changes in admin page by running following commands python manage.py makemigrations python manage.py migrate Now check it in admin area by running server python manage.py runserver Output – here how it will look like it may have different appearance Editor in admin area Python Django Python Web Technologies Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 54, "s": 26, "text": "\n05 Sep, 2020" }, { "code": null, "e": 252, "s": 54, "text": "TinyMCE is a online rich text editor which is fully flexible and provides customisation. mostly used to get dynamic data such as articles in GFG and much more, their is no static database for posts" }, { "code": null, "e": 267, "s": 252, "text": "Installation –" }, { "code": null, "e": 356, "s": 267, "text": "To integrate it with Django web app or website you need to first install its pip library" }, { "code": null, "e": 384, "s": 356, "text": "pip install django-tinymce\n" }, { "code": null, "e": 416, "s": 384, "text": "Integrate with Django Project –" }, { "code": null, "e": 460, "s": 416, "text": "add tinyMCE as individual app in setting.py" }, { "code": null, "e": 516, "s": 460, "text": "INSTALLED_APPS = [\n ...\n 'tinymce',\n ... \n]\n" }, { "code": null, "e": 581, "s": 516, "text": "Also add default configuration for tinyMCE editor in settings.py" }, { "code": null, "e": 1620, "s": 581, "text": "TINYMCE_DEFAULT_CONFIG = {\n 'cleanup_on_startup': True,\n 'custom_undo_redo_levels': 20,\n 'selector': 'textarea',\n 'theme': 'silver',\n 'plugins': '''\n textcolor save link image media preview codesample contextmenu\n table code lists fullscreen insertdatetime nonbreaking\n contextmenu directionality searchreplace wordcount visualblocks\n visualchars code fullscreen autolink lists charmap print hr\n anchor pagebreak\n ''',\n 'toolbar1': '''\n fullscreen preview bold italic underline | fontselect,\n fontsizeselect | forecolor backcolor | alignleft alignright |\n aligncenter alignjustify | indent outdent | bullist numlist table |\n | link image media | codesample |\n ''',\n 'toolbar2': '''\n visualblocks visualchars |\n charmap hr pagebreak nonbreaking anchor | code |\n ''',\n 'contextmenu': 'formats | link image',\n 'menubar': True,\n 'statusbar': True,\n}\n\n\n" }, { "code": null, "e": 1723, "s": 1620, "text": "here in configuration dictionary you can customise editor by changing values like theme and many more." }, { "code": null, "e": 1902, "s": 1723, "text": "setting TinyMCE is done now to bring it into actions we need forms.py file with some required values like needed size of input field it is used by displaying content on html page" }, { "code": "from django import formsfrom tinymce import TinyMCEfrom .models import _your_model_ class TinyMCEWidget(TinyMCE): def use_required_attribute(self, *args): return False class PostForm(forms.ModelForm): content = forms.CharField( widget=TinyMCEWidget( attrs={'required': False, 'cols': 30, 'rows': 10} ) ) class Meta: model = _your_model_ fields = '__all__'", "e": 2322, "s": 1902, "text": null }, { "code": null, "e": 2440, "s": 2322, "text": "Last step is to add htmlfield to your model you can also use different field check out them on their official website" }, { "code": "...from tinymce.models import HTMLField class article(models.Model): ... content = HTMLField()", "e": 2546, "s": 2440, "text": null }, { "code": null, "e": 2643, "s": 2546, "text": "And its all set just make migrations for see changes in admin page by running following commands" }, { "code": null, "e": 2676, "s": 2643, "text": "python manage.py makemigrations\n" }, { "code": null, "e": 2701, "s": 2676, "text": "python manage.py migrate" }, { "code": null, "e": 2747, "s": 2701, "text": "Now check it in admin area by running server " }, { "code": null, "e": 2775, "s": 2747, "text": "python manage.py runserver\n" }, { "code": null, "e": 2784, "s": 2775, "text": "Output –" }, { "code": null, "e": 2845, "s": 2784, "text": "here how it will look like it may have different appearance " }, { "code": null, "e": 2866, "s": 2845, "text": "Editor in admin area" }, { "code": null, "e": 2880, "s": 2866, "text": "Python Django" }, { "code": null, "e": 2887, "s": 2880, "text": "Python" }, { "code": null, "e": 2904, "s": 2887, "text": "Web Technologies" } ]
Find N distinct numbers whose Bitwise XOR is equal to K
24 Feb, 2022 Given two positive integers N and X, the task is to construct N positive integers having Bitwise XOR of all these integers equal to K. Examples: Input: N = 4, K = 6Output: 1 0 2 5Explanation: Bitwise XOR the integers {1, 0, 2, 5} = 1 XOR 0 XOR 2 XOR 5 = 6(= K). Input: N = 1, K = 1Output: 1 Approach: The idea to solve this problem is to include the first (N – 3) natural numbers and calculate their Bitwise XOR and select the remaining 3 integers based on the calculated XOR values. Follow the steps below to solve the problem: If N = 1: Print the integer K itself. If N = 2: Print K and 0 as the required output. Otherwise, consider the first (N – 3) natural numbers. Now, calculate Bitwise XOR of (N – 3) elements and store it in a variable, say val. The remaining three elements can be selected based on the following conditions: Case 1: If val is equal to K, perform the following steps:In this case, the Bitwise XOR of the remaining three elements needs to be equal to zero to make Bitwise XOR of all integers equal to K.Therefore, the remaining three elements must be P, Q, P XOR Q, thus making their Bitwise XOR equal to 0. But P XOR Q must be greater than N-2(i.e. P) so that all the numbers should remain distinct. ( In case, if you are wondering P XOR Q should also not be equal to Q, well this is not possible since the value of P will never be zero.Case (i): P XOR Q is already greater than P :The remaining three elements will be P, Q, P XOR Q.Case (ii): P XOR Q is not greater than P :Here, we will use the while loop with condition P XOR Q <= P with increment on Q by 1. After the termination of the loop, the remaining three elements will be P, Q, P XOR Q.Case 2: If val is not equal to K, perform the following steps:In this case, Bitwise XOR of the remaining three elements together with Bitwise XOR of the first (N – 3) elements needs to be equal to K.By considering the last 3 elements to be equal to 0, P, P XOR K XOR val, Bitwise XOR of these three elements is equal to K XOR val. Again, P XOR K XOR val must be greater than N-2 for all the N numbers to be distinct.Case (i): P XOR K XOR val is already greater than N-2 :The remaining three elements will be 0, P, P XOR K XOR val.Case (ii): P XOR K XOR val is not greater than N-2:Here, we will use the while loop with condition P XOR K XOR val <= N-2 with increment on P by 1. After the termination of loop, the remaining three elements will be 0, P, P XOR K XOR val. Case 1: If val is equal to K, perform the following steps:In this case, the Bitwise XOR of the remaining three elements needs to be equal to zero to make Bitwise XOR of all integers equal to K.Therefore, the remaining three elements must be P, Q, P XOR Q, thus making their Bitwise XOR equal to 0. But P XOR Q must be greater than N-2(i.e. P) so that all the numbers should remain distinct. ( In case, if you are wondering P XOR Q should also not be equal to Q, well this is not possible since the value of P will never be zero.Case (i): P XOR Q is already greater than P :The remaining three elements will be P, Q, P XOR Q.Case (ii): P XOR Q is not greater than P :Here, we will use the while loop with condition P XOR Q <= P with increment on Q by 1. After the termination of the loop, the remaining three elements will be P, Q, P XOR Q. In this case, the Bitwise XOR of the remaining three elements needs to be equal to zero to make Bitwise XOR of all integers equal to K. Therefore, the remaining three elements must be P, Q, P XOR Q, thus making their Bitwise XOR equal to 0. But P XOR Q must be greater than N-2(i.e. P) so that all the numbers should remain distinct. ( In case, if you are wondering P XOR Q should also not be equal to Q, well this is not possible since the value of P will never be zero. Case (i): P XOR Q is already greater than P :The remaining three elements will be P, Q, P XOR Q. The remaining three elements will be P, Q, P XOR Q. Case (ii): P XOR Q is not greater than P :Here, we will use the while loop with condition P XOR Q <= P with increment on Q by 1. After the termination of the loop, the remaining three elements will be P, Q, P XOR Q. Here, we will use the while loop with condition P XOR Q <= P with increment on Q by 1. After the termination of the loop, the remaining three elements will be P, Q, P XOR Q. Case 2: If val is not equal to K, perform the following steps:In this case, Bitwise XOR of the remaining three elements together with Bitwise XOR of the first (N – 3) elements needs to be equal to K.By considering the last 3 elements to be equal to 0, P, P XOR K XOR val, Bitwise XOR of these three elements is equal to K XOR val. Again, P XOR K XOR val must be greater than N-2 for all the N numbers to be distinct.Case (i): P XOR K XOR val is already greater than N-2 :The remaining three elements will be 0, P, P XOR K XOR val.Case (ii): P XOR K XOR val is not greater than N-2:Here, we will use the while loop with condition P XOR K XOR val <= N-2 with increment on P by 1. After the termination of loop, the remaining three elements will be 0, P, P XOR K XOR val. In this case, Bitwise XOR of the remaining three elements together with Bitwise XOR of the first (N – 3) elements needs to be equal to K. By considering the last 3 elements to be equal to 0, P, P XOR K XOR val, Bitwise XOR of these three elements is equal to K XOR val. Again, P XOR K XOR val must be greater than N-2 for all the N numbers to be distinct. Case (i): P XOR K XOR val is already greater than N-2 :The remaining three elements will be 0, P, P XOR K XOR val. The remaining three elements will be 0, P, P XOR K XOR val. Case (ii): P XOR K XOR val is not greater than N-2:Here, we will use the while loop with condition P XOR K XOR val <= N-2 with increment on P by 1. After the termination of loop, the remaining three elements will be 0, P, P XOR K XOR val. Here, we will use the while loop with condition P XOR K XOR val <= N-2 with increment on P by 1. After the termination of loop, the remaining three elements will be 0, P, P XOR K XOR val. Choosing P and Q: For both cases, the value of P and Q requires to be distinct from the first (N – 3) elements. Therefore, consider P and Q to be (N – 2) and (N – 1). In case you are wondering that while loops may be stuck for too long, is not true. You will generally get the number in the range of 100 iterations. So on average, the time complexity of both the while loops mentioned in cases 1 and 2 is almost constant. Below is the implementation of the above solution: C++ C Java Python3 C# Javascript // C++ program for the above approach#include <bits/stdc++.h>using namespace std; // Function to find N integers// having Bitwise XOR equal to Kvoid findArray(int N, int K){ // Base Cases if (N == 1) { cout << " " << K; return; } if (N == 2) { cout << 0 << " " << K; return; } // Assign values to P and Q int P = N - 2; int Q = N - 1; // Stores Bitwise XOR of the // first (N - 3) elements int VAL = 0; // Print the first N - 3 elements for(int i = 1; i <= (N - 3); i++) { cout << " " << i; // Calculate Bitwise XOR of // first (N - 3) elements VAL ^= i; } if (VAL == K) { // checking whether P ^ Q is greater than P or not. while( (P ^ Q) <= P) { Q++; } cout << " " << P << " " << Q << " " << (P ^ Q); } else { // checking whether P ^ K ^ VAL is greater than N-2 or not. while( (P ^ K ^ VAL) <= N-3) { P++; } cout << " " << 0 << " " << P << " " << (P ^ K ^ VAL); }} // Driver Codeint main(){ int N = 4, X = 6; // Function Call findArray(N, X); return 0;} // This code is contributed by shivanisinghss2110 // C program for the above approach#include <stdio.h> // Function to find N integers// having Bitwise XOR equal to Kvoid findArray(int N, int K){ // Base Cases if (N == 1) { printf("%d", K); return; } if (N == 2) { printf("%d %d", 0, K); return; } // Assign values to P and Q int P = N - 2; int Q = N - 1; // Stores Bitwise XOR of the // first (N - 3) elements int VAL = 0; // Print the first N - 3 elements for (int i = 1; i <= (N - 3); i++) { printf("%d ", i); // Calculate Bitwise XOR of // first (N - 3) elements VAL ^= i; } if (VAL == K) { // checking whether P ^ Q is greater than P or not. while( (P ^ Q) <= P) { Q++; } printf("%d %d %d", P, Q, P ^ Q); } else { // checking whether P ^ K ^ VAL is greater than N-2 or not. while( (P ^ K ^ VAL) <= N-2) { P++; } printf("%d %d %d", 0, P, P ^ K ^ VAL); }} // Driver Codeint main(){ int N = 4, X = 6; // Function Call findArray(N, X); return 0;} // Java program for the above approachimport java.util.*; class GFG{ // Function to find N integers// having Bitwise XOR equal to Kstatic void findArray(int N, int K){ // Base Cases if (N == 1) { System.out.print(K + " "); return; } if (N == 2) { System.out.print(0 + " " + K); return; } // Assign values to P and Q int P = N - 2; int Q = N - 1; // Stores Bitwise XOR of the // first (N - 3) elements int VAL = 0; // Print the first N - 3 elements for(int i = 1; i <= (N - 3); i++) { System.out.print(i + " "); // Calculate Bitwise XOR of // first (N - 3) elements VAL ^= i; } if (VAL == K) { // checking whether P ^ Q is greater than P or not. while( (P ^ Q) <= P) { Q++; } System.out.print(P + " " + Q + " " + (P ^ Q)); } else { // checking whether P ^ K ^ VAL is greater than N-2 or not. while( (P ^ K ^ VAL) <= N-2) { P++; } System.out.print(0 + " " + P + " " + (P ^ K ^ VAL)); }} // Driver Codepublic static void main(String[] args){ int N = 4, X = 6; // Function Call findArray(N, X);}} // This code is contributed by susmitakundugoaldanga # Python3 program for the above approach # Function to find N integers# having Bitwise XOR equal to Kdef findArray(N, K): # Base Cases if (N == 1): print(K, end=" ") return if (N == 2): print("0", end=" ") print(K, end=" ") return # Assign values to P and Q P = N - 2 Q = N - 1 # Stores Bitwise XOR of the # first (N - 3) elements VAL = 0 # Print the first N - 3 elements for i in range(1, N - 2): print(i, end=" ") # Calculate Bitwise XOR of # first (N - 3) elements VAL ^= i if (VAL == K): # checking whether P ^ Q is greater than P or not. while ((P ^ Q) <= P): Q = Q + 1 print(P, end=" ") print(Q, end=" ") print(P ^ Q, end=" ") else: # checking whether P ^ K ^ VAL is greater than N-2 or not. while ((P ^ K ^ VAL) <= N - 2): P = P + 1 print("0", end=" ") print(P, end=" ") print(P ^ K ^ VAL, end=" ") # Driver CodeN = 4X = 6 # Function CallfindArray(N, X) # This code is contributed by sanjoy_62 // C# program for the above approachusing System; class GFG{ // Function to find N integers// having Bitwise XOR equal to Kstatic void findArray(int N, int K){ // Base Cases if (N == 1) { Console.Write(K + " "); return; } if (N == 2) { Console.Write(0 + " " + K); return; } // Assign values to P and Q int P = N - 2; int Q = N - 1; // Stores Bitwise XOR of the // first (N - 3) elements int VAL = 0; // Print the first N - 3 elements for (int i = 1; i <= (N - 3); i++) { Console.Write(i + " "); // Calculate Bitwise XOR of // first (N - 3) elements VAL ^= i; } if (VAL == K) { // checking whether P ^ Q is greater than P or not. while( (P ^ Q) <= P) { Q++; } Console.Write(P + " " + Q + " " + (P ^ Q)); } else { // checking whether P ^ K ^ VAL is greater than N-2 or not. while( (P ^ K ^ VAL) <= N-2) { P++; } Console.Write(0 + " " + P + " " + (P ^ K ^ VAL)); }} // Driver Codepublic static void Main(){ int N = 4, X = 6; // Function Call findArray(N, X);}} // This code is contributed by code_hunt. <script> // Javascript program for the above approach // Function to find N integers// having Bitwise XOR equal to Kfunction findArray(N, K){ // Base Cases if (N == 1) { document.write(K + " "); return; } if (N == 2) { document.write(0 + " " + K); return; } // Assign values to P and Q let P = N - 2; let Q = N - 1; // Stores Bitwise XOR of the // first (N - 3) elements let VAL = 0; // Print the first N - 3 elements for(let i = 1; i <= (N - 3); i++) { document.write(i + " "); // Calculate Bitwise XOR of // first (N - 3) elements VAL ^= i; } if (VAL == K) { // checking whether P ^ Q is greater than P or not. while( (P ^ Q) <= P) { Q++; } document.write(P + " " + Q + " " + (P ^ Q)); } else { // checking whether P ^ K ^ VAL is greater than N-2 or not. while( (P ^ K ^ VAL) <= N-2) { P++; } document.write(0 + " " + P + " " + (P ^ K ^ VAL)); }} // Driver Code let N = 4, X = 6; // Function Call findArray(N, X); </script> Output: 1 0 2 5 Time Complexity: O(N)Auxiliary Space: O(1) code_hunt susmitakundugoaldanga sanjoy_62 chinmoy1997pal shivanisinghss2110 simranarora5sos kumarbaharatbhavesh864 purnananddubey3701 arorakashish0911 Bitwise-XOR Bit Magic Greedy Mathematical Greedy Mathematical Bit Magic Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 54, "s": 26, "text": "\n24 Feb, 2022" }, { "code": null, "e": 189, "s": 54, "text": "Given two positive integers N and X, the task is to construct N positive integers having Bitwise XOR of all these integers equal to K." }, { "code": null, "e": 199, "s": 189, "text": "Examples:" }, { "code": null, "e": 316, "s": 199, "text": "Input: N = 4, K = 6Output: 1 0 2 5Explanation: Bitwise XOR the integers {1, 0, 2, 5} = 1 XOR 0 XOR 2 XOR 5 = 6(= K)." }, { "code": null, "e": 345, "s": 316, "text": "Input: N = 1, K = 1Output: 1" }, { "code": null, "e": 583, "s": 345, "text": "Approach: The idea to solve this problem is to include the first (N – 3) natural numbers and calculate their Bitwise XOR and select the remaining 3 integers based on the calculated XOR values. Follow the steps below to solve the problem:" }, { "code": null, "e": 621, "s": 583, "text": "If N = 1: Print the integer K itself." }, { "code": null, "e": 669, "s": 621, "text": "If N = 2: Print K and 0 as the required output." }, { "code": null, "e": 724, "s": 669, "text": "Otherwise, consider the first (N – 3) natural numbers." }, { "code": null, "e": 2498, "s": 724, "text": "Now, calculate Bitwise XOR of (N – 3) elements and store it in a variable, say val. The remaining three elements can be selected based on the following conditions: Case 1: If val is equal to K, perform the following steps:In this case, the Bitwise XOR of the remaining three elements needs to be equal to zero to make Bitwise XOR of all integers equal to K.Therefore, the remaining three elements must be P, Q, P XOR Q, thus making their Bitwise XOR equal to 0. But P XOR Q must be greater than N-2(i.e. P) so that all the numbers should remain distinct. ( In case, if you are wondering P XOR Q should also not be equal to Q, well this is not possible since the value of P will never be zero.Case (i): P XOR Q is already greater than P :The remaining three elements will be P, Q, P XOR Q.Case (ii): P XOR Q is not greater than P :Here, we will use the while loop with condition P XOR Q <= P with increment on Q by 1. After the termination of the loop, the remaining three elements will be P, Q, P XOR Q.Case 2: If val is not equal to K, perform the following steps:In this case, Bitwise XOR of the remaining three elements together with Bitwise XOR of the first (N – 3) elements needs to be equal to K.By considering the last 3 elements to be equal to 0, P, P XOR K XOR val, Bitwise XOR of these three elements is equal to K XOR val. Again, P XOR K XOR val must be greater than N-2 for all the N numbers to be distinct.Case (i): P XOR K XOR val is already greater than N-2 :The remaining three elements will be 0, P, P XOR K XOR val.Case (ii): P XOR K XOR val is not greater than N-2:Here, we will use the while loop with condition P XOR K XOR val <= N-2 with increment on P by 1. After the termination of loop, the remaining three elements will be 0, P, P XOR K XOR val." }, { "code": null, "e": 3339, "s": 2498, "text": "Case 1: If val is equal to K, perform the following steps:In this case, the Bitwise XOR of the remaining three elements needs to be equal to zero to make Bitwise XOR of all integers equal to K.Therefore, the remaining three elements must be P, Q, P XOR Q, thus making their Bitwise XOR equal to 0. But P XOR Q must be greater than N-2(i.e. P) so that all the numbers should remain distinct. ( In case, if you are wondering P XOR Q should also not be equal to Q, well this is not possible since the value of P will never be zero.Case (i): P XOR Q is already greater than P :The remaining three elements will be P, Q, P XOR Q.Case (ii): P XOR Q is not greater than P :Here, we will use the while loop with condition P XOR Q <= P with increment on Q by 1. After the termination of the loop, the remaining three elements will be P, Q, P XOR Q." }, { "code": null, "e": 3475, "s": 3339, "text": "In this case, the Bitwise XOR of the remaining three elements needs to be equal to zero to make Bitwise XOR of all integers equal to K." }, { "code": null, "e": 3811, "s": 3475, "text": "Therefore, the remaining three elements must be P, Q, P XOR Q, thus making their Bitwise XOR equal to 0. But P XOR Q must be greater than N-2(i.e. P) so that all the numbers should remain distinct. ( In case, if you are wondering P XOR Q should also not be equal to Q, well this is not possible since the value of P will never be zero." }, { "code": null, "e": 3908, "s": 3811, "text": "Case (i): P XOR Q is already greater than P :The remaining three elements will be P, Q, P XOR Q." }, { "code": null, "e": 3960, "s": 3908, "text": "The remaining three elements will be P, Q, P XOR Q." }, { "code": null, "e": 4177, "s": 3960, "text": "Case (ii): P XOR Q is not greater than P :Here, we will use the while loop with condition P XOR Q <= P with increment on Q by 1. After the termination of the loop, the remaining three elements will be P, Q, P XOR Q." }, { "code": null, "e": 4351, "s": 4177, "text": "Here, we will use the while loop with condition P XOR Q <= P with increment on Q by 1. After the termination of the loop, the remaining three elements will be P, Q, P XOR Q." }, { "code": null, "e": 5121, "s": 4351, "text": "Case 2: If val is not equal to K, perform the following steps:In this case, Bitwise XOR of the remaining three elements together with Bitwise XOR of the first (N – 3) elements needs to be equal to K.By considering the last 3 elements to be equal to 0, P, P XOR K XOR val, Bitwise XOR of these three elements is equal to K XOR val. Again, P XOR K XOR val must be greater than N-2 for all the N numbers to be distinct.Case (i): P XOR K XOR val is already greater than N-2 :The remaining three elements will be 0, P, P XOR K XOR val.Case (ii): P XOR K XOR val is not greater than N-2:Here, we will use the while loop with condition P XOR K XOR val <= N-2 with increment on P by 1. After the termination of loop, the remaining three elements will be 0, P, P XOR K XOR val." }, { "code": null, "e": 5259, "s": 5121, "text": "In this case, Bitwise XOR of the remaining three elements together with Bitwise XOR of the first (N – 3) elements needs to be equal to K." }, { "code": null, "e": 5477, "s": 5259, "text": "By considering the last 3 elements to be equal to 0, P, P XOR K XOR val, Bitwise XOR of these three elements is equal to K XOR val. Again, P XOR K XOR val must be greater than N-2 for all the N numbers to be distinct." }, { "code": null, "e": 5592, "s": 5477, "text": "Case (i): P XOR K XOR val is already greater than N-2 :The remaining three elements will be 0, P, P XOR K XOR val." }, { "code": null, "e": 5652, "s": 5592, "text": "The remaining three elements will be 0, P, P XOR K XOR val." }, { "code": null, "e": 5892, "s": 5652, "text": "Case (ii): P XOR K XOR val is not greater than N-2:Here, we will use the while loop with condition P XOR K XOR val <= N-2 with increment on P by 1. After the termination of loop, the remaining three elements will be 0, P, P XOR K XOR val." }, { "code": null, "e": 6081, "s": 5892, "text": "Here, we will use the while loop with condition P XOR K XOR val <= N-2 with increment on P by 1. After the termination of loop, the remaining three elements will be 0, P, P XOR K XOR val." }, { "code": null, "e": 6248, "s": 6081, "text": "Choosing P and Q: For both cases, the value of P and Q requires to be distinct from the first (N – 3) elements. Therefore, consider P and Q to be (N – 2) and (N – 1)." }, { "code": null, "e": 6503, "s": 6248, "text": "In case you are wondering that while loops may be stuck for too long, is not true. You will generally get the number in the range of 100 iterations. So on average, the time complexity of both the while loops mentioned in cases 1 and 2 is almost constant." }, { "code": null, "e": 6554, "s": 6503, "text": "Below is the implementation of the above solution:" }, { "code": null, "e": 6558, "s": 6554, "text": "C++" }, { "code": null, "e": 6560, "s": 6558, "text": "C" }, { "code": null, "e": 6565, "s": 6560, "text": "Java" }, { "code": null, "e": 6573, "s": 6565, "text": "Python3" }, { "code": null, "e": 6576, "s": 6573, "text": "C#" }, { "code": null, "e": 6587, "s": 6576, "text": "Javascript" }, { "code": "// C++ program for the above approach#include <bits/stdc++.h>using namespace std; // Function to find N integers// having Bitwise XOR equal to Kvoid findArray(int N, int K){ // Base Cases if (N == 1) { cout << \" \" << K; return; } if (N == 2) { cout << 0 << \" \" << K; return; } // Assign values to P and Q int P = N - 2; int Q = N - 1; // Stores Bitwise XOR of the // first (N - 3) elements int VAL = 0; // Print the first N - 3 elements for(int i = 1; i <= (N - 3); i++) { cout << \" \" << i; // Calculate Bitwise XOR of // first (N - 3) elements VAL ^= i; } if (VAL == K) { // checking whether P ^ Q is greater than P or not. while( (P ^ Q) <= P) { Q++; } cout << \" \" << P << \" \" << Q << \" \" << (P ^ Q); } else { // checking whether P ^ K ^ VAL is greater than N-2 or not. while( (P ^ K ^ VAL) <= N-3) { P++; } cout << \" \" << 0 << \" \" << P << \" \" << (P ^ K ^ VAL); }} // Driver Codeint main(){ int N = 4, X = 6; // Function Call findArray(N, X); return 0;} // This code is contributed by shivanisinghss2110", "e": 7839, "s": 6587, "text": null }, { "code": "// C program for the above approach#include <stdio.h> // Function to find N integers// having Bitwise XOR equal to Kvoid findArray(int N, int K){ // Base Cases if (N == 1) { printf(\"%d\", K); return; } if (N == 2) { printf(\"%d %d\", 0, K); return; } // Assign values to P and Q int P = N - 2; int Q = N - 1; // Stores Bitwise XOR of the // first (N - 3) elements int VAL = 0; // Print the first N - 3 elements for (int i = 1; i <= (N - 3); i++) { printf(\"%d \", i); // Calculate Bitwise XOR of // first (N - 3) elements VAL ^= i; } if (VAL == K) { // checking whether P ^ Q is greater than P or not. while( (P ^ Q) <= P) { Q++; } printf(\"%d %d %d\", P, Q, P ^ Q); } else { // checking whether P ^ K ^ VAL is greater than N-2 or not. while( (P ^ K ^ VAL) <= N-2) { P++; } printf(\"%d %d %d\", 0, P, P ^ K ^ VAL); }} // Driver Codeint main(){ int N = 4, X = 6; // Function Call findArray(N, X); return 0;}", "e": 8969, "s": 7839, "text": null }, { "code": "// Java program for the above approachimport java.util.*; class GFG{ // Function to find N integers// having Bitwise XOR equal to Kstatic void findArray(int N, int K){ // Base Cases if (N == 1) { System.out.print(K + \" \"); return; } if (N == 2) { System.out.print(0 + \" \" + K); return; } // Assign values to P and Q int P = N - 2; int Q = N - 1; // Stores Bitwise XOR of the // first (N - 3) elements int VAL = 0; // Print the first N - 3 elements for(int i = 1; i <= (N - 3); i++) { System.out.print(i + \" \"); // Calculate Bitwise XOR of // first (N - 3) elements VAL ^= i; } if (VAL == K) { // checking whether P ^ Q is greater than P or not. while( (P ^ Q) <= P) { Q++; } System.out.print(P + \" \" + Q + \" \" + (P ^ Q)); } else { // checking whether P ^ K ^ VAL is greater than N-2 or not. while( (P ^ K ^ VAL) <= N-2) { P++; } System.out.print(0 + \" \" + P + \" \" + (P ^ K ^ VAL)); }} // Driver Codepublic static void main(String[] args){ int N = 4, X = 6; // Function Call findArray(N, X);}} // This code is contributed by susmitakundugoaldanga", "e": 10338, "s": 8969, "text": null }, { "code": "# Python3 program for the above approach # Function to find N integers# having Bitwise XOR equal to Kdef findArray(N, K): # Base Cases if (N == 1): print(K, end=\" \") return if (N == 2): print(\"0\", end=\" \") print(K, end=\" \") return # Assign values to P and Q P = N - 2 Q = N - 1 # Stores Bitwise XOR of the # first (N - 3) elements VAL = 0 # Print the first N - 3 elements for i in range(1, N - 2): print(i, end=\" \") # Calculate Bitwise XOR of # first (N - 3) elements VAL ^= i if (VAL == K): # checking whether P ^ Q is greater than P or not. while ((P ^ Q) <= P): Q = Q + 1 print(P, end=\" \") print(Q, end=\" \") print(P ^ Q, end=\" \") else: # checking whether P ^ K ^ VAL is greater than N-2 or not. while ((P ^ K ^ VAL) <= N - 2): P = P + 1 print(\"0\", end=\" \") print(P, end=\" \") print(P ^ K ^ VAL, end=\" \") # Driver CodeN = 4X = 6 # Function CallfindArray(N, X) # This code is contributed by sanjoy_62", "e": 11438, "s": 10338, "text": null }, { "code": "// C# program for the above approachusing System; class GFG{ // Function to find N integers// having Bitwise XOR equal to Kstatic void findArray(int N, int K){ // Base Cases if (N == 1) { Console.Write(K + \" \"); return; } if (N == 2) { Console.Write(0 + \" \" + K); return; } // Assign values to P and Q int P = N - 2; int Q = N - 1; // Stores Bitwise XOR of the // first (N - 3) elements int VAL = 0; // Print the first N - 3 elements for (int i = 1; i <= (N - 3); i++) { Console.Write(i + \" \"); // Calculate Bitwise XOR of // first (N - 3) elements VAL ^= i; } if (VAL == K) { // checking whether P ^ Q is greater than P or not. while( (P ^ Q) <= P) { Q++; } Console.Write(P + \" \" + Q + \" \" + (P ^ Q)); } else { // checking whether P ^ K ^ VAL is greater than N-2 or not. while( (P ^ K ^ VAL) <= N-2) { P++; } Console.Write(0 + \" \" + P + \" \" + (P ^ K ^ VAL)); }} // Driver Codepublic static void Main(){ int N = 4, X = 6; // Function Call findArray(N, X);}} // This code is contributed by code_hunt.", "e": 12672, "s": 11438, "text": null }, { "code": "<script> // Javascript program for the above approach // Function to find N integers// having Bitwise XOR equal to Kfunction findArray(N, K){ // Base Cases if (N == 1) { document.write(K + \" \"); return; } if (N == 2) { document.write(0 + \" \" + K); return; } // Assign values to P and Q let P = N - 2; let Q = N - 1; // Stores Bitwise XOR of the // first (N - 3) elements let VAL = 0; // Print the first N - 3 elements for(let i = 1; i <= (N - 3); i++) { document.write(i + \" \"); // Calculate Bitwise XOR of // first (N - 3) elements VAL ^= i; } if (VAL == K) { // checking whether P ^ Q is greater than P or not. while( (P ^ Q) <= P) { Q++; } document.write(P + \" \" + Q + \" \" + (P ^ Q)); } else { // checking whether P ^ K ^ VAL is greater than N-2 or not. while( (P ^ K ^ VAL) <= N-2) { P++; } document.write(0 + \" \" + P + \" \" + (P ^ K ^ VAL)); }} // Driver Code let N = 4, X = 6; // Function Call findArray(N, X); </script>", "e": 13931, "s": 12672, "text": null }, { "code": null, "e": 13939, "s": 13931, "text": "Output:" }, { "code": null, "e": 13947, "s": 13939, "text": "1 0 2 5" }, { "code": null, "e": 13990, "s": 13947, "text": "Time Complexity: O(N)Auxiliary Space: O(1)" }, { "code": null, "e": 14000, "s": 13990, "text": "code_hunt" }, { "code": null, "e": 14022, "s": 14000, "text": "susmitakundugoaldanga" }, { "code": null, "e": 14032, "s": 14022, "text": "sanjoy_62" }, { "code": null, "e": 14047, "s": 14032, "text": "chinmoy1997pal" }, { "code": null, "e": 14066, "s": 14047, "text": "shivanisinghss2110" }, { "code": null, "e": 14082, "s": 14066, "text": "simranarora5sos" }, { "code": null, "e": 14105, "s": 14082, "text": "kumarbaharatbhavesh864" }, { "code": null, "e": 14124, "s": 14105, "text": "purnananddubey3701" }, { "code": null, "e": 14141, "s": 14124, "text": "arorakashish0911" }, { "code": null, "e": 14153, "s": 14141, "text": "Bitwise-XOR" }, { "code": null, "e": 14163, "s": 14153, "text": "Bit Magic" }, { "code": null, "e": 14170, "s": 14163, "text": "Greedy" }, { "code": null, "e": 14183, "s": 14170, "text": "Mathematical" }, { "code": null, "e": 14190, "s": 14183, "text": "Greedy" }, { "code": null, "e": 14203, "s": 14190, "text": "Mathematical" }, { "code": null, "e": 14213, "s": 14203, "text": "Bit Magic" } ]
Stack vs Heap Memory Allocation
13 Jun, 2022 Memory in a C/C++/Java program can either be allocated on a stack or a heap.Prerequisite: Memory layout of C program. Stack Allocation: The allocation happens on contiguous blocks of memory. We call it a stack memory allocation because the allocation happens in the function call stack. The size of memory to be allocated is known to the compiler and whenever a function is called, its variables get memory allocated on the stack. And whenever the function call is over, the memory for the variables is de-allocated. This all happens using some predefined routines in the compiler. A programmer does not have to worry about memory allocation and de-allocation of stack variables. This kind of memory allocation also known as Temporary memory allocation because as soon as the method finishes its execution all the data belongs to that method flushes out from the stack automatically. Means, any value stored in the stack memory scheme is accessible as long as the method hasn’t completed its execution and currently in running state. Key Points: It’s a temporary memory allocation scheme where the data members are accessible only if the method( ) that contained them is currently is running. It allocates or de-allocates the memory automatically as soon as the corresponding method completes its execution. We receive the corresponding error Java. lang. StackOverFlowError by JVM, If the stack memory is filled completely. Stack memory allocation is considered safer as compared to heap memory allocation because the data stored can only be access by owner thread. Memory allocation and de-allocation is faster as compared to Heap-memory allocation. Stack-memory has less storage space as compared to Heap-memory. CPP int main(){ // All these variables get memory // allocated on stack int a; int b[10]; int n = 20; int c[n];} Heap Allocation: The memory is allocated during the execution of instructions written by programmers. Note that the name heap has nothing to do with the heap data structure. It is called heap because it is a pile of memory space available to programmers to allocated and de-allocate. Every time when we made an object it always creates in Heap-space and the referencing information to these objects are always stored in Stack-memory. Heap memory allocation isn’t as safe as Stack memory allocation was because the data stored in this space is accessible or visible to all threads. If a programmer does not handle this memory well, a memory leak can happen in the program. The Heap-memory allocation is further divided into three categories:- These three categories help us to prioritize the data(Objects) to be stored in the Heap-memory or in the Garbage collection. Young Generation – It’s the portion of the memory where all the new data(objects) are made to allocate the space and whenever this memory is completely filled then the rest of the data is stored in Garbage collection. Old or Tenured Generation – This is the part of Heap-memory that contains the older data objects that are not in frequent use or not in use at all are placed. Permanent Generation – This is the portion of Heap-memory that contains the JVM’s metadata for the runtime classes and application methods. Key Points: We receive the corresponding error message if Heap-space is entirely full, java. lang.OutOfMemoryError by JVM. This memory allocation scheme is different from the Stack-space allocation, here no automatic de-allocation feature is provided. We need to use a Garbage collector to remove the old unused objects in order to use the memory efficiently. The processing time(Accessing time) of this memory is quite slow as compared to Stack-memory. Heap-memory is also not threaded-safe as Stack-memory because data stored in Heap-memory are visible to all threads. Size of Heap-memory is quite larger as compared to the Stack-memory. Heap-memory is accessible or exists as long as the whole application(or java program) runs. CPP int main(){ // This memory for 10 integers // is allocated on heap. int *ptr = new int[10];} Intermixed example of both kind of memory allocation Heap and Stack in java: Java class Emp { int id; String emp_name; public Emp(int id, String emp_name) { this.id = id; this.emp_name = emp_name; }} public class Emp_detail { private static Emp Emp_detail(int id, String emp_name) { return new Emp(id, emp_name); } public static void main(String[] args) { int id = 21; String name = "Maddy"; Emp person_ = null; person_ = Emp_detail(id, emp_name); }} Following are the conclusions on which we’ll make after analyzing the above example: As we start execution of the have program, all the run-time classes are stored in the Heap-memory space. Then we find the main() method in the next line which is stored into the stack along with all it’s primitive(or local) and the reference variable Emp of type Emp_detail will also be stored in the Stack and will point out to the corresponding object stored in Heap memory. Then the next line will call to the parameterized constructor Emp(int, String) from main( ) and it’ll also allocate to the top of the same stack memory block. This will store:The object reference of the invoked object of the stack memory.The primitive value(primitive data type) int id in the stack memory.The reference variable of String emp_name argument which will point to the actual string from string pool into the heap memory. The object reference of the invoked object of the stack memory. The primitive value(primitive data type) int id in the stack memory. The reference variable of String emp_name argument which will point to the actual string from string pool into the heap memory. Then the main method will again call to the Emp_detail() static method, for which allocation will be made in stack memory block on top of the previous memory block. So, for the newly created object Emp of type Emp_detail and all instance variables will be stored in heap memory. Pictorial representation as shown in the Figure.1 below: Fig.1 Key Differences Between Stack and Heap Allocations In a stack, the allocation and de-allocation are automatically done by the compiler whereas in heap, it needs to be done by the programmer manually.Handling of Heap frame is costlier than the handling of the stack frame.Memory shortage problem is more likely to happen in stack whereas the main issue in heap memory is fragmentation.Stack frame access is easier than the heap frame as the stack have a small region of memory and is cache-friendly, but in case of heap frames which are dispersed throughout the memory so it causes more cache misses.A stack is not flexible, the memory size allotted cannot be changed whereas a heap is flexible, and the allotted memory can be altered.Accessing time of heap takes is more than a stack. In a stack, the allocation and de-allocation are automatically done by the compiler whereas in heap, it needs to be done by the programmer manually. Handling of Heap frame is costlier than the handling of the stack frame. Memory shortage problem is more likely to happen in stack whereas the main issue in heap memory is fragmentation. Stack frame access is easier than the heap frame as the stack have a small region of memory and is cache-friendly, but in case of heap frames which are dispersed throughout the memory so it causes more cache misses. A stack is not flexible, the memory size allotted cannot be changed whereas a heap is flexible, and the allotted memory can be altered. Accessing time of heap takes is more than a stack. Comparison Chart ShubhamKatta ashushrma378 madhav_mohan SagarPawar shubhamsharma8337 nehasagar144 dev6251 priyansh70890 system-programming Technical Scripter 2018 Difference Between Technical Scripter Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 52, "s": 24, "text": "\n13 Jun, 2022" }, { "code": null, "e": 170, "s": 52, "text": "Memory in a C/C++/Java program can either be allocated on a stack or a heap.Prerequisite: Memory layout of C program." }, { "code": null, "e": 1086, "s": 170, "text": "Stack Allocation: The allocation happens on contiguous blocks of memory. We call it a stack memory allocation because the allocation happens in the function call stack. The size of memory to be allocated is known to the compiler and whenever a function is called, its variables get memory allocated on the stack. And whenever the function call is over, the memory for the variables is de-allocated. This all happens using some predefined routines in the compiler. A programmer does not have to worry about memory allocation and de-allocation of stack variables. This kind of memory allocation also known as Temporary memory allocation because as soon as the method finishes its execution all the data belongs to that method flushes out from the stack automatically. Means, any value stored in the stack memory scheme is accessible as long as the method hasn’t completed its execution and currently in running state." }, { "code": null, "e": 1098, "s": 1086, "text": "Key Points:" }, { "code": null, "e": 1245, "s": 1098, "text": "It’s a temporary memory allocation scheme where the data members are accessible only if the method( ) that contained them is currently is running." }, { "code": null, "e": 1360, "s": 1245, "text": "It allocates or de-allocates the memory automatically as soon as the corresponding method completes its execution." }, { "code": null, "e": 1476, "s": 1360, "text": "We receive the corresponding error Java. lang. StackOverFlowError by JVM, If the stack memory is filled completely." }, { "code": null, "e": 1618, "s": 1476, "text": "Stack memory allocation is considered safer as compared to heap memory allocation because the data stored can only be access by owner thread." }, { "code": null, "e": 1703, "s": 1618, "text": "Memory allocation and de-allocation is faster as compared to Heap-memory allocation." }, { "code": null, "e": 1767, "s": 1703, "text": "Stack-memory has less storage space as compared to Heap-memory." }, { "code": null, "e": 1771, "s": 1767, "text": "CPP" }, { "code": "int main(){ // All these variables get memory // allocated on stack int a; int b[10]; int n = 20; int c[n];}", "e": 1892, "s": 1771, "text": null }, { "code": null, "e": 2564, "s": 1892, "text": "Heap Allocation: The memory is allocated during the execution of instructions written by programmers. Note that the name heap has nothing to do with the heap data structure. It is called heap because it is a pile of memory space available to programmers to allocated and de-allocate. Every time when we made an object it always creates in Heap-space and the referencing information to these objects are always stored in Stack-memory. Heap memory allocation isn’t as safe as Stack memory allocation was because the data stored in this space is accessible or visible to all threads. If a programmer does not handle this memory well, a memory leak can happen in the program." }, { "code": null, "e": 2759, "s": 2564, "text": "The Heap-memory allocation is further divided into three categories:- These three categories help us to prioritize the data(Objects) to be stored in the Heap-memory or in the Garbage collection." }, { "code": null, "e": 2977, "s": 2759, "text": "Young Generation – It’s the portion of the memory where all the new data(objects) are made to allocate the space and whenever this memory is completely filled then the rest of the data is stored in Garbage collection." }, { "code": null, "e": 3136, "s": 2977, "text": "Old or Tenured Generation – This is the part of Heap-memory that contains the older data objects that are not in frequent use or not in use at all are placed." }, { "code": null, "e": 3276, "s": 3136, "text": "Permanent Generation – This is the portion of Heap-memory that contains the JVM’s metadata for the runtime classes and application methods." }, { "code": null, "e": 3288, "s": 3276, "text": "Key Points:" }, { "code": null, "e": 3400, "s": 3288, "text": "We receive the corresponding error message if Heap-space is entirely full, java. lang.OutOfMemoryError by JVM." }, { "code": null, "e": 3637, "s": 3400, "text": "This memory allocation scheme is different from the Stack-space allocation, here no automatic de-allocation feature is provided. We need to use a Garbage collector to remove the old unused objects in order to use the memory efficiently." }, { "code": null, "e": 3731, "s": 3637, "text": "The processing time(Accessing time) of this memory is quite slow as compared to Stack-memory." }, { "code": null, "e": 3848, "s": 3731, "text": "Heap-memory is also not threaded-safe as Stack-memory because data stored in Heap-memory are visible to all threads." }, { "code": null, "e": 3917, "s": 3848, "text": "Size of Heap-memory is quite larger as compared to the Stack-memory." }, { "code": null, "e": 4009, "s": 3917, "text": "Heap-memory is accessible or exists as long as the whole application(or java program) runs." }, { "code": null, "e": 4013, "s": 4009, "text": "CPP" }, { "code": "int main(){ // This memory for 10 integers // is allocated on heap. int *ptr = new int[10];}", "e": 4113, "s": 4013, "text": null }, { "code": null, "e": 4190, "s": 4113, "text": "Intermixed example of both kind of memory allocation Heap and Stack in java:" }, { "code": null, "e": 4195, "s": 4190, "text": "Java" }, { "code": "class Emp { int id; String emp_name; public Emp(int id, String emp_name) { this.id = id; this.emp_name = emp_name; }} public class Emp_detail { private static Emp Emp_detail(int id, String emp_name) { return new Emp(id, emp_name); } public static void main(String[] args) { int id = 21; String name = \"Maddy\"; Emp person_ = null; person_ = Emp_detail(id, emp_name); }}", "e": 4639, "s": 4195, "text": null }, { "code": null, "e": 4724, "s": 4639, "text": "Following are the conclusions on which we’ll make after analyzing the above example:" }, { "code": null, "e": 4829, "s": 4724, "text": "As we start execution of the have program, all the run-time classes are stored in the Heap-memory space." }, { "code": null, "e": 5101, "s": 4829, "text": "Then we find the main() method in the next line which is stored into the stack along with all it’s primitive(or local) and the reference variable Emp of type Emp_detail will also be stored in the Stack and will point out to the corresponding object stored in Heap memory." }, { "code": null, "e": 5535, "s": 5101, "text": "Then the next line will call to the parameterized constructor Emp(int, String) from main( ) and it’ll also allocate to the top of the same stack memory block. This will store:The object reference of the invoked object of the stack memory.The primitive value(primitive data type) int id in the stack memory.The reference variable of String emp_name argument which will point to the actual string from string pool into the heap memory." }, { "code": null, "e": 5599, "s": 5535, "text": "The object reference of the invoked object of the stack memory." }, { "code": null, "e": 5668, "s": 5599, "text": "The primitive value(primitive data type) int id in the stack memory." }, { "code": null, "e": 5796, "s": 5668, "text": "The reference variable of String emp_name argument which will point to the actual string from string pool into the heap memory." }, { "code": null, "e": 5961, "s": 5796, "text": "Then the main method will again call to the Emp_detail() static method, for which allocation will be made in stack memory block on top of the previous memory block." }, { "code": null, "e": 6075, "s": 5961, "text": "So, for the newly created object Emp of type Emp_detail and all instance variables will be stored in heap memory." }, { "code": null, "e": 6132, "s": 6075, "text": "Pictorial representation as shown in the Figure.1 below:" }, { "code": null, "e": 6138, "s": 6132, "text": "Fig.1" }, { "code": null, "e": 6191, "s": 6138, "text": "Key Differences Between Stack and Heap Allocations " }, { "code": null, "e": 6925, "s": 6191, "text": "In a stack, the allocation and de-allocation are automatically done by the compiler whereas in heap, it needs to be done by the programmer manually.Handling of Heap frame is costlier than the handling of the stack frame.Memory shortage problem is more likely to happen in stack whereas the main issue in heap memory is fragmentation.Stack frame access is easier than the heap frame as the stack have a small region of memory and is cache-friendly, but in case of heap frames which are dispersed throughout the memory so it causes more cache misses.A stack is not flexible, the memory size allotted cannot be changed whereas a heap is flexible, and the allotted memory can be altered.Accessing time of heap takes is more than a stack." }, { "code": null, "e": 7074, "s": 6925, "text": "In a stack, the allocation and de-allocation are automatically done by the compiler whereas in heap, it needs to be done by the programmer manually." }, { "code": null, "e": 7147, "s": 7074, "text": "Handling of Heap frame is costlier than the handling of the stack frame." }, { "code": null, "e": 7261, "s": 7147, "text": "Memory shortage problem is more likely to happen in stack whereas the main issue in heap memory is fragmentation." }, { "code": null, "e": 7477, "s": 7261, "text": "Stack frame access is easier than the heap frame as the stack have a small region of memory and is cache-friendly, but in case of heap frames which are dispersed throughout the memory so it causes more cache misses." }, { "code": null, "e": 7613, "s": 7477, "text": "A stack is not flexible, the memory size allotted cannot be changed whereas a heap is flexible, and the allotted memory can be altered." }, { "code": null, "e": 7664, "s": 7613, "text": "Accessing time of heap takes is more than a stack." }, { "code": null, "e": 7681, "s": 7664, "text": "Comparison Chart" }, { "code": null, "e": 7694, "s": 7681, "text": "ShubhamKatta" }, { "code": null, "e": 7707, "s": 7694, "text": "ashushrma378" }, { "code": null, "e": 7720, "s": 7707, "text": "madhav_mohan" }, { "code": null, "e": 7731, "s": 7720, "text": "SagarPawar" }, { "code": null, "e": 7749, "s": 7731, "text": "shubhamsharma8337" }, { "code": null, "e": 7762, "s": 7749, "text": "nehasagar144" }, { "code": null, "e": 7770, "s": 7762, "text": "dev6251" }, { "code": null, "e": 7784, "s": 7770, "text": "priyansh70890" }, { "code": null, "e": 7803, "s": 7784, "text": "system-programming" }, { "code": null, "e": 7827, "s": 7803, "text": "Technical Scripter 2018" }, { "code": null, "e": 7846, "s": 7827, "text": "Difference Between" }, { "code": null, "e": 7865, "s": 7846, "text": "Technical Scripter" } ]
Python | os.path.size() method
22 May, 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 submodule of OS module in Python used for common path name manipulation. os.path.getsize() method in Python is used to check the size of specified path. It returns the size of specified path in bytes. The method raise OSError if the file does not exist or is somehow inaccessible. Syntax: os.path.getsize(path) Parameter:path: A path-like object representing a file system path. A path-like object is either a string or bytes object representing a path. Return Type: This method returns a integer value which represents the size of specified path in bytes. Code #1: Use of os.path.getsize() method # Python program to explain os.path.getsize() method # importing os module import os # Pathpath = '/home/User/Desktop/file.txt' # Get the size (in bytes)# of specified path size = os.path.getsize(path) # Print the size (in bytes)# of specified path print("Size (In bytes) of '%s':" %path, size) Size (In bytes) of '/home/User/Desktop/file.txt': 243 Code #2: Handling error while using os.path.getsize() method # Python program to explain os.path.getsize() method # importing os module import os # Pathpath = '/home/User/Desktop/file2.txt' # Get the size (in bytes)# of specified path try : size = os.path.getsize(path) except OSError : print("Path '%s' does not exists or is inaccessible" %path) sys.exit() # Print the size (in bytes)# of specified path print("Size (In bytes) of '% s':" % path, size) Path '/home/User/Desktop/file2.txt' does not exists or is inaccessible Reference: https://docs.python.org/3/library/os.path.html python-os-module Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n22 May, 2019" }, { "code": null, "e": 338, "s": 28, "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 submodule of OS module in Python used for common path name manipulation." }, { "code": null, "e": 546, "s": 338, "text": "os.path.getsize() method in Python is used to check the size of specified path. It returns the size of specified path in bytes. The method raise OSError if the file does not exist or is somehow inaccessible." }, { "code": null, "e": 576, "s": 546, "text": "Syntax: os.path.getsize(path)" }, { "code": null, "e": 719, "s": 576, "text": "Parameter:path: A path-like object representing a file system path. A path-like object is either a string or bytes object representing a path." }, { "code": null, "e": 822, "s": 719, "text": "Return Type: This method returns a integer value which represents the size of specified path in bytes." }, { "code": null, "e": 863, "s": 822, "text": "Code #1: Use of os.path.getsize() method" }, { "code": "# Python program to explain os.path.getsize() method # importing os module import os # Pathpath = '/home/User/Desktop/file.txt' # Get the size (in bytes)# of specified path size = os.path.getsize(path) # Print the size (in bytes)# of specified path print(\"Size (In bytes) of '%s':\" %path, size)", "e": 1167, "s": 863, "text": null }, { "code": null, "e": 1222, "s": 1167, "text": "Size (In bytes) of '/home/User/Desktop/file.txt': 243\n" }, { "code": null, "e": 1283, "s": 1222, "text": "Code #2: Handling error while using os.path.getsize() method" }, { "code": "# Python program to explain os.path.getsize() method # importing os module import os # Pathpath = '/home/User/Desktop/file2.txt' # Get the size (in bytes)# of specified path try : size = os.path.getsize(path) except OSError : print(\"Path '%s' does not exists or is inaccessible\" %path) sys.exit() # Print the size (in bytes)# of specified path print(\"Size (In bytes) of '% s':\" % path, size)", "e": 1692, "s": 1283, "text": null }, { "code": null, "e": 1764, "s": 1692, "text": "Path '/home/User/Desktop/file2.txt' does not exists or is inaccessible\n" }, { "code": null, "e": 1822, "s": 1764, "text": "Reference: https://docs.python.org/3/library/os.path.html" }, { "code": null, "e": 1839, "s": 1822, "text": "python-os-module" }, { "code": null, "e": 1846, "s": 1839, "text": "Python" } ]
Given a sorted dictionary of an alien language, find order of characters
23 Jun, 2022 Given a sorted dictionary (array of words) of an alien language, find order of characters in the language. Examples: Input: words[] = {"baa", "abcd", "abca", "cab", "cad"} Output: Order of characters is 'b', 'd', 'a', 'c' Note that words are sorted and in the given language "baa" comes before "abcd", therefore 'b' is before 'a' in output. Similarly we can find other orders. Input: words[] = {"caa", "aaa", "aab"} Output: Order of characters is 'c', 'a', 'b' Approach 1: The idea is to create a graph of characters and then find topological sorting of the created graph. Following are the detailed steps.1) Create a graph g with number of vertices equal to the size of alphabet in the given alien language. For example, if the alphabet size is 5, then there can be 5 characters in words. Initially there are no edges in graph.2) Do following for every pair of adjacent words in given sorted array. .....a) Let the current pair of words be word1 and word2. One by one compare characters of both words and find the first mismatching characters. .....b) Create an edge in g from mismatching character of word1 to that of word2.3) Print topological sorting of the above created graph. The implementation of the above is in C++. Time Complexity: The first step to create a graph takes O(n + alpha) time where n is number of given words and alpha is number of characters in given alphabet. The second step is also topological sorting. Note that there would be alpha vertices and at-most (n-1) edges in the graph. The time complexity of topological sorting is O(V+E) which is O(n + alpha) here. So overall time complexity is O(n + alpha) + O(n + alpha) which is O(n + alpha). Exercise: The above code doesn’t work when the input is not valid. For example {“aba”, “bba”, “aaa”} is not valid, because from first two words, we can deduce ‘a’ should appear before ‘b’, but from last two words, we can deduce ‘b’ should appear before ‘a’ which is not possible. Extend the above program to handle invalid inputs and generate the output as “Not valid”. Approach 2: [Works for invalid input data] We have implemented this approach in C#. Algorithm: (1) Compare 2 adjacent words at a time (i.e, word1 with word2, word2 with word3, ... , word(startIndex) and word(startIndex + 1) (2) Then we compare one character at a time for the 2 words selected. (2a) If both characters are different, we stop the comparison here and conclude that the character from word(startIndex) comes before the other. (2b) If both characters are the same, we continue to compare until (2a) occurs or if either of the words has been exhausted. (3) We continue to compare each word in this fashion until we have compared all words. Once we find a character set in (2a) we pass them to class ‘AlienCharacters’ which takes care of the overall ordering of the characters. The idea is to maintain the ordering of the characters in a linked list (DNode). To optimize the insertion time into the linked list, a map (C# Dictionary) is used as an indexing entity, thus, bringing down the complexity to O(1). This is an improvement from the previous algorithm where topological sort was used for the purpose. Boundary conditions: 1. The startIndex must be within range 2. When comparing 2 words, if we exhaust on one i.e, the length of both words is different. Compare only until either one exhausts. Complexity Analysis: The method-wise time complexities have been mentioned in the code below (C#) for better understanding. If ‘N’ is the number of words in the input alien vocabulary/dictionary, ‘L’ length of the max length word, and ‘C’ is the final number of unique characters, Time Complexity: O(N * L) Space Complexity: O(C) C++ Java C# Javascript // A C++ program to order of characters in an alien language#include<bits/stdc++.h>using namespace std; // Class to represent a graphclass Graph{ int V; // No. of vertices' // Pointer to an array containing adjacency listsList list<int> *adj; // A function used by topologicalSort void topologicalSortUtil(int v, bool visited[], stack<int> &Stack);public: Graph(int V); // Constructor // function to add an edge to graph void addEdge(int v, int w); // prints a Topological Sort of the complete graph void topologicalSort();}; Graph::Graph(int V){ this->V = V; adj = new list<int>[V];} void Graph::addEdge(int v, int w){ adj[v].push_back(w); // Add w to v’s list.} // A recursive function used by topologicalSortvoid Graph::topologicalSortUtil(int v, bool visited[], stack<int> &Stack){ // Mark the current node as visited. visited[v] = true; // Recur for all the vertices adjacent to this vertex list<int>::iterator i; for (i = adj[v].begin(); i != adj[v].end(); ++i) if (!visited[*i]) topologicalSortUtil(*i, visited, Stack); // Push current vertex to stack which stores result Stack.push(v);} // The function to do Topological Sort. It uses recursive topologicalSortUtil()void Graph::topologicalSort(){ stack<int> Stack; // Mark all the vertices as not visited bool *visited = new bool[V]; for (int i = 0; i < V; i++) visited[i] = false; // Call the recursive helper function to store Topological Sort // starting from all vertices one by one for (int i = 0; i < V; i++) if (visited[i] == false) topologicalSortUtil(i, visited, Stack); // Print contents of stack while (Stack.empty() == false) { cout << (char) ('a' + Stack.top()) << " "; Stack.pop(); }} int min(int x, int y){ return (x < y)? x : y;} // This function finds and prints order of character from a sorted// array of words. n is size of words[]. alpha is set of possible// alphabets.// For simplicity, this function is written in a way that only// first 'alpha' characters can be there in words array. For// example if alpha is 7, then words[] should have only 'a', 'b',// 'c' 'd', 'e', 'f', 'g'void printOrder(string words[], int n, int alpha){ // Create a graph with 'alpha' edges Graph g(alpha); // Process all adjacent pairs of words and create a graph for (int i = 0; i < n-1; i++) { // Take the current two words and find the first mismatching // character string word1 = words[i], word2 = words[i+1]; for (int j = 0; j < min(word1.length(), word2.length()); j++) { // If we find a mismatching character, then add an edge // from character of word1 to that of word2 if (word1[j] != word2[j]) { g.addEdge(word1[j]-'a', word2[j]-'a'); break; } } } // Print topological sort of the above created graph g.topologicalSort();} // Driver program to test above functionsint main(){ string words[] = {"caa", "aaa", "aab"}; printOrder(words, 3, 3); return 0;} // A Java program to order of// characters in an alien languageimport java.util.*; // Class to represent a graphclass Graph { // An array representing the graph as an adjacency list private final LinkedList<Integer>[] adjacencyList; Graph(int nVertices) { adjacencyList = new LinkedList[nVertices]; for (int vertexIndex = 0; vertexIndex < nVertices; vertexIndex++) { adjacencyList[vertexIndex] = new LinkedList<>(); } } // function to add an edge to graph void addEdge(int startVertex, int endVertex) { adjacencyList[startVertex].add(endVertex); } private int getNoOfVertices() { return adjacencyList.length; } // A recursive function used by topologicalSort private void topologicalSortUtil(int currentVertex, boolean[] visited, Stack<Integer> stack) { // Mark the current node as visited. visited[currentVertex] = true; // Recur for all the vertices adjacent to this // vertex for (int adjacentVertex : adjacencyList[currentVertex]) { if (!visited[adjacentVertex]) { topologicalSortUtil(adjacentVertex, visited, stack); } } // Push current vertex to stack which stores result stack.push(currentVertex); } // prints a Topological Sort of the complete graph void topologicalSort() { Stack<Integer> stack = new Stack<>(); // Mark all the vertices as not visited boolean[] visited = new boolean[getNoOfVertices()]; for (int i = 0; i < getNoOfVertices(); i++) { visited[i] = false; } // Call the recursive helper function to store // Topological Sort starting from all vertices one // by one for (int i = 0; i < getNoOfVertices(); i++) { if (!visited[i]) { topologicalSortUtil(i, visited, stack); } } // Print contents of stack while (!stack.isEmpty()) { System.out.print((char)('a' + stack.pop()) + " "); } }} public class OrderOfCharacters { // This function finds and prints order // of character from a sorted array of words. // alpha is number of possible alphabets // starting from 'a'. For simplicity, this // function is written in a way that only // first 'alpha' characters can be there // in words array. For example if alpha // is 7, then words[] should contain words // having only 'a', 'b','c' 'd', 'e', 'f', 'g' private static void printOrder(String[] words, int n, int alpha) { // Create a graph with 'alpha' edges Graph graph = new Graph(alpha); for (int i = 0; i < n - 1; i++) { // Take the current two words and find the first // mismatching character String word1 = words[i]; String word2 = words[i + 1]; for (int j = 0; j < Math.min(word1.length(), word2.length()); j++) { // If we find a mismatching character, then // add an edge from character of word1 to // that of word2 if (word1.charAt(j) != word2.charAt(j)) { graph.addEdge(word1.charAt(j) - 'a', word2.charAt(j) - 'a'); break; } } } // Print topological sort of the above created graph graph.topologicalSort(); } // Driver program to test above functions public static void main(String[] args) { String[] words = { "caa", "aaa", "aab" }; printOrder(words, 3, 3); }} // Contributed by Harikrishnan Rajan using System;using System.Collections.Generic;using System.Linq; namespace AlienDictionary{ public class DNode { public string Char; public DNode prev = null; public DNode next = null; public DNode(string character) => Char = character; } public class AlienCharacters { public AlienCharacters(int k) => MaxChars = k; private int MaxChars; private DNode head = null; private Dictionary<string, DNode> index = new Dictionary<string, DNode>(); // As we use Dictionary for indexing, the time complexity for inserting // characters in order will take O(1) // Time: O(1) // Space: O(c), where 'c' is the unique character count. public bool UpdateCharacterOrdering(string predChar, string succChar) { DNode pNode = null, sNode = null; bool isSNodeNew = false, isPNodeNew = false; if(!index.TryGetValue(predChar, out pNode)) { pNode = new DNode(predChar); index[predChar] = pNode; isPNodeNew = true; } if (!index.TryGetValue(succChar, out sNode)) { sNode = new DNode(succChar); index[succChar] = sNode; isSNodeNew = true; } // before ordering is formed, validate if both the nodes are already present if (!isSNodeNew && !isPNodeNew) { if (!Validate(predChar, succChar)) return false; } else if ((isPNodeNew && !isSNodeNew) || (isPNodeNew && isSNodeNew)) InsertNodeBefore(ref pNode, ref sNode); else InsertNodeAfter(ref pNode, ref sNode); if (pNode.prev == null) head = pNode; return true; } // Time: O(1) private void InsertNodeAfter(ref DNode pNode, ref DNode sNode) { sNode.next = pNode?.next; if (pNode.next != null) pNode.next.prev = sNode; pNode.next = sNode; sNode.prev = pNode; } // Time: O(1) private void InsertNodeBefore(ref DNode pNode, ref DNode sNode) { // insert pnode before snode pNode.prev = sNode?.prev; if (sNode.prev != null) sNode.prev.next = pNode; sNode.prev = pNode; pNode.next = sNode; } // Time: O(1) private bool Validate(string predChar, string succChar) { // this is the first level of validation // validate if predChar node actually occurs before succCharNode. DNode sNode = index[succChar]; while(sNode != null) { if (sNode.Char != predChar) sNode = sNode.prev; else return true; // validation successful } // if we have reached the end and not found the predChar before succChar // something is not right! return false; } // Time: O(c), where 'c' is the unique character count. public override string ToString() { string res = ""; int count = 0; DNode currNode = head; while(currNode != null) { res += currNode.Char + " "; count++; currNode = currNode.next; } // second level of validation if (count != MaxChars) // something went wrong! res = "ERROR!!! Input words not enough to find all k unique characters."; return res; } } class Program { static int k = 4; static AlienCharacters alienCharacters = new AlienCharacters(k); static List<string> vocabulary = new List<string>(); static void Main(string[] args) { vocabulary.Add("baa"); vocabulary.Add("abcd"); vocabulary.Add("abca"); vocabulary.Add("cab"); vocabulary.Add("cad"); ProcessVocabulary(0); Console.WriteLine(alienCharacters.ToString()); Console.ReadLine(); } // Time: O(vocabulary.Count + max(word.Length)) static void ProcessVocabulary(int startIndex) { if (startIndex >= vocabulary.Count - 1) return; var res = GetPredSuccChar(vocabulary.ElementAt(startIndex), vocabulary.ElementAt(startIndex + 1)); if (res != null) { if (!alienCharacters.UpdateCharacterOrdering(res.Item1, res.Item2)) { Console.WriteLine("ERROR!!! Invalid input data, the words maybe in wrong order"); return; } } ProcessVocabulary(startIndex + 1); } //Time: O(max(str1.Length, str2.Length) static Tuple<string, string> GetPredSuccChar(string str1, string str2) { Tuple<string, string> result = null; if (str1.Length == 0 || str2.Length == 0) return null; // invalid condition. if(str1[0] != str2[0]) // found an ordering { result = new Tuple<string, string>(str1[0].ToString(), str2[0].ToString()); return result; } string s1 = str1.Substring(1, str1.Length - 1); string s2 = str2.Substring(1, str2.Length - 1); if (s1.Length == 0 || s2.Length == 0) return null; // recursion can stop now. return GetPredSuccChar(s1, s2); } }} // Contributed by Priyanka Pardesi Ramachander <script>// Javascript program to order of characters in an alien language // Class to represent a graphclass Graph{ constructor(V) { this.V = V; this.adj = new Array(V); for(let i = 0; i < V; i++) this.adj[i] = []; } addEdge(v, w) { this.adj[v].push(w); // Add w to v’s list. } // A recursive function used by topologicalSort topologicalSortUtil(v, visited, stack) { // Mark the current node as visited. visited[v] = true; // Recur for all the vertices adjacent to this vertex this.adj[v].forEach(i => { if(!visited[i]) this.topologicalSortUtil(i, visited, stack); }) // Push current vertex to stack which stores result stack.push(v); } // The function to do Topological Sort. It uses recursive topologicalSortUtil() topologicalSort() { let stack = []; // Mark all the vertices as not visited let visited = new Array(this.V); for (let i = 0; i < this.V; i++) visited[i] = false; // Call the recursive helper function to store Topological Sort // starting from all vertices one by one for (let i = 0; i < this.V; i++) { if (visited[i] == false) this.topologicalSortUtil(i, visited, stack); } // Print contents of stack while (stack.length > 0) { let x = stack.pop() + 'a'.charCodeAt(0); document.write(String.fromCharCode(x) + " "); } }} // This function finds and prints order of character from a sorted// array of words. n is size of words[]. alpha is set of possible// alphabets.// For simplicity, this function is written in a way that only// first 'alpha' characters can be there in words array. For// example if alpha is 7, then words[] should have only 'a', 'b',// 'c' 'd', 'e', 'f', 'g'function printOrder(words, n, alpha){ // Create a graph with 'alpha' edges let g = new Graph(alpha); // Process all adjacent pairs of words and create a graph for (let i = 0; i < n-1; i++) { // Take the current two words and find the first mismatching // character word1 = words[i]; word2 = words[i+1]; for (let j = 0; j < Math.min(word1.length, word2.length); j++) { // If we find a mismatching character, then add an edge // from character of word1 to that of word2 if (word1[j] != word2[j]) { g.addEdge(word1.charCodeAt(j) - 'a'.charCodeAt(0), word2.charCodeAt(j) - 'a'.charCodeAt(0)); break; } } } // Print topological sort of the above created graph g.topologicalSort();} // Driver program to test above functionswords = ["caa", "aaa", "aab"];printOrder(words, 3, 3); // This code is contributed by cavi4762</script> Output: c a b This article is contributed by Piyush Gupta (C++), Harikrishnan Rajan (java), and Priyanka Pardesi Ramachander (C#). Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. wangkekekexili dasguptabhargav sumitgumber28 priyankapardesiramachander sagar0719kumar div3yansh saurabh1990aror simranarora5sos cavi4762 Amazon Google Topological Sorting Walmart Graph Sorting Strings Amazon Walmart Google Strings Sorting Graph Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Dijkstra's shortest path algorithm | Greedy Algo-7 Find if there is a path between two vertices in a directed graph Kruskal’s Minimum Spanning Tree Algorithm | Greedy Algo-2 Find if there is a path between two vertices in an undirected graph Detect Cycle in a Directed Graph Merge Sort Bubble Sort Algorithm QuickSort Insertion Sort Selection Sort Algorithm
[ { "code": null, "e": 52, "s": 24, "text": "\n23 Jun, 2022" }, { "code": null, "e": 159, "s": 52, "text": "Given a sorted dictionary (array of words) of an alien language, find order of characters in the language." }, { "code": null, "e": 171, "s": 159, "text": "Examples: " }, { "code": null, "e": 519, "s": 171, "text": "Input: words[] = {\"baa\", \"abcd\", \"abca\", \"cab\", \"cad\"}\nOutput: Order of characters is 'b', 'd', 'a', 'c'\nNote that words are sorted and in the given language \"baa\" \ncomes before \"abcd\", therefore 'b' is before 'a' in output.\nSimilarly we can find other orders.\n\nInput: words[] = {\"caa\", \"aaa\", \"aab\"}\nOutput: Order of characters is 'c', 'a', 'b'" }, { "code": null, "e": 532, "s": 519, "text": "Approach 1: " }, { "code": null, "e": 1242, "s": 532, "text": "The idea is to create a graph of characters and then find topological sorting of the created graph. Following are the detailed steps.1) Create a graph g with number of vertices equal to the size of alphabet in the given alien language. For example, if the alphabet size is 5, then there can be 5 characters in words. Initially there are no edges in graph.2) Do following for every pair of adjacent words in given sorted array. .....a) Let the current pair of words be word1 and word2. One by one compare characters of both words and find the first mismatching characters. .....b) Create an edge in g from mismatching character of word1 to that of word2.3) Print topological sorting of the above created graph." }, { "code": null, "e": 1286, "s": 1242, "text": "The implementation of the above is in C++. " }, { "code": null, "e": 1731, "s": 1286, "text": "Time Complexity: The first step to create a graph takes O(n + alpha) time where n is number of given words and alpha is number of characters in given alphabet. The second step is also topological sorting. Note that there would be alpha vertices and at-most (n-1) edges in the graph. The time complexity of topological sorting is O(V+E) which is O(n + alpha) here. So overall time complexity is O(n + alpha) + O(n + alpha) which is O(n + alpha)." }, { "code": null, "e": 2101, "s": 1731, "text": "Exercise: The above code doesn’t work when the input is not valid. For example {“aba”, “bba”, “aaa”} is not valid, because from first two words, we can deduce ‘a’ should appear before ‘b’, but from last two words, we can deduce ‘b’ should appear before ‘a’ which is not possible. Extend the above program to handle invalid inputs and generate the output as “Not valid”." }, { "code": null, "e": 2144, "s": 2101, "text": "Approach 2: [Works for invalid input data]" }, { "code": null, "e": 2186, "s": 2144, "text": "We have implemented this approach in C#. " }, { "code": null, "e": 2197, "s": 2186, "text": "Algorithm:" }, { "code": null, "e": 2326, "s": 2197, "text": "(1) Compare 2 adjacent words at a time (i.e, word1 with word2, word2 with word3, ... , word(startIndex) and word(startIndex + 1)" }, { "code": null, "e": 2397, "s": 2326, "text": "(2) Then we compare one character at a time for the 2 words selected. " }, { "code": null, "e": 2544, "s": 2397, "text": "(2a) If both characters are different, we stop the comparison here and conclude that the character from word(startIndex) comes before the other. " }, { "code": null, "e": 2670, "s": 2544, "text": "(2b) If both characters are the same, we continue to compare until (2a) occurs or if either of the words has been exhausted. " }, { "code": null, "e": 2758, "s": 2670, "text": "(3) We continue to compare each word in this fashion until we have compared all words. " }, { "code": null, "e": 3227, "s": 2758, "text": "Once we find a character set in (2a) we pass them to class ‘AlienCharacters’ which takes care of the overall ordering of the characters. The idea is to maintain the ordering of the characters in a linked list (DNode). To optimize the insertion time into the linked list, a map (C# Dictionary) is used as an indexing entity, thus, bringing down the complexity to O(1). This is an improvement from the previous algorithm where topological sort was used for the purpose. " }, { "code": null, "e": 3250, "s": 3227, "text": "Boundary conditions: " }, { "code": null, "e": 3289, "s": 3250, "text": "1. The startIndex must be within range" }, { "code": null, "e": 3421, "s": 3289, "text": "2. When comparing 2 words, if we exhaust on one i.e, the length of both words is different. Compare only until either one exhausts." }, { "code": null, "e": 3443, "s": 3421, "text": "Complexity Analysis: " }, { "code": null, "e": 3547, "s": 3443, "text": "The method-wise time complexities have been mentioned in the code below (C#) for better understanding. " }, { "code": null, "e": 3704, "s": 3547, "text": "If ‘N’ is the number of words in the input alien vocabulary/dictionary, ‘L’ length of the max length word, and ‘C’ is the final number of unique characters," }, { "code": null, "e": 3731, "s": 3704, "text": "Time Complexity: O(N * L) " }, { "code": null, "e": 3754, "s": 3731, "text": "Space Complexity: O(C)" }, { "code": null, "e": 3758, "s": 3754, "text": "C++" }, { "code": null, "e": 3763, "s": 3758, "text": "Java" }, { "code": null, "e": 3766, "s": 3763, "text": "C#" }, { "code": null, "e": 3777, "s": 3766, "text": "Javascript" }, { "code": "// A C++ program to order of characters in an alien language#include<bits/stdc++.h>using namespace std; // Class to represent a graphclass Graph{ int V; // No. of vertices' // Pointer to an array containing adjacency listsList list<int> *adj; // A function used by topologicalSort void topologicalSortUtil(int v, bool visited[], stack<int> &Stack);public: Graph(int V); // Constructor // function to add an edge to graph void addEdge(int v, int w); // prints a Topological Sort of the complete graph void topologicalSort();}; Graph::Graph(int V){ this->V = V; adj = new list<int>[V];} void Graph::addEdge(int v, int w){ adj[v].push_back(w); // Add w to v’s list.} // A recursive function used by topologicalSortvoid Graph::topologicalSortUtil(int v, bool visited[], stack<int> &Stack){ // Mark the current node as visited. visited[v] = true; // Recur for all the vertices adjacent to this vertex list<int>::iterator i; for (i = adj[v].begin(); i != adj[v].end(); ++i) if (!visited[*i]) topologicalSortUtil(*i, visited, Stack); // Push current vertex to stack which stores result Stack.push(v);} // The function to do Topological Sort. It uses recursive topologicalSortUtil()void Graph::topologicalSort(){ stack<int> Stack; // Mark all the vertices as not visited bool *visited = new bool[V]; for (int i = 0; i < V; i++) visited[i] = false; // Call the recursive helper function to store Topological Sort // starting from all vertices one by one for (int i = 0; i < V; i++) if (visited[i] == false) topologicalSortUtil(i, visited, Stack); // Print contents of stack while (Stack.empty() == false) { cout << (char) ('a' + Stack.top()) << \" \"; Stack.pop(); }} int min(int x, int y){ return (x < y)? x : y;} // This function finds and prints order of character from a sorted// array of words. n is size of words[]. alpha is set of possible// alphabets.// For simplicity, this function is written in a way that only// first 'alpha' characters can be there in words array. For// example if alpha is 7, then words[] should have only 'a', 'b',// 'c' 'd', 'e', 'f', 'g'void printOrder(string words[], int n, int alpha){ // Create a graph with 'alpha' edges Graph g(alpha); // Process all adjacent pairs of words and create a graph for (int i = 0; i < n-1; i++) { // Take the current two words and find the first mismatching // character string word1 = words[i], word2 = words[i+1]; for (int j = 0; j < min(word1.length(), word2.length()); j++) { // If we find a mismatching character, then add an edge // from character of word1 to that of word2 if (word1[j] != word2[j]) { g.addEdge(word1[j]-'a', word2[j]-'a'); break; } } } // Print topological sort of the above created graph g.topologicalSort();} // Driver program to test above functionsint main(){ string words[] = {\"caa\", \"aaa\", \"aab\"}; printOrder(words, 3, 3); return 0;}", "e": 6929, "s": 3777, "text": null }, { "code": "// A Java program to order of// characters in an alien languageimport java.util.*; // Class to represent a graphclass Graph { // An array representing the graph as an adjacency list private final LinkedList<Integer>[] adjacencyList; Graph(int nVertices) { adjacencyList = new LinkedList[nVertices]; for (int vertexIndex = 0; vertexIndex < nVertices; vertexIndex++) { adjacencyList[vertexIndex] = new LinkedList<>(); } } // function to add an edge to graph void addEdge(int startVertex, int endVertex) { adjacencyList[startVertex].add(endVertex); } private int getNoOfVertices() { return adjacencyList.length; } // A recursive function used by topologicalSort private void topologicalSortUtil(int currentVertex, boolean[] visited, Stack<Integer> stack) { // Mark the current node as visited. visited[currentVertex] = true; // Recur for all the vertices adjacent to this // vertex for (int adjacentVertex : adjacencyList[currentVertex]) { if (!visited[adjacentVertex]) { topologicalSortUtil(adjacentVertex, visited, stack); } } // Push current vertex to stack which stores result stack.push(currentVertex); } // prints a Topological Sort of the complete graph void topologicalSort() { Stack<Integer> stack = new Stack<>(); // Mark all the vertices as not visited boolean[] visited = new boolean[getNoOfVertices()]; for (int i = 0; i < getNoOfVertices(); i++) { visited[i] = false; } // Call the recursive helper function to store // Topological Sort starting from all vertices one // by one for (int i = 0; i < getNoOfVertices(); i++) { if (!visited[i]) { topologicalSortUtil(i, visited, stack); } } // Print contents of stack while (!stack.isEmpty()) { System.out.print((char)('a' + stack.pop()) + \" \"); } }} public class OrderOfCharacters { // This function finds and prints order // of character from a sorted array of words. // alpha is number of possible alphabets // starting from 'a'. For simplicity, this // function is written in a way that only // first 'alpha' characters can be there // in words array. For example if alpha // is 7, then words[] should contain words // having only 'a', 'b','c' 'd', 'e', 'f', 'g' private static void printOrder(String[] words, int n, int alpha) { // Create a graph with 'alpha' edges Graph graph = new Graph(alpha); for (int i = 0; i < n - 1; i++) { // Take the current two words and find the first // mismatching character String word1 = words[i]; String word2 = words[i + 1]; for (int j = 0; j < Math.min(word1.length(), word2.length()); j++) { // If we find a mismatching character, then // add an edge from character of word1 to // that of word2 if (word1.charAt(j) != word2.charAt(j)) { graph.addEdge(word1.charAt(j) - 'a', word2.charAt(j) - 'a'); break; } } } // Print topological sort of the above created graph graph.topologicalSort(); } // Driver program to test above functions public static void main(String[] args) { String[] words = { \"caa\", \"aaa\", \"aab\" }; printOrder(words, 3, 3); }} // Contributed by Harikrishnan Rajan", "e": 10838, "s": 6929, "text": null }, { "code": "using System;using System.Collections.Generic;using System.Linq; namespace AlienDictionary{ public class DNode { public string Char; public DNode prev = null; public DNode next = null; public DNode(string character) => Char = character; } public class AlienCharacters { public AlienCharacters(int k) => MaxChars = k; private int MaxChars; private DNode head = null; private Dictionary<string, DNode> index = new Dictionary<string, DNode>(); // As we use Dictionary for indexing, the time complexity for inserting // characters in order will take O(1) // Time: O(1) // Space: O(c), where 'c' is the unique character count. public bool UpdateCharacterOrdering(string predChar, string succChar) { DNode pNode = null, sNode = null; bool isSNodeNew = false, isPNodeNew = false; if(!index.TryGetValue(predChar, out pNode)) { pNode = new DNode(predChar); index[predChar] = pNode; isPNodeNew = true; } if (!index.TryGetValue(succChar, out sNode)) { sNode = new DNode(succChar); index[succChar] = sNode; isSNodeNew = true; } // before ordering is formed, validate if both the nodes are already present if (!isSNodeNew && !isPNodeNew) { if (!Validate(predChar, succChar)) return false; } else if ((isPNodeNew && !isSNodeNew) || (isPNodeNew && isSNodeNew)) InsertNodeBefore(ref pNode, ref sNode); else InsertNodeAfter(ref pNode, ref sNode); if (pNode.prev == null) head = pNode; return true; } // Time: O(1) private void InsertNodeAfter(ref DNode pNode, ref DNode sNode) { sNode.next = pNode?.next; if (pNode.next != null) pNode.next.prev = sNode; pNode.next = sNode; sNode.prev = pNode; } // Time: O(1) private void InsertNodeBefore(ref DNode pNode, ref DNode sNode) { // insert pnode before snode pNode.prev = sNode?.prev; if (sNode.prev != null) sNode.prev.next = pNode; sNode.prev = pNode; pNode.next = sNode; } // Time: O(1) private bool Validate(string predChar, string succChar) { // this is the first level of validation // validate if predChar node actually occurs before succCharNode. DNode sNode = index[succChar]; while(sNode != null) { if (sNode.Char != predChar) sNode = sNode.prev; else return true; // validation successful } // if we have reached the end and not found the predChar before succChar // something is not right! return false; } // Time: O(c), where 'c' is the unique character count. public override string ToString() { string res = \"\"; int count = 0; DNode currNode = head; while(currNode != null) { res += currNode.Char + \" \"; count++; currNode = currNode.next; } // second level of validation if (count != MaxChars) // something went wrong! res = \"ERROR!!! Input words not enough to find all k unique characters.\"; return res; } } class Program { static int k = 4; static AlienCharacters alienCharacters = new AlienCharacters(k); static List<string> vocabulary = new List<string>(); static void Main(string[] args) { vocabulary.Add(\"baa\"); vocabulary.Add(\"abcd\"); vocabulary.Add(\"abca\"); vocabulary.Add(\"cab\"); vocabulary.Add(\"cad\"); ProcessVocabulary(0); Console.WriteLine(alienCharacters.ToString()); Console.ReadLine(); } // Time: O(vocabulary.Count + max(word.Length)) static void ProcessVocabulary(int startIndex) { if (startIndex >= vocabulary.Count - 1) return; var res = GetPredSuccChar(vocabulary.ElementAt(startIndex), vocabulary.ElementAt(startIndex + 1)); if (res != null) { if (!alienCharacters.UpdateCharacterOrdering(res.Item1, res.Item2)) { Console.WriteLine(\"ERROR!!! Invalid input data, the words maybe in wrong order\"); return; } } ProcessVocabulary(startIndex + 1); } //Time: O(max(str1.Length, str2.Length) static Tuple<string, string> GetPredSuccChar(string str1, string str2) { Tuple<string, string> result = null; if (str1.Length == 0 || str2.Length == 0) return null; // invalid condition. if(str1[0] != str2[0]) // found an ordering { result = new Tuple<string, string>(str1[0].ToString(), str2[0].ToString()); return result; } string s1 = str1.Substring(1, str1.Length - 1); string s2 = str2.Substring(1, str2.Length - 1); if (s1.Length == 0 || s2.Length == 0) return null; // recursion can stop now. return GetPredSuccChar(s1, s2); } }} // Contributed by Priyanka Pardesi Ramachander", "e": 16588, "s": 10838, "text": null }, { "code": "<script>// Javascript program to order of characters in an alien language // Class to represent a graphclass Graph{ constructor(V) { this.V = V; this.adj = new Array(V); for(let i = 0; i < V; i++) this.adj[i] = []; } addEdge(v, w) { this.adj[v].push(w); // Add w to v’s list. } // A recursive function used by topologicalSort topologicalSortUtil(v, visited, stack) { // Mark the current node as visited. visited[v] = true; // Recur for all the vertices adjacent to this vertex this.adj[v].forEach(i => { if(!visited[i]) this.topologicalSortUtil(i, visited, stack); }) // Push current vertex to stack which stores result stack.push(v); } // The function to do Topological Sort. It uses recursive topologicalSortUtil() topologicalSort() { let stack = []; // Mark all the vertices as not visited let visited = new Array(this.V); for (let i = 0; i < this.V; i++) visited[i] = false; // Call the recursive helper function to store Topological Sort // starting from all vertices one by one for (let i = 0; i < this.V; i++) { if (visited[i] == false) this.topologicalSortUtil(i, visited, stack); } // Print contents of stack while (stack.length > 0) { let x = stack.pop() + 'a'.charCodeAt(0); document.write(String.fromCharCode(x) + \" \"); } }} // This function finds and prints order of character from a sorted// array of words. n is size of words[]. alpha is set of possible// alphabets.// For simplicity, this function is written in a way that only// first 'alpha' characters can be there in words array. For// example if alpha is 7, then words[] should have only 'a', 'b',// 'c' 'd', 'e', 'f', 'g'function printOrder(words, n, alpha){ // Create a graph with 'alpha' edges let g = new Graph(alpha); // Process all adjacent pairs of words and create a graph for (let i = 0; i < n-1; i++) { // Take the current two words and find the first mismatching // character word1 = words[i]; word2 = words[i+1]; for (let j = 0; j < Math.min(word1.length, word2.length); j++) { // If we find a mismatching character, then add an edge // from character of word1 to that of word2 if (word1[j] != word2[j]) { g.addEdge(word1.charCodeAt(j) - 'a'.charCodeAt(0), word2.charCodeAt(j) - 'a'.charCodeAt(0)); break; } } } // Print topological sort of the above created graph g.topologicalSort();} // Driver program to test above functionswords = [\"caa\", \"aaa\", \"aab\"];printOrder(words, 3, 3); // This code is contributed by cavi4762</script>", "e": 19478, "s": 16588, "text": null }, { "code": null, "e": 19487, "s": 19478, "text": "Output: " }, { "code": null, "e": 19493, "s": 19487, "text": "c a b" }, { "code": null, "e": 19610, "s": 19493, "text": "This article is contributed by Piyush Gupta (C++), Harikrishnan Rajan (java), and Priyanka Pardesi Ramachander (C#)." }, { "code": null, "e": 19737, "s": 19610, "text": "Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. " }, { "code": null, "e": 19752, "s": 19737, "text": "wangkekekexili" }, { "code": null, "e": 19768, "s": 19752, "text": "dasguptabhargav" }, { "code": null, "e": 19782, "s": 19768, "text": "sumitgumber28" }, { "code": null, "e": 19809, "s": 19782, "text": "priyankapardesiramachander" }, { "code": null, "e": 19824, "s": 19809, "text": "sagar0719kumar" }, { "code": null, "e": 19834, "s": 19824, "text": "div3yansh" }, { "code": null, "e": 19850, "s": 19834, "text": "saurabh1990aror" }, { "code": null, "e": 19866, "s": 19850, "text": "simranarora5sos" }, { "code": null, "e": 19875, "s": 19866, "text": "cavi4762" }, { "code": null, "e": 19882, "s": 19875, "text": "Amazon" }, { "code": null, "e": 19889, "s": 19882, "text": "Google" }, { "code": null, "e": 19909, "s": 19889, "text": "Topological Sorting" }, { "code": null, "e": 19917, "s": 19909, "text": "Walmart" }, { "code": null, "e": 19923, "s": 19917, "text": "Graph" }, { "code": null, "e": 19931, "s": 19923, "text": "Sorting" }, { "code": null, "e": 19939, "s": 19931, "text": "Strings" }, { "code": null, "e": 19946, "s": 19939, "text": "Amazon" }, { "code": null, "e": 19954, "s": 19946, "text": "Walmart" }, { "code": null, "e": 19961, "s": 19954, "text": "Google" }, { "code": null, "e": 19969, "s": 19961, "text": "Strings" }, { "code": null, "e": 19977, "s": 19969, "text": "Sorting" }, { "code": null, "e": 19983, "s": 19977, "text": "Graph" }, { "code": null, "e": 20081, "s": 19983, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 20132, "s": 20081, "text": "Dijkstra's shortest path algorithm | Greedy Algo-7" }, { "code": null, "e": 20197, "s": 20132, "text": "Find if there is a path between two vertices in a directed graph" }, { "code": null, "e": 20255, "s": 20197, "text": "Kruskal’s Minimum Spanning Tree Algorithm | Greedy Algo-2" }, { "code": null, "e": 20323, "s": 20255, "text": "Find if there is a path between two vertices in an undirected graph" }, { "code": null, "e": 20356, "s": 20323, "text": "Detect Cycle in a Directed Graph" }, { "code": null, "e": 20367, "s": 20356, "text": "Merge Sort" }, { "code": null, "e": 20389, "s": 20367, "text": "Bubble Sort Algorithm" }, { "code": null, "e": 20399, "s": 20389, "text": "QuickSort" }, { "code": null, "e": 20414, "s": 20399, "text": "Insertion Sort" } ]
Double doubleValue() method in Java with examples
09 Oct, 2018 The doubleValue() method of Double class is a built in method to return the value specified by the calling object as double after type casting. Syntax: DoubleObject.doubleValue() Return Value: It return the value of DoubleObject as double. Below programs illustrate doubleValue() method in Java: Program 1: // Java code to demonstrate// Double doubleValue() method class GFG { public static void main(String[] args) { // Double value Double a = 17.47; // wrapping the Double value // in the wrapper class Double Double b = new Double(a); // doubleValue of the Double Object double output = b.doubleValue(); // prdoubleing the output System.out.println("Double value of " + b + " is : " + output); }} Double value of 17.47 is : 17.47 Program 2: // Java code to demonstrate// Double doubleValue() method class GFG { public static void main(String[] args) { String value = "54.1"; // wrapping the Double value // in the wrapper class Double Double b = new Double(value); // doubleValue of the Double Object double output = b.doubleValue(); // prdoubleing the output System.out.println("Double value of " + b + " is : " + output); }} Double value of 54.1 is : 54.1 Java-Double Java-Functions Java-lang package Java Java Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 53, "s": 25, "text": "\n09 Oct, 2018" }, { "code": null, "e": 197, "s": 53, "text": "The doubleValue() method of Double class is a built in method to return the value specified by the calling object as double after type casting." }, { "code": null, "e": 205, "s": 197, "text": "Syntax:" }, { "code": null, "e": 232, "s": 205, "text": "DoubleObject.doubleValue()" }, { "code": null, "e": 293, "s": 232, "text": "Return Value: It return the value of DoubleObject as double." }, { "code": null, "e": 349, "s": 293, "text": "Below programs illustrate doubleValue() method in Java:" }, { "code": null, "e": 360, "s": 349, "text": "Program 1:" }, { "code": "// Java code to demonstrate// Double doubleValue() method class GFG { public static void main(String[] args) { // Double value Double a = 17.47; // wrapping the Double value // in the wrapper class Double Double b = new Double(a); // doubleValue of the Double Object double output = b.doubleValue(); // prdoubleing the output System.out.println(\"Double value of \" + b + \" is : \" + output); }}", "e": 860, "s": 360, "text": null }, { "code": null, "e": 894, "s": 860, "text": "Double value of 17.47 is : 17.47\n" }, { "code": null, "e": 905, "s": 894, "text": "Program 2:" }, { "code": "// Java code to demonstrate// Double doubleValue() method class GFG { public static void main(String[] args) { String value = \"54.1\"; // wrapping the Double value // in the wrapper class Double Double b = new Double(value); // doubleValue of the Double Object double output = b.doubleValue(); // prdoubleing the output System.out.println(\"Double value of \" + b + \" is : \" + output); }}", "e": 1391, "s": 905, "text": null }, { "code": null, "e": 1423, "s": 1391, "text": "Double value of 54.1 is : 54.1\n" }, { "code": null, "e": 1435, "s": 1423, "text": "Java-Double" }, { "code": null, "e": 1450, "s": 1435, "text": "Java-Functions" }, { "code": null, "e": 1468, "s": 1450, "text": "Java-lang package" }, { "code": null, "e": 1473, "s": 1468, "text": "Java" }, { "code": null, "e": 1478, "s": 1473, "text": "Java" } ]
Little and Big Endian Mystery
12 Jun, 2022 What are these? Little and big endian are two ways of storing multibyte data-types ( int, float, etc). In little endian machines, last byte of binary representation of the multibyte data-type is stored first. On the other hand, in big endian machines, first byte of binary representation of the multibyte data-type is stored first. Suppose integer is stored as 4 bytes (For those who are using DOS-based compilers such as C++ 3.0, integer is 2 bytes) then a variable x with value 0x01234567 will be stored as following. How to see memory representation of multibyte data types on your machine? Here is a sample C code that shows the byte representation of int, float and pointer. c #include <stdio.h> /* function to show bytes in memory, from location start to start+n*/void show_mem_rep(char *start, int n){ int i; for (i = 0; i < n; i++) printf(" %.2x", start[i]); printf("\n");} /*Main function to call above function for 0x01234567*/int main(){ int i = 0x01234567; show_mem_rep((char *)&i, sizeof(i)); getchar(); return 0;} Time Complexity: O(1) Auxiliary Space: O(1) When above program is run on little endian machine, gives “67 45 23 01” as output, while if it is run on big endian machine, gives “01 23 45 67” as output.Is there a quick way to determine endianness of your machine? There are n no. of ways for determining endianness of your machine. Here is one quick way of doing the same. C++ C #include <bits/stdc++.h>using namespace std;int main(){ unsigned int i = 1; char *c = (char*)&i; if (*c) cout<<"Little endian"; else cout<<"Big endian"; return 0;} // This code is contributed by rathbhupendra #include <stdio.h>int main(){ unsigned int i = 1; char *c = (char*)&i; if (*c) printf("Little endian"); else printf("Big endian"); getchar(); return 0;} Output: Little endian Time Complexity: O(1) Auxiliary Space: O(1) In the above program, a character pointer c is pointing to an integer i. Since size of character is 1 byte when the character pointer is de-referenced it will contain only first byte of integer. If machine is little endian then *c will be 1 (because last byte is stored first) and if the machine is big endian then *c will be 0. Does endianness matter for programmers? Most of the times compiler takes care of endianness, however, endianness becomes an issue in following cases.It matters in network programming: Suppose you write integers to file on a little endian machine and you transfer this file to a big-endian machine. Unless there is little endian to big endian transformation, big endian machine will read the file in reverse order. You can find such a practical example here.Standard byte order for networks is big endian, also known as network byte order. Before transferring data on network, data is first converted to network byte order (big endian). Sometimes it matters when you are using type casting, below program is an example. c #include <stdio.h>int main(){ unsigned char arr[2] = {0x01, 0x00}; unsigned short int x = *(unsigned short int *) arr; printf("%d", x); getchar(); return 0;} Time Complexity: O(1) Auxiliary Space: O(1) In the above program, a char array is typecasted to an unsigned short integer type. When I run above program on little endian machine, I get 1 as output, while if I run it on a big endian machine I get 256. To make programs endianness independent, above programming style should be avoided. What are bi-endians? Bi-endian processors can run in both modes little and big endian.What are the examples of little, big endian and bi-endian machines ? Intel based processors are little endians. ARM processors were little endians. Current generation ARM processors are bi-endian.Motorola 68K processors are big endians. PowerPC (by Motorola) and SPARK (by Sun) processors were big endian. Current version of these processors are bi-endians. Does endianness affects file formats? File formats which have 1 byte as a basic unit are independent of endianness e.g., ASCII files. Other file formats use some fixed endianness format e.g, JPEG files are stored in big endian format. Which one is better — little endian or big endian? The term little and big endian came from Gulliver’s Travels by Jonathan Swift. Two groups could not agree by which end an egg should be opened -a- the little or the big. Just like the egg issue, there is no technological reason to choose one-byte ordering convention over the other, hence the arguments degenerate into bickering about sociopolitical issues. As long as one of the conventions is selected and adhered to consistently, the choice is arbitrary. skbarnwal louisportay rathbhupendra surinderdawra388 rishavmahato348 subham348 ranjanrohit840 Big Endian Endianness Little Endian Articles Bit Magic Bit Magic Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 52, "s": 24, "text": "\n12 Jun, 2022" }, { "code": null, "e": 573, "s": 52, "text": "What are these? Little and big endian are two ways of storing multibyte data-types ( int, float, etc). In little endian machines, last byte of binary representation of the multibyte data-type is stored first. On the other hand, in big endian machines, first byte of binary representation of the multibyte data-type is stored first. Suppose integer is stored as 4 bytes (For those who are using DOS-based compilers such as C++ 3.0, integer is 2 bytes) then a variable x with value 0x01234567 will be stored as following. " }, { "code": null, "e": 737, "s": 575, "text": "How to see memory representation of multibyte data types on your machine? Here is a sample C code that shows the byte representation of int, float and pointer. " }, { "code": null, "e": 739, "s": 737, "text": "c" }, { "code": "#include <stdio.h> /* function to show bytes in memory, from location start to start+n*/void show_mem_rep(char *start, int n){ int i; for (i = 0; i < n; i++) printf(\" %.2x\", start[i]); printf(\"\\n\");} /*Main function to call above function for 0x01234567*/int main(){ int i = 0x01234567; show_mem_rep((char *)&i, sizeof(i)); getchar(); return 0;}", "e": 1110, "s": 739, "text": null }, { "code": null, "e": 1132, "s": 1110, "text": "Time Complexity: O(1)" }, { "code": null, "e": 1154, "s": 1132, "text": "Auxiliary Space: O(1)" }, { "code": null, "e": 1482, "s": 1154, "text": "When above program is run on little endian machine, gives “67 45 23 01” as output, while if it is run on big endian machine, gives “01 23 45 67” as output.Is there a quick way to determine endianness of your machine? There are n no. of ways for determining endianness of your machine. Here is one quick way of doing the same. " }, { "code": null, "e": 1486, "s": 1482, "text": "C++" }, { "code": null, "e": 1488, "s": 1486, "text": "C" }, { "code": "#include <bits/stdc++.h>using namespace std;int main(){ unsigned int i = 1; char *c = (char*)&i; if (*c) cout<<\"Little endian\"; else cout<<\"Big endian\"; return 0;} // This code is contributed by rathbhupendra", "e": 1726, "s": 1488, "text": null }, { "code": "#include <stdio.h>int main(){ unsigned int i = 1; char *c = (char*)&i; if (*c) printf(\"Little endian\"); else printf(\"Big endian\"); getchar(); return 0;}", "e": 1906, "s": 1726, "text": null }, { "code": null, "e": 1916, "s": 1906, "text": "Output: " }, { "code": null, "e": 1930, "s": 1916, "text": "Little endian" }, { "code": null, "e": 1952, "s": 1930, "text": "Time Complexity: O(1)" }, { "code": null, "e": 1974, "s": 1952, "text": "Auxiliary Space: O(1)" }, { "code": null, "e": 3023, "s": 1974, "text": "In the above program, a character pointer c is pointing to an integer i. Since size of character is 1 byte when the character pointer is de-referenced it will contain only first byte of integer. If machine is little endian then *c will be 1 (because last byte is stored first) and if the machine is big endian then *c will be 0. Does endianness matter for programmers? Most of the times compiler takes care of endianness, however, endianness becomes an issue in following cases.It matters in network programming: Suppose you write integers to file on a little endian machine and you transfer this file to a big-endian machine. Unless there is little endian to big endian transformation, big endian machine will read the file in reverse order. You can find such a practical example here.Standard byte order for networks is big endian, also known as network byte order. Before transferring data on network, data is first converted to network byte order (big endian). Sometimes it matters when you are using type casting, below program is an example. " }, { "code": null, "e": 3025, "s": 3023, "text": "c" }, { "code": "#include <stdio.h>int main(){ unsigned char arr[2] = {0x01, 0x00}; unsigned short int x = *(unsigned short int *) arr; printf(\"%d\", x); getchar(); return 0;}", "e": 3198, "s": 3025, "text": null }, { "code": null, "e": 3220, "s": 3198, "text": "Time Complexity: O(1)" }, { "code": null, "e": 3242, "s": 3220, "text": "Auxiliary Space: O(1)" }, { "code": null, "e": 4722, "s": 3242, "text": "In the above program, a char array is typecasted to an unsigned short integer type. When I run above program on little endian machine, I get 1 as output, while if I run it on a big endian machine I get 256. To make programs endianness independent, above programming style should be avoided. What are bi-endians? Bi-endian processors can run in both modes little and big endian.What are the examples of little, big endian and bi-endian machines ? Intel based processors are little endians. ARM processors were little endians. Current generation ARM processors are bi-endian.Motorola 68K processors are big endians. PowerPC (by Motorola) and SPARK (by Sun) processors were big endian. Current version of these processors are bi-endians. Does endianness affects file formats? File formats which have 1 byte as a basic unit are independent of endianness e.g., ASCII files. Other file formats use some fixed endianness format e.g, JPEG files are stored in big endian format. Which one is better — little endian or big endian? The term little and big endian came from Gulliver’s Travels by Jonathan Swift. Two groups could not agree by which end an egg should be opened -a- the little or the big. Just like the egg issue, there is no technological reason to choose one-byte ordering convention over the other, hence the arguments degenerate into bickering about sociopolitical issues. As long as one of the conventions is selected and adhered to consistently, the choice is arbitrary. " }, { "code": null, "e": 4732, "s": 4722, "text": "skbarnwal" }, { "code": null, "e": 4744, "s": 4732, "text": "louisportay" }, { "code": null, "e": 4758, "s": 4744, "text": "rathbhupendra" }, { "code": null, "e": 4775, "s": 4758, "text": "surinderdawra388" }, { "code": null, "e": 4791, "s": 4775, "text": "rishavmahato348" }, { "code": null, "e": 4801, "s": 4791, "text": "subham348" }, { "code": null, "e": 4816, "s": 4801, "text": "ranjanrohit840" }, { "code": null, "e": 4827, "s": 4816, "text": "Big Endian" }, { "code": null, "e": 4838, "s": 4827, "text": "Endianness" }, { "code": null, "e": 4852, "s": 4838, "text": "Little Endian" }, { "code": null, "e": 4861, "s": 4852, "text": "Articles" }, { "code": null, "e": 4871, "s": 4861, "text": "Bit Magic" }, { "code": null, "e": 4881, "s": 4871, "text": "Bit Magic" } ]
Non-Contiguous Allocation in Operating System
13 Jun, 2022 Prerequisite – Variable Partitioning, Fixed Partitioning Paging and Segmentation are the two ways that allow a process’s physical address space to be non-contiguous. It has the advantage of reducing memory wastage but it increases the overheads due to address translation. It slows the execution of the memory because time is consumed in address translation. In non-contiguous allocation, the Operating system needs to maintain the table which is called the Page Table for each process which contains the base address of each block that is acquired by the process in memory space. In non-contiguous memory allocation, different parts of a process are allocated to different places in Main Memory. Spanning is allowed which is not possible in other techniques like Dynamic or Static Contiguous memory allocation. That’s why paging is needed to ensure effective memory allocation. Paging is done to remove External Fragmentation. There are five types of Non-Contiguous Allocation of Memory in the Operating System: PagingMultilevel PagingInverted PagingSegmentationSegmented Paging Paging Multilevel Paging Inverted Paging Segmentation Segmented Paging Working: Here a process can be spanned across different spaces in the main memory in a non-consecutive manner. Suppose process P of size 4KB. Consider main memory has two empty slots each of size 2KB. Hence total free space is, 2*2= 4 KB. In contiguous memory allocation, process P cannot be accommodated as spanning is not allowed. In contiguous allocation, space in memory should be allocated to the whole process. If not, then that space remains unallocated. But in Non-Contiguous allocation, the process can be divided into different parts and hence filling the space in the main memory. In this example, process P can be divided into two parts of equal size – 2KB. Hence one part of process P can be allocated to the first 2KB space of main memory and the other part of the process can be allocated to the second 2KB space of main memory. The below diagram will explain in a better way: But, in what manner we divide a process to allocate them into main memory is very important to understand. The process is divided after analysing the number of empty spaces and their size in the main memory. Then only we do divide our process. It is a very time-consuming process. Their number as well as their sizes changing every time due to execution of already present processes in main memory. In order to avoid this time-consuming process, we divide our process in secondary memory in advance before reaching the main memory for its execution. Every process is divided into various parts of equal size called Pages. We also divide our main memory into different parts of equal size called Frames. It is important to understand that: Size of page in process = Size of frame in memory Although their numbers can be different. Below diagram will make you understand it in a better way: consider empty main memory having a size of each frame is 2 KB, and two processes P1 and P2 are 2 KB each. Resolvent main memory, Concluding, we can say that Paging allows the memory address space of a process to be non-contiguous. Paging is more flexible as only pages of a process are moved. It allows more processes to reside in main memory than Contiguous memory allocation. PulkitJoshi geeky01adarsh GATE CS Operating Systems Operating Systems Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Layers of OSI Model ACID Properties in DBMS TCP/IP Model Normal Forms in DBMS Cache Memory in Computer Organization Cache Memory in Computer Organization LRU Cache Implementation Cd cmd command 'crontab' in Linux with Examples Memory Management in Operating System
[ { "code": null, "e": 54, "s": 26, "text": "\n13 Jun, 2022" }, { "code": null, "e": 414, "s": 54, "text": "Prerequisite – Variable Partitioning, Fixed Partitioning Paging and Segmentation are the two ways that allow a process’s physical address space to be non-contiguous. It has the advantage of reducing memory wastage but it increases the overheads due to address translation. It slows the execution of the memory because time is consumed in address translation. " }, { "code": null, "e": 984, "s": 414, "text": "In non-contiguous allocation, the Operating system needs to maintain the table which is called the Page Table for each process which contains the base address of each block that is acquired by the process in memory space. In non-contiguous memory allocation, different parts of a process are allocated to different places in Main Memory. Spanning is allowed which is not possible in other techniques like Dynamic or Static Contiguous memory allocation. That’s why paging is needed to ensure effective memory allocation. Paging is done to remove External Fragmentation. " }, { "code": null, "e": 1069, "s": 984, "text": "There are five types of Non-Contiguous Allocation of Memory in the Operating System:" }, { "code": null, "e": 1136, "s": 1069, "text": "PagingMultilevel PagingInverted PagingSegmentationSegmented Paging" }, { "code": null, "e": 1143, "s": 1136, "text": "Paging" }, { "code": null, "e": 1161, "s": 1143, "text": "Multilevel Paging" }, { "code": null, "e": 1177, "s": 1161, "text": "Inverted Paging" }, { "code": null, "e": 1190, "s": 1177, "text": "Segmentation" }, { "code": null, "e": 1207, "s": 1190, "text": "Segmented Paging" }, { "code": null, "e": 1541, "s": 1207, "text": "Working: Here a process can be spanned across different spaces in the main memory in a non-consecutive manner. Suppose process P of size 4KB. Consider main memory has two empty slots each of size 2KB. Hence total free space is, 2*2= 4 KB. In contiguous memory allocation, process P cannot be accommodated as spanning is not allowed. " }, { "code": null, "e": 2101, "s": 1541, "text": "In contiguous allocation, space in memory should be allocated to the whole process. If not, then that space remains unallocated. But in Non-Contiguous allocation, the process can be divided into different parts and hence filling the space in the main memory. In this example, process P can be divided into two parts of equal size – 2KB. Hence one part of process P can be allocated to the first 2KB space of main memory and the other part of the process can be allocated to the second 2KB space of main memory. The below diagram will explain in a better way: " }, { "code": null, "e": 2503, "s": 2103, "text": "But, in what manner we divide a process to allocate them into main memory is very important to understand. The process is divided after analysing the number of empty spaces and their size in the main memory. Then only we do divide our process. It is a very time-consuming process. Their number as well as their sizes changing every time due to execution of already present processes in main memory. " }, { "code": null, "e": 2844, "s": 2503, "text": "In order to avoid this time-consuming process, we divide our process in secondary memory in advance before reaching the main memory for its execution. Every process is divided into various parts of equal size called Pages. We also divide our main memory into different parts of equal size called Frames. It is important to understand that: " }, { "code": null, "e": 2898, "s": 2846, "text": "Size of page in process \n= Size of frame in memory " }, { "code": null, "e": 3106, "s": 2898, "text": "Although their numbers can be different. Below diagram will make you understand it in a better way: consider empty main memory having a size of each frame is 2 KB, and two processes P1 and P2 are 2 KB each. " }, { "code": null, "e": 3132, "s": 3108, "text": "Resolvent main memory, " }, { "code": null, "e": 3384, "s": 3134, "text": "Concluding, we can say that Paging allows the memory address space of a process to be non-contiguous. Paging is more flexible as only pages of a process are moved. It allows more processes to reside in main memory than Contiguous memory allocation. " }, { "code": null, "e": 3396, "s": 3384, "text": "PulkitJoshi" }, { "code": null, "e": 3410, "s": 3396, "text": "geeky01adarsh" }, { "code": null, "e": 3418, "s": 3410, "text": "GATE CS" }, { "code": null, "e": 3436, "s": 3418, "text": "Operating Systems" }, { "code": null, "e": 3454, "s": 3436, "text": "Operating Systems" }, { "code": null, "e": 3552, "s": 3454, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 3572, "s": 3552, "text": "Layers of OSI Model" }, { "code": null, "e": 3596, "s": 3572, "text": "ACID Properties in DBMS" }, { "code": null, "e": 3609, "s": 3596, "text": "TCP/IP Model" }, { "code": null, "e": 3630, "s": 3609, "text": "Normal Forms in DBMS" }, { "code": null, "e": 3668, "s": 3630, "text": "Cache Memory in Computer Organization" }, { "code": null, "e": 3706, "s": 3668, "text": "Cache Memory in Computer Organization" }, { "code": null, "e": 3731, "s": 3706, "text": "LRU Cache Implementation" }, { "code": null, "e": 3746, "s": 3731, "text": "Cd cmd command" }, { "code": null, "e": 3779, "s": 3746, "text": "'crontab' in Linux with Examples" } ]
Integer intValue() Method in Java
03 May, 2022 intValue() of Integer class that is present inside java.lang package is an inbuilt method in java that returns the value of this integer as an int which is inherited from Number Class. The package view is as follows: --> java.lang Package --> Integer Class --> intValue() Method Syntax: public int intValue() Return Type: A numeric value that is represented by the object after conversion to the integer type. Note: This method is applicable from java version 1.2 and onwards. Now we will be covering different numbers such as positive, negative, decimal, and even strings. For a positive integer For a negative number For a decimal value and string Case 1: For a positive integer Example: Java // Java Program to Illustrate// the Usage of intValue() method// of Integer class // Importing required class/esimport java.lang.*; // Main classpublic class GFG { // Main driver method public static void main(String[] args) { // Creating object of Integer class inside main() Integer intobject = new Integer(68); // Returns the value of this Integer as an int int i = intobject.intValue(); // Printing the value above stored in integer System.out.println("The integer Value of i = " + i); }} The integer Value of i = 68 Case 2: For a negative number Example: Java // Java program to illustrate the// use of intValue() method of// Integer class of java.lang package // Importing required classesimport java.lang.*; // Main classpublic class GFG { // Main driver method public static void main(String[] args) { // Creating an object of Integer class Integer intobject = new Integer(-76); // Returns the value of this Integer as an int int i = intobject.intValue(); // Printing the integer value above stored on // console System.out.println("The integer Value of i = " + i); }} The integer Value of i = -76 Case 3: For a decimal value and string. Example: Java // Java Program to illustrate// Usage of intValue() method// of Integer class of java.lang package // Importing required classesimport java.lang.*; // Main classclass GFG { // Main driver method public static void main(String[] args) { // Creating an object of Integer class Integer intobject = new Integer(98.22); // Using intValue() method int i = intobject.intValue(); // Printing the value stored in above integer // variable System.out.println("The integer Value of i = " + i); // Creating another object of Integer class Integer ab = new Integer("52"); int a = ab.intValue(); // This time printing the value stored in "ab" System.out.println("The integer Value of ab = " + a); }} Output: Note: It returns an error message when a decimal value is given. For a string this works fine. amlanbosefitcse15 adnanirshad158 solankimayank Java-Functions Java-Integer Java-lang package Java Java Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 53, "s": 25, "text": "\n03 May, 2022" }, { "code": null, "e": 270, "s": 53, "text": "intValue() of Integer class that is present inside java.lang package is an inbuilt method in java that returns the value of this integer as an int which is inherited from Number Class. The package view is as follows:" }, { "code": null, "e": 349, "s": 270, "text": "--> java.lang Package\n --> Integer Class\n --> intValue() Method " }, { "code": null, "e": 358, "s": 349, "text": "Syntax: " }, { "code": null, "e": 380, "s": 358, "text": "public int intValue()" }, { "code": null, "e": 481, "s": 380, "text": "Return Type: A numeric value that is represented by the object after conversion to the integer type." }, { "code": null, "e": 549, "s": 481, "text": "Note: This method is applicable from java version 1.2 and onwards. " }, { "code": null, "e": 646, "s": 549, "text": "Now we will be covering different numbers such as positive, negative, decimal, and even strings." }, { "code": null, "e": 669, "s": 646, "text": "For a positive integer" }, { "code": null, "e": 691, "s": 669, "text": "For a negative number" }, { "code": null, "e": 722, "s": 691, "text": "For a decimal value and string" }, { "code": null, "e": 753, "s": 722, "text": "Case 1: For a positive integer" }, { "code": null, "e": 762, "s": 753, "text": "Example:" }, { "code": null, "e": 767, "s": 762, "text": "Java" }, { "code": "// Java Program to Illustrate// the Usage of intValue() method// of Integer class // Importing required class/esimport java.lang.*; // Main classpublic class GFG { // Main driver method public static void main(String[] args) { // Creating object of Integer class inside main() Integer intobject = new Integer(68); // Returns the value of this Integer as an int int i = intobject.intValue(); // Printing the value above stored in integer System.out.println(\"The integer Value of i = \" + i); }}", "e": 1318, "s": 767, "text": null }, { "code": null, "e": 1346, "s": 1318, "text": "The integer Value of i = 68" }, { "code": null, "e": 1379, "s": 1348, "text": "Case 2: For a negative number" }, { "code": null, "e": 1388, "s": 1379, "text": "Example:" }, { "code": null, "e": 1393, "s": 1388, "text": "Java" }, { "code": "// Java program to illustrate the// use of intValue() method of// Integer class of java.lang package // Importing required classesimport java.lang.*; // Main classpublic class GFG { // Main driver method public static void main(String[] args) { // Creating an object of Integer class Integer intobject = new Integer(-76); // Returns the value of this Integer as an int int i = intobject.intValue(); // Printing the integer value above stored on // console System.out.println(\"The integer Value of i = \" + i); }}", "e": 1970, "s": 1393, "text": null }, { "code": null, "e": 1999, "s": 1970, "text": "The integer Value of i = -76" }, { "code": null, "e": 2042, "s": 2001, "text": "Case 3: For a decimal value and string. " }, { "code": null, "e": 2051, "s": 2042, "text": "Example:" }, { "code": null, "e": 2056, "s": 2051, "text": "Java" }, { "code": "// Java Program to illustrate// Usage of intValue() method// of Integer class of java.lang package // Importing required classesimport java.lang.*; // Main classclass GFG { // Main driver method public static void main(String[] args) { // Creating an object of Integer class Integer intobject = new Integer(98.22); // Using intValue() method int i = intobject.intValue(); // Printing the value stored in above integer // variable System.out.println(\"The integer Value of i = \" + i); // Creating another object of Integer class Integer ab = new Integer(\"52\"); int a = ab.intValue(); // This time printing the value stored in \"ab\" System.out.println(\"The integer Value of ab = \" + a); }}", "e": 2870, "s": 2056, "text": null }, { "code": null, "e": 2879, "s": 2870, "text": "Output: " }, { "code": null, "e": 2975, "s": 2879, "text": "Note: It returns an error message when a decimal value is given. For a string this works fine. " }, { "code": null, "e": 2993, "s": 2975, "text": "amlanbosefitcse15" }, { "code": null, "e": 3008, "s": 2993, "text": "adnanirshad158" }, { "code": null, "e": 3022, "s": 3008, "text": "solankimayank" }, { "code": null, "e": 3037, "s": 3022, "text": "Java-Functions" }, { "code": null, "e": 3050, "s": 3037, "text": "Java-Integer" }, { "code": null, "e": 3068, "s": 3050, "text": "Java-lang package" }, { "code": null, "e": 3073, "s": 3068, "text": "Java" }, { "code": null, "e": 3078, "s": 3073, "text": "Java" } ]
How to Create a Programming Language using Python?
10 Jul, 2020 In this article, we are going to learn how to create your own programming language using SLY(Sly Lex Yacc) and Python. Before we dig deeper into this topic, it is to be noted that this is not a beginner’s tutorial and you need to have some knowledge of the prerequisites given below. Rough knowledge about compiler design. Basic understanding of lexical analysis, parsing and other compiler design aspects. Understanding of regular expressions. Familiarity with Python programming language. Install SLY for Python. SLY is a lexing and parsing tool which makes our process much easier. pip install sly The first phase of a compiler is to convert all the character streams(the high level program that is written) to token streams. This is done by a process called lexical analysis. However, this process is simplified by using SLY First let’s import all the necessary modules. Python3 from sly import Lexer Now let’s build a class BasicLexer which extends the Lexer class from SLY. Let’s make a compiler that makes simple arithmetic operations. Thus we will need some basic tokens such as NAME, NUMBER, STRING. In any programming language, there will be space between two characters. Thus we create an ignore literal. Then we also create the basic literals like ‘=’, ‘+’ etc., NAME tokens are basically names of variables, which can be defined by the regular expression [a-zA-Z_][a-zA-Z0-9_]*. STRING tokens are string values and are bounded by quotation marks(” “). This can be defined by the regular expression \”.*?\”. Whenever we find digit/s, we should allocate it to the token NUMBER and the number must be stored as an integer. We are doing a basic programmable script, so let’s just make it with integers, however, feel free to extend the same for decimals, long etc., We can also make comments. Whenever we find “//”, we ignore whatever that comes next in that line. We do the same thing with new line character. Thus, we have build a basic lexer that converts the character stream to token stream. Python3 class BasicLexer(Lexer): tokens = { NAME, NUMBER, STRING } ignore = '\t ' literals = { '=', '+', '-', '/', '*', '(', ')', ',', ';'} # Define tokens as regular expressions # (stored as raw strings) NAME = r'[a-zA-Z_][a-zA-Z0-9_]*' STRING = r'\".*?\"' # Number token @_(r'\d+') def NUMBER(self, t): # convert it into a python integer t.value = int(t.value) return t # Comment token @_(r'//.*') def COMMENT(self, t): pass # Newline token(used only for showing # errors in new line) @_(r'\n+') def newline(self, t): self.lineno = t.value.count('\n') First let’s import all the necessary modules. Python3 from sly import Parser Now let’s build a class BasicParser which extends the Lexer class. The token stream from the BasicLexer is passed to a variable tokens. The precedence is defined, which is the same for most programming languages. Most of the parsing written in the program below is very simple. When there is nothing, the statement passes nothing. Essentially you can press enter on your keyboard(without typing in anything) and go to the next line. Next, your language should comprehend assignments using the “=”. This is handled in line 18 of the program below. The same thing can be done when assigned to a string. Python3 class BasicParser(Parser): #tokens are passed from lexer to parser tokens = BasicLexer.tokens precedence = ( ('left', '+', '-'), ('left', '*', '/'), ('right', 'UMINUS'), ) def __init__(self): self.env = { } @_('') def statement(self, p): pass @_('var_assign') def statement(self, p): return p.var_assign @_('NAME "=" expr') def var_assign(self, p): return ('var_assign', p.NAME, p.expr) @_('NAME "=" STRING') def var_assign(self, p): return ('var_assign', p.NAME, p.STRING) @_('expr') def statement(self, p): return (p.expr) @_('expr "+" expr') def expr(self, p): return ('add', p.expr0, p.expr1) @_('expr "-" expr') def expr(self, p): return ('sub', p.expr0, p.expr1) @_('expr "*" expr') def expr(self, p): return ('mul', p.expr0, p.expr1) @_('expr "/" expr') def expr(self, p): return ('div', p.expr0, p.expr1) @_('"-" expr %prec UMINUS') def expr(self, p): return p.expr @_('NAME') def expr(self, p): return ('var', p.NAME) @_('NUMBER') def expr(self, p): return ('num', p.NUMBER) The parser should also parse in arithmetic operations, this can be done by expressions. Let’s say you want something like shown below. Here all of them are made into token stream line-by-line and parsed line-by-line. Therefore, according to the program above, a = 10 resembles line 22. Same for b =20. a + b resembles line 34, which returns a parse tree (‘add’, (‘var’, ‘a’), (‘var’, ‘b’)). GFG Language > a = 10 GFG Language > b = 20 GFG Language > a + b 30 Now we have converted the token streams to a parse tree. Next step is to interpret it. Interpreting is a simple procedure. The basic idea is to take the tree and walk through it to and evaluate arithmetic operations hierarchically. This process is recursively called over and over again till the entire tree is evaluated and the answer is retrieved. Let’s say, for example, 5 + 7 + 4. This character stream is first tokenized to token stream in a lexer. The token stream is then parsed to form a parse tree. The parse tree essentially returns (‘add’, (‘add’, (‘num’, 5), (‘num’, 7)), (‘num’, 4)). (see image below) The interpreter is going to add 5 and 7 first and then recursively call walkTree and add 4 to the result of addition of 5 and 7. Thus, we are going to get 16. The below code does the same process. Python3 class BasicExecute: def __init__(self, tree, env): self.env = env result = self.walkTree(tree) if result is not None and isinstance(result, int): print(result) if isinstance(result, str) and result[0] == '"': print(result) def walkTree(self, node): if isinstance(node, int): return node if isinstance(node, str): return node if node is None: return None if node[0] == 'program': if node[1] == None: self.walkTree(node[2]) else: self.walkTree(node[1]) self.walkTree(node[2]) if node[0] == 'num': return node[1] if node[0] == 'str': return node[1] if node[0] == 'add': return self.walkTree(node[1]) + self.walkTree(node[2]) elif node[0] == 'sub': return self.walkTree(node[1]) - self.walkTree(node[2]) elif node[0] == 'mul': return self.walkTree(node[1]) * self.walkTree(node[2]) elif node[0] == 'div': return self.walkTree(node[1]) / self.walkTree(node[2]) if node[0] == 'var_assign': self.env[node[1]] = self.walkTree(node[2]) return node[1] if node[0] == 'var': try: return self.env[node[1]] except LookupError: print("Undefined variable '"+node[1]+"' found!") return 0 To display the output from the interpreter, we should write some codes. The code should first call the lexer, then the parser and then the interpreter and finally retrieves the output. The output in then displayed on to the shell. Python3 if __name__ == '__main__': lexer = BasicLexer() parser = BasicParser() print('GFG Language') env = {} while True: try: text = input('GFG Language > ') except EOFError: break if text: tree = parser.parse(lexer.tokenize(text)) BasicExecute(tree, env) It is necessary to know that we haven’t handled any errors. So SLY is going to show it’s error messages whenever you do something that is not specified by the rules you have written. Execute the program you have written using, python you_program_name.py The interpreter that we built is very basic. This, of course, can be extended to do a lot more. Loops and conditionals can be added. Modular or object oriented design features can be implemented. Module integration, method definitions, parameters to methods are some of the features that can be extended on to the same. Compiler Design Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 52, "s": 24, "text": "\n10 Jul, 2020" }, { "code": null, "e": 336, "s": 52, "text": "In this article, we are going to learn how to create your own programming language using SLY(Sly Lex Yacc) and Python. Before we dig deeper into this topic, it is to be noted that this is not a beginner’s tutorial and you need to have some knowledge of the prerequisites given below." }, { "code": null, "e": 375, "s": 336, "text": "Rough knowledge about compiler design." }, { "code": null, "e": 459, "s": 375, "text": "Basic understanding of lexical analysis, parsing and other compiler design aspects." }, { "code": null, "e": 497, "s": 459, "text": "Understanding of regular expressions." }, { "code": null, "e": 543, "s": 497, "text": "Familiarity with Python programming language." }, { "code": null, "e": 637, "s": 543, "text": "Install SLY for Python. SLY is a lexing and parsing tool which makes our process much easier." }, { "code": null, "e": 654, "s": 637, "text": "pip install sly\n" }, { "code": null, "e": 882, "s": 654, "text": "The first phase of a compiler is to convert all the character streams(the high level program that is written) to token streams. This is done by a process called lexical analysis. However, this process is simplified by using SLY" }, { "code": null, "e": 928, "s": 882, "text": "First let’s import all the necessary modules." }, { "code": null, "e": 936, "s": 928, "text": "Python3" }, { "code": "from sly import Lexer", "e": 958, "s": 936, "text": null }, { "code": null, "e": 1574, "s": 958, "text": "Now let’s build a class BasicLexer which extends the Lexer class from SLY. Let’s make a compiler that makes simple arithmetic operations. Thus we will need some basic tokens such as NAME, NUMBER, STRING. In any programming language, there will be space between two characters. Thus we create an ignore literal. Then we also create the basic literals like ‘=’, ‘+’ etc., NAME tokens are basically names of variables, which can be defined by the regular expression [a-zA-Z_][a-zA-Z0-9_]*. STRING tokens are string values and are bounded by quotation marks(” “). This can be defined by the regular expression \\”.*?\\”." }, { "code": null, "e": 2060, "s": 1574, "text": "Whenever we find digit/s, we should allocate it to the token NUMBER and the number must be stored as an integer. We are doing a basic programmable script, so let’s just make it with integers, however, feel free to extend the same for decimals, long etc., We can also make comments. Whenever we find “//”, we ignore whatever that comes next in that line. We do the same thing with new line character. Thus, we have build a basic lexer that converts the character stream to token stream." }, { "code": null, "e": 2068, "s": 2060, "text": "Python3" }, { "code": "class BasicLexer(Lexer): tokens = { NAME, NUMBER, STRING } ignore = '\\t ' literals = { '=', '+', '-', '/', '*', '(', ')', ',', ';'} # Define tokens as regular expressions # (stored as raw strings) NAME = r'[a-zA-Z_][a-zA-Z0-9_]*' STRING = r'\\\".*?\\\"' # Number token @_(r'\\d+') def NUMBER(self, t): # convert it into a python integer t.value = int(t.value) return t # Comment token @_(r'//.*') def COMMENT(self, t): pass # Newline token(used only for showing # errors in new line) @_(r'\\n+') def newline(self, t): self.lineno = t.value.count('\\n')", "e": 2735, "s": 2068, "text": null }, { "code": null, "e": 2782, "s": 2735, "text": " First let’s import all the necessary modules." }, { "code": null, "e": 2790, "s": 2782, "text": "Python3" }, { "code": "from sly import Parser", "e": 2813, "s": 2790, "text": null }, { "code": null, "e": 3415, "s": 2813, "text": "Now let’s build a class BasicParser which extends the Lexer class. The token stream from the BasicLexer is passed to a variable tokens. The precedence is defined, which is the same for most programming languages. Most of the parsing written in the program below is very simple. When there is nothing, the statement passes nothing. Essentially you can press enter on your keyboard(without typing in anything) and go to the next line. Next, your language should comprehend assignments using the “=”. This is handled in line 18 of the program below. The same thing can be done when assigned to a string." }, { "code": null, "e": 3423, "s": 3415, "text": "Python3" }, { "code": "class BasicParser(Parser): #tokens are passed from lexer to parser tokens = BasicLexer.tokens precedence = ( ('left', '+', '-'), ('left', '*', '/'), ('right', 'UMINUS'), ) def __init__(self): self.env = { } @_('') def statement(self, p): pass @_('var_assign') def statement(self, p): return p.var_assign @_('NAME \"=\" expr') def var_assign(self, p): return ('var_assign', p.NAME, p.expr) @_('NAME \"=\" STRING') def var_assign(self, p): return ('var_assign', p.NAME, p.STRING) @_('expr') def statement(self, p): return (p.expr) @_('expr \"+\" expr') def expr(self, p): return ('add', p.expr0, p.expr1) @_('expr \"-\" expr') def expr(self, p): return ('sub', p.expr0, p.expr1) @_('expr \"*\" expr') def expr(self, p): return ('mul', p.expr0, p.expr1) @_('expr \"/\" expr') def expr(self, p): return ('div', p.expr0, p.expr1) @_('\"-\" expr %prec UMINUS') def expr(self, p): return p.expr @_('NAME') def expr(self, p): return ('var', p.NAME) @_('NUMBER') def expr(self, p): return ('num', p.NUMBER)", "e": 4634, "s": 3423, "text": null }, { "code": null, "e": 5025, "s": 4634, "text": "The parser should also parse in arithmetic operations, this can be done by expressions. Let’s say you want something like shown below. Here all of them are made into token stream line-by-line and parsed line-by-line. Therefore, according to the program above, a = 10 resembles line 22. Same for b =20. a + b resembles line 34, which returns a parse tree (‘add’, (‘var’, ‘a’), (‘var’, ‘b’))." }, { "code": null, "e": 5094, "s": 5025, "text": "GFG Language > a = 10\nGFG Language > b = 20\nGFG Language > a + b\n30\n" }, { "code": null, "e": 5181, "s": 5094, "text": "Now we have converted the token streams to a parse tree. Next step is to interpret it." }, { "code": null, "e": 5709, "s": 5181, "text": "Interpreting is a simple procedure. The basic idea is to take the tree and walk through it to and evaluate arithmetic operations hierarchically. This process is recursively called over and over again till the entire tree is evaluated and the answer is retrieved. Let’s say, for example, 5 + 7 + 4. This character stream is first tokenized to token stream in a lexer. The token stream is then parsed to form a parse tree. The parse tree essentially returns (‘add’, (‘add’, (‘num’, 5), (‘num’, 7)), (‘num’, 4)). (see image below)" }, { "code": null, "e": 5907, "s": 5709, "text": "The interpreter is going to add 5 and 7 first and then recursively call walkTree and add 4 to the result of addition of 5 and 7. Thus, we are going to get 16. The below code does the same process. " }, { "code": null, "e": 5915, "s": 5907, "text": "Python3" }, { "code": "class BasicExecute: def __init__(self, tree, env): self.env = env result = self.walkTree(tree) if result is not None and isinstance(result, int): print(result) if isinstance(result, str) and result[0] == '\"': print(result) def walkTree(self, node): if isinstance(node, int): return node if isinstance(node, str): return node if node is None: return None if node[0] == 'program': if node[1] == None: self.walkTree(node[2]) else: self.walkTree(node[1]) self.walkTree(node[2]) if node[0] == 'num': return node[1] if node[0] == 'str': return node[1] if node[0] == 'add': return self.walkTree(node[1]) + self.walkTree(node[2]) elif node[0] == 'sub': return self.walkTree(node[1]) - self.walkTree(node[2]) elif node[0] == 'mul': return self.walkTree(node[1]) * self.walkTree(node[2]) elif node[0] == 'div': return self.walkTree(node[1]) / self.walkTree(node[2]) if node[0] == 'var_assign': self.env[node[1]] = self.walkTree(node[2]) return node[1] if node[0] == 'var': try: return self.env[node[1]] except LookupError: print(\"Undefined variable '\"+node[1]+\"' found!\") return 0", "e": 7403, "s": 5915, "text": null }, { "code": null, "e": 7634, "s": 7403, "text": "To display the output from the interpreter, we should write some codes. The code should first call the lexer, then the parser and then the interpreter and finally retrieves the output. The output in then displayed on to the shell." }, { "code": null, "e": 7642, "s": 7634, "text": "Python3" }, { "code": "if __name__ == '__main__': lexer = BasicLexer() parser = BasicParser() print('GFG Language') env = {} while True: try: text = input('GFG Language > ') except EOFError: break if text: tree = parser.parse(lexer.tokenize(text)) BasicExecute(tree, env)", "e": 8007, "s": 7642, "text": null }, { "code": null, "e": 8190, "s": 8007, "text": "It is necessary to know that we haven’t handled any errors. So SLY is going to show it’s error messages whenever you do something that is not specified by the rules you have written." }, { "code": null, "e": 8234, "s": 8190, "text": "Execute the program you have written using," }, { "code": null, "e": 8262, "s": 8234, "text": "python you_program_name.py\n" }, { "code": null, "e": 8583, "s": 8262, "text": "The interpreter that we built is very basic. This, of course, can be extended to do a lot more. Loops and conditionals can be added. Modular or object oriented design features can be implemented. Module integration, method definitions, parameters to methods are some of the features that can be extended on to the same. " }, { "code": null, "e": 8599, "s": 8583, "text": "Compiler Design" }, { "code": null, "e": 8606, "s": 8599, "text": "Python" } ]
How to get the file name from page URL using JavaScript ?
29 Jan, 2020 Suppose you have given an HTML page and the task is to get the file name of an HTML page with the help of JavaScript. There are two approaches that are discussed below: Approach 1: In this approach, window.location.pathname returns the relative URL of the page. Use split() method to split the URL on “/” and pop() method to get the last item from the array. Example: This example implements the above approach.<!DOCTYPE html><html> <head> <title> How to get the name of a file using JavaScript </title> <style> body { text-align: center; } h1 { color: green; } #geeks { font-size: 26px; font-weight: bold; color: green; } </style></head> <body> <h1>GeeksforGeeks</h1> <p> Click on the button to get the name of the file. </p> <button onclick="GFG_Fun();"> click here </button> <p id="geeks"></p> <script> var down = document.getElementById('geeks'); function GFG_Fun() { var path = window.location.pathname; down.innerHTML = path.split("/").pop(); } </script></body> </html> <!DOCTYPE html><html> <head> <title> How to get the name of a file using JavaScript </title> <style> body { text-align: center; } h1 { color: green; } #geeks { font-size: 26px; font-weight: bold; color: green; } </style></head> <body> <h1>GeeksforGeeks</h1> <p> Click on the button to get the name of the file. </p> <button onclick="GFG_Fun();"> click here </button> <p id="geeks"></p> <script> var down = document.getElementById('geeks'); function GFG_Fun() { var path = window.location.pathname; down.innerHTML = path.split("/").pop(); } </script></body> </html> Output: Approach 2: In this approach, location.pathname returns the relative URL of the page. Use lastIndexOf() method to get the last “/” and substring() method to get the item after “/” from the string. Example: This example implements the above approach.<!DOCTYPE html><html> <head> <title> How to get the name of a file in JavaScript </title> <style> body { text-align: center; } h1 { color: green; } #geeks { font-size: 26px; font-weight: bold; color: green; } </style></head> <body> <h1>GeeksforGeeks</h1> <p> Click on the button to get the name of the file. </p> <button onclick="GFG_Fun();"> click here </button> <p id="geeks"></p> <script> var down = document.getElementById('geeks'); function GFG_Fun() { down.innerHTML = location.pathname.substring (location.pathname.lastIndexOf("/") + 1); } </script></body> </html> <!DOCTYPE html><html> <head> <title> How to get the name of a file in JavaScript </title> <style> body { text-align: center; } h1 { color: green; } #geeks { font-size: 26px; font-weight: bold; color: green; } </style></head> <body> <h1>GeeksforGeeks</h1> <p> Click on the button to get the name of the file. </p> <button onclick="GFG_Fun();"> click here </button> <p id="geeks"></p> <script> var down = document.getElementById('geeks'); function GFG_Fun() { down.innerHTML = location.pathname.substring (location.pathname.lastIndexOf("/") + 1); } </script></body> </html> Output: CSS-Misc HTML-Misc JavaScript-Misc JavaScript Web Technologies Web technologies Questions Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n29 Jan, 2020" }, { "code": null, "e": 197, "s": 28, "text": "Suppose you have given an HTML page and the task is to get the file name of an HTML page with the help of JavaScript. There are two approaches that are discussed below:" }, { "code": null, "e": 387, "s": 197, "text": "Approach 1: In this approach, window.location.pathname returns the relative URL of the page. Use split() method to split the URL on “/” and pop() method to get the last item from the array." }, { "code": null, "e": 1252, "s": 387, "text": "Example: This example implements the above approach.<!DOCTYPE html><html> <head> <title> How to get the name of a file using JavaScript </title> <style> body { text-align: center; } h1 { color: green; } #geeks { font-size: 26px; font-weight: bold; color: green; } </style></head> <body> <h1>GeeksforGeeks</h1> <p> Click on the button to get the name of the file. </p> <button onclick=\"GFG_Fun();\"> click here </button> <p id=\"geeks\"></p> <script> var down = document.getElementById('geeks'); function GFG_Fun() { var path = window.location.pathname; down.innerHTML = path.split(\"/\").pop(); } </script></body> </html>" }, { "code": "<!DOCTYPE html><html> <head> <title> How to get the name of a file using JavaScript </title> <style> body { text-align: center; } h1 { color: green; } #geeks { font-size: 26px; font-weight: bold; color: green; } </style></head> <body> <h1>GeeksforGeeks</h1> <p> Click on the button to get the name of the file. </p> <button onclick=\"GFG_Fun();\"> click here </button> <p id=\"geeks\"></p> <script> var down = document.getElementById('geeks'); function GFG_Fun() { var path = window.location.pathname; down.innerHTML = path.split(\"/\").pop(); } </script></body> </html>", "e": 2065, "s": 1252, "text": null }, { "code": null, "e": 2073, "s": 2065, "text": "Output:" }, { "code": null, "e": 2270, "s": 2073, "text": "Approach 2: In this approach, location.pathname returns the relative URL of the page. Use lastIndexOf() method to get the last “/” and substring() method to get the item after “/” from the string." }, { "code": null, "e": 3142, "s": 2270, "text": "Example: This example implements the above approach.<!DOCTYPE html><html> <head> <title> How to get the name of a file in JavaScript </title> <style> body { text-align: center; } h1 { color: green; } #geeks { font-size: 26px; font-weight: bold; color: green; } </style></head> <body> <h1>GeeksforGeeks</h1> <p> Click on the button to get the name of the file. </p> <button onclick=\"GFG_Fun();\"> click here </button> <p id=\"geeks\"></p> <script> var down = document.getElementById('geeks'); function GFG_Fun() { down.innerHTML = location.pathname.substring (location.pathname.lastIndexOf(\"/\") + 1); } </script></body> </html>" }, { "code": "<!DOCTYPE html><html> <head> <title> How to get the name of a file in JavaScript </title> <style> body { text-align: center; } h1 { color: green; } #geeks { font-size: 26px; font-weight: bold; color: green; } </style></head> <body> <h1>GeeksforGeeks</h1> <p> Click on the button to get the name of the file. </p> <button onclick=\"GFG_Fun();\"> click here </button> <p id=\"geeks\"></p> <script> var down = document.getElementById('geeks'); function GFG_Fun() { down.innerHTML = location.pathname.substring (location.pathname.lastIndexOf(\"/\") + 1); } </script></body> </html>", "e": 3962, "s": 3142, "text": null }, { "code": null, "e": 3970, "s": 3962, "text": "Output:" }, { "code": null, "e": 3979, "s": 3970, "text": "CSS-Misc" }, { "code": null, "e": 3989, "s": 3979, "text": "HTML-Misc" }, { "code": null, "e": 4005, "s": 3989, "text": "JavaScript-Misc" }, { "code": null, "e": 4016, "s": 4005, "text": "JavaScript" }, { "code": null, "e": 4033, "s": 4016, "text": "Web Technologies" }, { "code": null, "e": 4060, "s": 4033, "text": "Web technologies Questions" } ]
Variadic function templates in C++
25 Nov, 2021 Variadic templates are class or function templates, that can take any variable(zero or more) number of arguments. In C++, templates can have a fixed number of parameters only that have to be specified at the time of declaration. However, variadic templates help to overcome this issue. Douglas Gregor and Jaakko Järvi came up with this feature for C++. Variadic arguments are very similar to arrays in C++. We can easily iterate through the arguments, find the size(length) of the template, can access the values by an index, and can slice the templates too. So basically, Variadic function templates are functions that can take multiple numbers of arguments. Syntax: template(typename arg, typename... args) return_type function_name(arg var1, args... var2) Note: The arguments must be put inside angular brackets. Below is an example in C++ to show how we can use a variadic function template: CPP // C++ program to demonstrate working of// Variadic function Template#include <iostream>using namespace std; // To handle base case of below recursive// Variadic function Templatevoid print(){ cout << "I am empty function and " "I am called at last.\n";} // Variadic function Template that takes// variable number of arguments and prints// all of them.template <typename T, typename... Types>void print(T var1, Types... var2){ cout << var1 << endl; print(var2...);} // Driver codeint main(){ print(1, 2, 3.14, "Pass me any " "number of arguments", "I will print\n"); return 0;} 1 2 3.14 Pass me any number of arguments I will print I am empty function and I am called at last. Remember that templates are replaced by actual functions by the compiler. Explanation: The variadic templates work as follows : The statement, print(1, 2, 3.14, “Pass me any number of arguments”, “I will print\n”); is evaluated in the following manner: Firstly, the compiler resolves the statement into cout<< 1 <<endl ; print(2, 3.14, "Pass me any number of arguments", "I will print\n"); Now, the compiler finds a print() function which can take those arguments and in result executes the variadic print() function again in a similar manner: cout<< 2 <<endl ; print(3.14, "Pass me any number of arguments", "I will print\n"); Again, it is resolved into the following forms : cout<< 3.14 <<endl ; print("Pass me any number of arguments", "I will print\n"); cout<< "Pass me any number of arguments" <<endl ; print("I will print\n"); cout<< "I will print\n" <<endl ; print(); Now, at this point, the compiler searches for a function overload whose match is the empty function i.e. the function which has no argument. This means that all functions that have 1 or more arguments are matched to the variadic template and all functions that with no argument are matched to the empty function. This article is contributed by MAZHAR IMAM KHAN. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. Akanksha_Rai anshikajain26 cpp-template C++ CPP Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 52, "s": 24, "text": "\n25 Nov, 2021" }, { "code": null, "e": 406, "s": 52, "text": "Variadic templates are class or function templates, that can take any variable(zero or more) number of arguments. In C++, templates can have a fixed number of parameters only that have to be specified at the time of declaration. However, variadic templates help to overcome this issue. Douglas Gregor and Jaakko Järvi came up with this feature for C++." }, { "code": null, "e": 613, "s": 406, "text": "Variadic arguments are very similar to arrays in C++. We can easily iterate through the arguments, find the size(length) of the template, can access the values by an index, and can slice the templates too. " }, { "code": null, "e": 714, "s": 613, "text": "So basically, Variadic function templates are functions that can take multiple numbers of arguments." }, { "code": null, "e": 722, "s": 714, "text": "Syntax:" }, { "code": null, "e": 813, "s": 722, "text": "template(typename arg, typename... args)\nreturn_type function_name(arg var1, args... var2)" }, { "code": null, "e": 871, "s": 813, "text": "Note: The arguments must be put inside angular brackets. " }, { "code": null, "e": 951, "s": 871, "text": "Below is an example in C++ to show how we can use a variadic function template:" }, { "code": null, "e": 955, "s": 951, "text": "CPP" }, { "code": "// C++ program to demonstrate working of// Variadic function Template#include <iostream>using namespace std; // To handle base case of below recursive// Variadic function Templatevoid print(){ cout << \"I am empty function and \" \"I am called at last.\\n\";} // Variadic function Template that takes// variable number of arguments and prints// all of them.template <typename T, typename... Types>void print(T var1, Types... var2){ cout << var1 << endl; print(var2...);} // Driver codeint main(){ print(1, 2, 3.14, \"Pass me any \" \"number of arguments\", \"I will print\\n\"); return 0;}", "e": 1588, "s": 955, "text": null }, { "code": null, "e": 1688, "s": 1588, "text": "1\n2\n3.14\nPass me any number of arguments\nI will print\n\nI am empty function and I am called at last." }, { "code": null, "e": 1762, "s": 1688, "text": "Remember that templates are replaced by actual functions by the compiler." }, { "code": null, "e": 1817, "s": 1762, "text": "Explanation: The variadic templates work as follows : " }, { "code": null, "e": 1943, "s": 1817, "text": "The statement, print(1, 2, 3.14, “Pass me any number of arguments”, “I will print\\n”); is evaluated in the following manner: " }, { "code": null, "e": 1994, "s": 1943, "text": "Firstly, the compiler resolves the statement into " }, { "code": null, "e": 2088, "s": 1994, "text": "cout<< 1 <<endl ;\nprint(2, 3.14, \"Pass me any number of arguments\", \n \"I will print\\n\");" }, { "code": null, "e": 2243, "s": 2088, "text": "Now, the compiler finds a print() function which can take those arguments and in result executes the variadic print() function again in a similar manner: " }, { "code": null, "e": 2334, "s": 2243, "text": "cout<< 2 <<endl ;\nprint(3.14, \"Pass me any number of arguments\", \n \"I will print\\n\");" }, { "code": null, "e": 2384, "s": 2334, "text": "Again, it is resolved into the following forms : " }, { "code": null, "e": 2472, "s": 2384, "text": "cout<< 3.14 <<endl ;\nprint(\"Pass me any number of arguments\", \n \"I will print\\n\");" }, { "code": null, "e": 2547, "s": 2472, "text": "cout<< \"Pass me any number of arguments\" <<endl ;\nprint(\"I will print\\n\");" }, { "code": null, "e": 2589, "s": 2547, "text": "cout<< \"I will print\\n\" <<endl ;\nprint();" }, { "code": null, "e": 2902, "s": 2589, "text": "Now, at this point, the compiler searches for a function overload whose match is the empty function i.e. the function which has no argument. This means that all functions that have 1 or more arguments are matched to the variadic template and all functions that with no argument are matched to the empty function." }, { "code": null, "e": 3327, "s": 2902, "text": "This article is contributed by MAZHAR IMAM KHAN. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above." }, { "code": null, "e": 3340, "s": 3327, "text": "Akanksha_Rai" }, { "code": null, "e": 3354, "s": 3340, "text": "anshikajain26" }, { "code": null, "e": 3367, "s": 3354, "text": "cpp-template" }, { "code": null, "e": 3371, "s": 3367, "text": "C++" }, { "code": null, "e": 3375, "s": 3371, "text": "CPP" } ]
Scala Sequence
01 Jun, 2021 Sequence is an iterable collection of class Iterable. It is used to represent indexed sequences that are having a defined order of element i.e. guaranteed immutable. The elements of sequences can be accessed using their indexes. Method apply is used for the purpose of indexing. Sequences can also be accessed reversibly using the method reverse and reverseIterator. The indices range from 0 to (n – 1) Where, n= the length of the sequence. For the purpose of finding the subsequences, sequences support various methods. Methods such as indexOf, segmentLength, prefixLength, lastIndexWhere, lastIndexOf, startsWith, endsWith. There are two primary subtraits of Sequence namely IndexedSeq and LinearSeq which gives different performance guarantees. IndexexedSeq provides fast and random access of elements while LinearSeq provides fast access to the first element only via head and also contains a fast tail operation. Example #1: Scala // Scala program to illustrate sequenceimport scala.collection.immutable._ object GFG{ // Main Method def main(args:Array[String]) { // Initializing sequence var seq:Seq[Int] = Seq(1,2,3,4,5,6) // Printing Sequence seq.foreach((element:Int) => print(element+",")) println("\nElements Access Using Index") println(seq(0)) println(seq(1)) println(seq(2)) println(seq(3)) println(seq(4)) println(seq(5)) }} 1,2,3,4,5,6, Elements Access Using Index 1 2 3 4 5 6 Some of the Predefined Methods used in Sequence def apply(index: Int): A -> To select an element from the sequence def contains[A1 >: A](elem: A1): Boolean -> To check whether a sequence contains the given element def count(p: (A)=> Boolean): Int-> To count the number of elements that satisfies a predicate def length: Int -> gives the length of the Sequence def copyToArray(xs: Array[A], start: Int, len: Int): Unit -> For copying the elements of Sequence to array def endsWith[B](that: GenSeq[B]): Boolean-> to check whether a sequence terminates with a given sequence or not def head: A ->It selects the first element of the sequence. def indexOf(elem: A): Int-> To find the index of first occurrence of a value in the sequence def isEmpty: Boolean ->To test the emptiness of the sequence. def lastIndexOf(elem: A): Int-> To find the index of last occurrence of a value in the sequence def reverse: Seq[A]-> To return a new sequence with elements in reverse order. Sequence Example using Predefined methods Example #2: Scala // Scala program to illustrate sequenceobject MainObject{ // Main Method def main(args:Array[String]) { // Initializing sequence var seq:Seq[Int] = Seq(1, 2, 3, 4, 5, 6) // Printing Sequence seq.foreach((element:Int) => print(element+",")) // Using Some Predefined Methods println("\nis Empty: "+ seq.isEmpty) println("\nEnds with (5,6): "+ seq.endsWith(Seq(5,6))) println("\nLength of sequence: "+ seq.length) println("\ncontains 3: "+ seq.contains(3)) println("\nlast index of 4 : "+ seq.lastIndexOf(4)) println("\nReversed sequence: "+ seq.reverse) }} 1,2,3,4,5,6, is Empty: false Ends with (5,6): true Length of sequence: 6 contains 3: true last index of 4 : 3 Reversed sequence: List(6, 5, 4, 3, 2, 1) clintra Scala scala-collection Articles Scala Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n01 Jun, 2021" }, { "code": null, "e": 960, "s": 28, "text": "Sequence is an iterable collection of class Iterable. It is used to represent indexed sequences that are having a defined order of element i.e. guaranteed immutable. The elements of sequences can be accessed using their indexes. Method apply is used for the purpose of indexing. Sequences can also be accessed reversibly using the method reverse and reverseIterator. The indices range from 0 to (n – 1) Where, n= the length of the sequence. For the purpose of finding the subsequences, sequences support various methods. Methods such as indexOf, segmentLength, prefixLength, lastIndexWhere, lastIndexOf, startsWith, endsWith. There are two primary subtraits of Sequence namely IndexedSeq and LinearSeq which gives different performance guarantees. IndexexedSeq provides fast and random access of elements while LinearSeq provides fast access to the first element only via head and also contains a fast tail operation. Example #1: " }, { "code": null, "e": 966, "s": 960, "text": "Scala" }, { "code": "// Scala program to illustrate sequenceimport scala.collection.immutable._ object GFG{ // Main Method def main(args:Array[String]) { // Initializing sequence var seq:Seq[Int] = Seq(1,2,3,4,5,6) // Printing Sequence seq.foreach((element:Int) => print(element+\",\")) println(\"\\nElements Access Using Index\") println(seq(0)) println(seq(1)) println(seq(2)) println(seq(3)) println(seq(4)) println(seq(5)) }}", "e": 1468, "s": 966, "text": null }, { "code": null, "e": 1521, "s": 1468, "text": "1,2,3,4,5,6,\nElements Access Using Index\n1\n2\n3\n4\n5\n6" }, { "code": null, "e": 1573, "s": 1523, "text": "Some of the Predefined Methods used in Sequence " }, { "code": null, "e": 1640, "s": 1573, "text": "def apply(index: Int): A -> To select an element from the sequence" }, { "code": null, "e": 1739, "s": 1640, "text": "def contains[A1 >: A](elem: A1): Boolean -> To check whether a sequence contains the given element" }, { "code": null, "e": 1833, "s": 1739, "text": "def count(p: (A)=> Boolean): Int-> To count the number of elements that satisfies a predicate" }, { "code": null, "e": 1885, "s": 1833, "text": "def length: Int -> gives the length of the Sequence" }, { "code": null, "e": 1992, "s": 1885, "text": "def copyToArray(xs: Array[A], start: Int, len: Int): Unit -> For copying the elements of Sequence to array" }, { "code": null, "e": 2104, "s": 1992, "text": "def endsWith[B](that: GenSeq[B]): Boolean-> to check whether a sequence terminates with a given sequence or not" }, { "code": null, "e": 2164, "s": 2104, "text": "def head: A ->It selects the first element of the sequence." }, { "code": null, "e": 2257, "s": 2164, "text": "def indexOf(elem: A): Int-> To find the index of first occurrence of a value in the sequence" }, { "code": null, "e": 2319, "s": 2257, "text": "def isEmpty: Boolean ->To test the emptiness of the sequence." }, { "code": null, "e": 2415, "s": 2319, "text": "def lastIndexOf(elem: A): Int-> To find the index of last occurrence of a value in the sequence" }, { "code": null, "e": 2494, "s": 2415, "text": "def reverse: Seq[A]-> To return a new sequence with elements in reverse order." }, { "code": null, "e": 2550, "s": 2494, "text": "Sequence Example using Predefined methods Example #2: " }, { "code": null, "e": 2556, "s": 2550, "text": "Scala" }, { "code": "// Scala program to illustrate sequenceobject MainObject{ // Main Method def main(args:Array[String]) { // Initializing sequence var seq:Seq[Int] = Seq(1, 2, 3, 4, 5, 6) // Printing Sequence seq.foreach((element:Int) => print(element+\",\")) // Using Some Predefined Methods println(\"\\nis Empty: \"+ seq.isEmpty) println(\"\\nEnds with (5,6): \"+ seq.endsWith(Seq(5,6))) println(\"\\nLength of sequence: \"+ seq.length) println(\"\\ncontains 3: \"+ seq.contains(3)) println(\"\\nlast index of 4 : \"+ seq.lastIndexOf(4)) println(\"\\nReversed sequence: \"+ seq.reverse) }}", "e": 3218, "s": 2556, "text": null }, { "code": null, "e": 3375, "s": 3218, "text": "1,2,3,4,5,6,\nis Empty: false\n\nEnds with (5,6): true\n\nLength of sequence: 6\n\ncontains 3: true\n\nlast index of 4 : 3\n\nReversed sequence: List(6, 5, 4, 3, 2, 1)" }, { "code": null, "e": 3385, "s": 3377, "text": "clintra" }, { "code": null, "e": 3391, "s": 3385, "text": "Scala" }, { "code": null, "e": 3408, "s": 3391, "text": "scala-collection" }, { "code": null, "e": 3417, "s": 3408, "text": "Articles" }, { "code": null, "e": 3423, "s": 3417, "text": "Scala" } ]
Different Ways To Declare And Initialize 2-D Array in Java
29 Oct, 2021 An array with more than one dimension is known as a multi-dimensional array. The most commonly used multi-dimensional arrays are 2-D and 3-D arrays. We can say that any higher dimensional array is basically an array of arrays. A very common example of a 2D Array is Chess Board. A chessboard is a grid containing 64 1×1 square boxes. You can similarly visualize a 2D array. In a 2D array, every element is associated with a row number and column number. Accessing any element of the 2D array is similar to accessing the record of an Excel File using both row number and column number. 2D arrays are useful while implementing a Tic-Tac-Toe game, Chess, or even storing the image pixels. Any 2-dimensional array can be declared as follows: Syntax: data_type array_name[][]; (OR) data_type[][] array_name; data_type: Since Java is a statically-typed language (i.e. it expects its variables to be declared before they can be assigned values). So, specifying the datatype decides the type of elements it will accept. e.g. to store integer values only, the data type will be declared as int. array_name: It is the name that is given to the 2-D array. e.g. subjects, students, fruits, department, etc. Note: We can write [ ][ ] after data_type or we can write [ ][ ] after array_name while declaring the 2D array. Java // java program showing declaration of arraysimport java.io.*; class GFG { public static void main(String[] args) { int[][] integer2DArray; // 2D integer array String[][] string2DArray; // 2D String array double[][] double2DArray; // 2D double array boolean[][] boolean2DArray; // 2D boolean array float[][] float2DArray; // 2D float array double[][] double2DArray; // 2D double array }} data_type[][] array_Name = new data_type[no_of_rows][no_of_columns]; The total elements in any 2D array will be equal to (no_of_rows) * (no_of_columns). no_of_rows: The number of rows an array can store. e.g. no_of_rows = 3, then the array will have three rows. no_of_columns: The number of rows an array can store. e.g. no_of_columns = 4, then the array will have four columns. The above syntax of array initialization will assign default values to all array elements according to the data type specified. Let us see various approaches of initializing 2D arrays: Java // java program to initialize a 2D arrayimport java.io.*; class GFG { public static void main(String[] args) { // Declaration along with initialization // 2D integer array with 5 rows and 3 columns // integer array elements are initialized with 0 int[][] integer2DArray = new int[5][3]; System.out.println( "Default value of int array element: " + integer2DArray[0][0]); // 2D String array with 4 rows and 4 columns // String array elements are initialized with null String[][] string2DArray = new String[4][4]; System.out.println( "Default value of String array element: " + string2DArray[0][0]); // 2D boolean array with 3 rows and 5 columns // boolean array elements are initialized with false boolean[][] boolean2DArray = new boolean[4][4]; System.out.println( "Default value of boolean array element: " + boolean2DArray[0][0]); // 2D char array with 10 rows and 10 columns // char array elements are initialized with // '\u0000'(null character) char[][] char2DArray = new char[10][10]; System.out.println( "Default value of char array element: " + char2DArray[0][0]); // First declaration and then initialization int[][] arr; // declaration // System.out.println("arr[0][0]: "+ arr[0][0]); // The above line will throw an error, as we have // only declared the 2D array, but not initialized // it. arr = new int[5][3]; // initialization System.out.println("arr[0][0]: " + arr[0][0]); }} Note: When you initialize a 2D array, you must always specify the first dimension(no. of rows), but providing the second dimension(no. of columns) may be omitted. In the code snippet below, we have not specified the number of columns. However, the Java compiler is smart enough to manipulate the size by checking the number of elements inside the columns. Java import java.io.*; class GFG { public static void main(String[] args) { // The line below will throw an error, as the first // dimension(no. of rows) is not specified int[][] arr = new int[][3]; // The line below will execute without any error, as // the first dimension(no. of rows) is specified int[][] arr = new int[2][]; }} You can access any element of a 2D array using row number and column number. In the code snippet below, we have not specified the number of rows and columns. However, the Java compiler is smart enough to manipulate the size by checking the number of elements inside the rows and columns. Java import java.io.*; class GFG { public static void main(String[] args) { String[][] subjects = { { "Data Structures & Algorithms", "Programming & Logic", "Software Engineering", "Theory of Computation" }, // row 1 { "Thermodynamics", "Metallurgy", "Machine Drawing", "Fluid Mechanics" }, // row2 { "Signals and Systems", "Digital Electronics", "Power Electronics" } // row3 }; System.out.println( "Fundamental Subject in Computer Engineering: " + subjects[0][0]); System.out.println( "Fundamental Subject in Mechanical Engineering: " + subjects[1][3]); System.out.println( "Fundamental Subject in Electronics Engineering: " + subjects[2][1]); }} Moreover, we can initialize each element of the array separately. Look at the code snippet below: Java import java.io.*;import java.util.*; class GFG { public static void main(String[] args) { int[][] scores = new int[2][2]; // Initializing array element at position[0][0], // i.e. 0th row and 0th column scores[0][0] = 15; // Initializing array element at position[0][1], // i.e. 0th row and 1st column scores[0][1] = 23; // Initializing array element at position[1][0], // i.e. 1st row and 0th column scores[1][0] = 30; // Initializing array element at position[1][1], // i.e. 1st row and 1st column scores[1][1] = 21; // printing the array elements individually System.out.println("scores[0][0] = " + scores[0][0]); System.out.println("scores[0][1] = " + scores[0][1]); System.out.println("scores[1][0] = " + scores[1][0]); System.out.println("scores[1][1] = " + scores[1][1]); // printing 2D array using Arrays.deepToString() method System.out.println( "Printing 2D array using Arrays.deepToString() method: "); System.out.println(Arrays.deepToString(scores)); }} Using the above approach for array initialization would be a tedious task if the size of the 2D array is too large. The efficient way is to use for loop for initializing the array elements in the case of a large 2D array. Java import java.io.*; class GFG { public static void main(String[] args) { int rows = 80, columns = 5; int[][] marks = new int[rows][columns]; // initializing the array elements using for loop for (int i = 0; i < rows; i++) { for (int j = 0; j < columns; j++) { marks[i][j] = i + j; } } // printing the first three rows of marks array System.out.println("First three rows are: "); for (int i = 0; i < 3; i++) { for (int j = 0; j < columns; j++) { System.out.printf(marks[i][j] + " "); } System.out.println(); } }} We can use arr. length can be used to find the size of the rows (1st dimension), and arr[0].length can be to find the size of the columns (2nd dimension). There may be a certain scenario where you want every row to a different number of columns. This type of array is called a Jagged Array. Java import java.io.*; class GFG { public static void main(String[] args) { // declaring a 2D array with 2 rows int jagged[][] = new int[2][]; // not specifying the 2nd dimension, // and making it as jagged array // first row has 2 columns jagged[0] = new int[2]; // second row has 2 columns jagged[1] = new int[4]; // Initializing the array int count = 0; for (int i = 0; i < jagged.length; i++) { // remember to use jagged[i].length instead of // jagged[0].length, since every row has // different number of columns for (int j = 0; j < jagged[i].length; j++) { jagged[i][j] = count++; } } // printing the values of 2D Jagged array System.out.println("The values of 2D jagged array"); for (int i = 0; i < jagged.length; i++) { for (int j = 0; j < jagged[i].length; j++) System.out.printf(jagged[i][j] + " "); System.out.println(); } }} Implementation: Let’s look at a simple program to add two 2D arrays: Java import java.io.*;import java.util.*; class GFG { public static void main(String[] args) { int[][] arr1 = { { 1, 2, 3 }, { 4, 5, 6 } }; int[][] arr2 = { { 4, 5, 6 }, { 1, 3, 2 } }; int[][] sum = new int[2][3]; // adding two 2D arrays element-wise for (int i = 0; i < arr1.length; i++) { for (int j = 0; j < arr1[0].length; j++) { sum[i][j] = arr1[i][j] + arr2[i][j]; } } System.out.println("Resultant 2D array: "); for (int i = 0; i < sum.length; i++) { System.out.println(Arrays.toString(sum[i])); } }} gabaa406 surindertarika1234 chhabradhanvi Java-Arrays Picked Technical Scripter 2020 Java Technical Scripter Java Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 53, "s": 25, "text": "\n29 Oct, 2021" }, { "code": null, "e": 740, "s": 53, "text": "An array with more than one dimension is known as a multi-dimensional array. The most commonly used multi-dimensional arrays are 2-D and 3-D arrays. We can say that any higher dimensional array is basically an array of arrays. A very common example of a 2D Array is Chess Board. A chessboard is a grid containing 64 1×1 square boxes. You can similarly visualize a 2D array. In a 2D array, every element is associated with a row number and column number. Accessing any element of the 2D array is similar to accessing the record of an Excel File using both row number and column number. 2D arrays are useful while implementing a Tic-Tac-Toe game, Chess, or even storing the image pixels. " }, { "code": null, "e": 792, "s": 740, "text": "Any 2-dimensional array can be declared as follows:" }, { "code": null, "e": 800, "s": 792, "text": "Syntax:" }, { "code": null, "e": 863, "s": 800, "text": "data_type array_name[][]; (OR) data_type[][] array_name;" }, { "code": null, "e": 1146, "s": 863, "text": "data_type: Since Java is a statically-typed language (i.e. it expects its variables to be declared before they can be assigned values). So, specifying the datatype decides the type of elements it will accept. e.g. to store integer values only, the data type will be declared as int." }, { "code": null, "e": 1255, "s": 1146, "text": "array_name: It is the name that is given to the 2-D array. e.g. subjects, students, fruits, department, etc." }, { "code": null, "e": 1367, "s": 1255, "text": "Note: We can write [ ][ ] after data_type or we can write [ ][ ] after array_name while declaring the 2D array." }, { "code": null, "e": 1372, "s": 1367, "text": "Java" }, { "code": "// java program showing declaration of arraysimport java.io.*; class GFG { public static void main(String[] args) { int[][] integer2DArray; // 2D integer array String[][] string2DArray; // 2D String array double[][] double2DArray; // 2D double array boolean[][] boolean2DArray; // 2D boolean array float[][] float2DArray; // 2D float array double[][] double2DArray; // 2D double array }}", "e": 1814, "s": 1372, "text": null }, { "code": null, "e": 1886, "s": 1817, "text": "data_type[][] array_Name = new data_type[no_of_rows][no_of_columns];" }, { "code": null, "e": 1972, "s": 1888, "text": "The total elements in any 2D array will be equal to (no_of_rows) * (no_of_columns)." }, { "code": null, "e": 2083, "s": 1974, "text": "no_of_rows: The number of rows an array can store. e.g. no_of_rows = 3, then the array will have three rows." }, { "code": null, "e": 2200, "s": 2083, "text": "no_of_columns: The number of rows an array can store. e.g. no_of_columns = 4, then the array will have four columns." }, { "code": null, "e": 2331, "s": 2202, "text": "The above syntax of array initialization will assign default values to all array elements according to the data type specified. " }, { "code": null, "e": 2390, "s": 2333, "text": "Let us see various approaches of initializing 2D arrays:" }, { "code": null, "e": 2399, "s": 2394, "text": "Java" }, { "code": "// java program to initialize a 2D arrayimport java.io.*; class GFG { public static void main(String[] args) { // Declaration along with initialization // 2D integer array with 5 rows and 3 columns // integer array elements are initialized with 0 int[][] integer2DArray = new int[5][3]; System.out.println( \"Default value of int array element: \" + integer2DArray[0][0]); // 2D String array with 4 rows and 4 columns // String array elements are initialized with null String[][] string2DArray = new String[4][4]; System.out.println( \"Default value of String array element: \" + string2DArray[0][0]); // 2D boolean array with 3 rows and 5 columns // boolean array elements are initialized with false boolean[][] boolean2DArray = new boolean[4][4]; System.out.println( \"Default value of boolean array element: \" + boolean2DArray[0][0]); // 2D char array with 10 rows and 10 columns // char array elements are initialized with // '\\u0000'(null character) char[][] char2DArray = new char[10][10]; System.out.println( \"Default value of char array element: \" + char2DArray[0][0]); // First declaration and then initialization int[][] arr; // declaration // System.out.println(\"arr[0][0]: \"+ arr[0][0]); // The above line will throw an error, as we have // only declared the 2D array, but not initialized // it. arr = new int[5][3]; // initialization System.out.println(\"arr[0][0]: \" + arr[0][0]); }}", "e": 4081, "s": 2399, "text": null }, { "code": null, "e": 4244, "s": 4081, "text": "Note: When you initialize a 2D array, you must always specify the first dimension(no. of rows), but providing the second dimension(no. of columns) may be omitted." }, { "code": null, "e": 4437, "s": 4244, "text": "In the code snippet below, we have not specified the number of columns. However, the Java compiler is smart enough to manipulate the size by checking the number of elements inside the columns." }, { "code": null, "e": 4442, "s": 4437, "text": "Java" }, { "code": "import java.io.*; class GFG { public static void main(String[] args) { // The line below will throw an error, as the first // dimension(no. of rows) is not specified int[][] arr = new int[][3]; // The line below will execute without any error, as // the first dimension(no. of rows) is specified int[][] arr = new int[2][]; }}", "e": 4823, "s": 4442, "text": null }, { "code": null, "e": 4900, "s": 4823, "text": "You can access any element of a 2D array using row number and column number." }, { "code": null, "e": 5111, "s": 4900, "text": "In the code snippet below, we have not specified the number of rows and columns. However, the Java compiler is smart enough to manipulate the size by checking the number of elements inside the rows and columns." }, { "code": null, "e": 5116, "s": 5111, "text": "Java" }, { "code": "import java.io.*; class GFG { public static void main(String[] args) { String[][] subjects = { { \"Data Structures & Algorithms\", \"Programming & Logic\", \"Software Engineering\", \"Theory of Computation\" }, // row 1 { \"Thermodynamics\", \"Metallurgy\", \"Machine Drawing\", \"Fluid Mechanics\" }, // row2 { \"Signals and Systems\", \"Digital Electronics\", \"Power Electronics\" } // row3 }; System.out.println( \"Fundamental Subject in Computer Engineering: \" + subjects[0][0]); System.out.println( \"Fundamental Subject in Mechanical Engineering: \" + subjects[1][3]); System.out.println( \"Fundamental Subject in Electronics Engineering: \" + subjects[2][1]); }}", "e": 6052, "s": 5116, "text": null }, { "code": null, "e": 6150, "s": 6052, "text": "Moreover, we can initialize each element of the array separately. Look at the code snippet below:" }, { "code": null, "e": 6155, "s": 6150, "text": "Java" }, { "code": "import java.io.*;import java.util.*; class GFG { public static void main(String[] args) { int[][] scores = new int[2][2]; // Initializing array element at position[0][0], // i.e. 0th row and 0th column scores[0][0] = 15; // Initializing array element at position[0][1], // i.e. 0th row and 1st column scores[0][1] = 23; // Initializing array element at position[1][0], // i.e. 1st row and 0th column scores[1][0] = 30; // Initializing array element at position[1][1], // i.e. 1st row and 1st column scores[1][1] = 21; // printing the array elements individually System.out.println(\"scores[0][0] = \" + scores[0][0]); System.out.println(\"scores[0][1] = \" + scores[0][1]); System.out.println(\"scores[1][0] = \" + scores[1][0]); System.out.println(\"scores[1][1] = \" + scores[1][1]); // printing 2D array using Arrays.deepToString() method System.out.println( \"Printing 2D array using Arrays.deepToString() method: \"); System.out.println(Arrays.deepToString(scores)); }}", "e": 7394, "s": 6155, "text": null }, { "code": null, "e": 7617, "s": 7394, "text": "Using the above approach for array initialization would be a tedious task if the size of the 2D array is too large. The efficient way is to use for loop for initializing the array elements in the case of a large 2D array. " }, { "code": null, "e": 7622, "s": 7617, "text": "Java" }, { "code": "import java.io.*; class GFG { public static void main(String[] args) { int rows = 80, columns = 5; int[][] marks = new int[rows][columns]; // initializing the array elements using for loop for (int i = 0; i < rows; i++) { for (int j = 0; j < columns; j++) { marks[i][j] = i + j; } } // printing the first three rows of marks array System.out.println(\"First three rows are: \"); for (int i = 0; i < 3; i++) { for (int j = 0; j < columns; j++) { System.out.printf(marks[i][j] + \" \"); } System.out.println(); } }}", "e": 8302, "s": 7622, "text": null }, { "code": null, "e": 8457, "s": 8302, "text": "We can use arr. length can be used to find the size of the rows (1st dimension), and arr[0].length can be to find the size of the columns (2nd dimension)." }, { "code": null, "e": 8593, "s": 8457, "text": "There may be a certain scenario where you want every row to a different number of columns. This type of array is called a Jagged Array." }, { "code": null, "e": 8598, "s": 8593, "text": "Java" }, { "code": "import java.io.*; class GFG { public static void main(String[] args) { // declaring a 2D array with 2 rows int jagged[][] = new int[2][]; // not specifying the 2nd dimension, // and making it as jagged array // first row has 2 columns jagged[0] = new int[2]; // second row has 2 columns jagged[1] = new int[4]; // Initializing the array int count = 0; for (int i = 0; i < jagged.length; i++) { // remember to use jagged[i].length instead of // jagged[0].length, since every row has // different number of columns for (int j = 0; j < jagged[i].length; j++) { jagged[i][j] = count++; } } // printing the values of 2D Jagged array System.out.println(\"The values of 2D jagged array\"); for (int i = 0; i < jagged.length; i++) { for (int j = 0; j < jagged[i].length; j++) System.out.printf(jagged[i][j] + \" \"); System.out.println(); } }}", "e": 9663, "s": 8598, "text": null }, { "code": null, "e": 9679, "s": 9663, "text": "Implementation:" }, { "code": null, "e": 9732, "s": 9679, "text": "Let’s look at a simple program to add two 2D arrays:" }, { "code": null, "e": 9737, "s": 9732, "text": "Java" }, { "code": "import java.io.*;import java.util.*; class GFG { public static void main(String[] args) { int[][] arr1 = { { 1, 2, 3 }, { 4, 5, 6 } }; int[][] arr2 = { { 4, 5, 6 }, { 1, 3, 2 } }; int[][] sum = new int[2][3]; // adding two 2D arrays element-wise for (int i = 0; i < arr1.length; i++) { for (int j = 0; j < arr1[0].length; j++) { sum[i][j] = arr1[i][j] + arr2[i][j]; } } System.out.println(\"Resultant 2D array: \"); for (int i = 0; i < sum.length; i++) { System.out.println(Arrays.toString(sum[i])); } }}", "e": 10373, "s": 9737, "text": null }, { "code": null, "e": 10382, "s": 10373, "text": "gabaa406" }, { "code": null, "e": 10401, "s": 10382, "text": "surindertarika1234" }, { "code": null, "e": 10415, "s": 10401, "text": "chhabradhanvi" }, { "code": null, "e": 10427, "s": 10415, "text": "Java-Arrays" }, { "code": null, "e": 10434, "s": 10427, "text": "Picked" }, { "code": null, "e": 10458, "s": 10434, "text": "Technical Scripter 2020" }, { "code": null, "e": 10463, "s": 10458, "text": "Java" }, { "code": null, "e": 10482, "s": 10463, "text": "Technical Scripter" }, { "code": null, "e": 10487, "s": 10482, "text": "Java" } ]
Mean Function in MATLAB
29 Jun, 2021 Mean or average is the average of a sequence of numbers. In MATLAB, mean (A) returns the mean of the components of A along the first array dimension whose size doesn’t equal to 1. Suppose that A is a vector, then mean(A) returns the mean of the components. Now, if A is a Matrix form, then mean(A) returns a row vector containing the mean of every column. Mean = Example: Mean of sequence x = [1,2,3,4,5] = Sum of numbers/Count of numbers = 15/5 = 3 Different syntax of the mean() method is: M = mean(A) M = mean(A,’all’) M = mean(A,dim) M = mean(A,vecdim) It returns the mean of sequence A. If A is a vector, then it returns the mean of all elements in the vector If A is a matrix, then it returns a vector where each element is the mean of each column in A. Example: Matlab % Input vectorA = [1 2 3 4 5];disp("Vector :");disp(A); % Find mean of vectorx = mean(A);disp("Mean :");disp(x); Output: Example: Matlab % Input matrixA = [1 1 2; 2 3 2; 0 1 2; 1 5 7];disp("Matrix :");disp(A); % Find mean of matrixx = mean(A);disp("Mean :");disp(x); Output : It returns the mean of all the elements in A either it can be vector or matrix. Example: Matlab % Input matrixA = [1 1 2; 2 3 2; 0 1 2; 1 5 7];disp("Matrix :");disp(A); % Find mean of whole matrixx = mean(A,'all');disp("Mean :");disp(x); Output : It returns the mean of matrix A along each of the given dim. If dim = 1, then it returns a vector where the mean of each column is included. If dim = 2, then it returns a vector where the mean of each row is included. Example: Matlab % Input matrixA = [1 1 2; 2 3 2; 0 1 2; 1 5 7];disp("Matrix :");disp(A); % Find mean of each row in matrixx = mean(A,2);disp("Mean :");disp(x); Output : It returns the mean of A based on the specified dimensions vecdim in A. If A is a 2-by-2-by-3 array, then mean(A,[1 2]) calculates the mean of each page of size 2-by-2 as it’s considered as a single entity. So it returns the vector of size 3 as the mean of each page. Example: Matlab % Creating a 2-by-3-by-3 arrayA(:,:,1) = [12 2; -1 1];A(:,:,2) = [3 13; -2 10];A(:,:,3) = [4 7 ; 3 -3];disp("Array :");disp(A); % Calculate mean of each pageM1 = mean(A,[1 2]);disp("Mean of each page :");disp(M1); Output: arorakashish0911 MATLAB-Maths Picked MATLAB Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n29 Jun, 2021" }, { "code": null, "e": 384, "s": 28, "text": "Mean or average is the average of a sequence of numbers. In MATLAB, mean (A) returns the mean of the components of A along the first array dimension whose size doesn’t equal to 1. Suppose that A is a vector, then mean(A) returns the mean of the components. Now, if A is a Matrix form, then mean(A) returns a row vector containing the mean of every column." }, { "code": null, "e": 394, "s": 384, "text": "Mean = " }, { "code": null, "e": 403, "s": 394, "text": "Example:" }, { "code": null, "e": 471, "s": 403, "text": "Mean of sequence x = [1,2,3,4,5] = Sum of numbers/Count of numbers" }, { "code": null, "e": 528, "s": 471, "text": " = 15/5" }, { "code": null, "e": 582, "s": 528, "text": " = 3" }, { "code": null, "e": 624, "s": 582, "text": "Different syntax of the mean() method is:" }, { "code": null, "e": 636, "s": 624, "text": "M = mean(A)" }, { "code": null, "e": 654, "s": 636, "text": "M = mean(A,’all’)" }, { "code": null, "e": 670, "s": 654, "text": "M = mean(A,dim)" }, { "code": null, "e": 689, "s": 670, "text": "M = mean(A,vecdim)" }, { "code": null, "e": 724, "s": 689, "text": "It returns the mean of sequence A." }, { "code": null, "e": 797, "s": 724, "text": "If A is a vector, then it returns the mean of all elements in the vector" }, { "code": null, "e": 892, "s": 797, "text": "If A is a matrix, then it returns a vector where each element is the mean of each column in A." }, { "code": null, "e": 901, "s": 892, "text": "Example:" }, { "code": null, "e": 908, "s": 901, "text": "Matlab" }, { "code": "% Input vectorA = [1 2 3 4 5];disp(\"Vector :\");disp(A); % Find mean of vectorx = mean(A);disp(\"Mean :\");disp(x);", "e": 1021, "s": 908, "text": null }, { "code": null, "e": 1033, "s": 1025, "text": "Output:" }, { "code": null, "e": 1046, "s": 1037, "text": "Example:" }, { "code": null, "e": 1055, "s": 1048, "text": "Matlab" }, { "code": "% Input matrixA = [1 1 2; 2 3 2; 0 1 2; 1 5 7];disp(\"Matrix :\");disp(A); % Find mean of matrixx = mean(A);disp(\"Mean :\");disp(x);", "e": 1185, "s": 1055, "text": null }, { "code": null, "e": 1194, "s": 1185, "text": "Output :" }, { "code": null, "e": 1274, "s": 1194, "text": "It returns the mean of all the elements in A either it can be vector or matrix." }, { "code": null, "e": 1283, "s": 1274, "text": "Example:" }, { "code": null, "e": 1290, "s": 1283, "text": "Matlab" }, { "code": "% Input matrixA = [1 1 2; 2 3 2; 0 1 2; 1 5 7];disp(\"Matrix :\");disp(A); % Find mean of whole matrixx = mean(A,'all');disp(\"Mean :\");disp(x);", "e": 1432, "s": 1290, "text": null }, { "code": null, "e": 1441, "s": 1432, "text": "Output :" }, { "code": null, "e": 1502, "s": 1441, "text": "It returns the mean of matrix A along each of the given dim." }, { "code": null, "e": 1582, "s": 1502, "text": "If dim = 1, then it returns a vector where the mean of each column is included." }, { "code": null, "e": 1659, "s": 1582, "text": "If dim = 2, then it returns a vector where the mean of each row is included." }, { "code": null, "e": 1668, "s": 1659, "text": "Example:" }, { "code": null, "e": 1675, "s": 1668, "text": "Matlab" }, { "code": "% Input matrixA = [1 1 2; 2 3 2; 0 1 2; 1 5 7];disp(\"Matrix :\");disp(A); % Find mean of each row in matrixx = mean(A,2);disp(\"Mean :\");disp(x);", "e": 1819, "s": 1675, "text": null }, { "code": null, "e": 1828, "s": 1819, "text": "Output :" }, { "code": null, "e": 1900, "s": 1828, "text": "It returns the mean of A based on the specified dimensions vecdim in A." }, { "code": null, "e": 2096, "s": 1900, "text": "If A is a 2-by-2-by-3 array, then mean(A,[1 2]) calculates the mean of each page of size 2-by-2 as it’s considered as a single entity. So it returns the vector of size 3 as the mean of each page." }, { "code": null, "e": 2105, "s": 2096, "text": "Example:" }, { "code": null, "e": 2112, "s": 2105, "text": "Matlab" }, { "code": "% Creating a 2-by-3-by-3 arrayA(:,:,1) = [12 2; -1 1];A(:,:,2) = [3 13; -2 10];A(:,:,3) = [4 7 ; 3 -3];disp(\"Array :\");disp(A); % Calculate mean of each pageM1 = mean(A,[1 2]);disp(\"Mean of each page :\");disp(M1);", "e": 2326, "s": 2112, "text": null }, { "code": null, "e": 2334, "s": 2326, "text": "Output:" }, { "code": null, "e": 2351, "s": 2334, "text": "arorakashish0911" }, { "code": null, "e": 2364, "s": 2351, "text": "MATLAB-Maths" }, { "code": null, "e": 2371, "s": 2364, "text": "Picked" }, { "code": null, "e": 2378, "s": 2371, "text": "MATLAB" } ]
SQL Joins
A JOIN clause is used to combine rows from two or more tables, based on a related column between them. Let's look at a selection from the "Orders" table: Then, look at a selection from the "Customers" table: Notice that the "CustomerID" column in the "Orders" table refers to the "CustomerID" in the "Customers" table. The relationship between the two tables above is the "CustomerID" column. Then, we can create the following SQL statement (that contains an INNER JOIN), that selects records that have matching values in both tables: and it will produce something like this: Here are the different types of the JOINs in SQL: (INNER) JOIN: Returns records that have matching values in both tables LEFT (OUTER) JOIN: Returns all records from the left table, and the matched records from the right table RIGHT (OUTER) JOIN: Returns all records from the right table, and the matched records from the left table FULL (OUTER) JOIN: Returns all records when there is a match in either left or right table Insert the missing parts in the JOIN clause to join the two tables Orders and Customers, using the CustomerID field in both tables as the relationship between the two tables. SELECT * FROM Orders LEFT JOIN Customers =; Start the Exercise We just launchedW3Schools videos Get certifiedby completinga course today! If you want to report an error, or if you want to make a suggestion, do not hesitate to send us an e-mail: [email protected] Your message has been sent to W3Schools.
[ { "code": null, "e": 104, "s": 0, "text": "A JOIN clause is used to combine rows from two or more tables, based on \na related column between them." }, { "code": null, "e": 155, "s": 104, "text": "Let's look at a selection from the \"Orders\" table:" }, { "code": null, "e": 209, "s": 155, "text": "Then, look at a selection from the \"Customers\" table:" }, { "code": null, "e": 396, "s": 209, "text": "Notice that the \"CustomerID\" column in the \"Orders\" table refers to the \n\"CustomerID\" in the \"Customers\" table. The relationship between the two tables above \nis the \"CustomerID\" column." }, { "code": null, "e": 540, "s": 396, "text": "Then, we can create the following SQL statement (that contains an \nINNER JOIN), \nthat selects records that have matching values in both tables:" }, { "code": null, "e": 581, "s": 540, "text": "and it will produce something like this:" }, { "code": null, "e": 631, "s": 581, "text": "Here are the different types of the JOINs in SQL:" }, { "code": null, "e": 702, "s": 631, "text": "(INNER) JOIN: Returns records that have matching values in both tables" }, { "code": null, "e": 807, "s": 702, "text": "LEFT (OUTER) JOIN: Returns all records from the left table, and the matched records from the right table" }, { "code": null, "e": 916, "s": 807, "text": "RIGHT (OUTER) JOIN: Returns all records from the right table, and the matched \n records from the left table" }, { "code": null, "e": 1010, "s": 916, "text": "FULL (OUTER) JOIN: Returns all records when there is a match in either left \n or right table" }, { "code": null, "e": 1194, "s": 1019, "text": "Insert the missing parts in the JOIN clause to join the two tables Orders and Customers,\nusing the CustomerID field in both tables as the relationship between the two tables." }, { "code": null, "e": 1239, "s": 1194, "text": "SELECT *\nFROM Orders\nLEFT JOIN Customers\n=;\n" }, { "code": null, "e": 1258, "s": 1239, "text": "Start the Exercise" }, { "code": null, "e": 1291, "s": 1258, "text": "We just launchedW3Schools videos" }, { "code": null, "e": 1333, "s": 1291, "text": "Get certifiedby completinga course today!" }, { "code": null, "e": 1440, "s": 1333, "text": "If you want to report an error, or if you want to make a suggestion, do not hesitate to send us an e-mail:" }, { "code": null, "e": 1459, "s": 1440, "text": "[email protected]" } ]
Cucumber - Ruby Testing
Ruby language has the following advantages − It is easy to understand. It is easy to understand. It is an object-oriented language. It is an object-oriented language. It is a powerful class library. It is a powerful class library. It has massive online support. It has massive online support. Following is the step-by-step process of how Cucumber works with Ruby. Step 1 − Install Ruby. Go to RubyInstaller download page. Go to RubyInstaller download page. Download the version best suited for your operating system (i.e. 32 or 64 bit). Download the version best suited for your operating system (i.e. 32 or 64 bit). Run the downloaded exe. Run the downloaded exe. During the installation, tick the option “Add Ruby...” and “Associate ...”, as shown in the following image. During the installation, tick the option “Add Ruby...” and “Associate ...”, as shown in the following image. Step 2 − Download and extract Dev kit. Go to RubyInstaller download page. Go to RubyInstaller download page. Download the Devkit version best suited for your operating system (i.e. 32 or 64 bit). Download the Devkit version best suited for your operating system (i.e. 32 or 64 bit). Extract the devkit at c:\Ruby\Devkit folder. Extract the devkit at c:\Ruby\Devkit folder. Open the command prompt. Open the command prompt. Inside the Ruby devkit, run the following command. Inside the Ruby devkit, run the following command. C:\Ruby\devkit> ruby dk.rb init C:\Ruby\devkit> ruby dk.rb install Step 3 − Install Cucumber and other Ruby gem. To install Cucumber, first update the current gem setup To install Cucumber, first update the current gem setup C:\Users\Admin> gem update –system Next, install the gems you need for Cucumber web testing. Next, install the gems you need for Cucumber web testing. C:\Users\Admin> gem install --no-ri --no-rdoc rspec C:\Users\Admin> gem install --no-ri --no-rdoc win32console C:\Users\Admin> gem install --no-ri --no-rdoc watir-webdriver C:\Users\Admin> gem install --no-ri --no-rdoc cucumber Run Cucumber Run Cucumber C:\Users\Admin\Documents>cucumber –init C:\Users\Admin\Documents>cucumber Step 4 − Install IDE – KOMODO. Go to the page http://www.activestate.com/komodo-ide/downloads Go to the page http://www.activestate.com/komodo-ide/downloads Download the free trial installer. Download the free trial installer. Double-click on the downloaded exe. Double-click on the downloaded exe. Follow the installation steps. Follow the installation steps. Finish the installation and open the IDE. Finish the installation and open the IDE. Step 5 − Install Watir − Go to command prompt and run the following command, "gem install watir" Step 6 − Install rspec − Go to command prompt and run the following command, "gem install rspec" Step 7 − Create feature file. Open KOMODO editor. Open KOMODO editor. Click on new file icon. Click on new file icon. Write the following text. Feature: Users must be able to search for content using Google. Scenario: Search for a term. Given I have entered "watir" into the query. When I click "search" Then I should see some results Write the following text. Feature: Users must be able to search for content using Google. Scenario: Search for a term. Given I have entered "watir" into the query. When I click "search" Then I should see some results Click save icon. Click save icon. Give the name as CucumberRuby.feature. Give the name as CucumberRuby.feature. Choose any folder, for example: “e:\WithRuby” Choose any folder, for example: “e:\WithRuby” Save the file. Save the file. Step 8 − Create step definition file. Open KOMODO editor. Open KOMODO editor. Click ‘New’ file icon. Click ‘New’ file icon. Write the following code. Write the following code. require "watir-webdriver" require "rspec/expectations" Given /^I have entered "([^"]*)" into the query$/ do |term| @browser ||= Watir::Browser.new :firefox @browser.goto "google.com" @browser.text_field(:name => "q").set term end When /^I click "([^"]*)"$/ do |button_name| @browser.button.click end Then /^I should see some results$/ do @browser.div(:id => "resultStats").wait_until_present @browser.div(:id => "resultStats").should exist @browser.close End Click save icon. Click save icon. Give the name as CucumberRuby.rb Give the name as CucumberRuby.rb Choose any folder for example: “e:\WithRuby” Choose any folder for example: “e:\WithRuby” Save the file. Save the file. Step 9 − Create the test file. Open KOMODO editor. Open KOMODO editor. Click on ‘New’ file icon. Click on ‘New’ file icon. Write the following code. Write the following code. require "rubygems" require "test/unit" require "watir-webdriver" class GoogleSearch < Test::Unit::TestCase def setup @browser ||= Watir::Browser.new :firefox end def teardown @browser.close end def test_search @browser.goto "google.com" @browser.text_field(:name => "q").set "watir" @browser.button.click @browser.div(:id => "resultStats").wait_until_present assert @browser.title == "watir - Google Search" end end Click Save icon. Click Save icon. Name the file as test.rb and choose any folder for example: “e:\WithRuby” Name the file as test.rb and choose any folder for example: “e:\WithRuby” Save the file. Save the file. Step 10 − Run the feature file. Go to command prompt. Go to command prompt. Go to directory e:\WithRuby Go to directory e:\WithRuby Run the following command. Run the following command. e:\With Ruby>ruby test.rb You will observe the following things upon execution − A web browser instance will open. A web browser instance will open. Google.com webpage will get loaded. Google.com webpage will get loaded. Search text watir will be entered. Search text watir will be entered. Search button will be placed. Search button will be placed. Search results shall be displayed on the webpage. Search results shall be displayed on the webpage. Browser instance will get closed. Browser instance will get closed. Print Add Notes Bookmark this page
[ { "code": null, "e": 2007, "s": 1962, "text": "Ruby language has the following advantages −" }, { "code": null, "e": 2033, "s": 2007, "text": "It is easy to understand." }, { "code": null, "e": 2059, "s": 2033, "text": "It is easy to understand." }, { "code": null, "e": 2094, "s": 2059, "text": "It is an object-oriented language." }, { "code": null, "e": 2129, "s": 2094, "text": "It is an object-oriented language." }, { "code": null, "e": 2161, "s": 2129, "text": "It is a powerful class library." }, { "code": null, "e": 2193, "s": 2161, "text": "It is a powerful class library." }, { "code": null, "e": 2224, "s": 2193, "text": "It has massive online support." }, { "code": null, "e": 2255, "s": 2224, "text": "It has massive online support." }, { "code": null, "e": 2326, "s": 2255, "text": "Following is the step-by-step process of how Cucumber works with Ruby." }, { "code": null, "e": 2349, "s": 2326, "text": "Step 1 − Install Ruby." }, { "code": null, "e": 2384, "s": 2349, "text": "Go to RubyInstaller download page." }, { "code": null, "e": 2419, "s": 2384, "text": "Go to RubyInstaller download page." }, { "code": null, "e": 2499, "s": 2419, "text": "Download the version best suited for your operating system (i.e. 32 or 64 bit)." }, { "code": null, "e": 2579, "s": 2499, "text": "Download the version best suited for your operating system (i.e. 32 or 64 bit)." }, { "code": null, "e": 2603, "s": 2579, "text": "Run the downloaded exe." }, { "code": null, "e": 2627, "s": 2603, "text": "Run the downloaded exe." }, { "code": null, "e": 2736, "s": 2627, "text": "During the installation, tick the option “Add Ruby...” and “Associate ...”, as shown in the following image." }, { "code": null, "e": 2845, "s": 2736, "text": "During the installation, tick the option “Add Ruby...” and “Associate ...”, as shown in the following image." }, { "code": null, "e": 2884, "s": 2845, "text": "Step 2 − Download and extract Dev kit." }, { "code": null, "e": 2919, "s": 2884, "text": "Go to RubyInstaller download page." }, { "code": null, "e": 2954, "s": 2919, "text": "Go to RubyInstaller download page." }, { "code": null, "e": 3041, "s": 2954, "text": "Download the Devkit version best suited for your operating system (i.e. 32 or 64 bit)." }, { "code": null, "e": 3128, "s": 3041, "text": "Download the Devkit version best suited for your operating system (i.e. 32 or 64 bit)." }, { "code": null, "e": 3173, "s": 3128, "text": "Extract the devkit at c:\\Ruby\\Devkit folder." }, { "code": null, "e": 3218, "s": 3173, "text": "Extract the devkit at c:\\Ruby\\Devkit folder." }, { "code": null, "e": 3243, "s": 3218, "text": "Open the command prompt." }, { "code": null, "e": 3268, "s": 3243, "text": "Open the command prompt." }, { "code": null, "e": 3319, "s": 3268, "text": "Inside the Ruby devkit, run the following command." }, { "code": null, "e": 3370, "s": 3319, "text": "Inside the Ruby devkit, run the following command." }, { "code": null, "e": 3439, "s": 3370, "text": "C:\\Ruby\\devkit> ruby dk.rb init \nC:\\Ruby\\devkit> ruby dk.rb install\n" }, { "code": null, "e": 3485, "s": 3439, "text": "Step 3 − Install Cucumber and other Ruby gem." }, { "code": null, "e": 3541, "s": 3485, "text": "To install Cucumber, first update the current gem setup" }, { "code": null, "e": 3597, "s": 3541, "text": "To install Cucumber, first update the current gem setup" }, { "code": null, "e": 3633, "s": 3597, "text": "C:\\Users\\Admin> gem update –system\n" }, { "code": null, "e": 3691, "s": 3633, "text": "Next, install the gems you need for Cucumber web testing." }, { "code": null, "e": 3749, "s": 3691, "text": "Next, install the gems you need for Cucumber web testing." }, { "code": null, "e": 3981, "s": 3749, "text": "C:\\Users\\Admin> gem install --no-ri --no-rdoc rspec \nC:\\Users\\Admin> gem install --no-ri --no-rdoc win32console \nC:\\Users\\Admin> gem install --no-ri --no-rdoc watir-webdriver \nC:\\Users\\Admin> gem install --no-ri --no-rdoc cucumber\n" }, { "code": null, "e": 3994, "s": 3981, "text": "Run Cucumber" }, { "code": null, "e": 4007, "s": 3994, "text": "Run Cucumber" }, { "code": null, "e": 4083, "s": 4007, "text": "C:\\Users\\Admin\\Documents>cucumber –init \nC:\\Users\\Admin\\Documents>cucumber\n" }, { "code": null, "e": 4114, "s": 4083, "text": "Step 4 − Install IDE – KOMODO." }, { "code": null, "e": 4177, "s": 4114, "text": "Go to the page http://www.activestate.com/komodo-ide/downloads" }, { "code": null, "e": 4240, "s": 4177, "text": "Go to the page http://www.activestate.com/komodo-ide/downloads" }, { "code": null, "e": 4275, "s": 4240, "text": "Download the free trial installer." }, { "code": null, "e": 4310, "s": 4275, "text": "Download the free trial installer." }, { "code": null, "e": 4346, "s": 4310, "text": "Double-click on the downloaded exe." }, { "code": null, "e": 4382, "s": 4346, "text": "Double-click on the downloaded exe." }, { "code": null, "e": 4413, "s": 4382, "text": "Follow the installation steps." }, { "code": null, "e": 4444, "s": 4413, "text": "Follow the installation steps." }, { "code": null, "e": 4486, "s": 4444, "text": "Finish the installation and open the IDE." }, { "code": null, "e": 4528, "s": 4486, "text": "Finish the installation and open the IDE." }, { "code": null, "e": 4625, "s": 4528, "text": "Step 5 − Install Watir − Go to command prompt and run the following command, \"gem install watir\"" }, { "code": null, "e": 4722, "s": 4625, "text": "Step 6 − Install rspec − Go to command prompt and run the following command, \"gem install rspec\"" }, { "code": null, "e": 4752, "s": 4722, "text": "Step 7 − Create feature file." }, { "code": null, "e": 4772, "s": 4752, "text": "Open KOMODO editor." }, { "code": null, "e": 4792, "s": 4772, "text": "Open KOMODO editor." }, { "code": null, "e": 4816, "s": 4792, "text": "Click on new file icon." }, { "code": null, "e": 4840, "s": 4816, "text": "Click on new file icon." }, { "code": null, "e": 5057, "s": 4840, "text": "Write the following text.\nFeature: Users must be able to search for content using Google.\nScenario: Search for a term.\nGiven I have entered \"watir\" into the query.\nWhen I click \"search\"\nThen I should see some results" }, { "code": null, "e": 5083, "s": 5057, "text": "Write the following text." }, { "code": null, "e": 5147, "s": 5083, "text": "Feature: Users must be able to search for content using Google." }, { "code": null, "e": 5176, "s": 5147, "text": "Scenario: Search for a term." }, { "code": null, "e": 5221, "s": 5176, "text": "Given I have entered \"watir\" into the query." }, { "code": null, "e": 5243, "s": 5221, "text": "When I click \"search\"" }, { "code": null, "e": 5274, "s": 5243, "text": "Then I should see some results" }, { "code": null, "e": 5291, "s": 5274, "text": "Click save icon." }, { "code": null, "e": 5308, "s": 5291, "text": "Click save icon." }, { "code": null, "e": 5347, "s": 5308, "text": "Give the name as CucumberRuby.feature." }, { "code": null, "e": 5386, "s": 5347, "text": "Give the name as CucumberRuby.feature." }, { "code": null, "e": 5432, "s": 5386, "text": "Choose any folder, for example: “e:\\WithRuby”" }, { "code": null, "e": 5478, "s": 5432, "text": "Choose any folder, for example: “e:\\WithRuby”" }, { "code": null, "e": 5493, "s": 5478, "text": "Save the file." }, { "code": null, "e": 5508, "s": 5493, "text": "Save the file." }, { "code": null, "e": 5546, "s": 5508, "text": "Step 8 − Create step definition file." }, { "code": null, "e": 5566, "s": 5546, "text": "Open KOMODO editor." }, { "code": null, "e": 5586, "s": 5566, "text": "Open KOMODO editor." }, { "code": null, "e": 5609, "s": 5586, "text": "Click ‘New’ file icon." }, { "code": null, "e": 5632, "s": 5609, "text": "Click ‘New’ file icon." }, { "code": null, "e": 5658, "s": 5632, "text": "Write the following code." }, { "code": null, "e": 5684, "s": 5658, "text": "Write the following code." }, { "code": null, "e": 6160, "s": 5684, "text": "require \"watir-webdriver\" \nrequire \"rspec/expectations\" \n\nGiven /^I have entered \"([^\"]*)\" into the query$/ do |term| \n@browser ||= Watir::Browser.new :firefox \[email protected] \"google.com\" \[email protected]_field(:name => \"q\").set term \nend \n\nWhen /^I click \"([^\"]*)\"$/ do |button_name| \[email protected] \nend \n\nThen /^I should see some results$/ do \[email protected](:id => \"resultStats\").wait_until_present \[email protected](:id => \"resultStats\").should exist \[email protected] \nEnd" }, { "code": null, "e": 6177, "s": 6160, "text": "Click save icon." }, { "code": null, "e": 6194, "s": 6177, "text": "Click save icon." }, { "code": null, "e": 6227, "s": 6194, "text": "Give the name as CucumberRuby.rb" }, { "code": null, "e": 6260, "s": 6227, "text": "Give the name as CucumberRuby.rb" }, { "code": null, "e": 6305, "s": 6260, "text": "Choose any folder for example: “e:\\WithRuby”" }, { "code": null, "e": 6350, "s": 6305, "text": "Choose any folder for example: “e:\\WithRuby”" }, { "code": null, "e": 6365, "s": 6350, "text": "Save the file." }, { "code": null, "e": 6380, "s": 6365, "text": "Save the file." }, { "code": null, "e": 6411, "s": 6380, "text": "Step 9 − Create the test file." }, { "code": null, "e": 6431, "s": 6411, "text": "Open KOMODO editor." }, { "code": null, "e": 6451, "s": 6431, "text": "Open KOMODO editor." }, { "code": null, "e": 6477, "s": 6451, "text": "Click on ‘New’ file icon." }, { "code": null, "e": 6503, "s": 6477, "text": "Click on ‘New’ file icon." }, { "code": null, "e": 6529, "s": 6503, "text": "Write the following code." }, { "code": null, "e": 6555, "s": 6529, "text": "Write the following code." }, { "code": null, "e": 6991, "s": 6555, "text": "require \"rubygems\" \nrequire \"test/unit\" \nrequire \"watir-webdriver\" \n\nclass GoogleSearch < Test::Unit::TestCase \ndef setup \n@browser ||= Watir::Browser.new :firefox \nend \n\ndef teardown \[email protected] \nend \n\ndef test_search \[email protected] \"google.com\" \[email protected]_field(:name => \"q\").set \"watir\" \[email protected] \[email protected](:id => \"resultStats\").wait_until_present assert \[email protected] == \"watir - Google Search\" \nend \nend" }, { "code": null, "e": 7008, "s": 6991, "text": "Click Save icon." }, { "code": null, "e": 7025, "s": 7008, "text": "Click Save icon." }, { "code": null, "e": 7099, "s": 7025, "text": "Name the file as test.rb and choose any folder for example: “e:\\WithRuby”" }, { "code": null, "e": 7173, "s": 7099, "text": "Name the file as test.rb and choose any folder for example: “e:\\WithRuby”" }, { "code": null, "e": 7188, "s": 7173, "text": "Save the file." }, { "code": null, "e": 7203, "s": 7188, "text": "Save the file." }, { "code": null, "e": 7235, "s": 7203, "text": "Step 10 − Run the feature file." }, { "code": null, "e": 7257, "s": 7235, "text": "Go to command prompt." }, { "code": null, "e": 7279, "s": 7257, "text": "Go to command prompt." }, { "code": null, "e": 7307, "s": 7279, "text": "Go to directory e:\\WithRuby" }, { "code": null, "e": 7335, "s": 7307, "text": "Go to directory e:\\WithRuby" }, { "code": null, "e": 7362, "s": 7335, "text": "Run the following command." }, { "code": null, "e": 7389, "s": 7362, "text": "Run the following command." }, { "code": null, "e": 7416, "s": 7389, "text": "e:\\With Ruby>ruby test.rb\n" }, { "code": null, "e": 7471, "s": 7416, "text": "You will observe the following things upon execution −" }, { "code": null, "e": 7505, "s": 7471, "text": "A web browser instance will open." }, { "code": null, "e": 7539, "s": 7505, "text": "A web browser instance will open." }, { "code": null, "e": 7575, "s": 7539, "text": "Google.com webpage will get loaded." }, { "code": null, "e": 7611, "s": 7575, "text": "Google.com webpage will get loaded." }, { "code": null, "e": 7646, "s": 7611, "text": "Search text watir will be entered." }, { "code": null, "e": 7681, "s": 7646, "text": "Search text watir will be entered." }, { "code": null, "e": 7711, "s": 7681, "text": "Search button will be placed." }, { "code": null, "e": 7741, "s": 7711, "text": "Search button will be placed." }, { "code": null, "e": 7791, "s": 7741, "text": "Search results shall be displayed on the webpage." }, { "code": null, "e": 7841, "s": 7791, "text": "Search results shall be displayed on the webpage." }, { "code": null, "e": 7875, "s": 7841, "text": "Browser instance will get closed." }, { "code": null, "e": 7909, "s": 7875, "text": "Browser instance will get closed." }, { "code": null, "e": 7916, "s": 7909, "text": " Print" }, { "code": null, "e": 7927, "s": 7916, "text": " Add Notes" } ]
Evaluating Model Performance
To evaluate the model performance, we call evaluate method as follows − loss_and_metrics = model.evaluate(X_test, Y_test, verbose=2) To evaluate the model performance, we call evaluate method as follows − loss_and_metrics = model.evaluate(X_test, Y_test, verbose=2) We will print the loss and accuracy using the following two statements − print("Test Loss", loss_and_metrics[0]) print("Test Accuracy", loss_and_metrics[1]) When you run the above statements, you would see the following output − Test Loss 0.08041584826191042 Test Accuracy 0.9837 This shows a test accuracy of 98%, which should be acceptable to us. What it means to us that in 2% of the cases, the handwritten digits would not be classified correctly. We will also plot accuracy and loss metrics to see how the model performs on the test data. We use the recorded history during our training to get a plot of accuracy metrics. The following code will plot the accuracy on each epoch. We pick up the training data accuracy (“acc”) and the validation data accuracy (“val_acc”) for plotting. plot.subplot(2,1,1) plot.plot(history.history['acc']) plot.plot(history.history['val_acc']) plot.title('model accuracy') plot.ylabel('accuracy') plot.xlabel('epoch') plot.legend(['train', 'test'], loc='lower right') The output plot is shown below − As you can see in the diagram, the accuracy increases rapidly in the first two epochs, indicating that the network is learning fast. Afterwards, the curve flattens indicating that not too many epochs are required to train the model further. Generally, if the training data accuracy (“acc”) keeps improving while the validation data accuracy (“val_acc”) gets worse, you are encountering overfitting. It indicates that the model is starting to memorize the data. We will also plot the loss metrics to check our model’s performance. Again, we plot the loss on both the training (“loss”) and test (“val_loss”) data. This is done using the following code − plot.subplot(2,1,2) plot.plot(history.history['loss']) plot.plot(history.history['val_loss']) plot.title('model loss') plot.ylabel('loss') plot.xlabel('epoch') plot.legend(['train', 'test'], loc='upper right') The output of this code is shown below − As you can see in the diagram, the loss on the training set decreases rapidly for the first two epochs. For the test set, the loss does not decrease at the same rate as the training set, but remains almost flat for multiple epochs. This means our model is generalizing well to unseen data. Now, we will use our trained model to predict the digits in our test data. 87 Lectures 11 hours Abhilash Nelson 106 Lectures 13.5 hours Abhilash Nelson 28 Lectures 4 hours Abhilash Nelson 58 Lectures 8 hours Soumyadeep Dey 59 Lectures 2.5 hours Mike West 128 Lectures 5.5 hours TELCOMA Global Print Add Notes Bookmark this page
[ { "code": null, "e": 2031, "s": 1959, "text": "To evaluate the model performance, we call evaluate method as follows −" }, { "code": null, "e": 2092, "s": 2031, "text": "loss_and_metrics = model.evaluate(X_test, Y_test, verbose=2)" }, { "code": null, "e": 2164, "s": 2092, "text": "To evaluate the model performance, we call evaluate method as follows −" }, { "code": null, "e": 2226, "s": 2164, "text": "loss_and_metrics = model.evaluate(X_test, Y_test, verbose=2)\n" }, { "code": null, "e": 2299, "s": 2226, "text": "We will print the loss and accuracy using the following two statements −" }, { "code": null, "e": 2384, "s": 2299, "text": "print(\"Test Loss\", loss_and_metrics[0])\nprint(\"Test Accuracy\", loss_and_metrics[1])\n" }, { "code": null, "e": 2456, "s": 2384, "text": "When you run the above statements, you would see the following output −" }, { "code": null, "e": 2508, "s": 2456, "text": "Test Loss 0.08041584826191042\nTest Accuracy 0.9837\n" }, { "code": null, "e": 2772, "s": 2508, "text": "This shows a test accuracy of 98%, which should be acceptable to us. What it means to us that in 2% of the cases, the handwritten digits would not be classified correctly. We will also plot accuracy and loss metrics to see how the model performs on the test data." }, { "code": null, "e": 3017, "s": 2772, "text": "We use the recorded history during our training to get a plot of accuracy metrics. The following code will plot the accuracy on each epoch. We pick up the training data accuracy (“acc”) and the validation data accuracy (“val_acc”) for plotting." }, { "code": null, "e": 3233, "s": 3017, "text": "plot.subplot(2,1,1)\nplot.plot(history.history['acc'])\nplot.plot(history.history['val_acc'])\nplot.title('model accuracy')\nplot.ylabel('accuracy')\nplot.xlabel('epoch')\nplot.legend(['train', 'test'], loc='lower right')" }, { "code": null, "e": 3266, "s": 3233, "text": "The output plot is shown below −" }, { "code": null, "e": 3727, "s": 3266, "text": "As you can see in the diagram, the accuracy increases rapidly in the first two epochs, indicating that the network is learning fast. Afterwards, the curve flattens indicating that not too many epochs are required to train the model further. Generally, if the training data accuracy (“acc”) keeps improving while the validation data accuracy (“val_acc”) gets worse, you are encountering overfitting. It indicates that the model is starting to memorize the data." }, { "code": null, "e": 3796, "s": 3727, "text": "We will also plot the loss metrics to check our model’s performance." }, { "code": null, "e": 3918, "s": 3796, "text": "Again, we plot the loss on both the training (“loss”) and test (“val_loss”) data. This is done using the following code −" }, { "code": null, "e": 4128, "s": 3918, "text": "plot.subplot(2,1,2)\nplot.plot(history.history['loss'])\nplot.plot(history.history['val_loss'])\nplot.title('model loss')\nplot.ylabel('loss')\nplot.xlabel('epoch')\nplot.legend(['train', 'test'], loc='upper right')" }, { "code": null, "e": 4169, "s": 4128, "text": "The output of this code is shown below −" }, { "code": null, "e": 4459, "s": 4169, "text": "As you can see in the diagram, the loss on the training set decreases rapidly for the first two epochs. For the test set, the loss does not decrease at the same rate as the training set, but remains almost flat for multiple epochs. This means our model is generalizing well to unseen data." }, { "code": null, "e": 4534, "s": 4459, "text": "Now, we will use our trained model to predict the digits in our test data." }, { "code": null, "e": 4568, "s": 4534, "text": "\n 87 Lectures \n 11 hours \n" }, { "code": null, "e": 4585, "s": 4568, "text": " Abhilash Nelson" }, { "code": null, "e": 4622, "s": 4585, "text": "\n 106 Lectures \n 13.5 hours \n" }, { "code": null, "e": 4639, "s": 4622, "text": " Abhilash Nelson" }, { "code": null, "e": 4672, "s": 4639, "text": "\n 28 Lectures \n 4 hours \n" }, { "code": null, "e": 4689, "s": 4672, "text": " Abhilash Nelson" }, { "code": null, "e": 4722, "s": 4689, "text": "\n 58 Lectures \n 8 hours \n" }, { "code": null, "e": 4738, "s": 4722, "text": " Soumyadeep Dey" }, { "code": null, "e": 4773, "s": 4738, "text": "\n 59 Lectures \n 2.5 hours \n" }, { "code": null, "e": 4784, "s": 4773, "text": " Mike West" }, { "code": null, "e": 4820, "s": 4784, "text": "\n 128 Lectures \n 5.5 hours \n" }, { "code": null, "e": 4836, "s": 4820, "text": " TELCOMA Global" }, { "code": null, "e": 4843, "s": 4836, "text": " Print" }, { "code": null, "e": 4854, "s": 4843, "text": " Add Notes" } ]
Describe pass by value and pass by reference in JavaScript?
In pass by value, a function is called by directly passing the value of the variable as the argument. Changing the argument inside the function doesn’t affect the variable passed from outside the function. Javascript always pass by value so changing the value of the variable never changes the underlying primitive (String or number). In the following example, variable 'a' has assigned value 1. But inside function 'change' it got assigned with value 2. Since javascript is always a pass by value, the displayed output will be '1' but not '2'. Live Demo <html> <body> <script> let a = 1; let change = (val) => { val = 2 } change(a); document.write(a); </script> </body> </html> 1 There are some instances that address is passed instead of arguments to call a function. At that time, changing the value inside the function affect the variable passed from outside the function. This is called a pass by reference. In javascript mostly arrays and objects follow pass by reference. In the following example an object named 'a' is declared outside the function 'change'. Here one should heed that variable 'a' got mutated but not assigned with value 2, as shown in example 2. A pass by reference takes place when mutation has occurred. Live Demo <html> <body> <script> let a = {num:1}; let change = (val) => { val.num = 2 } change(a); document.write(JSON.stringify(a)); </script> </body> </html> {"num":2} In the following example instead of mutation, variable 'a' got assigned with value 2. So pass by value takes place and there will be no affect on outside variable. Live Demo <html> <body> <script> let a = {num : 1}; let change = (val) => { val = {num :2}; } change(a); document.write(JSON.stringify(a)); </script> </body> </html> {"num":1}
[ { "code": null, "e": 1397, "s": 1062, "text": "In pass by value, a function is called by directly passing the value of the variable as the argument. Changing the argument inside the function doesn’t affect the variable passed from outside the function. Javascript always pass by value so changing the value of the variable never changes the underlying primitive (String or number)." }, { "code": null, "e": 1607, "s": 1397, "text": "In the following example, variable 'a' has assigned value 1. But inside function 'change' it got assigned with value 2. Since javascript is always a pass by value, the displayed output will be '1' but not '2'." }, { "code": null, "e": 1617, "s": 1607, "text": "Live Demo" }, { "code": null, "e": 1762, "s": 1617, "text": "<html>\n<body>\n<script>\n let a = 1;\n let change = (val) => {\n val = 2\n }\n change(a);\n document.write(a);\n</script>\n</body>\n</html>" }, { "code": null, "e": 1764, "s": 1762, "text": "1" }, { "code": null, "e": 2062, "s": 1764, "text": "There are some instances that address is passed instead of arguments to call a function. At that time, changing the value inside the function affect the variable passed from outside the function. This is called a pass by reference. In javascript mostly arrays and objects follow pass by reference." }, { "code": null, "e": 2318, "s": 2062, "text": "In the following example an object named 'a' is declared outside the function 'change'. Here one should heed that variable 'a' got mutated but not assigned with value 2, as shown in example 2. A pass by reference takes place when mutation has occurred. " }, { "code": null, "e": 2328, "s": 2318, "text": "Live Demo" }, { "code": null, "e": 2498, "s": 2328, "text": "<html>\n<body>\n<script>\n let a = {num:1};\n let change = (val) => {\n val.num = 2\n }\n change(a);\n document.write(JSON.stringify(a));\n</script>\n</body>\n</html>" }, { "code": null, "e": 2508, "s": 2498, "text": "{\"num\":2}" }, { "code": null, "e": 2672, "s": 2508, "text": "In the following example instead of mutation, variable 'a' got assigned with value 2. So pass by value takes place and there will be no affect on outside variable." }, { "code": null, "e": 2682, "s": 2672, "text": "Live Demo" }, { "code": null, "e": 2859, "s": 2682, "text": "<html>\n<body>\n<script>\n let a = {num : 1};\n let change = (val) => {\n val = {num :2};\n }\n change(a);\n document.write(JSON.stringify(a));\n</script>\n</body>\n</html>" }, { "code": null, "e": 2869, "s": 2859, "text": "{\"num\":1}" } ]
PyQt5 - Different border color to lineedit part on mouse hover (for non editable Combobox) - GeeksforGeeks
06 May, 2020 In this article we will see how we can set different border color to the line edit part of the combo box when mouse hover over the line edit part, line edit is the part of combo box which displays the selected item, it is editable by nature. In order to set and access the line edit object we use setLineEdit and lineEdit method respectively. Note : When we create line edit object it make the combo box editable. In order to do this we have to do the following : 1. Create a combo box2. Add item to the combo box3. Create a QLineEdit object4. Set border to the QLineEdit object5. Set border with different color when mouse hover over it6. Make line edit object non-editable(read-only)7. Add QLineEdit object to the combo box Below is the implementation # importing librariesfrom PyQt5.QtWidgets import * from PyQt5 import QtCore, QtGuifrom PyQt5.QtGui import * from PyQt5.QtCore import * import sys class Window(QMainWindow): def __init__(self): super().__init__() # setting title self.setWindowTitle("Python ") # setting geometry self.setGeometry(100, 100, 600, 400) # calling method self.UiComponents() # showing all the widgets self.show() # method for widgets def UiComponents(self): # creating a check-able combo box object self.combo_box = QComboBox(self) # setting geometry of combo box self.combo_box.setGeometry(200, 150, 150, 80) # geek list geek_list = ["Sayian", "Super Sayian", "Super Sayian 2", "Super Sayian B"] # adding list of items to combo box self.combo_box.addItems(geek_list) # creating line edit object line_edit = QLineEdit() # setting border to the line edit part # set different border color when mouse hover over it line_edit.setStyleSheet("QLineEdit" "{" "border : 5px solid black;" "}" "QLineEdit::hover" "{" "border-color : red green blue yellow" "}") # making line edit object read only line_edit.setReadOnly(True) # adding line edit object to the combo box self.combo_box.setLineEdit(line_edit) # create pyqt5 appApp = QApplication(sys.argv) # create the instance of our Windowwindow = Window() # start the appsys.exit(App.exec()) Output : Python PyQt5-ComboBox Python PyQt5-ComboBox-stylesheet Python-gui Python-PyQt Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Python Dictionary Read a file line by line in Python Enumerate() in Python How to Install PIP on Windows ? Iterate over a list in Python Different ways to create Pandas Dataframe Python String | replace() Create a Pandas DataFrame from Lists Python program to convert a list to string Reading and Writing to text files in Python
[ { "code": null, "e": 25086, "s": 25058, "text": "\n06 May, 2020" }, { "code": null, "e": 25429, "s": 25086, "text": "In this article we will see how we can set different border color to the line edit part of the combo box when mouse hover over the line edit part, line edit is the part of combo box which displays the selected item, it is editable by nature. In order to set and access the line edit object we use setLineEdit and lineEdit method respectively." }, { "code": null, "e": 25500, "s": 25429, "text": "Note : When we create line edit object it make the combo box editable." }, { "code": null, "e": 25550, "s": 25500, "text": "In order to do this we have to do the following :" }, { "code": null, "e": 25812, "s": 25550, "text": "1. Create a combo box2. Add item to the combo box3. Create a QLineEdit object4. Set border to the QLineEdit object5. Set border with different color when mouse hover over it6. Make line edit object non-editable(read-only)7. Add QLineEdit object to the combo box" }, { "code": null, "e": 25840, "s": 25812, "text": "Below is the implementation" }, { "code": "# importing librariesfrom PyQt5.QtWidgets import * from PyQt5 import QtCore, QtGuifrom PyQt5.QtGui import * from PyQt5.QtCore import * import sys class Window(QMainWindow): def __init__(self): super().__init__() # setting title self.setWindowTitle(\"Python \") # setting geometry self.setGeometry(100, 100, 600, 400) # calling method self.UiComponents() # showing all the widgets self.show() # method for widgets def UiComponents(self): # creating a check-able combo box object self.combo_box = QComboBox(self) # setting geometry of combo box self.combo_box.setGeometry(200, 150, 150, 80) # geek list geek_list = [\"Sayian\", \"Super Sayian\", \"Super Sayian 2\", \"Super Sayian B\"] # adding list of items to combo box self.combo_box.addItems(geek_list) # creating line edit object line_edit = QLineEdit() # setting border to the line edit part # set different border color when mouse hover over it line_edit.setStyleSheet(\"QLineEdit\" \"{\" \"border : 5px solid black;\" \"}\" \"QLineEdit::hover\" \"{\" \"border-color : red green blue yellow\" \"}\") # making line edit object read only line_edit.setReadOnly(True) # adding line edit object to the combo box self.combo_box.setLineEdit(line_edit) # create pyqt5 appApp = QApplication(sys.argv) # create the instance of our Windowwindow = Window() # start the appsys.exit(App.exec())", "e": 27590, "s": 25840, "text": null }, { "code": null, "e": 27599, "s": 27590, "text": "Output :" }, { "code": null, "e": 27621, "s": 27599, "text": "Python PyQt5-ComboBox" }, { "code": null, "e": 27654, "s": 27621, "text": "Python PyQt5-ComboBox-stylesheet" }, { "code": null, "e": 27665, "s": 27654, "text": "Python-gui" }, { "code": null, "e": 27677, "s": 27665, "text": "Python-PyQt" }, { "code": null, "e": 27684, "s": 27677, "text": "Python" }, { "code": null, "e": 27782, "s": 27684, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 27800, "s": 27782, "text": "Python Dictionary" }, { "code": null, "e": 27835, "s": 27800, "text": "Read a file line by line in Python" }, { "code": null, "e": 27857, "s": 27835, "text": "Enumerate() in Python" }, { "code": null, "e": 27889, "s": 27857, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 27919, "s": 27889, "text": "Iterate over a list in Python" }, { "code": null, "e": 27961, "s": 27919, "text": "Different ways to create Pandas Dataframe" }, { "code": null, "e": 27987, "s": 27961, "text": "Python String | replace()" }, { "code": null, "e": 28024, "s": 27987, "text": "Create a Pandas DataFrame from Lists" }, { "code": null, "e": 28067, "s": 28024, "text": "Python program to convert a list to string" } ]
Program to find lexicographically smallest subsequence of size k in Python
Suppose we have a list of numbers called nums and another value k, we have to find the lexicographically smallest subsequence of size k. So, if the input is like nums = [2, 3, 1, 10, 3, 4] k = 3, then the output will be [1, 3, 4] To solve this, we will follow these steps − l := size of nums, r := k - 1 out := a new list for j in range 0 to k, domn := nums[complement of r]for i in range r to l, doif mn >= nums[complement of i], thenmn := nums[complement of i]l := ir := r - 1 mn := nums[complement of r] for i in range r to l, doif mn >= nums[complement of i], thenmn := nums[complement of i]l := i if mn >= nums[complement of i], thenmn := nums[complement of i]l := i mn := nums[complement of i] l := i r := r - 1 insert mn at the end of out return out Let us see the following implementation to get better understanding − Live Demo class Solution: def solve(self, nums, k): l, r = len(nums), k - 1 out = [] for j in range(k): mn = nums[~r] for i in range(r, l): if mn >= nums[~i]: mn = nums[~i] l = i r -= 1 out.append(mn) return out ob = Solution() nums = [2, 3, 1, 10, 3, 4] k = 3 print(ob.solve(nums, k)) [2, 3, 1, 10, 3, 4], 3 [1, 3, 4]
[ { "code": null, "e": 1199, "s": 1062, "text": "Suppose we have a list of numbers called nums and another value k, we have to find the lexicographically smallest subsequence of size k." }, { "code": null, "e": 1292, "s": 1199, "text": "So, if the input is like nums = [2, 3, 1, 10, 3, 4] k = 3, then the output will be [1, 3, 4]" }, { "code": null, "e": 1336, "s": 1292, "text": "To solve this, we will follow these steps −" }, { "code": null, "e": 1366, "s": 1336, "text": "l := size of nums, r := k - 1" }, { "code": null, "e": 1384, "s": 1366, "text": "out := a new list" }, { "code": null, "e": 1541, "s": 1384, "text": "for j in range 0 to k, domn := nums[complement of r]for i in range r to l, doif mn >= nums[complement of i], thenmn := nums[complement of i]l := ir := r - 1" }, { "code": null, "e": 1569, "s": 1541, "text": "mn := nums[complement of r]" }, { "code": null, "e": 1664, "s": 1569, "text": "for i in range r to l, doif mn >= nums[complement of i], thenmn := nums[complement of i]l := i" }, { "code": null, "e": 1734, "s": 1664, "text": "if mn >= nums[complement of i], thenmn := nums[complement of i]l := i" }, { "code": null, "e": 1762, "s": 1734, "text": "mn := nums[complement of i]" }, { "code": null, "e": 1769, "s": 1762, "text": "l := i" }, { "code": null, "e": 1780, "s": 1769, "text": "r := r - 1" }, { "code": null, "e": 1808, "s": 1780, "text": "insert mn at the end of out" }, { "code": null, "e": 1819, "s": 1808, "text": "return out" }, { "code": null, "e": 1889, "s": 1819, "text": "Let us see the following implementation to get better understanding −" }, { "code": null, "e": 1900, "s": 1889, "text": " Live Demo" }, { "code": null, "e": 2278, "s": 1900, "text": "class Solution:\n def solve(self, nums, k):\n l, r = len(nums), k - 1\n out = []\n for j in range(k):\n mn = nums[~r]\n for i in range(r, l):\n if mn >= nums[~i]:\n mn = nums[~i]\n l = i\n r -= 1\n out.append(mn)\n return out\nob = Solution()\nnums = [2, 3, 1, 10, 3, 4]\nk = 3\nprint(ob.solve(nums, k))" }, { "code": null, "e": 2301, "s": 2278, "text": "[2, 3, 1, 10, 3, 4], 3" }, { "code": null, "e": 2311, "s": 2301, "text": "[1, 3, 4]" } ]
Creating React + GraphQL Serverless Web application using AWS Amplify | by Janitha Tennakoon | Towards Data Science
AWS Amplify is a service provided by Amazon Web Services where it gives the ability to create end to end solutions for mobile and web platforms with a more secure and scalable way using AWS services. AWS Amplify was initially launched in November 2018 and since then many developers have created and deployed their new applications to Amplify because of the simplicity and reliability provided by Amplify. Amplify provides easy to configure features with it called modules named authentication, storage, backend API, and hosting and deployments, etc. You can get more information about the modules provided by the Amplify from here. In this article, we are going to use 3 modules, authentication, backend api, and the hosting and deployment. In this article let’s try to build and deploy a react application with a GraphQL api. Below are tasks that we are going to perform in this article in order to achieve our goal. Install and configure Amplify CLI Create react application Add authentication Add GraphQL api Deploy and host on Amplify The full react application code that I am using for the article can be found here. The first step we need to do before creating our react application is that we need to install the Amplify CLI tool globally in our system. For that, we need to run the following command in the terminal. (we need node.js installed in our system to use npm) npm install -g @aws-amplify/cli Now in order to configure the installed Amplify with our AWS account issue the below command. amplify configure This will prompt a series of questions that we need to answer. First, it will ask us to log in to our AWS account using the web console. The next important question is the IAM user that it will create for our Amplify CLI tool. After specifying a name for the user it will again redirect us to the IAM console where we need to provide necessary permission policies for our user. Here make sure to add AdministratorAccess policy to the user. Then go to Security credentials tab and create an access key for this user and remember to download and store credential details. Back in the console as next steps, it will ask for this accessKeyId and secretAccessKey. Now our configuration for Amplify CLI is done. Now let’s start creating our react application. For the creation of a new react application issue the following commands. npx create-react-app amplify-react-samplecd amplify-react-samplenpm start If everything went smoothly in localhost:3000 it should show the newly created react application. The next step is to add aws-amplify to our react application as a dependency. This package will have the functionality of doing all the configurations on Amplify from our react code. npm install aws-amplify @aws-amplify/ui-react Next, let’s initialize an Amplify project for our react application. amplify init Again we will be prompted to answer a series of questions. For the project name, you can give any name you want. For the type of application select javascript and for the framework select react. For other questions, we can leave the default values since we are not going to change the react build and run scripts inside our application. The following modifications in our project will be done during this step. A new folder named amplify will be created at the root level of the project. This stores every configuration related to our backend (AWS resources). (In this article we are going to add authentication and GraphQL API). As we add more amplify features configurations related to those features will be stored inside this folder as Infrastructure As code. a file called aws-exports.js will be created in the src directory that holds all the configuration for the services that we will create with Amplify. For now, it only contains region information because we are still not using any Amplify services. At the same time on AWS a cloud project will be created which we can access through the Amplify console. The console also gives some other additional configuration options as well for our application. Now our react application is initialized with Amplify and let’s move to the next task, adding authentication. For authentication, Amplify uses AWS Cognito as the main authentication provider. AWS Cognito provides many features like authentication, user registration, account recovery, and many more. You can check more available features or Cognito from here. To add Cognito authentication on our application issue the below command in the terminal. amplify add auth Again we will be prompted with questions for our authentication configurations. For this article, we will choose the default configuration for security configuration. (if we want we can update this later by running amplify update auth). For the sign-in option, you can choose either username or email. That’s it, now we have our authentication module created for us. But before testing it in our application we need to push this configuration to Amplify. To do that simply issue the following command in the terminal. amplify push This command will create the required configurations on Amplify and Cognito on AWS and will also edit our aws-exports.js file with Cognito auth configurations. The next step is to use this Cognito authentication in our react application. For that first, we need to import the Amplify module for our application. Edit index.js file to import Amplify and configure Amplify module using the configurations in aws-exports.jsfile. import Amplify from 'aws-amplify';import awsconfig from './aws-exports'; Amplify.configure(awsconfig); Now we can use the auth module in our application. Go to app.jsand first import the below modules. import { withAuthenticator, AmplifySignOut } from "@aws-amplify/ui-react"; Next, wrap our App component with WithAuthenticator. Here AmplifySignOut is a component provided by amplify-react where it acts as a signout button. For more pre-built UI components offered by Amplify, you can check here. Now that we have added the Amplify authentication in our react application let’s start the server and test whether it works. Run npm start and go to the browser. Now it should display a sign-in page when we try to access localhost:3000. If you can see the above page that means our authentication is set correctly. The next step would be to create a user in our Cognito user pool. You can either create a user through the IAM console or by clicking on Create account. Users can be managed through the Cognito console as well. Now try to login using the user we created and should now be able to go to our home page.IF everything works just fine let’s move to the next task. Amplify supports creating serverless backend APIs using AWS AppSync. AppSync supports both REST and GraphQL API frameworks. For this article, we are going to use AppSync GraphQL api. To learn more about what is GraphQL and how to create a serverless GraphQL using AWS AppSync you can check out this article written by me. Before adding our backend GraphQL api let’s do some modifications on our react application for showing data in a table. In this article Let’s assume our application will show data related to actors. In the above code, I am using material-ui for the creation of the table which you can install using npm install @material-ui/core . The code only displays a table where for now we have defined a set of data inside getActors() method. (Make sure to import the Home component in App.js as well) Now rather than taking hard coded values inside the code, let’s try to create our own GraphQL API to retrieve actor information from the api. To add a GraphQL api to our application simply issue the following command in the terminal. amplify add api For the questions you will be asked to provide select service as GraphQL and for authorization choose Amazon Cognito User Pool. Next for the schema template select Single object with fields. This will automatically create a simple GraphQL schema for us. Next when you asked to edit the schema press Y. This will open our schema.graphql which is created automatically. There we can see the schema with model Todo already created. type Todo @model { id: ID! name: String! description: String} let’s edit this schema for our use case where our model will be Actors. Here if we need we can also specify the Query and Mutation that is allowed in our schema. In GraphQL Query is like a GET call where we do not do any modifications to the data and Mutation is like PUT, POST, DELETE calls where we do modifications on the data. But this can be automatically generated in AppSync if we want as well when we push the api. The next step is to push this GraphQL api to Amplify where it will be get created on AppSync. Issue below command to push the API. amplify push Here again, a set of configurations will be asked from us. Select the language target to be javascript and make file pattern the default. Later it will ask to generate all GraphQL operations for our schema. Make sure to enter Yes for this as this will auto-generate Query and Mutation for our Actor model. This will create our GraphQL API on AppSync. Our database will also get automatically created on AWS DynamoDB. Also, it creates a new folder inside the amplify folder named backend. Our Actor schema and other AppSync related configurations can be found inside this backend folder. At the end of the configuration, we will be provided with the GraphQL endpoint which we configured using actors schema. Now if we go to the AppSync console we can see the newly created Actors api. Now you can see that our schema is updated with Query and Mutation since AppSync generated those for us. Here let’s try to create some data so we can query from the API. Go to Queries tab. There, from the dropdown select Mutation and click on the + button. Mutation is how we can do updates in our database. Since we need to create actor click on createActor and fill with Actor details. For now, let’s add two actors. Now let’s test our GraphQL. For that, we need to use a Query. Remove Mutation and add Query by clicking on + button Let’s do a Query using listActors by returning only id, firstName, lastName, age, and movies fields. If the correct results are returning from our Query that means our GraphQL api is now properly configured. Now let’s start adding the GraphQL API to our react application. First, we need to import Amplify, API, graphqlOperation modules in our Home component. import Amplify, { API, graphqlOperation } from 'aws-amplify' Next, we need to import Query and Mutation we are going to perform in the application. In our case Query is listActors and Mutation is createActor. We can get these Query or Mutation from either AppSync console or in the aws-schema.graphql file inside backend/api folder import { createActor} from './graphql/mutations' import { listActors} from './graphql/queries' Also, make sure to configure imported Amplify using the correct configurations. import awsExports from "./aws-exports"; Amplify.configure(awsExports); Below is the function that we are going to use for fetch actors. Now the last thing we need to do is calling this fetchActors() function from UseEffect. Remove previously called getActors() method and replace with fetchActors(). Now if all is working it should show only 2 actors which now come from our GraphQL api. Next, let’s try to add actors using our react application. For this, we are going to use addActor Mutation which we already imported. Apart from creating addActor() function we need to have input fields as well. Below is the fully completed code for the Home component. Now let’s try to add an actor and after it should appear on the table. Now that it is completed let’s move to our final task, deploying and hosting Now for the last part let’s add the hosting module for our application by issuing the following command. amplify add hosting Again we will be prompted with several questions. For the plugin select Hosting with Amplify Control and for the type select Manual deployment. Now only thing remains is to publish this module to Amplify. For that issue following command. amplify publish This will generate a cloudFormation stack and will create necessary infrastructure on AWS. After a while, all infrastructure will be get created and we will have the deployed URL. You can go ahead and check the URL to make sure every thing works as it should be. Additionally, rather than making a manual deployment, we have the option of continuous deployment as well from Amplify. Ok, that’s was a simple guideline for how to deploy a react application using a serverless GraphQL api and using Cognito authentication. Please follow official documentation if you want to know more about AWS Amplify and it’s many more features. Thank you :)
[ { "code": null, "e": 578, "s": 172, "text": "AWS Amplify is a service provided by Amazon Web Services where it gives the ability to create end to end solutions for mobile and web platforms with a more secure and scalable way using AWS services. AWS Amplify was initially launched in November 2018 and since then many developers have created and deployed their new applications to Amplify because of the simplicity and reliability provided by Amplify." }, { "code": null, "e": 914, "s": 578, "text": "Amplify provides easy to configure features with it called modules named authentication, storage, backend API, and hosting and deployments, etc. You can get more information about the modules provided by the Amplify from here. In this article, we are going to use 3 modules, authentication, backend api, and the hosting and deployment." }, { "code": null, "e": 1091, "s": 914, "text": "In this article let’s try to build and deploy a react application with a GraphQL api. Below are tasks that we are going to perform in this article in order to achieve our goal." }, { "code": null, "e": 1125, "s": 1091, "text": "Install and configure Amplify CLI" }, { "code": null, "e": 1150, "s": 1125, "text": "Create react application" }, { "code": null, "e": 1169, "s": 1150, "text": "Add authentication" }, { "code": null, "e": 1185, "s": 1169, "text": "Add GraphQL api" }, { "code": null, "e": 1212, "s": 1185, "text": "Deploy and host on Amplify" }, { "code": null, "e": 1295, "s": 1212, "text": "The full react application code that I am using for the article can be found here." }, { "code": null, "e": 1551, "s": 1295, "text": "The first step we need to do before creating our react application is that we need to install the Amplify CLI tool globally in our system. For that, we need to run the following command in the terminal. (we need node.js installed in our system to use npm)" }, { "code": null, "e": 1583, "s": 1551, "text": "npm install -g @aws-amplify/cli" }, { "code": null, "e": 1677, "s": 1583, "text": "Now in order to configure the installed Amplify with our AWS account issue the below command." }, { "code": null, "e": 1695, "s": 1677, "text": "amplify configure" }, { "code": null, "e": 2073, "s": 1695, "text": "This will prompt a series of questions that we need to answer. First, it will ask us to log in to our AWS account using the web console. The next important question is the IAM user that it will create for our Amplify CLI tool. After specifying a name for the user it will again redirect us to the IAM console where we need to provide necessary permission policies for our user." }, { "code": null, "e": 2401, "s": 2073, "text": "Here make sure to add AdministratorAccess policy to the user. Then go to Security credentials tab and create an access key for this user and remember to download and store credential details. Back in the console as next steps, it will ask for this accessKeyId and secretAccessKey. Now our configuration for Amplify CLI is done." }, { "code": null, "e": 2523, "s": 2401, "text": "Now let’s start creating our react application. For the creation of a new react application issue the following commands." }, { "code": null, "e": 2597, "s": 2523, "text": "npx create-react-app amplify-react-samplecd amplify-react-samplenpm start" }, { "code": null, "e": 2695, "s": 2597, "text": "If everything went smoothly in localhost:3000 it should show the newly created react application." }, { "code": null, "e": 2878, "s": 2695, "text": "The next step is to add aws-amplify to our react application as a dependency. This package will have the functionality of doing all the configurations on Amplify from our react code." }, { "code": null, "e": 2924, "s": 2878, "text": "npm install aws-amplify @aws-amplify/ui-react" }, { "code": null, "e": 2993, "s": 2924, "text": "Next, let’s initialize an Amplify project for our react application." }, { "code": null, "e": 3006, "s": 2993, "text": "amplify init" }, { "code": null, "e": 3343, "s": 3006, "text": "Again we will be prompted to answer a series of questions. For the project name, you can give any name you want. For the type of application select javascript and for the framework select react. For other questions, we can leave the default values since we are not going to change the react build and run scripts inside our application." }, { "code": null, "e": 3417, "s": 3343, "text": "The following modifications in our project will be done during this step." }, { "code": null, "e": 3770, "s": 3417, "text": "A new folder named amplify will be created at the root level of the project. This stores every configuration related to our backend (AWS resources). (In this article we are going to add authentication and GraphQL API). As we add more amplify features configurations related to those features will be stored inside this folder as Infrastructure As code." }, { "code": null, "e": 4018, "s": 3770, "text": "a file called aws-exports.js will be created in the src directory that holds all the configuration for the services that we will create with Amplify. For now, it only contains region information because we are still not using any Amplify services." }, { "code": null, "e": 4219, "s": 4018, "text": "At the same time on AWS a cloud project will be created which we can access through the Amplify console. The console also gives some other additional configuration options as well for our application." }, { "code": null, "e": 4329, "s": 4219, "text": "Now our react application is initialized with Amplify and let’s move to the next task, adding authentication." }, { "code": null, "e": 4669, "s": 4329, "text": "For authentication, Amplify uses AWS Cognito as the main authentication provider. AWS Cognito provides many features like authentication, user registration, account recovery, and many more. You can check more available features or Cognito from here. To add Cognito authentication on our application issue the below command in the terminal." }, { "code": null, "e": 4686, "s": 4669, "text": "amplify add auth" }, { "code": null, "e": 4988, "s": 4686, "text": "Again we will be prompted with questions for our authentication configurations. For this article, we will choose the default configuration for security configuration. (if we want we can update this later by running amplify update auth). For the sign-in option, you can choose either username or email." }, { "code": null, "e": 5204, "s": 4988, "text": "That’s it, now we have our authentication module created for us. But before testing it in our application we need to push this configuration to Amplify. To do that simply issue the following command in the terminal." }, { "code": null, "e": 5217, "s": 5204, "text": "amplify push" }, { "code": null, "e": 5377, "s": 5217, "text": "This command will create the required configurations on Amplify and Cognito on AWS and will also edit our aws-exports.js file with Cognito auth configurations." }, { "code": null, "e": 5643, "s": 5377, "text": "The next step is to use this Cognito authentication in our react application. For that first, we need to import the Amplify module for our application. Edit index.js file to import Amplify and configure Amplify module using the configurations in aws-exports.jsfile." }, { "code": null, "e": 5746, "s": 5643, "text": "import Amplify from 'aws-amplify';import awsconfig from './aws-exports'; Amplify.configure(awsconfig);" }, { "code": null, "e": 5845, "s": 5746, "text": "Now we can use the auth module in our application. Go to app.jsand first import the below modules." }, { "code": null, "e": 5920, "s": 5845, "text": "import { withAuthenticator, AmplifySignOut } from \"@aws-amplify/ui-react\";" }, { "code": null, "e": 6142, "s": 5920, "text": "Next, wrap our App component with WithAuthenticator. Here AmplifySignOut is a component provided by amplify-react where it acts as a signout button. For more pre-built UI components offered by Amplify, you can check here." }, { "code": null, "e": 6304, "s": 6142, "text": "Now that we have added the Amplify authentication in our react application let’s start the server and test whether it works. Run npm start and go to the browser." }, { "code": null, "e": 6668, "s": 6304, "text": "Now it should display a sign-in page when we try to access localhost:3000. If you can see the above page that means our authentication is set correctly. The next step would be to create a user in our Cognito user pool. You can either create a user through the IAM console or by clicking on Create account. Users can be managed through the Cognito console as well." }, { "code": null, "e": 6816, "s": 6668, "text": "Now try to login using the user we created and should now be able to go to our home page.IF everything works just fine let’s move to the next task." }, { "code": null, "e": 7138, "s": 6816, "text": "Amplify supports creating serverless backend APIs using AWS AppSync. AppSync supports both REST and GraphQL API frameworks. For this article, we are going to use AppSync GraphQL api. To learn more about what is GraphQL and how to create a serverless GraphQL using AWS AppSync you can check out this article written by me." }, { "code": null, "e": 7337, "s": 7138, "text": "Before adding our backend GraphQL api let’s do some modifications on our react application for showing data in a table. In this article Let’s assume our application will show data related to actors." }, { "code": null, "e": 7630, "s": 7337, "text": "In the above code, I am using material-ui for the creation of the table which you can install using npm install @material-ui/core . The code only displays a table where for now we have defined a set of data inside getActors() method. (Make sure to import the Home component in App.js as well)" }, { "code": null, "e": 7864, "s": 7630, "text": "Now rather than taking hard coded values inside the code, let’s try to create our own GraphQL API to retrieve actor information from the api. To add a GraphQL api to our application simply issue the following command in the terminal." }, { "code": null, "e": 7880, "s": 7864, "text": "amplify add api" }, { "code": null, "e": 8182, "s": 7880, "text": "For the questions you will be asked to provide select service as GraphQL and for authorization choose Amazon Cognito User Pool. Next for the schema template select Single object with fields. This will automatically create a simple GraphQL schema for us. Next when you asked to edit the schema press Y." }, { "code": null, "e": 8309, "s": 8182, "text": "This will open our schema.graphql which is created automatically. There we can see the schema with model Todo already created." }, { "code": null, "e": 8374, "s": 8309, "text": "type Todo @model { id: ID! name: String! description: String}" }, { "code": null, "e": 8446, "s": 8374, "text": "let’s edit this schema for our use case where our model will be Actors." }, { "code": null, "e": 8797, "s": 8446, "text": "Here if we need we can also specify the Query and Mutation that is allowed in our schema. In GraphQL Query is like a GET call where we do not do any modifications to the data and Mutation is like PUT, POST, DELETE calls where we do modifications on the data. But this can be automatically generated in AppSync if we want as well when we push the api." }, { "code": null, "e": 8928, "s": 8797, "text": "The next step is to push this GraphQL api to Amplify where it will be get created on AppSync. Issue below command to push the API." }, { "code": null, "e": 8941, "s": 8928, "text": "amplify push" }, { "code": null, "e": 9247, "s": 8941, "text": "Here again, a set of configurations will be asked from us. Select the language target to be javascript and make file pattern the default. Later it will ask to generate all GraphQL operations for our schema. Make sure to enter Yes for this as this will auto-generate Query and Mutation for our Actor model." }, { "code": null, "e": 9528, "s": 9247, "text": "This will create our GraphQL API on AppSync. Our database will also get automatically created on AWS DynamoDB. Also, it creates a new folder inside the amplify folder named backend. Our Actor schema and other AppSync related configurations can be found inside this backend folder." }, { "code": null, "e": 9725, "s": 9528, "text": "At the end of the configuration, we will be provided with the GraphQL endpoint which we configured using actors schema. Now if we go to the AppSync console we can see the newly created Actors api." }, { "code": null, "e": 9982, "s": 9725, "text": "Now you can see that our schema is updated with Query and Mutation since AppSync generated those for us. Here let’s try to create some data so we can query from the API. Go to Queries tab. There, from the dropdown select Mutation and click on the + button." }, { "code": null, "e": 10144, "s": 9982, "text": "Mutation is how we can do updates in our database. Since we need to create actor click on createActor and fill with Actor details. For now, let’s add two actors." }, { "code": null, "e": 10260, "s": 10144, "text": "Now let’s test our GraphQL. For that, we need to use a Query. Remove Mutation and add Query by clicking on + button" }, { "code": null, "e": 10361, "s": 10260, "text": "Let’s do a Query using listActors by returning only id, firstName, lastName, age, and movies fields." }, { "code": null, "e": 10533, "s": 10361, "text": "If the correct results are returning from our Query that means our GraphQL api is now properly configured. Now let’s start adding the GraphQL API to our react application." }, { "code": null, "e": 10620, "s": 10533, "text": "First, we need to import Amplify, API, graphqlOperation modules in our Home component." }, { "code": null, "e": 10681, "s": 10620, "text": "import Amplify, { API, graphqlOperation } from 'aws-amplify'" }, { "code": null, "e": 10952, "s": 10681, "text": "Next, we need to import Query and Mutation we are going to perform in the application. In our case Query is listActors and Mutation is createActor. We can get these Query or Mutation from either AppSync console or in the aws-schema.graphql file inside backend/api folder" }, { "code": null, "e": 11047, "s": 10952, "text": "import { createActor} from './graphql/mutations' import { listActors} from './graphql/queries'" }, { "code": null, "e": 11127, "s": 11047, "text": "Also, make sure to configure imported Amplify using the correct configurations." }, { "code": null, "e": 11198, "s": 11127, "text": "import awsExports from \"./aws-exports\"; Amplify.configure(awsExports);" }, { "code": null, "e": 11263, "s": 11198, "text": "Below is the function that we are going to use for fetch actors." }, { "code": null, "e": 11427, "s": 11263, "text": "Now the last thing we need to do is calling this fetchActors() function from UseEffect. Remove previously called getActors() method and replace with fetchActors()." }, { "code": null, "e": 11515, "s": 11427, "text": "Now if all is working it should show only 2 actors which now come from our GraphQL api." }, { "code": null, "e": 11649, "s": 11515, "text": "Next, let’s try to add actors using our react application. For this, we are going to use addActor Mutation which we already imported." }, { "code": null, "e": 11785, "s": 11649, "text": "Apart from creating addActor() function we need to have input fields as well. Below is the fully completed code for the Home component." }, { "code": null, "e": 11856, "s": 11785, "text": "Now let’s try to add an actor and after it should appear on the table." }, { "code": null, "e": 11933, "s": 11856, "text": "Now that it is completed let’s move to our final task, deploying and hosting" }, { "code": null, "e": 12038, "s": 11933, "text": "Now for the last part let’s add the hosting module for our application by issuing the following command." }, { "code": null, "e": 12058, "s": 12038, "text": "amplify add hosting" }, { "code": null, "e": 12202, "s": 12058, "text": "Again we will be prompted with several questions. For the plugin select Hosting with Amplify Control and for the type select Manual deployment." }, { "code": null, "e": 12297, "s": 12202, "text": "Now only thing remains is to publish this module to Amplify. For that issue following command." }, { "code": null, "e": 12313, "s": 12297, "text": "amplify publish" }, { "code": null, "e": 12404, "s": 12313, "text": "This will generate a cloudFormation stack and will create necessary infrastructure on AWS." }, { "code": null, "e": 12576, "s": 12404, "text": "After a while, all infrastructure will be get created and we will have the deployed URL. You can go ahead and check the URL to make sure every thing works as it should be." }, { "code": null, "e": 12696, "s": 12576, "text": "Additionally, rather than making a manual deployment, we have the option of continuous deployment as well from Amplify." } ]
Visualizing the Stock Market with Tableau | by Tony Yiu | Towards Data Science
Tableau is a critical data visualization tool that belongs in every data analyst’s and data scientist’s toolkit. Today we play around with stock market data in order to explore how Tableau can help us dissect and better understand our data. We can grab stock market data from Quandl. We’re going to focus on the S&P 500, a market cap weighted index of large cap American stocks (basically, the biggest American companies). Here is the Python code for grabbing the data (note that you will need your own Quandl API key and that the Sharadar data requires a paid subscription). I’ve also added comments in the code below, but the following snippet uses Quandl’s API to grab financial data for all publicly listed companies in Sharadar’s database (financial data is stuff like revenues, net income, debt, return on invested capital, and so on). This financial data is stored in the dataframe stock_df. import quandlquandl.ApiConfig.api_key = 'your_qandl_api_key'import numpy as npimport pandas as pd# Download financial data from Quandl/Sharadartable = quandl.get_table('SHARADAR/SF1', paginate=True)# Grab the most recent annual data ('MRY' denotes annual data)stock_df = table[(table['calendardate'] == '2018-12-31 00:00:00') & (table['dimension']=='MRY')] However, we don’t need data on every company — we just want the S&P 500. To get the S&P 500 tickers, we turn to web scraping and Wikipedia. The following lines of code web scrape a Wikipedia table that lists the tickers and industries of every company that is currently in the S&P 500 and stores it in the variable called page_content. # Scrape S&P 500 tickers from Wikipediafrom bs4 import BeautifulSoupimport requestsimport repage_link = 'https://en.wikipedia.org/wiki/List_of_S%26P_500_companies'page_response = requests.get(page_link, timeout=1000)page_content = BeautifulSoup(page_response.content, 'lxml') Next we use some parsing code to grab ticker and industry from page_content, which is a BeautifulSoup data structure. The code can be summarized as doing the following: Loop through all the ‘tr’ (I believe it denotes a table row in HTML) tagged items in page_content. Grab the ticker as a string (the .text converts the item to string format) and store it in the list tickers. Grab the industry as a string and store it in the list industries. # From web scraped Wikipedia content on the S&P 500, grab the ticker and industry for each firmtickers = []industries = []for i, val in enumerate(page_content.find_all('tr')): if i > 0: try: # Here is where I grab the ticker tickers.append(val.find_all('a')[0].text) # Here is where I grab the industry industries.append(val.find_all('td')[3].text.replace('\n', '')) except: pass Finally, we need to do a bit of data manipulation to join up our ticker and industry data (from Wikipedia) with our financial data (from Quandl). The first two blocks of code (as detailed in the comments) store the tickers that we want into a dataframe called sp_df. The last block of code uses the Pandas merge method to join sp_df, which contains our ticker and industry data, with stock_df, which contains our financial data. We store the resulting dataframe, merged_df, in a .csv file that we can now load into Tableau (I use Tableau Public, which is free). Hurray done! # After ticker ZTS, the rest of the table entries are for acquisitions/mergerslast_pos = tickers.index('ZTS') + 1sp_tickers = tickers[:last_pos]sp_industries = industries[:last_pos]# Create a new dataframe for S&P 500 and merge in Quandl datasp_df = pd.DataFrame()sp_df['tickers'] = sp_tickerssp_df['industries'] = sp_industriesmerged_df = sp_df.merge(stock_df, left_on='tickers', right_on='ticker', how='left')merged_df.to_csv('sp500.csv', index=False) Data visualization sounds fun and easy but it’s not. A lot of thought goes into all those cool dashboards and interactive charts that we see. While I am no expert, before I start slapping numbers onto graphs, I first try to answer the following questions: What insight are we trying to uncover through our visualization? Pretty charts are nice and all but if there is no insight to draw from them then they are nothing more than empty shapes and colors.Is the visual meant to be exploratory or answer a specific question? These two objectives might seem similar but they are not. An exploratory visualization can afford to be more general and contain lots of information — as the objective is to provoke thought and discussion. It is meant to be stared at, digested gradually, and different people can arrive at different conclusions upon studying one. On the other hand, visualizations meant to answer a specific question need to do exactly that — they are meant to be unambiguous supporters of whatever point you are trying to make. What insight are we trying to uncover through our visualization? Pretty charts are nice and all but if there is no insight to draw from them then they are nothing more than empty shapes and colors. Is the visual meant to be exploratory or answer a specific question? These two objectives might seem similar but they are not. An exploratory visualization can afford to be more general and contain lots of information — as the objective is to provoke thought and discussion. It is meant to be stared at, digested gradually, and different people can arrive at different conclusions upon studying one. On the other hand, visualizations meant to answer a specific question need to do exactly that — they are meant to be unambiguous supporters of whatever point you are trying to make. Let’s try to answer these questions now: We want to use our stock data to look for attractive industries or individual companies that might be worth investing in.We will focus on exploratory visuals in this post. Picking stocks is a complicated and subjective endeavor. Our aim here is not to tell people what stocks to buy; but rather we hope our visualizations can help them identify and drill down into more specific areas of interest. We want to use our stock data to look for attractive industries or individual companies that might be worth investing in. We will focus on exploratory visuals in this post. Picking stocks is a complicated and subjective endeavor. Our aim here is not to tell people what stocks to buy; but rather we hope our visualizations can help them identify and drill down into more specific areas of interest. Let’s start off by looking at a Tableau treemap of the S&P 500. The S&P 500 is a cap weighted index — that means each company’s representation in the index is proportional to its market cap (market cap is the sum value of all the company’s shares, in other words what it would cost to buy the entire firm). In the following treemap, the size and color of each rectangle corresponds to that company’s representation in the S&P 500. There are some familiar faces at the top — Apple, Microsoft, Amazon, Google, Berkshire Hathaway make up the top 5. Interestingly, these top 5 companies make up 17% of the S&P 500’s market cap and the top 15 companies make up 30% of the total market cap. Note that market cap alone is not enough to explain what drives the S&P 500’s price changes — the volatility of a company’s share price matters too. For example, even though Facebook (FB) has a lower market cap than Microsoft (MSFT), Facebook’s share price has been more volatile in the past 12 months as it has attempted to navigate a slew of scandals. Thus, over the last year, Facebook’s stock has most likely been a greater driver of the S&P 500 than Microsoft’s has. Owning a share of a company is equivalent to owning a portion (however small) of that same company. For example, if we were fabulously rich and bought shares in Google equivalent to 1% of the firm, then as minority owners, we would be entitled to 1% of the profits. Of course, as minority owners, we are also forced to entrust the management and investment of these profits to Google’s upper management and board (which is why we don’t get a profit sharing check from Google every quarter even if we own the shares). So if a firm’s profits (a.k.a. net income) are what we ultimately hope to gain when we buy its shares, perhaps we should redo our treemap in terms of profits. In the following treemap, the size and color of each rectangle corresponds to the magnitude of that company’s profits (a.k.a. net income). While Apple and Google are still in the top 5, we now have some new faces — J.P. Morgan (JPM), Bank of America (BAC), and Wells Fargo (WFC). Despite all the hype over how tech is upending traditional industries, the banking industry (as traditional an industry as there is) continues to earn massive profits. Intel (INTC) the forgotten tech titan, Exxon Mobil (XOM) the oil giant, and AT&T (T) the telecommunications conglomerate also still earn tons of money despite being somewhat forgotten in today’s innovation obsessed market. Personally I believe the best long term investment strategy is to “buy low and sell high” (easier said than done). But how do we do that? At its most basic level, for each dollar that we pay, we should be trying to purchase as many dollars in profits as possible. The previous visualization showed us that unloved industries may sometimes harbor under-appreciated sources of profit. Let’s shift to looking at industries instead of companies to see whether we can find some good profit ponds to fish in. The treemap below breaks down each industry in terms of median market cap (the area of each rectangle) and median profits (the color of each rectangle). We use medians because we want to know that if I were to pick a company at random from a particular industry bucket, how much is it likely to cost (market cap) and how profitable is it likely to be (net income). Before we discuss results, we should first understand the proper way to think about this treemap. We are using it to eyeball the relationship between median market cap (the price we pay) and median net income (the profits we get). If the price of a sector were perfectly correlated with the profits of the firms inside it, then we would expect the biggest rectangles to be the most green and for the color to transition to red as the rectangles decrease in size. We obviously don’t see that here, so it looks like there are potential opportunities. The treemap highlights Financials (banks, insurance companies, etc.) and Communication Services (Google, Facebook, AT&T, Disney, etc.) as potentially attractive sectors in which to search for cheap stocks — because they are middle of the pack in terms of rectangle size (median market cap) but very green (high median profits). Meanwhile, Real Estate, in deep red, seems like a definite no go. Healthcare also seems like a sector to avoid as it owns both the highest median market cap along with near “bottom of the pack” median profits (bad bang for our buck). Of course, these are just quick rules of thumb for identifying potential investments — much more due diligence should be done before an actual investment is made. Surprisingly the Information Technology sector, which contains heavy hitters like Apple and Microsoft, does not come off looking great in our previous analysis — it is expensive in terms of price but “back of the pack” in terms of median profits. What gives? There are two factors at play: In late 2018, Google and Facebook were moved from Information Technology to Communication Services. Those are two massively profitable companies that people associate deeply with tech. If they were still in the Information Technology sector, then both its market cap and profits would be significantly higher.The level of profits is not the only thing investors care about. How those profits are earned is also extremely important — things like profit margin (what proportion of sales ultimately translate into profits) and return on investment (how much money we need to put into a business in order to generate a given level of profits) matter a lot too. In late 2018, Google and Facebook were moved from Information Technology to Communication Services. Those are two massively profitable companies that people associate deeply with tech. If they were still in the Information Technology sector, then both its market cap and profits would be significantly higher. The level of profits is not the only thing investors care about. How those profits are earned is also extremely important — things like profit margin (what proportion of sales ultimately translate into profits) and return on investment (how much money we need to put into a business in order to generate a given level of profits) matter a lot too. Let’s use a Tableau scatter plot to check out the relationship between P/E ratios and ROIC: P/E ratio is a popular measure of how expensive a company’s stock is. It is simply the company’s market capitalization divided by its net income — in other words, how much does it cost us to buy $1 of a particular company’s earnings. The higher the P/E ratio, all other things equal, the more expensive a stock is perceived to be. ROIC stands for Return on Capital Invested and represents the amount of profit we can generate from a $1 investment into the business. Invested capital is a measure of the amount of capital it takes to run a certain business. For example, a capital intensive business would be something like Toyota, which requires massive factories to manufacture its vehicles. On the opposite side of the spectrum, software is a capital light business — once it is developed, it costs very little in terms of fixed costs or infrastructure (relative to the profits generated) to maintain and deploy something like Microsoft’s Office (Word, Excel, PowerPoint, Outlook). Check out our scatter plot to the left. It shows that there is a positive correlation between a stock’s P/E ratio (how expensive it is) and its ROIC. This makes sense — investors like high ROIC companies because they generally require little upfront investment to generate significant profits (companies that require large upfront investments are viewed as risky because we might never get paid back). And the Information Technology sector has by far the highest median ROIC. This also makes sense as this sector is filled with software firms, which as we previously observed are very capital light. So it’s not high current profits that attract investors to Information Technology (and drive its high P/E ratio and market capitalizations) but rather the capital light nature of the business and the hope that relatively small investments today will yield high growth and profits tomorrow (everyone loves a business model that is easy and cheap to scale). Will that happen? I have no idea but the market is currently making a big bet that it will — so if you are looking for good odds, you may want to look elsewhere. Finally, note that the Financials sector has the lowest ROIC. This plus the perceived riskiness of banks (2008 anyone?) probably drives their low valuation. But banks use capital differently — instead of borrowing money to build a factory, banks borrow money from folks like you and me in order to lend it back out at higher rates. Usually high invested capital implies that high fixed, upfront costs are needed to operate the business. This is not the case for banks — despite having extremely high levels of invested capital (due to high debt), banks have very little in the ways of fixed costs. This high debt does make them riskier and perhaps deserving of a P/E ratio discount, but we should not rule banks out as investments just because of their low ROICs — instead, we should seek to understand what drives these low ROICs and whether it is a real concern or not. Nice, we made it to the end! Honestly, there is still so much more we can explore. The stock market and corporate strategy are two incredibly deep and rich subjects; and the question of “what stocks to buy” is an immensely tricky one. We have only begun to scratch the surface in this post. However, I hope that I’ve demonstrated how visualizations can help us digest complex datasets and begin to tackle challenging problems. Cheers! More by me on Finance and Investing: The Dangers of Shorting Volatility A Data Science Project I Did on Investing in Lending Club Loans On Stock Market Downturns More by me on Data Science: The Random Forest Classifier How Neural Networks Work Principal Components Analysis
[ { "code": null, "e": 413, "s": 172, "text": "Tableau is a critical data visualization tool that belongs in every data analyst’s and data scientist’s toolkit. Today we play around with stock market data in order to explore how Tableau can help us dissect and better understand our data." }, { "code": null, "e": 595, "s": 413, "text": "We can grab stock market data from Quandl. We’re going to focus on the S&P 500, a market cap weighted index of large cap American stocks (basically, the biggest American companies)." }, { "code": null, "e": 1071, "s": 595, "text": "Here is the Python code for grabbing the data (note that you will need your own Quandl API key and that the Sharadar data requires a paid subscription). I’ve also added comments in the code below, but the following snippet uses Quandl’s API to grab financial data for all publicly listed companies in Sharadar’s database (financial data is stuff like revenues, net income, debt, return on invested capital, and so on). This financial data is stored in the dataframe stock_df." }, { "code": null, "e": 1428, "s": 1071, "text": "import quandlquandl.ApiConfig.api_key = 'your_qandl_api_key'import numpy as npimport pandas as pd# Download financial data from Quandl/Sharadartable = quandl.get_table('SHARADAR/SF1', paginate=True)# Grab the most recent annual data ('MRY' denotes annual data)stock_df = table[(table['calendardate'] == '2018-12-31 00:00:00') & (table['dimension']=='MRY')]" }, { "code": null, "e": 1764, "s": 1428, "text": "However, we don’t need data on every company — we just want the S&P 500. To get the S&P 500 tickers, we turn to web scraping and Wikipedia. The following lines of code web scrape a Wikipedia table that lists the tickers and industries of every company that is currently in the S&P 500 and stores it in the variable called page_content." }, { "code": null, "e": 2040, "s": 1764, "text": "# Scrape S&P 500 tickers from Wikipediafrom bs4 import BeautifulSoupimport requestsimport repage_link = 'https://en.wikipedia.org/wiki/List_of_S%26P_500_companies'page_response = requests.get(page_link, timeout=1000)page_content = BeautifulSoup(page_response.content, 'lxml')" }, { "code": null, "e": 2209, "s": 2040, "text": "Next we use some parsing code to grab ticker and industry from page_content, which is a BeautifulSoup data structure. The code can be summarized as doing the following:" }, { "code": null, "e": 2308, "s": 2209, "text": "Loop through all the ‘tr’ (I believe it denotes a table row in HTML) tagged items in page_content." }, { "code": null, "e": 2417, "s": 2308, "text": "Grab the ticker as a string (the .text converts the item to string format) and store it in the list tickers." }, { "code": null, "e": 2484, "s": 2417, "text": "Grab the industry as a string and store it in the list industries." }, { "code": null, "e": 2936, "s": 2484, "text": "# From web scraped Wikipedia content on the S&P 500, grab the ticker and industry for each firmtickers = []industries = []for i, val in enumerate(page_content.find_all('tr')): if i > 0: try: # Here is where I grab the ticker tickers.append(val.find_all('a')[0].text) # Here is where I grab the industry industries.append(val.find_all('td')[3].text.replace('\\n', '')) except: pass" }, { "code": null, "e": 3203, "s": 2936, "text": "Finally, we need to do a bit of data manipulation to join up our ticker and industry data (from Wikipedia) with our financial data (from Quandl). The first two blocks of code (as detailed in the comments) store the tickers that we want into a dataframe called sp_df." }, { "code": null, "e": 3511, "s": 3203, "text": "The last block of code uses the Pandas merge method to join sp_df, which contains our ticker and industry data, with stock_df, which contains our financial data. We store the resulting dataframe, merged_df, in a .csv file that we can now load into Tableau (I use Tableau Public, which is free). Hurray done!" }, { "code": null, "e": 3965, "s": 3511, "text": "# After ticker ZTS, the rest of the table entries are for acquisitions/mergerslast_pos = tickers.index('ZTS') + 1sp_tickers = tickers[:last_pos]sp_industries = industries[:last_pos]# Create a new dataframe for S&P 500 and merge in Quandl datasp_df = pd.DataFrame()sp_df['tickers'] = sp_tickerssp_df['industries'] = sp_industriesmerged_df = sp_df.merge(stock_df, left_on='tickers', right_on='ticker', how='left')merged_df.to_csv('sp500.csv', index=False)" }, { "code": null, "e": 4221, "s": 3965, "text": "Data visualization sounds fun and easy but it’s not. A lot of thought goes into all those cool dashboards and interactive charts that we see. While I am no expert, before I start slapping numbers onto graphs, I first try to answer the following questions:" }, { "code": null, "e": 5000, "s": 4221, "text": "What insight are we trying to uncover through our visualization? Pretty charts are nice and all but if there is no insight to draw from them then they are nothing more than empty shapes and colors.Is the visual meant to be exploratory or answer a specific question? These two objectives might seem similar but they are not. An exploratory visualization can afford to be more general and contain lots of information — as the objective is to provoke thought and discussion. It is meant to be stared at, digested gradually, and different people can arrive at different conclusions upon studying one. On the other hand, visualizations meant to answer a specific question need to do exactly that — they are meant to be unambiguous supporters of whatever point you are trying to make." }, { "code": null, "e": 5198, "s": 5000, "text": "What insight are we trying to uncover through our visualization? Pretty charts are nice and all but if there is no insight to draw from them then they are nothing more than empty shapes and colors." }, { "code": null, "e": 5780, "s": 5198, "text": "Is the visual meant to be exploratory or answer a specific question? These two objectives might seem similar but they are not. An exploratory visualization can afford to be more general and contain lots of information — as the objective is to provoke thought and discussion. It is meant to be stared at, digested gradually, and different people can arrive at different conclusions upon studying one. On the other hand, visualizations meant to answer a specific question need to do exactly that — they are meant to be unambiguous supporters of whatever point you are trying to make." }, { "code": null, "e": 5821, "s": 5780, "text": "Let’s try to answer these questions now:" }, { "code": null, "e": 6219, "s": 5821, "text": "We want to use our stock data to look for attractive industries or individual companies that might be worth investing in.We will focus on exploratory visuals in this post. Picking stocks is a complicated and subjective endeavor. Our aim here is not to tell people what stocks to buy; but rather we hope our visualizations can help them identify and drill down into more specific areas of interest." }, { "code": null, "e": 6341, "s": 6219, "text": "We want to use our stock data to look for attractive industries or individual companies that might be worth investing in." }, { "code": null, "e": 6618, "s": 6341, "text": "We will focus on exploratory visuals in this post. Picking stocks is a complicated and subjective endeavor. Our aim here is not to tell people what stocks to buy; but rather we hope our visualizations can help them identify and drill down into more specific areas of interest." }, { "code": null, "e": 7049, "s": 6618, "text": "Let’s start off by looking at a Tableau treemap of the S&P 500. The S&P 500 is a cap weighted index — that means each company’s representation in the index is proportional to its market cap (market cap is the sum value of all the company’s shares, in other words what it would cost to buy the entire firm). In the following treemap, the size and color of each rectangle corresponds to that company’s representation in the S&P 500." }, { "code": null, "e": 7775, "s": 7049, "text": "There are some familiar faces at the top — Apple, Microsoft, Amazon, Google, Berkshire Hathaway make up the top 5. Interestingly, these top 5 companies make up 17% of the S&P 500’s market cap and the top 15 companies make up 30% of the total market cap. Note that market cap alone is not enough to explain what drives the S&P 500’s price changes — the volatility of a company’s share price matters too. For example, even though Facebook (FB) has a lower market cap than Microsoft (MSFT), Facebook’s share price has been more volatile in the past 12 months as it has attempted to navigate a slew of scandals. Thus, over the last year, Facebook’s stock has most likely been a greater driver of the S&P 500 than Microsoft’s has." }, { "code": null, "e": 8292, "s": 7775, "text": "Owning a share of a company is equivalent to owning a portion (however small) of that same company. For example, if we were fabulously rich and bought shares in Google equivalent to 1% of the firm, then as minority owners, we would be entitled to 1% of the profits. Of course, as minority owners, we are also forced to entrust the management and investment of these profits to Google’s upper management and board (which is why we don’t get a profit sharing check from Google every quarter even if we own the shares)." }, { "code": null, "e": 8590, "s": 8292, "text": "So if a firm’s profits (a.k.a. net income) are what we ultimately hope to gain when we buy its shares, perhaps we should redo our treemap in terms of profits. In the following treemap, the size and color of each rectangle corresponds to the magnitude of that company’s profits (a.k.a. net income)." }, { "code": null, "e": 9122, "s": 8590, "text": "While Apple and Google are still in the top 5, we now have some new faces — J.P. Morgan (JPM), Bank of America (BAC), and Wells Fargo (WFC). Despite all the hype over how tech is upending traditional industries, the banking industry (as traditional an industry as there is) continues to earn massive profits. Intel (INTC) the forgotten tech titan, Exxon Mobil (XOM) the oil giant, and AT&T (T) the telecommunications conglomerate also still earn tons of money despite being somewhat forgotten in today’s innovation obsessed market." }, { "code": null, "e": 9625, "s": 9122, "text": "Personally I believe the best long term investment strategy is to “buy low and sell high” (easier said than done). But how do we do that? At its most basic level, for each dollar that we pay, we should be trying to purchase as many dollars in profits as possible. The previous visualization showed us that unloved industries may sometimes harbor under-appreciated sources of profit. Let’s shift to looking at industries instead of companies to see whether we can find some good profit ponds to fish in." }, { "code": null, "e": 9990, "s": 9625, "text": "The treemap below breaks down each industry in terms of median market cap (the area of each rectangle) and median profits (the color of each rectangle). We use medians because we want to know that if I were to pick a company at random from a particular industry bucket, how much is it likely to cost (market cap) and how profitable is it likely to be (net income)." }, { "code": null, "e": 10539, "s": 9990, "text": "Before we discuss results, we should first understand the proper way to think about this treemap. We are using it to eyeball the relationship between median market cap (the price we pay) and median net income (the profits we get). If the price of a sector were perfectly correlated with the profits of the firms inside it, then we would expect the biggest rectangles to be the most green and for the color to transition to red as the rectangles decrease in size. We obviously don’t see that here, so it looks like there are potential opportunities." }, { "code": null, "e": 10867, "s": 10539, "text": "The treemap highlights Financials (banks, insurance companies, etc.) and Communication Services (Google, Facebook, AT&T, Disney, etc.) as potentially attractive sectors in which to search for cheap stocks — because they are middle of the pack in terms of rectangle size (median market cap) but very green (high median profits)." }, { "code": null, "e": 11101, "s": 10867, "text": "Meanwhile, Real Estate, in deep red, seems like a definite no go. Healthcare also seems like a sector to avoid as it owns both the highest median market cap along with near “bottom of the pack” median profits (bad bang for our buck)." }, { "code": null, "e": 11264, "s": 11101, "text": "Of course, these are just quick rules of thumb for identifying potential investments — much more due diligence should be done before an actual investment is made." }, { "code": null, "e": 11523, "s": 11264, "text": "Surprisingly the Information Technology sector, which contains heavy hitters like Apple and Microsoft, does not come off looking great in our previous analysis — it is expensive in terms of price but “back of the pack” in terms of median profits. What gives?" }, { "code": null, "e": 11554, "s": 11523, "text": "There are two factors at play:" }, { "code": null, "e": 12211, "s": 11554, "text": "In late 2018, Google and Facebook were moved from Information Technology to Communication Services. Those are two massively profitable companies that people associate deeply with tech. If they were still in the Information Technology sector, then both its market cap and profits would be significantly higher.The level of profits is not the only thing investors care about. How those profits are earned is also extremely important — things like profit margin (what proportion of sales ultimately translate into profits) and return on investment (how much money we need to put into a business in order to generate a given level of profits) matter a lot too." }, { "code": null, "e": 12521, "s": 12211, "text": "In late 2018, Google and Facebook were moved from Information Technology to Communication Services. Those are two massively profitable companies that people associate deeply with tech. If they were still in the Information Technology sector, then both its market cap and profits would be significantly higher." }, { "code": null, "e": 12869, "s": 12521, "text": "The level of profits is not the only thing investors care about. How those profits are earned is also extremely important — things like profit margin (what proportion of sales ultimately translate into profits) and return on investment (how much money we need to put into a business in order to generate a given level of profits) matter a lot too." }, { "code": null, "e": 12961, "s": 12869, "text": "Let’s use a Tableau scatter plot to check out the relationship between P/E ratios and ROIC:" }, { "code": null, "e": 13292, "s": 12961, "text": "P/E ratio is a popular measure of how expensive a company’s stock is. It is simply the company’s market capitalization divided by its net income — in other words, how much does it cost us to buy $1 of a particular company’s earnings. The higher the P/E ratio, all other things equal, the more expensive a stock is perceived to be." }, { "code": null, "e": 13945, "s": 13292, "text": "ROIC stands for Return on Capital Invested and represents the amount of profit we can generate from a $1 investment into the business. Invested capital is a measure of the amount of capital it takes to run a certain business. For example, a capital intensive business would be something like Toyota, which requires massive factories to manufacture its vehicles. On the opposite side of the spectrum, software is a capital light business — once it is developed, it costs very little in terms of fixed costs or infrastructure (relative to the profits generated) to maintain and deploy something like Microsoft’s Office (Word, Excel, PowerPoint, Outlook)." }, { "code": null, "e": 14347, "s": 13945, "text": "Check out our scatter plot to the left. It shows that there is a positive correlation between a stock’s P/E ratio (how expensive it is) and its ROIC. This makes sense — investors like high ROIC companies because they generally require little upfront investment to generate significant profits (companies that require large upfront investments are viewed as risky because we might never get paid back)." }, { "code": null, "e": 14901, "s": 14347, "text": "And the Information Technology sector has by far the highest median ROIC. This also makes sense as this sector is filled with software firms, which as we previously observed are very capital light. So it’s not high current profits that attract investors to Information Technology (and drive its high P/E ratio and market capitalizations) but rather the capital light nature of the business and the hope that relatively small investments today will yield high growth and profits tomorrow (everyone loves a business model that is easy and cheap to scale)." }, { "code": null, "e": 15063, "s": 14901, "text": "Will that happen? I have no idea but the market is currently making a big bet that it will — so if you are looking for good odds, you may want to look elsewhere." }, { "code": null, "e": 15395, "s": 15063, "text": "Finally, note that the Financials sector has the lowest ROIC. This plus the perceived riskiness of banks (2008 anyone?) probably drives their low valuation. But banks use capital differently — instead of borrowing money to build a factory, banks borrow money from folks like you and me in order to lend it back out at higher rates." }, { "code": null, "e": 15935, "s": 15395, "text": "Usually high invested capital implies that high fixed, upfront costs are needed to operate the business. This is not the case for banks — despite having extremely high levels of invested capital (due to high debt), banks have very little in the ways of fixed costs. This high debt does make them riskier and perhaps deserving of a P/E ratio discount, but we should not rule banks out as investments just because of their low ROICs — instead, we should seek to understand what drives these low ROICs and whether it is a real concern or not." }, { "code": null, "e": 16226, "s": 15935, "text": "Nice, we made it to the end! Honestly, there is still so much more we can explore. The stock market and corporate strategy are two incredibly deep and rich subjects; and the question of “what stocks to buy” is an immensely tricky one. We have only begun to scratch the surface in this post." }, { "code": null, "e": 16362, "s": 16226, "text": "However, I hope that I’ve demonstrated how visualizations can help us digest complex datasets and begin to tackle challenging problems." }, { "code": null, "e": 16370, "s": 16362, "text": "Cheers!" }, { "code": null, "e": 16407, "s": 16370, "text": "More by me on Finance and Investing:" }, { "code": null, "e": 16442, "s": 16407, "text": "The Dangers of Shorting Volatility" }, { "code": null, "e": 16506, "s": 16442, "text": "A Data Science Project I Did on Investing in Lending Club Loans" }, { "code": null, "e": 16532, "s": 16506, "text": "On Stock Market Downturns" }, { "code": null, "e": 16560, "s": 16532, "text": "More by me on Data Science:" }, { "code": null, "e": 16589, "s": 16560, "text": "The Random Forest Classifier" }, { "code": null, "e": 16614, "s": 16589, "text": "How Neural Networks Work" } ]
queue::front() and queue::back() in C++ STL
In this article we will be discussing the working, syntax and examples of queue::front() and queue::back() functions in C++ STL. Queue is a simple sequence or data structure defined in the C++ STL which does insertion and deletion of the data in FIFO(First In First Out) fashion. The data in a queue is stored in continuous manner. The elements are inserted at the end and removed from the starting of the queue. In C++ STL there is already a predefined template of queue, which inserts and removes the data in the similar fashion of a queue. queue::front() is an inbuilt function in C++ STL which is declared in header file. queue::front() returns a reference to the first element which is inserted in the queue container associated with it. Also in other words we can state that front() directly refers to the element which is oldest in a queue container. Like in the above given figure, head i.e. 1 is the first element which has been entered in the queue and tail i.e. -4 is the last or the most recent element which is entered in the queue myqueue.front(); This function accepts no parameter This function returns a reference to the element which is first inserted in the queue container. Input: queue<int> myqueue = {10, 20, 30, 40}; myqueue.front(); Output: Front element of the queue = 10 Live Demo #include <iostream> #include <queue> using namespace std; int main(){ queue<int> Queue; Queue.push(10); Queue.push(20); Queue.push(30); Queue.push(40); Queue.push(40); cout<<"Element in front of a queue is: "<<Queue.front(); return 0; } If we run the above code it will generate the following output − Element in front of a queue is: 10 queue::back() is an inbuilt function in C++ STL which is declared in header file. queue::back() returns a reference to the last element which is inserted in the queue container associated with it. Also in other words we can state that back() directly refers to the element which is newest in a queue container. myqueue.back(); This function accepts no parameter This function returns a reference to the element which is last inserted in the queue container. Input: queue<int> myqueue = {10, 20 30, 40}; myqueue.back(); Output: Back element of the queue = 40 Live Demo #include <iostream> #include <queue> using namespace std; int main(){ queue<int> Queue; Queue.push(10); Queue.push(20); Queue.push(30); Queue.push(40); Queue.push(50); cout<<"Elements at the back of the queue is: "<<Queue.back(); return 0; } If we run the above code it will generate the following output − Elements at the back of the queue is: 50
[ { "code": null, "e": 1191, "s": 1062, "text": "In this article we will be discussing the working, syntax and examples of queue::front() and queue::back() functions in C++ STL." }, { "code": null, "e": 1605, "s": 1191, "text": "Queue is a simple sequence or data structure defined in the C++ STL which does insertion and deletion of the data in FIFO(First In First Out) fashion. The data in a queue is stored in continuous manner. The elements are inserted at the end and removed from the starting of the queue. In C++ STL there is already a predefined template of queue, which inserts and removes the data in the similar fashion of a queue." }, { "code": null, "e": 1921, "s": 1605, "text": "queue::front() is an inbuilt function in C++ STL which is declared in header file. queue::front() returns a reference to the first element which is inserted in the queue container associated with it. Also in other words we can state that front() directly refers to the element which is oldest in a queue container." }, { "code": null, "e": 2108, "s": 1921, "text": "Like in the above given figure, head i.e. 1 is the first element which has been entered in the queue and tail i.e. -4 is the last or the most recent element which is entered in the queue" }, { "code": null, "e": 2125, "s": 2108, "text": "myqueue.front();" }, { "code": null, "e": 2160, "s": 2125, "text": "This function accepts no parameter" }, { "code": null, "e": 2257, "s": 2160, "text": "This function returns a reference to the element which is first inserted in the queue container." }, { "code": null, "e": 2372, "s": 2257, "text": "Input: queue<int> myqueue = {10, 20, 30, 40};\n myqueue.front();\nOutput:\n Front element of the queue = 10" }, { "code": null, "e": 2383, "s": 2372, "text": " Live Demo" }, { "code": null, "e": 2647, "s": 2383, "text": "#include <iostream>\n#include <queue>\nusing namespace std;\nint main(){\n queue<int> Queue;\n Queue.push(10);\n Queue.push(20);\n Queue.push(30);\n Queue.push(40);\n Queue.push(40);\n cout<<\"Element in front of a queue is: \"<<Queue.front();\n return 0;\n}" }, { "code": null, "e": 2712, "s": 2647, "text": "If we run the above code it will generate the following output −" }, { "code": null, "e": 2747, "s": 2712, "text": "Element in front of a queue is: 10" }, { "code": null, "e": 3059, "s": 2747, "text": "queue::back() is an inbuilt function in C++ STL which is declared in header file. queue::back() returns a reference to the last element which is inserted in the queue container associated with it. Also in other words we can state that back() directly refers to the element which is newest in a queue container." }, { "code": null, "e": 3075, "s": 3059, "text": "myqueue.back();" }, { "code": null, "e": 3110, "s": 3075, "text": "This function accepts no parameter" }, { "code": null, "e": 3206, "s": 3110, "text": "This function returns a reference to the element which is last inserted in the queue container." }, { "code": null, "e": 3318, "s": 3206, "text": "Input: queue<int> myqueue = {10, 20 30, 40};\n myqueue.back();\nOutput:\n Back element of the queue = 40" }, { "code": null, "e": 3329, "s": 3318, "text": " Live Demo" }, { "code": null, "e": 3598, "s": 3329, "text": "#include <iostream>\n#include <queue>\nusing namespace std;\nint main(){\n queue<int> Queue;\n Queue.push(10);\n Queue.push(20);\n Queue.push(30);\n Queue.push(40);\n Queue.push(50);\n cout<<\"Elements at the back of the queue is: \"<<Queue.back();\n return 0;\n}" }, { "code": null, "e": 3663, "s": 3598, "text": "If we run the above code it will generate the following output −" }, { "code": null, "e": 3704, "s": 3663, "text": "Elements at the back of the queue is: 50" } ]
Clojure - Maps get
Returns the value mapped to key, not-found or nil if key is not present. Following is the syntax. (get hmap key) Parameters − ‘hmap’ is the map of hash keys and values. ‘key’ is the key for which the value needs to be returned. Return Value − Returns the value of the key passed to the get function. Following is an example of get in Clojure. (ns clojure.examples.example (:gen-class)) (defn example [] (def demokeys (hash-map "z" "1" "b" "2" "a" "3")) (println demokeys) (println (get demokeys "b"))) (example) The above code produces the following output. {z 1, b 2, a 3} 2 Print Add Notes Bookmark this page
[ { "code": null, "e": 2447, "s": 2374, "text": "Returns the value mapped to key, not-found or nil if key is not present." }, { "code": null, "e": 2472, "s": 2447, "text": "Following is the syntax." }, { "code": null, "e": 2488, "s": 2472, "text": "(get hmap key)\n" }, { "code": null, "e": 2603, "s": 2488, "text": "Parameters − ‘hmap’ is the map of hash keys and values. ‘key’ is the key for which the value needs to be returned." }, { "code": null, "e": 2675, "s": 2603, "text": "Return Value − Returns the value of the key passed to the get function." }, { "code": null, "e": 2718, "s": 2675, "text": "Following is an example of get in Clojure." }, { "code": null, "e": 2899, "s": 2718, "text": "(ns clojure.examples.example\n (:gen-class))\n(defn example []\n (def demokeys (hash-map \"z\" \"1\" \"b\" \"2\" \"a\" \"3\"))\n (println demokeys)\n (println (get demokeys \"b\")))\n(example)" }, { "code": null, "e": 2945, "s": 2899, "text": "The above code produces the following output." }, { "code": null, "e": 2964, "s": 2945, "text": "{z 1, b 2, a 3}\n2\n" }, { "code": null, "e": 2971, "s": 2964, "text": " Print" }, { "code": null, "e": 2982, "s": 2971, "text": " Add Notes" } ]
.NET Core - Adding References to Library
In this chapter, we will discuss how to add references to your library. Adding references to library is like adding references to your other projects, like console project and UWP project. You can now see that the PCL project has some references by default. You can also add other references as per your application need. In the PCL library, you can also see the project.json file. { "supports": {}, "dependencies": { "NETStandard.Library": "1.6.0", "Microsoft.NETCore.Portable.Compatibility": "1.0.1" }, "frameworks": { "netstandard1.3": {} } } One method of adding references to your library is by typing it directly in the project.json file. As you can see that we have added some references under the dependencies section as shown in the following code. { "supports": {}, "dependencies": { "NETStandard.Library": "1.6.0", "Microsoft.NETCore.Portable.Compatibility": "1.0.1", "System.Runtime.Serialization.Json": "4.0.3", "Microsoft.EntityFrameworkCore": "1.1.0" }, "frameworks": { "netstandard1.3": {} } } Let us now save this file and you will see that references are added to your library now. The other method of adding references to your library is the NuGet Package Manager. Let us now right-click on the StringLibrary (Portable) project and select Mange NuGet Packages... On the Browse tab, you can search any NuGet package; let us say we want to add “System.Runtime.Serialization.Primitives” package. Click the Install button, which will display the following screen. Now, click the OK button. Finally, click the I Accept button to start installation of this NuGet package. Once installation is finished, then you will see that the “System.Runtime.Serialization.Primitives” NuGet package is added to your library. Print Add Notes Bookmark this page
[ { "code": null, "e": 2575, "s": 2386, "text": "In this chapter, we will discuss how to add references to your library. Adding references to library is like adding references to your other projects, like console project and UWP project." }, { "code": null, "e": 2708, "s": 2575, "text": "You can now see that the PCL project has some references by default. You can also add other references as per your application need." }, { "code": null, "e": 2768, "s": 2708, "text": "In the PCL library, you can also see the project.json file." }, { "code": null, "e": 2974, "s": 2768, "text": "{ \n \"supports\": {}, \n \"dependencies\": { \n \"NETStandard.Library\": \"1.6.0\", \n \"Microsoft.NETCore.Portable.Compatibility\": \"1.0.1\" \n }, \n \"frameworks\": { \n \"netstandard1.3\": {} \n } \n}" }, { "code": null, "e": 3186, "s": 2974, "text": "One method of adding references to your library is by typing it directly in the project.json file. As you can see that we have added some references under the dependencies section as shown in the following code." }, { "code": null, "e": 3495, "s": 3186, "text": "{ \n \"supports\": {}, \n \"dependencies\": { \n \"NETStandard.Library\": \"1.6.0\", \n \"Microsoft.NETCore.Portable.Compatibility\": \"1.0.1\", \n \"System.Runtime.Serialization.Json\": \"4.0.3\", \n \"Microsoft.EntityFrameworkCore\": \"1.1.0\" \n }, \n \"frameworks\": { \n \"netstandard1.3\": {} \n } \n} " }, { "code": null, "e": 3585, "s": 3495, "text": "Let us now save this file and you will see that references are added to your library now." }, { "code": null, "e": 3767, "s": 3585, "text": "The other method of adding references to your library is the NuGet Package Manager. Let us now right-click on the StringLibrary (Portable) project and select Mange NuGet Packages..." }, { "code": null, "e": 3897, "s": 3767, "text": "On the Browse tab, you can search any NuGet package; let us say we want to add “System.Runtime.Serialization.Primitives” package." }, { "code": null, "e": 3964, "s": 3897, "text": "Click the Install button, which will display the following screen." }, { "code": null, "e": 3990, "s": 3964, "text": "Now, click the OK button." }, { "code": null, "e": 4210, "s": 3990, "text": "Finally, click the I Accept button to start installation of this NuGet package. Once installation is finished, then you will see that the “System.Runtime.Serialization.Primitives” NuGet package is added to your library." }, { "code": null, "e": 4217, "s": 4210, "text": " Print" }, { "code": null, "e": 4228, "s": 4217, "text": " Add Notes" } ]
Deep Dive Into Desision Trees and Random Forest | by Vardaan Bajaj | Towards Data Science
In this post, we’ll go through: Terminology of Decision TreesWays of Measuring ImpurityCART AlgorithmConstruction of a Decision Tree by hand using CARTWhy choose Random Forest over Decision TreesDiversification of Decision Trees in Random ForestImproving Titanic Dataset classifier using Random Forest Terminology of Decision Trees Ways of Measuring Impurity CART Algorithm Construction of a Decision Tree by hand using CART Why choose Random Forest over Decision Trees Diversification of Decision Trees in Random Forest Improving Titanic Dataset classifier using Random Forest In the previous post, we went through Support Vector Machines in great detail and also solved fraudulent credit card transaction dataset from Kaggle. In this post, we’ll be looking at 2 more supervised learning algorithms: Decision Trees and Random Forest. After completing this post, we would have pretty much covered all the widely used supervised machine learning algorithms in the industry. The term decision tree is pretty much self-explanatory and its working is similar to a human’s decision making power. How do humans make decisions? First of all, humans define the objective. In machine learning, the objective of a particular task is determined by the dataset. Once humans have a defined objective, they answer various questions/perform various tasks in order to achieve that objective. The first task that is performed to achieve the objective is analogous to the root node of the decision tree. It is representative of the objective of the decision tree. The root node branches out to a certain set of options and each of these options have their own set of options. This process perpetuates until we arrive at the final decision. Now, each of these options is analogous to a decision node and the final decision is represented by a leaf node. In almost all the cases, the root node also acts as a decision node. For huge decision trees, the output of a decision node is a number of decision nodes, except at the deepest level of the tree, where it is the leaf node. Decision Tree modelling is a supervised learning algorithm which can be used for both, continuous and discrete valued datasets, both in regression and classification problems. Most commonly, a decision tree is used as a classifier that recursively partitions data into categories. Decision tree is a directed tree i.e. once we reach particular node in the tree, we cannot backtrack to the previous node i.e. parent nodes are not accessible from child nodes. After seeing the above example of a decision tree, we can see that the algorithm decides that the best question to ask first is the color of the car. All other questions follow some order as well. The order of asking questions is extremely important otherwise the decision tree can become very complex for a simple scenario like the one shown above. How does the decision tree determine the order of questions it needs to ask? The order of questions being asked depends on which question leads to a good split of the data at that level. The split of data at each node happens in a way similar to binary search. At the root node, we have the entire dataset. The root node should split the data into fed to it into 2 or more groups, where the data in each group has similar attributes. Suppose the root node splits data into 3 groups, then these 3 groups will be the 3 children of the root node and each of these 3 nodes will perform this operation of splitting the data, creating more children and this process is carried on for each node until that node has no more splits to make (leaf node), which is the point where predictions are made. How does a decision tree decide which question leads to a good split and which question doesn’t? This is quantified by measuring impurity. The problem of learning an optimal decision tree is NP-Complete, so in order to better mimic the optimal solution, the concept of impurity came into existence. Impurity is a measure of homogeneity of data. Data is said to be pure or homogenous if it only contains a single class. The more the classes in the data, the more impure it is. Each node in the decision tree, except the leaf nodes, contains data which has a potential of splitting into further groups i.e. each node has some sort of impurity related to data. Less impure nodes require less information to describe them and more impure nodes require more information to describe them. Hence, sub-nodes of a node have more purity than their parent nodes. There are various methods to measure impurity, but the most commonly used are Information Gain and Gini Index. Let’s look at them one by one. Information Gain is used to determine which feature/attribute gives us the maximum information about a class. It is based on the concept of entropy. Entropy in statistics is analogous to entropy in thermodynamics where it signifies disorder. Higher the entropy, more the randomness (i.e. less purity) and it becomes difficult to draw conclusions from the given information. For totally pure data sample i.e. when only one class exists, the entropy is the least (0) and if data is distributed between all the classes equally, then the entropy is the highest (1). The binary cross-entropy loss function that we defined for Logistic Regression is quite similar to entropy. For a dataset with ‘c’ different classes, entropy is measured as: where pi represents the fraction of examples in a given class i. In the example in the image above, there are 2 classes so c=2. p(yes) = 9/14 (0.64) and p(no) = 5/14 (0.36). Once entropy for a node is computed, then the information gain of a specific output given a particular feature is calculated as: where S is the output class, A is a particular feature of the dataset and P has the same meaning defined above (for pi). Due to the high computational time of the log function, Gini Index is preferred over information gain for practical purposes. Formally, Gini Index measures the probability of a particular variable being wrongly classified when it is randomly chosen. The probability value of 0 means that the variable couldn’t be wrongly classified and it’s possible only when we have only one output class i.e. the data is 100% pure. As the Gini Index value increases, the chances of misclassification of a particular variable increases since the impurity increases. The information conveyed by these values resonate with the entropy values. For a dataset with ‘c’ classes, Gini Index is defined as: where pi represents the fraction of examples in a given class i, which is similar to the entropy definition. There are many more measures of impurity like chi-square, classification error, etc. but the main idea here was to familiarize the readers with impurity measurement methods. One important thing to note here is that these impurity measurement functions play a role analogous to the cost function. Constructing a decision tree is actually partitioning of the input data features, which leads to 2 or more sub-nodes and this process is carried on recursively for each sub-node. Once this tree is created, features have been partitioned throughout the nodes. Various decision tree algorithms for classification are compared along the following lines: (i) The splitting criteria (ii) Techniques to eliminate/reduce overfitting (iii) Handling incomplete data Some of the various algorithms for decision tree construction are CART, ID3, C4.5, C5.0, CHAID, MARS, etc. In this post, we’ll be discussing CART in great detail. CART is one of the most widely used and a highly effective decision tree algorithm. As the name suggests, CART algorithm is used to generate both, classification and regression decision trees. We’ll be focussing on the classification part here. It is used to solve multi-class classification problem (for binary classification, it generates a binary tree) and uses Gini index as a metric to evaluate the split of a feature node in the decision tree. In CART algorithm, the objective is to minimize the cost function (Gini Index) at each node. The selection of the input variables/features that decides the specific split for each node is selected in a greedy way to minimize the cost function. In this greedy way, a number of split points with different set of variables/features are considered and that split is chosen which results in the minimum value for the Gini Index (i.e. more homogenous splits) at that node. This process is carried out recursively for all sub-nodes in the tree. This process can continue on forever and can lead to the formation of many unnecessary sub-nodes, so it needs to be stopped. For this, we count the total number of training examples that pass through each node of the tree. This number is a hyperparameter and is tuned according to the dataset and the optimal choice of this number leads to formation of robust decision trees. To give some intuition, if a node of the tree only has one training example that passes through it, this means that the generated decision tree is suffering from overfitting since it has given so much importance to just one example that it called for its separate node. Such a decision tree needs to reduce its complexity which is achieved using pruning. Decision tree pruning is a technique to reduce the size of a decision tree by removing sections of the tree that provide little power to the classification objective. 2 popular pruning methods are: (i) Reduced Error Pruning (bottom-up) (ii) Cost complexity pruning (top-down) More about these pruning methods can be found here. Now that we know the underlying logic behind the CART algorithm, let’s see through an example of binary classification, how a decision tree is constructed using CART. Let’s use 10 records of UCI machine learning Zoo Animal Classification dataset to build a decision tree by hand. Given the features “toothed”, “hair”, “breathes”, “legs”, the decision tree should output the species of the animal (mammal/reptile). Let’s start with each feature one by one. We observe in the data that all the input features are represented by Boolean values. (i) toothed: Let’s summarize the output (species) wrt the ‘toothed’ feature values. Gini Index (toothed = true) = 1 — {(5/8)2 + (3/8)2} = 1–0.39–0.14 = 0.47 Gini Index (toothed = false) = 1 — {(1/2)2 + (1/2)2} = 1–0.25 -0.25 = 0.5 To obtain the final Gini index of ‘species’ wrt ‘toothed’, we use the weighted sum of the above calculated values as: Gini Index(toothed) = (8/10) * 0.47 + (2/10) * 0.5 = 0.38 + 0.1 = 0.48 (ii) hair: Let’s summarize the output (species) wrt the ‘hair’ feature values. Gini Index(hair = true) = 1 — {(5/5)2 + (0/5)2} = 1–1–0 = 0 Gini Index(hair = false) = 1 — {(1/5)2 + (4/5)2} = 1–0.04–0.64 = 0.32 To obtain the final Gini index of ‘species’ wrt ‘hair’, we use the weighted sum of the above calculated values as: Gini Index(hair) = (5/10) * 0 + (5/10) * 0.32 = 0.16 (iii) breathes: Let’s summarize the output (species) wrt the ‘breathes’ feature values. Gini Index (breathes = true) = 1 — {(6/9)2 + (3/9)2} = 1–0.45–0.11 = 0.44 Gini Index (breathes = false) = 1 — {(0/1)2 + (1/1)2} = 1–0–1 = 0 To obtain the final Gini index of ‘species’ wrt ‘breathes’, we use the weighted sum of the above calculated values as: Gini Index(breathes) = (9/10) * 0.44 + (1/10) * 0 = 0.40 (iv) legs: Let’s summarize the output (species) wrt the ‘legs’ feature values. Gini Index (legs = true) = 1 — {(6/7)2 + (1/7)2} = 1–0.73–0.02 = 0.25 Gini Index (breathes = false) = 1 — {(0/3)2 + (3/3)2} = 1–0–1 = 0 To obtain the final Gini index of ‘species’ wrt ‘legs’, we use the weighted sum of the above calculated values as: Gini Index(breathes) = (7/10) * 0.25 + (3/10) * 0 = 0.18 Now that we have calculated Gini Index for the output variable against all 4 input features, we need to choose the root node. The root node is chosen such that it has minimum Gini Index. The lower the Gini Index, the higher the chances of predicting the answer early (due to more purity of the node). So here, we choose hair as the root node. The decision tree at this point looks like: Let’s first consider the case when ‘hair’ takes the values of TRUE. Let’s calculate Gini Index for the output against the input features excluding the hair feature, when hair takes the value of TRUE. (i) toothed: Let’s summarize the output (species) wrt the ‘toothed’ feature values when hair = TRUE Gini Index (hair = true & toothed = true) = 1 — {(4/4)2 + (0/4)2} = 1–1–0 = 0 Gini Index (hair = true & toothed = false) = 1 — {(1/1)2 + (0/1)2} = 1–1–0 = 0 To obtain the final Gini index of ‘species’ wrt ‘toothed’ for ‘hair=true’, we use the weighted sum of the above calculated values as: Gini Index (toothed & hair = true) = (4/5) * 0 + (1/5) * 0 = 0 + 0 = 0 (ii) breathes: Let’s summarize the output (species) wrt the ‘breathes’ feature values when hair = TRUE Gini Index (hair = true & breathes = true) = 0 Gini Index (hair = true & breathes = false) = 0 To obtain the final Gini index of ‘species’ wrt ‘breathes’ for ‘hair=true’, we use the weighted sum of the above. Gini Index (breathes & hair = true) = 0 (iii) legs: Let’s summarize the output (species) wrt the ‘legs feature values when hair = TRUE Gini Index (hair = true & legs = true) = 0 Gini Index (hair = true & legs = false) = 0 To obtain the final Gini index of ‘species’ wrt ‘legs’ for ‘hair=true’, we use the weighted sum of the above. Gini Index (legs & hair = true) = 0 In all the above cases, the Gini Index is equal to 0. This means that if we predict that the species has hair, it can be classified as a ‘mammal’ based on the given dataset with high confidence. At this point, the decision tree looks like: Now, let’s consider the case when ‘hair’ takes the values of FALSE. Let’s calculate Gini Index for the output against the input features excluding the hair feature, when hair takes the value of FALSE. (i) toothed: Let’s summarize the output (species) wrt the ‘toothed’ feature values when hair = FALSE Gini Index (hair = false & toothed = true) = 1 — {(1/4)2 + (3/4)2} = 1–0.06–0.56 = 0.38 Gini Index (hair = false & toothed = false) = 1 — {(0/1)2 + (1/1)2} = 1–0–1 = 0 To obtain the final Gini index of ‘species’ wrt ‘toothed’ for ‘hair=false’, we use the weighted sum of the above calculated values as: Gini Index (toothed & hair = false) = (4/5) * 0.38 + (1/5) * 0 = 0.3 + 0 = 0.3 (ii) breathes: Let’s summarize the output (species) wrt the ‘breathes’ feature values when hair = FALSE Gini Index (hair = false & breathes = true) = 1 — {(1/4)2 + (3/4)2} = 1–0.06–0.56 = 0.38 Gini Index (hair = false & breathes = false) = 1 — {(0/1)2 + (1/1)2} = 1–0–1 = 0 To obtain the final Gini index of ‘species’ wrt ‘breathes’ for ‘hair=false’, we use the weighted sum of the above calculated values as: Gini Index (breathes & hair = false) = (4/5) * 0.38 + (1/5) * 0 = 0.3 + 0 = 0.3 (iii) legs: Let’s summarize the output (species) wrt the ‘legs’ feature values when hair = FALSE Gini Index (hair = false & legs = true) = 1 — {(1/2)2 + (1/2)2} = 1–0.25–0.25 = 0.5 Gini Index (hair = false & legs = false) = 1 — {(0/3)2 + (3/3)2} = 1–0–1 = 0 To obtain the final Gini index of ‘species’ wrt ‘legs’ for ‘hair=false’, we use the weighted sum of the above calculated values as: Gini Index (toothed & hair = false) = (2/5) * 0.5 + (3/5) * 0 = 0.2 + 0 = 0.2 In the above 3 cases, we see that the Gini Index is minimum for the ‘legs’ feature given the condition ‘hair=FALSE’. So, ‘legs’ is chosen as the child node when ‘hair=FALSE’. At this point, the decision tree looks like: To proceed further, let us consider the cases when legs = TRUE (hair = FALSE is implied now). Let’s calculate Gini Index for the output against the input features excluding the hair and legs feature, when hair takes the value of FALSE and legs takes the value of TRUE. (i) toothed: Let’s summarize the output (species) wrt the ‘toothed’ feature values when hair = FALSE and legs = TRUE. Gini Index (hair = false & legs = true & toothed=true) = 0 Gini Index (hair = false & legs = true & toothed=false) = 0 To obtain the final Gini index of ‘species’ wrt ‘toothed’ for ‘hair=false’ and legs=’true’, we use the weighted sum of the above. Gini Index (toothed & hair = false & legs = true) = 0 (ii) breathes: Let’s summarize the output (species) wrt the ‘breathes’ feature values when hair = FALSE and legs = TRUE. Gini Index (hair = false & legs = true & breathes=true) = 1 — {(1/2)2 + (1/2)2} = 1–0.25–0.25 = 0.5 Gini Index (hair = false & legs = true & breathes=false) = 0 To obtain the final Gini index of ‘species’ wrt ‘toothed’ for ‘hair=false’ and legs=’true’, we use the weighted sum of the above. Gini Index (toothed & hair = false & legs = true) = (2/2) * 0.5 + (0/2) * 0 = 0.5 In the above 2 cases, we see that ‘toothed’ has lower Gini Index, so it is selected as a child node when ‘legs = TRUE’. The decision tree now looks like: Now, let’s consider the case when ‘legs’ takes the value of FALSE. From the above scenario, we can clearly see that when ‘hair = TRUE’ and ‘legs = FALSE’, the output ‘species’ is ‘Reptile’ in all the cases. Hence, we without calculating the Gini Index, we can safely conclude that the child node produced for the decision tree will be a leaf node with the value ‘Reptile’. (Remember that when we just considered ‘hair = TRUE’ case, we saw that all the output ‘species’ values were ‘Mammals’ and by calculating Gini Index, we directly produced a leaf node with the value ‘Mammal’) Proceeding further, let’s consider the case when ‘toothed = TRUE’. Here, the cases ‘hair = FALSE’ and ‘legs = TRUE’ are implied. Here, we only have one record which is classified as mammal. Hence, this combination of features results in the output ‘species’ being a ‘Mammal’. Considering the case ‘toothed = FALSE’, we get In a similar way, we can conclude that the output ‘species’ for this set of features is a ‘Reptile’. Now, we have finally constructed the decision tree on which we can throw some test data to make predictions. If you’ve followed carefully so far, you may have observed that all the variables in this dataset were categorical variables (i.e. the features had a finite set of distinct values (2) like TRUE and FALSE). In the datasets that you encounter in real life have a mixture of categorical and continuous variables. In order to construct decision trees from a dataset having continuous values, these continuous values are converted to categorical values by defining a certain threshold. Using this, decision trees can be constructed for any type of data. Although decision trees are quite intuitive and simple to create, they suffer from the following drawbacks. 1. They are unstable, meaning that a small change in the data can lead to a large change in the structure of the optimal decision tree. 2. Calculations can get very complex, particularly if many values are uncertain and/or if many outcomes are linked. 3. Decision Trees tend to overfit to the training data very quickly and can become very inaccurate. Due to the aforementioned disadvantages of Decision Trees, Random Forest algorithm is used instead of Decision Trees. Random Forest algorithm employs the use of a large number of decision trees that operate as an ensemble. A machine learning ensemble consists of only a concrete finite set of alternative models, but typically allows for much more flexible structure to exist among those alternatives. Random Forest algorithm is based on the concept of The Wisdom of Crowds. Wisdom of Crowds is a very effective technique employed in various tasks of computer science. The fact that Wikipedia (fully crowdsourced, editable by everyone) and Britannica (fully written by experts) have been found to have similar levels of quality standards is a testament to the power of the wisdom of crowds. Every individual in the crowd makes their prediction with a certain error. Since all the individuals act independently, their errors are also independent to each other’s. In other words, these errors are uncorrelated i.e. when considered in a bunch, these errors cancel each other out and what we’re left with is a good, accurate prediction. This is the way how Random Forest algorithm operates. Random Forest algorithm uses a large number of decision trees (creating a forest), which are independent of/uncorrelated to each other, from a given dataset, which collectively outperform any of its constituent trees. This little to no correlation between the constituent trees in the forest imparts the element of randomness to this ensemble method, which produces a wonderful effect of protecting trees from each other for their individual errors. But we need to make sure that the outputs of the various decision trees that we make randomly for random forest to work should not be completely random. In order to ensure this, we need to make sure that: (i) The output should be dependent on all the training features and not only some of them in order to make random decision trees effective. (ii) The predictions made by each decision tree should have low correlations with each other in order to make the wisdom of crowds concept to work. The first point is the feature of the dataset that we collect. So, as a data scientist, how do we make sure that the constituent decision trees are as diversified as possible? For this, random forest uses the following 2 techniques: (i) Bagging (ii) Feature Randomness One of the major drawbacks of Decision Trees was that they were not robust to even small changes in the data which made them prone to overfitting. Let’s understand how bagging solves this problem. Consider a training dataset with M ( >> 50) training examples and for simplicity let’s consider these are M numbers in the range of 1 to 50. If we want to use B decision trees for Random Forest, then through bagging, each of the B decision trees is made up of M training examples, but instead of using all the M training examples, a random subset of these training examples (here numbers in the range from 1 to 50) is used and numbers from this subset are randomly repeated until a total of M training examples are created. How does bagging help? By creating a large number of decision trees with a large number of training examples distributed randomly across decision trees, the aggregate result is a random forest model which is robust to even small changes in the data, thereby eliminating one of the major disadvantages of decision trees (by using decision trees). The idea of using random training examples can also be applied to the features of the training data. Recall that while constructing decision trees, when deciding the split at each node, we take all the features into account. If the training dataset has N features, then in feature randomness, while creating each of the B decision trees, the decision of splitting a node is made by using a random subset of these N features instead of using all N features. When both bagging and feature randomness are used to make a forest of decision trees for random forest, each of the decision trees constitutes of a random subset of training examples as well as a random subset of features. This randomness adds a lot of robustness and stability to a Random Forest classifier by ensuring the formation of uncorrelated decision trees that protect each other from their errors. Once all these constituent decision trees make a prediction, majority voting takes place in order to get the final prediction of the classifier. We’ve looked at a lot of concepts so far. From the mathematics behind decision trees to creating a decision tree by hand and then seeing how decision trees are used in random forest, we’ve come a long way. Now is the time that we get hands on practice for a Random Forest classifier and for this post, we won’t be dealing with a new dataset, instead we’ll be improving upon our Logistic Regression model which we trained over the Titanic dataset in this post. This is the way actual machine learning tasks are carried out. Various machine learning models are tried and the one that works the best and justifies the results obtained is used in practice. Remember, persistence is the key. So let’s get started. The dataset for the Titanic problem can be found here. We have to predict whether a passenger on the Titanic will survive or not given the data corresponding to them. We have already applied data pre-processing and logistic regression in this post. Now, we will use the same pre-processed data from the previous post, but will apply Random Forest classification this time. Dataset after pre-processing looks like: After applying recursive feature elimination(RFE), we obtain the top 8 most important features that will help in training the Random Forest Classifier. More on RFE can be found here. from sklearn.ensemble import RandomForestClassifierfrom sklearn.feature_selection import RFEcols = [“Age”, “SibSp”, “Parch”, “Fare”, “Pclass_1”, “Pclass_2”, “Pclass_3”, “Embarked_C”, “Embarked_Q”, “Embarked_S”, “Sex_male”]X = final_train[cols]y = final_train[‘Survived’]model = RandomForestClassifier()# selecting top 8 featuresrfe = RFE(model, n_features_to_select = 8)rfe = rfe.fit(X, y)print(‘Top 8 most important features: ‘ + str(list(X.columns[rfe.support_]))) Now that we have the list of features we should use for training the classifier, let us apply Random Forest classifier on the dataset. Unlike Logistic Regression, Random Forest has a large number of parameters that need to be fed into the model. The most important parameters are: 1. n_estimators = number of trees in the foreset 2. max_features = max number of features considered for splitting a node 3. max_depth = max number of levels in each decision tree 4. min_samples_split = min number of data points placed in a node before the node is split 5. min_samples_leaf = min number of data points allowed in a leaf node 6. bootstrap (like bagging) = method for sampling data points (with or without replacement) These are a lot of parameters and it is difficult to obtain their optimal value together manually. So, we make use of the computation power by passing the model a set of values for each parameter, the parameter applies these values to the dataset and chooses the best ones. For this dataset, this took me about 5 minutes to get optimal values using Random Hyperparameter Grid technique. # Number of trees in random forestn_estimators = [int(x) for x in np.linspace(start = 200, stop = 2000, num = 10)]# Number of features to consider at every splitmax_features = ['auto', 'sqrt']# Maximum number of levels in treemax_depth = [int(x) for x in np.linspace(10, 110, num = 11)]max_depth.append(None)# Minimum number of samples required to split a nodemin_samples_split = [2, 5, 10]# Minimum number of samples required at each leaf nodemin_samples_leaf = [1, 2, 4]# Method of selecting samples for training each tree (bagging)bootstrap = [True, False]# Creating random gridrandom_grid = {'n_estimators': n_estimators, 'max_features': max_features, 'max_depth': max_depth, 'min_samples_split': min_samples_split, 'min_samples_leaf': min_samples_leaf, 'bootstrap': bootstrap} On each iteration, the algorithm will choose a difference combination of the features. Altogether, there are 2 * 12 * 2 * 3 * 3 * 10 = 4320 settings! However, the benefit of a random search is that we are not trying every combination, but selecting at random to sample a wide range of values. # First create the base model to tunerf = RandomForestClassifier()# Random search of parameters, using 3 fold cross validation,# search across 100 different combinations, and use all available coresrf_random = RandomizedSearchCV(estimator = rf, param_distributions = random_grid, n_iter = 100, cv = 3, verbose=2, random_state=42, n_jobs = -1)# Fit the random search modelrf_random.fit(final_train[selected_features], final_train['Survived'])rf_random.best_params_ Now that we have an optimal set of parameters from the given range supplied to the algorithm, let’s train the random forest classifier, both with default values that sci-kit learn provides and with the values we obtained. X = final_train[selected_features]y = final_train['Survived']X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.15, random_state=2)# fitting both base random forest model and RandomizedSearchCV random forest modelbase_model = RandomForestClassifier()base_model.fit(X_train, y_train)best_random = RandomForestClassifier(n_estimators = 2000, min_samples_split= 5, min_samples_leaf = 1, max_features = 'sqrt', max_depth = 100, bootstrap = True)best_random.fit(X_train, y_train) Now that we have trained these models, let’s evaluate them using the evaluation function defined below. def evaluate(model, test_features, test_labels): predictions = model.predict(test_features) errors = abs(predictions - test_labels) accuracy = accuracy_score(test_labels, predictions) * 100 print('Model Performance') print('Average Error: {:0.4f} degrees.'.format(np.mean(errors))) print('Accuracy = {:0.2f}%.'.format(accuracy)) return accuracybase_accuracy = evaluate(base_model, X_test, y_test) random_accuracy = evaluate(best_random, X_test, y_test) We observe that the base model had a test accuracy of 84.33% whereas the model in which we fed the parameters obtained RandomizedSearchCV yielded test accuracy of 81.34%, which should have been higher than the base model’s accuracy. This can be due to the fact that the training dataset was not big enough or the values we supplied for random search to choose from might have included the range of optimal values. We can definitely toy around with it to improve our accuracy though. Similarly, I also applied GridSearchCV to check for the accuracy of the classifier which was again around 81%. The relatively low accuracy might be due to the reasons posited above. But, the key takeaway from this exercise is that we improved our model’s accuracy on the test set from 77.6% using Logistic Regression to around 84% using Random Forest algorithm, which indeed justified our discussion of Random Forest algorithm above. When I submitted the results of this model on Kaggle, I received a public score of 0.7751, which is better than the score we received for Logistic Regression classifier (0.7703), although not by much, but good enough to take a step forward to improve an already existing robust classifier. The entire code for this post can be found here. That’s it for this post. In all the posts so far, we have explored the most frequently used supervised machine learning algorithms in great detail. From the next post onwards, we’ll dive deep into the basics of Unsupervised Learning and also learn about various unsupervised learning algorithms, starting with K-means clustering.
[ { "code": null, "e": 204, "s": 172, "text": "In this post, we’ll go through:" }, { "code": null, "e": 474, "s": 204, "text": "Terminology of Decision TreesWays of Measuring ImpurityCART AlgorithmConstruction of a Decision Tree by hand using CARTWhy choose Random Forest over Decision TreesDiversification of Decision Trees in Random ForestImproving Titanic Dataset classifier using Random Forest" }, { "code": null, "e": 504, "s": 474, "text": "Terminology of Decision Trees" }, { "code": null, "e": 531, "s": 504, "text": "Ways of Measuring Impurity" }, { "code": null, "e": 546, "s": 531, "text": "CART Algorithm" }, { "code": null, "e": 597, "s": 546, "text": "Construction of a Decision Tree by hand using CART" }, { "code": null, "e": 642, "s": 597, "text": "Why choose Random Forest over Decision Trees" }, { "code": null, "e": 693, "s": 642, "text": "Diversification of Decision Trees in Random Forest" }, { "code": null, "e": 750, "s": 693, "text": "Improving Titanic Dataset classifier using Random Forest" }, { "code": null, "e": 1145, "s": 750, "text": "In the previous post, we went through Support Vector Machines in great detail and also solved fraudulent credit card transaction dataset from Kaggle. In this post, we’ll be looking at 2 more supervised learning algorithms: Decision Trees and Random Forest. After completing this post, we would have pretty much covered all the widely used supervised machine learning algorithms in the industry." }, { "code": null, "e": 2230, "s": 1145, "text": "The term decision tree is pretty much self-explanatory and its working is similar to a human’s decision making power. How do humans make decisions? First of all, humans define the objective. In machine learning, the objective of a particular task is determined by the dataset. Once humans have a defined objective, they answer various questions/perform various tasks in order to achieve that objective. The first task that is performed to achieve the objective is analogous to the root node of the decision tree. It is representative of the objective of the decision tree. The root node branches out to a certain set of options and each of these options have their own set of options. This process perpetuates until we arrive at the final decision. Now, each of these options is analogous to a decision node and the final decision is represented by a leaf node. In almost all the cases, the root node also acts as a decision node. For huge decision trees, the output of a decision node is a number of decision nodes, except at the deepest level of the tree, where it is the leaf node." }, { "code": null, "e": 2688, "s": 2230, "text": "Decision Tree modelling is a supervised learning algorithm which can be used for both, continuous and discrete valued datasets, both in regression and classification problems. Most commonly, a decision tree is used as a classifier that recursively partitions data into categories. Decision tree is a directed tree i.e. once we reach particular node in the tree, we cannot backtrack to the previous node i.e. parent nodes are not accessible from child nodes." }, { "code": null, "e": 3829, "s": 2688, "text": "After seeing the above example of a decision tree, we can see that the algorithm decides that the best question to ask first is the color of the car. All other questions follow some order as well. The order of asking questions is extremely important otherwise the decision tree can become very complex for a simple scenario like the one shown above. How does the decision tree determine the order of questions it needs to ask? The order of questions being asked depends on which question leads to a good split of the data at that level. The split of data at each node happens in a way similar to binary search. At the root node, we have the entire dataset. The root node should split the data into fed to it into 2 or more groups, where the data in each group has similar attributes. Suppose the root node splits data into 3 groups, then these 3 groups will be the 3 children of the root node and each of these 3 nodes will perform this operation of splitting the data, creating more children and this process is carried on for each node until that node has no more splits to make (leaf node), which is the point where predictions are made." }, { "code": null, "e": 3968, "s": 3829, "text": "How does a decision tree decide which question leads to a good split and which question doesn’t? This is quantified by measuring impurity." }, { "code": null, "e": 4681, "s": 3968, "text": "The problem of learning an optimal decision tree is NP-Complete, so in order to better mimic the optimal solution, the concept of impurity came into existence. Impurity is a measure of homogeneity of data. Data is said to be pure or homogenous if it only contains a single class. The more the classes in the data, the more impure it is. Each node in the decision tree, except the leaf nodes, contains data which has a potential of splitting into further groups i.e. each node has some sort of impurity related to data. Less impure nodes require less information to describe them and more impure nodes require more information to describe them. Hence, sub-nodes of a node have more purity than their parent nodes." }, { "code": null, "e": 4823, "s": 4681, "text": "There are various methods to measure impurity, but the most commonly used are Information Gain and Gini Index. Let’s look at them one by one." }, { "code": null, "e": 5385, "s": 4823, "text": "Information Gain is used to determine which feature/attribute gives us the maximum information about a class. It is based on the concept of entropy. Entropy in statistics is analogous to entropy in thermodynamics where it signifies disorder. Higher the entropy, more the randomness (i.e. less purity) and it becomes difficult to draw conclusions from the given information. For totally pure data sample i.e. when only one class exists, the entropy is the least (0) and if data is distributed between all the classes equally, then the entropy is the highest (1)." }, { "code": null, "e": 5559, "s": 5385, "text": "The binary cross-entropy loss function that we defined for Logistic Regression is quite similar to entropy. For a dataset with ‘c’ different classes, entropy is measured as:" }, { "code": null, "e": 5862, "s": 5559, "text": "where pi represents the fraction of examples in a given class i. In the example in the image above, there are 2 classes so c=2. p(yes) = 9/14 (0.64) and p(no) = 5/14 (0.36). Once entropy for a node is computed, then the information gain of a specific output given a particular feature is calculated as:" }, { "code": null, "e": 6109, "s": 5862, "text": "where S is the output class, A is a particular feature of the dataset and P has the same meaning defined above (for pi). Due to the high computational time of the log function, Gini Index is preferred over information gain for practical purposes." }, { "code": null, "e": 6667, "s": 6109, "text": "Formally, Gini Index measures the probability of a particular variable being wrongly classified when it is randomly chosen. The probability value of 0 means that the variable couldn’t be wrongly classified and it’s possible only when we have only one output class i.e. the data is 100% pure. As the Gini Index value increases, the chances of misclassification of a particular variable increases since the impurity increases. The information conveyed by these values resonate with the entropy values. For a dataset with ‘c’ classes, Gini Index is defined as:" }, { "code": null, "e": 6776, "s": 6667, "text": "where pi represents the fraction of examples in a given class i, which is similar to the entropy definition." }, { "code": null, "e": 7072, "s": 6776, "text": "There are many more measures of impurity like chi-square, classification error, etc. but the main idea here was to familiarize the readers with impurity measurement methods. One important thing to note here is that these impurity measurement functions play a role analogous to the cost function." }, { "code": null, "e": 7331, "s": 7072, "text": "Constructing a decision tree is actually partitioning of the input data features, which leads to 2 or more sub-nodes and this process is carried on recursively for each sub-node. Once this tree is created, features have been partitioned throughout the nodes." }, { "code": null, "e": 7423, "s": 7331, "text": "Various decision tree algorithms for classification are compared along the following lines:" }, { "code": null, "e": 7450, "s": 7423, "text": "(i) The splitting criteria" }, { "code": null, "e": 7498, "s": 7450, "text": "(ii) Techniques to eliminate/reduce overfitting" }, { "code": null, "e": 7529, "s": 7498, "text": "(iii) Handling incomplete data" }, { "code": null, "e": 7776, "s": 7529, "text": "Some of the various algorithms for decision tree construction are CART, ID3, C4.5, C5.0, CHAID, MARS, etc. In this post, we’ll be discussing CART in great detail. CART is one of the most widely used and a highly effective decision tree algorithm." }, { "code": null, "e": 8142, "s": 7776, "text": "As the name suggests, CART algorithm is used to generate both, classification and regression decision trees. We’ll be focussing on the classification part here. It is used to solve multi-class classification problem (for binary classification, it generates a binary tree) and uses Gini index as a metric to evaluate the split of a feature node in the decision tree." }, { "code": null, "e": 8681, "s": 8142, "text": "In CART algorithm, the objective is to minimize the cost function (Gini Index) at each node. The selection of the input variables/features that decides the specific split for each node is selected in a greedy way to minimize the cost function. In this greedy way, a number of split points with different set of variables/features are considered and that split is chosen which results in the minimum value for the Gini Index (i.e. more homogenous splits) at that node. This process is carried out recursively for all sub-nodes in the tree." }, { "code": null, "e": 9412, "s": 8681, "text": "This process can continue on forever and can lead to the formation of many unnecessary sub-nodes, so it needs to be stopped. For this, we count the total number of training examples that pass through each node of the tree. This number is a hyperparameter and is tuned according to the dataset and the optimal choice of this number leads to formation of robust decision trees. To give some intuition, if a node of the tree only has one training example that passes through it, this means that the generated decision tree is suffering from overfitting since it has given so much importance to just one example that it called for its separate node. Such a decision tree needs to reduce its complexity which is achieved using pruning." }, { "code": null, "e": 9610, "s": 9412, "text": "Decision tree pruning is a technique to reduce the size of a decision tree by removing sections of the tree that provide little power to the classification objective. 2 popular pruning methods are:" }, { "code": null, "e": 9648, "s": 9610, "text": "(i) Reduced Error Pruning (bottom-up)" }, { "code": null, "e": 9688, "s": 9648, "text": "(ii) Cost complexity pruning (top-down)" }, { "code": null, "e": 10154, "s": 9688, "text": "More about these pruning methods can be found here. Now that we know the underlying logic behind the CART algorithm, let’s see through an example of binary classification, how a decision tree is constructed using CART. Let’s use 10 records of UCI machine learning Zoo Animal Classification dataset to build a decision tree by hand. Given the features “toothed”, “hair”, “breathes”, “legs”, the decision tree should output the species of the animal (mammal/reptile)." }, { "code": null, "e": 10282, "s": 10154, "text": "Let’s start with each feature one by one. We observe in the data that all the input features are represented by Boolean values." }, { "code": null, "e": 10366, "s": 10282, "text": "(i) toothed: Let’s summarize the output (species) wrt the ‘toothed’ feature values." }, { "code": null, "e": 10439, "s": 10366, "text": "Gini Index (toothed = true) = 1 — {(5/8)2 + (3/8)2} = 1–0.39–0.14 = 0.47" }, { "code": null, "e": 10513, "s": 10439, "text": "Gini Index (toothed = false) = 1 — {(1/2)2 + (1/2)2} = 1–0.25 -0.25 = 0.5" }, { "code": null, "e": 10631, "s": 10513, "text": "To obtain the final Gini index of ‘species’ wrt ‘toothed’, we use the weighted sum of the above calculated values as:" }, { "code": null, "e": 10702, "s": 10631, "text": "Gini Index(toothed) = (8/10) * 0.47 + (2/10) * 0.5 = 0.38 + 0.1 = 0.48" }, { "code": null, "e": 10781, "s": 10702, "text": "(ii) hair: Let’s summarize the output (species) wrt the ‘hair’ feature values." }, { "code": null, "e": 10841, "s": 10781, "text": "Gini Index(hair = true) = 1 — {(5/5)2 + (0/5)2} = 1–1–0 = 0" }, { "code": null, "e": 10911, "s": 10841, "text": "Gini Index(hair = false) = 1 — {(1/5)2 + (4/5)2} = 1–0.04–0.64 = 0.32" }, { "code": null, "e": 11026, "s": 10911, "text": "To obtain the final Gini index of ‘species’ wrt ‘hair’, we use the weighted sum of the above calculated values as:" }, { "code": null, "e": 11079, "s": 11026, "text": "Gini Index(hair) = (5/10) * 0 + (5/10) * 0.32 = 0.16" }, { "code": null, "e": 11167, "s": 11079, "text": "(iii) breathes: Let’s summarize the output (species) wrt the ‘breathes’ feature values." }, { "code": null, "e": 11241, "s": 11167, "text": "Gini Index (breathes = true) = 1 — {(6/9)2 + (3/9)2} = 1–0.45–0.11 = 0.44" }, { "code": null, "e": 11307, "s": 11241, "text": "Gini Index (breathes = false) = 1 — {(0/1)2 + (1/1)2} = 1–0–1 = 0" }, { "code": null, "e": 11426, "s": 11307, "text": "To obtain the final Gini index of ‘species’ wrt ‘breathes’, we use the weighted sum of the above calculated values as:" }, { "code": null, "e": 11483, "s": 11426, "text": "Gini Index(breathes) = (9/10) * 0.44 + (1/10) * 0 = 0.40" }, { "code": null, "e": 11562, "s": 11483, "text": "(iv) legs: Let’s summarize the output (species) wrt the ‘legs’ feature values." }, { "code": null, "e": 11632, "s": 11562, "text": "Gini Index (legs = true) = 1 — {(6/7)2 + (1/7)2} = 1–0.73–0.02 = 0.25" }, { "code": null, "e": 11698, "s": 11632, "text": "Gini Index (breathes = false) = 1 — {(0/3)2 + (3/3)2} = 1–0–1 = 0" }, { "code": null, "e": 11813, "s": 11698, "text": "To obtain the final Gini index of ‘species’ wrt ‘legs’, we use the weighted sum of the above calculated values as:" }, { "code": null, "e": 11870, "s": 11813, "text": "Gini Index(breathes) = (7/10) * 0.25 + (3/10) * 0 = 0.18" }, { "code": null, "e": 12257, "s": 11870, "text": "Now that we have calculated Gini Index for the output variable against all 4 input features, we need to choose the root node. The root node is chosen such that it has minimum Gini Index. The lower the Gini Index, the higher the chances of predicting the answer early (due to more purity of the node). So here, we choose hair as the root node. The decision tree at this point looks like:" }, { "code": null, "e": 12325, "s": 12257, "text": "Let’s first consider the case when ‘hair’ takes the values of TRUE." }, { "code": null, "e": 12457, "s": 12325, "text": "Let’s calculate Gini Index for the output against the input features excluding the hair feature, when hair takes the value of TRUE." }, { "code": null, "e": 12557, "s": 12457, "text": "(i) toothed: Let’s summarize the output (species) wrt the ‘toothed’ feature values when hair = TRUE" }, { "code": null, "e": 12635, "s": 12557, "text": "Gini Index (hair = true & toothed = true) = 1 — {(4/4)2 + (0/4)2} = 1–1–0 = 0" }, { "code": null, "e": 12714, "s": 12635, "text": "Gini Index (hair = true & toothed = false) = 1 — {(1/1)2 + (0/1)2} = 1–1–0 = 0" }, { "code": null, "e": 12848, "s": 12714, "text": "To obtain the final Gini index of ‘species’ wrt ‘toothed’ for ‘hair=true’, we use the weighted sum of the above calculated values as:" }, { "code": null, "e": 12919, "s": 12848, "text": "Gini Index (toothed & hair = true) = (4/5) * 0 + (1/5) * 0 = 0 + 0 = 0" }, { "code": null, "e": 13022, "s": 12919, "text": "(ii) breathes: Let’s summarize the output (species) wrt the ‘breathes’ feature values when hair = TRUE" }, { "code": null, "e": 13069, "s": 13022, "text": "Gini Index (hair = true & breathes = true) = 0" }, { "code": null, "e": 13117, "s": 13069, "text": "Gini Index (hair = true & breathes = false) = 0" }, { "code": null, "e": 13231, "s": 13117, "text": "To obtain the final Gini index of ‘species’ wrt ‘breathes’ for ‘hair=true’, we use the weighted sum of the above." }, { "code": null, "e": 13271, "s": 13231, "text": "Gini Index (breathes & hair = true) = 0" }, { "code": null, "e": 13366, "s": 13271, "text": "(iii) legs: Let’s summarize the output (species) wrt the ‘legs feature values when hair = TRUE" }, { "code": null, "e": 13409, "s": 13366, "text": "Gini Index (hair = true & legs = true) = 0" }, { "code": null, "e": 13453, "s": 13409, "text": "Gini Index (hair = true & legs = false) = 0" }, { "code": null, "e": 13563, "s": 13453, "text": "To obtain the final Gini index of ‘species’ wrt ‘legs’ for ‘hair=true’, we use the weighted sum of the above." }, { "code": null, "e": 13599, "s": 13563, "text": "Gini Index (legs & hair = true) = 0" }, { "code": null, "e": 13839, "s": 13599, "text": "In all the above cases, the Gini Index is equal to 0. This means that if we predict that the species has hair, it can be classified as a ‘mammal’ based on the given dataset with high confidence. At this point, the decision tree looks like:" }, { "code": null, "e": 13907, "s": 13839, "text": "Now, let’s consider the case when ‘hair’ takes the values of FALSE." }, { "code": null, "e": 14040, "s": 13907, "text": "Let’s calculate Gini Index for the output against the input features excluding the hair feature, when hair takes the value of FALSE." }, { "code": null, "e": 14141, "s": 14040, "text": "(i) toothed: Let’s summarize the output (species) wrt the ‘toothed’ feature values when hair = FALSE" }, { "code": null, "e": 14229, "s": 14141, "text": "Gini Index (hair = false & toothed = true) = 1 — {(1/4)2 + (3/4)2} = 1–0.06–0.56 = 0.38" }, { "code": null, "e": 14309, "s": 14229, "text": "Gini Index (hair = false & toothed = false) = 1 — {(0/1)2 + (1/1)2} = 1–0–1 = 0" }, { "code": null, "e": 14444, "s": 14309, "text": "To obtain the final Gini index of ‘species’ wrt ‘toothed’ for ‘hair=false’, we use the weighted sum of the above calculated values as:" }, { "code": null, "e": 14523, "s": 14444, "text": "Gini Index (toothed & hair = false) = (4/5) * 0.38 + (1/5) * 0 = 0.3 + 0 = 0.3" }, { "code": null, "e": 14627, "s": 14523, "text": "(ii) breathes: Let’s summarize the output (species) wrt the ‘breathes’ feature values when hair = FALSE" }, { "code": null, "e": 14716, "s": 14627, "text": "Gini Index (hair = false & breathes = true) = 1 — {(1/4)2 + (3/4)2} = 1–0.06–0.56 = 0.38" }, { "code": null, "e": 14797, "s": 14716, "text": "Gini Index (hair = false & breathes = false) = 1 — {(0/1)2 + (1/1)2} = 1–0–1 = 0" }, { "code": null, "e": 14933, "s": 14797, "text": "To obtain the final Gini index of ‘species’ wrt ‘breathes’ for ‘hair=false’, we use the weighted sum of the above calculated values as:" }, { "code": null, "e": 15013, "s": 14933, "text": "Gini Index (breathes & hair = false) = (4/5) * 0.38 + (1/5) * 0 = 0.3 + 0 = 0.3" }, { "code": null, "e": 15110, "s": 15013, "text": "(iii) legs: Let’s summarize the output (species) wrt the ‘legs’ feature values when hair = FALSE" }, { "code": null, "e": 15194, "s": 15110, "text": "Gini Index (hair = false & legs = true) = 1 — {(1/2)2 + (1/2)2} = 1–0.25–0.25 = 0.5" }, { "code": null, "e": 15271, "s": 15194, "text": "Gini Index (hair = false & legs = false) = 1 — {(0/3)2 + (3/3)2} = 1–0–1 = 0" }, { "code": null, "e": 15403, "s": 15271, "text": "To obtain the final Gini index of ‘species’ wrt ‘legs’ for ‘hair=false’, we use the weighted sum of the above calculated values as:" }, { "code": null, "e": 15481, "s": 15403, "text": "Gini Index (toothed & hair = false) = (2/5) * 0.5 + (3/5) * 0 = 0.2 + 0 = 0.2" }, { "code": null, "e": 15701, "s": 15481, "text": "In the above 3 cases, we see that the Gini Index is minimum for the ‘legs’ feature given the condition ‘hair=FALSE’. So, ‘legs’ is chosen as the child node when ‘hair=FALSE’. At this point, the decision tree looks like:" }, { "code": null, "e": 15795, "s": 15701, "text": "To proceed further, let us consider the cases when legs = TRUE (hair = FALSE is implied now)." }, { "code": null, "e": 15970, "s": 15795, "text": "Let’s calculate Gini Index for the output against the input features excluding the hair and legs feature, when hair takes the value of FALSE and legs takes the value of TRUE." }, { "code": null, "e": 16088, "s": 15970, "text": "(i) toothed: Let’s summarize the output (species) wrt the ‘toothed’ feature values when hair = FALSE and legs = TRUE." }, { "code": null, "e": 16147, "s": 16088, "text": "Gini Index (hair = false & legs = true & toothed=true) = 0" }, { "code": null, "e": 16207, "s": 16147, "text": "Gini Index (hair = false & legs = true & toothed=false) = 0" }, { "code": null, "e": 16337, "s": 16207, "text": "To obtain the final Gini index of ‘species’ wrt ‘toothed’ for ‘hair=false’ and legs=’true’, we use the weighted sum of the above." }, { "code": null, "e": 16391, "s": 16337, "text": "Gini Index (toothed & hair = false & legs = true) = 0" }, { "code": null, "e": 16512, "s": 16391, "text": "(ii) breathes: Let’s summarize the output (species) wrt the ‘breathes’ feature values when hair = FALSE and legs = TRUE." }, { "code": null, "e": 16612, "s": 16512, "text": "Gini Index (hair = false & legs = true & breathes=true) = 1 — {(1/2)2 + (1/2)2} = 1–0.25–0.25 = 0.5" }, { "code": null, "e": 16673, "s": 16612, "text": "Gini Index (hair = false & legs = true & breathes=false) = 0" }, { "code": null, "e": 16803, "s": 16673, "text": "To obtain the final Gini index of ‘species’ wrt ‘toothed’ for ‘hair=false’ and legs=’true’, we use the weighted sum of the above." }, { "code": null, "e": 16885, "s": 16803, "text": "Gini Index (toothed & hair = false & legs = true) = (2/2) * 0.5 + (0/2) * 0 = 0.5" }, { "code": null, "e": 17039, "s": 16885, "text": "In the above 2 cases, we see that ‘toothed’ has lower Gini Index, so it is selected as a child node when ‘legs = TRUE’. The decision tree now looks like:" }, { "code": null, "e": 17106, "s": 17039, "text": "Now, let’s consider the case when ‘legs’ takes the value of FALSE." }, { "code": null, "e": 17619, "s": 17106, "text": "From the above scenario, we can clearly see that when ‘hair = TRUE’ and ‘legs = FALSE’, the output ‘species’ is ‘Reptile’ in all the cases. Hence, we without calculating the Gini Index, we can safely conclude that the child node produced for the decision tree will be a leaf node with the value ‘Reptile’. (Remember that when we just considered ‘hair = TRUE’ case, we saw that all the output ‘species’ values were ‘Mammals’ and by calculating Gini Index, we directly produced a leaf node with the value ‘Mammal’)" }, { "code": null, "e": 17748, "s": 17619, "text": "Proceeding further, let’s consider the case when ‘toothed = TRUE’. Here, the cases ‘hair = FALSE’ and ‘legs = TRUE’ are implied." }, { "code": null, "e": 17895, "s": 17748, "text": "Here, we only have one record which is classified as mammal. Hence, this combination of features results in the output ‘species’ being a ‘Mammal’." }, { "code": null, "e": 17942, "s": 17895, "text": "Considering the case ‘toothed = FALSE’, we get" }, { "code": null, "e": 18152, "s": 17942, "text": "In a similar way, we can conclude that the output ‘species’ for this set of features is a ‘Reptile’. Now, we have finally constructed the decision tree on which we can throw some test data to make predictions." }, { "code": null, "e": 18701, "s": 18152, "text": "If you’ve followed carefully so far, you may have observed that all the variables in this dataset were categorical variables (i.e. the features had a finite set of distinct values (2) like TRUE and FALSE). In the datasets that you encounter in real life have a mixture of categorical and continuous variables. In order to construct decision trees from a dataset having continuous values, these continuous values are converted to categorical values by defining a certain threshold. Using this, decision trees can be constructed for any type of data." }, { "code": null, "e": 18809, "s": 18701, "text": "Although decision trees are quite intuitive and simple to create, they suffer from the following drawbacks." }, { "code": null, "e": 18945, "s": 18809, "text": "1. They are unstable, meaning that a small change in the data can lead to a large change in the structure of the optimal decision tree." }, { "code": null, "e": 19061, "s": 18945, "text": "2. Calculations can get very complex, particularly if many values are uncertain and/or if many outcomes are linked." }, { "code": null, "e": 19161, "s": 19061, "text": "3. Decision Trees tend to overfit to the training data very quickly and can become very inaccurate." }, { "code": null, "e": 19563, "s": 19161, "text": "Due to the aforementioned disadvantages of Decision Trees, Random Forest algorithm is used instead of Decision Trees. Random Forest algorithm employs the use of a large number of decision trees that operate as an ensemble. A machine learning ensemble consists of only a concrete finite set of alternative models, but typically allows for much more flexible structure to exist among those alternatives." }, { "code": null, "e": 20348, "s": 19563, "text": "Random Forest algorithm is based on the concept of The Wisdom of Crowds. Wisdom of Crowds is a very effective technique employed in various tasks of computer science. The fact that Wikipedia (fully crowdsourced, editable by everyone) and Britannica (fully written by experts) have been found to have similar levels of quality standards is a testament to the power of the wisdom of crowds. Every individual in the crowd makes their prediction with a certain error. Since all the individuals act independently, their errors are also independent to each other’s. In other words, these errors are uncorrelated i.e. when considered in a bunch, these errors cancel each other out and what we’re left with is a good, accurate prediction. This is the way how Random Forest algorithm operates." }, { "code": null, "e": 21003, "s": 20348, "text": "Random Forest algorithm uses a large number of decision trees (creating a forest), which are independent of/uncorrelated to each other, from a given dataset, which collectively outperform any of its constituent trees. This little to no correlation between the constituent trees in the forest imparts the element of randomness to this ensemble method, which produces a wonderful effect of protecting trees from each other for their individual errors. But we need to make sure that the outputs of the various decision trees that we make randomly for random forest to work should not be completely random. In order to ensure this, we need to make sure that:" }, { "code": null, "e": 21143, "s": 21003, "text": "(i) The output should be dependent on all the training features and not only some of them in order to make random decision trees effective." }, { "code": null, "e": 21291, "s": 21143, "text": "(ii) The predictions made by each decision tree should have low correlations with each other in order to make the wisdom of crowds concept to work." }, { "code": null, "e": 21524, "s": 21291, "text": "The first point is the feature of the dataset that we collect. So, as a data scientist, how do we make sure that the constituent decision trees are as diversified as possible? For this, random forest uses the following 2 techniques:" }, { "code": null, "e": 21536, "s": 21524, "text": "(i) Bagging" }, { "code": null, "e": 21560, "s": 21536, "text": "(ii) Feature Randomness" }, { "code": null, "e": 22281, "s": 21560, "text": "One of the major drawbacks of Decision Trees was that they were not robust to even small changes in the data which made them prone to overfitting. Let’s understand how bagging solves this problem. Consider a training dataset with M ( >> 50) training examples and for simplicity let’s consider these are M numbers in the range of 1 to 50. If we want to use B decision trees for Random Forest, then through bagging, each of the B decision trees is made up of M training examples, but instead of using all the M training examples, a random subset of these training examples (here numbers in the range from 1 to 50) is used and numbers from this subset are randomly repeated until a total of M training examples are created." }, { "code": null, "e": 22627, "s": 22281, "text": "How does bagging help? By creating a large number of decision trees with a large number of training examples distributed randomly across decision trees, the aggregate result is a random forest model which is robust to even small changes in the data, thereby eliminating one of the major disadvantages of decision trees (by using decision trees)." }, { "code": null, "e": 23084, "s": 22627, "text": "The idea of using random training examples can also be applied to the features of the training data. Recall that while constructing decision trees, when deciding the split at each node, we take all the features into account. If the training dataset has N features, then in feature randomness, while creating each of the B decision trees, the decision of splitting a node is made by using a random subset of these N features instead of using all N features." }, { "code": null, "e": 23637, "s": 23084, "text": "When both bagging and feature randomness are used to make a forest of decision trees for random forest, each of the decision trees constitutes of a random subset of training examples as well as a random subset of features. This randomness adds a lot of robustness and stability to a Random Forest classifier by ensuring the formation of uncorrelated decision trees that protect each other from their errors. Once all these constituent decision trees make a prediction, majority voting takes place in order to get the final prediction of the classifier." }, { "code": null, "e": 24346, "s": 23637, "text": "We’ve looked at a lot of concepts so far. From the mathematics behind decision trees to creating a decision tree by hand and then seeing how decision trees are used in random forest, we’ve come a long way. Now is the time that we get hands on practice for a Random Forest classifier and for this post, we won’t be dealing with a new dataset, instead we’ll be improving upon our Logistic Regression model which we trained over the Titanic dataset in this post. This is the way actual machine learning tasks are carried out. Various machine learning models are tried and the one that works the best and justifies the results obtained is used in practice. Remember, persistence is the key. So let’s get started." }, { "code": null, "e": 24760, "s": 24346, "text": "The dataset for the Titanic problem can be found here. We have to predict whether a passenger on the Titanic will survive or not given the data corresponding to them. We have already applied data pre-processing and logistic regression in this post. Now, we will use the same pre-processed data from the previous post, but will apply Random Forest classification this time. Dataset after pre-processing looks like:" }, { "code": null, "e": 24943, "s": 24760, "text": "After applying recursive feature elimination(RFE), we obtain the top 8 most important features that will help in training the Random Forest Classifier. More on RFE can be found here." }, { "code": null, "e": 25410, "s": 24943, "text": "from sklearn.ensemble import RandomForestClassifierfrom sklearn.feature_selection import RFEcols = [“Age”, “SibSp”, “Parch”, “Fare”, “Pclass_1”, “Pclass_2”, “Pclass_3”, “Embarked_C”, “Embarked_Q”, “Embarked_S”, “Sex_male”]X = final_train[cols]y = final_train[‘Survived’]model = RandomForestClassifier()# selecting top 8 featuresrfe = RFE(model, n_features_to_select = 8)rfe = rfe.fit(X, y)print(‘Top 8 most important features: ‘ + str(list(X.columns[rfe.support_])))" }, { "code": null, "e": 25691, "s": 25410, "text": "Now that we have the list of features we should use for training the classifier, let us apply Random Forest classifier on the dataset. Unlike Logistic Regression, Random Forest has a large number of parameters that need to be fed into the model. The most important parameters are:" }, { "code": null, "e": 25740, "s": 25691, "text": "1. n_estimators = number of trees in the foreset" }, { "code": null, "e": 25813, "s": 25740, "text": "2. max_features = max number of features considered for splitting a node" }, { "code": null, "e": 25871, "s": 25813, "text": "3. max_depth = max number of levels in each decision tree" }, { "code": null, "e": 25962, "s": 25871, "text": "4. min_samples_split = min number of data points placed in a node before the node is split" }, { "code": null, "e": 26033, "s": 25962, "text": "5. min_samples_leaf = min number of data points allowed in a leaf node" }, { "code": null, "e": 26125, "s": 26033, "text": "6. bootstrap (like bagging) = method for sampling data points (with or without replacement)" }, { "code": null, "e": 26512, "s": 26125, "text": "These are a lot of parameters and it is difficult to obtain their optimal value together manually. So, we make use of the computation power by passing the model a set of values for each parameter, the parameter applies these values to the dataset and chooses the best ones. For this dataset, this took me about 5 minutes to get optimal values using Random Hyperparameter Grid technique." }, { "code": null, "e": 27294, "s": 26512, "text": "# Number of trees in random forestn_estimators = [int(x) for x in np.linspace(start = 200, stop = 2000, num = 10)]# Number of features to consider at every splitmax_features = ['auto', 'sqrt']# Maximum number of levels in treemax_depth = [int(x) for x in np.linspace(10, 110, num = 11)]max_depth.append(None)# Minimum number of samples required to split a nodemin_samples_split = [2, 5, 10]# Minimum number of samples required at each leaf nodemin_samples_leaf = [1, 2, 4]# Method of selecting samples for training each tree (bagging)bootstrap = [True, False]# Creating random gridrandom_grid = {'n_estimators': n_estimators, 'max_features': max_features, 'max_depth': max_depth, 'min_samples_split': min_samples_split, 'min_samples_leaf': min_samples_leaf, 'bootstrap': bootstrap}" }, { "code": null, "e": 27587, "s": 27294, "text": "On each iteration, the algorithm will choose a difference combination of the features. Altogether, there are 2 * 12 * 2 * 3 * 3 * 10 = 4320 settings! However, the benefit of a random search is that we are not trying every combination, but selecting at random to sample a wide range of values." }, { "code": null, "e": 28051, "s": 27587, "text": "# First create the base model to tunerf = RandomForestClassifier()# Random search of parameters, using 3 fold cross validation,# search across 100 different combinations, and use all available coresrf_random = RandomizedSearchCV(estimator = rf, param_distributions = random_grid, n_iter = 100, cv = 3, verbose=2, random_state=42, n_jobs = -1)# Fit the random search modelrf_random.fit(final_train[selected_features], final_train['Survived'])rf_random.best_params_" }, { "code": null, "e": 28273, "s": 28051, "text": "Now that we have an optimal set of parameters from the given range supplied to the algorithm, let’s train the random forest classifier, both with default values that sci-kit learn provides and with the values we obtained." }, { "code": null, "e": 28767, "s": 28273, "text": "X = final_train[selected_features]y = final_train['Survived']X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.15, random_state=2)# fitting both base random forest model and RandomizedSearchCV random forest modelbase_model = RandomForestClassifier()base_model.fit(X_train, y_train)best_random = RandomForestClassifier(n_estimators = 2000, min_samples_split= 5, min_samples_leaf = 1, max_features = 'sqrt', max_depth = 100, bootstrap = True)best_random.fit(X_train, y_train)" }, { "code": null, "e": 28871, "s": 28767, "text": "Now that we have trained these models, let’s evaluate them using the evaluation function defined below." }, { "code": null, "e": 29275, "s": 28871, "text": "def evaluate(model, test_features, test_labels): predictions = model.predict(test_features) errors = abs(predictions - test_labels) accuracy = accuracy_score(test_labels, predictions) * 100 print('Model Performance') print('Average Error: {:0.4f} degrees.'.format(np.mean(errors))) print('Accuracy = {:0.2f}%.'.format(accuracy)) return accuracybase_accuracy = evaluate(base_model, X_test, y_test)" }, { "code": null, "e": 29331, "s": 29275, "text": "random_accuracy = evaluate(best_random, X_test, y_test)" }, { "code": null, "e": 29814, "s": 29331, "text": "We observe that the base model had a test accuracy of 84.33% whereas the model in which we fed the parameters obtained RandomizedSearchCV yielded test accuracy of 81.34%, which should have been higher than the base model’s accuracy. This can be due to the fact that the training dataset was not big enough or the values we supplied for random search to choose from might have included the range of optimal values. We can definitely toy around with it to improve our accuracy though." }, { "code": null, "e": 29996, "s": 29814, "text": "Similarly, I also applied GridSearchCV to check for the accuracy of the classifier which was again around 81%. The relatively low accuracy might be due to the reasons posited above." }, { "code": null, "e": 30538, "s": 29996, "text": "But, the key takeaway from this exercise is that we improved our model’s accuracy on the test set from 77.6% using Logistic Regression to around 84% using Random Forest algorithm, which indeed justified our discussion of Random Forest algorithm above. When I submitted the results of this model on Kaggle, I received a public score of 0.7751, which is better than the score we received for Logistic Regression classifier (0.7703), although not by much, but good enough to take a step forward to improve an already existing robust classifier." }, { "code": null, "e": 30587, "s": 30538, "text": "The entire code for this post can be found here." } ]
How to Make a Process Monitor in Python? - GeeksforGeeks
04 Jul, 2021 A process monitor is a tool that displays the system information like processes, memory, network, and other stuff. There are plenty of tools available, but we can make our own process monitor using Python. In Python, there is a module called psutil that we can use to grab various information about our system psutil: Type the below command in the terminal to install this module. python3 -m pip install psutil Prettytable: To print the data on console, we can use a formatter module PrettyTable: python3 -m pip install prettytable psutil provides lots of features to monitor the system. We will see some of them in brief: First, we need to import psutil: import psutil List the process ids: psutil.pids() # [1,2,.....4352] Fetch process information: process_id = 1 psutil.Process(process_id) # psutil.Process(pid=1, name='systemd', status='sleeping', started='19:49:25') We can access various keys of this process: process = psutil.Process(process_id) process.name() process.status() Accessing battery status: psutil.sensors_battery() psutil.sensors_battery().percent Accessing Network Interfaces: psutil.net_if_stats() psutil.net_if_stats()['wlo1'].isup # True We can also check the memory: psutil.virtual_memory() psutil.virtual_memory().total # 8180498432 (In Bytes) psutil.virtual_memory().used # 2155720704 psutil.virtual_memory().available # 5563060224 Now that we know some basic features, we can implement the process monitor. Create a new python file and add the following code in it. The code below works on Linux distributions. For other operating systems, some functions may slightly differ. Approach: Import the required packages. Clear the console using the call() function of the subprocess module. We can use the ‘clear’ or ‘cls’ command depending on OS. Fetch the battery information Fetch the network information and print it as PrettyTable Fetch the memory information Fetch the process information Create a delay. We have created a 1-second delay using time.sleep(1) Press CTRL+C to stop the program. Below is the implementation: Python3 # Import the required librariesimport psutilimport timefrom subprocess import callfrom prettytable import PrettyTable # Run an infinite loop to constantly monitor the systemwhile True: # Clear the screen using a bash command call('clear') print("==============================Process Monitor\ ======================================") # Fetch the battery information battery = psutil.sensors_battery().percent print("----Battery Available: %d "%(battery,) + "%") # We have used PrettyTable to print the data on console. # t = PrettyTable(<list of headings>) # t.add_row(<list of cells in row>) # Fetch the Network information print("----Networks----") table = PrettyTable(['Network', 'Status', 'Speed']) for key in psutil.net_if_stats().keys(): name = key up = "Up" if psutil.net_if_stats()[key].isup else "Down" speed = psutil.net_if_stats()[key].speed table.add_row([name, up, speed]) print(table) # Fetch the memory information print("----Memory----") memory_table = PrettyTable(["Total", "Used", "Available", "Percentage"]) vm = psutil.virtual_memory() memory_table.add_row([ vm.total, vm.used, vm.available, vm.percent ]) print(memory_table) # Fetch the last 10 processes from available processes print("----Processes----") process_table = PrettyTable(['PID', 'PNAME', 'STATUS', 'CPU', 'NUM THREADS']) for process in psutil.pids()[-10:]: # While fetching the processes, some of the subprocesses may exit # Hence we need to put this code in try-except block try: p = psutil.Process(process) process_table.add_row([ str(process), p.name(), p.status(), str(p.cpu_percent())+"%", p.num_threads() ]) except Exception as e: pass print(process_table) # Create a 1 second delay time.sleep(1) Output: surindertarika1234 Picked python-utility Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to Install PIP on Windows ? How to drop one or multiple columns in Pandas Dataframe How To Convert Python Dictionary To JSON? Selecting rows in pandas DataFrame based on conditions Check if element exists in list in Python Defaultdict in Python Python | Get unique values from a list Python | os.path.join() method Create a directory in Python Python | Pandas dataframe.groupby()
[ { "code": null, "e": 24318, "s": 24290, "text": "\n04 Jul, 2021" }, { "code": null, "e": 24628, "s": 24318, "text": "A process monitor is a tool that displays the system information like processes, memory, network, and other stuff. There are plenty of tools available, but we can make our own process monitor using Python. In Python, there is a module called psutil that we can use to grab various information about our system" }, { "code": null, "e": 24699, "s": 24628, "text": "psutil: Type the below command in the terminal to install this module." }, { "code": null, "e": 24730, "s": 24699, "text": "python3 -m pip install psutil " }, { "code": null, "e": 24816, "s": 24730, "text": "Prettytable: To print the data on console, we can use a formatter module PrettyTable:" }, { "code": null, "e": 24851, "s": 24816, "text": "python3 -m pip install prettytable" }, { "code": null, "e": 24942, "s": 24851, "text": "psutil provides lots of features to monitor the system. We will see some of them in brief:" }, { "code": null, "e": 24975, "s": 24942, "text": "First, we need to import psutil:" }, { "code": null, "e": 24989, "s": 24975, "text": "import psutil" }, { "code": null, "e": 25011, "s": 24989, "text": "List the process ids:" }, { "code": null, "e": 25044, "s": 25011, "text": "psutil.pids() # [1,2,.....4352]" }, { "code": null, "e": 25071, "s": 25044, "text": "Fetch process information:" }, { "code": null, "e": 25194, "s": 25071, "text": "process_id = 1\npsutil.Process(process_id) \n# psutil.Process(pid=1, name='systemd', status='sleeping', started='19:49:25')" }, { "code": null, "e": 25238, "s": 25194, "text": "We can access various keys of this process:" }, { "code": null, "e": 25307, "s": 25238, "text": "process = psutil.Process(process_id)\nprocess.name()\nprocess.status()" }, { "code": null, "e": 25333, "s": 25307, "text": "Accessing battery status:" }, { "code": null, "e": 25395, "s": 25333, "text": "psutil.sensors_battery() \npsutil.sensors_battery().percent" }, { "code": null, "e": 25425, "s": 25395, "text": "Accessing Network Interfaces:" }, { "code": null, "e": 25494, "s": 25425, "text": "psutil.net_if_stats() \npsutil.net_if_stats()['wlo1'].isup # True" }, { "code": null, "e": 25524, "s": 25494, "text": "We can also check the memory:" }, { "code": null, "e": 25699, "s": 25524, "text": "psutil.virtual_memory()\npsutil.virtual_memory().total # 8180498432 (In Bytes)\npsutil.virtual_memory().used # 2155720704\npsutil.virtual_memory().available # 5563060224" }, { "code": null, "e": 25944, "s": 25699, "text": "Now that we know some basic features, we can implement the process monitor. Create a new python file and add the following code in it. The code below works on Linux distributions. For other operating systems, some functions may slightly differ." }, { "code": null, "e": 25954, "s": 25944, "text": "Approach:" }, { "code": null, "e": 25984, "s": 25954, "text": "Import the required packages." }, { "code": null, "e": 26111, "s": 25984, "text": "Clear the console using the call() function of the subprocess module. We can use the ‘clear’ or ‘cls’ command depending on OS." }, { "code": null, "e": 26141, "s": 26111, "text": "Fetch the battery information" }, { "code": null, "e": 26199, "s": 26141, "text": "Fetch the network information and print it as PrettyTable" }, { "code": null, "e": 26228, "s": 26199, "text": "Fetch the memory information" }, { "code": null, "e": 26258, "s": 26228, "text": "Fetch the process information" }, { "code": null, "e": 26327, "s": 26258, "text": "Create a delay. We have created a 1-second delay using time.sleep(1)" }, { "code": null, "e": 26361, "s": 26327, "text": "Press CTRL+C to stop the program." }, { "code": null, "e": 26390, "s": 26361, "text": "Below is the implementation:" }, { "code": null, "e": 26398, "s": 26390, "text": "Python3" }, { "code": "# Import the required librariesimport psutilimport timefrom subprocess import callfrom prettytable import PrettyTable # Run an infinite loop to constantly monitor the systemwhile True: # Clear the screen using a bash command call('clear') print(\"==============================Process Monitor\\ ======================================\") # Fetch the battery information battery = psutil.sensors_battery().percent print(\"----Battery Available: %d \"%(battery,) + \"%\") # We have used PrettyTable to print the data on console. # t = PrettyTable(<list of headings>) # t.add_row(<list of cells in row>) # Fetch the Network information print(\"----Networks----\") table = PrettyTable(['Network', 'Status', 'Speed']) for key in psutil.net_if_stats().keys(): name = key up = \"Up\" if psutil.net_if_stats()[key].isup else \"Down\" speed = psutil.net_if_stats()[key].speed table.add_row([name, up, speed]) print(table) # Fetch the memory information print(\"----Memory----\") memory_table = PrettyTable([\"Total\", \"Used\", \"Available\", \"Percentage\"]) vm = psutil.virtual_memory() memory_table.add_row([ vm.total, vm.used, vm.available, vm.percent ]) print(memory_table) # Fetch the last 10 processes from available processes print(\"----Processes----\") process_table = PrettyTable(['PID', 'PNAME', 'STATUS', 'CPU', 'NUM THREADS']) for process in psutil.pids()[-10:]: # While fetching the processes, some of the subprocesses may exit # Hence we need to put this code in try-except block try: p = psutil.Process(process) process_table.add_row([ str(process), p.name(), p.status(), str(p.cpu_percent())+\"%\", p.num_threads() ]) except Exception as e: pass print(process_table) # Create a 1 second delay time.sleep(1)", "e": 28484, "s": 26398, "text": null }, { "code": null, "e": 28492, "s": 28484, "text": "Output:" }, { "code": null, "e": 28511, "s": 28492, "text": "surindertarika1234" }, { "code": null, "e": 28518, "s": 28511, "text": "Picked" }, { "code": null, "e": 28533, "s": 28518, "text": "python-utility" }, { "code": null, "e": 28540, "s": 28533, "text": "Python" }, { "code": null, "e": 28638, "s": 28540, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 28670, "s": 28638, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 28726, "s": 28670, "text": "How to drop one or multiple columns in Pandas Dataframe" }, { "code": null, "e": 28768, "s": 28726, "text": "How To Convert Python Dictionary To JSON?" }, { "code": null, "e": 28823, "s": 28768, "text": "Selecting rows in pandas DataFrame based on conditions" }, { "code": null, "e": 28865, "s": 28823, "text": "Check if element exists in list in Python" }, { "code": null, "e": 28887, "s": 28865, "text": "Defaultdict in Python" }, { "code": null, "e": 28926, "s": 28887, "text": "Python | Get unique values from a list" }, { "code": null, "e": 28957, "s": 28926, "text": "Python | os.path.join() method" }, { "code": null, "e": 28986, "s": 28957, "text": "Create a directory in Python" } ]
Python - Chunks and Chinks
Chunking is the process of grouping similar words together based on the nature of the word. In the below example we define a grammar by which the chunk must be generated. The grammar suggests the sequence of the phrases like nouns and adjectives etc. which will be followed when creating the chunks. The pictorial output of chunks is shown below. import nltk sentence = [("The", "DT"), ("small", "JJ"), ("red", "JJ"),("flower", "NN"), ("flew", "VBD"), ("through", "IN"), ("the", "DT"), ("window", "NN")] grammar = "NP: {?*}" cp = nltk.RegexpParser(grammar) result = cp.parse(sentence) print(result) result.draw() When we run the above program we get the following output − Changing the grammar, we get a different output as shown below. import nltk sentence = [("The", "DT"), ("small", "JJ"), ("red", "JJ"),("flower", "NN"), ("flew", "VBD"), ("through", "IN"), ("the", "DT"), ("window", "NN")] grammar = "NP: {?*}" chunkprofile = nltk.RegexpParser(grammar) result = chunkprofile.parse(sentence) print(result) result.draw() When we run the above program we get the following output − Chinking is the process of removing a sequence of tokens from a chunk. If the sequence of tokens appears in the middle of the chunk, these tokens are removed, leaving two chunks where they were already present. import nltk sentence = [("The", "DT"), ("small", "JJ"), ("red", "JJ"),("flower", "NN"), ("flew", "VBD"), ("through", "IN"), ("the", "DT"), ("window", "NN")] grammar = r""" NP: {<.*>+} # Chunk everything }+{ # Chink sequences of JJ and NN """ chunkprofile = nltk.RegexpParser(grammar) result = chunkprofile.parse(sentence) print(result) result.draw() When we run the above program, we get the following output − As you can see the parts meeting the criteria in grammar are left out from the Noun phrases as separate chunks. This process of extracting text not in the required chunk is called chinking. 187 Lectures 17.5 hours Malhar Lathkar 55 Lectures 8 hours Arnab Chakraborty 136 Lectures 11 hours In28Minutes Official 75 Lectures 13 hours Eduonix Learning Solutions 70 Lectures 8.5 hours Lets Kode It 63 Lectures 6 hours Abhilash Nelson Print Add Notes Bookmark this page
[ { "code": null, "e": 2935, "s": 2587, "text": " Chunking is the process of grouping similar words together based on the nature of the word. In the below example we define a grammar by which the chunk must be generated. The grammar suggests the sequence of the phrases like nouns and adjectives etc. which will be followed when creating the chunks. The pictorial output of chunks is shown below." }, { "code": null, "e": 3207, "s": 2935, "text": "import nltk\n\nsentence = [(\"The\", \"DT\"), (\"small\", \"JJ\"), (\"red\", \"JJ\"),(\"flower\", \"NN\"), \n(\"flew\", \"VBD\"), (\"through\", \"IN\"), (\"the\", \"DT\"), (\"window\", \"NN\")]\ngrammar = \"NP: {?*}\" \ncp = nltk.RegexpParser(grammar)\nresult = cp.parse(sentence) \nprint(result)\nresult.draw()\n" }, { "code": null, "e": 3267, "s": 3207, "text": "When we run the above program we get the following output −" }, { "code": null, "e": 3332, "s": 3267, "text": "Changing the grammar, we get a different output as shown below. " }, { "code": null, "e": 3626, "s": 3332, "text": "import nltk\n\nsentence = [(\"The\", \"DT\"), (\"small\", \"JJ\"), (\"red\", \"JJ\"),(\"flower\", \"NN\"),\n (\"flew\", \"VBD\"), (\"through\", \"IN\"), (\"the\", \"DT\"), (\"window\", \"NN\")]\n\ngrammar = \"NP: {?*}\" \n\nchunkprofile = nltk.RegexpParser(grammar)\nresult = chunkprofile.parse(sentence) \nprint(result)\nresult.draw()\n" }, { "code": null, "e": 3686, "s": 3626, "text": "When we run the above program we get the following output −" }, { "code": null, "e": 3898, "s": 3686, "text": "Chinking is the process of removing a sequence of tokens from a chunk. If the sequence of tokens appears in the middle of the chunk, these tokens are removed, leaving two chunks where they were already present. " }, { "code": null, "e": 4279, "s": 3900, "text": "import nltk\n\nsentence = [(\"The\", \"DT\"), (\"small\", \"JJ\"), (\"red\", \"JJ\"),(\"flower\", \"NN\"), (\"flew\", \"VBD\"), (\"through\", \"IN\"), (\"the\", \"DT\"), (\"window\", \"NN\")]\n\ngrammar = r\"\"\"\n NP:\n {<.*>+} # Chunk everything\n }+{ # Chink sequences of JJ and NN\n \"\"\"\nchunkprofile = nltk.RegexpParser(grammar)\nresult = chunkprofile.parse(sentence) \nprint(result)\nresult.draw()" }, { "code": null, "e": 4340, "s": 4279, "text": "When we run the above program, we get the following output −" }, { "code": null, "e": 4530, "s": 4340, "text": "As you can see the parts meeting the criteria in grammar are left out from the Noun phrases as separate chunks. This process of extracting text not in the required chunk is called chinking." }, { "code": null, "e": 4567, "s": 4530, "text": "\n 187 Lectures \n 17.5 hours \n" }, { "code": null, "e": 4583, "s": 4567, "text": " Malhar Lathkar" }, { "code": null, "e": 4616, "s": 4583, "text": "\n 55 Lectures \n 8 hours \n" }, { "code": null, "e": 4635, "s": 4616, "text": " Arnab Chakraborty" }, { "code": null, "e": 4670, "s": 4635, "text": "\n 136 Lectures \n 11 hours \n" }, { "code": null, "e": 4692, "s": 4670, "text": " In28Minutes Official" }, { "code": null, "e": 4726, "s": 4692, "text": "\n 75 Lectures \n 13 hours \n" }, { "code": null, "e": 4754, "s": 4726, "text": " Eduonix Learning Solutions" }, { "code": null, "e": 4789, "s": 4754, "text": "\n 70 Lectures \n 8.5 hours \n" }, { "code": null, "e": 4803, "s": 4789, "text": " Lets Kode It" }, { "code": null, "e": 4836, "s": 4803, "text": "\n 63 Lectures \n 6 hours \n" }, { "code": null, "e": 4853, "s": 4836, "text": " Abhilash Nelson" }, { "code": null, "e": 4860, "s": 4853, "text": " Print" }, { "code": null, "e": 4871, "s": 4860, "text": " Add Notes" } ]
Word Ladder in C++
Suppose we have two words (beginWord and endWord), and we have dictionary's word list, find the length of shortest transformation sequence from beginWord to endWord, such that − Only one letter can be converted at a time. Only one letter can be converted at a time. In each transformed word must exist in the word list. The beginWord is not a transformed word. In each transformed word must exist in the word list. The beginWord is not a transformed word. We have to keep in mind that − Return 0 when there is no such change sequence. Return 0 when there is no such change sequence. All words have the same length. All words have the same length. All words contain only lowercase characters. All words contain only lowercase characters. We can assume no duplicates in the word list. We can assume no duplicates in the word list. So if the input is like: beginWord = "hit", endWord = "cog", and wordlist = ["hot", "dot", "dog", "lot", "log", "cog"] Then the output will be 5, as one shortest transformation is hit → hot → dot → dog → cog To solve this, we will follow these steps − Define a method called putStar, this will take j and string s. This will work as follows − Define a method called putStar, this will take j and string s. This will work as follows − temp := empty string temp := empty string for i in range 0 to size of s – 1if i = j, then update temp by concatenating “*” with it, otherwise update temp by concatenating s[i] with temp. for i in range 0 to size of s – 1 if i = j, then update temp by concatenating “*” with it, otherwise update temp by concatenating s[i] with temp. if i = j, then update temp by concatenating “*” with it, otherwise update temp by concatenating s[i] with temp. in the main method it will take string b, string e and list of words w, this will work like − in the main method it will take string b, string e and list of words w, this will work like − if e is not in w, or b is empty, or e is empty, or w is empty, then return 0 if e is not in w, or b is empty, or e is empty, or w is empty, then return 0 define a map m for string type key and array type value. define a map m for string type key and array type value. for i in range 0 to size of wx := w[i]for j := 0 to size of xinter := putStar(j, x)insert x into m[inter] for i in range 0 to size of w x := w[i] x := w[i] for j := 0 to size of xinter := putStar(j, x)insert x into m[inter] for j := 0 to size of x inter := putStar(j, x) inter := putStar(j, x) insert x into m[inter] insert x into m[inter] Define a queue q, insert a pair (b, 1) into q Define a queue q, insert a pair (b, 1) into q make a map called visited make a map called visited while q is not emptys := front pair from q, delete front element from qx := first element of the pair s, l := second element of the pair sfor i in range 0 to size of xtemp := putStar(i, x)for j in range 0 to size of m[temp]aa := m[temp, j]if aa is same as e, then return l + 1if visited[aa] is not set, then insert pair (aa, l + 1), and set visited[aa] = 1 while q is not empty s := front pair from q, delete front element from q s := front pair from q, delete front element from q x := first element of the pair s, l := second element of the pair s x := first element of the pair s, l := second element of the pair s for i in range 0 to size of xtemp := putStar(i, x)for j in range 0 to size of m[temp]aa := m[temp, j]if aa is same as e, then return l + 1if visited[aa] is not set, then insert pair (aa, l + 1), and set visited[aa] = 1 for i in range 0 to size of x temp := putStar(i, x) temp := putStar(i, x) for j in range 0 to size of m[temp]aa := m[temp, j]if aa is same as e, then return l + 1if visited[aa] is not set, then insert pair (aa, l + 1), and set visited[aa] = 1 for j in range 0 to size of m[temp] aa := m[temp, j] aa := m[temp, j] if aa is same as e, then return l + 1 if aa is same as e, then return l + 1 if visited[aa] is not set, then insert pair (aa, l + 1), and set visited[aa] = 1 if visited[aa] is not set, then insert pair (aa, l + 1), and set visited[aa] = 1 level := 0 level := 0 return 0 return 0 Let us see the following implementation to get a better understanding − Live Demo #include <bits/stdc++.h> using namespace std; class Solution { public: string putStar(int j, string s){ string temp = ""; for(int i = 0; i < s.size(); i++){ if(i == j)temp += "*"; else temp += s[i]; } return temp; } int ladderLength(string b, string e, vector<string>& w) { if(find(w.begin(), w.end(), e) == w.end() || !b.size() || !e.size() || !w.size())return 0; map < string , vector <string> > m; for(int i = 0; i < w.size(); i++){ string x = w[i]; for(int j = 0; j < x.size(); j++){ string inter = putStar(j,x); m[inter].push_back(x); } } queue < pair <string, int> > q; q.push({b, 1}); map <string, int> visited; while(!q.empty()){ pair < string, int > s = q.front(); q.pop(); string x = s.first; int l = s.second; for(int i = 0; i < x.size(); i++){ string temp = putStar(i ,x); for(int j = 0; j < m[temp].size(); j++){ string aa = m[temp][j]; if(aa == e)return l+1; if(!visited[aa]){ q.push({aa, l+1}); visited[aa] = 1; } } } } int level = 0; return 0; } }; main(){ vector<string> v = {"hot","dot","dog","lot","log","cog"}; Solution ob; cout << (ob.ladderLength("hit", "cog", v)); } "hit" "cog" ["hot","dot","dog","lot","log","cog"] 5
[ { "code": null, "e": 1240, "s": 1062, "text": "Suppose we have two words (beginWord and endWord), and we have dictionary's word list, find the length of shortest transformation sequence from beginWord to endWord, such that −" }, { "code": null, "e": 1284, "s": 1240, "text": "Only one letter can be converted at a time." }, { "code": null, "e": 1328, "s": 1284, "text": "Only one letter can be converted at a time." }, { "code": null, "e": 1423, "s": 1328, "text": "In each transformed word must exist in the word list. The beginWord is not a transformed word." }, { "code": null, "e": 1518, "s": 1423, "text": "In each transformed word must exist in the word list. The beginWord is not a transformed word." }, { "code": null, "e": 1549, "s": 1518, "text": "We have to keep in mind that −" }, { "code": null, "e": 1597, "s": 1549, "text": "Return 0 when there is no such change sequence." }, { "code": null, "e": 1645, "s": 1597, "text": "Return 0 when there is no such change sequence." }, { "code": null, "e": 1677, "s": 1645, "text": "All words have the same length." }, { "code": null, "e": 1709, "s": 1677, "text": "All words have the same length." }, { "code": null, "e": 1754, "s": 1709, "text": "All words contain only lowercase characters." }, { "code": null, "e": 1799, "s": 1754, "text": "All words contain only lowercase characters." }, { "code": null, "e": 1845, "s": 1799, "text": "We can assume no duplicates in the word list." }, { "code": null, "e": 1891, "s": 1845, "text": "We can assume no duplicates in the word list." }, { "code": null, "e": 2010, "s": 1891, "text": "So if the input is like: beginWord = \"hit\", endWord = \"cog\", and wordlist = [\"hot\", \"dot\", \"dog\", \"lot\", \"log\", \"cog\"]" }, { "code": null, "e": 2099, "s": 2010, "text": "Then the output will be 5, as one shortest transformation is hit → hot → dot → dog → cog" }, { "code": null, "e": 2143, "s": 2099, "text": "To solve this, we will follow these steps −" }, { "code": null, "e": 2234, "s": 2143, "text": "Define a method called putStar, this will take j and string s. This will work as follows −" }, { "code": null, "e": 2325, "s": 2234, "text": "Define a method called putStar, this will take j and string s. This will work as follows −" }, { "code": null, "e": 2346, "s": 2325, "text": "temp := empty string" }, { "code": null, "e": 2367, "s": 2346, "text": "temp := empty string" }, { "code": null, "e": 2512, "s": 2367, "text": "for i in range 0 to size of s – 1if i = j, then update temp by concatenating “*” with it, otherwise update temp by concatenating s[i] with temp." }, { "code": null, "e": 2546, "s": 2512, "text": "for i in range 0 to size of s – 1" }, { "code": null, "e": 2658, "s": 2546, "text": "if i = j, then update temp by concatenating “*” with it, otherwise update temp by concatenating s[i] with temp." }, { "code": null, "e": 2770, "s": 2658, "text": "if i = j, then update temp by concatenating “*” with it, otherwise update temp by concatenating s[i] with temp." }, { "code": null, "e": 2864, "s": 2770, "text": "in the main method it will take string b, string e and list of words w, this will work like −" }, { "code": null, "e": 2958, "s": 2864, "text": "in the main method it will take string b, string e and list of words w, this will work like −" }, { "code": null, "e": 3035, "s": 2958, "text": "if e is not in w, or b is empty, or e is empty, or w is empty, then return 0" }, { "code": null, "e": 3112, "s": 3035, "text": "if e is not in w, or b is empty, or e is empty, or w is empty, then return 0" }, { "code": null, "e": 3169, "s": 3112, "text": "define a map m for string type key and array type value." }, { "code": null, "e": 3226, "s": 3169, "text": "define a map m for string type key and array type value." }, { "code": null, "e": 3332, "s": 3226, "text": "for i in range 0 to size of wx := w[i]for j := 0 to size of xinter := putStar(j, x)insert x into m[inter]" }, { "code": null, "e": 3362, "s": 3332, "text": "for i in range 0 to size of w" }, { "code": null, "e": 3372, "s": 3362, "text": "x := w[i]" }, { "code": null, "e": 3382, "s": 3372, "text": "x := w[i]" }, { "code": null, "e": 3450, "s": 3382, "text": "for j := 0 to size of xinter := putStar(j, x)insert x into m[inter]" }, { "code": null, "e": 3474, "s": 3450, "text": "for j := 0 to size of x" }, { "code": null, "e": 3497, "s": 3474, "text": "inter := putStar(j, x)" }, { "code": null, "e": 3520, "s": 3497, "text": "inter := putStar(j, x)" }, { "code": null, "e": 3543, "s": 3520, "text": "insert x into m[inter]" }, { "code": null, "e": 3566, "s": 3543, "text": "insert x into m[inter]" }, { "code": null, "e": 3612, "s": 3566, "text": "Define a queue q, insert a pair (b, 1) into q" }, { "code": null, "e": 3658, "s": 3612, "text": "Define a queue q, insert a pair (b, 1) into q" }, { "code": null, "e": 3684, "s": 3658, "text": "make a map called visited" }, { "code": null, "e": 3710, "s": 3684, "text": "make a map called visited" }, { "code": null, "e": 4067, "s": 3710, "text": "while q is not emptys := front pair from q, delete front element from qx := first element of the pair s, l := second element of the pair sfor i in range 0 to size of xtemp := putStar(i, x)for j in range 0 to size of m[temp]aa := m[temp, j]if aa is same as e, then return l + 1if visited[aa] is not set, then insert pair (aa, l + 1), and set visited[aa] = 1" }, { "code": null, "e": 4088, "s": 4067, "text": "while q is not empty" }, { "code": null, "e": 4140, "s": 4088, "text": "s := front pair from q, delete front element from q" }, { "code": null, "e": 4192, "s": 4140, "text": "s := front pair from q, delete front element from q" }, { "code": null, "e": 4260, "s": 4192, "text": "x := first element of the pair s, l := second element of the pair s" }, { "code": null, "e": 4328, "s": 4260, "text": "x := first element of the pair s, l := second element of the pair s" }, { "code": null, "e": 4547, "s": 4328, "text": "for i in range 0 to size of xtemp := putStar(i, x)for j in range 0 to size of m[temp]aa := m[temp, j]if aa is same as e, then return l + 1if visited[aa] is not set, then insert pair (aa, l + 1), and set visited[aa] = 1" }, { "code": null, "e": 4577, "s": 4547, "text": "for i in range 0 to size of x" }, { "code": null, "e": 4599, "s": 4577, "text": "temp := putStar(i, x)" }, { "code": null, "e": 4621, "s": 4599, "text": "temp := putStar(i, x)" }, { "code": null, "e": 4790, "s": 4621, "text": "for j in range 0 to size of m[temp]aa := m[temp, j]if aa is same as e, then return l + 1if visited[aa] is not set, then insert pair (aa, l + 1), and set visited[aa] = 1" }, { "code": null, "e": 4826, "s": 4790, "text": "for j in range 0 to size of m[temp]" }, { "code": null, "e": 4843, "s": 4826, "text": "aa := m[temp, j]" }, { "code": null, "e": 4860, "s": 4843, "text": "aa := m[temp, j]" }, { "code": null, "e": 4898, "s": 4860, "text": "if aa is same as e, then return l + 1" }, { "code": null, "e": 4936, "s": 4898, "text": "if aa is same as e, then return l + 1" }, { "code": null, "e": 5017, "s": 4936, "text": "if visited[aa] is not set, then insert pair (aa, l + 1), and set visited[aa] = 1" }, { "code": null, "e": 5098, "s": 5017, "text": "if visited[aa] is not set, then insert pair (aa, l + 1), and set visited[aa] = 1" }, { "code": null, "e": 5109, "s": 5098, "text": "level := 0" }, { "code": null, "e": 5120, "s": 5109, "text": "level := 0" }, { "code": null, "e": 5129, "s": 5120, "text": "return 0" }, { "code": null, "e": 5138, "s": 5129, "text": "return 0" }, { "code": null, "e": 5210, "s": 5138, "text": "Let us see the following implementation to get a better understanding −" }, { "code": null, "e": 5221, "s": 5210, "text": " Live Demo" }, { "code": null, "e": 6680, "s": 5221, "text": "#include <bits/stdc++.h>\nusing namespace std;\nclass Solution {\n public:\n string putStar(int j, string s){\n string temp = \"\";\n for(int i = 0; i < s.size(); i++){\n if(i == j)temp += \"*\";\n else temp += s[i];\n }\n return temp;\n }\n int ladderLength(string b, string e, vector<string>& w) {\n if(find(w.begin(), w.end(), e) == w.end() || !b.size() || !e.size() || !w.size())return 0;\n map < string , vector <string> > m;\n for(int i = 0; i < w.size(); i++){\n string x = w[i];\n for(int j = 0; j < x.size(); j++){\n string inter = putStar(j,x);\n m[inter].push_back(x);\n }\n }\n queue < pair <string, int> > q;\n q.push({b, 1});\n map <string, int> visited;\n while(!q.empty()){\n pair < string, int > s = q.front();\n q.pop();\n string x = s.first;\n int l = s.second;\n for(int i = 0; i < x.size(); i++){\n string temp = putStar(i ,x);\n for(int j = 0; j < m[temp].size(); j++){\n string aa = m[temp][j];\n if(aa == e)return l+1;\n if(!visited[aa]){\n q.push({aa, l+1});\n visited[aa] = 1;\n }\n }\n }\n }\n int level = 0;\n return 0;\n }\n};\nmain(){\n vector<string> v = {\"hot\",\"dot\",\"dog\",\"lot\",\"log\",\"cog\"};\n Solution ob;\n cout << (ob.ladderLength(\"hit\", \"cog\", v));\n}" }, { "code": null, "e": 6730, "s": 6680, "text": "\"hit\"\n\"cog\"\n[\"hot\",\"dot\",\"dog\",\"lot\",\"log\",\"cog\"]" }, { "code": null, "e": 6732, "s": 6730, "text": "5" } ]
Math.Abs() Method in C#
The Math.Abs() method in C# is used to return the absolute value of a specified number in C#. This specified number can be decimal, double, 16-bit signed integer, etc. Let us now see an example to implement the Math.abs() method to return the absolute value of double number − using System; class Demo { public static void Main(){ Double val1 = 30.40; Double val2 = Double.MinValue; Double val3 = Double.MaxValue; Console.WriteLine("Absolute value of {0} : {1}", val1, Math.Abs(val1)); Console.WriteLine("Absolute value of {0} : {1}", val2, Math.Abs(val2)); Console.WriteLine("Absolute value of {0} : {1}", val3, Math.Abs(val3)); } } This will produce the following output − Absolute value of 30.4 : 30.4 Absolute value of -1.79769313486232E+308 : 1.79769313486232E+308 Absolute value of 1.79769313486232E+308 : 1.79769313486232E+308 Let us now see another example to implement the Math.abs() method to return the absolute value of 16-bit signed integer − using System; class Demo { public static void Main(){ short val1 = -300; short val2 = Int16.MaxValue; short val3 = 0; Console.WriteLine("Absolute value of {0} : {1}", val1, Math.Abs(val1)); Console.WriteLine("Absolute value of {0} : {1}" val2, Math.Abs(val2)); Console.WriteLine("Absolute value of {0} : {1}", val3, Math.Abs(val3)); } } This will produce the following output − Absolute value of -300 : 300 Absolute value of 32767 : 32767 Absolute value of 0 : 0
[ { "code": null, "e": 1230, "s": 1062, "text": "The Math.Abs() method in C# is used to return the absolute value of a specified number in C#. This specified number can be decimal, double, 16-bit signed integer, etc." }, { "code": null, "e": 1339, "s": 1230, "text": "Let us now see an example to implement the Math.abs() method to return the absolute value of double number −" }, { "code": null, "e": 1738, "s": 1339, "text": "using System;\nclass Demo {\n public static void Main(){\n Double val1 = 30.40;\n Double val2 = Double.MinValue;\n Double val3 = Double.MaxValue;\n Console.WriteLine(\"Absolute value of {0} : {1}\", val1, Math.Abs(val1));\n Console.WriteLine(\"Absolute value of {0} : {1}\", val2, Math.Abs(val2));\n Console.WriteLine(\"Absolute value of {0} : {1}\", val3, Math.Abs(val3));\n }\n}" }, { "code": null, "e": 1779, "s": 1738, "text": "This will produce the following output −" }, { "code": null, "e": 1938, "s": 1779, "text": "Absolute value of 30.4 : 30.4\nAbsolute value of -1.79769313486232E+308 : 1.79769313486232E+308\nAbsolute value of 1.79769313486232E+308 : 1.79769313486232E+308" }, { "code": null, "e": 2060, "s": 1938, "text": "Let us now see another example to implement the Math.abs() method to return the absolute value of 16-bit signed integer −" }, { "code": null, "e": 2439, "s": 2060, "text": "using System;\nclass Demo {\n public static void Main(){\n short val1 = -300;\n short val2 = Int16.MaxValue;\n short val3 = 0;\n Console.WriteLine(\"Absolute value of {0} : {1}\", val1, Math.Abs(val1));\n Console.WriteLine(\"Absolute value of {0} : {1}\" val2, Math.Abs(val2));\n Console.WriteLine(\"Absolute value of {0} : {1}\", val3, Math.Abs(val3));\n }\n}" }, { "code": null, "e": 2480, "s": 2439, "text": "This will produce the following output −" }, { "code": null, "e": 2565, "s": 2480, "text": "Absolute value of -300 : 300\nAbsolute value of 32767 : 32767\nAbsolute value of 0 : 0" } ]
How to make an alert dialog fill 50% of screen size on Android devices using Kotlin?
This example demonstrates how to make an alert dialog fill 50% of screen size on Android devices using Kotlin. Step 1 − Create a new project in Android Studio, go to File ⇒ New Project and fill all required details to create a new project. Step 2 − Add the following code to res/layout/activity_main.xml. <?xml version="1.0" encoding="utf-8"?> <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:id="@+id/rl" android:layout_width="match_parent" android:layout_height="match_parent" android:background="#f2f6f4" android:padding="10dp" tools:context=".MainActivity"> <TextView android:id="@+id/text2" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_centerHorizontal="true" android:layout_marginTop="70dp" android:background="#008080" android:padding="5dp" android:text="TutorialsPoint" android:textColor="#fff" android:textSize="24sp" android:textStyle="bold" /> <Button android:id="@+id/buttonAlert" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_centerInParent="true" android:text="Show Alert Dialog"/> </RelativeLayout> Step 3 − Add the following code to src/MainActivity.kt import android.os.Bundle import android.util.DisplayMetrics import android.view.WindowManager import android.widget.Button import androidx.appcompat.app.AppCompatActivity class MainActivity : AppCompatActivity() { lateinit var button: Button override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) title = "KotlinApp" button = findViewById(R.id.buttonAlert) button.setOnClickListener { val builder: android.app.AlertDialog.Builder = android.app.AlertDialog.Builder(this) builder.setTitle("Say Hello!") builder.setMessage("Do you want to reply back?") builder.setPositiveButton("Yes", null) builder.setNegativeButton("No", null) val dialog: android.app.AlertDialog? = builder.create() dialog?.show() val displayMetrics = DisplayMetrics() windowManager.defaultDisplay.getMetrics(displayMetrics) val displayWidth = displayMetrics.widthPixels val displayHeight = displayMetrics.heightPixels val layoutParams = WindowManager.LayoutParams() layoutParams.copyFrom(dialog?.window?.attributes) val dialogWindowWidth = (displayWidth * 0.5f).toInt() val dialogWindowHeight = (displayHeight * 0.5f).toInt() layoutParams.width = dialogWindowWidth layoutParams.height = dialogWindowHeight dialog?.window?.attributes = layoutParams } } } Step 4 − Add the following code to androidManifest.xml <?xml version="1.0" encoding="utf-8"?> <manifest xmlns:android="http://schemas.android.com/apk/res/android" package="com.example.q11"> <application android:allowBackup="true" android:icon="@mipmap/ic_launcher" android:label="@string/app_name" android:roundIcon="@mipmap/ic_launcher_round" android:supportsRtl="true" android:theme="@style/AppTheme"> <activity android:name=".MainActivity"> <intent-filter> <action android:name="android.intent.action.MAIN" /> <category android:name="android.intent.category.LAUNCHER" /> </intent-filter> </activity> </application> </manifest> Let's try to run your application. I assume you have connected your actual Android Mobile device with your computer. To run the app from android studio, open one of your project's activity files and click the Run icon from the toolbar. Select your mobile device as an option and then check your mobile device which will display your default screen.
[ { "code": null, "e": 1173, "s": 1062, "text": "This example demonstrates how to make an alert dialog fill 50% of screen size on Android devices using Kotlin." }, { "code": null, "e": 1302, "s": 1173, "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": 1367, "s": 1302, "text": "Step 2 − Add the following code to res/layout/activity_main.xml." }, { "code": null, "e": 2365, "s": 1367, "text": "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<RelativeLayout xmlns:android=\"http://schemas.android.com/apk/res/android\"\n xmlns:tools=\"http://schemas.android.com/tools\"\n android:id=\"@+id/rl\"\n android:layout_width=\"match_parent\"\n android:layout_height=\"match_parent\"\n android:background=\"#f2f6f4\"\n android:padding=\"10dp\"\n tools:context=\".MainActivity\">\n <TextView\n android:id=\"@+id/text2\"\n android:layout_width=\"wrap_content\"\n android:layout_height=\"wrap_content\"\n android:layout_centerHorizontal=\"true\"\n android:layout_marginTop=\"70dp\"\n android:background=\"#008080\"\n android:padding=\"5dp\"\n android:text=\"TutorialsPoint\"\n android:textColor=\"#fff\"\n android:textSize=\"24sp\"\n android:textStyle=\"bold\" />\n <Button\n android:id=\"@+id/buttonAlert\"\n android:layout_width=\"wrap_content\"\n android:layout_height=\"wrap_content\"\n android:layout_centerInParent=\"true\"\n android:text=\"Show Alert Dialog\"/>\n</RelativeLayout>" }, { "code": null, "e": 2420, "s": 2365, "text": "Step 3 − Add the following code to src/MainActivity.kt" }, { "code": null, "e": 3921, "s": 2420, "text": "import android.os.Bundle\nimport android.util.DisplayMetrics\nimport android.view.WindowManager\nimport android.widget.Button\nimport androidx.appcompat.app.AppCompatActivity\nclass MainActivity : AppCompatActivity() {\n lateinit var button: Button\n override fun onCreate(savedInstanceState: Bundle?) {\n super.onCreate(savedInstanceState)\n setContentView(R.layout.activity_main)\n title = \"KotlinApp\"\n button = findViewById(R.id.buttonAlert)\n button.setOnClickListener {\n val builder: android.app.AlertDialog.Builder = android.app.AlertDialog.Builder(this)\n builder.setTitle(\"Say Hello!\")\n builder.setMessage(\"Do you want to reply back?\")\n builder.setPositiveButton(\"Yes\", null)\n builder.setNegativeButton(\"No\", null)\n val dialog: android.app.AlertDialog? = builder.create()\n dialog?.show()\n val displayMetrics = DisplayMetrics()\n windowManager.defaultDisplay.getMetrics(displayMetrics)\n val displayWidth = displayMetrics.widthPixels\n val displayHeight = displayMetrics.heightPixels\n val layoutParams = WindowManager.LayoutParams()\n layoutParams.copyFrom(dialog?.window?.attributes)\n val dialogWindowWidth = (displayWidth * 0.5f).toInt()\n val dialogWindowHeight = (displayHeight * 0.5f).toInt()\n layoutParams.width = dialogWindowWidth\n layoutParams.height = dialogWindowHeight\n dialog?.window?.attributes = layoutParams\n }\n }\n}" }, { "code": null, "e": 3976, "s": 3921, "text": "Step 4 − Add the following code to androidManifest.xml" }, { "code": null, "e": 4650, "s": 3976, "text": "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<manifest xmlns:android=\"http://schemas.android.com/apk/res/android\"\n package=\"com.example.q11\">\n <application\n android:allowBackup=\"true\"\n android:icon=\"@mipmap/ic_launcher\"\n android:label=\"@string/app_name\"\n android:roundIcon=\"@mipmap/ic_launcher_round\"\n android:supportsRtl=\"true\"\n android:theme=\"@style/AppTheme\">\n <activity android:name=\".MainActivity\">\n <intent-filter>\n <action android:name=\"android.intent.action.MAIN\" />\n <category android:name=\"android.intent.category.LAUNCHER\" />\n </intent-filter>\n </activity>\n </application>\n</manifest>" }, { "code": null, "e": 4999, "s": 4650, "text": "Let's try to run your application. I assume you have connected your actual Android Mobile device with your computer. To run the app from android studio, open one of your project's activity files and click the Run icon from the toolbar. Select your mobile device as an option and then check your mobile device which will display your default screen." } ]
MongoDB - Projection
In MongoDB, projection means selecting only the necessary data rather than selecting whole of the data of a document. If a document has 5 fields and you need to show only 3, then select only 3 fields from them. MongoDB's find() method, explained in MongoDB Query Document accepts second optional parameter that is list of fields that you want to retrieve. In MongoDB, when you execute find() method, then it displays all fields of a document. To limit this, you need to set a list of fields with value 1 or 0. 1 is used to show the field while 0 is used to hide the fields. The basic syntax of find() method with projection is as follows − >db.COLLECTION_NAME.find({},{KEY:1}) Consider the collection mycol has the following data − {_id : ObjectId("507f191e810c19729de860e1"), title: "MongoDB Overview"}, {_id : ObjectId("507f191e810c19729de860e2"), title: "NoSQL Overview"}, {_id : ObjectId("507f191e810c19729de860e3"), title: "Tutorials Point Overview"} Following example will display the title of the document while querying the document. >db.mycol.find({},{"title":1,_id:0}) {"title":"MongoDB Overview"} {"title":"NoSQL Overview"} {"title":"Tutorials Point Overview"} > Please note _id field is always displayed while executing find() method, if you don't want this field, then you need to set it as 0. 44 Lectures 3 hours Arnab Chakraborty 54 Lectures 5.5 hours Eduonix Learning Solutions 44 Lectures 4.5 hours Kaushik Roy Chowdhury 40 Lectures 2.5 hours University Code 26 Lectures 8 hours Bassir Jafarzadeh 70 Lectures 2.5 hours Skillbakerystudios Print Add Notes Bookmark this page
[ { "code": null, "e": 2764, "s": 2553, "text": "In MongoDB, projection means selecting only the necessary data rather than selecting whole of the data of a document. If a document has 5 fields and you need to show only 3, then select only 3 fields from them." }, { "code": null, "e": 3127, "s": 2764, "text": "MongoDB's find() method, explained in MongoDB Query Document accepts second optional parameter that is list of fields that you want to retrieve. In MongoDB, when you execute find() method, then it displays all fields of a document. To limit this, you need to set a list of fields with value 1 or 0. 1 is used to show the field while 0 is used to hide the fields." }, { "code": null, "e": 3193, "s": 3127, "text": "The basic syntax of find() method with projection is as follows −" }, { "code": null, "e": 3231, "s": 3193, "text": ">db.COLLECTION_NAME.find({},{KEY:1})\n" }, { "code": null, "e": 3286, "s": 3231, "text": "Consider the collection mycol has the following data −" }, { "code": null, "e": 3510, "s": 3286, "text": "{_id : ObjectId(\"507f191e810c19729de860e1\"), title: \"MongoDB Overview\"},\n{_id : ObjectId(\"507f191e810c19729de860e2\"), title: \"NoSQL Overview\"},\n{_id : ObjectId(\"507f191e810c19729de860e3\"), title: \"Tutorials Point Overview\"}" }, { "code": null, "e": 3596, "s": 3510, "text": "Following example will display the title of the document while querying the document." }, { "code": null, "e": 3728, "s": 3596, "text": ">db.mycol.find({},{\"title\":1,_id:0})\n{\"title\":\"MongoDB Overview\"}\n{\"title\":\"NoSQL Overview\"}\n{\"title\":\"Tutorials Point Overview\"}\n>" }, { "code": null, "e": 3861, "s": 3728, "text": "Please note _id field is always displayed while executing find() method, if you don't want this field, then you need to set it as 0." }, { "code": null, "e": 3894, "s": 3861, "text": "\n 44 Lectures \n 3 hours \n" }, { "code": null, "e": 3913, "s": 3894, "text": " Arnab Chakraborty" }, { "code": null, "e": 3948, "s": 3913, "text": "\n 54 Lectures \n 5.5 hours \n" }, { "code": null, "e": 3976, "s": 3948, "text": " Eduonix Learning Solutions" }, { "code": null, "e": 4011, "s": 3976, "text": "\n 44 Lectures \n 4.5 hours \n" }, { "code": null, "e": 4034, "s": 4011, "text": " Kaushik Roy Chowdhury" }, { "code": null, "e": 4069, "s": 4034, "text": "\n 40 Lectures \n 2.5 hours \n" }, { "code": null, "e": 4086, "s": 4069, "text": " University Code" }, { "code": null, "e": 4119, "s": 4086, "text": "\n 26 Lectures \n 8 hours \n" }, { "code": null, "e": 4138, "s": 4119, "text": " Bassir Jafarzadeh" }, { "code": null, "e": 4173, "s": 4138, "text": "\n 70 Lectures \n 2.5 hours \n" }, { "code": null, "e": 4193, "s": 4173, "text": " Skillbakerystudios" }, { "code": null, "e": 4200, "s": 4193, "text": " Print" }, { "code": null, "e": 4211, "s": 4200, "text": " Add Notes" } ]
Teradata - SubQueries
A subquery returns records from one table based on the values from another table. It is a SELECT query within another query. The SELECT query called as inner query is executed first and the result is used by the outer query. Some of its salient features are − A query can have multiple subqueries and subqueries may contain another subquery. A query can have multiple subqueries and subqueries may contain another subquery. Subqueries doesn't return duplicate records. Subqueries doesn't return duplicate records. If subquery returns only one value, you can use = operator to use it with the outer query. If it returns multiple values you can use IN or NOT IN. If subquery returns only one value, you can use = operator to use it with the outer query. If it returns multiple values you can use IN or NOT IN. Following is the generic syntax of subqueries. SELECT col1, col2, col3,... FROM Outer Table WHERE col1 OPERATOR ( Inner SELECT Query); Consider the following Salary table. The following query identifies the employee number with highest salary. The inner SELECT performs the aggregation function to return the maximum NetPay value and the outer SELECT query uses this value to return the employee record with this value. SELECT EmployeeNo, NetPay FROM Salary WHERE NetPay = (SELECT MAX(NetPay) FROM Salary); When this query is executed, it produces the following output. *** Query completed. One row found. 2 columns returned. *** Total elapsed time was 1 second. EmployeeNo NetPay ----------- ----------- 103 83000 Print Add Notes Bookmark this page
[ { "code": null, "e": 2890, "s": 2630, "text": "A subquery returns records from one table based on the values from another table. It is a SELECT query within another query. The SELECT query called as inner query is executed first and the result is used by the outer query. Some of its salient features are −" }, { "code": null, "e": 2972, "s": 2890, "text": "A query can have multiple subqueries and subqueries may contain another subquery." }, { "code": null, "e": 3054, "s": 2972, "text": "A query can have multiple subqueries and subqueries may contain another subquery." }, { "code": null, "e": 3099, "s": 3054, "text": "Subqueries doesn't return duplicate records." }, { "code": null, "e": 3144, "s": 3099, "text": "Subqueries doesn't return duplicate records." }, { "code": null, "e": 3291, "s": 3144, "text": "If subquery returns only one value, you can use = operator to use it with the outer query. If it returns multiple values you can use IN or NOT IN." }, { "code": null, "e": 3438, "s": 3291, "text": "If subquery returns only one value, you can use = operator to use it with the outer query. If it returns multiple values you can use IN or NOT IN." }, { "code": null, "e": 3485, "s": 3438, "text": "Following is the generic syntax of subqueries." }, { "code": null, "e": 3578, "s": 3485, "text": "SELECT col1, col2, col3,... \nFROM \nOuter Table \nWHERE col1 OPERATOR ( Inner SELECT Query);\n" }, { "code": null, "e": 3615, "s": 3578, "text": "Consider the following Salary table." }, { "code": null, "e": 3863, "s": 3615, "text": "The following query identifies the employee number with highest salary. The inner SELECT performs the aggregation function to return the maximum NetPay value and the outer SELECT query uses this value to return the employee record with this value." }, { "code": null, "e": 3956, "s": 3863, "text": "SELECT EmployeeNo, NetPay \nFROM Salary \nWHERE NetPay = \n(SELECT MAX(NetPay) \nFROM Salary);" }, { "code": null, "e": 4019, "s": 3956, "text": "When this query is executed, it produces the following output." }, { "code": null, "e": 4189, "s": 4019, "text": "*** Query completed. One row found. 2 columns returned. \n*** Total elapsed time was 1 second. \n EmployeeNo NetPay \n----------- ----------- \n 103 83000 \n" }, { "code": null, "e": 4196, "s": 4189, "text": " Print" }, { "code": null, "e": 4207, "s": 4196, "text": " Add Notes" } ]
Count quadruples from four sorted arrays whose sum is equal to a given value x - GeeksforGeeks
28 Jun, 2021 Given four sorted arrays each of size n of distinct elements. Given a value x. The problem is to count all quadruples(group of four numbers) from all the four arrays whose sum is equal to x.Note: The quadruple has an element from each of the four arrays. Examples: Input : arr1 = {1, 4, 5, 6}, arr2 = {2, 3, 7, 8}, arr3 = {1, 4, 6, 10}, arr4 = {2, 4, 7, 8} n = 4, x = 30 Output : 4 The quadruples are: (4, 8, 10, 8), (5, 7, 10, 8), (5, 8, 10, 7), (6, 7, 10, 7) Input : For the same above given fours arrays x = 25 Output : 14 Method 1 (Naive Approach): Using four nested loops generate all quadruples and check whether elements in the quadruple sum up to x or not. C++ Java Python3 C# PHP Javascript // C++ implementation to count quadruples from four sorted arrays// whose sum is equal to a given value x#include <bits/stdc++.h> using namespace std; // function to count all quadruples from// four sorted arrays whose sum is equal// to a given value xint countQuadruples(int arr1[], int arr2[], int arr3[], int arr4[], int n, int x){ int count = 0; // generate all possible quadruples from // the four sorted arrays for (int i = 0; i < n; i++) for (int j = 0; j < n; j++) for (int k = 0; k < n; k++) for (int l = 0; l < n; l++) // check whether elements of // quadruple sum up to x or not if ((arr1[i] + arr2[j] + arr3[k] + arr4[l]) == x) count++; // required count of quadruples return count;} // Driver program to test aboveint main(){ // four sorted arrays each of size 'n' int arr1[] = { 1, 4, 5, 6 }; int arr2[] = { 2, 3, 7, 8 }; int arr3[] = { 1, 4, 6, 10 }; int arr4[] = { 2, 4, 7, 8 }; int n = sizeof(arr1) / sizeof(arr1[0]); int x = 30; cout << "Count = " << countQuadruples(arr1, arr2, arr3, arr4, n, x); return 0;} // Java implementation to count quadruples from four sorted arrays// whose sum is equal to a given value xclass GFG {// function to count all quadruples from// four sorted arrays whose sum is equal// to a given value x static int countQuadruples(int arr1[], int arr2[], int arr3[], int arr4[], int n, int x) { int count = 0; // generate all possible quadruples from // the four sorted arrays for (int i = 0; i < n; i++) { for (int j = 0; j < n; j++) { for (int k = 0; k < n; k++) { for (int l = 0; l < n; l++) // check whether elements of // quadruple sum up to x or not { if ((arr1[i] + arr2[j] + arr3[k] + arr4[l]) == x) { count++; } } } } } // required count of quadruples return count; } // Driver program to test above public static void main(String[] args) { // four sorted arrays each of size 'n' int arr1[] = {1, 4, 5, 6}; int arr2[] = {2, 3, 7, 8}; int arr3[] = {1, 4, 6, 10}; int arr4[] = {2, 4, 7, 8}; int n = arr1.length; int x = 30; System.out.println("Count = " + countQuadruples(arr1, arr2, arr3, arr4, n, x)); }}//This code is contributed by PrinciRaj1992 # A Python3 implementation to count# quadruples from four sorted arrays# whose sum is equal to a given value x # function to count all quadruples# from four sorted arrays whose sum# is equal to a given value xdef countQuuadruples(arr1, arr2, arr3, arr4, n, x): count = 0 # generate all possible # quadruples from the four # sorted arrays for i in range(n): for j in range(n): for k in range(n): for l in range(n): # check whether elements of # quadruple sum up to x or not if (arr1[i] + arr2[j] + arr3[k] + arr4[l] == x): count += 1 # required count of quadruples return count # Driver Codearr1 = [1, 4, 5, 6]arr2 = [2, 3, 7, 8]arr3 = [1, 4, 6, 10]arr4 = [2, 4, 7, 8 ]n = len(arr1)x = 30print("Count = ", countQuuadruples(arr1, arr2, arr3, arr4, n, x)) # This code is contributed# by Shrikant13 // C# implementation to count quadruples from four sorted arrays// whose sum is equal to a given value xusing System;public class GFG {// function to count all quadruples from// four sorted arrays whose sum is equal// to a given value x static int countQuadruples(int []arr1, int []arr2, int []arr3, int []arr4, int n, int x) { int count = 0; // generate all possible quadruples from // the four sorted arrays for (int i = 0; i < n; i++) { for (int j = 0; j < n; j++) { for (int k = 0; k < n; k++) { for (int l = 0; l < n; l++) // check whether elements of // quadruple sum up to x or not { if ((arr1[i] + arr2[j] + arr3[k] + arr4[l]) == x) { count++; } } } } } // required count of quadruples return count; } // Driver program to test above public static void Main() { // four sorted arrays each of size 'n' int []arr1 = {1, 4, 5, 6}; int []arr2 = {2, 3, 7, 8}; int []arr3 = {1, 4, 6, 10}; int []arr4 = {2, 4, 7, 8}; int n = arr1.Length; int x = 30; Console.Write("Count = " + countQuadruples(arr1, arr2, arr3, arr4, n, x)); }} // This code is contributed by PrinciRaj19992 <?php// PHP implementation to count quadruples// from four sorted arrays whose sum is// equal to a given value x // function to count all quadruples from// four sorted arrays whose sum is equal// to a given value xfunction countQuadruples(&$arr1, &$arr2, &$arr3, &$arr4, $n, $x){ $count = 0; // generate all possible quadruples // from the four sorted arrays for ($i = 0; $i < $n; $i++) for ($j = 0; $j < $n; $j++) for ($k = 0; $k < $n; $k++) for ($l = 0; $l < $n; $l++) // check whether elements of // quadruple sum up to x or not if (($arr1[$i] + $arr2[$j] + $arr3[$k] + $arr4[$l]) == $x) $count++; // required count of quadruples return $count;} // Driver Code // four sorted arrays each of size 'n'$arr1 = array( 1, 4, 5, 6 );$arr2 = array( 2, 3, 7, 8 );$arr3 = array( 1, 4, 6, 10 );$arr4 = array( 2, 4, 7, 8 ); $n = sizeof($arr1);$x = 30;echo "Count = " . countQuadruples($arr1, $arr2, $arr3, $arr4, $n, $x); // This code is contributed by ita_c?> <script>// Javascript implementation to count quadruples from four sorted arrays// whose sum is equal to a given value x // function to count all quadruples from// four sorted arrays whose sum is equal// to a given value x function countQuadruples(arr1,arr2,arr3,arr4,n,x) { let count = 0; // generate all possible quadruples from // the four sorted arrays for (let i = 0; i < n; i++) { for (let j = 0; j < n; j++) { for (let k = 0; k < n; k++) { for (let l = 0; l < n; l++) // check whether elements of // quadruple sum up to x or not { if ((arr1[i] + arr2[j] + arr3[k] + arr4[l]) == x) { count++; } } } } } // required count of quadruples return count; } // Driver program to test above let arr1=[1, 4, 5, 6]; let arr2=[2, 3, 7, 8]; let arr3=[1, 4, 6, 10]; let arr4=[2, 4, 7, 8]; let n = arr1.length; let x = 30; document.write("Count = " + countQuadruples(arr1, arr2, arr3, arr4, n, x)); //This code is contributed by rag2127 </script> Output: Count = 4 Time Complexity: O(n4) Auxiliary Space: O(1) Method 2 (Binary Search): Generate all triplets from the 1st three arrays. For each triplet so generated, find the sum of elements in the triplet. Let it be T. Now, search the value (x – T) in the 4th array. If the value found in the 4th array, then increment count. This process is repeated for all the triplets generated from the 1st three arrays. C++ Java C# PHP Javascript // C++ implementation to count quadruples from// four sorted arrays whose sum is equal to a// given value x#include <bits/stdc++.h> using namespace std; // find the 'value' in the given array 'arr[]'// binary search technique is appliedbool isPresent(int arr[], int low, int high, int value){ while (low <= high) { int mid = (low + high) / 2; // 'value' found if (arr[mid] == value) return true; else if (arr[mid] > value) high = mid - 1; else low = mid + 1; } // 'value' not found return false;} // function to count all quadruples from four// sorted arrays whose sum is equal to a given value xint countQuadruples(int arr1[], int arr2[], int arr3[], int arr4[], int n, int x){ int count = 0; // generate all triplets from the 1st three arrays for (int i = 0; i < n; i++) for (int j = 0; j < n; j++) for (int k = 0; k < n; k++) { // calculate the sum of elements in // the triplet so generated int T = arr1[i] + arr2[j] + arr3[k]; // check if 'x-T' is present in 4th // array or not if (isPresent(arr4, 0, n, x - T)) // increment count count++; } // required count of quadruples return count;} // Driver program to test aboveint main(){ // four sorted arrays each of size 'n' int arr1[] = { 1, 4, 5, 6 }; int arr2[] = { 2, 3, 7, 8 }; int arr3[] = { 1, 4, 6, 10 }; int arr4[] = { 2, 4, 7, 8 }; int n = sizeof(arr1) / sizeof(arr1[0]); int x = 30; cout << "Count = " << countQuadruples(arr1, arr2, arr3, arr4, n, x); return 0;} // Java implementation to count quadruples from// four sorted arrays whose sum is equal to a// given value xclass GFG{ // find the 'value' in the given array 'arr[]' // binary search technique is applied static boolean isPresent(int[] arr, int low, int high, int value) { while (low <= high) { int mid = (low + high) / 2; // 'value' found if (arr[mid] == value) return true; else if (arr[mid] > value) high = mid - 1; else low = mid + 1; } // 'value' not found return false; } // function to count all quadruples from four // sorted arrays whose sum is equal to a given value x static int countQuadruples(int[] arr1, int[] arr2, int[] arr3, int[] arr4, int n, int x) { int count = 0; // generate all triplets from the 1st three arrays for (int i = 0; i < n; i++) for (int j = 0; j < n; j++) for (int k = 0; k < n; k++) { // calculate the sum of elements in // the triplet so generated int T = arr1[i] + arr2[j] + arr3[k]; // check if 'x-T' is present in 4th // array or not if (isPresent(arr4, 0, n-1, x - T)) // increment count count++; } // required count of quadruples return count; } // Driver code public static void main(String[] args) { // four sorted arrays each of size 'n' int[] arr1 = { 1, 4, 5, 6 }; int[] arr2 = { 2, 3, 7, 8 }; int[] arr3 = { 1, 4, 6, 10 }; int[] arr4 = { 2, 4, 7, 8 }; int n = 4; int x = 30; System.out.println( "Count = " + countQuadruples(arr1, arr2, arr3, arr4, n, x)); }} // This code is contributed by Rajput-Ji // C# implementation to count quadruples from// four sorted arrays whose sum is equal to a// given value xusing System; class GFG{ // find the 'value' in the given array 'arr[]' // binary search technique is applied static bool isPresent(int[] arr, int low, int high, int value) { while (low <= high) { int mid = (low + high) / 2; // 'value' found if (arr[mid] == value) return true; else if (arr[mid] > value) high = mid - 1; else low = mid + 1; } // 'value' not found return false; } // function to count all quadruples from four // sorted arrays whose sum is equal to a given value x static int countQuadruples(int[] arr1, int[] arr2, int[] arr3, int[] arr4, int n, int x) { int count = 0; // generate all triplets from the 1st three arrays for (int i = 0; i < n; i++) for (int j = 0; j < n; j++) for (int k = 0; k < n; k++) { // calculate the sum of elements in // the triplet so generated int T = arr1[i] + arr2[j] + arr3[k]; // check if 'x-T' is present in 4th // array or not if (isPresent(arr4, 0, n-1, x - T)) // increment count count++; } // required count of quadruples return count; } // Driver code public static void Main(String[] args) { // four sorted arrays each of size 'n' int[] arr1 = { 1, 4, 5, 6 }; int[] arr2 = { 2, 3, 7, 8 }; int[] arr3 = { 1, 4, 6, 10 }; int[] arr4 = { 2, 4, 7, 8 }; int n = 4; int x = 30; Console.WriteLine( "Count = " + countQuadruples(arr1, arr2, arr3, arr4, n, x)); }} // This code has been contributed by 29AjayKumar <?php// PHP implementation to count quadruples from// four sorted arrays whose sum is equal to a// given value x // find the 'value' in the given array 'arr[]'// binary search technique is appliedfunction isPresent($arr, $low, $high, $value){ while ($low <= $high) { $mid = ($low + $high) / 2; // 'value' found if ($arr[$mid] == $value) return true; else if ($arr[$mid] > $value) $high = $mid - 1; else $low = $mid + 1; } // 'value' not found return false;} // function to count all quadruples from// four sorted arrays whose sum is equal// to a given value xfunction countQuadruples($arr1, $arr2, $arr3, $arr4, $n, $x){ $count = 0; // generate all triplets from the // 1st three arrays for ($i = 0; $i < $n; $i++) for ($j = 0; $j < $n; $j++) for ($k = 0; $k < $n; $k++) { // calculate the sum of elements in // the triplet so generated $T = $arr1[$i] + $arr2[$j] + $arr3[$k]; // check if 'x-T' is present in 4th // array or not if (isPresent($arr4, 0, $n, $x - $T)) // increment count $count++; } // required count of quadruples return $count;} // Driver Code // four sorted arrays each of size 'n'$arr1 = array(1, 4, 5, 6);$arr2 = array(2, 3, 7, 8);$arr3 = array(1, 4, 6, 10);$arr4 = array(2, 4, 7, 8); $n = sizeof($arr1);$x = 30;echo "Count = " . countQuadruples($arr1, $arr2, $arr3, $arr4, $n, $x); // This code is contributed// by Akanksha Rai?> <script> // Javascript implementation to count quadruples from // four sorted arrays whose sum is equal to a // given value x // find the 'value' in the given array 'arr[]' // binary search technique is applied function isPresent(arr, low, high, value) { while (low <= high) { let mid = parseInt((low + high) / 2, 10); // 'value' found if (arr[mid] == value) return true; else if (arr[mid] > value) high = mid - 1; else low = mid + 1; } // 'value' not found return false; } // function to count all quadruples from four // sorted arrays whose sum is equal to a given value x function countQuadruples(arr1, arr2, arr3, arr4, n, x) { let count = 0; // generate all triplets from the 1st three arrays for (let i = 0; i < n; i++) for (let j = 0; j < n; j++) for (let k = 0; k < n; k++) { // calculate the sum of elements in // the triplet so generated let T = arr1[i] + arr2[j] + arr3[k]; // check if 'x-T' is present in 4th // array or not if (isPresent(arr4, 0, n-1, x - T)) // increment count count++; } // required count of quadruples return count; } // four sorted arrays each of size 'n' let arr1 = [ 1, 4, 5, 6 ]; let arr2 = [ 2, 3, 7, 8 ]; let arr3 = [ 1, 4, 6, 10 ]; let arr4 = [ 2, 4, 7, 8 ]; let n = 4; let x = 30; document.write( "Count = " + countQuadruples(arr1, arr2, arr3, arr4, n, x)); </script> Output: Count = 4 Time Complexity: O(n3logn) Auxiliary Space: O(1) Method 3 (Use of two pointers): Generate all pairs from the 1st two arrays. For each pair so generated, find the sum of elements in the pair. Let it be p_sum. For each p_sum, count pairs from the 3rd and 4th sorted array with sum equal to (x – p_sum). Accumulate these count in the total_count of quadruples. C++ Java Python3 C# Javascript // C++ implementation to count quadruples from// four sorted arrays whose sum is equal to a// given value x#include <bits/stdc++.h> using namespace std; // count pairs from the two sorted array whose sum// is equal to the given 'value'int countPairs(int arr1[], int arr2[], int n, int value){ int count = 0; int l = 0, r = n - 1; // traverse 'arr1[]' from left to right // traverse 'arr2[]' from right to left while (l < n & amp; &r >= 0) { int sum = arr1[l] + arr2[r]; // if the 'sum' is equal to 'value', then // increment 'l', decrement 'r' and // increment 'count' if (sum == value) { l++, r--; count++; } // if the 'sum' is greater than 'value', then // decrement r else if (sum > value) r--; // else increment l else l++; } // required count of pairs return count;} // function to count all quadruples from four sorted arrays// whose sum is equal to a given value xint countQuadruples(int arr1[], int arr2[], int arr3[], int arr4[], int n, int x){ int count = 0; // generate all pairs from arr1[] and arr2[] for (int i = 0; i < n; i++) for (int j = 0; j < n; j++) { // calculate the sum of elements in // the pair so generated int p_sum = arr1[i] + arr2[j]; // count pairs in the 3rd and 4th array // having value 'x-p_sum' and then // accumulate it to 'count' count += countPairs(arr3, arr4, n, x - p_sum); } // required count of quadruples return count;} // Driver program to test aboveint main(){ // four sorted arrays each of size 'n' int arr1[] = { 1, 4, 5, 6 }; int arr2[] = { 2, 3, 7, 8 }; int arr3[] = { 1, 4, 6, 10 }; int arr4[] = { 2, 4, 7, 8 }; int n = sizeof(arr1) / sizeof(arr1[0]); int x = 30; cout << "Count = " << countQuadruples(arr1, arr2, arr3, arr4, n, x); return 0;} // Java implementation to count quadruples from// four sorted arrays whose sum is equal to a// given value x class GFG { // count pairs from the two sorted array whose sum// is equal to the given 'value'static int countPairs(int arr1[], int arr2[], int n, int value){ int count = 0; int l = 0, r = n - 1; // traverse 'arr1[]' from left to right // traverse 'arr2[]' from right to left while (l < n & r >= 0) { int sum = arr1[l] + arr2[r]; // if the 'sum' is equal to 'value', then // increment 'l', decrement 'r' and // increment 'count' if (sum == value) { l++; r--; count++; } // if the 'sum' is greater than 'value', then // decrement r else if (sum > value) r--; // else increment l else l++; } // required count of pairs return count;} // function to count all quadruples from four sorted arrays// whose sum is equal to a given value xstatic int countQuadruples(int arr1[], int arr2[], int arr3[], int arr4[], int n, int x){ int count = 0; // generate all pairs from arr1[] and arr2[] for (int i = 0; i < n; i++) for (int j = 0; j < n; j++) { // calculate the sum of elements in // the pair so generated int p_sum = arr1[i] + arr2[j]; // count pairs in the 3rd and 4th array // having value 'x-p_sum' and then // accumulate it to 'count' count += countPairs(arr3, arr4, n, x - p_sum); } // required count of quadruples return count;}// Driver program to test above static public void main(String[] args) { // four sorted arrays each of size 'n' int arr1[] = {1, 4, 5, 6}; int arr2[] = {2, 3, 7, 8}; int arr3[] = {1, 4, 6, 10}; int arr4[] = {2, 4, 7, 8}; int n = arr1.length; int x = 30; System.out.println("Count = " + countQuadruples(arr1, arr2, arr3, arr4, n, x)); }} // This code is contributed by PrinciRaj19992 # Python3 implementation to# count quadruples from four# sorted arrays whose sum is# equal to a given value x# count pairs from the two# sorted array whose sum# is equal to the given 'value'def countPairs(arr1, arr2, n, value): count = 0 l = 0 r = n - 1 # traverse 'arr1[]' from # left to right # traverse 'arr2[]' from # right to left while (l < n and r >= 0): sum = arr1[l] + arr2[r] # if the 'sum' is equal # to 'value', then # increment 'l', decrement # 'r' and increment 'count' if (sum == value): l += 1 r -= 1 count += 1 # if the 'sum' is greater # than 'value', then decrement r elif (sum > value): r -= 1 # else increment l else: l += 1 # required count of pairs # print(count) return count # function to count all quadruples# from four sorted arrays whose sum# is equal to a given value xdef countQuadruples(arr1, arr2, arr3, arr4, n, x): count = 0 # generate all pairs from # arr1[] and arr2[] for i in range(0, n): for j in range(0, n): # calculate the sum of # elements in the pair # so generated p_sum = arr1[i] + arr2[j] # count pairs in the 3rd # and 4th array having # value 'x-p_sum' and then # accumulate it to 'count count += int(countPairs(arr3, arr4, n, x - p_sum)) # required count of quadruples return count # Driver codearr1 = [1, 4, 5, 6]arr2 = [2, 3, 7, 8]arr3 = [1, 4, 6, 10]arr4 = [2, 4, 7, 8]n = len(arr1)x = 30print("Count = ", countQuadruples(arr1, arr2, arr3, arr4, n, x)) # This code is contributed by Stream_Cipher // C# implementation to count quadruples from// four sorted arrays whose sum is equal to a// given value x using System;public class GFG { // count pairs from the two sorted array whose sum // is equal to the given 'value' static int countPairs(int []arr1, int []arr2, int n, int value) { int count = 0; int l = 0, r = n - 1; // traverse 'arr1[]' from left to right // traverse 'arr2[]' from right to left while (l < n & r >= 0) { int sum = arr1[l] + arr2[r]; // if the 'sum' is equal to 'value', then // increment 'l', decrement 'r' and // increment 'count' if (sum == value) { l++; r--; count++; } // if the 'sum' is greater than 'value', then // decrement r else if (sum > value) r--; // else increment l else l++; } // required count of pairs return count; } // function to count all quadruples from four sorted arrays // whose sum is equal to a given value x static int countQuadruples(int []arr1, int []arr2, int []arr3, int []arr4, int n, int x) { int count = 0; // generate all pairs from arr1[] and arr2[] for (int i = 0; i < n; i++) for (int j = 0; j < n; j++) { // calculate the sum of elements in // the pair so generated int p_sum = arr1[i] + arr2[j]; // count pairs in the 3rd and 4th array // having value 'x-p_sum' and then // accumulate it to 'count' count += countPairs(arr3, arr4, n, x - p_sum); } // required count of quadruples return count; } // Driver program to test above static public void Main() { // four sorted arrays each of size 'n' int []arr1 = {1, 4, 5, 6}; int []arr2 = {2, 3, 7, 8}; int []arr3 = {1, 4, 6, 10}; int []arr4 = {2, 4, 7, 8}; int n = arr1.Length; int x = 30; Console.Write("Count = " + countQuadruples(arr1, arr2, arr3, arr4, n, x)); }} // This code is contributed by PrinciRaj19992 <script>// Javascript implementation to count quadruples from// four sorted arrays whose sum is equal to a// given value x // count pairs from the two sorted array whose sum// is equal to the given 'value'function countPairs(arr1,arr2,n,value){ let count = 0; let l = 0, r = n - 1; // traverse 'arr1[]' from left to right // traverse 'arr2[]' from right to left while (l < n & r >= 0) { let sum = arr1[l] + arr2[r]; // if the 'sum' is equal to 'value', then // increment 'l', decrement 'r' and // increment 'count' if (sum == value) { l++; r--; count++; } // if the 'sum' is greater than 'value', then // decrement r else if (sum > value) r--; // else increment l else l++; } // required count of pairs return count;} // function to count all quadruples from four sorted arrays// whose sum is equal to a given value xfunction countQuadruples(arr1,arr2,arr3,arr4,n,x){ let count = 0; // generate all pairs from arr1[] and arr2[] for (let i = 0; i < n; i++) for (let j = 0; j < n; j++) { // calculate the sum of elements in // the pair so generated let p_sum = arr1[i] + arr2[j]; // count pairs in the 3rd and 4th array // having value 'x-p_sum' and then // accumulate it to 'count' count += countPairs(arr3, arr4, n, x - p_sum); } // required count of quadruples return count;} // Driver program to test above// four sorted arrays each of size 'n'let arr1=[1, 4, 5, 6];let arr2=[2, 3, 7, 8];let arr3=[1, 4, 6, 10];let arr4=[2, 4, 7, 8];let n = arr1.length;let x = 30;document.write("Count = " + countQuadruples(arr1, arr2, arr3, arr4, n, x)); // This code is contributed by ab2127</script> Output: Count = 4 Time Complexity: O(n3) Auxiliary Space: O(1) Method 4 Efficient Approach(Hashing): Create a hash table where (key, value) tuples are represented as (sum, frequency) tuples. Here the sum are obtained from the pairs of 1st and 2nd array and their frequency count is maintained in the hash table. Hash table is implemented using unordered_map in C++. Now, generate all pairs from the 3rd and 4th array. For each pair so generated, find the sum of elements in the pair. Let it be p_sum. For each p_sum, check whether (x – p_sum) exists in the hash table or not. If it exists, then add the frequency of (x – p_sum) to the count of quadruples. C++ Java Python3 C# Javascript // C++ implementation to count quadruples from// four sorted arrays whose sum is equal to a// given value x#include <bits/stdc++.h> using namespace std; // function to count all quadruples from four sorted// arrays whose sum is equal to a given value xint countQuadruples(int arr1[], int arr2[], int arr3[], int arr4[], int n, int x){ int count = 0; // unordered_map 'um' implemented as hash table // for <sum, frequency> tuples unordered_map<int, int> um; // count frequency of each sum obtained from the // pairs of arr1[] and arr2[] and store them in 'um' for (int i = 0; i < n; i++) for (int j = 0; j < n; j++) um[arr1[i] + arr2[j]]++; // generate pair from arr3[] and arr4[] for (int k = 0; k < n; k++) for (int l = 0; l < n; l++) { // calculate the sum of elements in // the pair so generated int p_sum = arr3[k] + arr4[l]; // if 'x-p_sum' is present in 'um' then // add frequency of 'x-p_sum' to 'count' if (um.find(x - p_sum) != um.end()) count += um[x - p_sum]; } // required count of quadruples return count;} // Driver program to test aboveint main(){ // four sorted arrays each of size 'n' int arr1[] = { 1, 4, 5, 6 }; int arr2[] = { 2, 3, 7, 8 }; int arr3[] = { 1, 4, 6, 10 }; int arr4[] = { 2, 4, 7, 8 }; int n = sizeof(arr1) / sizeof(arr1[0]); int x = 30; cout << "Count = " << countQuadruples(arr1, arr2, arr3, arr4, n, x); return 0;} // Java implementation to count quadruples from// four sorted arrays whose sum is equal to a// given value ximport java.util.*; class GFG{ // function to count all quadruples from four sorted// arrays whose sum is equal to a given value xstatic int countQuadruples(int arr1[], int arr2[], int arr3[], int arr4[], int n, int x){ int count = 0; // unordered_map 'um' implemented as hash table // for <sum, frequency> tuples Map<Integer,Integer> m = new HashMap<>(); // count frequency of each sum obtained from the // pairs of arr1[] and arr2[] and store them in 'um' for (int i = 0; i < n; i++) for (int j = 0; j < n; j++) if(m.containsKey(arr1[i] + arr2[j])) m.put((arr1[i] + arr2[j]), m.get((arr1[i] + arr2[j]))+1); else m.put((arr1[i] + arr2[j]), 1); // generate pair from arr3[] and arr4[] for (int k = 0; k < n; k++) for (int l = 0; l < n; l++) { // calculate the sum of elements in // the pair so generated int p_sum = arr3[k] + arr4[l]; // if 'x-p_sum' is present in 'um' then // add frequency of 'x-p_sum' to 'count' if (m.containsKey(x - p_sum)) count += m.get(x - p_sum); } // required count of quadruples return count;} // Driver program to test abovepublic static void main(String[] args){ // four sorted arrays each of size 'n' int arr1[] = { 1, 4, 5, 6 }; int arr2[] = { 2, 3, 7, 8 }; int arr3[] = { 1, 4, 6, 10 }; int arr4[] = { 2, 4, 7, 8 }; int n = arr1.length; int x = 30; System.out.println("Count = " + countQuadruples(arr1, arr2, arr3, arr4, n, x));}} // This code has been contributed by 29AjayKumar # Python implementation to count quadruples from# four sorted arrays whose sum is equal to a# given value x # function to count all quadruples from four sorted# arrays whose sum is equal to a given value xdef countQuadruples(arr1, arr2, arr3, arr4, n, x): count = 0 # unordered_map 'um' implemented as hash table # for <sum, frequency> tuples m = {} # count frequency of each sum obtained from the # pairs of arr1[] and arr2[] and store them in 'um' for i in range(n): for j in range(n): if (arr1[i] + arr2[j]) in m: m[arr1[i] + arr2[j]] += 1 else: m[arr1[i] + arr2[j]] = 1 # generate pair from arr3[] and arr4[] for k in range(n): for l in range(n): # calculate the sum of elements in # the pair so generated p_sum = arr3[k] + arr4[l] # if 'x-p_sum' is present in 'um' then # add frequency of 'x-p_sum' to 'count' if (x - p_sum) in m: count += m[x - p_sum] # required count of quadruples return count # Driver program to test above # four sorted arrays each of size 'n'arr1 = [1, 4, 5, 6]arr2 = [2, 3, 7, 8 ]arr3 = [1, 4, 6, 10]arr4 = [2, 4, 7, 8 ] n = len(arr1)x = 30print("Count =", countQuadruples(arr1, arr2, arr3, arr4, n, x)) # This code is contributed by avanitrachhadiya2155 // C# implementation to count quadruples from// four sorted arrays whose sum is equal to a// given value xusing System;using System.Collections.Generic; class GFG{ // function to count all quadruples from four sorted// arrays whose sum is equal to a given value xstatic int countQuadruples(int []arr1, int []arr2, int []arr3, int []arr4, int n, int x){ int count = 0; // unordered_map 'um' implemented as hash table // for <sum, frequency> tuples Dictionary<int,int> m = new Dictionary<int,int>(); // count frequency of each sum obtained from the // pairs of arr1[] and arr2[] and store them in 'um' for (int i = 0; i < n; i++) for (int j = 0; j < n; j++) if(m.ContainsKey(arr1[i] + arr2[j])){ var val = m[arr1[i] + arr2[j]]; m.Remove(arr1[i] + arr2[j]); m.Add((arr1[i] + arr2[j]), val+1); } else m.Add((arr1[i] + arr2[j]), 1); // generate pair from arr3[] and arr4[] for (int k = 0; k < n; k++) for (int l = 0; l < n; l++) { // calculate the sum of elements in // the pair so generated int p_sum = arr3[k] + arr4[l]; // if 'x-p_sum' is present in 'um' then // add frequency of 'x-p_sum' to 'count' if (m.ContainsKey(x - p_sum)) count += m[x - p_sum]; } // required count of quadruples return count;} // Driver codepublic static void Main(String[] args){ // four sorted arrays each of size 'n' int []arr1 = { 1, 4, 5, 6 }; int []arr2 = { 2, 3, 7, 8 }; int []arr3 = { 1, 4, 6, 10 }; int []arr4 = { 2, 4, 7, 8 }; int n = arr1.Length; int x = 30; Console.WriteLine("Count = " + countQuadruples(arr1, arr2, arr3, arr4, n, x));}} // This code has been contributed by 29AjayKumar <script>// Javascript implementation to count quadruples from// four sorted arrays whose sum is equal to a// given value x // function to count all quadruples from four sorted// arrays whose sum is equal to a given value xfunction countQuadruples(arr1,arr2,arr3,arr4,n,X){ let count = 0; // unordered_map 'um' implemented as hash table // for <sum, frequency> tuples let m = new Map(); // count frequency of each sum obtained from the // pairs of arr1[] and arr2[] and store them in 'um' for (let i = 0; i < n; i++) for (let j = 0; j < n; j++) if(m.has(arr1[i] + arr2[j])) m.set((arr1[i] + arr2[j]), m.get((arr1[i] + arr2[j]))+1); else m.set((arr1[i] + arr2[j]), 1); // generate pair from arr3[] and arr4[] for (let k = 0; k < n; k++) for (let l = 0; l < n; l++) { // calculate the sum of elements in // the pair so generated let p_sum = arr3[k] + arr4[l]; // if 'x-p_sum' is present in 'um' then // add frequency of 'x-p_sum' to 'count' if (m.has(x - p_sum)) count += m.get(x - p_sum); } // required count of quadruples return count;} // Driver program to test above// four sorted arrays each of size 'n'let arr1 = [ 1, 4, 5, 6 ];let arr2 = [ 2, 3, 7, 8 ];let arr3 = [ 1, 4, 6, 10 ];let arr4 = [ 2, 4, 7, 8 ]; let n = arr1.length;let x = 30;document.write("Count = " + countQuadruples(arr1, arr2, arr3, arr4, n, x)); // This code is contributed by unknown2108</script> Output: Count = 4 Time Complexity: O(n2) Auxiliary Space: O(n2) This article is contributed by Ayush Jauhari. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks. count pairs in the 3rd and 4th sorted array with sum equal to (x – p_sum)Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. shrikanth13 princiraj1992 ukasp Akanksha_Rai Rajput-Ji 29AjayKumar Stream_Cipher avanitrachhadiya2155 rag2127 decode2207 ab2127 unknown2108 Binary Search Hash Searching Sorting Searching Hash Sorting Binary Search Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Quadratic Probing in Hashing Rearrange an array such that arr[i] = i Hashing in Java Non-Repeating Element What are Hash Functions and How to choose a good Hash Function? Binary Search Maximum and minimum of an array using minimum number of comparisons Linear Search Find the Missing Number K'th Smallest/Largest Element in Unsorted Array | Set 1
[ { "code": null, "e": 25156, "s": 25128, "text": "\n28 Jun, 2021" }, { "code": null, "e": 25411, "s": 25156, "text": "Given four sorted arrays each of size n of distinct elements. Given a value x. The problem is to count all quadruples(group of four numbers) from all the four arrays whose sum is equal to x.Note: The quadruple has an element from each of the four arrays." }, { "code": null, "e": 25422, "s": 25411, "text": "Examples: " }, { "code": null, "e": 25725, "s": 25422, "text": "Input : arr1 = {1, 4, 5, 6},\n arr2 = {2, 3, 7, 8},\n arr3 = {1, 4, 6, 10},\n arr4 = {2, 4, 7, 8} \n n = 4, x = 30\nOutput : 4\nThe quadruples are:\n(4, 8, 10, 8), (5, 7, 10, 8),\n(5, 8, 10, 7), (6, 7, 10, 7)\n\nInput : For the same above given fours arrays\n x = 25\nOutput : 14" }, { "code": null, "e": 25753, "s": 25725, "text": "Method 1 (Naive Approach): " }, { "code": null, "e": 25866, "s": 25753, "text": "Using four nested loops generate all quadruples and check whether elements in the quadruple sum up to x or not. " }, { "code": null, "e": 25870, "s": 25866, "text": "C++" }, { "code": null, "e": 25875, "s": 25870, "text": "Java" }, { "code": null, "e": 25883, "s": 25875, "text": "Python3" }, { "code": null, "e": 25886, "s": 25883, "text": "C#" }, { "code": null, "e": 25890, "s": 25886, "text": "PHP" }, { "code": null, "e": 25901, "s": 25890, "text": "Javascript" }, { "code": " // C++ implementation to count quadruples from four sorted arrays// whose sum is equal to a given value x#include <bits/stdc++.h> using namespace std; // function to count all quadruples from// four sorted arrays whose sum is equal// to a given value xint countQuadruples(int arr1[], int arr2[], int arr3[], int arr4[], int n, int x){ int count = 0; // generate all possible quadruples from // the four sorted arrays for (int i = 0; i < n; i++) for (int j = 0; j < n; j++) for (int k = 0; k < n; k++) for (int l = 0; l < n; l++) // check whether elements of // quadruple sum up to x or not if ((arr1[i] + arr2[j] + arr3[k] + arr4[l]) == x) count++; // required count of quadruples return count;} // Driver program to test aboveint main(){ // four sorted arrays each of size 'n' int arr1[] = { 1, 4, 5, 6 }; int arr2[] = { 2, 3, 7, 8 }; int arr3[] = { 1, 4, 6, 10 }; int arr4[] = { 2, 4, 7, 8 }; int n = sizeof(arr1) / sizeof(arr1[0]); int x = 30; cout << \"Count = \" << countQuadruples(arr1, arr2, arr3, arr4, n, x); return 0;}", "e": 27146, "s": 25901, "text": null }, { "code": "// Java implementation to count quadruples from four sorted arrays// whose sum is equal to a given value xclass GFG {// function to count all quadruples from// four sorted arrays whose sum is equal// to a given value x static int countQuadruples(int arr1[], int arr2[], int arr3[], int arr4[], int n, int x) { int count = 0; // generate all possible quadruples from // the four sorted arrays for (int i = 0; i < n; i++) { for (int j = 0; j < n; j++) { for (int k = 0; k < n; k++) { for (int l = 0; l < n; l++) // check whether elements of // quadruple sum up to x or not { if ((arr1[i] + arr2[j] + arr3[k] + arr4[l]) == x) { count++; } } } } } // required count of quadruples return count; } // Driver program to test above public static void main(String[] args) { // four sorted arrays each of size 'n' int arr1[] = {1, 4, 5, 6}; int arr2[] = {2, 3, 7, 8}; int arr3[] = {1, 4, 6, 10}; int arr4[] = {2, 4, 7, 8}; int n = arr1.length; int x = 30; System.out.println(\"Count = \" + countQuadruples(arr1, arr2, arr3, arr4, n, x)); }}//This code is contributed by PrinciRaj1992", "e": 28591, "s": 27146, "text": null }, { "code": "# A Python3 implementation to count# quadruples from four sorted arrays# whose sum is equal to a given value x # function to count all quadruples# from four sorted arrays whose sum# is equal to a given value xdef countQuuadruples(arr1, arr2, arr3, arr4, n, x): count = 0 # generate all possible # quadruples from the four # sorted arrays for i in range(n): for j in range(n): for k in range(n): for l in range(n): # check whether elements of # quadruple sum up to x or not if (arr1[i] + arr2[j] + arr3[k] + arr4[l] == x): count += 1 # required count of quadruples return count # Driver Codearr1 = [1, 4, 5, 6]arr2 = [2, 3, 7, 8]arr3 = [1, 4, 6, 10]arr4 = [2, 4, 7, 8 ]n = len(arr1)x = 30print(\"Count = \", countQuuadruples(arr1, arr2, arr3, arr4, n, x)) # This code is contributed# by Shrikant13", "e": 29624, "s": 28591, "text": null }, { "code": "// C# implementation to count quadruples from four sorted arrays// whose sum is equal to a given value xusing System;public class GFG {// function to count all quadruples from// four sorted arrays whose sum is equal// to a given value x static int countQuadruples(int []arr1, int []arr2, int []arr3, int []arr4, int n, int x) { int count = 0; // generate all possible quadruples from // the four sorted arrays for (int i = 0; i < n; i++) { for (int j = 0; j < n; j++) { for (int k = 0; k < n; k++) { for (int l = 0; l < n; l++) // check whether elements of // quadruple sum up to x or not { if ((arr1[i] + arr2[j] + arr3[k] + arr4[l]) == x) { count++; } } } } } // required count of quadruples return count; } // Driver program to test above public static void Main() { // four sorted arrays each of size 'n' int []arr1 = {1, 4, 5, 6}; int []arr2 = {2, 3, 7, 8}; int []arr3 = {1, 4, 6, 10}; int []arr4 = {2, 4, 7, 8}; int n = arr1.Length; int x = 30; Console.Write(\"Count = \" + countQuadruples(arr1, arr2, arr3, arr4, n, x)); }} // This code is contributed by PrinciRaj19992", "e": 31072, "s": 29624, "text": null }, { "code": "<?php// PHP implementation to count quadruples// from four sorted arrays whose sum is// equal to a given value x // function to count all quadruples from// four sorted arrays whose sum is equal// to a given value xfunction countQuadruples(&$arr1, &$arr2, &$arr3, &$arr4, $n, $x){ $count = 0; // generate all possible quadruples // from the four sorted arrays for ($i = 0; $i < $n; $i++) for ($j = 0; $j < $n; $j++) for ($k = 0; $k < $n; $k++) for ($l = 0; $l < $n; $l++) // check whether elements of // quadruple sum up to x or not if (($arr1[$i] + $arr2[$j] + $arr3[$k] + $arr4[$l]) == $x) $count++; // required count of quadruples return $count;} // Driver Code // four sorted arrays each of size 'n'$arr1 = array( 1, 4, 5, 6 );$arr2 = array( 2, 3, 7, 8 );$arr3 = array( 1, 4, 6, 10 );$arr4 = array( 2, 4, 7, 8 ); $n = sizeof($arr1);$x = 30;echo \"Count = \" . countQuadruples($arr1, $arr2, $arr3, $arr4, $n, $x); // This code is contributed by ita_c?>", "e": 32286, "s": 31072, "text": null }, { "code": "<script>// Javascript implementation to count quadruples from four sorted arrays// whose sum is equal to a given value x // function to count all quadruples from// four sorted arrays whose sum is equal// to a given value x function countQuadruples(arr1,arr2,arr3,arr4,n,x) { let count = 0; // generate all possible quadruples from // the four sorted arrays for (let i = 0; i < n; i++) { for (let j = 0; j < n; j++) { for (let k = 0; k < n; k++) { for (let l = 0; l < n; l++) // check whether elements of // quadruple sum up to x or not { if ((arr1[i] + arr2[j] + arr3[k] + arr4[l]) == x) { count++; } } } } } // required count of quadruples return count; } // Driver program to test above let arr1=[1, 4, 5, 6]; let arr2=[2, 3, 7, 8]; let arr3=[1, 4, 6, 10]; let arr4=[2, 4, 7, 8]; let n = arr1.length; let x = 30; document.write(\"Count = \" + countQuadruples(arr1, arr2, arr3, arr4, n, x)); //This code is contributed by rag2127 </script>", "e": 33575, "s": 32286, "text": null }, { "code": null, "e": 33585, "s": 33575, "text": "Output: " }, { "code": null, "e": 33595, "s": 33585, "text": "Count = 4" }, { "code": null, "e": 33641, "s": 33595, "text": "Time Complexity: O(n4) Auxiliary Space: O(1) " }, { "code": null, "e": 33992, "s": 33641, "text": "Method 2 (Binary Search): Generate all triplets from the 1st three arrays. For each triplet so generated, find the sum of elements in the triplet. Let it be T. Now, search the value (x – T) in the 4th array. If the value found in the 4th array, then increment count. This process is repeated for all the triplets generated from the 1st three arrays. " }, { "code": null, "e": 33996, "s": 33992, "text": "C++" }, { "code": null, "e": 34001, "s": 33996, "text": "Java" }, { "code": null, "e": 34004, "s": 34001, "text": "C#" }, { "code": null, "e": 34008, "s": 34004, "text": "PHP" }, { "code": null, "e": 34019, "s": 34008, "text": "Javascript" }, { "code": "// C++ implementation to count quadruples from// four sorted arrays whose sum is equal to a// given value x#include <bits/stdc++.h> using namespace std; // find the 'value' in the given array 'arr[]'// binary search technique is appliedbool isPresent(int arr[], int low, int high, int value){ while (low <= high) { int mid = (low + high) / 2; // 'value' found if (arr[mid] == value) return true; else if (arr[mid] > value) high = mid - 1; else low = mid + 1; } // 'value' not found return false;} // function to count all quadruples from four// sorted arrays whose sum is equal to a given value xint countQuadruples(int arr1[], int arr2[], int arr3[], int arr4[], int n, int x){ int count = 0; // generate all triplets from the 1st three arrays for (int i = 0; i < n; i++) for (int j = 0; j < n; j++) for (int k = 0; k < n; k++) { // calculate the sum of elements in // the triplet so generated int T = arr1[i] + arr2[j] + arr3[k]; // check if 'x-T' is present in 4th // array or not if (isPresent(arr4, 0, n, x - T)) // increment count count++; } // required count of quadruples return count;} // Driver program to test aboveint main(){ // four sorted arrays each of size 'n' int arr1[] = { 1, 4, 5, 6 }; int arr2[] = { 2, 3, 7, 8 }; int arr3[] = { 1, 4, 6, 10 }; int arr4[] = { 2, 4, 7, 8 }; int n = sizeof(arr1) / sizeof(arr1[0]); int x = 30; cout << \"Count = \" << countQuadruples(arr1, arr2, arr3, arr4, n, x); return 0;}", "e": 35759, "s": 34019, "text": null }, { "code": "// Java implementation to count quadruples from// four sorted arrays whose sum is equal to a// given value xclass GFG{ // find the 'value' in the given array 'arr[]' // binary search technique is applied static boolean isPresent(int[] arr, int low, int high, int value) { while (low <= high) { int mid = (low + high) / 2; // 'value' found if (arr[mid] == value) return true; else if (arr[mid] > value) high = mid - 1; else low = mid + 1; } // 'value' not found return false; } // function to count all quadruples from four // sorted arrays whose sum is equal to a given value x static int countQuadruples(int[] arr1, int[] arr2, int[] arr3, int[] arr4, int n, int x) { int count = 0; // generate all triplets from the 1st three arrays for (int i = 0; i < n; i++) for (int j = 0; j < n; j++) for (int k = 0; k < n; k++) { // calculate the sum of elements in // the triplet so generated int T = arr1[i] + arr2[j] + arr3[k]; // check if 'x-T' is present in 4th // array or not if (isPresent(arr4, 0, n-1, x - T)) // increment count count++; } // required count of quadruples return count; } // Driver code public static void main(String[] args) { // four sorted arrays each of size 'n' int[] arr1 = { 1, 4, 5, 6 }; int[] arr2 = { 2, 3, 7, 8 }; int[] arr3 = { 1, 4, 6, 10 }; int[] arr4 = { 2, 4, 7, 8 }; int n = 4; int x = 30; System.out.println( \"Count = \" + countQuadruples(arr1, arr2, arr3, arr4, n, x)); }} // This code is contributed by Rajput-Ji", "e": 37803, "s": 35759, "text": null }, { "code": "// C# implementation to count quadruples from// four sorted arrays whose sum is equal to a// given value xusing System; class GFG{ // find the 'value' in the given array 'arr[]' // binary search technique is applied static bool isPresent(int[] arr, int low, int high, int value) { while (low <= high) { int mid = (low + high) / 2; // 'value' found if (arr[mid] == value) return true; else if (arr[mid] > value) high = mid - 1; else low = mid + 1; } // 'value' not found return false; } // function to count all quadruples from four // sorted arrays whose sum is equal to a given value x static int countQuadruples(int[] arr1, int[] arr2, int[] arr3, int[] arr4, int n, int x) { int count = 0; // generate all triplets from the 1st three arrays for (int i = 0; i < n; i++) for (int j = 0; j < n; j++) for (int k = 0; k < n; k++) { // calculate the sum of elements in // the triplet so generated int T = arr1[i] + arr2[j] + arr3[k]; // check if 'x-T' is present in 4th // array or not if (isPresent(arr4, 0, n-1, x - T)) // increment count count++; } // required count of quadruples return count; } // Driver code public static void Main(String[] args) { // four sorted arrays each of size 'n' int[] arr1 = { 1, 4, 5, 6 }; int[] arr2 = { 2, 3, 7, 8 }; int[] arr3 = { 1, 4, 6, 10 }; int[] arr4 = { 2, 4, 7, 8 }; int n = 4; int x = 30; Console.WriteLine( \"Count = \" + countQuadruples(arr1, arr2, arr3, arr4, n, x)); }} // This code has been contributed by 29AjayKumar", "e": 39857, "s": 37803, "text": null }, { "code": "<?php// PHP implementation to count quadruples from// four sorted arrays whose sum is equal to a// given value x // find the 'value' in the given array 'arr[]'// binary search technique is appliedfunction isPresent($arr, $low, $high, $value){ while ($low <= $high) { $mid = ($low + $high) / 2; // 'value' found if ($arr[$mid] == $value) return true; else if ($arr[$mid] > $value) $high = $mid - 1; else $low = $mid + 1; } // 'value' not found return false;} // function to count all quadruples from// four sorted arrays whose sum is equal// to a given value xfunction countQuadruples($arr1, $arr2, $arr3, $arr4, $n, $x){ $count = 0; // generate all triplets from the // 1st three arrays for ($i = 0; $i < $n; $i++) for ($j = 0; $j < $n; $j++) for ($k = 0; $k < $n; $k++) { // calculate the sum of elements in // the triplet so generated $T = $arr1[$i] + $arr2[$j] + $arr3[$k]; // check if 'x-T' is present in 4th // array or not if (isPresent($arr4, 0, $n, $x - $T)) // increment count $count++; } // required count of quadruples return $count;} // Driver Code // four sorted arrays each of size 'n'$arr1 = array(1, 4, 5, 6);$arr2 = array(2, 3, 7, 8);$arr3 = array(1, 4, 6, 10);$arr4 = array(2, 4, 7, 8); $n = sizeof($arr1);$x = 30;echo \"Count = \" . countQuadruples($arr1, $arr2, $arr3, $arr4, $n, $x); // This code is contributed// by Akanksha Rai?>", "e": 41541, "s": 39857, "text": null }, { "code": "<script> // Javascript implementation to count quadruples from // four sorted arrays whose sum is equal to a // given value x // find the 'value' in the given array 'arr[]' // binary search technique is applied function isPresent(arr, low, high, value) { while (low <= high) { let mid = parseInt((low + high) / 2, 10); // 'value' found if (arr[mid] == value) return true; else if (arr[mid] > value) high = mid - 1; else low = mid + 1; } // 'value' not found return false; } // function to count all quadruples from four // sorted arrays whose sum is equal to a given value x function countQuadruples(arr1, arr2, arr3, arr4, n, x) { let count = 0; // generate all triplets from the 1st three arrays for (let i = 0; i < n; i++) for (let j = 0; j < n; j++) for (let k = 0; k < n; k++) { // calculate the sum of elements in // the triplet so generated let T = arr1[i] + arr2[j] + arr3[k]; // check if 'x-T' is present in 4th // array or not if (isPresent(arr4, 0, n-1, x - T)) // increment count count++; } // required count of quadruples return count; } // four sorted arrays each of size 'n' let arr1 = [ 1, 4, 5, 6 ]; let arr2 = [ 2, 3, 7, 8 ]; let arr3 = [ 1, 4, 6, 10 ]; let arr4 = [ 2, 4, 7, 8 ]; let n = 4; let x = 30; document.write( \"Count = \" + countQuadruples(arr1, arr2, arr3, arr4, n, x)); </script>", "e": 43333, "s": 41541, "text": null }, { "code": null, "e": 43343, "s": 43333, "text": "Output: " }, { "code": null, "e": 43353, "s": 43343, "text": "Count = 4" }, { "code": null, "e": 43403, "s": 43353, "text": "Time Complexity: O(n3logn) Auxiliary Space: O(1) " }, { "code": null, "e": 43713, "s": 43403, "text": "Method 3 (Use of two pointers): Generate all pairs from the 1st two arrays. For each pair so generated, find the sum of elements in the pair. Let it be p_sum. For each p_sum, count pairs from the 3rd and 4th sorted array with sum equal to (x – p_sum). Accumulate these count in the total_count of quadruples. " }, { "code": null, "e": 43717, "s": 43713, "text": "C++" }, { "code": null, "e": 43722, "s": 43717, "text": "Java" }, { "code": null, "e": 43730, "s": 43722, "text": "Python3" }, { "code": null, "e": 43733, "s": 43730, "text": "C#" }, { "code": null, "e": 43744, "s": 43733, "text": "Javascript" }, { "code": "// C++ implementation to count quadruples from// four sorted arrays whose sum is equal to a// given value x#include <bits/stdc++.h> using namespace std; // count pairs from the two sorted array whose sum// is equal to the given 'value'int countPairs(int arr1[], int arr2[], int n, int value){ int count = 0; int l = 0, r = n - 1; // traverse 'arr1[]' from left to right // traverse 'arr2[]' from right to left while (l < n & amp; &r >= 0) { int sum = arr1[l] + arr2[r]; // if the 'sum' is equal to 'value', then // increment 'l', decrement 'r' and // increment 'count' if (sum == value) { l++, r--; count++; } // if the 'sum' is greater than 'value', then // decrement r else if (sum > value) r--; // else increment l else l++; } // required count of pairs return count;} // function to count all quadruples from four sorted arrays// whose sum is equal to a given value xint countQuadruples(int arr1[], int arr2[], int arr3[], int arr4[], int n, int x){ int count = 0; // generate all pairs from arr1[] and arr2[] for (int i = 0; i < n; i++) for (int j = 0; j < n; j++) { // calculate the sum of elements in // the pair so generated int p_sum = arr1[i] + arr2[j]; // count pairs in the 3rd and 4th array // having value 'x-p_sum' and then // accumulate it to 'count' count += countPairs(arr3, arr4, n, x - p_sum); } // required count of quadruples return count;} // Driver program to test aboveint main(){ // four sorted arrays each of size 'n' int arr1[] = { 1, 4, 5, 6 }; int arr2[] = { 2, 3, 7, 8 }; int arr3[] = { 1, 4, 6, 10 }; int arr4[] = { 2, 4, 7, 8 }; int n = sizeof(arr1) / sizeof(arr1[0]); int x = 30; cout << \"Count = \" << countQuadruples(arr1, arr2, arr3, arr4, n, x); return 0;}", "e": 45779, "s": 43744, "text": null }, { "code": "// Java implementation to count quadruples from// four sorted arrays whose sum is equal to a// given value x class GFG { // count pairs from the two sorted array whose sum// is equal to the given 'value'static int countPairs(int arr1[], int arr2[], int n, int value){ int count = 0; int l = 0, r = n - 1; // traverse 'arr1[]' from left to right // traverse 'arr2[]' from right to left while (l < n & r >= 0) { int sum = arr1[l] + arr2[r]; // if the 'sum' is equal to 'value', then // increment 'l', decrement 'r' and // increment 'count' if (sum == value) { l++; r--; count++; } // if the 'sum' is greater than 'value', then // decrement r else if (sum > value) r--; // else increment l else l++; } // required count of pairs return count;} // function to count all quadruples from four sorted arrays// whose sum is equal to a given value xstatic int countQuadruples(int arr1[], int arr2[], int arr3[], int arr4[], int n, int x){ int count = 0; // generate all pairs from arr1[] and arr2[] for (int i = 0; i < n; i++) for (int j = 0; j < n; j++) { // calculate the sum of elements in // the pair so generated int p_sum = arr1[i] + arr2[j]; // count pairs in the 3rd and 4th array // having value 'x-p_sum' and then // accumulate it to 'count' count += countPairs(arr3, arr4, n, x - p_sum); } // required count of quadruples return count;}// Driver program to test above static public void main(String[] args) { // four sorted arrays each of size 'n' int arr1[] = {1, 4, 5, 6}; int arr2[] = {2, 3, 7, 8}; int arr3[] = {1, 4, 6, 10}; int arr4[] = {2, 4, 7, 8}; int n = arr1.length; int x = 30; System.out.println(\"Count = \" + countQuadruples(arr1, arr2, arr3, arr4, n, x)); }} // This code is contributed by PrinciRaj19992", "e": 47865, "s": 45779, "text": null }, { "code": "# Python3 implementation to# count quadruples from four# sorted arrays whose sum is# equal to a given value x# count pairs from the two# sorted array whose sum# is equal to the given 'value'def countPairs(arr1, arr2, n, value): count = 0 l = 0 r = n - 1 # traverse 'arr1[]' from # left to right # traverse 'arr2[]' from # right to left while (l < n and r >= 0): sum = arr1[l] + arr2[r] # if the 'sum' is equal # to 'value', then # increment 'l', decrement # 'r' and increment 'count' if (sum == value): l += 1 r -= 1 count += 1 # if the 'sum' is greater # than 'value', then decrement r elif (sum > value): r -= 1 # else increment l else: l += 1 # required count of pairs # print(count) return count # function to count all quadruples# from four sorted arrays whose sum# is equal to a given value xdef countQuadruples(arr1, arr2, arr3, arr4, n, x): count = 0 # generate all pairs from # arr1[] and arr2[] for i in range(0, n): for j in range(0, n): # calculate the sum of # elements in the pair # so generated p_sum = arr1[i] + arr2[j] # count pairs in the 3rd # and 4th array having # value 'x-p_sum' and then # accumulate it to 'count count += int(countPairs(arr3, arr4, n, x - p_sum)) # required count of quadruples return count # Driver codearr1 = [1, 4, 5, 6]arr2 = [2, 3, 7, 8]arr3 = [1, 4, 6, 10]arr4 = [2, 4, 7, 8]n = len(arr1)x = 30print(\"Count = \", countQuadruples(arr1, arr2, arr3, arr4, n, x)) # This code is contributed by Stream_Cipher", "e": 49952, "s": 47865, "text": null }, { "code": " // C# implementation to count quadruples from// four sorted arrays whose sum is equal to a// given value x using System;public class GFG { // count pairs from the two sorted array whose sum // is equal to the given 'value' static int countPairs(int []arr1, int []arr2, int n, int value) { int count = 0; int l = 0, r = n - 1; // traverse 'arr1[]' from left to right // traverse 'arr2[]' from right to left while (l < n & r >= 0) { int sum = arr1[l] + arr2[r]; // if the 'sum' is equal to 'value', then // increment 'l', decrement 'r' and // increment 'count' if (sum == value) { l++; r--; count++; } // if the 'sum' is greater than 'value', then // decrement r else if (sum > value) r--; // else increment l else l++; } // required count of pairs return count; } // function to count all quadruples from four sorted arrays // whose sum is equal to a given value x static int countQuadruples(int []arr1, int []arr2, int []arr3, int []arr4, int n, int x) { int count = 0; // generate all pairs from arr1[] and arr2[] for (int i = 0; i < n; i++) for (int j = 0; j < n; j++) { // calculate the sum of elements in // the pair so generated int p_sum = arr1[i] + arr2[j]; // count pairs in the 3rd and 4th array // having value 'x-p_sum' and then // accumulate it to 'count' count += countPairs(arr3, arr4, n, x - p_sum); } // required count of quadruples return count; } // Driver program to test above static public void Main() { // four sorted arrays each of size 'n' int []arr1 = {1, 4, 5, 6}; int []arr2 = {2, 3, 7, 8}; int []arr3 = {1, 4, 6, 10}; int []arr4 = {2, 4, 7, 8}; int n = arr1.Length; int x = 30; Console.Write(\"Count = \" + countQuadruples(arr1, arr2, arr3, arr4, n, x)); }} // This code is contributed by PrinciRaj19992", "e": 52232, "s": 49952, "text": null }, { "code": "<script>// Javascript implementation to count quadruples from// four sorted arrays whose sum is equal to a// given value x // count pairs from the two sorted array whose sum// is equal to the given 'value'function countPairs(arr1,arr2,n,value){ let count = 0; let l = 0, r = n - 1; // traverse 'arr1[]' from left to right // traverse 'arr2[]' from right to left while (l < n & r >= 0) { let sum = arr1[l] + arr2[r]; // if the 'sum' is equal to 'value', then // increment 'l', decrement 'r' and // increment 'count' if (sum == value) { l++; r--; count++; } // if the 'sum' is greater than 'value', then // decrement r else if (sum > value) r--; // else increment l else l++; } // required count of pairs return count;} // function to count all quadruples from four sorted arrays// whose sum is equal to a given value xfunction countQuadruples(arr1,arr2,arr3,arr4,n,x){ let count = 0; // generate all pairs from arr1[] and arr2[] for (let i = 0; i < n; i++) for (let j = 0; j < n; j++) { // calculate the sum of elements in // the pair so generated let p_sum = arr1[i] + arr2[j]; // count pairs in the 3rd and 4th array // having value 'x-p_sum' and then // accumulate it to 'count' count += countPairs(arr3, arr4, n, x - p_sum); } // required count of quadruples return count;} // Driver program to test above// four sorted arrays each of size 'n'let arr1=[1, 4, 5, 6];let arr2=[2, 3, 7, 8];let arr3=[1, 4, 6, 10];let arr4=[2, 4, 7, 8];let n = arr1.length;let x = 30;document.write(\"Count = \" + countQuadruples(arr1, arr2, arr3, arr4, n, x)); // This code is contributed by ab2127</script>", "e": 54111, "s": 52232, "text": null }, { "code": null, "e": 54121, "s": 54111, "text": "Output: " }, { "code": null, "e": 54131, "s": 54121, "text": "Count = 4" }, { "code": null, "e": 54177, "s": 54131, "text": "Time Complexity: O(n3) Auxiliary Space: O(1) " }, { "code": null, "e": 54772, "s": 54177, "text": "Method 4 Efficient Approach(Hashing): Create a hash table where (key, value) tuples are represented as (sum, frequency) tuples. Here the sum are obtained from the pairs of 1st and 2nd array and their frequency count is maintained in the hash table. Hash table is implemented using unordered_map in C++. Now, generate all pairs from the 3rd and 4th array. For each pair so generated, find the sum of elements in the pair. Let it be p_sum. For each p_sum, check whether (x – p_sum) exists in the hash table or not. If it exists, then add the frequency of (x – p_sum) to the count of quadruples. " }, { "code": null, "e": 54776, "s": 54772, "text": "C++" }, { "code": null, "e": 54781, "s": 54776, "text": "Java" }, { "code": null, "e": 54789, "s": 54781, "text": "Python3" }, { "code": null, "e": 54792, "s": 54789, "text": "C#" }, { "code": null, "e": 54803, "s": 54792, "text": "Javascript" }, { "code": "// C++ implementation to count quadruples from// four sorted arrays whose sum is equal to a// given value x#include <bits/stdc++.h> using namespace std; // function to count all quadruples from four sorted// arrays whose sum is equal to a given value xint countQuadruples(int arr1[], int arr2[], int arr3[], int arr4[], int n, int x){ int count = 0; // unordered_map 'um' implemented as hash table // for <sum, frequency> tuples unordered_map<int, int> um; // count frequency of each sum obtained from the // pairs of arr1[] and arr2[] and store them in 'um' for (int i = 0; i < n; i++) for (int j = 0; j < n; j++) um[arr1[i] + arr2[j]]++; // generate pair from arr3[] and arr4[] for (int k = 0; k < n; k++) for (int l = 0; l < n; l++) { // calculate the sum of elements in // the pair so generated int p_sum = arr3[k] + arr4[l]; // if 'x-p_sum' is present in 'um' then // add frequency of 'x-p_sum' to 'count' if (um.find(x - p_sum) != um.end()) count += um[x - p_sum]; } // required count of quadruples return count;} // Driver program to test aboveint main(){ // four sorted arrays each of size 'n' int arr1[] = { 1, 4, 5, 6 }; int arr2[] = { 2, 3, 7, 8 }; int arr3[] = { 1, 4, 6, 10 }; int arr4[] = { 2, 4, 7, 8 }; int n = sizeof(arr1) / sizeof(arr1[0]); int x = 30; cout << \"Count = \" << countQuadruples(arr1, arr2, arr3, arr4, n, x); return 0;}", "e": 56361, "s": 54803, "text": null }, { "code": "// Java implementation to count quadruples from// four sorted arrays whose sum is equal to a// given value ximport java.util.*; class GFG{ // function to count all quadruples from four sorted// arrays whose sum is equal to a given value xstatic int countQuadruples(int arr1[], int arr2[], int arr3[], int arr4[], int n, int x){ int count = 0; // unordered_map 'um' implemented as hash table // for <sum, frequency> tuples Map<Integer,Integer> m = new HashMap<>(); // count frequency of each sum obtained from the // pairs of arr1[] and arr2[] and store them in 'um' for (int i = 0; i < n; i++) for (int j = 0; j < n; j++) if(m.containsKey(arr1[i] + arr2[j])) m.put((arr1[i] + arr2[j]), m.get((arr1[i] + arr2[j]))+1); else m.put((arr1[i] + arr2[j]), 1); // generate pair from arr3[] and arr4[] for (int k = 0; k < n; k++) for (int l = 0; l < n; l++) { // calculate the sum of elements in // the pair so generated int p_sum = arr3[k] + arr4[l]; // if 'x-p_sum' is present in 'um' then // add frequency of 'x-p_sum' to 'count' if (m.containsKey(x - p_sum)) count += m.get(x - p_sum); } // required count of quadruples return count;} // Driver program to test abovepublic static void main(String[] args){ // four sorted arrays each of size 'n' int arr1[] = { 1, 4, 5, 6 }; int arr2[] = { 2, 3, 7, 8 }; int arr3[] = { 1, 4, 6, 10 }; int arr4[] = { 2, 4, 7, 8 }; int n = arr1.length; int x = 30; System.out.println(\"Count = \" + countQuadruples(arr1, arr2, arr3, arr4, n, x));}} // This code has been contributed by 29AjayKumar", "e": 58169, "s": 56361, "text": null }, { "code": "# Python implementation to count quadruples from# four sorted arrays whose sum is equal to a# given value x # function to count all quadruples from four sorted# arrays whose sum is equal to a given value xdef countQuadruples(arr1, arr2, arr3, arr4, n, x): count = 0 # unordered_map 'um' implemented as hash table # for <sum, frequency> tuples m = {} # count frequency of each sum obtained from the # pairs of arr1[] and arr2[] and store them in 'um' for i in range(n): for j in range(n): if (arr1[i] + arr2[j]) in m: m[arr1[i] + arr2[j]] += 1 else: m[arr1[i] + arr2[j]] = 1 # generate pair from arr3[] and arr4[] for k in range(n): for l in range(n): # calculate the sum of elements in # the pair so generated p_sum = arr3[k] + arr4[l] # if 'x-p_sum' is present in 'um' then # add frequency of 'x-p_sum' to 'count' if (x - p_sum) in m: count += m[x - p_sum] # required count of quadruples return count # Driver program to test above # four sorted arrays each of size 'n'arr1 = [1, 4, 5, 6]arr2 = [2, 3, 7, 8 ]arr3 = [1, 4, 6, 10]arr4 = [2, 4, 7, 8 ] n = len(arr1)x = 30print(\"Count =\", countQuadruples(arr1, arr2, arr3, arr4, n, x)) # This code is contributed by avanitrachhadiya2155", "e": 59581, "s": 58169, "text": null }, { "code": "// C# implementation to count quadruples from// four sorted arrays whose sum is equal to a// given value xusing System;using System.Collections.Generic; class GFG{ // function to count all quadruples from four sorted// arrays whose sum is equal to a given value xstatic int countQuadruples(int []arr1, int []arr2, int []arr3, int []arr4, int n, int x){ int count = 0; // unordered_map 'um' implemented as hash table // for <sum, frequency> tuples Dictionary<int,int> m = new Dictionary<int,int>(); // count frequency of each sum obtained from the // pairs of arr1[] and arr2[] and store them in 'um' for (int i = 0; i < n; i++) for (int j = 0; j < n; j++) if(m.ContainsKey(arr1[i] + arr2[j])){ var val = m[arr1[i] + arr2[j]]; m.Remove(arr1[i] + arr2[j]); m.Add((arr1[i] + arr2[j]), val+1); } else m.Add((arr1[i] + arr2[j]), 1); // generate pair from arr3[] and arr4[] for (int k = 0; k < n; k++) for (int l = 0; l < n; l++) { // calculate the sum of elements in // the pair so generated int p_sum = arr3[k] + arr4[l]; // if 'x-p_sum' is present in 'um' then // add frequency of 'x-p_sum' to 'count' if (m.ContainsKey(x - p_sum)) count += m[x - p_sum]; } // required count of quadruples return count;} // Driver codepublic static void Main(String[] args){ // four sorted arrays each of size 'n' int []arr1 = { 1, 4, 5, 6 }; int []arr2 = { 2, 3, 7, 8 }; int []arr3 = { 1, 4, 6, 10 }; int []arr4 = { 2, 4, 7, 8 }; int n = arr1.Length; int x = 30; Console.WriteLine(\"Count = \" + countQuadruples(arr1, arr2, arr3, arr4, n, x));}} // This code has been contributed by 29AjayKumar", "e": 61492, "s": 59581, "text": null }, { "code": "<script>// Javascript implementation to count quadruples from// four sorted arrays whose sum is equal to a// given value x // function to count all quadruples from four sorted// arrays whose sum is equal to a given value xfunction countQuadruples(arr1,arr2,arr3,arr4,n,X){ let count = 0; // unordered_map 'um' implemented as hash table // for <sum, frequency> tuples let m = new Map(); // count frequency of each sum obtained from the // pairs of arr1[] and arr2[] and store them in 'um' for (let i = 0; i < n; i++) for (let j = 0; j < n; j++) if(m.has(arr1[i] + arr2[j])) m.set((arr1[i] + arr2[j]), m.get((arr1[i] + arr2[j]))+1); else m.set((arr1[i] + arr2[j]), 1); // generate pair from arr3[] and arr4[] for (let k = 0; k < n; k++) for (let l = 0; l < n; l++) { // calculate the sum of elements in // the pair so generated let p_sum = arr3[k] + arr4[l]; // if 'x-p_sum' is present in 'um' then // add frequency of 'x-p_sum' to 'count' if (m.has(x - p_sum)) count += m.get(x - p_sum); } // required count of quadruples return count;} // Driver program to test above// four sorted arrays each of size 'n'let arr1 = [ 1, 4, 5, 6 ];let arr2 = [ 2, 3, 7, 8 ];let arr3 = [ 1, 4, 6, 10 ];let arr4 = [ 2, 4, 7, 8 ]; let n = arr1.length;let x = 30;document.write(\"Count = \" + countQuadruples(arr1, arr2, arr3, arr4, n, x)); // This code is contributed by unknown2108</script>", "e": 63107, "s": 61492, "text": null }, { "code": null, "e": 63117, "s": 63107, "text": "Output: " }, { "code": null, "e": 63127, "s": 63117, "text": "Count = 4" }, { "code": null, "e": 63174, "s": 63127, "text": "Time Complexity: O(n2) Auxiliary Space: O(n2) " }, { "code": null, "e": 63675, "s": 63174, "text": "This article is contributed by Ayush Jauhari. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks. count pairs in the 3rd and 4th sorted array with sum equal to (x – p_sum)Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. " }, { "code": null, "e": 63687, "s": 63675, "text": "shrikanth13" }, { "code": null, "e": 63701, "s": 63687, "text": "princiraj1992" }, { "code": null, "e": 63707, "s": 63701, "text": "ukasp" }, { "code": null, "e": 63720, "s": 63707, "text": "Akanksha_Rai" }, { "code": null, "e": 63730, "s": 63720, "text": "Rajput-Ji" }, { "code": null, "e": 63742, "s": 63730, "text": "29AjayKumar" }, { "code": null, "e": 63756, "s": 63742, "text": "Stream_Cipher" }, { "code": null, "e": 63777, "s": 63756, "text": "avanitrachhadiya2155" }, { "code": null, "e": 63785, "s": 63777, "text": "rag2127" }, { "code": null, "e": 63796, "s": 63785, "text": "decode2207" }, { "code": null, "e": 63803, "s": 63796, "text": "ab2127" }, { "code": null, "e": 63815, "s": 63803, "text": "unknown2108" }, { "code": null, "e": 63829, "s": 63815, "text": "Binary Search" }, { "code": null, "e": 63834, "s": 63829, "text": "Hash" }, { "code": null, "e": 63844, "s": 63834, "text": "Searching" }, { "code": null, "e": 63852, "s": 63844, "text": "Sorting" }, { "code": null, "e": 63862, "s": 63852, "text": "Searching" }, { "code": null, "e": 63867, "s": 63862, "text": "Hash" }, { "code": null, "e": 63875, "s": 63867, "text": "Sorting" }, { "code": null, "e": 63889, "s": 63875, "text": "Binary Search" }, { "code": null, "e": 63987, "s": 63889, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 64016, "s": 63987, "text": "Quadratic Probing in Hashing" }, { "code": null, "e": 64056, "s": 64016, "text": "Rearrange an array such that arr[i] = i" }, { "code": null, "e": 64072, "s": 64056, "text": "Hashing in Java" }, { "code": null, "e": 64094, "s": 64072, "text": "Non-Repeating Element" }, { "code": null, "e": 64158, "s": 64094, "text": "What are Hash Functions and How to choose a good Hash Function?" }, { "code": null, "e": 64172, "s": 64158, "text": "Binary Search" }, { "code": null, "e": 64240, "s": 64172, "text": "Maximum and minimum of an array using minimum number of comparisons" }, { "code": null, "e": 64254, "s": 64240, "text": "Linear Search" }, { "code": null, "e": 64278, "s": 64254, "text": "Find the Missing Number" } ]
Gesture Recognition for Beginners with CNN | by That Data Bloke | Towards Data Science
The CNN or convolutional neural networks are the most commonly used algorithms for image classification problems. An image classifier takes a photograph or video as an input and classifies it into one of the possible categories that it was trained to identify. They have applications in various fields like driver less cars, defense, healthcare etc. There are many algorithms for image classification and in this experiment, we are going to look at one of the most popular algorithms in this genre, called SqueezeNet by DeepScale. Our goal is to design an application that will use a webcam(or an external camera) as an input device and it will then identify and classify the gesture into one of the categories that we are going to define. In this article, we will see how we can use the SqueezeNet algorithm to design an application that takes different gestures and then triggers certain actions. In short, we can send some commands to our computer (without touching that keyboard or the mouse). Let’s put on our magician’s hat! 🧙‍♂️ The experiment consists of four stages listed below: Defining our classification categoriesCollect training imagesTrain the modelTest our model Defining our classification categories Collect training images Train the model Test our model In our final program, we will be performing some actions. Here is a sample list of actions that I have decided to do. Depending on your specific requirement this number of items in this list would be different. Next, we will map these actions with a category name for ease, to be used later in our program. Increase the speaker volume (category=up)Decrease the speaker volume (category=down)Mute/Unmute (category=mute)Play/Pause (category=play)Open Google Chrome (category=chrome) Increase the speaker volume (category=up) Decrease the speaker volume (category=down) Mute/Unmute (category=mute) Play/Pause (category=play) Open Google Chrome (category=chrome) Apart from these five categories, we should also have another category (category=nothing) which will be used in our final program when the user shows a hand gesture that our model does not recognize or when there is no input gesture from the user. Now that we have decided on our six categories, let us see how my gestures look like. I have created a collage of all the gestures and their respective category name (in red) below. The next set is to prepare our training images for each of these categories. To gather our training data set (images), we will use our webcam. To make things easy, I have made sure to use images with plain uncluttered background. The following python program will use the OpenCV library to perform this action and store these images into a folder by the name — “training_images”. The program takes two inputs parameters: python get_training_images.py 50 up a) Number of images to capture (eg:- 50) b) Label (or category) name (eg:- up, down, play, chrome etc) The program stops after capturing that many images. The second parameter instructs the name of the category that these images belong to. The program creates a sub-folder by the category name inside our ‘training_images’ folder and stores all the images over there. Once you run the program, the webcam feed will turn On. Place your hand within the boundary of the white box and press ‘s’ key to start taking picture of your hand. Try moving your hand around a bit during this process to add some variations in the training data set. I have started here by running the program twice for each category, 50 images with right hand and next 50 images with my left hand. Once the program ends, you should be able to see the images inside the sub-folder by the name of your gesture. Once this process is complete, you will end up with 100 images in each of the folders. You might want to choose a number that suits you, the more the better. We are going to be using SqueezeNet for this demo. SqueezeNet is a popular pretrained model for image classification problems and it is extremely lightweight with an impressive level of accuracy. We will use Keras library for the training process. Keras is a simple and powerful python library that is widely used in deep learning. It has made it really easy to train neural network models. Let us look at some of the parameters used for our training. Sequential: We will use a sequential model, meaning that the layers are arranged in a linear stack (sequence). The layers in a model are added as arguments to this constructor. Dropout Rate: Neural networks trained on smaller datasets often tend to over-fit and are therefore less likely to be accurate on new data. Theoretically, the best way to train a model could be to try out as many different combination of different parameter values and then take an average of those individual results to come up with a generalized result. But this would require a lot of time and computational resources in training the model multiple times with multiple combinations of these parameters. To get around this, the dropout rate was introduced. Here, some units/nodes in a layer(from input layers or hidden layers, but not from the output layer) are ‘dropped’ which makes that node’s incoming and outgoing connections disappear. Simply put, when this is done multiple times during training, different number of node(s) are dropped from the layer making the layer appear differently in terms of number of nodes and its connections to former layer (roughly simulating multiple models with different layer configurations). A good value for Dropout rate for a layer is between 0.5 – 0.8. In my case, I have found 0.5 to be giving me the best result after trying out few different values. Do note that dropout is used to avoid over fitting. If the model’s accuracy is low, this parameter could be avoided. Nodes: Number of neurons/nodes in our output layer is equal to the number of classes we are trying to predict. Input Shape: The input shape that SqueezeNet requires is at least 224 X 224 (with 3 channels for RGB). In this program, we have used 225 X 225. Choosing an optimizer & loss: Here I have chosen the Adam optimizer. And The loss function is chosen based on the type of problem. For eg:- for a binary classification problem, [loss=’binary_crossentropy’] is better suited and for a multi-class classification problem, [loss=’categorical_crossentropy’] is chosen. Whereas for a regression problem, [loss=’mse’] could be chosen. Since ours is a multi-class classification problem, we will use categorical_crossentropy. Number of Epochs: The number of epochs is the number of times the entire dataset is passed through the neural network during training. There is no ideal number for this and it depends on the data. In this case, I started with 10, I have used 15. Higher number indicates longer training time. Activation Function: We are using the ReLU activation function, which is the most common activation function that is used in neural networks due to its computational simplicity (among other advantages). This function returns a zero for negative inputs and the value itself for positive inputs. For most of the modern neural networks, ReLU is the default activation function. Other activation functions that are also used are Sigmoid, Tanh etc. Pooling: In CNN, it is a common practice to add a pooling layer after the convolution & activation layer. The input image is down sampled or converted to a low resolution version in order to keep only the significant details and remove the finer less important details. Softmax: The softmax layer is used in multi-class classification right before the output layer. It gives the likelihood of the input image belonging to a particular category. import numpy as npfrom keras_squeezenet import SqueezeNetfrom keras.optimizers import Adamfrom keras.utils import np_utilsfrom keras.layers import Activation, Dropout, Convolution2D, GlobalAveragePooling2Dfrom keras.models import Sequentialimport tensorflow as tfGESTURE_CATEGORIES=6base_model = Sequential()base_model.add(SqueezeNet(input_shape=(225, 225, 3), include_top=False))base_model.add(Dropout(0.5))base_model.add(Convolution2D(GESTURE_CATEGORIES, (1, 1), padding='valid'))base_model.add(Activation('relu'))base_model.add(GlobalAveragePooling2D())base_model.add(Activation('softmax'))base_model.compile( optimizer=Adam(lr=0.0001), loss='categorical_crossentropy', metrics=['accuracy']) After training we will store the trained model parameters into a file(gesture-model05_20.h5) which we will be using later during model testing. The entire code is present in the github repository. model.save("gesture-model05_20.h5") To test the model, I am using some images of hand gestures captured again with my webcam. The program loads the model file “gesture-model05_20.h5” and it takes the input image as a parameter and predicts the class it belongs to. Before passing the image, we need to ensure that we are using the same dimensions that we used during the training phase. from keras.models import load_modelimport cv2import numpy as npimg = cv2.imread(<input image file path>)img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)img = cv2.resize(img, (225, 225))model = load_model("gesture-base-rmsprop-model05_20.h5")prediction = model.predict(np.array([img])) For the following test images the model predicted correctly. However, if the image contains too many other items in the background it isn’t always accurate. In closing, although this model may not work perfectly every single time and there is a lot we can do to improve its performance, it gives us a starting point and build on these fundamentals from here. Thank your for taking out time to read this article and I hope it helps you to create your first CNN project. I look forward to see your version of this project. Do share with me what you come up with :) In my next article, we will take a look at how to take actions based on the identified class using Python. This article uses Python OpenCV. If you are unfamiliar with OpenCV library in Python, here’s a link to my introductory article on this subject. towardsdatascience.com medium.com References & Further Reading: [1] SqueezeNet, https://codelabs.developers.google.com/codelabs/keras-flowers-squeezenet/ [2] Pooling, 2019, https://machinelearningmastery.com/pooling-layers-for-convolutional-neural-networks/ [3] SqueezeNet Paper, 2016, https://arxiv.org/abs/1602.07360 [4] Alternative OpenCV approach, https://www.youtube.com/watch?v=-_9WFzgI7ak [5] Dropout: A Simple Way to Prevent Neural Networks from Overfitting, 2014 , http://jmlr.org/papers/v15/srivastava14a.html
[ { "code": null, "e": 703, "s": 172, "text": "The CNN or convolutional neural networks are the most commonly used algorithms for image classification problems. An image classifier takes a photograph or video as an input and classifies it into one of the possible categories that it was trained to identify. They have applications in various fields like driver less cars, defense, healthcare etc. There are many algorithms for image classification and in this experiment, we are going to look at one of the most popular algorithms in this genre, called SqueezeNet by DeepScale." }, { "code": null, "e": 1208, "s": 703, "text": "Our goal is to design an application that will use a webcam(or an external camera) as an input device and it will then identify and classify the gesture into one of the categories that we are going to define. In this article, we will see how we can use the SqueezeNet algorithm to design an application that takes different gestures and then triggers certain actions. In short, we can send some commands to our computer (without touching that keyboard or the mouse). Let’s put on our magician’s hat! 🧙‍♂️" }, { "code": null, "e": 1261, "s": 1208, "text": "The experiment consists of four stages listed below:" }, { "code": null, "e": 1352, "s": 1261, "text": "Defining our classification categoriesCollect training imagesTrain the modelTest our model" }, { "code": null, "e": 1391, "s": 1352, "text": "Defining our classification categories" }, { "code": null, "e": 1415, "s": 1391, "text": "Collect training images" }, { "code": null, "e": 1431, "s": 1415, "text": "Train the model" }, { "code": null, "e": 1446, "s": 1431, "text": "Test our model" }, { "code": null, "e": 1753, "s": 1446, "text": "In our final program, we will be performing some actions. Here is a sample list of actions that I have decided to do. Depending on your specific requirement this number of items in this list would be different. Next, we will map these actions with a category name for ease, to be used later in our program." }, { "code": null, "e": 1927, "s": 1753, "text": "Increase the speaker volume (category=up)Decrease the speaker volume (category=down)Mute/Unmute (category=mute)Play/Pause (category=play)Open Google Chrome (category=chrome)" }, { "code": null, "e": 1969, "s": 1927, "text": "Increase the speaker volume (category=up)" }, { "code": null, "e": 2013, "s": 1969, "text": "Decrease the speaker volume (category=down)" }, { "code": null, "e": 2041, "s": 2013, "text": "Mute/Unmute (category=mute)" }, { "code": null, "e": 2068, "s": 2041, "text": "Play/Pause (category=play)" }, { "code": null, "e": 2105, "s": 2068, "text": "Open Google Chrome (category=chrome)" }, { "code": null, "e": 2353, "s": 2105, "text": "Apart from these five categories, we should also have another category (category=nothing) which will be used in our final program when the user shows a hand gesture that our model does not recognize or when there is no input gesture from the user." }, { "code": null, "e": 2439, "s": 2353, "text": "Now that we have decided on our six categories, let us see how my gestures look like." }, { "code": null, "e": 2535, "s": 2439, "text": "I have created a collage of all the gestures and their respective category name (in red) below." }, { "code": null, "e": 2956, "s": 2535, "text": "The next set is to prepare our training images for each of these categories. To gather our training data set (images), we will use our webcam. To make things easy, I have made sure to use images with plain uncluttered background. The following python program will use the OpenCV library to perform this action and store these images into a folder by the name — “training_images”. The program takes two inputs parameters:" }, { "code": null, "e": 2992, "s": 2956, "text": "python get_training_images.py 50 up" }, { "code": null, "e": 3033, "s": 2992, "text": "a) Number of images to capture (eg:- 50)" }, { "code": null, "e": 3095, "s": 3033, "text": "b) Label (or category) name (eg:- up, down, play, chrome etc)" }, { "code": null, "e": 3360, "s": 3095, "text": "The program stops after capturing that many images. The second parameter instructs the name of the category that these images belong to. The program creates a sub-folder by the category name inside our ‘training_images’ folder and stores all the images over there." }, { "code": null, "e": 4029, "s": 3360, "text": "Once you run the program, the webcam feed will turn On. Place your hand within the boundary of the white box and press ‘s’ key to start taking picture of your hand. Try moving your hand around a bit during this process to add some variations in the training data set. I have started here by running the program twice for each category, 50 images with right hand and next 50 images with my left hand. Once the program ends, you should be able to see the images inside the sub-folder by the name of your gesture. Once this process is complete, you will end up with 100 images in each of the folders. You might want to choose a number that suits you, the more the better." }, { "code": null, "e": 4420, "s": 4029, "text": "We are going to be using SqueezeNet for this demo. SqueezeNet is a popular pretrained model for image classification problems and it is extremely lightweight with an impressive level of accuracy. We will use Keras library for the training process. Keras is a simple and powerful python library that is widely used in deep learning. It has made it really easy to train neural network models." }, { "code": null, "e": 4481, "s": 4420, "text": "Let us look at some of the parameters used for our training." }, { "code": null, "e": 4658, "s": 4481, "text": "Sequential: We will use a sequential model, meaning that the layers are arranged in a linear stack (sequence). The layers in a model are added as arguments to this constructor." }, { "code": null, "e": 5972, "s": 4658, "text": "Dropout Rate: Neural networks trained on smaller datasets often tend to over-fit and are therefore less likely to be accurate on new data. Theoretically, the best way to train a model could be to try out as many different combination of different parameter values and then take an average of those individual results to come up with a generalized result. But this would require a lot of time and computational resources in training the model multiple times with multiple combinations of these parameters. To get around this, the dropout rate was introduced. Here, some units/nodes in a layer(from input layers or hidden layers, but not from the output layer) are ‘dropped’ which makes that node’s incoming and outgoing connections disappear. Simply put, when this is done multiple times during training, different number of node(s) are dropped from the layer making the layer appear differently in terms of number of nodes and its connections to former layer (roughly simulating multiple models with different layer configurations). A good value for Dropout rate for a layer is between 0.5 – 0.8. In my case, I have found 0.5 to be giving me the best result after trying out few different values. Do note that dropout is used to avoid over fitting. If the model’s accuracy is low, this parameter could be avoided." }, { "code": null, "e": 6083, "s": 5972, "text": "Nodes: Number of neurons/nodes in our output layer is equal to the number of classes we are trying to predict." }, { "code": null, "e": 6227, "s": 6083, "text": "Input Shape: The input shape that SqueezeNet requires is at least 224 X 224 (with 3 channels for RGB). In this program, we have used 225 X 225." }, { "code": null, "e": 6695, "s": 6227, "text": "Choosing an optimizer & loss: Here I have chosen the Adam optimizer. And The loss function is chosen based on the type of problem. For eg:- for a binary classification problem, [loss=’binary_crossentropy’] is better suited and for a multi-class classification problem, [loss=’categorical_crossentropy’] is chosen. Whereas for a regression problem, [loss=’mse’] could be chosen. Since ours is a multi-class classification problem, we will use categorical_crossentropy." }, { "code": null, "e": 6987, "s": 6695, "text": "Number of Epochs: The number of epochs is the number of times the entire dataset is passed through the neural network during training. There is no ideal number for this and it depends on the data. In this case, I started with 10, I have used 15. Higher number indicates longer training time." }, { "code": null, "e": 7431, "s": 6987, "text": "Activation Function: We are using the ReLU activation function, which is the most common activation function that is used in neural networks due to its computational simplicity (among other advantages). This function returns a zero for negative inputs and the value itself for positive inputs. For most of the modern neural networks, ReLU is the default activation function. Other activation functions that are also used are Sigmoid, Tanh etc." }, { "code": null, "e": 7701, "s": 7431, "text": "Pooling: In CNN, it is a common practice to add a pooling layer after the convolution & activation layer. The input image is down sampled or converted to a low resolution version in order to keep only the significant details and remove the finer less important details." }, { "code": null, "e": 7876, "s": 7701, "text": "Softmax: The softmax layer is used in multi-class classification right before the output layer. It gives the likelihood of the input image belonging to a particular category." }, { "code": null, "e": 8580, "s": 7876, "text": "import numpy as npfrom keras_squeezenet import SqueezeNetfrom keras.optimizers import Adamfrom keras.utils import np_utilsfrom keras.layers import Activation, Dropout, Convolution2D, GlobalAveragePooling2Dfrom keras.models import Sequentialimport tensorflow as tfGESTURE_CATEGORIES=6base_model = Sequential()base_model.add(SqueezeNet(input_shape=(225, 225, 3), include_top=False))base_model.add(Dropout(0.5))base_model.add(Convolution2D(GESTURE_CATEGORIES, (1, 1), padding='valid'))base_model.add(Activation('relu'))base_model.add(GlobalAveragePooling2D())base_model.add(Activation('softmax'))base_model.compile( optimizer=Adam(lr=0.0001), loss='categorical_crossentropy', metrics=['accuracy'])" }, { "code": null, "e": 8777, "s": 8580, "text": "After training we will store the trained model parameters into a file(gesture-model05_20.h5) which we will be using later during model testing. The entire code is present in the github repository." }, { "code": null, "e": 8813, "s": 8777, "text": "model.save(\"gesture-model05_20.h5\")" }, { "code": null, "e": 9164, "s": 8813, "text": "To test the model, I am using some images of hand gestures captured again with my webcam. The program loads the model file “gesture-model05_20.h5” and it takes the input image as a parameter and predicts the class it belongs to. Before passing the image, we need to ensure that we are using the same dimensions that we used during the training phase." }, { "code": null, "e": 9443, "s": 9164, "text": "from keras.models import load_modelimport cv2import numpy as npimg = cv2.imread(<input image file path>)img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)img = cv2.resize(img, (225, 225))model = load_model(\"gesture-base-rmsprop-model05_20.h5\")prediction = model.predict(np.array([img]))" }, { "code": null, "e": 9600, "s": 9443, "text": "For the following test images the model predicted correctly. However, if the image contains too many other items in the background it isn’t always accurate." }, { "code": null, "e": 10006, "s": 9600, "text": "In closing, although this model may not work perfectly every single time and there is a lot we can do to improve its performance, it gives us a starting point and build on these fundamentals from here. Thank your for taking out time to read this article and I hope it helps you to create your first CNN project. I look forward to see your version of this project. Do share with me what you come up with :)" }, { "code": null, "e": 10113, "s": 10006, "text": "In my next article, we will take a look at how to take actions based on the identified class using Python." }, { "code": null, "e": 10257, "s": 10113, "text": "This article uses Python OpenCV. If you are unfamiliar with OpenCV library in Python, here’s a link to my introductory article on this subject." }, { "code": null, "e": 10280, "s": 10257, "text": "towardsdatascience.com" }, { "code": null, "e": 10291, "s": 10280, "text": "medium.com" }, { "code": null, "e": 10321, "s": 10291, "text": "References & Further Reading:" }, { "code": null, "e": 10411, "s": 10321, "text": "[1] SqueezeNet, https://codelabs.developers.google.com/codelabs/keras-flowers-squeezenet/" }, { "code": null, "e": 10515, "s": 10411, "text": "[2] Pooling, 2019, https://machinelearningmastery.com/pooling-layers-for-convolutional-neural-networks/" }, { "code": null, "e": 10576, "s": 10515, "text": "[3] SqueezeNet Paper, 2016, https://arxiv.org/abs/1602.07360" }, { "code": null, "e": 10653, "s": 10576, "text": "[4] Alternative OpenCV approach, https://www.youtube.com/watch?v=-_9WFzgI7ak" } ]
Bootstrap - Dropdown Plugin
Using Dropdown plugin you can add dropdown menus to any components like navbars, tabs, pills and buttons. You can toggle the dropdown plugin's hidden content − Via data attributes − Add data-toggle = "dropdown" to a link or button to toggle a dropdown as shown below − Via data attributes − Add data-toggle = "dropdown" to a link or button to toggle a dropdown as shown below − <div class = "dropdown"> <a data-toggle = "dropdown" href = "#">Dropdown trigger</a> <ul class = "dropdown-menu" role = "menu" aria-labelledby = "dLabel"> ... </ul> </div> If you need to keep links intact (which is useful if the browser is not enabling JavaScript), use the data-target attribute instead of href = "#"− If you need to keep links intact (which is useful if the browser is not enabling JavaScript), use the data-target attribute instead of href = "#"− <div class = "dropdown"> <a id = "dLabel" role = "button" data-toggle = "dropdown" data-target = "#" href = "/page.html"> Dropdown <span class = "caret"></span> </a> <ul class = "dropdown-menu" role = "menu" aria-labelledby = "dLabel"> ... </ul> </div> Via JavaScript − To call the dropdown toggle via JavaScript, use the following method − Via JavaScript − To call the dropdown toggle via JavaScript, use the following method − $('.dropdown-toggle').dropdown() Within Navbar The following example demonstrates the usage of dropdown menu within a navbar − <nav class = "navbar navbar-default" role = "navigation"> <div class = "navbar-header"> <a class = "navbar-brand" href = "#">TutorialsPoint</a> </div> <div> <ul class = "nav navbar-nav"> <li class = "active"><a href = "#">iOS</a></li> <li><a href = "#">SVN</a></li> <li class = "dropdown"> <a href = "#" class = "dropdown-toggle" data-toggle = "dropdown"> Java <b class="caret"></b> </a> <ul class = "dropdown-menu"> <li><a href = "#">jmeter</a></li> <li><a href = "#">EJB</a></li> <li><a href = "#">Jasper Report</a></li> <li class = "divider"></li> <li><a href = "#">Separated link</a></li> <li class = "divider"></li> <li><a href = "#">One more separated link</a></li> </ul> </li> </ul> </div> </nav> iOS SVN Java jmeter EJB Jasper Report Separated link One more separated link jmeter EJB Jasper Report Separated link One more separated link Within Tabs The following example demonstrates the usage of dropdown menu within tabs − <p>Tabs With Dropdown Example</p> <ul class = "nav nav-tabs"> <li class = "active"><a href = "#">Home</a></li> <li><a href = "#">SVN</a></li> <li><a href = "#">iOS</a></li> <li><a href = "#">VB.Net</a></li> <li class = "dropdown"> <a class = "dropdown-toggle" data-toggle = "dropdown" href = "#"> Java <span class = "caret"></span> </a> <ul class = "dropdown-menu"> <li><a href = "#">Swing</a></li> <li><a href = "#">jMeter</a></li> <li><a href = "#">EJB</a></li> <li class = "divider"></li> <li><a href = "#">Separated link</a></li> </ul> </li> <li><a href = "#">PHP</a></li> </ul> Tabs With Dropdown Example Home SVN iOS VB.Net Java Swing jMeter EJB Separated link Swing jMeter EJB Separated link PHP There are no options. The dropdown toggle has a simple method to show or hide the dropdown. $().dropdown('toggle') The following example demonstrates the usage of dropdown plugin method. <nav class = "navbar navbar-default" role = "navigation"> <div class = "navbar-header"> <a class = "navbar-brand" href = "#">TutorialsPoint</a> </div> <div id = "myexample"> <ul class = "nav navbar-nav"> <li class = "active"><a href = "#">iOS</a></li> <li><a href = "#">SVN</a></li> <li class = "dropdown"> <a href = "#" class = "dropdown-toggle">Java <b class = "caret"></b></a> <ul class = "dropdown-menu"> <li><a id = "action-1" href = "#">jmeter</a></li> <li><a href = "#">EJB</a></li> <li><a href = "#">Jasper Report</a></li> <li class = "divider"></li> <li><a href = "#">Separated link</a></li> <li class = "divider"></li> <li><a href = "#">One more separated link</a></li> </ul> </li> </ul> </div> </nav> <script> $(function(){ $(".dropdown-toggle").dropdown('toggle'); }); </script> iOS SVN Java jmeter EJB Jasper Report Separated link One more separated link jmeter EJB Jasper Report Separated link One more separated link 26 Lectures 2 hours Anadi Sharma 54 Lectures 4.5 hours Frahaan Hussain 161 Lectures 14.5 hours Eduonix Learning Solutions 20 Lectures 4 hours Azaz Patel 15 Lectures 1.5 hours Muhammad Ismail 62 Lectures 8 hours Yossef Ayman Zedan Print Add Notes Bookmark this page
[ { "code": null, "e": 3437, "s": 3331, "text": "Using Dropdown plugin you can add dropdown menus to any components like navbars, tabs, pills and buttons." }, { "code": null, "e": 3491, "s": 3437, "text": "You can toggle the dropdown plugin's hidden content −" }, { "code": null, "e": 3600, "s": 3491, "text": "Via data attributes − Add data-toggle = \"dropdown\" to a link or button to toggle a dropdown as shown below −" }, { "code": null, "e": 3709, "s": 3600, "text": "Via data attributes − Add data-toggle = \"dropdown\" to a link or button to toggle a dropdown as shown below −" }, { "code": null, "e": 3902, "s": 3709, "text": "<div class = \"dropdown\">\n <a data-toggle = \"dropdown\" href = \"#\">Dropdown trigger</a>\n \n <ul class = \"dropdown-menu\" role = \"menu\" aria-labelledby = \"dLabel\">\n ...\n </ul>\n\t\n</div>" }, { "code": null, "e": 4049, "s": 3902, "text": "If you need to keep links intact (which is useful if the browser is not enabling JavaScript), use the data-target attribute instead of href = \"#\"−" }, { "code": null, "e": 4196, "s": 4049, "text": "If you need to keep links intact (which is useful if the browser is not enabling JavaScript), use the data-target attribute instead of href = \"#\"−" }, { "code": null, "e": 4486, "s": 4196, "text": "<div class = \"dropdown\">\n <a id = \"dLabel\" role = \"button\" data-toggle = \"dropdown\" data-target = \"#\" href = \"/page.html\">\n Dropdown \n <span class = \"caret\"></span>\n </a>\n \n <ul class = \"dropdown-menu\" role = \"menu\" aria-labelledby = \"dLabel\">\n ...\n </ul>\n\t\n</div>" }, { "code": null, "e": 4574, "s": 4486, "text": "Via JavaScript − To call the dropdown toggle via JavaScript, use the following method −" }, { "code": null, "e": 4662, "s": 4574, "text": "Via JavaScript − To call the dropdown toggle via JavaScript, use the following method −" }, { "code": null, "e": 4696, "s": 4662, "text": "$('.dropdown-toggle').dropdown()\n" }, { "code": null, "e": 4710, "s": 4696, "text": "Within Navbar" }, { "code": null, "e": 4790, "s": 4710, "text": "The following example demonstrates the usage of dropdown menu within a navbar −" }, { "code": null, "e": 5821, "s": 4790, "text": "<nav class = \"navbar navbar-default\" role = \"navigation\">\n\n <div class = \"navbar-header\">\n <a class = \"navbar-brand\" href = \"#\">TutorialsPoint</a>\n </div>\n \n <div>\n <ul class = \"nav navbar-nav\">\n <li class = \"active\"><a href = \"#\">iOS</a></li>\n <li><a href = \"#\">SVN</a></li>\n \n <li class = \"dropdown\">\n <a href = \"#\" class = \"dropdown-toggle\" data-toggle = \"dropdown\">\n Java \n <b class=\"caret\"></b>\n </a>\n \n <ul class = \"dropdown-menu\">\n <li><a href = \"#\">jmeter</a></li>\n <li><a href = \"#\">EJB</a></li>\n <li><a href = \"#\">Jasper Report</a></li>\n \n <li class = \"divider\"></li>\n <li><a href = \"#\">Separated link</a></li>\n \n <li class = \"divider\"></li>\n <li><a href = \"#\">One more separated link</a></li>\n </ul>\n \n </li>\n </ul>\n </div>\n \n</nav>" }, { "code": null, "e": 5825, "s": 5821, "text": "iOS" }, { "code": null, "e": 5829, "s": 5825, "text": "SVN" }, { "code": null, "e": 5947, "s": 5829, "text": "\n\n Java \n \n\n\njmeter\nEJB\nJasper Report\n\nSeparated link\n\nOne more separated link\n\n" }, { "code": null, "e": 5954, "s": 5947, "text": "jmeter" }, { "code": null, "e": 5958, "s": 5954, "text": "EJB" }, { "code": null, "e": 5972, "s": 5958, "text": "Jasper Report" }, { "code": null, "e": 5987, "s": 5972, "text": "Separated link" }, { "code": null, "e": 6011, "s": 5987, "text": "One more separated link" }, { "code": null, "e": 6023, "s": 6011, "text": "Within Tabs" }, { "code": null, "e": 6099, "s": 6023, "text": "The following example demonstrates the usage of dropdown menu within tabs −" }, { "code": null, "e": 6822, "s": 6099, "text": "<p>Tabs With Dropdown Example</p>\n\n<ul class = \"nav nav-tabs\">\n <li class = \"active\"><a href = \"#\">Home</a></li>\n <li><a href = \"#\">SVN</a></li>\n <li><a href = \"#\">iOS</a></li>\n <li><a href = \"#\">VB.Net</a></li>\n \n <li class = \"dropdown\">\n <a class = \"dropdown-toggle\" data-toggle = \"dropdown\" href = \"#\">\n Java \n <span class = \"caret\"></span>\n </a>\n \n <ul class = \"dropdown-menu\">\n <li><a href = \"#\">Swing</a></li>\n <li><a href = \"#\">jMeter</a></li>\n <li><a href = \"#\">EJB</a></li>\n \n <li class = \"divider\"></li>\n <li><a href = \"#\">Separated link</a></li>\n </ul>\n \n </li>\n\t\n <li><a href = \"#\">PHP</a></li>\n</ul>" }, { "code": null, "e": 6849, "s": 6822, "text": "Tabs With Dropdown Example" }, { "code": null, "e": 6854, "s": 6849, "text": "Home" }, { "code": null, "e": 6858, "s": 6854, "text": "SVN" }, { "code": null, "e": 6862, "s": 6858, "text": "iOS" }, { "code": null, "e": 6869, "s": 6862, "text": "VB.Net" }, { "code": null, "e": 6945, "s": 6869, "text": "\n\n Java \n \n\n\nSwing\njMeter\nEJB\n\nSeparated link\n\n" }, { "code": null, "e": 6951, "s": 6945, "text": "Swing" }, { "code": null, "e": 6958, "s": 6951, "text": "jMeter" }, { "code": null, "e": 6962, "s": 6958, "text": "EJB" }, { "code": null, "e": 6977, "s": 6962, "text": "Separated link" }, { "code": null, "e": 6981, "s": 6977, "text": "PHP" }, { "code": null, "e": 7003, "s": 6981, "text": "There are no options." }, { "code": null, "e": 7073, "s": 7003, "text": "The dropdown toggle has a simple method to show or hide the dropdown." }, { "code": null, "e": 7097, "s": 7073, "text": "$().dropdown('toggle')\n" }, { "code": null, "e": 7169, "s": 7097, "text": "The following example demonstrates the usage of dropdown plugin method." }, { "code": null, "e": 8252, "s": 7169, "text": "<nav class = \"navbar navbar-default\" role = \"navigation\">\n <div class = \"navbar-header\">\n <a class = \"navbar-brand\" href = \"#\">TutorialsPoint</a>\n </div>\n\n <div id = \"myexample\">\n <ul class = \"nav navbar-nav\">\n <li class = \"active\"><a href = \"#\">iOS</a></li>\n <li><a href = \"#\">SVN</a></li>\n\t\t\t\n <li class = \"dropdown\">\n <a href = \"#\" class = \"dropdown-toggle\">Java <b class = \"caret\"></b></a>\n \n <ul class = \"dropdown-menu\">\n <li><a id = \"action-1\" href = \"#\">jmeter</a></li>\n <li><a href = \"#\">EJB</a></li>\n <li><a href = \"#\">Jasper Report</a></li>\n \n <li class = \"divider\"></li>\n <li><a href = \"#\">Separated link</a></li>\n \n <li class = \"divider\"></li>\n <li><a href = \"#\">One more separated link</a></li>\n </ul>\n \n </li>\n\t\t\t\n </ul>\n </div>\n \n</nav>\n\n<script>\n $(function(){\n $(\".dropdown-toggle\").dropdown('toggle');\n }); \n</script>" }, { "code": null, "e": 8256, "s": 8252, "text": "iOS" }, { "code": null, "e": 8260, "s": 8256, "text": "SVN" }, { "code": null, "e": 8336, "s": 8260, "text": "\nJava \n\njmeter\nEJB\nJasper Report\n\nSeparated link\n\nOne more separated link\n\n" }, { "code": null, "e": 8343, "s": 8336, "text": "jmeter" }, { "code": null, "e": 8347, "s": 8343, "text": "EJB" }, { "code": null, "e": 8361, "s": 8347, "text": "Jasper Report" }, { "code": null, "e": 8376, "s": 8361, "text": "Separated link" }, { "code": null, "e": 8400, "s": 8376, "text": "One more separated link" }, { "code": null, "e": 8433, "s": 8400, "text": "\n 26 Lectures \n 2 hours \n" }, { "code": null, "e": 8447, "s": 8433, "text": " Anadi Sharma" }, { "code": null, "e": 8482, "s": 8447, "text": "\n 54 Lectures \n 4.5 hours \n" }, { "code": null, "e": 8499, "s": 8482, "text": " Frahaan Hussain" }, { "code": null, "e": 8536, "s": 8499, "text": "\n 161 Lectures \n 14.5 hours \n" }, { "code": null, "e": 8564, "s": 8536, "text": " Eduonix Learning Solutions" }, { "code": null, "e": 8597, "s": 8564, "text": "\n 20 Lectures \n 4 hours \n" }, { "code": null, "e": 8609, "s": 8597, "text": " Azaz Patel" }, { "code": null, "e": 8644, "s": 8609, "text": "\n 15 Lectures \n 1.5 hours \n" }, { "code": null, "e": 8661, "s": 8644, "text": " Muhammad Ismail" }, { "code": null, "e": 8694, "s": 8661, "text": "\n 62 Lectures \n 8 hours \n" }, { "code": null, "e": 8714, "s": 8694, "text": " Yossef Ayman Zedan" }, { "code": null, "e": 8721, "s": 8714, "text": " Print" }, { "code": null, "e": 8732, "s": 8721, "text": " Add Notes" } ]
Difference between normal links and active links - GeeksforGeeks
10 Oct, 2021 Websites are designed to point you to different resources. You can move from one website to another through links. Links help you to get information from different resources. Links are established in simple HTML web pages through <a> tag.Links are categorized into three types. Typically a Link is displayed in three different colors based on the usage. Normal links (Unvisited links) Visited links Active links Example 1: The following example shows the basic example for Normal Link ( Unvisited Link ). If you want to create a link to go to “https://www.geeksforgeeks.org/“, you can get the normal link through this code. The default color is blue color and underlined but you can apply your own custom styling according to the application’s need. HTML <!DOCTYPE html><html> <body> <h2>This is a Link</h2> <h1> Welcome to <a href="https://www.geeksforgeeks.org/"> GeeksforGeeks </a> </h1></body> </html> Output: Visited Link: In example 1, If you click on the link shown above and again go back to the link page, you can now see the link is in purple color and underlined. It shows that the user has visited this link before. You can do your own custom styling using CSS :visited selector. In the above output, notice the visited link after going back from the home page. Active Link: In example 1, If you left or right-click any one of the links Visited or Unvisited, it will turn into Red and Underline. Active Links shows that the browser is in the process to load a new resource. You can do your own custom styling using CSS :active selector. In the above output, notice the active link on right-click of the link. The <a> tag is supported in almost all browsers. So, these are the 3 types of links with their different usages and default stylings. This helps the user to navigate through different resources. Attention reader! Don’t stop learning now. Get hold of all the important HTML concepts with the Web Design for Beginners | HTML course. HTML-Questions HTML-Tags Picked Difference Between HTML Web Technologies HTML 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 Difference Between Method Overloading and Method Overriding in Java Difference between Prim's and Kruskal's algorithm for MST Difference between Internal and External fragmentation Differences and Applications of List, Tuple, Set and Dictionary in Python Top 10 Projects For Beginners To Practice HTML and CSS Skills How to insert spaces/tabs in text using HTML/CSS? How to set the default value for an HTML <select> element ? How to update Node.js and NPM to next version ? How to set input type date in dd-mm-yyyy format using HTML ?
[ { "code": null, "e": 24858, "s": 24830, "text": "\n10 Oct, 2021" }, { "code": null, "e": 25212, "s": 24858, "text": "Websites are designed to point you to different resources. You can move from one website to another through links. Links help you to get information from different resources. Links are established in simple HTML web pages through <a> tag.Links are categorized into three types. Typically a Link is displayed in three different colors based on the usage." }, { "code": null, "e": 25243, "s": 25212, "text": "Normal links (Unvisited links)" }, { "code": null, "e": 25257, "s": 25243, "text": "Visited links" }, { "code": null, "e": 25270, "s": 25257, "text": "Active links" }, { "code": null, "e": 25608, "s": 25270, "text": "Example 1: The following example shows the basic example for Normal Link ( Unvisited Link ). If you want to create a link to go to “https://www.geeksforgeeks.org/“, you can get the normal link through this code. The default color is blue color and underlined but you can apply your own custom styling according to the application’s need." }, { "code": null, "e": 25613, "s": 25608, "text": "HTML" }, { "code": "<!DOCTYPE html><html> <body> <h2>This is a Link</h2> <h1> Welcome to <a href=\"https://www.geeksforgeeks.org/\"> GeeksforGeeks </a> </h1></body> </html>", "e": 25807, "s": 25613, "text": null }, { "code": null, "e": 25839, "s": 25807, "text": "Output: " }, { "code": null, "e": 26199, "s": 25839, "text": "Visited Link: In example 1, If you click on the link shown above and again go back to the link page, you can now see the link is in purple color and underlined. It shows that the user has visited this link before. You can do your own custom styling using CSS :visited selector. In the above output, notice the visited link after going back from the home page." }, { "code": null, "e": 26547, "s": 26199, "text": "Active Link: In example 1, If you left or right-click any one of the links Visited or Unvisited, it will turn into Red and Underline. Active Links shows that the browser is in the process to load a new resource. You can do your own custom styling using CSS :active selector. In the above output, notice the active link on right-click of the link." }, { "code": null, "e": 26743, "s": 26547, "text": "The <a> tag is supported in almost all browsers. So, these are the 3 types of links with their different usages and default stylings. This helps the user to navigate through different resources. " }, { "code": null, "e": 26880, "s": 26743, "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": 26895, "s": 26880, "text": "HTML-Questions" }, { "code": null, "e": 26905, "s": 26895, "text": "HTML-Tags" }, { "code": null, "e": 26912, "s": 26905, "text": "Picked" }, { "code": null, "e": 26931, "s": 26912, "text": "Difference Between" }, { "code": null, "e": 26936, "s": 26931, "text": "HTML" }, { "code": null, "e": 26953, "s": 26936, "text": "Web Technologies" }, { "code": null, "e": 26958, "s": 26953, "text": "HTML" }, { "code": null, "e": 27056, "s": 26958, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 27117, "s": 27056, "text": "Difference between var, let and const keywords in JavaScript" }, { "code": null, "e": 27185, "s": 27117, "text": "Difference Between Method Overloading and Method Overriding in Java" }, { "code": null, "e": 27243, "s": 27185, "text": "Difference between Prim's and Kruskal's algorithm for MST" }, { "code": null, "e": 27298, "s": 27243, "text": "Difference between Internal and External fragmentation" }, { "code": null, "e": 27372, "s": 27298, "text": "Differences and Applications of List, Tuple, Set and Dictionary in Python" }, { "code": null, "e": 27434, "s": 27372, "text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills" }, { "code": null, "e": 27484, "s": 27434, "text": "How to insert spaces/tabs in text using HTML/CSS?" }, { "code": null, "e": 27544, "s": 27484, "text": "How to set the default value for an HTML <select> element ?" }, { "code": null, "e": 27592, "s": 27544, "text": "How to update Node.js and NPM to next version ?" } ]
NGBoost Explained. Stanford ML Group recently published a... | by Kyosuke Morita | Towards Data Science
Stanford ML Group recently published a new algorithm in their paper, [1] Duan et al., 2019 and its implementation called NGBoost. This algorithm includes uncertainty estimation into the gradient boosting by using the Natural gradient. This post tries to understand this new algorithm and comparing with other popular boosting algorithms, LightGBM and XGboost to see how it works in practice. What is Natural Gradient Boosting anyways?Empirical validation — comparison to LightGBM and XGBoostConclusion What is Natural Gradient Boosting anyways? Empirical validation — comparison to LightGBM and XGBoost Conclusion What is Natural Gradient Boosting anyways? What is Natural Gradient Boosting anyways? As I wrote in the intro, NGBoost is a new boosting algorithm, which uses Natural Gradient Boosting, a modular boosting algorithm for probabilistic predictions. This algorithm is consist of base learner, parametric probability distribution, and scoring rule. I will briefly explain what are those terms. Base learners This algorithm uses base (weak) learners. It takes inputs x and outputs are used to form the conditional probability. Those base learners use scikit-learn’s Decision Tree for a tree learner and Ridge regression for a linear learner. Parametric probability distribution Parametric probability distribution is a conditional distribution. This is formed by an additive combination of base learner outputs. Scoring Rule A scoring rule takes a predicted probability distribution and one observation of the target feature to produce a score to the prediction, where the true distribution of the outcomes gets the best score in expectation. This algorithm uses MLE (Maximum Likelihood Estimation) or CRPS (Continuous Ranked Probability Score). We just went through the basic concepts of NGBoost. I definitely recommend you to read the original paper for further understanding (it’s easier to understand the algorithms with math notations). 2. Empirical Validation — Comparison to LightGBM and XGBoost Let’s implement NGBoost and see how is the performance of it. The original paper also did some experiments on various datasets. They compared MC dropout, Deep Ensembles and NGBoost in regression problems and NGBoost shows its quite competitive performance. In this blog post, I would like to show the model performance on the famous house price prediction dataset on Kaggle. This dataset consists of 81 features, 1460 rows and the target feature is the sale price. Let’s see NGBoost can handle these conditions. As testing the performance of the algorithms is the purpose of this post, we will skip a whole feature engineering part and will use Nanashi’s solution. Import the packages; # import packagesimport pandas as pdfrom ngboost.ngboost import NGBoostfrom ngboost.learners import default_tree_learnerfrom ngboost.distns import Normalfrom ngboost.scores import MLEimport lightgbm as lgbimport xgboost as xgbfrom sklearn.model_selection import train_test_splitfrom sklearn.metrics import mean_squared_errorfrom math import sqrt Here I will use the above default learners, distributions, and scoring rule. Would be interesting to play around with those and see how the results change. # read the datasetdf = pd.read_csv('~/train.csv')# feature engineeringtr, te = Nanashi_solution(df) Now predict by using NGBoost algorithm. # NGBoostngb = NGBoost(Base=default_tree_learner, Dist=Normal, Score=MLE(), natural_gradient=True,verbose=False)ngboost = ngb.fit(np.asarray(tr.drop(['SalePrice'],1)), np.asarray(tr.SalePrice))y_pred_ngb = pd.DataFrame(ngb.predict(te.drop(['SalePrice'],1))) Do the same with LightGBM and XGBoost. # LightGBMltr = lgb.Dataset(tr.drop(['SalePrice'],1),label=tr['SalePrice'])param = {'bagging_freq': 5,'bagging_fraction': 0.6,'bagging_seed': 123,'boost_from_average':'false','boost': 'gbdt','feature_fraction': 0.3,'learning_rate': .01,'max_depth': 3,'metric':'rmse','min_data_in_leaf': 128,'min_sum_hessian_in_leaf': 8,'num_leaves': 128,'num_threads': 8,'tree_learner': 'serial','objective': 'regression','verbosity': -1,'random_state':123,'max_bin': 8,'early_stopping_round':100}lgbm = lgb.train(param,ltr,num_boost_round=10000,valid_sets=[(ltr)],verbose_eval=1000)y_pred_lgb = lgbm.predict(te.drop(['SalePrice'],1))y_pred_lgb = np.where(y_pred>=.25,1,0)# XGBoostparams = {'max_depth': 4, 'eta': 0.01, 'objective':'reg:squarederror', 'eval_metric':['rmse'],'booster':'gbtree', 'verbosity':0,'sample_type':'weighted','max_delta_step':4, 'subsample':.5, 'min_child_weight':100,'early_stopping_round':50}dtr, dte = xgb.DMatrix(tr.drop(['SalePrice'],1),label=tr.SalePrice), xgb.DMatrix(te.drop(['SalePrice'],1),label=te.SalePrice)num_round = 5000xgbst = xgb.train(params,dtr,num_round,verbose_eval=500)y_pred_xgb = xgbst.predict(dte) Now we have predictions from all of the algorithms. Let’s check the accuracy. We will use the same metric as this Kaggle competition, RMSE. # Check the resultsprint('RMSE: NGBoost', round(sqrt(mean_squared_error(X_val.SalePrice,y_pred_ngb)),4))print('RMSE: LGBM', round(sqrt(mean_squared_error(X_val.SalePrice,y_pred_lgbm)),4))print('RMSE: XGBoost', round(sqrt(mean_squared_error(X_val.SalePrice,y_pred_xgb)),4)) Here is the summary of prediction results. It seems like NGBoost outperformed other famous boosting algorithms. To be fair, I feel like if I tune the parameters of BGBoost, it will be even better. NGBoost’s one of the biggest difference from other boosting algorithms is can return probabilistic distribution of each prediction. This can be visualised by using pred_dist function. This function enables to show the results of probabilistic predictions. # see the probability distributions by visualisingY_dists = ngb.pred_dist(X_val.drop(['SalePrice'],1))y_range = np.linspace(min(X_val.SalePrice), max(X_val.SalePrice), 200)dist_values = Y_dists.pdf(y_range).transpose()# plot index 0 and 114idx = 114plt.plot(y_range,dist_values[idx])plt.title(f"idx: {idx}")plt.tight_layout()plt.show() Above plots are the probability distributions of each prediction. X-axis shows the log value of Sale Price (target feature). We can observe that the probability distribution is wider for index 0 than index 114. 4. Conclusion and Thoughts From the result of this experiment, we can conclude that NGBoost is as good as other famous boosting algorithms. However, computing time is quite longer than other two algorithms. This can be probably improved by using subsampling method. Also I had an impression that NGBoost package is still in progress, for example there’s no early stopping option, no option of showing the intermediate results, the flexibility of choosing the base learner (so far we can only choose between decision tree and Ridge regression), setting a random state seed, and so on. I believe these points will be implemented very soon. Or you can contribute to the project :) Also you can find codes I used for this post on my GitHub page. NGBoost is a new boosting algorithm that returns probability distribution. Natural Gradient Boosting, a modular boosting algorithm for probabilistic prediction. This is consist of Base learner, Parametric probability distribution, and Scoring rule. NGBoost predictions are quite competitive against other popular boosting algorithms. If you found the story helpful, interesting or whatever, or also if you have any question, feedback or literally anything, feel free to leave a comment below :) I would really appreciate it. Also, you can find me on LinkedIn. [1] T. Duan, et al., NGBoost: Natural Gradient Boosting for Probabilistic Prediction (2019), ArXiv 1910.03225
[ { "code": null, "e": 564, "s": 172, "text": "Stanford ML Group recently published a new algorithm in their paper, [1] Duan et al., 2019 and its implementation called NGBoost. This algorithm includes uncertainty estimation into the gradient boosting by using the Natural gradient. This post tries to understand this new algorithm and comparing with other popular boosting algorithms, LightGBM and XGboost to see how it works in practice." }, { "code": null, "e": 674, "s": 564, "text": "What is Natural Gradient Boosting anyways?Empirical validation — comparison to LightGBM and XGBoostConclusion" }, { "code": null, "e": 717, "s": 674, "text": "What is Natural Gradient Boosting anyways?" }, { "code": null, "e": 775, "s": 717, "text": "Empirical validation — comparison to LightGBM and XGBoost" }, { "code": null, "e": 786, "s": 775, "text": "Conclusion" }, { "code": null, "e": 829, "s": 786, "text": "What is Natural Gradient Boosting anyways?" }, { "code": null, "e": 872, "s": 829, "text": "What is Natural Gradient Boosting anyways?" }, { "code": null, "e": 1175, "s": 872, "text": "As I wrote in the intro, NGBoost is a new boosting algorithm, which uses Natural Gradient Boosting, a modular boosting algorithm for probabilistic predictions. This algorithm is consist of base learner, parametric probability distribution, and scoring rule. I will briefly explain what are those terms." }, { "code": null, "e": 1189, "s": 1175, "text": "Base learners" }, { "code": null, "e": 1422, "s": 1189, "text": "This algorithm uses base (weak) learners. It takes inputs x and outputs are used to form the conditional probability. Those base learners use scikit-learn’s Decision Tree for a tree learner and Ridge regression for a linear learner." }, { "code": null, "e": 1458, "s": 1422, "text": "Parametric probability distribution" }, { "code": null, "e": 1592, "s": 1458, "text": "Parametric probability distribution is a conditional distribution. This is formed by an additive combination of base learner outputs." }, { "code": null, "e": 1605, "s": 1592, "text": "Scoring Rule" }, { "code": null, "e": 1926, "s": 1605, "text": "A scoring rule takes a predicted probability distribution and one observation of the target feature to produce a score to the prediction, where the true distribution of the outcomes gets the best score in expectation. This algorithm uses MLE (Maximum Likelihood Estimation) or CRPS (Continuous Ranked Probability Score)." }, { "code": null, "e": 2122, "s": 1926, "text": "We just went through the basic concepts of NGBoost. I definitely recommend you to read the original paper for further understanding (it’s easier to understand the algorithms with math notations)." }, { "code": null, "e": 2183, "s": 2122, "text": "2. Empirical Validation — Comparison to LightGBM and XGBoost" }, { "code": null, "e": 2695, "s": 2183, "text": "Let’s implement NGBoost and see how is the performance of it. The original paper also did some experiments on various datasets. They compared MC dropout, Deep Ensembles and NGBoost in regression problems and NGBoost shows its quite competitive performance. In this blog post, I would like to show the model performance on the famous house price prediction dataset on Kaggle. This dataset consists of 81 features, 1460 rows and the target feature is the sale price. Let’s see NGBoost can handle these conditions." }, { "code": null, "e": 2848, "s": 2695, "text": "As testing the performance of the algorithms is the purpose of this post, we will skip a whole feature engineering part and will use Nanashi’s solution." }, { "code": null, "e": 2869, "s": 2848, "text": "Import the packages;" }, { "code": null, "e": 3215, "s": 2869, "text": "# import packagesimport pandas as pdfrom ngboost.ngboost import NGBoostfrom ngboost.learners import default_tree_learnerfrom ngboost.distns import Normalfrom ngboost.scores import MLEimport lightgbm as lgbimport xgboost as xgbfrom sklearn.model_selection import train_test_splitfrom sklearn.metrics import mean_squared_errorfrom math import sqrt" }, { "code": null, "e": 3371, "s": 3215, "text": "Here I will use the above default learners, distributions, and scoring rule. Would be interesting to play around with those and see how the results change." }, { "code": null, "e": 3471, "s": 3371, "text": "# read the datasetdf = pd.read_csv('~/train.csv')# feature engineeringtr, te = Nanashi_solution(df)" }, { "code": null, "e": 3511, "s": 3471, "text": "Now predict by using NGBoost algorithm." }, { "code": null, "e": 3769, "s": 3511, "text": "# NGBoostngb = NGBoost(Base=default_tree_learner, Dist=Normal, Score=MLE(), natural_gradient=True,verbose=False)ngboost = ngb.fit(np.asarray(tr.drop(['SalePrice'],1)), np.asarray(tr.SalePrice))y_pred_ngb = pd.DataFrame(ngb.predict(te.drop(['SalePrice'],1)))" }, { "code": null, "e": 3808, "s": 3769, "text": "Do the same with LightGBM and XGBoost." }, { "code": null, "e": 4940, "s": 3808, "text": "# LightGBMltr = lgb.Dataset(tr.drop(['SalePrice'],1),label=tr['SalePrice'])param = {'bagging_freq': 5,'bagging_fraction': 0.6,'bagging_seed': 123,'boost_from_average':'false','boost': 'gbdt','feature_fraction': 0.3,'learning_rate': .01,'max_depth': 3,'metric':'rmse','min_data_in_leaf': 128,'min_sum_hessian_in_leaf': 8,'num_leaves': 128,'num_threads': 8,'tree_learner': 'serial','objective': 'regression','verbosity': -1,'random_state':123,'max_bin': 8,'early_stopping_round':100}lgbm = lgb.train(param,ltr,num_boost_round=10000,valid_sets=[(ltr)],verbose_eval=1000)y_pred_lgb = lgbm.predict(te.drop(['SalePrice'],1))y_pred_lgb = np.where(y_pred>=.25,1,0)# XGBoostparams = {'max_depth': 4, 'eta': 0.01, 'objective':'reg:squarederror', 'eval_metric':['rmse'],'booster':'gbtree', 'verbosity':0,'sample_type':'weighted','max_delta_step':4, 'subsample':.5, 'min_child_weight':100,'early_stopping_round':50}dtr, dte = xgb.DMatrix(tr.drop(['SalePrice'],1),label=tr.SalePrice), xgb.DMatrix(te.drop(['SalePrice'],1),label=te.SalePrice)num_round = 5000xgbst = xgb.train(params,dtr,num_round,verbose_eval=500)y_pred_xgb = xgbst.predict(dte)" }, { "code": null, "e": 5080, "s": 4940, "text": "Now we have predictions from all of the algorithms. Let’s check the accuracy. We will use the same metric as this Kaggle competition, RMSE." }, { "code": null, "e": 5353, "s": 5080, "text": "# Check the resultsprint('RMSE: NGBoost', round(sqrt(mean_squared_error(X_val.SalePrice,y_pred_ngb)),4))print('RMSE: LGBM', round(sqrt(mean_squared_error(X_val.SalePrice,y_pred_lgbm)),4))print('RMSE: XGBoost', round(sqrt(mean_squared_error(X_val.SalePrice,y_pred_xgb)),4))" }, { "code": null, "e": 5396, "s": 5353, "text": "Here is the summary of prediction results." }, { "code": null, "e": 5550, "s": 5396, "text": "It seems like NGBoost outperformed other famous boosting algorithms. To be fair, I feel like if I tune the parameters of BGBoost, it will be even better." }, { "code": null, "e": 5806, "s": 5550, "text": "NGBoost’s one of the biggest difference from other boosting algorithms is can return probabilistic distribution of each prediction. This can be visualised by using pred_dist function. This function enables to show the results of probabilistic predictions." }, { "code": null, "e": 6142, "s": 5806, "text": "# see the probability distributions by visualisingY_dists = ngb.pred_dist(X_val.drop(['SalePrice'],1))y_range = np.linspace(min(X_val.SalePrice), max(X_val.SalePrice), 200)dist_values = Y_dists.pdf(y_range).transpose()# plot index 0 and 114idx = 114plt.plot(y_range,dist_values[idx])plt.title(f\"idx: {idx}\")plt.tight_layout()plt.show()" }, { "code": null, "e": 6353, "s": 6142, "text": "Above plots are the probability distributions of each prediction. X-axis shows the log value of Sale Price (target feature). We can observe that the probability distribution is wider for index 0 than index 114." }, { "code": null, "e": 6380, "s": 6353, "text": "4. Conclusion and Thoughts" }, { "code": null, "e": 7031, "s": 6380, "text": "From the result of this experiment, we can conclude that NGBoost is as good as other famous boosting algorithms. However, computing time is quite longer than other two algorithms. This can be probably improved by using subsampling method. Also I had an impression that NGBoost package is still in progress, for example there’s no early stopping option, no option of showing the intermediate results, the flexibility of choosing the base learner (so far we can only choose between decision tree and Ridge regression), setting a random state seed, and so on. I believe these points will be implemented very soon. Or you can contribute to the project :)" }, { "code": null, "e": 7095, "s": 7031, "text": "Also you can find codes I used for this post on my GitHub page." }, { "code": null, "e": 7170, "s": 7095, "text": "NGBoost is a new boosting algorithm that returns probability distribution." }, { "code": null, "e": 7344, "s": 7170, "text": "Natural Gradient Boosting, a modular boosting algorithm for probabilistic prediction. This is consist of Base learner, Parametric probability distribution, and Scoring rule." }, { "code": null, "e": 7429, "s": 7344, "text": "NGBoost predictions are quite competitive against other popular boosting algorithms." }, { "code": null, "e": 7655, "s": 7429, "text": "If you found the story helpful, interesting or whatever, or also if you have any question, feedback or literally anything, feel free to leave a comment below :) I would really appreciate it. Also, you can find me on LinkedIn." } ]
C++ Program to Convert Binary Number to Decimal and vice-versa
In a computer system, the binary number is expressed in the binary numeral system while the decimal number is in the decimal numeral system. The binary number is in base 2 while the decimal number is in base 10. Examples of decimal numbers and their corresponding binary numbers are as follows − A program that converts the binary numbers into decimal and the decimal numbers into binary is as follows. Live Demo #include <iostream> using namespace std; void DecimalToBinary(int n) { int binaryNumber[100], num=n; int i = 0; while (n > 0) { binaryNumber[i] = n % 2; n = n / 2; i++; } cout<<"Binary form of "<<num<<" is "; for (int j = i - 1; j >= 0; j--) cout << binaryNumber[j]; cout<<endl; } int BinaryToDecimal(int n) { int decimalNumber = 0; int base = 1; int temp = n; while (temp) { int lastDigit = temp % 10; temp = temp/10; decimalNumber += lastDigit*base; base = base*2; } cout<<"Decimal form of "<<n<<" is "<<decimalNumber<<endl;; } int main() { DecimalToBinary(23); BinaryToDecimal(10101); return 0; } Binary form of 23 is 10111 Decimal form of 10101 is 21 In the program given above, there are two functions DecimalToBinary and BinaryToDecimal. These convert the number from decimal to binary and binary to decimal respectively. In the DecimalToBinary function, the binary value of the decimal number n is stored in the array binaryNumber[]. A while loop is used and the result of the n modulus 2 operation is stored in binaryNumber[] for each iteration of the loop. This is shown using the following code snippet. while (n > 0) { binaryNumber[i] = n % 2; n = n / 2; i++; } After this, the binary number is displayed using a for loop. This is shown as follows. cout<<"Binary form of "<<num<<" is "; for (int j = i - 1; j >= 0; j--) cout << binaryNumber[j]; In the function, BinaryToDecimal(), a while loop is used to convert the binary number into decimal number. The LastDigit contains the last bit of the temp variable. The base contains the base value such as 2, 4, 6, 8 etc. The DecimalNumber contains the sum of the previous DecimalNumber value and the product of the LastDigit and base. All this is demonstrated using the following code snippet − while (temp) { int lastDigit = temp % 10; temp = temp/10; decimalNumber += lastDigit*base; base = base*2; } In the main() function, the DecimalToBinary() and BinaryToDecimal() functions are called. This is shown as follows. DecimalToBinary(23); BinaryToDecimal(10101);
[ { "code": null, "e": 1274, "s": 1062, "text": "In a computer system, the binary number is expressed in the binary numeral system while the decimal number is in the decimal numeral system. The binary number is in base 2 while the decimal number is in base 10." }, { "code": null, "e": 1358, "s": 1274, "text": "Examples of decimal numbers and their corresponding binary numbers are as follows −" }, { "code": null, "e": 1465, "s": 1358, "text": "A program that converts the binary numbers into decimal and the decimal numbers into binary is as follows." }, { "code": null, "e": 1476, "s": 1465, "text": " Live Demo" }, { "code": null, "e": 2172, "s": 1476, "text": "#include <iostream>\nusing namespace std;\nvoid DecimalToBinary(int n) {\n int binaryNumber[100], num=n;\n int i = 0;\n while (n > 0) {\n binaryNumber[i] = n % 2;\n n = n / 2;\n i++;\n }\n cout<<\"Binary form of \"<<num<<\" is \";\n for (int j = i - 1; j >= 0; j--)\n cout << binaryNumber[j];\n cout<<endl;\n}\nint BinaryToDecimal(int n) {\n int decimalNumber = 0;\n int base = 1;\n int temp = n;\n while (temp) {\n int lastDigit = temp % 10;\n temp = temp/10;\n decimalNumber += lastDigit*base;\n base = base*2;\n }\n cout<<\"Decimal form of \"<<n<<\" is \"<<decimalNumber<<endl;;\n}\nint main() {\n DecimalToBinary(23);\n BinaryToDecimal(10101);\n return 0;\n}" }, { "code": null, "e": 2227, "s": 2172, "text": "Binary form of 23 is 10111\nDecimal form of 10101 is 21" }, { "code": null, "e": 2400, "s": 2227, "text": "In the program given above, there are two functions DecimalToBinary and BinaryToDecimal. These convert the number from decimal to binary and binary to decimal respectively." }, { "code": null, "e": 2686, "s": 2400, "text": "In the DecimalToBinary function, the binary value of the decimal number n is stored in the array binaryNumber[]. A while loop is used and the result of the n modulus 2 operation is stored in binaryNumber[] for each iteration of the loop. This is shown using the following code snippet." }, { "code": null, "e": 2754, "s": 2686, "text": "while (n > 0) {\n binaryNumber[i] = n % 2;\n n = n / 2;\n i++;\n}" }, { "code": null, "e": 2841, "s": 2754, "text": "After this, the binary number is displayed using a for loop. This is shown as follows." }, { "code": null, "e": 2937, "s": 2841, "text": "cout<<\"Binary form of \"<<num<<\" is \";\nfor (int j = i - 1; j >= 0; j--)\ncout << binaryNumber[j];" }, { "code": null, "e": 3273, "s": 2937, "text": "In the function, BinaryToDecimal(), a while loop is used to convert the binary number into decimal number. The LastDigit contains the last bit of the temp variable. The base contains the base value such as 2, 4, 6, 8 etc. The DecimalNumber contains the sum of the previous DecimalNumber value and the product of the LastDigit and base." }, { "code": null, "e": 3333, "s": 3273, "text": "All this is demonstrated using the following code snippet −" }, { "code": null, "e": 3453, "s": 3333, "text": "while (temp) {\n int lastDigit = temp % 10;\n temp = temp/10;\n decimalNumber += lastDigit*base;\n base = base*2;\n}" }, { "code": null, "e": 3569, "s": 3453, "text": "In the main() function, the DecimalToBinary() and BinaryToDecimal() functions are called. This is shown as follows." }, { "code": null, "e": 3614, "s": 3569, "text": "DecimalToBinary(23);\nBinaryToDecimal(10101);" } ]
C library macro - va_arg()
The C library macro type va_arg(va_list ap, type) retrieves the next argument in the parameter list of the function with type. This does not determine whether the retrieved argument is the last argument passed to the function. Following is the declaration for va_arg() macro. type va_arg(va_list ap, type) ap − This is the object of type va_list with information about the additional arguments and their retrieval state. This object should be initialized by an initial call to va_start before the first call to va_arg. ap − This is the object of type va_list with information about the additional arguments and their retrieval state. This object should be initialized by an initial call to va_start before the first call to va_arg. type − This is a type name. This type name is used as the type of the expression, this macro expands to. type − This is a type name. This type name is used as the type of the expression, this macro expands to. This macro returns the next additional argument as an expression of type type. The following example shows the usage of va_arg() macro. #include <stdarg.h> #include <stdio.h> int sum(int, ...); int main () { printf("Sum of 15 and 56 = %d\n", sum(2, 15, 56) ); return 0; } int sum(int num_args, ...) { int val = 0; va_list ap; int i; va_start(ap, num_args); for(i = 0; i < num_args; i++) { val += va_arg(ap, int); } va_end(ap); return val; } Let us compile and run the above program to produce the following result − Sum of 15 and 56 = 71 12 Lectures 2 hours Nishant Malik 12 Lectures 2.5 hours Nishant Malik 48 Lectures 6.5 hours Asif Hussain 12 Lectures 2 hours Richa Maheshwari 20 Lectures 3.5 hours Vandana Annavaram 44 Lectures 1 hours Amit Diwan Print Add Notes Bookmark this page
[ { "code": null, "e": 2234, "s": 2007, "text": "The C library macro type va_arg(va_list ap, type) retrieves the next argument in the parameter list of the function with type. This does not determine whether the retrieved argument is the last argument passed to the function." }, { "code": null, "e": 2283, "s": 2234, "text": "Following is the declaration for va_arg() macro." }, { "code": null, "e": 2313, "s": 2283, "text": "type va_arg(va_list ap, type)" }, { "code": null, "e": 2526, "s": 2313, "text": "ap − This is the object of type va_list with information about the additional arguments and their retrieval state. This object should be initialized by an initial call to va_start before the first call to va_arg." }, { "code": null, "e": 2739, "s": 2526, "text": "ap − This is the object of type va_list with information about the additional arguments and their retrieval state. This object should be initialized by an initial call to va_start before the first call to va_arg." }, { "code": null, "e": 2844, "s": 2739, "text": "type − This is a type name. This type name is used as the type of the expression, this macro expands to." }, { "code": null, "e": 2949, "s": 2844, "text": "type − This is a type name. This type name is used as the type of the expression, this macro expands to." }, { "code": null, "e": 3028, "s": 2949, "text": "This macro returns the next additional argument as an expression of type type." }, { "code": null, "e": 3085, "s": 3028, "text": "The following example shows the usage of va_arg() macro." }, { "code": null, "e": 3433, "s": 3085, "text": "#include <stdarg.h>\n#include <stdio.h>\n\nint sum(int, ...);\n\nint main () {\n printf(\"Sum of 15 and 56 = %d\\n\", sum(2, 15, 56) );\n return 0;\n}\n\nint sum(int num_args, ...) {\n int val = 0;\n va_list ap;\n int i;\n\n va_start(ap, num_args);\n for(i = 0; i < num_args; i++) {\n val += va_arg(ap, int);\n }\n va_end(ap);\n \n return val;\n}" }, { "code": null, "e": 3508, "s": 3433, "text": "Let us compile and run the above program to produce the following result −" }, { "code": null, "e": 3531, "s": 3508, "text": "Sum of 15 and 56 = 71\n" }, { "code": null, "e": 3564, "s": 3531, "text": "\n 12 Lectures \n 2 hours \n" }, { "code": null, "e": 3579, "s": 3564, "text": " Nishant Malik" }, { "code": null, "e": 3614, "s": 3579, "text": "\n 12 Lectures \n 2.5 hours \n" }, { "code": null, "e": 3629, "s": 3614, "text": " Nishant Malik" }, { "code": null, "e": 3664, "s": 3629, "text": "\n 48 Lectures \n 6.5 hours \n" }, { "code": null, "e": 3678, "s": 3664, "text": " Asif Hussain" }, { "code": null, "e": 3711, "s": 3678, "text": "\n 12 Lectures \n 2 hours \n" }, { "code": null, "e": 3729, "s": 3711, "text": " Richa Maheshwari" }, { "code": null, "e": 3764, "s": 3729, "text": "\n 20 Lectures \n 3.5 hours \n" }, { "code": null, "e": 3783, "s": 3764, "text": " Vandana Annavaram" }, { "code": null, "e": 3816, "s": 3783, "text": "\n 44 Lectures \n 1 hours \n" }, { "code": null, "e": 3828, "s": 3816, "text": " Amit Diwan" }, { "code": null, "e": 3835, "s": 3828, "text": " Print" }, { "code": null, "e": 3846, "s": 3835, "text": " Add Notes" } ]
How to convert an integer to string with padding zero in C#?
There are several ways to convert an integer to a string in C#. PadLeft − Returns a new string of a specified length in which the beginning of the current string is padded with spaces or with a specified Unicode character ToString − Returns a string that represents the current object. String Interpolation − The $ special character identifies a string literal as an interpolated string. This feature is available starting with C# 6. Example using string padding− Live Demo using System; namespace DemoApplication{ class Program{ public static void Main(){ int number = 5; Console.WriteLine("Number: {0}", number); var numberString = number.ToString().PadLeft(4, '0'); Console.WriteLine("Padded String: {0}", numberString); Console.ReadLine(); } } } The output of the above code is Number: 5 Padded String: 0005 Example using explicit form − Live Demo using System; namespace DemoApplication{ class Program{ public static void Main(){ int number = 5; Console.WriteLine("Number: {0}", number); var numberString = number.ToString("0000"); Console.WriteLine("Padded String: {0}", numberString); Console.ReadLine(); } } } The output of the above code is Number: 5 Padded String: 0005 Example using short form format specifier − Live Demo using System; namespace DemoApplication{ class Program{ public static void Main(){ int number = 5; Console.WriteLine("Number: {0}", number); var numberString = number.ToString("D4"); Console.WriteLine("Padded String: {0}", numberString); Console.ReadLine(); } } } The output of the above code is Number: 5 Padded String: 0005 Example using string interpolation− Live Demo using System; namespace DemoApplication{ class Program{ public static void Main(){ int number = 5; Console.WriteLine("Number: {0}", number); var numberString = $"{number:0000}"; Console.WriteLine("Padded String: {0}", numberString); Console.ReadLine(); } } } The output of the above code is Number: 5 Padded String: 0005
[ { "code": null, "e": 1126, "s": 1062, "text": "There are several ways to convert an integer to a string in C#." }, { "code": null, "e": 1284, "s": 1126, "text": "PadLeft − Returns a new string of a specified length in which the beginning of the current string is padded with spaces or with a specified Unicode character" }, { "code": null, "e": 1348, "s": 1284, "text": "ToString − Returns a string that represents the current object." }, { "code": null, "e": 1496, "s": 1348, "text": "String Interpolation − The $ special character identifies a string literal as an interpolated string. This feature is available starting with C# 6." }, { "code": null, "e": 1526, "s": 1496, "text": "Example using string padding−" }, { "code": null, "e": 1537, "s": 1526, "text": " Live Demo" }, { "code": null, "e": 1876, "s": 1537, "text": "using System;\nnamespace DemoApplication{\n class Program{\n public static void Main(){\n int number = 5;\n Console.WriteLine(\"Number: {0}\", number);\n var numberString = number.ToString().PadLeft(4, '0');\n Console.WriteLine(\"Padded String: {0}\", numberString);\n Console.ReadLine();\n }\n }\n}" }, { "code": null, "e": 1908, "s": 1876, "text": "The output of the above code is" }, { "code": null, "e": 1938, "s": 1908, "text": "Number: 5\nPadded String: 0005" }, { "code": null, "e": 1968, "s": 1938, "text": "Example using explicit form −" }, { "code": null, "e": 1979, "s": 1968, "text": " Live Demo" }, { "code": null, "e": 2308, "s": 1979, "text": "using System;\nnamespace DemoApplication{\n class Program{\n public static void Main(){\n int number = 5;\n Console.WriteLine(\"Number: {0}\", number);\n var numberString = number.ToString(\"0000\");\n Console.WriteLine(\"Padded String: {0}\", numberString);\n Console.ReadLine();\n }\n }\n}" }, { "code": null, "e": 2340, "s": 2308, "text": "The output of the above code is" }, { "code": null, "e": 2370, "s": 2340, "text": "Number: 5\nPadded String: 0005" }, { "code": null, "e": 2414, "s": 2370, "text": "Example using short form format specifier −" }, { "code": null, "e": 2425, "s": 2414, "text": " Live Demo" }, { "code": null, "e": 2752, "s": 2425, "text": "using System;\nnamespace DemoApplication{\n class Program{\n public static void Main(){\n int number = 5;\n Console.WriteLine(\"Number: {0}\", number);\n var numberString = number.ToString(\"D4\");\n Console.WriteLine(\"Padded String: {0}\", numberString);\n Console.ReadLine();\n }\n }\n}" }, { "code": null, "e": 2784, "s": 2752, "text": "The output of the above code is" }, { "code": null, "e": 2814, "s": 2784, "text": "Number: 5\nPadded String: 0005" }, { "code": null, "e": 2850, "s": 2814, "text": "Example using string interpolation−" }, { "code": null, "e": 2861, "s": 2850, "text": " Live Demo" }, { "code": null, "e": 3183, "s": 2861, "text": "using System;\nnamespace DemoApplication{\n class Program{\n public static void Main(){\n int number = 5;\n Console.WriteLine(\"Number: {0}\", number);\n var numberString = $\"{number:0000}\";\n Console.WriteLine(\"Padded String: {0}\", numberString);\n Console.ReadLine();\n }\n }\n}" }, { "code": null, "e": 3215, "s": 3183, "text": "The output of the above code is" }, { "code": null, "e": 3245, "s": 3215, "text": "Number: 5\nPadded String: 0005" } ]
How to use an enum with switch case in Java?
Enumeration (enum) in Java is a datatype which stores a set of constant values. You can use enumerations to store fixed values such as days in a week, months in a year etc. enum Days { SUNDAY, MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY } You can also define an enumeration with custom values to the constants declared. But you need to have an instance variable, a constructor and getter method to return values. Let us create an enum with 5 constants representing models of 5 different scoters with their prices as values, as shown below − enum Scoters { //Constants with values ACTIVA125(80000), ACTIVA5G(70000), ACCESS125(75000), VESPA(90000), TVSJUPITER(75000); //Instance variable private int price; //Constructor to initialize the instance variable Scoters(int price) { this.price = price; } //Static method to display the price public static void getPrice(int model){ Scoters constants[] = Scoters.values(); System.out.println("Price of: "+constants[model]+" is "+constants[model].price); } } Following Java program retrieves the prices of all the vehicles using switch case. public class EnumExample { Scoters sc; public EnumExample(Scoters sc) { this.sc = sc; } public void displayPrice() { switch (sc) { case Activa125: Scoters.getPrice(0); break; case Activa5G: Scoters.getPrice(1); break; case Access125: Scoters.getPrice(2); break; case Vespa: Scoters.getPrice(3); break; case TVSJupiter: Scoters.getPrice(4); break; default: System.out.println("Model not found"); break; } } public static void main(String args[]) { EnumExample activa125 = new EnumExample(Scoters.ACTIVA125); activa125.displayPrice(); EnumExample activa5G = new EnumExample(Scoters.ACTIVA5G); activa5G.displayPrice(); EnumExample access125 = new EnumExample(Scoters.ACCESS125); access125.displayPrice(); EnumExample vespa = new EnumExample(Scoters.VESPA); vespa.displayPrice(); EnumExample tvsJupiter = new EnumExample(Scoters.TVSJUPITER); tvsJupiter.displayPrice(); } } Price of: ACTIVA125 is 80000 Price of: ACTIVA5G is 70000 Price of: ACCESS125 is 75000 Price of: VESPA is 90000 Price of: TVSJUPITER is 75000
[ { "code": null, "e": 1235, "s": 1062, "text": "Enumeration (enum) in Java is a datatype which stores a set of constant values. You can use enumerations to store fixed values such as days in a week, months in a year etc." }, { "code": null, "e": 1312, "s": 1235, "text": "enum Days {\nSUNDAY, MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY\n}" }, { "code": null, "e": 1486, "s": 1312, "text": "You can also define an enumeration with custom values to the constants declared. But you need to have an instance variable, a constructor and getter method to return values." }, { "code": null, "e": 1614, "s": 1486, "text": "Let us create an enum with 5 constants representing models of 5 different scoters with their prices as values, as shown below −" }, { "code": null, "e": 2121, "s": 1614, "text": "enum Scoters {\n //Constants with values\n ACTIVA125(80000), ACTIVA5G(70000), ACCESS125(75000), VESPA(90000), TVSJUPITER(75000);\n //Instance variable\n private int price;\n //Constructor to initialize the instance variable\n Scoters(int price) {\n this.price = price;\n }\n //Static method to display the price\n public static void getPrice(int model){\n Scoters constants[] = Scoters.values();\n System.out.println(\"Price of: \"+constants[model]+\" is \"+constants[model].price);\n }\n}" }, { "code": null, "e": 2204, "s": 2121, "text": "Following Java program retrieves the prices of all the vehicles using switch case." }, { "code": null, "e": 3372, "s": 2204, "text": "public class EnumExample {\n Scoters sc;\n\n public EnumExample(Scoters sc) {\n this.sc = sc;\n }\n\n public void displayPrice() {\n switch (sc) {\n case Activa125:\n Scoters.getPrice(0);\n break;\n case Activa5G:\n Scoters.getPrice(1);\n break;\n case Access125:\n Scoters.getPrice(2);\n break;\n case Vespa:\n Scoters.getPrice(3);\n break;\n case TVSJupiter:\n Scoters.getPrice(4);\n break;\n default:\n System.out.println(\"Model not found\");\n break;\n }\n }\n public static void main(String args[]) {\n EnumExample activa125 = new EnumExample(Scoters.ACTIVA125);\n activa125.displayPrice();\n EnumExample activa5G = new EnumExample(Scoters.ACTIVA5G);\n activa5G.displayPrice();\n EnumExample access125 = new EnumExample(Scoters.ACCESS125);\n access125.displayPrice();\n EnumExample vespa = new EnumExample(Scoters.VESPA);\n vespa.displayPrice();\n EnumExample tvsJupiter = new EnumExample(Scoters.TVSJUPITER);\n tvsJupiter.displayPrice();\n }\n}" }, { "code": null, "e": 3513, "s": 3372, "text": "Price of: ACTIVA125 is 80000\nPrice of: ACTIVA5G is 70000\nPrice of: ACCESS125 is 75000\nPrice of: VESPA is 90000\nPrice of: TVSJUPITER is 75000" } ]
List Comprehensions vs. For Loops: It is not what you think | Towards Data Science
Usual articles will perform the following case: create a list using a for loop versus a list comprehension. So let’s do it and time it. import timeiterations = 100000000start = time.time()mylist = []for i in range(iterations): mylist.append(i+1)end = time.time()print(end - start)>> 9.90 secondsstart = time.time()mylist = [i+1 for i in range(iterations)]end = time.time()print(end - start)>> 8.20 seconds As we can see, the for loop is slower than the list comprehension (9.9 seconds vs. 8.2 seconds). List comprehensions are faster than for loops to create lists. But, this is because we are creating a list by appending new elements to it at each iteration. This is slow. Side note: It would even be worse if it was a Numpy Array and not a list. The for loop would take minutes to run. But you shouldn’t blame the for loop for this: we are simply not using the right tool. myarray = np.array([])for i in range(iterations): myarray = np.append(myarray, i+1) Do not create numpy arrays by appending values in a loop. Suppose we only want to perform some computations (or call an independent function multiple times) and do not want to create a list. start = time.time()for i in range(iterations): i+1end = time.time()print(end - start)>> 6.16 secondsstart = time.time()[i+1 for i in range(iterations)]end = time.time()print(end - start)>> 7.80 seconds In that case, we see that the list comprehension is 25% slower than the for loop. For loops are faster than list comprehensions to run functions. One element is missing here: what’s faster than a for loop or a list comprehension? Array computations! Actually, it is a bad practice in Python to use for loops, list comprehensions, or .apply() in pandas. Instead, you should always prefer array computations. As you can see, we can create our list even faster using list(range()) start = time.time()mylist = list(range(iterations))end = time.time()print(end - start)>> 4.84 seconds It only took 4.84 seconds! This is 40% less time-intensive than our previous list comprehension (8.2 seconds). Moreover, creating a list using list(range(iterations)) is even faster than performing simple computations (6.16 seconds with for loops). If you want to perform some computation on a list of numbers, the best practice is not to use a list comprehension or a for loop but to perform array computations. Array computations are faster than loops. List comprehensions are the right tool to create lists — it is nevertheless better to use list(range()). For loops are the right tool to perform computations or run functions. In any case, avoid using for loops and list comprehensions altogether: use array computations instead. Creating the list with np.arange() (6.32 seconds) is 48% slower than using list(range()) (4.84 seconds). import numpy as npstart = time.time()mylist = np.arange(0, iterations).tolist()end = time.time()print(end - start)>> 6.32 seconds But, creating a numpy array using np.arange() is twice as fast as first creating a list and then saving it as a numpy array. start = time.time()mylist = np.array(list(range(iterations)))end = time.time()print(end - start)>> 10.14 seconds Once you have your numpy array you’ll be able to perform lightning-fast array computations.
[ { "code": null, "e": 308, "s": 172, "text": "Usual articles will perform the following case: create a list using a for loop versus a list comprehension. So let’s do it and time it." }, { "code": null, "e": 581, "s": 308, "text": "import timeiterations = 100000000start = time.time()mylist = []for i in range(iterations): mylist.append(i+1)end = time.time()print(end - start)>> 9.90 secondsstart = time.time()mylist = [i+1 for i in range(iterations)]end = time.time()print(end - start)>> 8.20 seconds" }, { "code": null, "e": 678, "s": 581, "text": "As we can see, the for loop is slower than the list comprehension (9.9 seconds vs. 8.2 seconds)." }, { "code": null, "e": 741, "s": 678, "text": "List comprehensions are faster than for loops to create lists." }, { "code": null, "e": 850, "s": 741, "text": "But, this is because we are creating a list by appending new elements to it at each iteration. This is slow." }, { "code": null, "e": 1051, "s": 850, "text": "Side note: It would even be worse if it was a Numpy Array and not a list. The for loop would take minutes to run. But you shouldn’t blame the for loop for this: we are simply not using the right tool." }, { "code": null, "e": 1138, "s": 1051, "text": "myarray = np.array([])for i in range(iterations): myarray = np.append(myarray, i+1)" }, { "code": null, "e": 1196, "s": 1138, "text": "Do not create numpy arrays by appending values in a loop." }, { "code": null, "e": 1329, "s": 1196, "text": "Suppose we only want to perform some computations (or call an independent function multiple times) and do not want to create a list." }, { "code": null, "e": 1534, "s": 1329, "text": "start = time.time()for i in range(iterations): i+1end = time.time()print(end - start)>> 6.16 secondsstart = time.time()[i+1 for i in range(iterations)]end = time.time()print(end - start)>> 7.80 seconds" }, { "code": null, "e": 1616, "s": 1534, "text": "In that case, we see that the list comprehension is 25% slower than the for loop." }, { "code": null, "e": 1680, "s": 1616, "text": "For loops are faster than list comprehensions to run functions." }, { "code": null, "e": 1941, "s": 1680, "text": "One element is missing here: what’s faster than a for loop or a list comprehension? Array computations! Actually, it is a bad practice in Python to use for loops, list comprehensions, or .apply() in pandas. Instead, you should always prefer array computations." }, { "code": null, "e": 2012, "s": 1941, "text": "As you can see, we can create our list even faster using list(range())" }, { "code": null, "e": 2114, "s": 2012, "text": "start = time.time()mylist = list(range(iterations))end = time.time()print(end - start)>> 4.84 seconds" }, { "code": null, "e": 2363, "s": 2114, "text": "It only took 4.84 seconds! This is 40% less time-intensive than our previous list comprehension (8.2 seconds). Moreover, creating a list using list(range(iterations)) is even faster than performing simple computations (6.16 seconds with for loops)." }, { "code": null, "e": 2527, "s": 2363, "text": "If you want to perform some computation on a list of numbers, the best practice is not to use a list comprehension or a for loop but to perform array computations." }, { "code": null, "e": 2569, "s": 2527, "text": "Array computations are faster than loops." }, { "code": null, "e": 2848, "s": 2569, "text": "List comprehensions are the right tool to create lists — it is nevertheless better to use list(range()). For loops are the right tool to perform computations or run functions. In any case, avoid using for loops and list comprehensions altogether: use array computations instead." }, { "code": null, "e": 2953, "s": 2848, "text": "Creating the list with np.arange() (6.32 seconds) is 48% slower than using list(range()) (4.84 seconds)." }, { "code": null, "e": 3083, "s": 2953, "text": "import numpy as npstart = time.time()mylist = np.arange(0, iterations).tolist()end = time.time()print(end - start)>> 6.32 seconds" }, { "code": null, "e": 3208, "s": 3083, "text": "But, creating a numpy array using np.arange() is twice as fast as first creating a list and then saving it as a numpy array." }, { "code": null, "e": 3321, "s": 3208, "text": "start = time.time()mylist = np.array(list(range(iterations)))end = time.time()print(end - start)>> 10.14 seconds" } ]
Introduction to Pandas DataFrames | by Rebecca Vickery | Towards Data Science
Pandas is a python package designed for fast and flexible data processing, manipulation and analysis. Pandas has a number of fundamental data structures (a data management and storage format). If you are working with two-dimensional labelled data, which is data that has both columns and rows with row headers — similar to a spreadsheet table, then the DataFrame is the data structure that you will use with Pandas. In the following article, I will be giving an introduction to some of the most common data processing and manipulation methods available in this package. Throughout this tutorial, I will be using a dataset from drivendata.org, a machine learning competition website. The dataset can be downloaded here. The dataset comprises a set of training data for fitting a machine learning model and a test data file for making predictions. For the purposes of this article, as I am only performing preprocessing and analysis I will only be using the training data. The first step when working with data using Pandas is to read the data into your editor, throughout this article I will be using Jupyter Notebooks. Pandas provides methods for most types of data imports. To obtain data from a CSV file you can use the pandas.read_csv() function. The features (values) and labels in the dataset we are using are in separate files so we will read both in and will learn how to merge them together a bit later. import pandas as pdtrain_values = pd.read_csv('train_values.csv')train_labels = pd.read_csv('train_labels.csv') Pandas also has functions to read data from a variety of other sources including: Excel — pandas.read_excel(). JSON — pandas.read_json(). SQL — pandas.read_sql(). Google BigQuery — pandas.read_gbq(). When working on a data science project the data that you are working with will often be in multiple files and/or from multiple sources. There will often, therefore, be times when you need to combine datasets. There are a number of ways you might want to do this and pandas has a method for each. Merge If you have had previous experience working with SQL queries then this method will be quite familiar. Merging is the process of joining two datasets together via a common identifier, similar to a join in SQL. In the case of our datasets, we have a train_values dataset and a train_labels dataset each with the same building_id per row which is referred to as the key. The merge function takes a number of arguments but the three we need to pay attention to for combining our datasets is how and on. A full list of arguments and their explanations can be found here. The how argument refers to the method that determines which keys should appear in the resulting data set. For example, you may have rows in the values dataset which do not appear in the labels dataset. If this was the case we would need to determine which rows to keep. There are four variables for the how argument. left — this argument would keep only the keys from the left data frame. right — this would only keep key from the right data frame. outer — will keep all keys from both data frames including non-matching rows. inner — will keep all keys from both data frames but will not include non-matching rows. The below code joins the two data frames with an inner join using building_id in the on argument. train_data = pd.merge(train_values, train_labels, how='inner', on=['building_id', 'building_id']) Concatenate The concat() function in pandas is another method for combining data frames. However, rather than joining on a common key concat() effectively glues the data frames together either by adding columns to columns or rows to rows referred to as the axis. As our two datasets have the exact same indexes we can use the concat function to combine them as a direct replacement for merge. In the below, we pass the two data frames as a list and specify axis=1 which tells the function that we want to concatenate on columns. The downside of concat in our case is that we now have two occurrences of the building_id column. train_data_concat = pd.concat([train_values, train_labels], axis=1) One of the most common problems in data sets is missing data. Pandas has a number of methods for handling missing values in data frames. For dealing with missing data we have a number of options. Drop all the rows containing missing data in any column. Drop the column or columns containing missing data. Impute the missing value with a sensible replacement this could be a 0 or perhaps the median value for the remaining data in the column. Pandas has methods to perform each of these. Firstly to detect if there are missing values pandas has the isna() function. This returns True if the value is missing and False if not. We can use this to determine the volume of missing values per column as shown below. train_data.apply(lambda x: sum(x.isna()) / len(train_data)) Our data set doesn’t actually have any missing values but let's work through examples of how we might handle them if we did. The Pandas function drop_na() drops rows or columns (depending on the parameter you choose) that contain missing values. This function takes the axis parameter which you set as 0 to drop rows, and 1 to drop columns. The alternative function is fillna() . This function will replace missing values with the value of your choice. You can replace with a fixed value such as 0, or you can use a calculation such as the mean. You can also apply different values to different columns by passing a dictionary of values per column. The below code fills any missing values with the mode for that column. train_data_numeric = train_data.apply(lambda x: x.fillna(x.mode()),axis=0) During both data analysis and preprocessing, there will be many occasions when you will want to select a subset of your data. You may want to select specific columns, a subset of rows or create subsets of your data based on specific conditions. Pandas provides a variety of methods for performing these tasks. To select subsets and rows of data from your data frame based on either labels or positions pandas has two methods loc and iloc. The loc method selects rows based on the index label. Let’s walk through a quick example. This is our data frame. The index is the column of numbers to the left of the building_id column. In pandas, we always count from 0 so if we want to select the first three rows using loc we run the following. subset_loc = train_data.loc[[0, 1, 2]]subset_loc.head() This gives us the first three rows. The iloc method select rows by the index position. This might be used, for example, if the user does not know the index or if the index is not numeric. Selecting the first three rows looks very similar to the loc method. subset_iloc = train_data.iloc[[0, 1, 2]]subset_iloc.head() To select rows based on specific conditions we can use the where()function. This is very similar to the where clause in a SQL query. A few examples are shown below. To select data based on a boolean condition. The below code selects only the rows where the value in the columnhas_superstructure_cement_mortar_brick is 1. has_cement_mortar_brick = train_data[train_data['has_superstructure_cement_mortar_brick'] == 1]has_cement_mortar_brick.head() To select data based on a numerical condition. The below code selects only the rows where the value of the age column is greater than 50. has_age_greater_than_50 = train_data[train_data['age'] > 50]has_age_greater_than_50.head() You can combine multiple conditions as shown below. two_conditions = train_data_concat[train_data['has_superstructure_cement_mortar_brick'] == 1 & (train_data['age'] > 50)]two_conditions.head() This article has given a brief introduction to pandas data frames and some of the most common tasks you may perform on them. The Pandas user guide is an excellent reference point to find out more about these and other methods available in the library. If you are interested in finding out more about how to analyse data with the Pandas package I have written another article which can be found here. Thanks for reading! I send out a monthly newsletter if you would like to join please sign up via this link. Looking forward to being part of your learning journey!
[ { "code": null, "e": 587, "s": 171, "text": "Pandas is a python package designed for fast and flexible data processing, manipulation and analysis. Pandas has a number of fundamental data structures (a data management and storage format). If you are working with two-dimensional labelled data, which is data that has both columns and rows with row headers — similar to a spreadsheet table, then the DataFrame is the data structure that you will use with Pandas." }, { "code": null, "e": 741, "s": 587, "text": "In the following article, I will be giving an introduction to some of the most common data processing and manipulation methods available in this package." }, { "code": null, "e": 890, "s": 741, "text": "Throughout this tutorial, I will be using a dataset from drivendata.org, a machine learning competition website. The dataset can be downloaded here." }, { "code": null, "e": 1142, "s": 890, "text": "The dataset comprises a set of training data for fitting a machine learning model and a test data file for making predictions. For the purposes of this article, as I am only performing preprocessing and analysis I will only be using the training data." }, { "code": null, "e": 1290, "s": 1142, "text": "The first step when working with data using Pandas is to read the data into your editor, throughout this article I will be using Jupyter Notebooks." }, { "code": null, "e": 1346, "s": 1290, "text": "Pandas provides methods for most types of data imports." }, { "code": null, "e": 1583, "s": 1346, "text": "To obtain data from a CSV file you can use the pandas.read_csv() function. The features (values) and labels in the dataset we are using are in separate files so we will read both in and will learn how to merge them together a bit later." }, { "code": null, "e": 1695, "s": 1583, "text": "import pandas as pdtrain_values = pd.read_csv('train_values.csv')train_labels = pd.read_csv('train_labels.csv')" }, { "code": null, "e": 1777, "s": 1695, "text": "Pandas also has functions to read data from a variety of other sources including:" }, { "code": null, "e": 1806, "s": 1777, "text": "Excel — pandas.read_excel()." }, { "code": null, "e": 1833, "s": 1806, "text": "JSON — pandas.read_json()." }, { "code": null, "e": 1858, "s": 1833, "text": "SQL — pandas.read_sql()." }, { "code": null, "e": 1895, "s": 1858, "text": "Google BigQuery — pandas.read_gbq()." }, { "code": null, "e": 2191, "s": 1895, "text": "When working on a data science project the data that you are working with will often be in multiple files and/or from multiple sources. There will often, therefore, be times when you need to combine datasets. There are a number of ways you might want to do this and pandas has a method for each." }, { "code": null, "e": 2197, "s": 2191, "text": "Merge" }, { "code": null, "e": 2406, "s": 2197, "text": "If you have had previous experience working with SQL queries then this method will be quite familiar. Merging is the process of joining two datasets together via a common identifier, similar to a join in SQL." }, { "code": null, "e": 2565, "s": 2406, "text": "In the case of our datasets, we have a train_values dataset and a train_labels dataset each with the same building_id per row which is referred to as the key." }, { "code": null, "e": 2763, "s": 2565, "text": "The merge function takes a number of arguments but the three we need to pay attention to for combining our datasets is how and on. A full list of arguments and their explanations can be found here." }, { "code": null, "e": 3080, "s": 2763, "text": "The how argument refers to the method that determines which keys should appear in the resulting data set. For example, you may have rows in the values dataset which do not appear in the labels dataset. If this was the case we would need to determine which rows to keep. There are four variables for the how argument." }, { "code": null, "e": 3152, "s": 3080, "text": "left — this argument would keep only the keys from the left data frame." }, { "code": null, "e": 3212, "s": 3152, "text": "right — this would only keep key from the right data frame." }, { "code": null, "e": 3290, "s": 3212, "text": "outer — will keep all keys from both data frames including non-matching rows." }, { "code": null, "e": 3379, "s": 3290, "text": "inner — will keep all keys from both data frames but will not include non-matching rows." }, { "code": null, "e": 3477, "s": 3379, "text": "The below code joins the two data frames with an inner join using building_id in the on argument." }, { "code": null, "e": 3575, "s": 3477, "text": "train_data = pd.merge(train_values, train_labels, how='inner', on=['building_id', 'building_id'])" }, { "code": null, "e": 3587, "s": 3575, "text": "Concatenate" }, { "code": null, "e": 3838, "s": 3587, "text": "The concat() function in pandas is another method for combining data frames. However, rather than joining on a common key concat() effectively glues the data frames together either by adding columns to columns or rows to rows referred to as the axis." }, { "code": null, "e": 4202, "s": 3838, "text": "As our two datasets have the exact same indexes we can use the concat function to combine them as a direct replacement for merge. In the below, we pass the two data frames as a list and specify axis=1 which tells the function that we want to concatenate on columns. The downside of concat in our case is that we now have two occurrences of the building_id column." }, { "code": null, "e": 4270, "s": 4202, "text": "train_data_concat = pd.concat([train_values, train_labels], axis=1)" }, { "code": null, "e": 4407, "s": 4270, "text": "One of the most common problems in data sets is missing data. Pandas has a number of methods for handling missing values in data frames." }, { "code": null, "e": 4466, "s": 4407, "text": "For dealing with missing data we have a number of options." }, { "code": null, "e": 4523, "s": 4466, "text": "Drop all the rows containing missing data in any column." }, { "code": null, "e": 4575, "s": 4523, "text": "Drop the column or columns containing missing data." }, { "code": null, "e": 4712, "s": 4575, "text": "Impute the missing value with a sensible replacement this could be a 0 or perhaps the median value for the remaining data in the column." }, { "code": null, "e": 4757, "s": 4712, "text": "Pandas has methods to perform each of these." }, { "code": null, "e": 4980, "s": 4757, "text": "Firstly to detect if there are missing values pandas has the isna() function. This returns True if the value is missing and False if not. We can use this to determine the volume of missing values per column as shown below." }, { "code": null, "e": 5040, "s": 4980, "text": "train_data.apply(lambda x: sum(x.isna()) / len(train_data))" }, { "code": null, "e": 5165, "s": 5040, "text": "Our data set doesn’t actually have any missing values but let's work through examples of how we might handle them if we did." }, { "code": null, "e": 5381, "s": 5165, "text": "The Pandas function drop_na() drops rows or columns (depending on the parameter you choose) that contain missing values. This function takes the axis parameter which you set as 0 to drop rows, and 1 to drop columns." }, { "code": null, "e": 5689, "s": 5381, "text": "The alternative function is fillna() . This function will replace missing values with the value of your choice. You can replace with a fixed value such as 0, or you can use a calculation such as the mean. You can also apply different values to different columns by passing a dictionary of values per column." }, { "code": null, "e": 5760, "s": 5689, "text": "The below code fills any missing values with the mode for that column." }, { "code": null, "e": 5835, "s": 5760, "text": "train_data_numeric = train_data.apply(lambda x: x.fillna(x.mode()),axis=0)" }, { "code": null, "e": 6145, "s": 5835, "text": "During both data analysis and preprocessing, there will be many occasions when you will want to select a subset of your data. You may want to select specific columns, a subset of rows or create subsets of your data based on specific conditions. Pandas provides a variety of methods for performing these tasks." }, { "code": null, "e": 6274, "s": 6145, "text": "To select subsets and rows of data from your data frame based on either labels or positions pandas has two methods loc and iloc." }, { "code": null, "e": 6364, "s": 6274, "text": "The loc method selects rows based on the index label. Let’s walk through a quick example." }, { "code": null, "e": 6462, "s": 6364, "text": "This is our data frame. The index is the column of numbers to the left of the building_id column." }, { "code": null, "e": 6573, "s": 6462, "text": "In pandas, we always count from 0 so if we want to select the first three rows using loc we run the following." }, { "code": null, "e": 6629, "s": 6573, "text": "subset_loc = train_data.loc[[0, 1, 2]]subset_loc.head()" }, { "code": null, "e": 6665, "s": 6629, "text": "This gives us the first three rows." }, { "code": null, "e": 6817, "s": 6665, "text": "The iloc method select rows by the index position. This might be used, for example, if the user does not know the index or if the index is not numeric." }, { "code": null, "e": 6886, "s": 6817, "text": "Selecting the first three rows looks very similar to the loc method." }, { "code": null, "e": 6945, "s": 6886, "text": "subset_iloc = train_data.iloc[[0, 1, 2]]subset_iloc.head()" }, { "code": null, "e": 7110, "s": 6945, "text": "To select rows based on specific conditions we can use the where()function. This is very similar to the where clause in a SQL query. A few examples are shown below." }, { "code": null, "e": 7266, "s": 7110, "text": "To select data based on a boolean condition. The below code selects only the rows where the value in the columnhas_superstructure_cement_mortar_brick is 1." }, { "code": null, "e": 7392, "s": 7266, "text": "has_cement_mortar_brick = train_data[train_data['has_superstructure_cement_mortar_brick'] == 1]has_cement_mortar_brick.head()" }, { "code": null, "e": 7530, "s": 7392, "text": "To select data based on a numerical condition. The below code selects only the rows where the value of the age column is greater than 50." }, { "code": null, "e": 7621, "s": 7530, "text": "has_age_greater_than_50 = train_data[train_data['age'] > 50]has_age_greater_than_50.head()" }, { "code": null, "e": 7673, "s": 7621, "text": "You can combine multiple conditions as shown below." }, { "code": null, "e": 7815, "s": 7673, "text": "two_conditions = train_data_concat[train_data['has_superstructure_cement_mortar_brick'] == 1 & (train_data['age'] > 50)]two_conditions.head()" }, { "code": null, "e": 8215, "s": 7815, "text": "This article has given a brief introduction to pandas data frames and some of the most common tasks you may perform on them. The Pandas user guide is an excellent reference point to find out more about these and other methods available in the library. If you are interested in finding out more about how to analyse data with the Pandas package I have written another article which can be found here." }, { "code": null, "e": 8235, "s": 8215, "text": "Thanks for reading!" } ]
Different Types of Recursion in Golang - GeeksforGeeks
10 Jul, 2020 Recursion is a concept where a function calls itself by direct or indirect means. Each call to the recursive function is a smaller version so that it converges at some point. Every recursive function has a base case or base condition which is the final executable statement in recursion and halts further calls. There are different types of recursion as explained in the following examples: Type of recursion where the function calls itself directly, without the assistance of another function is called a direct recursion. The following example explains the concept of direct recursion: Example: // Golang program to illustrate the// concept of direct recursionpackage main import ( "fmt") // recursive function for // calculating a factorial // of a positive integerfunc factorial_calc(number int) int { // this is the base condition // if number is 0 or 1 the // function will return 1 if number == 0 || number == 1 { return 1 } // if negative argument is // given, it prints error // message and returns -1 if number < 0 { fmt.Println("Invalid number") return -1 } // recursive call to itself // with argument decremented // by 1 integer so that it // eventually reaches the base case return number*factorial_calc(number - 1)} // the main functionfunc main() { // passing 0 as a parameter answer1 := factorial_calc(0) fmt.Println(answer1, "\n") // passing a positive integer answer2 := factorial_calc(5) fmt.Println(answer2, "\n") // passing a negative integer // prints an error message // with a return value of -1 answer3 := factorial_calc(-1) fmt.Println(answer3, "\n") // passing a positive integer answer4 := factorial_calc(10) fmt.Println(answer4, "\n")} Output: 1 120 Invalid number -1 3628800 The type of recursion where the function calls another function and this function, in turn, calls the calling function is called an indirect recursion. This type of recursion takes the assistance of another function. The function does call itself, but indirectly, i.e., through another function. The following example explains the concept of indirect recursion: Example: // Golang program to illustrate the// concept of indirect recursionpackage main import ( "fmt") // recursive function for // printing all numbers // upto the number nfunc print_one(n int) { // if the number is positive // print the number and call // the second function if n >= 0 { fmt.Println("In first function:", n) // call to the second function // which calls this first // function indirectly print_two(n - 1) }} func print_two(n int) { // if the number is positive // print the number and call // the second function if n >= 0 { fmt.Println("In second function:", n) // call to the first function print_one(n - 1) }} // main functionfunc main() { // passing a positive // parameter which prints all // numbers from 1 - 10 print_one(10) // this will not print // anything as it does not // follow the base case print_one(-1)} Output: In first function: 10 In second function: 9 In first function: 8 In second function: 7 In first function: 6 In second function: 5 In first function: 4 In second function: 3 In first function: 2 In second function: 1 In first function: 0 Note: An indirect recursion with only 2 functions is called mutual recursion. There can be more than 2 functions to facilitate indirect recursion. A tail call is a subroutine call which is the last or final call of the function. When a tail call performs a call to the same function, the function is said to be tail-recursive. Here, the recursive call is the last thing executed by the function. Example: // Golang program to illustrate the// concept of tail recursionpackage main import ( "fmt") // tail recursive function// to print all numbers // from n to 1func print_num(n int) { // if number is still // positive, print it // and call the function // with decremented value if n > 0 { fmt.Println(n) // last statement in // the recursive function // tail recursive call print_num(n-1) }} // main functionfunc main() { // passing a positive // number, prints 5 to 1 print_num(5)} Output: 5 4 3 2 1 In a head recursion, the recursive call is the first statement in the function. There is no other statement or operation before the call. The function does not have to process anything at the time of calling and all operations are done at returning time. Example: // Golang program to illustrate the// concept of head recursionpackage main import ( "fmt") // head recursive function// to print all numbers // from 1 to nfunc print_num(n int) { // if number is still // less than n, call // the function // with decremented value if n > 0 { // first statement in // the function print_num(n-1) // printing is done at // returning time fmt.Println(n) }} // main functionfunc main() { // passing a positive // number, prints 5 to 1 print_num(5)} Output: 1 2 3 4 5 Note: Output of head recursion is exactly the reverse of that of tail recursion. This is because the tail recursion first prints the number and then calls itself, whereas, in head recursion, the function keeps calling itself until it reaches the base case and then starts printing during returning. All the recursive functions were definite or finite recursive functions, i.e., they halted on reaching a base condition. Infinite recursion is a type of recursion that goes on until infinity and never converges to a base case. This often results in system crashing or memory overflows. Example: // Golang program to illustrate the// concept of infinite recursionpackage main import ( "fmt") // infinite recursion functionfunc print_hello() { // printing infinite times fmt.Println("GeeksforGeeks") print_hello()} // main functionfunc main() { // call to infinite // recursive function print_hello()} Output: GeeksforGeeks GeeksforGeeks GeeksforGeeks ..... infinite times In Golang, there is a concept of functions which do not have a name. Such functions are called anonymous functions. Recursion can also be carried out using anonymous functions in Golang as shown below: Example: // Golang program to illustrate // the concept of anonymous // function recursionpackage main import ( "fmt") // main functionfunc main() { // declaring anonymous function // that takes an integer value var anon_func func(int) // defining an anonymous // function that prints // numbers from n to 1 anon_func = func(number int) { // base case if number == 0 { return } else { fmt.Println(number) // calling anonymous // function recursively anon_func(number-1) } } // call to anonymous // recursive function anon_func(5)} Output: 5 4 3 2 1 Go Language Recursion Recursion Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments strings.Replace() Function in Golang With Examples Arrays in Go How to Split a String in Golang? Slices in Golang Golang Maps Write a program to print all permutations of a given string Given an array A[] and a number x, check for pair in A[] with sum as x (aka Two Sum) Recursion Program for Tower of Hanoi Program for Sum of the digits of a given number
[ { "code": null, "e": 24083, "s": 24055, "text": "\n10 Jul, 2020" }, { "code": null, "e": 24395, "s": 24083, "text": "Recursion is a concept where a function calls itself by direct or indirect means. Each call to the recursive function is a smaller version so that it converges at some point. Every recursive function has a base case or base condition which is the final executable statement in recursion and halts further calls." }, { "code": null, "e": 24474, "s": 24395, "text": "There are different types of recursion as explained in the following examples:" }, { "code": null, "e": 24671, "s": 24474, "text": "Type of recursion where the function calls itself directly, without the assistance of another function is called a direct recursion. The following example explains the concept of direct recursion:" }, { "code": null, "e": 24680, "s": 24671, "text": "Example:" }, { "code": "// Golang program to illustrate the// concept of direct recursionpackage main import ( \"fmt\") // recursive function for // calculating a factorial // of a positive integerfunc factorial_calc(number int) int { // this is the base condition // if number is 0 or 1 the // function will return 1 if number == 0 || number == 1 { return 1 } // if negative argument is // given, it prints error // message and returns -1 if number < 0 { fmt.Println(\"Invalid number\") return -1 } // recursive call to itself // with argument decremented // by 1 integer so that it // eventually reaches the base case return number*factorial_calc(number - 1)} // the main functionfunc main() { // passing 0 as a parameter answer1 := factorial_calc(0) fmt.Println(answer1, \"\\n\") // passing a positive integer answer2 := factorial_calc(5) fmt.Println(answer2, \"\\n\") // passing a negative integer // prints an error message // with a return value of -1 answer3 := factorial_calc(-1) fmt.Println(answer3, \"\\n\") // passing a positive integer answer4 := factorial_calc(10) fmt.Println(answer4, \"\\n\")}", "e": 25899, "s": 24680, "text": null }, { "code": null, "e": 25907, "s": 25899, "text": "Output:" }, { "code": null, "e": 25946, "s": 25907, "text": "1 \n\n120 \n\nInvalid number\n-1 \n\n3628800\n" }, { "code": null, "e": 26308, "s": 25946, "text": "The type of recursion where the function calls another function and this function, in turn, calls the calling function is called an indirect recursion. This type of recursion takes the assistance of another function. The function does call itself, but indirectly, i.e., through another function. The following example explains the concept of indirect recursion:" }, { "code": null, "e": 26317, "s": 26308, "text": "Example:" }, { "code": "// Golang program to illustrate the// concept of indirect recursionpackage main import ( \"fmt\") // recursive function for // printing all numbers // upto the number nfunc print_one(n int) { // if the number is positive // print the number and call // the second function if n >= 0 { fmt.Println(\"In first function:\", n) // call to the second function // which calls this first // function indirectly print_two(n - 1) }} func print_two(n int) { // if the number is positive // print the number and call // the second function if n >= 0 { fmt.Println(\"In second function:\", n) // call to the first function print_one(n - 1) }} // main functionfunc main() { // passing a positive // parameter which prints all // numbers from 1 - 10 print_one(10) // this will not print // anything as it does not // follow the base case print_one(-1)}", "e": 27291, "s": 26317, "text": null }, { "code": null, "e": 27299, "s": 27291, "text": "Output:" }, { "code": null, "e": 27537, "s": 27299, "text": "In first function: 10\nIn second function: 9\nIn first function: 8\nIn second function: 7\nIn first function: 6\nIn second function: 5\nIn first function: 4\nIn second function: 3\nIn first function: 2\nIn second function: 1\nIn first function: 0\n" }, { "code": null, "e": 27684, "s": 27537, "text": "Note: An indirect recursion with only 2 functions is called mutual recursion. There can be more than 2 functions to facilitate indirect recursion." }, { "code": null, "e": 27933, "s": 27684, "text": "A tail call is a subroutine call which is the last or final call of the function. When a tail call performs a call to the same function, the function is said to be tail-recursive. Here, the recursive call is the last thing executed by the function." }, { "code": null, "e": 27942, "s": 27933, "text": "Example:" }, { "code": "// Golang program to illustrate the// concept of tail recursionpackage main import ( \"fmt\") // tail recursive function// to print all numbers // from n to 1func print_num(n int) { // if number is still // positive, print it // and call the function // with decremented value if n > 0 { fmt.Println(n) // last statement in // the recursive function // tail recursive call print_num(n-1) }} // main functionfunc main() { // passing a positive // number, prints 5 to 1 print_num(5)}", "e": 28515, "s": 27942, "text": null }, { "code": null, "e": 28523, "s": 28515, "text": "Output:" }, { "code": null, "e": 28534, "s": 28523, "text": "5\n4\n3\n2\n1\n" }, { "code": null, "e": 28789, "s": 28534, "text": "In a head recursion, the recursive call is the first statement in the function. There is no other statement or operation before the call. The function does not have to process anything at the time of calling and all operations are done at returning time." }, { "code": null, "e": 28798, "s": 28789, "text": "Example:" }, { "code": "// Golang program to illustrate the// concept of head recursionpackage main import ( \"fmt\") // head recursive function// to print all numbers // from 1 to nfunc print_num(n int) { // if number is still // less than n, call // the function // with decremented value if n > 0 { // first statement in // the function print_num(n-1) // printing is done at // returning time fmt.Println(n) }} // main functionfunc main() { // passing a positive // number, prints 5 to 1 print_num(5)}", "e": 29388, "s": 28798, "text": null }, { "code": null, "e": 29396, "s": 29388, "text": "Output:" }, { "code": null, "e": 29407, "s": 29396, "text": "1\n2\n3\n4\n5\n" }, { "code": null, "e": 29706, "s": 29407, "text": "Note: Output of head recursion is exactly the reverse of that of tail recursion. This is because the tail recursion first prints the number and then calls itself, whereas, in head recursion, the function keeps calling itself until it reaches the base case and then starts printing during returning." }, { "code": null, "e": 29992, "s": 29706, "text": "All the recursive functions were definite or finite recursive functions, i.e., they halted on reaching a base condition. Infinite recursion is a type of recursion that goes on until infinity and never converges to a base case. This often results in system crashing or memory overflows." }, { "code": null, "e": 30001, "s": 29992, "text": "Example:" }, { "code": "// Golang program to illustrate the// concept of infinite recursionpackage main import ( \"fmt\") // infinite recursion functionfunc print_hello() { // printing infinite times fmt.Println(\"GeeksforGeeks\") print_hello()} // main functionfunc main() { // call to infinite // recursive function print_hello()}", "e": 30343, "s": 30001, "text": null }, { "code": null, "e": 30351, "s": 30343, "text": "Output:" }, { "code": null, "e": 30415, "s": 30351, "text": "GeeksforGeeks\nGeeksforGeeks\nGeeksforGeeks\n..... infinite times\n" }, { "code": null, "e": 30617, "s": 30415, "text": "In Golang, there is a concept of functions which do not have a name. Such functions are called anonymous functions. Recursion can also be carried out using anonymous functions in Golang as shown below:" }, { "code": null, "e": 30626, "s": 30617, "text": "Example:" }, { "code": "// Golang program to illustrate // the concept of anonymous // function recursionpackage main import ( \"fmt\") // main functionfunc main() { // declaring anonymous function // that takes an integer value var anon_func func(int) // defining an anonymous // function that prints // numbers from n to 1 anon_func = func(number int) { // base case if number == 0 { return } else { fmt.Println(number) // calling anonymous // function recursively anon_func(number-1) } } // call to anonymous // recursive function anon_func(5)}", "e": 31359, "s": 30626, "text": null }, { "code": null, "e": 31367, "s": 31359, "text": "Output:" }, { "code": null, "e": 31378, "s": 31367, "text": "5\n4\n3\n2\n1\n" }, { "code": null, "e": 31390, "s": 31378, "text": "Go Language" }, { "code": null, "e": 31400, "s": 31390, "text": "Recursion" }, { "code": null, "e": 31410, "s": 31400, "text": "Recursion" }, { "code": null, "e": 31508, "s": 31410, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 31517, "s": 31508, "text": "Comments" }, { "code": null, "e": 31530, "s": 31517, "text": "Old Comments" }, { "code": null, "e": 31581, "s": 31530, "text": "strings.Replace() Function in Golang With Examples" }, { "code": null, "e": 31594, "s": 31581, "text": "Arrays in Go" }, { "code": null, "e": 31627, "s": 31594, "text": "How to Split a String in Golang?" }, { "code": null, "e": 31644, "s": 31627, "text": "Slices in Golang" }, { "code": null, "e": 31656, "s": 31644, "text": "Golang Maps" }, { "code": null, "e": 31716, "s": 31656, "text": "Write a program to print all permutations of a given string" }, { "code": null, "e": 31801, "s": 31716, "text": "Given an array A[] and a number x, check for pair in A[] with sum as x (aka Two Sum)" }, { "code": null, "e": 31811, "s": 31801, "text": "Recursion" }, { "code": null, "e": 31838, "s": 31811, "text": "Program for Tower of Hanoi" } ]
Remove minimum elements from array so that max <= 2 * min
27 Dec, 2019 Given an array arr, the task is to remove minimum number of elements such that after their removal, max(arr) <= 2 * min(arr). Examples: Input: arr[] = {4, 5, 3, 8, 3}Output: 1Remove 8 from the array. Input: arr[] = {1, 2, 3, 4}Output: 1Remove 1 from the array. Approach: Let us fix each value as the minimum value say x and find number of terms that are in range [x, 2*x]. This can be done using prefix-sums, we can use map (implements self balancing BST) instead of array as the values can be large. The remaining terms which are not in range [x, 2*x] will have to be removed. So, across all values of x, we choose the one which maximises the number of terms in range [x, 2*x]. Below is the implementation of the above approach: C++ Python3 // C++ implementation of the approach#include <bits/stdc++.h>using namespace std; // Function to return the minimum removals from // arr such that max(arr) <= 2 * min(arr)int minimumRemovals(int n, int a[]){ // Count occurrence of each element map<int, int> ct; for (int i = 0; i < n; i++) ct[a[i]]++; // Take prefix sum int sm = 0; for (auto mn : ct) { sm += mn.second; ct[mn.first] = sm; } int mx = 0, prev = 0; for (auto mn : ct) { // Chosen minimum int x = mn.first; int y = 2 * x; auto itr = ct.upper_bound(y); itr--; // Number of elements that are in // range [x, 2x] int cr = (itr->second) - prev; mx = max(mx, cr); prev = mn.second; } // Minimum elements to be removed return n - mx;} // Driver Program to test above functionint main(){ int arr[] = { 4, 5, 3, 8, 3 }; int n = sizeof(arr) / sizeof(arr[0]); cout << minimumRemovals(n, arr); return 0;} # Python3 implementation of the approachfrom bisect import bisect_left as upper_bound # Function to return the minimum removals from# arr such that max(arr) <= 2 * min(arr)def minimumRemovals(n, a): # Count occurrence of each element ct = dict() for i in a: ct[i] = ct.get(i, 0) + 1 # Take prefix sum sm = 0 for mn in ct: sm += ct[mn] ct[mn] = sm mx = 0 prev = 0; for mn in ct: # Chosen minimum x = mn y = 2 * x itr = upper_bound(list(ct), y) # Number of elements that are in # range [x, 2x] cr = ct[itr] - prev mx = max(mx, cr) prev = ct[mn] # Minimum elements to be removed return n - mx # Driver Codearr = [4, 5, 3, 8, 3]n = len(arr)print(minimumRemovals(n, arr)) # This code is contributed by Mohit Kumar 1 mohit kumar 29 cpp-map Arrays Binary Search Tree Arrays Binary Search Tree Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Maximum and minimum of an array using minimum number of comparisons Top 50 Array Coding Problems for Interviews Multidimensional Arrays in Java Stack Data Structure (Introduction and Program) Linear Search Binary Search Tree | Set 1 (Search and Insertion) AVL Tree | Set 1 (Insertion) Binary Search Tree | Set 2 (Delete) A program to check if a binary tree is BST or not Construct BST from given preorder traversal | Set 1
[ { "code": null, "e": 54, "s": 26, "text": "\n27 Dec, 2019" }, { "code": null, "e": 180, "s": 54, "text": "Given an array arr, the task is to remove minimum number of elements such that after their removal, max(arr) <= 2 * min(arr)." }, { "code": null, "e": 190, "s": 180, "text": "Examples:" }, { "code": null, "e": 254, "s": 190, "text": "Input: arr[] = {4, 5, 3, 8, 3}Output: 1Remove 8 from the array." }, { "code": null, "e": 315, "s": 254, "text": "Input: arr[] = {1, 2, 3, 4}Output: 1Remove 1 from the array." }, { "code": null, "e": 733, "s": 315, "text": "Approach: Let us fix each value as the minimum value say x and find number of terms that are in range [x, 2*x]. This can be done using prefix-sums, we can use map (implements self balancing BST) instead of array as the values can be large. The remaining terms which are not in range [x, 2*x] will have to be removed. So, across all values of x, we choose the one which maximises the number of terms in range [x, 2*x]." }, { "code": null, "e": 784, "s": 733, "text": "Below is the implementation of the above approach:" }, { "code": null, "e": 788, "s": 784, "text": "C++" }, { "code": null, "e": 796, "s": 788, "text": "Python3" }, { "code": "// C++ implementation of the approach#include <bits/stdc++.h>using namespace std; // Function to return the minimum removals from // arr such that max(arr) <= 2 * min(arr)int minimumRemovals(int n, int a[]){ // Count occurrence of each element map<int, int> ct; for (int i = 0; i < n; i++) ct[a[i]]++; // Take prefix sum int sm = 0; for (auto mn : ct) { sm += mn.second; ct[mn.first] = sm; } int mx = 0, prev = 0; for (auto mn : ct) { // Chosen minimum int x = mn.first; int y = 2 * x; auto itr = ct.upper_bound(y); itr--; // Number of elements that are in // range [x, 2x] int cr = (itr->second) - prev; mx = max(mx, cr); prev = mn.second; } // Minimum elements to be removed return n - mx;} // Driver Program to test above functionint main(){ int arr[] = { 4, 5, 3, 8, 3 }; int n = sizeof(arr) / sizeof(arr[0]); cout << minimumRemovals(n, arr); return 0;}", "e": 1805, "s": 796, "text": null }, { "code": "# Python3 implementation of the approachfrom bisect import bisect_left as upper_bound # Function to return the minimum removals from# arr such that max(arr) <= 2 * min(arr)def minimumRemovals(n, a): # Count occurrence of each element ct = dict() for i in a: ct[i] = ct.get(i, 0) + 1 # Take prefix sum sm = 0 for mn in ct: sm += ct[mn] ct[mn] = sm mx = 0 prev = 0; for mn in ct: # Chosen minimum x = mn y = 2 * x itr = upper_bound(list(ct), y) # Number of elements that are in # range [x, 2x] cr = ct[itr] - prev mx = max(mx, cr) prev = ct[mn] # Minimum elements to be removed return n - mx # Driver Codearr = [4, 5, 3, 8, 3]n = len(arr)print(minimumRemovals(n, arr)) # This code is contributed by Mohit Kumar", "e": 2650, "s": 1805, "text": null }, { "code": null, "e": 2653, "s": 2650, "text": "1\n" }, { "code": null, "e": 2668, "s": 2653, "text": "mohit kumar 29" }, { "code": null, "e": 2676, "s": 2668, "text": "cpp-map" }, { "code": null, "e": 2683, "s": 2676, "text": "Arrays" }, { "code": null, "e": 2702, "s": 2683, "text": "Binary Search Tree" }, { "code": null, "e": 2709, "s": 2702, "text": "Arrays" }, { "code": null, "e": 2728, "s": 2709, "text": "Binary Search Tree" }, { "code": null, "e": 2826, "s": 2728, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 2894, "s": 2826, "text": "Maximum and minimum of an array using minimum number of comparisons" }, { "code": null, "e": 2938, "s": 2894, "text": "Top 50 Array Coding Problems for Interviews" }, { "code": null, "e": 2970, "s": 2938, "text": "Multidimensional Arrays in Java" }, { "code": null, "e": 3018, "s": 2970, "text": "Stack Data Structure (Introduction and Program)" }, { "code": null, "e": 3032, "s": 3018, "text": "Linear Search" }, { "code": null, "e": 3082, "s": 3032, "text": "Binary Search Tree | Set 1 (Search and Insertion)" }, { "code": null, "e": 3111, "s": 3082, "text": "AVL Tree | Set 1 (Insertion)" }, { "code": null, "e": 3147, "s": 3111, "text": "Binary Search Tree | Set 2 (Delete)" }, { "code": null, "e": 3197, "s": 3147, "text": "A program to check if a binary tree is BST or not" } ]
Java Program to Read a File to String
16 Jun, 2022 There are multiple ways of writing and reading a text file. This is required while dealing with many applications. There are several ways to read a plain text file in Java e.g. you can use FileReader, BufferedReader or Scanner to read a text file. Given a text file, the task is to read the contents of a file present in a local directory and storing it in a string. Consider a file present on the system namely say it be ‘gfg.txt’. Let the random content in the file be as inserted below in the pretag block. Now we will be discussing out various ways to achieve the same. The content inside file ‘gfg.txt’ is as shown in the illustration block. Illustration: Lines inside the file Geeks-for-Geeks A computer science portal World's largest technical hub Note: Save above text file to your local computer with .txt extension and use that path in the programs. Methods: There are several ways to achieve the goal and with the advancement of the version in java, specific methods are there laid out which are discussed sequentially. Methods: Using File.readString() methodUsing readLine() method of BufferReader classUsing File.readAllBytes() methodUsing File.lines() methodUsing Scanner class Using File.readString() method Using readLine() method of BufferReader class Using File.readAllBytes() method Using File.lines() method Using Scanner class Let us discuss each of them by implementing clean java programs in order to understand them. Method 1: Using File.readString() method The readString() method of File Class in Java is used to read contents to the specified file. Syntax: Files.readString(filePath) ; Parameters: File path with data type as Path Return Value: This method returns the content of the file in String format. Note: File.readString() method was introduced in Java 11 and this method is used to read a file’s content into String. Example Java // Java Program Illustrating Reading a File to a String// Using File.readString() method // Importing required classesimport java.io.*;import java.io.IOException;import java.nio.file.Files;import java.nio.file.Path; // Main classpublic class GFG { // Main driver method public static void main(String[] args) throws IOException { // Creating a path choosing file from local // directory by creating an object of Path class Path fileName = Path.of("C:\\Users\\HP\\Desktop\\gfg.txt"); // Now calling Files.readString() method to // read the file String str = Files.readString(fileName); // Printing the string System.out.println(str); }} Output: Geeks-for-Geeks A computer science portal World's largest technical hub Method 2: Using readLine() method of BufferReader class BufferedReader is an object used to read text from a character-input stream. The readLine() method present in BufferReader method is used to read the file one line at a time and return the content. Syntax: public String readLine() throws IOException Parameters: This method does not accept any parameter. Return value: This method returns the string that is read by this method and excludes any termination symbol available. If the buffered stream has ended and there is no line to be read then this method returns NULL. Exceptions: This method throws IOException if an I/O error occurs. Example Java // Java Program Illustrating Reading a File to a String// Using readLine() method of BufferReader class // Importing required classesimport java.io.*;import java.io.BufferedReader;import java.io.FileReader;import java.io.IOException; // MAin classpublic class GFG { // Method 1 // To read file content into the string // using BufferedReader and FileReader private static String method(String filePath) { // Declaring object of StringBuilder class StringBuilder builder = new StringBuilder(); // try block to check for exceptions where // object of BufferedReader class us created // to read filepath try (BufferedReader buffer = new BufferedReader( new FileReader(filePath))) { String str; // Condition check via buffer.readLine() method // holding true upto that the while loop runs while ((str = buffer.readLine()) != null) { builder.append(str).append("\n"); } } // Catch block to handle the exceptions catch (IOException e) { // Print the line number here exception occurred // using printStackTrace() method e.printStackTrace(); } // Returning a string return builder.toString(); } // Method 2 // Main driver method public static void main(String[] args) { // Custom input file path stored in string type String filePath = "C:\\Users\\HP\\Desktop\\gfg.txt"; // Calling the Method 1 to // read file to a string System.out.println(method(filePath)); }} Output: Geeks-for-Geeks A computer science portal World's largest technical hub Method 3: Using File.readAllBytes() method File.readAllBytes() method is used to read all the bytes from a file. The method ensures that the file is closed when all bytes have been read or an I/O error, or other runtime exception, is thrown. After reading all bytes, we pass those bytes to the string class constructor to create a string. Syntax: public static byte[] ReadAllBytes (string path); Parameter: Path which is the specified file to open for reading. Approach: Declaring an empty string get() method of Path class helps in fetching the file by passing as an argument to it. Now readAllBytes() method of the File class is used to read the above file by passing into it. Lastly, print the string. Exceptions: ArgumentException: The path is a zero-length string, contains only white space, or one or more invalid characters as defined by InvalidPathChars. ArgumentNullException: The path is null. PathTooLongException: The specified path, file name, or both exceed the system-defined maximum length. DirectoryNotFoundException: The specified path is invalid. IOException: An I/O error occurred while opening the file. UnauthorizedAccessException: This operation is not supported on the current platform. OR the path specified a directory. OR the caller does not have the required permission. FileNotFoundException: The file specified in the path was not found. NotSupportedException: The path is in an invalid format. SecurityException: The caller does not have the required permission. Example Java // Java Program Illustrating Reading a File to a String// Using File.readAllBytes() method // Importing required classesimport java.io.*;import java.io.IOException;import java.nio.file.Files;import java.nio.file.Paths; // Main classpublic class GFG { // Method 1 // To read the file content into string with // Files.readAllBytes(Path path) private static String method(String file_path) { // Declaring an empty string String str = ""; // Try block to check for exceptions try { // Reading all bytes form file and // storing that in the string str = new String( Files.readAllBytes(Paths.get(file_path))); } // Catch block to handle the exceptions catch (IOException e) { // Print the exception along with line number // using printStackTrace() method e.printStackTrace(); } return str; } // Method 2 // Main driver method public static void main(String[] args) { // Path is passed from local directory of machine // and stored in a string String filePath = "C:\\Users\\HP\\Desktop\\gfg.txt"; // Now call Method1 to // read the content in above directory System.out.println(method(filePath)); }} Output: Geeks-for-Geeks A computer science portal World's largest technical hub Method 4: Using File.lines() method File.lines() method is used to read all lines from a file to stream. Then the bytes from the file are decoded into characters using the specified charset like UTF_8. Syntax: public static Stream<String> lines(Path path, Charset cs) throws IOException Parameters: It generically takes two parameters: Charset to use for decoding. Path of the file. Return Type: The lines from the file as a string. Example Java // Java Program Illustrating Reading a File to a String// Using File.lines() method // Importing required classesimport java.io.*;import java.io.IOException;import java.nio.charset.StandardCharsets;import java.nio.file.Files;import java.nio.file.Paths;import java.util.stream.Stream; // Main classpublic class GFG { // Method 1 // To read the file content into the string with - // Files.lines() private static String method(String filePath) { // Declaring an object of StringBuilder class StringBuilder contentBuilder = new StringBuilder(); // try block to check for exceptions // Reading file to string using File.lines() method // and storing it in an object of Stream class try (Stream<String> stream = Files.lines(Paths.get(filePath), StandardCharsets.UTF_8)) { stream.forEach( s -> contentBuilder.append(s).append("\n")); } // Catch block to handle the exceptions catch (IOException e) { // Print the line number where exception occurred // using printStackTrace() method e.printStackTrace(); } // Returning the string builder by // calling tostring() method return contentBuilder.toString(); } // Method 2 // Main driver method public static void main(String[] args) { // Custom file path is stored as as string String filePath = "C:\\Users\\HP\\Desktop\\gfg.txt"; // Calling method 1 to read content of a file System.out.println(method(filePath)); }} Output: Geeks-for-Geeks A computer science portal World's largest technical hub Method 5: Using next() and hasNext() method of Scanner class Scanner class works by breaking the input into tokens that are sequentially retrieved from the input stream. Scanner class has two in build methods named next() and hasNext(). Both of these in-build methods return objects of type String. Example Java // Java Program Illustrating Reading a File to a String// Using next() and hasNext() method of Scanner class // Importing required classesimport java.io.*;import java.io.IOException;import java.nio.file.Path;import java.util.Scanner; // Main classpublic class GFG { // Main driver method public static void main(String[] args) throws IOException { // Creating object of Path class where custom local // directory path is passed as arguments using .of() // method Path fileName = Path.of("C:\\Users\\HP\\Desktop\\gfg.txt"); // Creating an object of Scanner class Scanner sc = new Scanner(fileName); // It holds true till there is single element left // via hasNext() method while (sc.hasNext()) { // Iterating over elements in object System.out.println(sc.next()); } // Closing scanner class object to avoid errors and // free up memory space sc.close(); }} Output: Geeks-for-Geeks A computer science portal World's largest technical hub simranarora5sos kashishsoda sagartomar9927 simmytarika5 nikhatkhan11 Java-Files Picked Java Java Programs Java Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. List Interface in Java with Examples Strings in Java Different ways of Reading a text file in Java Reverse an array in Java How to remove an element from ArrayList 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": 28, "s": 0, "text": "\n16 Jun, 2022" }, { "code": null, "e": 276, "s": 28, "text": "There are multiple ways of writing and reading a text file. This is required while dealing with many applications. There are several ways to read a plain text file in Java e.g. you can use FileReader, BufferedReader or Scanner to read a text file." }, { "code": null, "e": 675, "s": 276, "text": "Given a text file, the task is to read the contents of a file present in a local directory and storing it in a string. Consider a file present on the system namely say it be ‘gfg.txt’. Let the random content in the file be as inserted below in the pretag block. Now we will be discussing out various ways to achieve the same. The content inside file ‘gfg.txt’ is as shown in the illustration block." }, { "code": null, "e": 712, "s": 675, "text": "Illustration: Lines inside the file " }, { "code": null, "e": 784, "s": 712, "text": "Geeks-for-Geeks\nA computer science portal\nWorld's largest technical hub" }, { "code": null, "e": 890, "s": 784, "text": "Note: Save above text file to your local computer with .txt extension and use that path in the programs. " }, { "code": null, "e": 899, "s": 890, "text": "Methods:" }, { "code": null, "e": 1061, "s": 899, "text": "There are several ways to achieve the goal and with the advancement of the version in java, specific methods are there laid out which are discussed sequentially." }, { "code": null, "e": 1070, "s": 1061, "text": "Methods:" }, { "code": null, "e": 1222, "s": 1070, "text": "Using File.readString() methodUsing readLine() method of BufferReader classUsing File.readAllBytes() methodUsing File.lines() methodUsing Scanner class" }, { "code": null, "e": 1253, "s": 1222, "text": "Using File.readString() method" }, { "code": null, "e": 1299, "s": 1253, "text": "Using readLine() method of BufferReader class" }, { "code": null, "e": 1332, "s": 1299, "text": "Using File.readAllBytes() method" }, { "code": null, "e": 1358, "s": 1332, "text": "Using File.lines() method" }, { "code": null, "e": 1378, "s": 1358, "text": "Using Scanner class" }, { "code": null, "e": 1471, "s": 1378, "text": "Let us discuss each of them by implementing clean java programs in order to understand them." }, { "code": null, "e": 1512, "s": 1471, "text": "Method 1: Using File.readString() method" }, { "code": null, "e": 1606, "s": 1512, "text": "The readString() method of File Class in Java is used to read contents to the specified file." }, { "code": null, "e": 1614, "s": 1606, "text": "Syntax:" }, { "code": null, "e": 1643, "s": 1614, "text": "Files.readString(filePath) ;" }, { "code": null, "e": 1688, "s": 1643, "text": "Parameters: File path with data type as Path" }, { "code": null, "e": 1764, "s": 1688, "text": "Return Value: This method returns the content of the file in String format." }, { "code": null, "e": 1883, "s": 1764, "text": "Note: File.readString() method was introduced in Java 11 and this method is used to read a file’s content into String." }, { "code": null, "e": 1891, "s": 1883, "text": "Example" }, { "code": null, "e": 1896, "s": 1891, "text": "Java" }, { "code": "// Java Program Illustrating Reading a File to a String// Using File.readString() method // Importing required classesimport java.io.*;import java.io.IOException;import java.nio.file.Files;import java.nio.file.Path; // Main classpublic class GFG { // Main driver method public static void main(String[] args) throws IOException { // Creating a path choosing file from local // directory by creating an object of Path class Path fileName = Path.of(\"C:\\\\Users\\\\HP\\\\Desktop\\\\gfg.txt\"); // Now calling Files.readString() method to // read the file String str = Files.readString(fileName); // Printing the string System.out.println(str); }}", "e": 2623, "s": 1896, "text": null }, { "code": null, "e": 2632, "s": 2623, "text": "Output: " }, { "code": null, "e": 2704, "s": 2632, "text": "Geeks-for-Geeks\nA computer science portal\nWorld's largest technical hub" }, { "code": null, "e": 2760, "s": 2704, "text": "Method 2: Using readLine() method of BufferReader class" }, { "code": null, "e": 2958, "s": 2760, "text": "BufferedReader is an object used to read text from a character-input stream. The readLine() method present in BufferReader method is used to read the file one line at a time and return the content." }, { "code": null, "e": 2967, "s": 2958, "text": "Syntax: " }, { "code": null, "e": 3012, "s": 2967, "text": "public String readLine() \nthrows IOException" }, { "code": null, "e": 3067, "s": 3012, "text": "Parameters: This method does not accept any parameter." }, { "code": null, "e": 3283, "s": 3067, "text": "Return value: This method returns the string that is read by this method and excludes any termination symbol available. If the buffered stream has ended and there is no line to be read then this method returns NULL." }, { "code": null, "e": 3350, "s": 3283, "text": "Exceptions: This method throws IOException if an I/O error occurs." }, { "code": null, "e": 3359, "s": 3350, "text": "Example " }, { "code": null, "e": 3364, "s": 3359, "text": "Java" }, { "code": "// Java Program Illustrating Reading a File to a String// Using readLine() method of BufferReader class // Importing required classesimport java.io.*;import java.io.BufferedReader;import java.io.FileReader;import java.io.IOException; // MAin classpublic class GFG { // Method 1 // To read file content into the string // using BufferedReader and FileReader private static String method(String filePath) { // Declaring object of StringBuilder class StringBuilder builder = new StringBuilder(); // try block to check for exceptions where // object of BufferedReader class us created // to read filepath try (BufferedReader buffer = new BufferedReader( new FileReader(filePath))) { String str; // Condition check via buffer.readLine() method // holding true upto that the while loop runs while ((str = buffer.readLine()) != null) { builder.append(str).append(\"\\n\"); } } // Catch block to handle the exceptions catch (IOException e) { // Print the line number here exception occurred // using printStackTrace() method e.printStackTrace(); } // Returning a string return builder.toString(); } // Method 2 // Main driver method public static void main(String[] args) { // Custom input file path stored in string type String filePath = \"C:\\\\Users\\\\HP\\\\Desktop\\\\gfg.txt\"; // Calling the Method 1 to // read file to a string System.out.println(method(filePath)); }}", "e": 5004, "s": 3364, "text": null }, { "code": null, "e": 5013, "s": 5004, "text": "Output: " }, { "code": null, "e": 5085, "s": 5013, "text": "Geeks-for-Geeks\nA computer science portal\nWorld's largest technical hub" }, { "code": null, "e": 5128, "s": 5085, "text": "Method 3: Using File.readAllBytes() method" }, { "code": null, "e": 5424, "s": 5128, "text": "File.readAllBytes() method is used to read all the bytes from a file. The method ensures that the file is closed when all bytes have been read or an I/O error, or other runtime exception, is thrown. After reading all bytes, we pass those bytes to the string class constructor to create a string." }, { "code": null, "e": 5434, "s": 5424, "text": "Syntax: " }, { "code": null, "e": 5483, "s": 5434, "text": "public static byte[] ReadAllBytes (string path);" }, { "code": null, "e": 5548, "s": 5483, "text": "Parameter: Path which is the specified file to open for reading." }, { "code": null, "e": 5559, "s": 5548, "text": "Approach: " }, { "code": null, "e": 5585, "s": 5559, "text": "Declaring an empty string" }, { "code": null, "e": 5672, "s": 5585, "text": "get() method of Path class helps in fetching the file by passing as an argument to it." }, { "code": null, "e": 5767, "s": 5672, "text": "Now readAllBytes() method of the File class is used to read the above file by passing into it." }, { "code": null, "e": 5793, "s": 5767, "text": "Lastly, print the string." }, { "code": null, "e": 5805, "s": 5793, "text": "Exceptions:" }, { "code": null, "e": 5951, "s": 5805, "text": "ArgumentException: The path is a zero-length string, contains only white space, or one or more invalid characters as defined by InvalidPathChars." }, { "code": null, "e": 5992, "s": 5951, "text": "ArgumentNullException: The path is null." }, { "code": null, "e": 6095, "s": 5992, "text": "PathTooLongException: The specified path, file name, or both exceed the system-defined maximum length." }, { "code": null, "e": 6154, "s": 6095, "text": "DirectoryNotFoundException: The specified path is invalid." }, { "code": null, "e": 6213, "s": 6154, "text": "IOException: An I/O error occurred while opening the file." }, { "code": null, "e": 6387, "s": 6213, "text": "UnauthorizedAccessException: This operation is not supported on the current platform. OR the path specified a directory. OR the caller does not have the required permission." }, { "code": null, "e": 6456, "s": 6387, "text": "FileNotFoundException: The file specified in the path was not found." }, { "code": null, "e": 6513, "s": 6456, "text": "NotSupportedException: The path is in an invalid format." }, { "code": null, "e": 6582, "s": 6513, "text": "SecurityException: The caller does not have the required permission." }, { "code": null, "e": 6591, "s": 6582, "text": "Example " }, { "code": null, "e": 6596, "s": 6591, "text": "Java" }, { "code": "// Java Program Illustrating Reading a File to a String// Using File.readAllBytes() method // Importing required classesimport java.io.*;import java.io.IOException;import java.nio.file.Files;import java.nio.file.Paths; // Main classpublic class GFG { // Method 1 // To read the file content into string with // Files.readAllBytes(Path path) private static String method(String file_path) { // Declaring an empty string String str = \"\"; // Try block to check for exceptions try { // Reading all bytes form file and // storing that in the string str = new String( Files.readAllBytes(Paths.get(file_path))); } // Catch block to handle the exceptions catch (IOException e) { // Print the exception along with line number // using printStackTrace() method e.printStackTrace(); } return str; } // Method 2 // Main driver method public static void main(String[] args) { // Path is passed from local directory of machine // and stored in a string String filePath = \"C:\\\\Users\\\\HP\\\\Desktop\\\\gfg.txt\"; // Now call Method1 to // read the content in above directory System.out.println(method(filePath)); }}", "e": 7920, "s": 6596, "text": null }, { "code": null, "e": 7929, "s": 7920, "text": "Output: " }, { "code": null, "e": 8001, "s": 7929, "text": "Geeks-for-Geeks\nA computer science portal\nWorld's largest technical hub" }, { "code": null, "e": 8037, "s": 8001, "text": "Method 4: Using File.lines() method" }, { "code": null, "e": 8203, "s": 8037, "text": "File.lines() method is used to read all lines from a file to stream. Then the bytes from the file are decoded into characters using the specified charset like UTF_8." }, { "code": null, "e": 8212, "s": 8203, "text": "Syntax: " }, { "code": null, "e": 8289, "s": 8212, "text": "public static Stream<String> lines(Path path, Charset cs)\nthrows IOException" }, { "code": null, "e": 8339, "s": 8289, "text": "Parameters: It generically takes two parameters: " }, { "code": null, "e": 8368, "s": 8339, "text": "Charset to use for decoding." }, { "code": null, "e": 8386, "s": 8368, "text": "Path of the file." }, { "code": null, "e": 8436, "s": 8386, "text": "Return Type: The lines from the file as a string." }, { "code": null, "e": 8445, "s": 8436, "text": "Example " }, { "code": null, "e": 8450, "s": 8445, "text": "Java" }, { "code": "// Java Program Illustrating Reading a File to a String// Using File.lines() method // Importing required classesimport java.io.*;import java.io.IOException;import java.nio.charset.StandardCharsets;import java.nio.file.Files;import java.nio.file.Paths;import java.util.stream.Stream; // Main classpublic class GFG { // Method 1 // To read the file content into the string with - // Files.lines() private static String method(String filePath) { // Declaring an object of StringBuilder class StringBuilder contentBuilder = new StringBuilder(); // try block to check for exceptions // Reading file to string using File.lines() method // and storing it in an object of Stream class try (Stream<String> stream = Files.lines(Paths.get(filePath), StandardCharsets.UTF_8)) { stream.forEach( s -> contentBuilder.append(s).append(\"\\n\")); } // Catch block to handle the exceptions catch (IOException e) { // Print the line number where exception occurred // using printStackTrace() method e.printStackTrace(); } // Returning the string builder by // calling tostring() method return contentBuilder.toString(); } // Method 2 // Main driver method public static void main(String[] args) { // Custom file path is stored as as string String filePath = \"C:\\\\Users\\\\HP\\\\Desktop\\\\gfg.txt\"; // Calling method 1 to read content of a file System.out.println(method(filePath)); }}", "e": 10068, "s": 8450, "text": null }, { "code": null, "e": 10077, "s": 10068, "text": "Output: " }, { "code": null, "e": 10149, "s": 10077, "text": "Geeks-for-Geeks\nA computer science portal\nWorld's largest technical hub" }, { "code": null, "e": 10210, "s": 10149, "text": "Method 5: Using next() and hasNext() method of Scanner class" }, { "code": null, "e": 10449, "s": 10210, "text": "Scanner class works by breaking the input into tokens that are sequentially retrieved from the input stream. Scanner class has two in build methods named next() and hasNext(). Both of these in-build methods return objects of type String. " }, { "code": null, "e": 10458, "s": 10449, "text": "Example " }, { "code": null, "e": 10463, "s": 10458, "text": "Java" }, { "code": "// Java Program Illustrating Reading a File to a String// Using next() and hasNext() method of Scanner class // Importing required classesimport java.io.*;import java.io.IOException;import java.nio.file.Path;import java.util.Scanner; // Main classpublic class GFG { // Main driver method public static void main(String[] args) throws IOException { // Creating object of Path class where custom local // directory path is passed as arguments using .of() // method Path fileName = Path.of(\"C:\\\\Users\\\\HP\\\\Desktop\\\\gfg.txt\"); // Creating an object of Scanner class Scanner sc = new Scanner(fileName); // It holds true till there is single element left // via hasNext() method while (sc.hasNext()) { // Iterating over elements in object System.out.println(sc.next()); } // Closing scanner class object to avoid errors and // free up memory space sc.close(); }}", "e": 11469, "s": 10463, "text": null }, { "code": null, "e": 11477, "s": 11469, "text": "Output:" }, { "code": null, "e": 11549, "s": 11477, "text": "Geeks-for-Geeks\nA computer science portal\nWorld's largest technical hub" }, { "code": null, "e": 11565, "s": 11549, "text": "simranarora5sos" }, { "code": null, "e": 11577, "s": 11565, "text": "kashishsoda" }, { "code": null, "e": 11592, "s": 11577, "text": "sagartomar9927" }, { "code": null, "e": 11605, "s": 11592, "text": "simmytarika5" }, { "code": null, "e": 11618, "s": 11605, "text": "nikhatkhan11" }, { "code": null, "e": 11629, "s": 11618, "text": "Java-Files" }, { "code": null, "e": 11636, "s": 11629, "text": "Picked" }, { "code": null, "e": 11641, "s": 11636, "text": "Java" }, { "code": null, "e": 11655, "s": 11641, "text": "Java Programs" }, { "code": null, "e": 11660, "s": 11655, "text": "Java" }, { "code": null, "e": 11758, "s": 11660, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 11795, "s": 11758, "text": "List Interface in Java with Examples" }, { "code": null, "e": 11811, "s": 11795, "text": "Strings in Java" }, { "code": null, "e": 11857, "s": 11811, "text": "Different ways of Reading a text file in Java" }, { "code": null, "e": 11882, "s": 11857, "text": "Reverse an array in Java" }, { "code": null, "e": 11931, "s": 11882, "text": "How to remove an element from ArrayList in Java?" }, { "code": null, "e": 11957, "s": 11931, "text": "Java Programming Examples" }, { "code": null, "e": 11991, "s": 11957, "text": "Convert Double to Integer in Java" }, { "code": null, "e": 12038, "s": 11991, "text": "Implementing a Linked List in Java using Class" }, { "code": null, "e": 12076, "s": 12038, "text": "Factory method design pattern in Java" } ]
Difference between Insertion sort and Selection sort
29 Mar, 2022 In this article, we will discuss the difference between the Insertion sort and the Selection sort: Insertion sort is a simple sorting algorithm that works similar to the way you sort playing cards in your hands. The array is virtually split into a sorted and an unsorted part. Values from the unsorted part are picked and placed at the correct position in the sorted part. Algorithm: To sort an array of size n in ascending order: Iterate from arr[1] to arr[n] over the array. Compare the current element (key) to its predecessor. If the key element is smaller than its predecessor, compare it to the elements before. Move the greater elements one position up to make space for the swapped element. Below is the image to illustrate the Insertion Sort: Below is the program for the same: C++ Java Python3 C# Javascript // C++ program for the insertion sort#include <bits/stdc++.h>using namespace std; // Function to sort an array using// insertion sortvoid insertionSort(int arr[], int n){ int i, key, j; for (i = 1; i < n; i++) { key = arr[i]; j = i - 1; // Move elements of arr[0..i-1], // that are greater than key to // one position ahead of their // current position while (j >= 0 && arr[j] > key) { arr[j + 1] = arr[j]; j = j - 1; } arr[j + 1] = key; }} // Function to print an array of size Nvoid printArray(int arr[], int n){ int i; // Print the array for (i = 0; i < n; i++) { cout << arr[i] << " "; } cout << endl;} // Driver Codeint main(){ int arr[] = { 12, 11, 13, 5, 6 }; int N = sizeof(arr) / sizeof(arr[0]); // Function Call insertionSort(arr, N); printArray(arr, N); return 0;} // Java program for the above approachimport java.util.*;class GFG{ // Function to sort an array using// insertion sortstatic void insertionSort(int arr[], int n){ int i, key, j; for (i = 1; i < n; i++) { key = arr[i]; j = i - 1; // Move elements of arr[0..i-1], // that are greater than key to // one position ahead of their // current position while (j >= 0 && arr[j] > key) { arr[j + 1] = arr[j]; j = j - 1; } arr[j + 1] = key; }} // Function to print an array of size Nstatic void printArray(int arr[], int n){ int i; // Print the array for (i = 0; i < n; i++) { System.out.print(arr[i] + " "); } System.out.println();} // Driver codepublic static void main(String[] args){ int arr[] = { 12, 11, 13, 5, 6 }; int N = arr.length; // Function Call insertionSort(arr, N); printArray(arr, N);}} // This code is contributed by code_hunt. # Python 3 program for the insertion sort # Function to sort an array using# insertion sortdef insertionSort(arr, n): i = 0 key = 0 j = 0 for i in range(1,n,1): key = arr[i] j = i - 1 # Move elements of arr[0..i-1], # that are greater than key to # one position ahead of their # current position while (j >= 0 and arr[j] > key): arr[j + 1] = arr[j] j = j - 1 arr[j + 1] = key # Function to print an array of size Ndef printArray(arr, n): i = 0 # Print the array for i in range(n): print(arr[i],end = " ") print("\n",end = "") # Driver Codeif __name__ == '__main__': arr = [12, 11, 13, 5, 6] N = len(arr) # Function Call insertionSort(arr, N) printArray(arr, N) # This code is contributed by bgangwar59. // C# program for the above approachusing System;class GFG{ // Function to sort an array using // insertion sort static void insertionSort(int[] arr, int n) { int i, key, j; for (i = 1; i < n; i++) { key = arr[i]; j = i - 1; // Move elements of arr[0..i-1], // that are greater than key to // one position ahead of their // current position while (j >= 0 && arr[j] > key) { arr[j + 1] = arr[j]; j = j - 1; } arr[j + 1] = key; } } // Function to print an array of size N static void printArray(int[] arr, int n) { int i; // Print the array for (i = 0; i < n; i++) { Console.Write(arr[i] + " "); } Console.WriteLine(); } // Driver code static public void Main() { int[] arr = new int[] { 12, 11, 13, 5, 6 }; int N = arr.Length; // Function Call insertionSort(arr, N); printArray(arr, N); }} // This code is contributed by Dharanendra L V <script> // JavaScript program for the above approach // Function to sort an array using// insertion sortfunction insertionSort(arr,n){ let i, key, j; for (i = 1; i < n; i++) { key = arr[i]; j = i - 1; // Move elements of arr[0..i-1], // that are greater than key to // one position ahead of their // current position while (j >= 0 && arr[j] > key) { arr[j + 1] = arr[j]; j = j - 1; } arr[j + 1] = key; }} // Function to print an array of size Nfunction printArray(arr,n){ let i; // Print the array for (i = 0; i < n; i++) { document.write(arr[i] + " "); } document.write("<br>");} // Driver codelet arr=[12, 11, 13, 5, 6];let N = arr.length; // Function CallinsertionSort(arr, N);printArray(arr, N); // This code is contributed by avanitrachhadiya2155 </script> 5 6 11 12 13 The selection sort algorithm sorts an array by repeatedly finding the minimum element (considering ascending order) from the unsorted part and putting it at the beginning. The algorithm maintains two subarrays in a given array. The subarray is already sorted. The remaining subarray is unsorted. In every iteration of the selection sort, the minimum element (considering ascending order) from the unsorted subarray is picked and moved to the sorted subarray. Below is an example to explains the above steps: arr[] = 64 25 12 22 11 // Find the minimum element in arr[0...4] // and place it at beginning 11 25 12 22 64 // Find the minimum element in arr[1...4] // and place it at beginning of arr[1...4] 11 12 25 22 64 // Find the minimum element in arr[2...4] // and place it at beginning of arr[2...4] 11 12 22 25 64 // Find the minimum element in arr[3...4] // and place it at beginning of arr[3...4] 11 12 22 25 64 Below is the program for the same: C++ Java Python3 C# Javascript // C++ program for implementation of// selection sort#include <bits/stdc++.h>using namespace std; // Function to swap two numbervoid swap(int* xp, int* yp){ int temp = *xp; *xp = *yp; *yp = temp;} // Function to implement the selection// sortvoid selectionSort(int arr[], int n){ int i, j, min_idx; // One by one move boundary of // unsorted subarray for (i = 0; i < n - 1; i++) { // Find the minimum element // in unsorted array min_idx = i; for (j = i + 1; j < n; j++) if (arr[j] < arr[min_idx]) min_idx = j; // Swap the found minimum element // with the first element swap(&arr[min_idx], &arr[i]); }} // Function to print an arrayvoid printArray(int arr[], int size){ int i; for (i = 0; i < size; i++) { cout << arr[i] << " "; } cout << endl;} // Driver Codeint main(){ int arr[] = { 64, 25, 12, 22, 11 }; int n = sizeof(arr) / sizeof(arr[0]); // Function Call selectionSort(arr, n); cout << "Sorted array: \n"; // Print the array printArray(arr, n); return 0;} // Java program for implementation of// selection sortimport java.util.*;class GFG{ // Function to implement the selection// sortstatic void selectionSort(int arr[], int n){ int i, j, min_idx; // One by one move boundary of // unsorted subarray for (i = 0; i < n - 1; i++) { // Find the minimum element // in unsorted array min_idx = i; for (j = i + 1; j < n; j++) if (arr[j] < arr[min_idx]) min_idx = j; // Swap the found minimum element // with the first element int temp = arr[min_idx]; arr[min_idx]= arr[i]; arr[i] = temp; }} // Function to print an arraystatic void printArray(int arr[], int size){ int i; for (i = 0; i < size; i++) { System.out.print(arr[i]+ " "); } System.out.println();} // Driver Codepublic static void main(String[] args){ int arr[] = { 64, 25, 12, 22, 11 }; int n = arr.length; // Function Call selectionSort(arr, n); System.out.print("Sorted array: \n"); // Print the array printArray(arr, n);}} // This code is contributed by aashish1995 # Python3 program for implementation of# selection sort # Function to implement the selection# sortdef selectionSort(arr, n): # One by one move boundary of # unsorted subarray for i in range(n - 1): # Find the minimum element # in unsorted array min_idx = i for j in range(i + 1, n): if (arr[j] < arr[min_idx]): min_idx = j # Swap the found minimum element # with the first element arr[min_idx], arr[i] = arr[i], arr[min_idx] # Function to print an arraydef printArray(arr, size): for i in range(size): print(arr[i], end = " ") print() # Driver Codeif __name__ == "__main__": arr = [64, 25, 12, 22, 11] n = len(arr) # Function Call selectionSort(arr, n) print("Sorted array: ") # Print the array printArray(arr, n) # This code is contributed by ukasp // C# program for implementation of// selection sortusing System;public class GFG{ // Function to implement the selection// sortstatic void selectionSort(int []arr, int n){ int i, j, min_idx; // One by one move boundary of // unsorted subarray for (i = 0; i < n - 1; i++) { // Find the minimum element // in unsorted array min_idx = i; for (j = i + 1; j < n; j++) if (arr[j] < arr[min_idx]) min_idx = j; // Swap the found minimum element // with the first element int temp = arr[min_idx]; arr[min_idx]= arr[i]; arr[i] = temp; }} // Function to print an arraystatic void printArray(int []arr, int size){ int i; for (i = 0; i < size; i++) { Console.Write(arr[i]+ " "); } Console.WriteLine();} // Driver Codepublic static void Main(String[] args){ int []arr = { 64, 25, 12, 22, 11 }; int n = arr.Length; // Function Call selectionSort(arr, n); Console.Write("Sorted array: \n"); // Print the array printArray(arr, n);}} // This code is contributed by gauravrajput1 <script> // Javascript program for implementation of// selection sort // Function to implement the selection// sortfunction selectionSort(arr, n){ let i, j, min_idx; // One by one move boundary of // unsorted subarray for(i = 0; i < n - 1; i++) { // Find the minimum element // in unsorted array min_idx = i; for(j = i + 1; j < n; j++) if (arr[j] < arr[min_idx]) min_idx = j; // Swap the found minimum element // with the first element let temp = arr[min_idx]; arr[min_idx]= arr[i]; arr[i] = temp; }} // Function to print an arrayfunction printArray(arr, size){ let i; for(i = 0; i < size; i++) { document.write(arr[i] + " "); } document.write("<br>");} // Driver Codelet arr = [ 64, 25, 12, 22, 11 ];let n = arr.length; // Function CallselectionSort(arr, n);document.write("Sorted array: <br>"); // Print the arrayprintArray(arr, n); // This code is contributed by rag2127 </script> Sorted array: 11 12 22 25 64 Tabular Difference between Insertion Sort and Selection Sort: The insertion sort is used when: The array is has a small number of elements There are only a few elements left to be sorted The selection sort is used when A small list is to be sorted The cost of swapping does not matter Checking of all the elements is compulsory Cost of writing to memory matters like in flash memory (number of Swaps is O(n) as compared to O(n2) of bubble sort) code_hunt dharanendralv23 bgangwar59 aashish1995 GauravRajput1 ukasp avanitrachhadiya2155 rag2127 mayank007rawa Technical Scripter 2020 Algorithms C++ C++ Programs Difference Between Sorting Technical Scripter Sorting Algorithms CPP Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. DSA Sheet by Love Babbar SDE SHEET - A Complete Guide for SDE Preparation What is Hashing | A Complete Tutorial Find if there is a path between two vertices in an undirected graph CPU Scheduling in Operating Systems Vector in C++ STL Map in C++ Standard Template Library (STL) Initialize a vector in C++ (7 different ways) std::sort() in C++ STL Bitwise Operators in C/C++
[ { "code": null, "e": 28, "s": 0, "text": "\n29 Mar, 2022" }, { "code": null, "e": 127, "s": 28, "text": "In this article, we will discuss the difference between the Insertion sort and the Selection sort:" }, { "code": null, "e": 401, "s": 127, "text": "Insertion sort is a simple sorting algorithm that works similar to the way you sort playing cards in your hands. The array is virtually split into a sorted and an unsorted part. Values from the unsorted part are picked and placed at the correct position in the sorted part." }, { "code": null, "e": 461, "s": 401, "text": "Algorithm: To sort an array of size n in ascending order: " }, { "code": null, "e": 507, "s": 461, "text": "Iterate from arr[1] to arr[n] over the array." }, { "code": null, "e": 561, "s": 507, "text": "Compare the current element (key) to its predecessor." }, { "code": null, "e": 729, "s": 561, "text": "If the key element is smaller than its predecessor, compare it to the elements before. Move the greater elements one position up to make space for the swapped element." }, { "code": null, "e": 784, "s": 729, "text": "Below is the image to illustrate the Insertion Sort: " }, { "code": null, "e": 819, "s": 784, "text": "Below is the program for the same:" }, { "code": null, "e": 823, "s": 819, "text": "C++" }, { "code": null, "e": 828, "s": 823, "text": "Java" }, { "code": null, "e": 836, "s": 828, "text": "Python3" }, { "code": null, "e": 839, "s": 836, "text": "C#" }, { "code": null, "e": 850, "s": 839, "text": "Javascript" }, { "code": "// C++ program for the insertion sort#include <bits/stdc++.h>using namespace std; // Function to sort an array using// insertion sortvoid insertionSort(int arr[], int n){ int i, key, j; for (i = 1; i < n; i++) { key = arr[i]; j = i - 1; // Move elements of arr[0..i-1], // that are greater than key to // one position ahead of their // current position while (j >= 0 && arr[j] > key) { arr[j + 1] = arr[j]; j = j - 1; } arr[j + 1] = key; }} // Function to print an array of size Nvoid printArray(int arr[], int n){ int i; // Print the array for (i = 0; i < n; i++) { cout << arr[i] << \" \"; } cout << endl;} // Driver Codeint main(){ int arr[] = { 12, 11, 13, 5, 6 }; int N = sizeof(arr) / sizeof(arr[0]); // Function Call insertionSort(arr, N); printArray(arr, N); return 0;}", "e": 1764, "s": 850, "text": null }, { "code": "// Java program for the above approachimport java.util.*;class GFG{ // Function to sort an array using// insertion sortstatic void insertionSort(int arr[], int n){ int i, key, j; for (i = 1; i < n; i++) { key = arr[i]; j = i - 1; // Move elements of arr[0..i-1], // that are greater than key to // one position ahead of their // current position while (j >= 0 && arr[j] > key) { arr[j + 1] = arr[j]; j = j - 1; } arr[j + 1] = key; }} // Function to print an array of size Nstatic void printArray(int arr[], int n){ int i; // Print the array for (i = 0; i < n; i++) { System.out.print(arr[i] + \" \"); } System.out.println();} // Driver codepublic static void main(String[] args){ int arr[] = { 12, 11, 13, 5, 6 }; int N = arr.length; // Function Call insertionSort(arr, N); printArray(arr, N);}} // This code is contributed by code_hunt.", "e": 2752, "s": 1764, "text": null }, { "code": "# Python 3 program for the insertion sort # Function to sort an array using# insertion sortdef insertionSort(arr, n): i = 0 key = 0 j = 0 for i in range(1,n,1): key = arr[i] j = i - 1 # Move elements of arr[0..i-1], # that are greater than key to # one position ahead of their # current position while (j >= 0 and arr[j] > key): arr[j + 1] = arr[j] j = j - 1 arr[j + 1] = key # Function to print an array of size Ndef printArray(arr, n): i = 0 # Print the array for i in range(n): print(arr[i],end = \" \") print(\"\\n\",end = \"\") # Driver Codeif __name__ == '__main__': arr = [12, 11, 13, 5, 6] N = len(arr) # Function Call insertionSort(arr, N) printArray(arr, N) # This code is contributed by bgangwar59.", "e": 3592, "s": 2752, "text": null }, { "code": "// C# program for the above approachusing System;class GFG{ // Function to sort an array using // insertion sort static void insertionSort(int[] arr, int n) { int i, key, j; for (i = 1; i < n; i++) { key = arr[i]; j = i - 1; // Move elements of arr[0..i-1], // that are greater than key to // one position ahead of their // current position while (j >= 0 && arr[j] > key) { arr[j + 1] = arr[j]; j = j - 1; } arr[j + 1] = key; } } // Function to print an array of size N static void printArray(int[] arr, int n) { int i; // Print the array for (i = 0; i < n; i++) { Console.Write(arr[i] + \" \"); } Console.WriteLine(); } // Driver code static public void Main() { int[] arr = new int[] { 12, 11, 13, 5, 6 }; int N = arr.Length; // Function Call insertionSort(arr, N); printArray(arr, N); }} // This code is contributed by Dharanendra L V", "e": 4729, "s": 3592, "text": null }, { "code": "<script> // JavaScript program for the above approach // Function to sort an array using// insertion sortfunction insertionSort(arr,n){ let i, key, j; for (i = 1; i < n; i++) { key = arr[i]; j = i - 1; // Move elements of arr[0..i-1], // that are greater than key to // one position ahead of their // current position while (j >= 0 && arr[j] > key) { arr[j + 1] = arr[j]; j = j - 1; } arr[j + 1] = key; }} // Function to print an array of size Nfunction printArray(arr,n){ let i; // Print the array for (i = 0; i < n; i++) { document.write(arr[i] + \" \"); } document.write(\"<br>\");} // Driver codelet arr=[12, 11, 13, 5, 6];let N = arr.length; // Function CallinsertionSort(arr, N);printArray(arr, N); // This code is contributed by avanitrachhadiya2155 </script>", "e": 5624, "s": 4729, "text": null }, { "code": null, "e": 5637, "s": 5624, "text": "5 6 11 12 13" }, { "code": null, "e": 5868, "s": 5639, "text": "The selection sort algorithm sorts an array by repeatedly finding the minimum element (considering ascending order) from the unsorted part and putting it at the beginning. The algorithm maintains two subarrays in a given array. " }, { "code": null, "e": 5900, "s": 5868, "text": "The subarray is already sorted." }, { "code": null, "e": 5936, "s": 5900, "text": "The remaining subarray is unsorted." }, { "code": null, "e": 6100, "s": 5936, "text": "In every iteration of the selection sort, the minimum element (considering ascending order) from the unsorted subarray is picked and moved to the sorted subarray. " }, { "code": null, "e": 6150, "s": 6100, "text": "Below is an example to explains the above steps: " }, { "code": null, "e": 6564, "s": 6150, "text": "arr[] = 64 25 12 22 11\n\n// Find the minimum element in arr[0...4]\n// and place it at beginning\n11 25 12 22 64\n\n// Find the minimum element in arr[1...4]\n// and place it at beginning of arr[1...4]\n11 12 25 22 64\n\n// Find the minimum element in arr[2...4]\n// and place it at beginning of arr[2...4]\n11 12 22 25 64\n\n// Find the minimum element in arr[3...4]\n// and place it at beginning of arr[3...4]\n11 12 22 25 64 " }, { "code": null, "e": 6599, "s": 6564, "text": "Below is the program for the same:" }, { "code": null, "e": 6603, "s": 6599, "text": "C++" }, { "code": null, "e": 6608, "s": 6603, "text": "Java" }, { "code": null, "e": 6616, "s": 6608, "text": "Python3" }, { "code": null, "e": 6619, "s": 6616, "text": "C#" }, { "code": null, "e": 6630, "s": 6619, "text": "Javascript" }, { "code": "// C++ program for implementation of// selection sort#include <bits/stdc++.h>using namespace std; // Function to swap two numbervoid swap(int* xp, int* yp){ int temp = *xp; *xp = *yp; *yp = temp;} // Function to implement the selection// sortvoid selectionSort(int arr[], int n){ int i, j, min_idx; // One by one move boundary of // unsorted subarray for (i = 0; i < n - 1; i++) { // Find the minimum element // in unsorted array min_idx = i; for (j = i + 1; j < n; j++) if (arr[j] < arr[min_idx]) min_idx = j; // Swap the found minimum element // with the first element swap(&arr[min_idx], &arr[i]); }} // Function to print an arrayvoid printArray(int arr[], int size){ int i; for (i = 0; i < size; i++) { cout << arr[i] << \" \"; } cout << endl;} // Driver Codeint main(){ int arr[] = { 64, 25, 12, 22, 11 }; int n = sizeof(arr) / sizeof(arr[0]); // Function Call selectionSort(arr, n); cout << \"Sorted array: \\n\"; // Print the array printArray(arr, n); return 0;}", "e": 7743, "s": 6630, "text": null }, { "code": "// Java program for implementation of// selection sortimport java.util.*;class GFG{ // Function to implement the selection// sortstatic void selectionSort(int arr[], int n){ int i, j, min_idx; // One by one move boundary of // unsorted subarray for (i = 0; i < n - 1; i++) { // Find the minimum element // in unsorted array min_idx = i; for (j = i + 1; j < n; j++) if (arr[j] < arr[min_idx]) min_idx = j; // Swap the found minimum element // with the first element int temp = arr[min_idx]; arr[min_idx]= arr[i]; arr[i] = temp; }} // Function to print an arraystatic void printArray(int arr[], int size){ int i; for (i = 0; i < size; i++) { System.out.print(arr[i]+ \" \"); } System.out.println();} // Driver Codepublic static void main(String[] args){ int arr[] = { 64, 25, 12, 22, 11 }; int n = arr.length; // Function Call selectionSort(arr, n); System.out.print(\"Sorted array: \\n\"); // Print the array printArray(arr, n);}} // This code is contributed by aashish1995", "e": 8864, "s": 7743, "text": null }, { "code": "# Python3 program for implementation of# selection sort # Function to implement the selection# sortdef selectionSort(arr, n): # One by one move boundary of # unsorted subarray for i in range(n - 1): # Find the minimum element # in unsorted array min_idx = i for j in range(i + 1, n): if (arr[j] < arr[min_idx]): min_idx = j # Swap the found minimum element # with the first element arr[min_idx], arr[i] = arr[i], arr[min_idx] # Function to print an arraydef printArray(arr, size): for i in range(size): print(arr[i], end = \" \") print() # Driver Codeif __name__ == \"__main__\": arr = [64, 25, 12, 22, 11] n = len(arr) # Function Call selectionSort(arr, n) print(\"Sorted array: \") # Print the array printArray(arr, n) # This code is contributed by ukasp", "e": 9741, "s": 8864, "text": null }, { "code": "// C# program for implementation of// selection sortusing System;public class GFG{ // Function to implement the selection// sortstatic void selectionSort(int []arr, int n){ int i, j, min_idx; // One by one move boundary of // unsorted subarray for (i = 0; i < n - 1; i++) { // Find the minimum element // in unsorted array min_idx = i; for (j = i + 1; j < n; j++) if (arr[j] < arr[min_idx]) min_idx = j; // Swap the found minimum element // with the first element int temp = arr[min_idx]; arr[min_idx]= arr[i]; arr[i] = temp; }} // Function to print an arraystatic void printArray(int []arr, int size){ int i; for (i = 0; i < size; i++) { Console.Write(arr[i]+ \" \"); } Console.WriteLine();} // Driver Codepublic static void Main(String[] args){ int []arr = { 64, 25, 12, 22, 11 }; int n = arr.Length; // Function Call selectionSort(arr, n); Console.Write(\"Sorted array: \\n\"); // Print the array printArray(arr, n);}} // This code is contributed by gauravrajput1", "e": 10856, "s": 9741, "text": null }, { "code": "<script> // Javascript program for implementation of// selection sort // Function to implement the selection// sortfunction selectionSort(arr, n){ let i, j, min_idx; // One by one move boundary of // unsorted subarray for(i = 0; i < n - 1; i++) { // Find the minimum element // in unsorted array min_idx = i; for(j = i + 1; j < n; j++) if (arr[j] < arr[min_idx]) min_idx = j; // Swap the found minimum element // with the first element let temp = arr[min_idx]; arr[min_idx]= arr[i]; arr[i] = temp; }} // Function to print an arrayfunction printArray(arr, size){ let i; for(i = 0; i < size; i++) { document.write(arr[i] + \" \"); } document.write(\"<br>\");} // Driver Codelet arr = [ 64, 25, 12, 22, 11 ];let n = arr.length; // Function CallselectionSort(arr, n);document.write(\"Sorted array: <br>\"); // Print the arrayprintArray(arr, n); // This code is contributed by rag2127 </script>", "e": 11896, "s": 10856, "text": null }, { "code": null, "e": 11926, "s": 11896, "text": "Sorted array: \n11 12 22 25 64" }, { "code": null, "e": 11990, "s": 11928, "text": "Tabular Difference between Insertion Sort and Selection Sort:" }, { "code": null, "e": 12025, "s": 11992, "text": "The insertion sort is used when:" }, { "code": null, "e": 12069, "s": 12025, "text": "The array is has a small number of elements" }, { "code": null, "e": 12117, "s": 12069, "text": "There are only a few elements left to be sorted" }, { "code": null, "e": 12149, "s": 12117, "text": "The selection sort is used when" }, { "code": null, "e": 12178, "s": 12149, "text": "A small list is to be sorted" }, { "code": null, "e": 12215, "s": 12178, "text": "The cost of swapping does not matter" }, { "code": null, "e": 12258, "s": 12215, "text": "Checking of all the elements is compulsory" }, { "code": null, "e": 12375, "s": 12258, "text": "Cost of writing to memory matters like in flash memory (number of Swaps is O(n) as compared to O(n2) of bubble sort)" }, { "code": null, "e": 12385, "s": 12375, "text": "code_hunt" }, { "code": null, "e": 12401, "s": 12385, "text": "dharanendralv23" }, { "code": null, "e": 12412, "s": 12401, "text": "bgangwar59" }, { "code": null, "e": 12424, "s": 12412, "text": "aashish1995" }, { "code": null, "e": 12438, "s": 12424, "text": "GauravRajput1" }, { "code": null, "e": 12444, "s": 12438, "text": "ukasp" }, { "code": null, "e": 12465, "s": 12444, "text": "avanitrachhadiya2155" }, { "code": null, "e": 12473, "s": 12465, "text": "rag2127" }, { "code": null, "e": 12487, "s": 12473, "text": "mayank007rawa" }, { "code": null, "e": 12511, "s": 12487, "text": "Technical Scripter 2020" }, { "code": null, "e": 12522, "s": 12511, "text": "Algorithms" }, { "code": null, "e": 12526, "s": 12522, "text": "C++" }, { "code": null, "e": 12539, "s": 12526, "text": "C++ Programs" }, { "code": null, "e": 12558, "s": 12539, "text": "Difference Between" }, { "code": null, "e": 12566, "s": 12558, "text": "Sorting" }, { "code": null, "e": 12585, "s": 12566, "text": "Technical Scripter" }, { "code": null, "e": 12593, "s": 12585, "text": "Sorting" }, { "code": null, "e": 12604, "s": 12593, "text": "Algorithms" }, { "code": null, "e": 12608, "s": 12604, "text": "CPP" }, { "code": null, "e": 12706, "s": 12608, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 12731, "s": 12706, "text": "DSA Sheet by Love Babbar" }, { "code": null, "e": 12780, "s": 12731, "text": "SDE SHEET - A Complete Guide for SDE Preparation" }, { "code": null, "e": 12818, "s": 12780, "text": "What is Hashing | A Complete Tutorial" }, { "code": null, "e": 12886, "s": 12818, "text": "Find if there is a path between two vertices in an undirected graph" }, { "code": null, "e": 12922, "s": 12886, "text": "CPU Scheduling in Operating Systems" }, { "code": null, "e": 12940, "s": 12922, "text": "Vector in C++ STL" }, { "code": null, "e": 12983, "s": 12940, "text": "Map in C++ Standard Template Library (STL)" }, { "code": null, "e": 13029, "s": 12983, "text": "Initialize a vector in C++ (7 different ways)" }, { "code": null, "e": 13052, "s": 13029, "text": "std::sort() in C++ STL" } ]
java.lang.Math.atan2() in Java
20 Jun, 2021 atan2() is an inbuilt method in Java that is used to return the theta component from the polar coordinate. The atan2() method returns a numeric value between –and representing the angle of a (x, y) point and the positive x-axis. It is the counterclockwise angle, measured in radian, between the positive X-axis, and the point (x, y). Syntax : Math.atan2(double y, double x) where, x and y are X and Y coordinates in double data type. Returns : It returns a double value. The double value is from polar coordinate (r, theta). Example: Program demonstrating the atan2() method Java // Java program for implementation of// atan2() methodimport java.util.*;class GFG { // Driver Code public static void main(String args[]) { // X and Y coordinates double x = 90.0; double y = 15.0; // theta value from polar coordinate (r, theta) double theta = Math.atan2(y, x); System.out.println(theta); }} 0.16514867741462683 mmarsland Java-lang package Java Java Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 52, "s": 24, "text": "\n20 Jun, 2021" }, { "code": null, "e": 397, "s": 52, "text": "atan2() is an inbuilt method in Java that is used to return the theta component from the polar coordinate. The atan2() method returns a numeric value between –and representing the angle of a (x, y) point and the positive x-axis. It is the counterclockwise angle, measured in radian, between the positive X-axis, and the point (x, y). Syntax : " }, { "code": null, "e": 488, "s": 397, "text": "Math.atan2(double y, double x)\nwhere, x and y are X and Y coordinates in double data type." }, { "code": null, "e": 631, "s": 488, "text": "Returns : It returns a double value. The double value is from polar coordinate (r, theta). Example: Program demonstrating the atan2() method " }, { "code": null, "e": 636, "s": 631, "text": "Java" }, { "code": "// Java program for implementation of// atan2() methodimport java.util.*;class GFG { // Driver Code public static void main(String args[]) { // X and Y coordinates double x = 90.0; double y = 15.0; // theta value from polar coordinate (r, theta) double theta = Math.atan2(y, x); System.out.println(theta); }}", "e": 1003, "s": 636, "text": null }, { "code": null, "e": 1024, "s": 1003, "text": "0.16514867741462683\n" }, { "code": null, "e": 1034, "s": 1024, "text": "mmarsland" }, { "code": null, "e": 1052, "s": 1034, "text": "Java-lang package" }, { "code": null, "e": 1057, "s": 1052, "text": "Java" }, { "code": null, "e": 1062, "s": 1057, "text": "Java" } ]
Program for nth Catalan Number
07 Jul, 2022 Catalan numbers are a sequence of natural numbers that occurs in many interesting counting problems like following. Count the number of expressions containing n pairs of parentheses which are correctly matched. For n = 3, possible expressions are ((())), ()(()), ()()(), (())(), (()()).Count the number of possible Binary Search Trees with n keys (See this)Count the number of full binary trees (A rooted binary tree is full if every vertex has either two children or no children) with n+1 leaves.Given a number n, return the number of ways you can draw n chords in a circle with 2 x n points such that no 2 chords intersect. Count the number of expressions containing n pairs of parentheses which are correctly matched. For n = 3, possible expressions are ((())), ()(()), ()()(), (())(), (()()). Count the number of possible Binary Search Trees with n keys (See this) Count the number of full binary trees (A rooted binary tree is full if every vertex has either two children or no children) with n+1 leaves. Given a number n, return the number of ways you can draw n chords in a circle with 2 x n points such that no 2 chords intersect. See this for more applications. The first few Catalan numbers for n = 0, 1, 2, 3, ... are 1, 1, 2, 5, 14, 42, 132, 429, 1430, 4862, ... Recursive Solution Catalan numbers satisfy the following recursive formula. Following is the implementation of above recursive formula. 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. C++ Java Python3 C# PHP Javascript #include <iostream>using namespace std; // A recursive function to find nth catalan numberunsigned long int catalan(unsigned int n){ // Base case if (n <= 1) return 1; // catalan(n) is sum of // catalan(i)*catalan(n-i-1) unsigned long int res = 0; for (int i = 0; i < n; i++) res += catalan(i) * catalan(n - i - 1); return res;} // Driver codeint main(){ for (int i = 0; i < 10; i++) cout << catalan(i) << " "; return 0;} class CatalnNumber { // A recursive function to find nth catalan number int catalan(int n) { int res = 0; // Base case if (n <= 1) { return 1; } for (int i = 0; i < n; i++) { res += catalan(i) * catalan(n - i - 1); } return res; } // Driver Code public static void main(String[] args) { CatalnNumber cn = new CatalnNumber(); for (int i = 0; i < 10; i++) { System.out.print(cn.catalan(i) + " "); } }} # A recursive function to# find nth catalan numberdef catalan(n): # Base Case if n <= 1: return 1 # Catalan(n) is the sum # of catalan(i)*catalan(n-i-1) res = 0 for i in range(n): res += catalan(i) * catalan(n-i-1) return res # Driver Codefor i in range(10): print (catalan(i),end=" ")# This code is contributed by# Nikhil Kumar Singh (nickzuck_007) // A recursive C# program to find// nth catalan numberusing System; class GFG { // A recursive function to find // nth catalan number static int catalan(int n) { int res = 0; // Base case if (n <= 1) { return 1; } for (int i = 0; i < n; i++) { res += catalan(i) * catalan(n - i - 1); } return res; } // Driver Code public static void Main() { for (int i = 0; i < 10; i++) Console.Write(catalan(i) + " "); }} // This code is contributed by// nitin mittal. <?php// PHP Program for nth// Catalan Number // A recursive function to// find nth catalan numberfunction catalan($n){ // Base case if ($n <= 1) return 1; // catalan(n) is sum of // catalan(i)*catalan(n-i-1) $res = 0; for($i = 0; $i < $n; $i++) $res += catalan($i) * catalan($n - $i - 1); return $res;} // Driver Codefor ($i = 0; $i < 10; $i++) echo catalan($i), " "; // This code is contributed aj_36?> <script> // Javascript Program for nth// Catalan Number // A recursive function to// find nth catalan numberfunction catalan(n){ // Base case if (n <= 1) return 1; // catalan(n) is sum of // catalan(i)*catalan(n-i-1) let res = 0; for(let i = 0; i < n; i++) res += catalan(i) * catalan(n - i - 1); return res;} // Driver Codefor (let i = 0; i < 10; i++) document.write(catalan(i) + " "); // This code is contributed _saurabh_jaiswal </script> 1 1 2 5 14 42 132 429 1430 4862 Time complexity of above implementation is equivalent to nth catalan number. The value of nth catalan number is exponential that makes the time complexity exponential. Dynamic Programming Solution : We can observe that the above recursive implementation does a lot of repeated work (we can the same by drawing recursion tree). Since there are overlapping subproblems, we can use dynamic programming for this. Following is a Dynamic programming based implementation . C++ Java Python3 C# PHP Javascript #include <iostream>using namespace std; // A dynamic programming based function to find nth// Catalan numberunsigned long int catalanDP(unsigned int n){ // Table to store results of subproblems unsigned long int catalan[n + 1]; // Initialize first two values in table catalan[0] = catalan[1] = 1; // Fill entries in catalan[] using recursive formula for (int i = 2; i <= n; i++) { catalan[i] = 0; for (int j = 0; j < i; j++) catalan[i] += catalan[j] * catalan[i - j - 1]; } // Return last entry return catalan[n];} // Driver codeint main(){ for (int i = 0; i < 10; i++) cout << catalanDP(i) << " "; return 0;} class GFG { // A dynamic programming based function to find nth // Catalan number static int catalanDP(int n) { // Table to store results of subproblems int catalan[] = new int[n + 2]; // Initialize first two values in table catalan[0] = 1; catalan[1] = 1; // Fill entries in catalan[] // using recursive formula for (int i = 2; i <= n; i++) { catalan[i] = 0; for (int j = 0; j < i; j++) { catalan[i] += catalan[j] * catalan[i - j - 1]; } } // Return last entry return catalan[n]; } // Driver code public static void main(String[] args) { for (int i = 0; i < 10; i++) { System.out.print(catalanDP(i) + " "); } }}// This code contributed by Rajput-Ji # A dynamic programming based function to find nth# Catalan number def catalan(n): if (n == 0 or n == 1): return 1 # Table to store results of subproblems catalan =[0]*(n+1) # Initialize first two values in table catalan[0] = 1 catalan[1] = 1 # Fill entries in catalan[] # using recursive formula for i in range(2, n + 1): for j in range(i): catalan[i] += catalan[j]* catalan[i-j-1] # Return last entry return catalan[n] # Driver codefor i in range(10): print(catalan(i), end=" ")# This code is contributed by Ediga_manisha using System; class GFG { // A dynamic programming based // function to find nth // Catalan number static uint catalanDP(uint n) { // Table to store results of subproblems uint[] catalan = new uint[n + 2]; // Initialize first two values in table catalan[0] = catalan[1] = 1; // Fill entries in catalan[] // using recursive formula for (uint i = 2; i <= n; i++) { catalan[i] = 0; for (uint j = 0; j < i; j++) catalan[i] += catalan[j] * catalan[i - j - 1]; } // Return last entry return catalan[n]; } // Driver code static void Main() { for (uint i = 0; i < 10; i++) Console.Write(catalanDP(i) + " "); }} // This code is contributed by Chandan_jnu <?php// PHP program for nth Catalan Number // A dynamic programming based function// to find nth Catalan numberfunction catalanDP( $n){ // Table to store results // of subproblems $catalan= array(); // Initialize first two // values in table $catalan[0] = $catalan[1] = 1; // Fill entries in catalan[] // using recursive formula for ($i = 2; $i <= $n; $i++) { $catalan[$i] = 0; for ( $j = 0; $j < $i; $j++) $catalan[$i] += $catalan[$j] * $catalan[$i - $j - 1]; } // Return last entry return $catalan[$n];} // Driver Code for ($i = 0; $i < 10; $i++) echo catalanDP($i) , " "; // This code is contributed anuj_67.?> <script>// Javascript program for nth Catalan Number // A dynamic programming based function// to find nth Catalan numberfunction catalanDP(n){ // Table to store results // of subproblems let catalan= []; // Initialize first two // values in table catalan[0] = catalan[1] = 1; // Fill entries in catalan[] // using recursive formula for (let i = 2; i <= n; i++) { catalan[i] = 0; for (let j = 0; j < i; j++) catalan[i] += catalan[j] * catalan[i - j - 1]; } // Return last entry return catalan[n];} // Driver Code for (let i = 0; i < 10; i++) document.write(catalanDP(i) + " "); // This code is contributed _saurabh_jaiswal</script> 1 1 2 5 14 42 132 429 1430 4862 Time Complexity: Time complexity of above implementation is O(n2) Using Binomial Coefficient We can also use the below formula to find nth Catalan number in O(n) time. We have discussed a O(n) approach to find binomial coefficient nCr. C++ Java Python3 C# PHP Javascript // C++ program for nth Catalan Number#include <iostream>using namespace std; // Returns value of Binomial Coefficient C(n, k)unsigned long int binomialCoeff(unsigned int n, unsigned int k){ unsigned long int res = 1; // Since C(n, k) = C(n, n-k) if (k > n - k) k = n - k; // Calculate value of [n*(n-1)*---*(n-k+1)] / // [k*(k-1)*---*1] for (int i = 0; i < k; ++i) { res *= (n - i); res /= (i + 1); } return res;} // A Binomial coefficient based function to find nth catalan// number in O(n) timeunsigned long int catalan(unsigned int n){ // Calculate value of 2nCn unsigned long int c = binomialCoeff(2 * n, n); // return 2nCn/(n+1) return c / (n + 1);} // Driver codeint main(){ for (int i = 0; i < 10; i++) cout << catalan(i) << " "; return 0;} // Java program for nth Catalan Number class GFG { // Returns value of Binomial Coefficient C(n, k) static long binomialCoeff(int n, int k) { long res = 1; // Since C(n, k) = C(n, n-k) if (k > n - k) { k = n - k; } // Calculate value of [n*(n-1)*---*(n-k+1)] / // [k*(k-1)*---*1] for (int i = 0; i < k; ++i) { res *= (n - i); res /= (i + 1); } return res; } // A Binomial coefficient based function // to find nth catalan number in O(n) time static long catalan(int n) { // Calculate value of 2nCn long c = binomialCoeff(2 * n, n); // return 2nCn/(n+1) return c / (n + 1); } // Driver code public static void main(String[] args) { for (int i = 0; i < 10; i++) { System.out.print(catalan(i) + " "); } }} # Python program for nth Catalan Number# Returns value of Binomial Coefficient C(n, k) def binomialCoefficient(n, k): # since C(n, k) = C(n, n - k) if (k > n - k): k = n - k # initialize result res = 1 # Calculate value of [n * (n-1) *---* (n-k + 1)] # / [k * (k-1) *----* 1] for i in range(k): res = res * (n - i) res = res / (i + 1) return res # A Binomial coefficient based function to# find nth catalan number in O(n) time def catalan(n): c = binomialCoefficient(2*n, n) return c/(n + 1) # Driver Codefor i in range(10): print(catalan(i), end=" ") # This code is contributed by Aditi Sharma // C# program for nth Catalan Numberusing System;class GFG { // Returns value of Binomial Coefficient C(n, k) static long binomialCoeff(int n, int k) { long res = 1; // Since C(n, k) = C(n, n-k) if (k > n - k) { k = n - k; } // Calculate value of [n*(n-1)*---*(n-k+1)] / // [k*(k-1)*---*1] for (int i = 0; i < k; ++i) { res *= (n - i); res /= (i + 1); } return res; } // A Binomial coefficient based function to find nth // catalan number in O(n) time static long catalan(int n) { // Calculate value of 2nCn long c = binomialCoeff(2 * n, n); // return 2nCn/(n+1) return c / (n + 1); } // Driver code public static void Main() { for (int i = 0; i < 10; i++) { Console.Write(catalan(i) + " "); } }} // This code is contributed// by Akanksha Rai <?php// PHP program for nth Catalan Number // Returns value of Binomial// Coefficient C(n, k)function binomialCoeff($n, $k){ $res = 1; // Since C(n, k) = C(n, n-k) if ($k > $n - $k) $k = $n - $k; // Calculate value of [n*(n-1)*---*(n-k+1)] / // [k*(k-1)*---*1] for ($i = 0; $i < $k; ++$i) { $res *= ($n - $i); $res = floor($res / ($i + 1)); } return $res;} // A Binomial coefficient based function// to find nth catalan number in O(n) timefunction catalan($n){ // Calculate value of 2nCn $c = binomialCoeff(2 * ($n), $n); // return 2nCn/(n+1) return floor($c / ($n + 1));} // Driver codefor ($i = 0; $i < 10; $i++)echo catalan($i), " " ; // This code is contributed by Ryuga?> <script>// Javascript program for nth Catalan Number // Returns value of Binomial// Coefficient C(n, k)function binomialCoeff(n, k){ let res = 1; // Since C(n, k) = C(n, n-k) if (k > n - k) k = n - k; // Calculate value of [n*(n-1)*---*(n-k+1)] / // [k*(k-1)*---*1] for (let i = 0; i < k; ++i) { res *= (n - i); res = Math.floor(res / (i + 1)); } return res;} // A Binomial coefficient based function// to find nth catalan number in O(n) timefunction catalan(n){ // Calculate value of 2nCn c = binomialCoeff(2 * (n), n); // return 2nCn/(n+1) return Math.floor(c / (n + 1));} // Driver codefor (let i = 0; i < 10; i++)document.write(catalan(i) + " " ); // This code is contributed by _saurabh_jaiswal</script> 1 1 2 5 14 42 132 429 1430 4862 Time Complexity: Time complexity of above implementation is O(n).We can also use below formulas to find nth catalan number in O(n) time. Use multi-precision library: In this method, we have used boost multi-precision library, and the motive behind its use is just only to have precision meanwhile finding the large CATALAN’s number and a generalized technique using for loop to calculate Catalan numbers . For example: N = 5 Initially set cat_=1 then, print cat_ , then, iterate from i = 1 to i < 5 for i = 1; cat_ = cat_ * (4*1-2)=1*2=2cat_ = cat_ / (i+1)=2/2 = 1 For i = 2; cat_ = cat_ * (4*2-2)=1*6=6cat_ = cat_ / (i+1)=6/3=2 For i = 3 :- cat_ = cat_ * (4*3-2)=2*10=20cat_ = cat_ / (i+1)=20/4=5 For i = 4 :- cat_ = cat_ * (4*4-2)=5*14=70 cat_ = cat_ / (i+1)=70/5=14 Pseudocode: a) initially set cat_=1 and print it b) run a for loop i=1 to i<=n cat_ *= (4*i-2) cat_ /= (i+1) print cat_ c) end loop and exit C++ Java Python3 C# Javascript #include <bits/stdc++.h>#include <boost/multiprecision/cpp_int.hpp>using boost::multiprecision::cpp_int;using namespace std; // Function to print the numbervoid catalan(int n){ cpp_int cat_ = 1; // For the first number cout << cat_ << " "; // C(0) // Iterate till N for (cpp_int i = 1; i <=n; i++) { // Calculate the number // and print it cat_ *= (4 * i - 2); cat_ /= (i + 1); cout << cat_ << " "; }} // Driver codeint main(){ int n = 5; // Function call catalan(n); return 0;} import java.util.*;class GFG{ // Function to print the numberstatic void catalan(int n){ int cat_ = 1; // For the first number System.out.print(cat_+" "); // C(0) // Iterate till N for (int i = 1; i < n; i++) { // Calculate the number // and print it cat_ *= (4 * i - 2); cat_ /= (i + 1); System.out.print(cat_+" "); }} // Driver codepublic static void main(String args[]){ int n = 5; // Function call catalan(n);}} // This code is contributed by Debojyoti Mandal # Function to print the numberdef catalan(n): cat_ = 1 # For the first number print(cat_, " ", end = '')# C(0) # Iterate till N for i in range(1, n): # Calculate the number # and print it cat_ *= (4 * i - 2); cat_ //= (i + 1); print(cat_, " ", end = '') # Driver coden = 5 # Function callcatalan(n) # This code is contributed by rohan07 using System; public class GFG { // Function to print the number static void catalan(int n) { int cat_ = 1; // For the first number Console.Write(cat_ + " "); // C(0) // Iterate till N for (int i = 1; i < n; i++) { // Calculate the number // and print it cat_ *= (4 * i - 2); cat_ /= (i + 1); Console.Write(cat_ + " "); } } // Driver code public static void Main(String []args) { int n = 5; // Function call catalan(n); }} // This code is contributed by Rajput-Ji <script> // Function to print the numberfunction catalan(n){ let cat_ = 1; // For the first number document.write(cat_ + " "); // C(0) // Iterate till N for (let i = 1; i < n; i++) { // Calculate the number // and print it cat_ *= (4 * i - 2); cat_ /= (i + 1); document.write(cat_ + " "); }} // Driver code let n = 5; // Function call catalan(n); //This code is contributed by Mayank Tyagi</script> 1 1 2 5 14 Time Complexity: O(n)Auxiliary Space: O(1) Another solution using BigInteger in java: Finding values of catalan numbers for N>80 is not possible even by using long in java, so we use BigInteger Here we find solution using Binomial Coefficient method as discussed above Java C# import java.io.*;import java.util.*;import java.math.*; class GFG{ public static BigInteger findCatalan(int n) { // using BigInteger to calculate large factorials BigInteger b = new BigInteger("1"); // calculating n! for (int i = 1; i <= n; i++) { b = b.multiply(BigInteger.valueOf(i)); } // calculating n! * n! b = b.multiply(b); BigInteger d = new BigInteger("1"); // calculating (2n)! for (int i = 1; i <= 2 * n; i++) { d = d.multiply(BigInteger.valueOf(i)); } // calculating (2n)! / (n! * n!) BigInteger ans = d.divide(b); // calculating (2n)! / ((n! * n!) * (n+1)) ans = ans.divide(BigInteger.valueOf(n + 1)); return ans; } // Driver Code public static void main(String[] args) { int n = 5; System.out.println(findCatalan(n)); }}// Contributed by Rohit Oberoi // C# code to implement the approachusing System;using System.Numerics; class GFG { public static BigInteger findCatalan(int n) { // using BigInteger to calculate large factorials BigInteger b = new BigInteger(1); // calculating n! for (int i = 1; i <= n; i++) { b = BigInteger.Multiply(b, new BigInteger(i)); } // calculating n! * n! b = BigInteger.Multiply(b, b); BigInteger d = new BigInteger(1); // calculating (2n)! for (int i = 1; i <= 2 * n; i++) { d = BigInteger.Multiply(d, new BigInteger(i)); } // calculating (2n)! / (n! * n!) BigInteger ans = BigInteger.Divide(d, b); // calculating (2n)! / ((n! * n!) * (n+1)) ans = BigInteger.Divide(ans, new BigInteger(n + 1)); return ans; } // Driver Code public static void Main(string[] args) { int n = 5; Console.WriteLine(findCatalan(n)); }} // This code is contributed by phasing17. 42 References: http://en.wikipedia.org/wiki/Catalan_number Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above icr0 jit_t nitin mittal vt_m soumya7 29AjayKumar Harshit Singhal 2 ankthon Akanksha_Rai Chandan_Kumar Rajput-Ji anantiitrk ankit_deshmukh madhav_mohan RohitOberoi manishaediga23 jyoti369 _saurabh_jaiswal mayanktyagi1709 rohan07 bunnyram19 manishku12j amartyaghoshgfg prasanna1995 07prashantsgh Amazon catalan series Dynamic Programming Mathematical Misc Amazon Misc Dynamic Programming Mathematical Misc series Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Largest Sum Contiguous Subarray Program for Fibonacci numbers 0-1 Knapsack Problem | DP-10 Longest Common Subsequence | DP-4 Subset Sum Problem | DP-25 Program for Fibonacci numbers Set in C++ Standard Template Library (STL) Write a program to print all permutations of a given string C++ Data Types Merge two sorted arrays
[ { "code": null, "e": 54, "s": 26, "text": "\n07 Jul, 2022" }, { "code": null, "e": 170, "s": 54, "text": "Catalan numbers are a sequence of natural numbers that occurs in many interesting counting problems like following." }, { "code": null, "e": 680, "s": 170, "text": "Count the number of expressions containing n pairs of parentheses which are correctly matched. For n = 3, possible expressions are ((())), ()(()), ()()(), (())(), (()()).Count the number of possible Binary Search Trees with n keys (See this)Count the number of full binary trees (A rooted binary tree is full if every vertex has either two children or no children) with n+1 leaves.Given a number n, return the number of ways you can draw n chords in a circle with 2 x n points such that no 2 chords intersect." }, { "code": null, "e": 851, "s": 680, "text": "Count the number of expressions containing n pairs of parentheses which are correctly matched. For n = 3, possible expressions are ((())), ()(()), ()()(), (())(), (()())." }, { "code": null, "e": 923, "s": 851, "text": "Count the number of possible Binary Search Trees with n keys (See this)" }, { "code": null, "e": 1064, "s": 923, "text": "Count the number of full binary trees (A rooted binary tree is full if every vertex has either two children or no children) with n+1 leaves." }, { "code": null, "e": 1193, "s": 1064, "text": "Given a number n, return the number of ways you can draw n chords in a circle with 2 x n points such that no 2 chords intersect." }, { "code": null, "e": 1331, "s": 1193, "text": "See this for more applications. The first few Catalan numbers for n = 0, 1, 2, 3, ... are 1, 1, 2, 5, 14, 42, 132, 429, 1430, 4862, ... " }, { "code": null, "e": 1408, "s": 1331, "text": "Recursive Solution Catalan numbers satisfy the following recursive formula. " }, { "code": null, "e": 1470, "s": 1408, "text": "Following is the implementation of above recursive formula. " }, { "code": null, "e": 1479, "s": 1470, "text": "Chapters" }, { "code": null, "e": 1506, "s": 1479, "text": "descriptions off, selected" }, { "code": null, "e": 1556, "s": 1506, "text": "captions settings, opens captions settings dialog" }, { "code": null, "e": 1579, "s": 1556, "text": "captions off, selected" }, { "code": null, "e": 1587, "s": 1579, "text": "English" }, { "code": null, "e": 1611, "s": 1587, "text": "This is a modal window." }, { "code": null, "e": 1680, "s": 1611, "text": "Beginning of dialog window. Escape will cancel and close the window." }, { "code": null, "e": 1702, "s": 1680, "text": "End of dialog window." }, { "code": null, "e": 1706, "s": 1702, "text": "C++" }, { "code": null, "e": 1711, "s": 1706, "text": "Java" }, { "code": null, "e": 1719, "s": 1711, "text": "Python3" }, { "code": null, "e": 1722, "s": 1719, "text": "C#" }, { "code": null, "e": 1726, "s": 1722, "text": "PHP" }, { "code": null, "e": 1737, "s": 1726, "text": "Javascript" }, { "code": "#include <iostream>using namespace std; // A recursive function to find nth catalan numberunsigned long int catalan(unsigned int n){ // Base case if (n <= 1) return 1; // catalan(n) is sum of // catalan(i)*catalan(n-i-1) unsigned long int res = 0; for (int i = 0; i < n; i++) res += catalan(i) * catalan(n - i - 1); return res;} // Driver codeint main(){ for (int i = 0; i < 10; i++) cout << catalan(i) << \" \"; return 0;}", "e": 2220, "s": 1737, "text": null }, { "code": "class CatalnNumber { // A recursive function to find nth catalan number int catalan(int n) { int res = 0; // Base case if (n <= 1) { return 1; } for (int i = 0; i < n; i++) { res += catalan(i) * catalan(n - i - 1); } return res; } // Driver Code public static void main(String[] args) { CatalnNumber cn = new CatalnNumber(); for (int i = 0; i < 10; i++) { System.out.print(cn.catalan(i) + \" \"); } }}", "e": 2787, "s": 2220, "text": null }, { "code": "# A recursive function to# find nth catalan numberdef catalan(n): # Base Case if n <= 1: return 1 # Catalan(n) is the sum # of catalan(i)*catalan(n-i-1) res = 0 for i in range(n): res += catalan(i) * catalan(n-i-1) return res # Driver Codefor i in range(10): print (catalan(i),end=\" \")# This code is contributed by# Nikhil Kumar Singh (nickzuck_007)", "e": 3178, "s": 2787, "text": null }, { "code": "// A recursive C# program to find// nth catalan numberusing System; class GFG { // A recursive function to find // nth catalan number static int catalan(int n) { int res = 0; // Base case if (n <= 1) { return 1; } for (int i = 0; i < n; i++) { res += catalan(i) * catalan(n - i - 1); } return res; } // Driver Code public static void Main() { for (int i = 0; i < 10; i++) Console.Write(catalan(i) + \" \"); }} // This code is contributed by// nitin mittal.", "e": 3781, "s": 3178, "text": null }, { "code": "<?php// PHP Program for nth// Catalan Number // A recursive function to// find nth catalan numberfunction catalan($n){ // Base case if ($n <= 1) return 1; // catalan(n) is sum of // catalan(i)*catalan(n-i-1) $res = 0; for($i = 0; $i < $n; $i++) $res += catalan($i) * catalan($n - $i - 1); return $res;} // Driver Codefor ($i = 0; $i < 10; $i++) echo catalan($i), \" \"; // This code is contributed aj_36?>", "e": 4245, "s": 3781, "text": null }, { "code": "<script> // Javascript Program for nth// Catalan Number // A recursive function to// find nth catalan numberfunction catalan(n){ // Base case if (n <= 1) return 1; // catalan(n) is sum of // catalan(i)*catalan(n-i-1) let res = 0; for(let i = 0; i < n; i++) res += catalan(i) * catalan(n - i - 1); return res;} // Driver Codefor (let i = 0; i < 10; i++) document.write(catalan(i) + \" \"); // This code is contributed _saurabh_jaiswal </script>", "e": 4747, "s": 4245, "text": null }, { "code": null, "e": 4780, "s": 4747, "text": "1 1 2 5 14 42 132 429 1430 4862 " }, { "code": null, "e": 4858, "s": 4780, "text": "Time complexity of above implementation is equivalent to nth catalan number. " }, { "code": null, "e": 4951, "s": 4860, "text": "The value of nth catalan number is exponential that makes the time complexity exponential." }, { "code": null, "e": 5250, "s": 4951, "text": "Dynamic Programming Solution : We can observe that the above recursive implementation does a lot of repeated work (we can the same by drawing recursion tree). Since there are overlapping subproblems, we can use dynamic programming for this. Following is a Dynamic programming based implementation ." }, { "code": null, "e": 5254, "s": 5250, "text": "C++" }, { "code": null, "e": 5259, "s": 5254, "text": "Java" }, { "code": null, "e": 5267, "s": 5259, "text": "Python3" }, { "code": null, "e": 5270, "s": 5267, "text": "C#" }, { "code": null, "e": 5274, "s": 5270, "text": "PHP" }, { "code": null, "e": 5285, "s": 5274, "text": "Javascript" }, { "code": "#include <iostream>using namespace std; // A dynamic programming based function to find nth// Catalan numberunsigned long int catalanDP(unsigned int n){ // Table to store results of subproblems unsigned long int catalan[n + 1]; // Initialize first two values in table catalan[0] = catalan[1] = 1; // Fill entries in catalan[] using recursive formula for (int i = 2; i <= n; i++) { catalan[i] = 0; for (int j = 0; j < i; j++) catalan[i] += catalan[j] * catalan[i - j - 1]; } // Return last entry return catalan[n];} // Driver codeint main(){ for (int i = 0; i < 10; i++) cout << catalanDP(i) << \" \"; return 0;}", "e": 5963, "s": 5285, "text": null }, { "code": "class GFG { // A dynamic programming based function to find nth // Catalan number static int catalanDP(int n) { // Table to store results of subproblems int catalan[] = new int[n + 2]; // Initialize first two values in table catalan[0] = 1; catalan[1] = 1; // Fill entries in catalan[] // using recursive formula for (int i = 2; i <= n; i++) { catalan[i] = 0; for (int j = 0; j < i; j++) { catalan[i] += catalan[j] * catalan[i - j - 1]; } } // Return last entry return catalan[n]; } // Driver code public static void main(String[] args) { for (int i = 0; i < 10; i++) { System.out.print(catalanDP(i) + \" \"); } }}// This code contributed by Rajput-Ji", "e": 6814, "s": 5963, "text": null }, { "code": "# A dynamic programming based function to find nth# Catalan number def catalan(n): if (n == 0 or n == 1): return 1 # Table to store results of subproblems catalan =[0]*(n+1) # Initialize first two values in table catalan[0] = 1 catalan[1] = 1 # Fill entries in catalan[] # using recursive formula for i in range(2, n + 1): for j in range(i): catalan[i] += catalan[j]* catalan[i-j-1] # Return last entry return catalan[n] # Driver codefor i in range(10): print(catalan(i), end=\" \")# This code is contributed by Ediga_manisha", "e": 7405, "s": 6814, "text": null }, { "code": "using System; class GFG { // A dynamic programming based // function to find nth // Catalan number static uint catalanDP(uint n) { // Table to store results of subproblems uint[] catalan = new uint[n + 2]; // Initialize first two values in table catalan[0] = catalan[1] = 1; // Fill entries in catalan[] // using recursive formula for (uint i = 2; i <= n; i++) { catalan[i] = 0; for (uint j = 0; j < i; j++) catalan[i] += catalan[j] * catalan[i - j - 1]; } // Return last entry return catalan[n]; } // Driver code static void Main() { for (uint i = 0; i < 10; i++) Console.Write(catalanDP(i) + \" \"); }} // This code is contributed by Chandan_jnu", "e": 8230, "s": 7405, "text": null }, { "code": "<?php// PHP program for nth Catalan Number // A dynamic programming based function// to find nth Catalan numberfunction catalanDP( $n){ // Table to store results // of subproblems $catalan= array(); // Initialize first two // values in table $catalan[0] = $catalan[1] = 1; // Fill entries in catalan[] // using recursive formula for ($i = 2; $i <= $n; $i++) { $catalan[$i] = 0; for ( $j = 0; $j < $i; $j++) $catalan[$i] += $catalan[$j] * $catalan[$i - $j - 1]; } // Return last entry return $catalan[$n];} // Driver Code for ($i = 0; $i < 10; $i++) echo catalanDP($i) , \" \"; // This code is contributed anuj_67.?>", "e": 8948, "s": 8230, "text": null }, { "code": "<script>// Javascript program for nth Catalan Number // A dynamic programming based function// to find nth Catalan numberfunction catalanDP(n){ // Table to store results // of subproblems let catalan= []; // Initialize first two // values in table catalan[0] = catalan[1] = 1; // Fill entries in catalan[] // using recursive formula for (let i = 2; i <= n; i++) { catalan[i] = 0; for (let j = 0; j < i; j++) catalan[i] += catalan[j] * catalan[i - j - 1]; } // Return last entry return catalan[n];} // Driver Code for (let i = 0; i < 10; i++) document.write(catalanDP(i) + \" \"); // This code is contributed _saurabh_jaiswal</script>", "e": 9684, "s": 8948, "text": null }, { "code": null, "e": 9717, "s": 9684, "text": "1 1 2 5 14 42 132 429 1430 4862 " }, { "code": null, "e": 9783, "s": 9717, "text": "Time Complexity: Time complexity of above implementation is O(n2)" }, { "code": null, "e": 9886, "s": 9783, "text": "Using Binomial Coefficient We can also use the below formula to find nth Catalan number in O(n) time. " }, { "code": null, "e": 9956, "s": 9886, "text": " We have discussed a O(n) approach to find binomial coefficient nCr. " }, { "code": null, "e": 9960, "s": 9956, "text": "C++" }, { "code": null, "e": 9965, "s": 9960, "text": "Java" }, { "code": null, "e": 9973, "s": 9965, "text": "Python3" }, { "code": null, "e": 9976, "s": 9973, "text": "C#" }, { "code": null, "e": 9980, "s": 9976, "text": "PHP" }, { "code": null, "e": 9991, "s": 9980, "text": "Javascript" }, { "code": "// C++ program for nth Catalan Number#include <iostream>using namespace std; // Returns value of Binomial Coefficient C(n, k)unsigned long int binomialCoeff(unsigned int n, unsigned int k){ unsigned long int res = 1; // Since C(n, k) = C(n, n-k) if (k > n - k) k = n - k; // Calculate value of [n*(n-1)*---*(n-k+1)] / // [k*(k-1)*---*1] for (int i = 0; i < k; ++i) { res *= (n - i); res /= (i + 1); } return res;} // A Binomial coefficient based function to find nth catalan// number in O(n) timeunsigned long int catalan(unsigned int n){ // Calculate value of 2nCn unsigned long int c = binomialCoeff(2 * n, n); // return 2nCn/(n+1) return c / (n + 1);} // Driver codeint main(){ for (int i = 0; i < 10; i++) cout << catalan(i) << \" \"; return 0;}", "e": 10844, "s": 9991, "text": null }, { "code": "// Java program for nth Catalan Number class GFG { // Returns value of Binomial Coefficient C(n, k) static long binomialCoeff(int n, int k) { long res = 1; // Since C(n, k) = C(n, n-k) if (k > n - k) { k = n - k; } // Calculate value of [n*(n-1)*---*(n-k+1)] / // [k*(k-1)*---*1] for (int i = 0; i < k; ++i) { res *= (n - i); res /= (i + 1); } return res; } // A Binomial coefficient based function // to find nth catalan number in O(n) time static long catalan(int n) { // Calculate value of 2nCn long c = binomialCoeff(2 * n, n); // return 2nCn/(n+1) return c / (n + 1); } // Driver code public static void main(String[] args) { for (int i = 0; i < 10; i++) { System.out.print(catalan(i) + \" \"); } }}", "e": 11743, "s": 10844, "text": null }, { "code": "# Python program for nth Catalan Number# Returns value of Binomial Coefficient C(n, k) def binomialCoefficient(n, k): # since C(n, k) = C(n, n - k) if (k > n - k): k = n - k # initialize result res = 1 # Calculate value of [n * (n-1) *---* (n-k + 1)] # / [k * (k-1) *----* 1] for i in range(k): res = res * (n - i) res = res / (i + 1) return res # A Binomial coefficient based function to# find nth catalan number in O(n) time def catalan(n): c = binomialCoefficient(2*n, n) return c/(n + 1) # Driver Codefor i in range(10): print(catalan(i), end=\" \") # This code is contributed by Aditi Sharma", "e": 12397, "s": 11743, "text": null }, { "code": "// C# program for nth Catalan Numberusing System;class GFG { // Returns value of Binomial Coefficient C(n, k) static long binomialCoeff(int n, int k) { long res = 1; // Since C(n, k) = C(n, n-k) if (k > n - k) { k = n - k; } // Calculate value of [n*(n-1)*---*(n-k+1)] / // [k*(k-1)*---*1] for (int i = 0; i < k; ++i) { res *= (n - i); res /= (i + 1); } return res; } // A Binomial coefficient based function to find nth // catalan number in O(n) time static long catalan(int n) { // Calculate value of 2nCn long c = binomialCoeff(2 * n, n); // return 2nCn/(n+1) return c / (n + 1); } // Driver code public static void Main() { for (int i = 0; i < 10; i++) { Console.Write(catalan(i) + \" \"); } }} // This code is contributed// by Akanksha Rai", "e": 13335, "s": 12397, "text": null }, { "code": "<?php// PHP program for nth Catalan Number // Returns value of Binomial// Coefficient C(n, k)function binomialCoeff($n, $k){ $res = 1; // Since C(n, k) = C(n, n-k) if ($k > $n - $k) $k = $n - $k; // Calculate value of [n*(n-1)*---*(n-k+1)] / // [k*(k-1)*---*1] for ($i = 0; $i < $k; ++$i) { $res *= ($n - $i); $res = floor($res / ($i + 1)); } return $res;} // A Binomial coefficient based function// to find nth catalan number in O(n) timefunction catalan($n){ // Calculate value of 2nCn $c = binomialCoeff(2 * ($n), $n); // return 2nCn/(n+1) return floor($c / ($n + 1));} // Driver codefor ($i = 0; $i < 10; $i++)echo catalan($i), \" \" ; // This code is contributed by Ryuga?>", "e": 14095, "s": 13335, "text": null }, { "code": "<script>// Javascript program for nth Catalan Number // Returns value of Binomial// Coefficient C(n, k)function binomialCoeff(n, k){ let res = 1; // Since C(n, k) = C(n, n-k) if (k > n - k) k = n - k; // Calculate value of [n*(n-1)*---*(n-k+1)] / // [k*(k-1)*---*1] for (let i = 0; i < k; ++i) { res *= (n - i); res = Math.floor(res / (i + 1)); } return res;} // A Binomial coefficient based function// to find nth catalan number in O(n) timefunction catalan(n){ // Calculate value of 2nCn c = binomialCoeff(2 * (n), n); // return 2nCn/(n+1) return Math.floor(c / (n + 1));} // Driver codefor (let i = 0; i < 10; i++)document.write(catalan(i) + \" \" ); // This code is contributed by _saurabh_jaiswal</script>", "e": 14888, "s": 14095, "text": null }, { "code": null, "e": 14921, "s": 14888, "text": "1 1 2 5 14 42 132 429 1430 4862 " }, { "code": null, "e": 15059, "s": 14921, "text": "Time Complexity: Time complexity of above implementation is O(n).We can also use below formulas to find nth catalan number in O(n) time. " }, { "code": null, "e": 15331, "s": 15059, "text": "Use multi-precision library: In this method, we have used boost multi-precision library, and the motive behind its use is just only to have precision meanwhile finding the large CATALAN’s number and a generalized technique using for loop to calculate Catalan numbers . " }, { "code": null, "e": 15350, "s": 15331, "text": "For example: N = 5" }, { "code": null, "e": 15391, "s": 15350, "text": "Initially set cat_=1 then, print cat_ ," }, { "code": null, "e": 15425, "s": 15391, "text": "then, iterate from i = 1 to i < 5" }, { "code": null, "e": 15497, "s": 15425, "text": "for i = 1; cat_ = cat_ * (4*1-2)=1*2=2cat_ = cat_ / (i+1)=2/2 = 1 " }, { "code": null, "e": 15563, "s": 15497, "text": "For i = 2; cat_ = cat_ * (4*2-2)=1*6=6cat_ = cat_ / (i+1)=6/3=2 " }, { "code": null, "e": 15640, "s": 15563, "text": "For i = 3 :- cat_ = cat_ * (4*3-2)=2*10=20cat_ = cat_ / (i+1)=20/4=5 " }, { "code": null, "e": 15721, "s": 15640, "text": "For i = 4 :- cat_ = cat_ * (4*4-2)=5*14=70 cat_ = cat_ / (i+1)=70/5=14 " }, { "code": null, "e": 15734, "s": 15721, "text": "Pseudocode: " }, { "code": null, "e": 15907, "s": 15734, "text": "a) initially set cat_=1 and print it\nb) run a for loop i=1 to i<=n\n cat_ *= (4*i-2)\n cat_ /= (i+1)\n print cat_\nc) end loop and exit " }, { "code": null, "e": 15911, "s": 15907, "text": "C++" }, { "code": null, "e": 15916, "s": 15911, "text": "Java" }, { "code": null, "e": 15924, "s": 15916, "text": "Python3" }, { "code": null, "e": 15927, "s": 15924, "text": "C#" }, { "code": null, "e": 15938, "s": 15927, "text": "Javascript" }, { "code": "#include <bits/stdc++.h>#include <boost/multiprecision/cpp_int.hpp>using boost::multiprecision::cpp_int;using namespace std; // Function to print the numbervoid catalan(int n){ cpp_int cat_ = 1; // For the first number cout << cat_ << \" \"; // C(0) // Iterate till N for (cpp_int i = 1; i <=n; i++) { // Calculate the number // and print it cat_ *= (4 * i - 2); cat_ /= (i + 1); cout << cat_ << \" \"; }} // Driver codeint main(){ int n = 5; // Function call catalan(n); return 0;}", "e": 16488, "s": 15938, "text": null }, { "code": "import java.util.*;class GFG{ // Function to print the numberstatic void catalan(int n){ int cat_ = 1; // For the first number System.out.print(cat_+\" \"); // C(0) // Iterate till N for (int i = 1; i < n; i++) { // Calculate the number // and print it cat_ *= (4 * i - 2); cat_ /= (i + 1); System.out.print(cat_+\" \"); }} // Driver codepublic static void main(String args[]){ int n = 5; // Function call catalan(n);}} // This code is contributed by Debojyoti Mandal", "e": 17022, "s": 16488, "text": null }, { "code": "# Function to print the numberdef catalan(n): cat_ = 1 # For the first number print(cat_, \" \", end = '')# C(0) # Iterate till N for i in range(1, n): # Calculate the number # and print it cat_ *= (4 * i - 2); cat_ //= (i + 1); print(cat_, \" \", end = '') # Driver coden = 5 # Function callcatalan(n) # This code is contributed by rohan07", "e": 17425, "s": 17022, "text": null }, { "code": "using System; public class GFG { // Function to print the number static void catalan(int n) { int cat_ = 1; // For the first number Console.Write(cat_ + \" \"); // C(0) // Iterate till N for (int i = 1; i < n; i++) { // Calculate the number // and print it cat_ *= (4 * i - 2); cat_ /= (i + 1); Console.Write(cat_ + \" \"); } } // Driver code public static void Main(String []args) { int n = 5; // Function call catalan(n); }} // This code is contributed by Rajput-Ji", "e": 18030, "s": 17425, "text": null }, { "code": "<script> // Function to print the numberfunction catalan(n){ let cat_ = 1; // For the first number document.write(cat_ + \" \"); // C(0) // Iterate till N for (let i = 1; i < n; i++) { // Calculate the number // and print it cat_ *= (4 * i - 2); cat_ /= (i + 1); document.write(cat_ + \" \"); }} // Driver code let n = 5; // Function call catalan(n); //This code is contributed by Mayank Tyagi</script>", "e": 18497, "s": 18030, "text": null }, { "code": null, "e": 18509, "s": 18497, "text": "1 1 2 5 14 " }, { "code": null, "e": 18552, "s": 18509, "text": "Time Complexity: O(n)Auxiliary Space: O(1)" }, { "code": null, "e": 18595, "s": 18552, "text": "Another solution using BigInteger in java:" }, { "code": null, "e": 18703, "s": 18595, "text": "Finding values of catalan numbers for N>80 is not possible even by using long in java, so we use BigInteger" }, { "code": null, "e": 18778, "s": 18703, "text": "Here we find solution using Binomial Coefficient method as discussed above" }, { "code": null, "e": 18783, "s": 18778, "text": "Java" }, { "code": null, "e": 18786, "s": 18783, "text": "C#" }, { "code": "import java.io.*;import java.util.*;import java.math.*; class GFG{ public static BigInteger findCatalan(int n) { // using BigInteger to calculate large factorials BigInteger b = new BigInteger(\"1\"); // calculating n! for (int i = 1; i <= n; i++) { b = b.multiply(BigInteger.valueOf(i)); } // calculating n! * n! b = b.multiply(b); BigInteger d = new BigInteger(\"1\"); // calculating (2n)! for (int i = 1; i <= 2 * n; i++) { d = d.multiply(BigInteger.valueOf(i)); } // calculating (2n)! / (n! * n!) BigInteger ans = d.divide(b); // calculating (2n)! / ((n! * n!) * (n+1)) ans = ans.divide(BigInteger.valueOf(n + 1)); return ans; } // Driver Code public static void main(String[] args) { int n = 5; System.out.println(findCatalan(n)); }}// Contributed by Rohit Oberoi", "e": 19729, "s": 18786, "text": null }, { "code": "// C# code to implement the approachusing System;using System.Numerics; class GFG { public static BigInteger findCatalan(int n) { // using BigInteger to calculate large factorials BigInteger b = new BigInteger(1); // calculating n! for (int i = 1; i <= n; i++) { b = BigInteger.Multiply(b, new BigInteger(i)); } // calculating n! * n! b = BigInteger.Multiply(b, b); BigInteger d = new BigInteger(1); // calculating (2n)! for (int i = 1; i <= 2 * n; i++) { d = BigInteger.Multiply(d, new BigInteger(i)); } // calculating (2n)! / (n! * n!) BigInteger ans = BigInteger.Divide(d, b); // calculating (2n)! / ((n! * n!) * (n+1)) ans = BigInteger.Divide(ans, new BigInteger(n + 1)); return ans; } // Driver Code public static void Main(string[] args) { int n = 5; Console.WriteLine(findCatalan(n)); }} // This code is contributed by phasing17.", "e": 20644, "s": 19729, "text": null }, { "code": null, "e": 20647, "s": 20644, "text": "42" }, { "code": null, "e": 20830, "s": 20649, "text": "References: http://en.wikipedia.org/wiki/Catalan_number Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above " }, { "code": null, "e": 20837, "s": 20832, "text": "icr0" }, { "code": null, "e": 20843, "s": 20837, "text": "jit_t" }, { "code": null, "e": 20856, "s": 20843, "text": "nitin mittal" }, { "code": null, "e": 20861, "s": 20856, "text": "vt_m" }, { "code": null, "e": 20869, "s": 20861, "text": "soumya7" }, { "code": null, "e": 20881, "s": 20869, "text": "29AjayKumar" }, { "code": null, "e": 20899, "s": 20881, "text": "Harshit Singhal 2" }, { "code": null, "e": 20907, "s": 20899, "text": "ankthon" }, { "code": null, "e": 20920, "s": 20907, "text": "Akanksha_Rai" }, { "code": null, "e": 20934, "s": 20920, "text": "Chandan_Kumar" }, { "code": null, "e": 20944, "s": 20934, "text": "Rajput-Ji" }, { "code": null, "e": 20955, "s": 20944, "text": "anantiitrk" }, { "code": null, "e": 20970, "s": 20955, "text": "ankit_deshmukh" }, { "code": null, "e": 20983, "s": 20970, "text": "madhav_mohan" }, { "code": null, "e": 20995, "s": 20983, "text": "RohitOberoi" }, { "code": null, "e": 21010, "s": 20995, "text": "manishaediga23" }, { "code": null, "e": 21019, "s": 21010, "text": "jyoti369" }, { "code": null, "e": 21036, "s": 21019, "text": "_saurabh_jaiswal" }, { "code": null, "e": 21052, "s": 21036, "text": "mayanktyagi1709" }, { "code": null, "e": 21060, "s": 21052, "text": "rohan07" }, { "code": null, "e": 21071, "s": 21060, "text": "bunnyram19" }, { "code": null, "e": 21083, "s": 21071, "text": "manishku12j" }, { "code": null, "e": 21099, "s": 21083, "text": "amartyaghoshgfg" }, { "code": null, "e": 21112, "s": 21099, "text": "prasanna1995" }, { "code": null, "e": 21126, "s": 21112, "text": "07prashantsgh" }, { "code": null, "e": 21133, "s": 21126, "text": "Amazon" }, { "code": null, "e": 21141, "s": 21133, "text": "catalan" }, { "code": null, "e": 21148, "s": 21141, "text": "series" }, { "code": null, "e": 21168, "s": 21148, "text": "Dynamic Programming" }, { "code": null, "e": 21181, "s": 21168, "text": "Mathematical" }, { "code": null, "e": 21186, "s": 21181, "text": "Misc" }, { "code": null, "e": 21193, "s": 21186, "text": "Amazon" }, { "code": null, "e": 21198, "s": 21193, "text": "Misc" }, { "code": null, "e": 21218, "s": 21198, "text": "Dynamic Programming" }, { "code": null, "e": 21231, "s": 21218, "text": "Mathematical" }, { "code": null, "e": 21236, "s": 21231, "text": "Misc" }, { "code": null, "e": 21243, "s": 21236, "text": "series" }, { "code": null, "e": 21341, "s": 21243, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 21373, "s": 21341, "text": "Largest Sum Contiguous Subarray" }, { "code": null, "e": 21403, "s": 21373, "text": "Program for Fibonacci numbers" }, { "code": null, "e": 21432, "s": 21403, "text": "0-1 Knapsack Problem | DP-10" }, { "code": null, "e": 21466, "s": 21432, "text": "Longest Common Subsequence | DP-4" }, { "code": null, "e": 21493, "s": 21466, "text": "Subset Sum Problem | DP-25" }, { "code": null, "e": 21523, "s": 21493, "text": "Program for Fibonacci numbers" }, { "code": null, "e": 21566, "s": 21523, "text": "Set in C++ Standard Template Library (STL)" }, { "code": null, "e": 21626, "s": 21566, "text": "Write a program to print all permutations of a given string" }, { "code": null, "e": 21641, "s": 21626, "text": "C++ Data Types" } ]
How to check pointer or interface is nil or not in Golang?
10 May, 2020 In Golang, nil check is frequently seen in GoLang code especially for error check. In most cases, nil check is straight forward, but in interface case, it’s a bit different and special care needs to be taken. Here the task is to check pointer or interface is nil or not in Golang, you can check with the following: Example 1: In this example, the pointer is checked whether it is a nil pointer or not. // Go program to illustrate how to// check pointer is nil or not package main import ( "fmt") type Temp struct {} func main() { var pnt *Temp // pointer var x = "123" var pnt1 *string = &x fmt.Printf("pnt is a nil pointer: %v\n", pnt == nil) fmt.Printf("pnt1 is a nil pointer: %v\n", pnt1 == nil)} Output: pnt is a nil pointer: true pnt1 is a nil pointer: false Example 2: In this example, the interface is checked whether it is a nil interface or not. // Go program to illustrate how to// check interface is nil or not package main import ( "fmt") // Creating an interfacetype tank interface { // Methods Tarea() float64 Volume() float64} type myvalue struct { radius float64 height float64} // Implementing methods of// the tank interfacefunc (m myvalue) Tarea() float64 { return 2*m.radius*m.height + 2*3.14*m.radius*m.radius} func (m myvalue) Volume() float64 { return 3.14 * m.radius * m.radius * m.height} func main() { var t tank fmt.Printf("t is a nil interface: %v\n", t == nil) t = myvalue{10, 14} fmt.Printf("t is a nil interface: %v\n", t == nil) } Output: t is a nil interface: true t is a nil interface: false Example 3: In this example, the interface holding a nil pointer is checked whether it is a nil interface or not. // Go program to illustrate how to// check interface holding a nil// pointer is nil or not package main import ( "fmt") type Temp struct {} func main() { // taking a pointer var val *Temp // taking a interface var val2 interface{} // val2 is a non-nil interface // holding a nil pointer (val) val2 = val fmt.Printf("val2 is a nil interface: %v\n", val2 == nil) fmt.Printf("val2 is a interface holding a nil"+ " pointer: %v\n", val2 == (*Temp)(nil))} Output: val2 is a nil interface: false val2 is a interface holding a nil pointer: true Golang-Interfaces Golang-Pointers Golang-Program Picked Go Language Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n10 May, 2020" }, { "code": null, "e": 237, "s": 28, "text": "In Golang, nil check is frequently seen in GoLang code especially for error check. In most cases, nil check is straight forward, but in interface case, it’s a bit different and special care needs to be taken." }, { "code": null, "e": 343, "s": 237, "text": "Here the task is to check pointer or interface is nil or not in Golang, you can check with the following:" }, { "code": null, "e": 430, "s": 343, "text": "Example 1: In this example, the pointer is checked whether it is a nil pointer or not." }, { "code": "// Go program to illustrate how to// check pointer is nil or not package main import ( \"fmt\") type Temp struct {} func main() { var pnt *Temp // pointer var x = \"123\" var pnt1 *string = &x fmt.Printf(\"pnt is a nil pointer: %v\\n\", pnt == nil) fmt.Printf(\"pnt1 is a nil pointer: %v\\n\", pnt1 == nil)}", "e": 752, "s": 430, "text": null }, { "code": null, "e": 760, "s": 752, "text": "Output:" }, { "code": null, "e": 817, "s": 760, "text": "pnt is a nil pointer: true\npnt1 is a nil pointer: false\n" }, { "code": null, "e": 908, "s": 817, "text": "Example 2: In this example, the interface is checked whether it is a nil interface or not." }, { "code": "// Go program to illustrate how to// check interface is nil or not package main import ( \"fmt\") // Creating an interfacetype tank interface { // Methods Tarea() float64 Volume() float64} type myvalue struct { radius float64 height float64} // Implementing methods of// the tank interfacefunc (m myvalue) Tarea() float64 { return 2*m.radius*m.height + 2*3.14*m.radius*m.radius} func (m myvalue) Volume() float64 { return 3.14 * m.radius * m.radius * m.height} func main() { var t tank fmt.Printf(\"t is a nil interface: %v\\n\", t == nil) t = myvalue{10, 14} fmt.Printf(\"t is a nil interface: %v\\n\", t == nil) }", "e": 1579, "s": 908, "text": null }, { "code": null, "e": 1587, "s": 1579, "text": "Output:" }, { "code": null, "e": 1643, "s": 1587, "text": "t is a nil interface: true\nt is a nil interface: false\n" }, { "code": null, "e": 1756, "s": 1643, "text": "Example 3: In this example, the interface holding a nil pointer is checked whether it is a nil interface or not." }, { "code": "// Go program to illustrate how to// check interface holding a nil// pointer is nil or not package main import ( \"fmt\") type Temp struct {} func main() { // taking a pointer var val *Temp // taking a interface var val2 interface{} // val2 is a non-nil interface // holding a nil pointer (val) val2 = val fmt.Printf(\"val2 is a nil interface: %v\\n\", val2 == nil) fmt.Printf(\"val2 is a interface holding a nil\"+ \" pointer: %v\\n\", val2 == (*Temp)(nil))}", "e": 2261, "s": 1756, "text": null }, { "code": null, "e": 2269, "s": 2261, "text": "Output:" }, { "code": null, "e": 2349, "s": 2269, "text": "val2 is a nil interface: false\nval2 is a interface holding a nil pointer: true\n" }, { "code": null, "e": 2367, "s": 2349, "text": "Golang-Interfaces" }, { "code": null, "e": 2383, "s": 2367, "text": "Golang-Pointers" }, { "code": null, "e": 2398, "s": 2383, "text": "Golang-Program" }, { "code": null, "e": 2405, "s": 2398, "text": "Picked" }, { "code": null, "e": 2417, "s": 2405, "text": "Go Language" } ]
CMSmap – Open Source CMS Scanner
14 Sep, 2021 CMSmap is a Python open source CMS scanner that automates the method of detecting security flaws of the foremost popular CMSs. The main purpose of this tool is to integrate common vulnerabilities for different types of CMSs into a single tool. at the instant, there’s support for WordPress, Joomla, Drupal, and Moodle. CMSmap tool is freely available on GitHub. CMSmap tool supports multiple target domain scanning and saves the results in text file format. CMSmap tool has the ability to set custom user-agent and header. CMSmap tool Support for SSL encryption. CMSmap tool supports Verbose mode for debugging purposes. Note: Make Sure You have Python Installed on your System, as this is a python-based tool. Click to check the Installation process: Python Installation Steps on Linux Step 1: Use the following command to install the tool in your Kali Linux operating system. git clone https://github.com/Dionach/CMSmap.git Step 2: Now use the following command to move into the directory of the tool. You have to move in the directory in order to run the tool. cd CMSmap Step 3: You are in the directory of the CMSmap. Now run the following command to complete the installation. sudo python3 setup.py install Step 4: All the dependencies have been installed in your Kali Linux operating system. Now use the following command to run the tool and check the help section. python3 cmsmap .py -h Example 1: Simple Scan (Single Target) python3 cmsmap.py https://geeksforgeeks.org In this Example, We are performing simple scanning on the target domain geeksforgeeks.org. We have got the details of CMS and the theme applied to the domain. The tool has identified the WordPress usernames on geeksforgeeks.org. Example 2: Force scan WordPress python3 cmsmap.py https://geeksforgeeks.org -f W -F --noedb -d In this Example, We are performing a Force scan of WordPress CMS on geeksforgeeks.org. Example 3: Scan multiple targets listed in a given file python3 cmsmap.py -i targets.txt -o output.txt -f D In this Example, We are scanning multiple target domains specified in the targets.txt file. Example 4: Verbose Mode python3 cmsmap.py https://geeksforgeeks.org -v In this Example, We are displaying the scan results in a more detailed way. We have used the -v tag for enabling the verbose mode. Kali-Linux Linux-Tools Linux-Unix Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Docker - COPY Instruction scp command in Linux with Examples chown command in Linux with Examples SED command in Linux | Set 2 mv command in Linux with examples nohup Command in Linux with Examples chmod command in Linux with examples Introduction to Linux Operating System Array Basics in Shell Scripting | Set 1 Basic Operators in Shell Scripting
[ { "code": null, "e": 28, "s": 0, "text": "\n14 Sep, 2021" }, { "code": null, "e": 649, "s": 28, "text": "CMSmap is a Python open source CMS scanner that automates the method of detecting security flaws of the foremost popular CMSs. The main purpose of this tool is to integrate common vulnerabilities for different types of CMSs into a single tool. at the instant, there’s support for WordPress, Joomla, Drupal, and Moodle. CMSmap tool is freely available on GitHub. CMSmap tool supports multiple target domain scanning and saves the results in text file format. CMSmap tool has the ability to set custom user-agent and header. CMSmap tool Support for SSL encryption. CMSmap tool supports Verbose mode for debugging purposes." }, { "code": null, "e": 815, "s": 649, "text": "Note: Make Sure You have Python Installed on your System, as this is a python-based tool. Click to check the Installation process: Python Installation Steps on Linux" }, { "code": null, "e": 906, "s": 815, "text": "Step 1: Use the following command to install the tool in your Kali Linux operating system." }, { "code": null, "e": 954, "s": 906, "text": "git clone https://github.com/Dionach/CMSmap.git" }, { "code": null, "e": 1092, "s": 954, "text": "Step 2: Now use the following command to move into the directory of the tool. You have to move in the directory in order to run the tool." }, { "code": null, "e": 1103, "s": 1092, "text": "cd CMSmap " }, { "code": null, "e": 1211, "s": 1103, "text": "Step 3: You are in the directory of the CMSmap. Now run the following command to complete the installation." }, { "code": null, "e": 1241, "s": 1211, "text": "sudo python3 setup.py install" }, { "code": null, "e": 1401, "s": 1241, "text": "Step 4: All the dependencies have been installed in your Kali Linux operating system. Now use the following command to run the tool and check the help section." }, { "code": null, "e": 1423, "s": 1401, "text": "python3 cmsmap .py -h" }, { "code": null, "e": 1462, "s": 1423, "text": "Example 1: Simple Scan (Single Target)" }, { "code": null, "e": 1506, "s": 1462, "text": "python3 cmsmap.py https://geeksforgeeks.org" }, { "code": null, "e": 1597, "s": 1506, "text": "In this Example, We are performing simple scanning on the target domain geeksforgeeks.org." }, { "code": null, "e": 1665, "s": 1597, "text": "We have got the details of CMS and the theme applied to the domain." }, { "code": null, "e": 1735, "s": 1665, "text": "The tool has identified the WordPress usernames on geeksforgeeks.org." }, { "code": null, "e": 1767, "s": 1735, "text": "Example 2: Force scan WordPress" }, { "code": null, "e": 1830, "s": 1767, "text": "python3 cmsmap.py https://geeksforgeeks.org -f W -F --noedb -d" }, { "code": null, "e": 1917, "s": 1830, "text": "In this Example, We are performing a Force scan of WordPress CMS on geeksforgeeks.org." }, { "code": null, "e": 1973, "s": 1917, "text": "Example 3: Scan multiple targets listed in a given file" }, { "code": null, "e": 2025, "s": 1973, "text": "python3 cmsmap.py -i targets.txt -o output.txt -f D" }, { "code": null, "e": 2117, "s": 2025, "text": "In this Example, We are scanning multiple target domains specified in the targets.txt file." }, { "code": null, "e": 2141, "s": 2117, "text": "Example 4: Verbose Mode" }, { "code": null, "e": 2188, "s": 2141, "text": "python3 cmsmap.py https://geeksforgeeks.org -v" }, { "code": null, "e": 2319, "s": 2188, "text": "In this Example, We are displaying the scan results in a more detailed way. We have used the -v tag for enabling the verbose mode." }, { "code": null, "e": 2330, "s": 2319, "text": "Kali-Linux" }, { "code": null, "e": 2342, "s": 2330, "text": "Linux-Tools" }, { "code": null, "e": 2353, "s": 2342, "text": "Linux-Unix" }, { "code": null, "e": 2451, "s": 2353, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 2477, "s": 2451, "text": "Docker - COPY Instruction" }, { "code": null, "e": 2512, "s": 2477, "text": "scp command in Linux with Examples" }, { "code": null, "e": 2549, "s": 2512, "text": "chown command in Linux with Examples" }, { "code": null, "e": 2578, "s": 2549, "text": "SED command in Linux | Set 2" }, { "code": null, "e": 2612, "s": 2578, "text": "mv command in Linux with examples" }, { "code": null, "e": 2649, "s": 2612, "text": "nohup Command in Linux with Examples" }, { "code": null, "e": 2686, "s": 2649, "text": "chmod command in Linux with examples" }, { "code": null, "e": 2725, "s": 2686, "text": "Introduction to Linux Operating System" }, { "code": null, "e": 2765, "s": 2725, "text": "Array Basics in Shell Scripting | Set 1" } ]
Union process in DFA
20 Nov, 2019 Prerequisite – Designing finite automataLet’s understand the Union process in Deterministic Finite Automata (DFA) with the help of below example. Designing a DFA for the set of string over {a, b} such that string of the language start and end with different symbols. There two desired language will be formed: L1 = {ab, aab, aabab, .......} L2 = {ba, bba, bbaba, .......} L1= {starts with a and ends with b } and L2= {starts with b and ends with a}.Then L= L1 ∪ L2 or L=L1 + L2 State Transition Diagram for the language L1:This DFA accepts all the string starting with a and ending with b. Here, State A is initial state and state C is final state. State Transition Diagram for the language L2:This DFA accepts all the string starting with b and ending with a. Here, State A is initial state and state C is final state. Now, Taking the union of L1 and L2 language which gives the final result of the language which starts and end with different elements.State Transition Diagram of L1 ∪ L2:Thus as we see that L1 and L2 have been combined through union process and this final DFA accept all the language containing strings starting and ending with a different symbols.Note: From above example we can also infer that regular languages are closed under union(i.e Union of two regular languages is also regular). VaibhavRai3 HasanBadran GATE CS Theory of Computation & Automata Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Mutual exclusion in distributed system Three address code in Compiler S - attributed and L - attributed SDTs in Syntax directed translation Types of Operating Systems Code Optimization in Compiler Design Difference between DFA and NFA Boyer-Moore Majority Voting Algorithm Variation of Turing Machine Design 101 sequence detector (Mealy machine) Post Correspondence Problem
[ { "code": null, "e": 53, "s": 25, "text": "\n20 Nov, 2019" }, { "code": null, "e": 199, "s": 53, "text": "Prerequisite – Designing finite automataLet’s understand the Union process in Deterministic Finite Automata (DFA) with the help of below example." }, { "code": null, "e": 363, "s": 199, "text": "Designing a DFA for the set of string over {a, b} such that string of the language start and end with different symbols. There two desired language will be formed:" }, { "code": null, "e": 426, "s": 363, "text": "L1 = {ab, aab, aabab, .......}\nL2 = {ba, bba, bbaba, .......} " }, { "code": null, "e": 532, "s": 426, "text": "L1= {starts with a and ends with b } and L2= {starts with b and ends with a}.Then L= L1 ∪ L2 or L=L1 + L2" }, { "code": null, "e": 703, "s": 532, "text": "State Transition Diagram for the language L1:This DFA accepts all the string starting with a and ending with b. Here, State A is initial state and state C is final state." }, { "code": null, "e": 874, "s": 703, "text": "State Transition Diagram for the language L2:This DFA accepts all the string starting with b and ending with a. Here, State A is initial state and state C is final state." }, { "code": null, "e": 1364, "s": 874, "text": "Now, Taking the union of L1 and L2 language which gives the final result of the language which starts and end with different elements.State Transition Diagram of L1 ∪ L2:Thus as we see that L1 and L2 have been combined through union process and this final DFA accept all the language containing strings starting and ending with a different symbols.Note: From above example we can also infer that regular languages are closed under union(i.e Union of two regular languages is also regular)." }, { "code": null, "e": 1376, "s": 1364, "text": "VaibhavRai3" }, { "code": null, "e": 1388, "s": 1376, "text": "HasanBadran" }, { "code": null, "e": 1396, "s": 1388, "text": "GATE CS" }, { "code": null, "e": 1429, "s": 1396, "text": "Theory of Computation & Automata" }, { "code": null, "e": 1527, "s": 1429, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 1566, "s": 1527, "text": "Mutual exclusion in distributed system" }, { "code": null, "e": 1597, "s": 1566, "text": "Three address code in Compiler" }, { "code": null, "e": 1667, "s": 1597, "text": "S - attributed and L - attributed SDTs in Syntax directed translation" }, { "code": null, "e": 1694, "s": 1667, "text": "Types of Operating Systems" }, { "code": null, "e": 1731, "s": 1694, "text": "Code Optimization in Compiler Design" }, { "code": null, "e": 1762, "s": 1731, "text": "Difference between DFA and NFA" }, { "code": null, "e": 1800, "s": 1762, "text": "Boyer-Moore Majority Voting Algorithm" }, { "code": null, "e": 1828, "s": 1800, "text": "Variation of Turing Machine" }, { "code": null, "e": 1873, "s": 1828, "text": "Design 101 sequence detector (Mealy machine)" } ]
Python | Merge, Join and Concatenate DataFrames using Panda
19 Jun, 2018 A dataframe is a two-dimensional data structure having multiple rows and columns. In a dataframe, the data is aligned in the form of rows and columns only. A dataframe can perform arithmetic as well as conditional operations. It has mutable size. Below is the implementation using Numpy and Pandas. Modules needed: import numpy as np import pandas as pd # Python program to concatenate# dataframes using Panda # Creating first dataframedf1 = pd.DataFrame({'A': ['A0', 'A1', 'A2', 'A3'], 'B': ['B0', 'B1', 'B2', 'B3'], 'C': ['C0', 'C1', 'C2', 'C3'], 'D': ['D0', 'D1', 'D2', 'D3']}, index = [0, 1, 2, 3]) # Creating second dataframedf2 = pd.DataFrame({'A': ['A4', 'A5', 'A6', 'A7'], 'B': ['B4', 'B5', 'B6', 'B7'], 'C': ['C4', 'C5', 'C6', 'C7'], 'D': ['D4', 'D5', 'D6', 'D7']}, index = [4, 5, 6, 7]) # Creating third dataframedf3 = pd.DataFrame({'A': ['A8', 'A9', 'A10', 'A11'], 'B': ['B8', 'B9', 'B10', 'B11'], 'C': ['C8', 'C9', 'C10', 'C11'], 'D': ['D8', 'D9', 'D10', 'D11']}, index = [8, 9, 10, 11]) # Concatenating the dataframespd.concat([df1, df2, df3]) Output: Code #2 : DataFrames MergePandas provides a single function, merge(), as the entry point for all standard database join operations between DataFrame objects. # Python program to merge# dataframes using Panda # Dataframe createdleft = pd.DataFrame({'Key': ['K0', 'K1', 'K2', 'K3'], 'A': ['A0', 'A1', 'A2', 'A3'], 'B': ['B0', 'B1', 'B2', 'B3']}) right = pd.DataFrame({'Key': ['K0', 'K1', 'K2', 'K3'], 'C': ['C0', 'C1', 'C2', 'C3'], 'D': ['D0', 'D1', 'D2', 'D3']}) # Merging the dataframes pd.merge(left, right, how ='inner', on ='Key') Output: Code #3 : DataFrames Join # Python program to join# dataframes using Panda left = pd.DataFrame({'A': ['A0', 'A1', 'A2', 'A3'], 'B': ['B0', 'B1', 'B2', 'B3']}, index = ['K0', 'K1', 'K2', 'K3']) right = pd.DataFrame({'C': ['C0', 'C1', 'C2', 'C3'], 'D': ['D0', 'D1', 'D2', 'D3']}, index = ['K0', 'K1', 'K2', 'K3']) # Joining the dataframes left.join(right) Output: python-modules Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 53, "s": 25, "text": "\n19 Jun, 2018" }, { "code": null, "e": 300, "s": 53, "text": "A dataframe is a two-dimensional data structure having multiple rows and columns. In a dataframe, the data is aligned in the form of rows and columns only. A dataframe can perform arithmetic as well as conditional operations. It has mutable size." }, { "code": null, "e": 352, "s": 300, "text": "Below is the implementation using Numpy and Pandas." }, { "code": null, "e": 368, "s": 352, "text": "Modules needed:" }, { "code": null, "e": 408, "s": 368, "text": "import numpy as np\nimport pandas as pd\n" }, { "code": "# Python program to concatenate# dataframes using Panda # Creating first dataframedf1 = pd.DataFrame({'A': ['A0', 'A1', 'A2', 'A3'], 'B': ['B0', 'B1', 'B2', 'B3'], 'C': ['C0', 'C1', 'C2', 'C3'], 'D': ['D0', 'D1', 'D2', 'D3']}, index = [0, 1, 2, 3]) # Creating second dataframedf2 = pd.DataFrame({'A': ['A4', 'A5', 'A6', 'A7'], 'B': ['B4', 'B5', 'B6', 'B7'], 'C': ['C4', 'C5', 'C6', 'C7'], 'D': ['D4', 'D5', 'D6', 'D7']}, index = [4, 5, 6, 7]) # Creating third dataframedf3 = pd.DataFrame({'A': ['A8', 'A9', 'A10', 'A11'], 'B': ['B8', 'B9', 'B10', 'B11'], 'C': ['C8', 'C9', 'C10', 'C11'], 'D': ['D8', 'D9', 'D10', 'D11']}, index = [8, 9, 10, 11]) # Concatenating the dataframespd.concat([df1, df2, df3])", "e": 1345, "s": 410, "text": null }, { "code": null, "e": 1353, "s": 1345, "text": "Output:" }, { "code": null, "e": 1511, "s": 1353, "text": "Code #2 : DataFrames MergePandas provides a single function, merge(), as the entry point for all standard database join operations between DataFrame objects." }, { "code": "# Python program to merge# dataframes using Panda # Dataframe createdleft = pd.DataFrame({'Key': ['K0', 'K1', 'K2', 'K3'], 'A': ['A0', 'A1', 'A2', 'A3'], 'B': ['B0', 'B1', 'B2', 'B3']}) right = pd.DataFrame({'Key': ['K0', 'K1', 'K2', 'K3'], 'C': ['C0', 'C1', 'C2', 'C3'], 'D': ['D0', 'D1', 'D2', 'D3']}) # Merging the dataframes pd.merge(left, right, how ='inner', on ='Key')", "e": 2013, "s": 1511, "text": null }, { "code": null, "e": 2021, "s": 2013, "text": "Output:" }, { "code": null, "e": 2048, "s": 2021, "text": " Code #3 : DataFrames Join" }, { "code": "# Python program to join# dataframes using Panda left = pd.DataFrame({'A': ['A0', 'A1', 'A2', 'A3'], 'B': ['B0', 'B1', 'B2', 'B3']}, index = ['K0', 'K1', 'K2', 'K3']) right = pd.DataFrame({'C': ['C0', 'C1', 'C2', 'C3'], 'D': ['D0', 'D1', 'D2', 'D3']}, index = ['K0', 'K1', 'K2', 'K3']) # Joining the dataframes left.join(right)", "e": 2502, "s": 2048, "text": null }, { "code": null, "e": 2510, "s": 2502, "text": "Output:" }, { "code": null, "e": 2525, "s": 2510, "text": "python-modules" }, { "code": null, "e": 2532, "s": 2525, "text": "Python" } ]
Python – Convert list of dictionaries to dictionary of lists
07 Jan, 2022 In this article, we will discuss how to convert a list of dictionaries to a dictionary of lists. By iterating based on the first key we can convert list of dict to dict of list. Python program to create student list of dictionaries Python3 # create a list of dictionaries# with student datadata = [ {'name': 'sravan', 'subjects': ['java', 'python']}, {'name': 'bobby', 'subjects': ['c/cpp', 'java']}, {'name': 'ojsawi', 'subjects': ['iot', 'cloud']}, {'name': 'rohith', 'subjects': ['php', 'os']}, {'name': 'gnanesh', 'subjects': ['html', 'sql']} ] # displaydata Output: [{'name': 'sravan', 'subjects': ['java', 'python']}, {'name': 'bobby', 'subjects': ['c/cpp', 'java']}, {'name': 'ojsawi', 'subjects': ['iot', 'cloud']}, {'name': 'rohith', 'subjects': ['php', 'os']}, {'name': 'gnanesh', 'subjects': ['html', 'sql']}] Example: Convert list of dictionary to a dictionary of list Python3 # create an empty dictionarydictionary_of_list = {} # for loop to convert list of dict# to dict of listfor item in data: name = item['name'] dictionary_of_list[name] = item # displaydictionary_of_list Output: {'bobby': {'name': 'bobby', 'subjects': ['c/cpp', 'java']}, 'gnanesh': {'name': 'gnanesh', 'subjects': ['html', 'sql']}, 'ojsawi': {'name': 'ojsawi', 'subjects': ['iot', 'cloud']}, 'rohith': {'name': 'rohith', 'subjects': ['php', 'os']}, 'sravan': {'name': 'sravan', 'subjects': ['java', 'python']}} Here we are using a dictionary comprehension to convert a list of dictionaries into the dictionary of the list, so we are passing the list as values based on keys in the new dictionary Syntax: {key: [i[key] for i in list_of_dictionary] for key in list_of_dictionary[0]} where list_of_dictionary is the input key is the key in list_of_dictionary Example: Program to convert student list of dictionary into dictionary of list Python3 # consider the list of dictionarydata = [{'manoj': 'java', 'bobby': 'python'}, {'manoj': 'php', 'bobby': 'java'}, {'manoj': 'cloud', 'bobby': 'big-data'}] # convert into dictionary of list# with list as valuesprint({key: [i[key] for i in data] for key in data[0]}) Output: {'manoj': ['java', 'php', 'cloud'], 'bobby': ['python', 'java', 'big-data']} By using pandas dataframe we will convert list of dict to dict of list Syntax: pandas.DataFrame(list_of_dictionary).to_dict(orient=”list”) Where: list_of_dictionary is the input to_dict() method is to convert into dictionary orient parameter is to convert into list Example: Python3 #import pandasimport pandas as pd # consider the list of dictionarydata = [{'manoj': 'java', 'bobby': 'python'}, {'manoj': 'php', 'bobby': 'java'}, {'manoj': 'cloud', 'bobby': 'big-data'}] # convert into dictionary of list# with list as values using pandas dataframepd.DataFrame(data).to_dict(orient="list") Output: {‘bobby’: [‘python’, ‘java’, ‘big-data’], ‘manoj’: [‘java’, ‘php’, ‘cloud’]} Numpy is used to process the arrays, we can get the values by using key or index Python3 # import numpy moduleimport numpy as np # create numpy datadata = np.array([(10, 20), (50, 60)], dtype=[('value1', int), ('value2', int)]) # display by using indexprint(data[0]) # display by using keyprint(data['value1']) Output: (10, 20) [10 50] prachisoda1234 Picked Python dictionary-programs Python list-programs python-dict python-list Python Python Programs python-dict python-list Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n07 Jan, 2022" }, { "code": null, "e": 125, "s": 28, "text": "In this article, we will discuss how to convert a list of dictionaries to a dictionary of lists." }, { "code": null, "e": 260, "s": 125, "text": "By iterating based on the first key we can convert list of dict to dict of list. Python program to create student list of dictionaries" }, { "code": null, "e": 268, "s": 260, "text": "Python3" }, { "code": "# create a list of dictionaries# with student datadata = [ {'name': 'sravan', 'subjects': ['java', 'python']}, {'name': 'bobby', 'subjects': ['c/cpp', 'java']}, {'name': 'ojsawi', 'subjects': ['iot', 'cloud']}, {'name': 'rohith', 'subjects': ['php', 'os']}, {'name': 'gnanesh', 'subjects': ['html', 'sql']} ] # displaydata", "e": 606, "s": 268, "text": null }, { "code": null, "e": 614, "s": 606, "text": "Output:" }, { "code": null, "e": 868, "s": 614, "text": "[{'name': 'sravan', 'subjects': ['java', 'python']},\n {'name': 'bobby', 'subjects': ['c/cpp', 'java']},\n {'name': 'ojsawi', 'subjects': ['iot', 'cloud']},\n {'name': 'rohith', 'subjects': ['php', 'os']},\n {'name': 'gnanesh', 'subjects': ['html', 'sql']}]" }, { "code": null, "e": 928, "s": 868, "text": "Example: Convert list of dictionary to a dictionary of list" }, { "code": null, "e": 936, "s": 928, "text": "Python3" }, { "code": "# create an empty dictionarydictionary_of_list = {} # for loop to convert list of dict# to dict of listfor item in data: name = item['name'] dictionary_of_list[name] = item # displaydictionary_of_list", "e": 1143, "s": 936, "text": null }, { "code": null, "e": 1151, "s": 1143, "text": "Output:" }, { "code": null, "e": 1455, "s": 1151, "text": "{'bobby': {'name': 'bobby', 'subjects': ['c/cpp', 'java']},\n 'gnanesh': {'name': 'gnanesh', 'subjects': ['html', 'sql']},\n 'ojsawi': {'name': 'ojsawi', 'subjects': ['iot', 'cloud']},\n 'rohith': {'name': 'rohith', 'subjects': ['php', 'os']},\n 'sravan': {'name': 'sravan', 'subjects': ['java', 'python']}}" }, { "code": null, "e": 1640, "s": 1455, "text": "Here we are using a dictionary comprehension to convert a list of dictionaries into the dictionary of the list, so we are passing the list as values based on keys in the new dictionary" }, { "code": null, "e": 1725, "s": 1640, "text": "Syntax: {key: [i[key] for i in list_of_dictionary] for key in list_of_dictionary[0]}" }, { "code": null, "e": 1731, "s": 1725, "text": "where" }, { "code": null, "e": 1763, "s": 1731, "text": "list_of_dictionary is the input" }, { "code": null, "e": 1800, "s": 1763, "text": "key is the key in list_of_dictionary" }, { "code": null, "e": 1879, "s": 1800, "text": "Example: Program to convert student list of dictionary into dictionary of list" }, { "code": null, "e": 1887, "s": 1879, "text": "Python3" }, { "code": "# consider the list of dictionarydata = [{'manoj': 'java', 'bobby': 'python'}, {'manoj': 'php', 'bobby': 'java'}, {'manoj': 'cloud', 'bobby': 'big-data'}] # convert into dictionary of list# with list as valuesprint({key: [i[key] for i in data] for key in data[0]})", "e": 2166, "s": 1887, "text": null }, { "code": null, "e": 2174, "s": 2166, "text": "Output:" }, { "code": null, "e": 2251, "s": 2174, "text": "{'manoj': ['java', 'php', 'cloud'], 'bobby': ['python', 'java', 'big-data']}" }, { "code": null, "e": 2322, "s": 2251, "text": "By using pandas dataframe we will convert list of dict to dict of list" }, { "code": null, "e": 2390, "s": 2322, "text": "Syntax: pandas.DataFrame(list_of_dictionary).to_dict(orient=”list”)" }, { "code": null, "e": 2397, "s": 2390, "text": "Where:" }, { "code": null, "e": 2429, "s": 2397, "text": "list_of_dictionary is the input" }, { "code": null, "e": 2476, "s": 2429, "text": "to_dict() method is to convert into dictionary" }, { "code": null, "e": 2517, "s": 2476, "text": "orient parameter is to convert into list" }, { "code": null, "e": 2526, "s": 2517, "text": "Example:" }, { "code": null, "e": 2534, "s": 2526, "text": "Python3" }, { "code": "#import pandasimport pandas as pd # consider the list of dictionarydata = [{'manoj': 'java', 'bobby': 'python'}, {'manoj': 'php', 'bobby': 'java'}, {'manoj': 'cloud', 'bobby': 'big-data'}] # convert into dictionary of list# with list as values using pandas dataframepd.DataFrame(data).to_dict(orient=\"list\")", "e": 2856, "s": 2534, "text": null }, { "code": null, "e": 2864, "s": 2856, "text": "Output:" }, { "code": null, "e": 2941, "s": 2864, "text": "{‘bobby’: [‘python’, ‘java’, ‘big-data’], ‘manoj’: [‘java’, ‘php’, ‘cloud’]}" }, { "code": null, "e": 3022, "s": 2941, "text": "Numpy is used to process the arrays, we can get the values by using key or index" }, { "code": null, "e": 3030, "s": 3022, "text": "Python3" }, { "code": "# import numpy moduleimport numpy as np # create numpy datadata = np.array([(10, 20), (50, 60)], dtype=[('value1', int), ('value2', int)]) # display by using indexprint(data[0]) # display by using keyprint(data['value1'])", "e": 3289, "s": 3030, "text": null }, { "code": null, "e": 3297, "s": 3289, "text": "Output:" }, { "code": null, "e": 3314, "s": 3297, "text": "(10, 20)\n[10 50]" }, { "code": null, "e": 3329, "s": 3314, "text": "prachisoda1234" }, { "code": null, "e": 3336, "s": 3329, "text": "Picked" }, { "code": null, "e": 3363, "s": 3336, "text": "Python dictionary-programs" }, { "code": null, "e": 3384, "s": 3363, "text": "Python list-programs" }, { "code": null, "e": 3396, "s": 3384, "text": "python-dict" }, { "code": null, "e": 3408, "s": 3396, "text": "python-list" }, { "code": null, "e": 3415, "s": 3408, "text": "Python" }, { "code": null, "e": 3431, "s": 3415, "text": "Python Programs" }, { "code": null, "e": 3443, "s": 3431, "text": "python-dict" }, { "code": null, "e": 3455, "s": 3443, "text": "python-list" } ]
Create Indian Flag using HTML and CSS
24 Oct, 2021 In this article, we will design an animated flag of India using HTML and CSS. As we know that our Indian flag has three colors saffron, white and green and there is also a wheel at the center of the white part. So let’s build the Indian flag. Here we will also create a stick of the flag. So first create a wrapper div (class named wrapper) that holds two divs class named stick and flag. HTML <div class = "wrapper"> <div class="stick"></div> <div class="flag"></div></div> The stick and the flag should be inline so we make the wrapper div’s display property to flex. And add some height, width, background-color, border styles to the stick, and in the flag, add height, width, box-shadow, background-color, and position properties. CSS .wrapper { display: flex;} .stick { height: 450px; width: 10px; background: black; border-top-left-radius: 10px; border-bottom-left-radius: 5px; border-bottom-right-radius: 5px;} .flag { width: 270px; height: 180px; box-shadow: 0px 0px 90px 1px #989; background-color: transparent; position: relative;} Till now it look like this: Now design the flag part. The flag part is made of three parts, So make three div’s and classes named top, middle, and bottom. HTML <div class="wrapper"> <div class="stick"></div> <div class="flag"> <div class="top"></div> <div class="middle"></div> <div class="bottom"></div> </div></div> Now add height and background-color property to the top, middle, and bottom divs. CSS .top { height: 60px; background-color: #ff9933} .middle { height: 60px; background-color: white} .bottom { height: 60px; background-color: green} Now our flag looks like this: Now it’s time to create a wheel so, the wheel is nothing but a div inside the div, class named middle. In the wheel, we create 12 span elements class named ‘line’. HTML <div class="flag"> <div class="top"></div> <div class="middle"> <div class="wheel"> <span class="line"></span> <span class="line"></span> <span class="line"></span> <span class="line"></span> <span class="line"></span> <span class="line"></span> <span class="line"></span> <span class="line"></span> <span class="line"></span> <span class="line"></span> <span class="line"></span> <span class="line"></span> </div> </div> <div class="bottom"></div></div> For styling the wheel, firstly we have to perfectly center the wheel inside the middle div by using flex properties. And design the wheel div by adding height, width, border, border-radius, position. And also design the span elements by adding the height width, position, ‘left’, background, etc properties. And rotate every line item by using :nth-child(n) selector and transform: rotate(angle) property, every rotation should be at the difference of 15 degrees. CSS .wheel { height: 43px; width: 43px; border: 1px solid darkblue; border-radius: 45px; position: relative; margin: 0 auto} .wheel .line { height: 100%; width: 1px; display: inline-block; position: absolute; left: 50%; background: darkblue;} .line:nth-child(1) { transform: rotate(15deg)} .line:nth-child(2) { transform: rotate(30deg)} .line:nth-child(3) { transform: rotate(45deg)} .line:nth-child(4) { transform: rotate(60deg)} .line:nth-child(5) { transform: rotate(75deg)} .line:nth-child(6) { transform: rotate(90deg)} .line:nth-child(7) { transform: rotate(105deg)} .line:nth-child(8) { transform: rotate(120deg)} .line:nth-child(9) { transform: rotate(135deg)} .line:nth-child(10) { transform: rotate(150deg)} .line:nth-child(11) { transform: rotate(165deg)} .line:nth-child(12) { transform: rotate(180deg)} Now our complete Indian flag looks like this: Add some animations: Till now we have created a complete but static flag, now it’s time to create some animations. Here we will add two animations, the first ss wheel rotation animation and the second is wave animation. Adding wheel rotation animation: To add wheel rotation, we use the transform: rotate(angle) property, making the animation duration 10 seconds, animation timing function linear, and running the animation infinite times. CSS .wheel { animation-name: wheel; animation-iteration-count: infinite; animation-duration: 5s; animation-timing-function: linear;} @keyframes wheel { 0% { transform: rotate(0deg); } 100% { transform: rotate(360deg); }} Now our Indian flag looks like this: Adding wave animation: Now add the wave animation. For this animation, we create a separate div and add it into the flag div (because we overlay this div inside the flag div only, not in ‘stick’). Add position: absolute, height, and width set to 100%, and add a gradient background-image and change the background positions to animate. CSS .wave { position: absolute; height: 100%; width: 100%; background-image: linear-gradient( 128deg, rgba(89, 72, 21, 0) 39%, rgba(250, 245, 245, 0.8474025974025974) 46%, rgba(89, 72, 21, 0) 53%); animation-name: wavy; animation-duration: 10s; animation-iteration-count: infinite; animation-timing-function: linear;} @keyframes wavy { 0% { background-position: -400px 0px, -400px 0px, -400px 0px, -400px 0px; } 100% { background-position: 800px 0px, 800px 0px, 800px 0px, 800px 0px; }} Complete code: The complete code of HTML and CSS to design Indian National Flag. HTML CSS <!DOCTYPE html><html> <head> <link rel="stylesheet" href="style.css"></head> <body> <div class="wrapper"> <div class="stick"></div> <div class="flag"> <div class="wave"></div> <div class="top"></div> <div class="middle"> <div class="wheel"> <span class="line"></span> <span class="line"></span> <span class="line"></span> <span class="line"></span> <span class="line"></span> <span class="line"></span> <span class="line"></span> <span class="line"></span> <span class="line"></span> <span class="line"></span> <span class="line"></span> <span class="line"></span> </div> </div> <div class="bottom"></div> </div> </div></body> </html> .wrapper { display: flex; } .stick { height: 450px; width: 10px; background: black; border-top-left-radius: 10px; border-bottom-left-radius: 5px; border-bottom-right-radius: 5px; } .flag { width: 270px; height: 180px; box-shadow: 0px 0px 90px 1px #989; background-color: transparent; position: relative; } .top { height: 60px; background-color: #ff9933 } .middle { height: 60px; display: flex; justify-content: center; align-items: center; } .bottom { height: 60px; background-color: green } .wheel { height: 43px; width: 43px; border: 1px solid darkblue; border-radius: 45px; position: relative; margin: 0 auto; animation-name: wheel; animation-iteration-count: infinite; animation-duration: 5s; animation-timing-function: linear; } .wheel .line { height: 100%; width: 1px; display: inline-block; position: absolute; left: 50%; background: darkblue; } .line:nth-child(1) { transform: rotate(15deg) } .line:nth-child(2) { transform: rotate(30deg) } .line:nth-child(3) { transform: rotate(45deg) } .line:nth-child(4) { transform: rotate(60deg) } .line:nth-child(5) { transform: rotate(75deg) } .line:nth-child(6) { transform: rotate(90deg) } .line:nth-child(7) { transform: rotate(105deg) } .line:nth-child(8) { transform: rotate(120deg) } .line:nth-child(9) { transform: rotate(135deg) } .line:nth-child(10) { transform: rotate(150deg) } .line:nth-child(11) { transform: rotate(165deg) } .line:nth-child(12) { transform: rotate(180deg) } @keyframes wheel { 0%{ transform: rotate(0deg); } 100%{ transform: rotate(360deg); } } .wave{ position: absolute; height: 100%; width: 100%; background-image: linear-gradient( 128deg, rgba(89,72,21,0) 39%, rgba(250,245,245,0.8474025974025974) 46%, rgba(89,72,21,0) 53%); animation-name: wavy; animation-duration: 10s; animation-iteration-count: infinite; animation-timing-function: linear; } @keyframes wavy { 0%{ background-position: -400px 0px, -400px 0px, -400px 0px,-400px 0px; } 100%{ background-position: 800px 0px, 800px 0px, 800px 0px, 800px 0px; } } Output: sumitgumber28 anikaseth98 CSS-Questions HTML-Questions CSS HTML Web Technologies HTML Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Design a Tribute Page using HTML & CSS How to set space between the flexbox ? Build a Survey Form using HTML and CSS Design a web page using HTML and CSS Form validation using jQuery REST API (Introduction) Hide or show elements in HTML using display property How to set the default value for an HTML <select> element ? How to set input type date in dd-mm-yyyy format using HTML ? Design a Tribute Page using HTML & CSS
[ { "code": null, "e": 54, "s": 26, "text": "\n24 Oct, 2021" }, { "code": null, "e": 443, "s": 54, "text": "In this article, we will design an animated flag of India using HTML and CSS. As we know that our Indian flag has three colors saffron, white and green and there is also a wheel at the center of the white part. So let’s build the Indian flag. Here we will also create a stick of the flag. So first create a wrapper div (class named wrapper) that holds two divs class named stick and flag." }, { "code": null, "e": 448, "s": 443, "text": "HTML" }, { "code": "<div class = \"wrapper\"> <div class=\"stick\"></div> <div class=\"flag\"></div></div>", "e": 537, "s": 448, "text": null }, { "code": null, "e": 797, "s": 537, "text": "The stick and the flag should be inline so we make the wrapper div’s display property to flex. And add some height, width, background-color, border styles to the stick, and in the flag, add height, width, box-shadow, background-color, and position properties." }, { "code": null, "e": 801, "s": 797, "text": "CSS" }, { "code": ".wrapper { display: flex;} .stick { height: 450px; width: 10px; background: black; border-top-left-radius: 10px; border-bottom-left-radius: 5px; border-bottom-right-radius: 5px;} .flag { width: 270px; height: 180px; box-shadow: 0px 0px 90px 1px #989; background-color: transparent; position: relative;}", "e": 1140, "s": 801, "text": null }, { "code": null, "e": 1168, "s": 1140, "text": "Till now it look like this:" }, { "code": null, "e": 1296, "s": 1168, "text": "Now design the flag part. The flag part is made of three parts, So make three div’s and classes named top, middle, and bottom. " }, { "code": null, "e": 1301, "s": 1296, "text": "HTML" }, { "code": "<div class=\"wrapper\"> <div class=\"stick\"></div> <div class=\"flag\"> <div class=\"top\"></div> <div class=\"middle\"></div> <div class=\"bottom\"></div> </div></div>", "e": 1489, "s": 1301, "text": null }, { "code": null, "e": 1571, "s": 1489, "text": "Now add height and background-color property to the top, middle, and bottom divs." }, { "code": null, "e": 1575, "s": 1571, "text": "CSS" }, { "code": ".top { height: 60px; background-color: #ff9933} .middle { height: 60px; background-color: white} .bottom { height: 60px; background-color: green}", "e": 1739, "s": 1575, "text": null }, { "code": null, "e": 1770, "s": 1739, "text": "Now our flag looks like this: " }, { "code": null, "e": 1935, "s": 1770, "text": "Now it’s time to create a wheel so, the wheel is nothing but a div inside the div, class named middle. In the wheel, we create 12 span elements class named ‘line’. " }, { "code": null, "e": 1940, "s": 1935, "text": "HTML" }, { "code": "<div class=\"flag\"> <div class=\"top\"></div> <div class=\"middle\"> <div class=\"wheel\"> <span class=\"line\"></span> <span class=\"line\"></span> <span class=\"line\"></span> <span class=\"line\"></span> <span class=\"line\"></span> <span class=\"line\"></span> <span class=\"line\"></span> <span class=\"line\"></span> <span class=\"line\"></span> <span class=\"line\"></span> <span class=\"line\"></span> <span class=\"line\"></span> </div> </div> <div class=\"bottom\"></div></div>", "e": 2553, "s": 1940, "text": null }, { "code": null, "e": 3017, "s": 2553, "text": "For styling the wheel, firstly we have to perfectly center the wheel inside the middle div by using flex properties. And design the wheel div by adding height, width, border, border-radius, position. And also design the span elements by adding the height width, position, ‘left’, background, etc properties. And rotate every line item by using :nth-child(n) selector and transform: rotate(angle) property, every rotation should be at the difference of 15 degrees." }, { "code": null, "e": 3021, "s": 3017, "text": "CSS" }, { "code": ".wheel { height: 43px; width: 43px; border: 1px solid darkblue; border-radius: 45px; position: relative; margin: 0 auto} .wheel .line { height: 100%; width: 1px; display: inline-block; position: absolute; left: 50%; background: darkblue;} .line:nth-child(1) { transform: rotate(15deg)} .line:nth-child(2) { transform: rotate(30deg)} .line:nth-child(3) { transform: rotate(45deg)} .line:nth-child(4) { transform: rotate(60deg)} .line:nth-child(5) { transform: rotate(75deg)} .line:nth-child(6) { transform: rotate(90deg)} .line:nth-child(7) { transform: rotate(105deg)} .line:nth-child(8) { transform: rotate(120deg)} .line:nth-child(9) { transform: rotate(135deg)} .line:nth-child(10) { transform: rotate(150deg)} .line:nth-child(11) { transform: rotate(165deg)} .line:nth-child(12) { transform: rotate(180deg)}", "e": 3905, "s": 3021, "text": null }, { "code": null, "e": 3951, "s": 3905, "text": "Now our complete Indian flag looks like this:" }, { "code": null, "e": 4171, "s": 3951, "text": "Add some animations: Till now we have created a complete but static flag, now it’s time to create some animations. Here we will add two animations, the first ss wheel rotation animation and the second is wave animation." }, { "code": null, "e": 4391, "s": 4171, "text": "Adding wheel rotation animation: To add wheel rotation, we use the transform: rotate(angle) property, making the animation duration 10 seconds, animation timing function linear, and running the animation infinite times." }, { "code": null, "e": 4397, "s": 4393, "text": "CSS" }, { "code": ".wheel { animation-name: wheel; animation-iteration-count: infinite; animation-duration: 5s; animation-timing-function: linear;} @keyframes wheel { 0% { transform: rotate(0deg); } 100% { transform: rotate(360deg); }}", "e": 4652, "s": 4397, "text": null }, { "code": null, "e": 4689, "s": 4652, "text": "Now our Indian flag looks like this:" }, { "code": null, "e": 5025, "s": 4689, "text": "Adding wave animation: Now add the wave animation. For this animation, we create a separate div and add it into the flag div (because we overlay this div inside the flag div only, not in ‘stick’). Add position: absolute, height, and width set to 100%, and add a gradient background-image and change the background positions to animate." }, { "code": null, "e": 5031, "s": 5027, "text": "CSS" }, { "code": ".wave { position: absolute; height: 100%; width: 100%; background-image: linear-gradient( 128deg, rgba(89, 72, 21, 0) 39%, rgba(250, 245, 245, 0.8474025974025974) 46%, rgba(89, 72, 21, 0) 53%); animation-name: wavy; animation-duration: 10s; animation-iteration-count: infinite; animation-timing-function: linear;} @keyframes wavy { 0% { background-position: -400px 0px, -400px 0px, -400px 0px, -400px 0px; } 100% { background-position: 800px 0px, 800px 0px, 800px 0px, 800px 0px; }}", "e": 5599, "s": 5031, "text": null }, { "code": null, "e": 5681, "s": 5599, "text": "Complete code: The complete code of HTML and CSS to design Indian National Flag. " }, { "code": null, "e": 5686, "s": 5681, "text": "HTML" }, { "code": null, "e": 5690, "s": 5686, "text": "CSS" }, { "code": "<!DOCTYPE html><html> <head> <link rel=\"stylesheet\" href=\"style.css\"></head> <body> <div class=\"wrapper\"> <div class=\"stick\"></div> <div class=\"flag\"> <div class=\"wave\"></div> <div class=\"top\"></div> <div class=\"middle\"> <div class=\"wheel\"> <span class=\"line\"></span> <span class=\"line\"></span> <span class=\"line\"></span> <span class=\"line\"></span> <span class=\"line\"></span> <span class=\"line\"></span> <span class=\"line\"></span> <span class=\"line\"></span> <span class=\"line\"></span> <span class=\"line\"></span> <span class=\"line\"></span> <span class=\"line\"></span> </div> </div> <div class=\"bottom\"></div> </div> </div></body> </html>", "e": 6668, "s": 5690, "text": null }, { "code": ".wrapper { display: flex; } .stick { height: 450px; width: 10px; background: black; border-top-left-radius: 10px; border-bottom-left-radius: 5px; border-bottom-right-radius: 5px; } .flag { width: 270px; height: 180px; box-shadow: 0px 0px 90px 1px #989; background-color: transparent; position: relative; } .top { height: 60px; background-color: #ff9933 } .middle { height: 60px; display: flex; justify-content: center; align-items: center; } .bottom { height: 60px; background-color: green } .wheel { height: 43px; width: 43px; border: 1px solid darkblue; border-radius: 45px; position: relative; margin: 0 auto; animation-name: wheel; animation-iteration-count: infinite; animation-duration: 5s; animation-timing-function: linear; } .wheel .line { height: 100%; width: 1px; display: inline-block; position: absolute; left: 50%; background: darkblue; } .line:nth-child(1) { transform: rotate(15deg) } .line:nth-child(2) { transform: rotate(30deg) } .line:nth-child(3) { transform: rotate(45deg) } .line:nth-child(4) { transform: rotate(60deg) } .line:nth-child(5) { transform: rotate(75deg) } .line:nth-child(6) { transform: rotate(90deg) } .line:nth-child(7) { transform: rotate(105deg) } .line:nth-child(8) { transform: rotate(120deg) } .line:nth-child(9) { transform: rotate(135deg) } .line:nth-child(10) { transform: rotate(150deg) } .line:nth-child(11) { transform: rotate(165deg) } .line:nth-child(12) { transform: rotate(180deg) } @keyframes wheel { 0%{ transform: rotate(0deg); } 100%{ transform: rotate(360deg); } } .wave{ position: absolute; height: 100%; width: 100%; background-image: linear-gradient( 128deg, rgba(89,72,21,0) 39%, rgba(250,245,245,0.8474025974025974) 46%, rgba(89,72,21,0) 53%); animation-name: wavy; animation-duration: 10s; animation-iteration-count: infinite; animation-timing-function: linear; } @keyframes wavy { 0%{ background-position: -400px 0px, -400px 0px, -400px 0px,-400px 0px; } 100%{ background-position: 800px 0px, 800px 0px, 800px 0px, 800px 0px; } }", "e": 9080, "s": 6668, "text": null }, { "code": null, "e": 9090, "s": 9080, "text": "Output: " }, { "code": null, "e": 9106, "s": 9092, "text": "sumitgumber28" }, { "code": null, "e": 9118, "s": 9106, "text": "anikaseth98" }, { "code": null, "e": 9132, "s": 9118, "text": "CSS-Questions" }, { "code": null, "e": 9147, "s": 9132, "text": "HTML-Questions" }, { "code": null, "e": 9151, "s": 9147, "text": "CSS" }, { "code": null, "e": 9156, "s": 9151, "text": "HTML" }, { "code": null, "e": 9173, "s": 9156, "text": "Web Technologies" }, { "code": null, "e": 9178, "s": 9173, "text": "HTML" }, { "code": null, "e": 9276, "s": 9178, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 9315, "s": 9276, "text": "Design a Tribute Page using HTML & CSS" }, { "code": null, "e": 9354, "s": 9315, "text": "How to set space between the flexbox ?" }, { "code": null, "e": 9393, "s": 9354, "text": "Build a Survey Form using HTML and CSS" }, { "code": null, "e": 9430, "s": 9393, "text": "Design a web page using HTML and CSS" }, { "code": null, "e": 9459, "s": 9430, "text": "Form validation using jQuery" }, { "code": null, "e": 9483, "s": 9459, "text": "REST API (Introduction)" }, { "code": null, "e": 9536, "s": 9483, "text": "Hide or show elements in HTML using display property" }, { "code": null, "e": 9596, "s": 9536, "text": "How to set the default value for an HTML <select> element ?" }, { "code": null, "e": 9657, "s": 9596, "text": "How to set input type date in dd-mm-yyyy format using HTML ?" } ]
map emplace() in C++ STL
22 Mar, 2022 The map::emplace() is a built-in function in C++ STL which inserts the key and its element in the map container. It effectively increases the container size by one. If the same key is emplaced more than once, the map stores the first element only as the map is a container which does not store multiple keys of the same value. Syntax: map_name.emplace(key, element) Parameters: The function accepts two mandatory parameters which are described below: key – specifies the key to be inserted in the multimap container. element – specifies the element to the key which is to be inserted in the map container. Return Value: The function returns a pair consisting of an iterator and a bool value. (Iterator of the position it inserted/found the key,Bool value indicating the success/failure of the insertion.) CPP // C++ program for the illustration of// map::emplace() function#include <bits/stdc++.h>using namespace std; int main(){ // initialize container map<int, int> mp; // insert elements in random order mp.emplace(2, 30); mp.emplace(1, 40); mp.emplace(2, 20); mp.emplace(1, 50); mp.emplace(4, 50); // prints the elements cout << "\nThe map is : \n"; cout << "KEY\tELEMENT\n"; for (auto itr = mp.begin(); itr != mp.end(); itr++) cout << itr->first << "\t" << itr->second << endl; return 0;} The map is : KEY ELEMENT 1 40 2 30 4 50 avishekmukhopadhyay76 CPP-Functions cpp-map 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++ vector erase() and clear() in C++ Inheritance in C++ Priority Queue in C++ Standard Template Library (STL) Substring in C++ The C++ Standard Template Library (STL) Object Oriented Programming in C++ C++ Classes and Objects Sorting a vector in C++ 2D Vector In C++ With User Defined Size
[ { "code": null, "e": 54, "s": 26, "text": "\n22 Mar, 2022" }, { "code": null, "e": 391, "s": 54, "text": "The map::emplace() is a built-in function in C++ STL which inserts the key and its element in the map container. It effectively increases the container size by one. If the same key is emplaced more than once, the map stores the first element only as the map is a container which does not store multiple keys of the same value. Syntax: " }, { "code": null, "e": 422, "s": 391, "text": "map_name.emplace(key, element)" }, { "code": null, "e": 509, "s": 422, "text": "Parameters: The function accepts two mandatory parameters which are described below: " }, { "code": null, "e": 575, "s": 509, "text": "key – specifies the key to be inserted in the multimap container." }, { "code": null, "e": 664, "s": 575, "text": "element – specifies the element to the key which is to be inserted in the map container." }, { "code": null, "e": 865, "s": 664, "text": "Return Value: The function returns a pair consisting of an iterator and a bool value. (Iterator of the position it inserted/found the key,Bool value indicating the success/failure of the insertion.) " }, { "code": null, "e": 869, "s": 865, "text": "CPP" }, { "code": "// C++ program for the illustration of// map::emplace() function#include <bits/stdc++.h>using namespace std; int main(){ // initialize container map<int, int> mp; // insert elements in random order mp.emplace(2, 30); mp.emplace(1, 40); mp.emplace(2, 20); mp.emplace(1, 50); mp.emplace(4, 50); // prints the elements cout << \"\\nThe map is : \\n\"; cout << \"KEY\\tELEMENT\\n\"; for (auto itr = mp.begin(); itr != mp.end(); itr++) cout << itr->first << \"\\t\" << itr->second << endl; return 0;}", "e": 1404, "s": 869, "text": null }, { "code": null, "e": 1457, "s": 1404, "text": "The map is : \nKEY ELEMENT\n1 40\n2 30\n4 50" }, { "code": null, "e": 1481, "s": 1459, "text": "avishekmukhopadhyay76" }, { "code": null, "e": 1495, "s": 1481, "text": "CPP-Functions" }, { "code": null, "e": 1503, "s": 1495, "text": "cpp-map" }, { "code": null, "e": 1507, "s": 1503, "text": "STL" }, { "code": null, "e": 1511, "s": 1507, "text": "C++" }, { "code": null, "e": 1515, "s": 1511, "text": "STL" }, { "code": null, "e": 1519, "s": 1515, "text": "CPP" }, { "code": null, "e": 1617, "s": 1519, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 1644, "s": 1617, "text": "Bitwise Operators in C/C++" }, { "code": null, "e": 1678, "s": 1644, "text": "vector erase() and clear() in C++" }, { "code": null, "e": 1697, "s": 1678, "text": "Inheritance in C++" }, { "code": null, "e": 1751, "s": 1697, "text": "Priority Queue in C++ Standard Template Library (STL)" }, { "code": null, "e": 1768, "s": 1751, "text": "Substring in C++" }, { "code": null, "e": 1808, "s": 1768, "text": "The C++ Standard Template Library (STL)" }, { "code": null, "e": 1843, "s": 1808, "text": "Object Oriented Programming in C++" }, { "code": null, "e": 1867, "s": 1843, "text": "C++ Classes and Objects" }, { "code": null, "e": 1891, "s": 1867, "text": "Sorting a vector in C++" } ]
How to Read Text Files with Pandas?
28 Nov, 2021 In this article, we will discuss how to read text files with pandas in python. In python, the pandas module allows us to load DataFrames from external files and work on them. The dataset can be in different types of files. Text File Used: We will read the text file with pandas using the read_csv() function. Along with the text file, we also pass separator as a single space (‘ ’) for the space character because, for text files, the space character will separate each field. There are three parameters we can pass to the read_csv() function. Syntax: data=pandas.read_csv(‘filename.txt’, sep=’ ‘, header=None, names=[“Column1”, “Column2”]) Parameters: filename.txt: As the name suggests it is the name of the text file from which we want to read data. sep: It is a separator field. In the text file, we use the space character(‘ ‘) as the separator. header: This is an optional field. By default, it will take the first line of the text file as a header. If we use header=None then it will create the header. names: We can assign column names while importing the text file by using the names argument. Example 1: Python3 # Read Text Files with Pandas using read_csv() # importing pandasimport pandas as pd # read text file into pandas DataFramedf = pd.read_csv("gfg.txt", sep=" ") # display DataFrameprint(df) Output: Example 2: In example 2 we will make the header filed equal to None. This will create a default header in the output. And take the first line of the text file as data entry. The created header name will be a number starting from 0. Python3 # Read Text Files with Pandas using read_csv() # importing pandasimport pandas as pd # read text file into pandas DataFrame and# create headerdf = pd.read_csv("gfg.txt", sep=" ", header=None) # display DataFrameprint(df) Output: Example 3: In the above output, we can see it creates a header starting from number 0. But we can also give names to the header. In this example, we will see how to create a header with a name using pandas. Python3 # Read Text Files with Pandas using read_csv() # importing pandasimport pandas as pd # read text file into pandas DataFrame and create # header with namesdf = pd.read_csv("gfg.txt", sep=" ", header=None, names=["Team1", "Team2"]) # display DataFrameprint(df) Output: We can read data from a text file using read_table() in pandas. This function reads a general delimited file to a DataFrame object. This function is essentially the same as the read_csv() function but with the delimiter = ‘\t’, instead of a comma by default. We will read data with the read_table function making separator equal to a single space(‘ ‘). Syntax: data=pandas.read_table('filename.txt', delimiter = ' ') Example: Python3 # Read Text Files with Pandas using read_table() # importing pandasimport pandas as pd # read text file into pandas DataFramedf = pd.read_table("gfg.txt", delimiter=" ") # display DataFrameprint(df) The fwf in the read_fwf() function stands for fixed-width lines. We can use this function to load DataFrames from files. This function also supports text files. We will read data from the text files using the read_fef() function with pandas. It also supports optionally iterating or breaking the file into chunks. Since the columns in the text file were separated with a fixed width, this read_fef() read the contents effectively into separate columns. Syntax: data=pandas.read_fwf('filename.txt') Example: Python3 # Read Text Files with Pandas using read_fwf() # importing pandasimport pandas as pd # read text file into pandas DataFramedf = pd.read_fwf("gfg.txt") # display DataFrameprint(df) Output: Picked Python pandas-io Python-pandas 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 Python String | replace() How to Install PIP on Windows ? *args and **kwargs in Python Iterate over a list in Python Python Classes and Objects Convert integer to string in Python Python | os.path.join() method
[ { "code": null, "e": 28, "s": 0, "text": "\n28 Nov, 2021" }, { "code": null, "e": 251, "s": 28, "text": "In this article, we will discuss how to read text files with pandas in python. In python, the pandas module allows us to load DataFrames from external files and work on them. The dataset can be in different types of files." }, { "code": null, "e": 267, "s": 251, "text": "Text File Used:" }, { "code": null, "e": 572, "s": 267, "text": "We will read the text file with pandas using the read_csv() function. Along with the text file, we also pass separator as a single space (‘ ’) for the space character because, for text files, the space character will separate each field. There are three parameters we can pass to the read_csv() function." }, { "code": null, "e": 581, "s": 572, "text": "Syntax: " }, { "code": null, "e": 670, "s": 581, "text": "data=pandas.read_csv(‘filename.txt’, sep=’ ‘, header=None, names=[“Column1”, “Column2”])" }, { "code": null, "e": 682, "s": 670, "text": "Parameters:" }, { "code": null, "e": 782, "s": 682, "text": "filename.txt: As the name suggests it is the name of the text file from which we want to read data." }, { "code": null, "e": 880, "s": 782, "text": "sep: It is a separator field. In the text file, we use the space character(‘ ‘) as the separator." }, { "code": null, "e": 1039, "s": 880, "text": "header: This is an optional field. By default, it will take the first line of the text file as a header. If we use header=None then it will create the header." }, { "code": null, "e": 1132, "s": 1039, "text": "names: We can assign column names while importing the text file by using the names argument." }, { "code": null, "e": 1145, "s": 1132, "text": "Example 1: " }, { "code": null, "e": 1153, "s": 1145, "text": "Python3" }, { "code": "# Read Text Files with Pandas using read_csv() # importing pandasimport pandas as pd # read text file into pandas DataFramedf = pd.read_csv(\"gfg.txt\", sep=\" \") # display DataFrameprint(df)", "e": 1345, "s": 1153, "text": null }, { "code": null, "e": 1353, "s": 1345, "text": "Output:" }, { "code": null, "e": 1364, "s": 1353, "text": "Example 2:" }, { "code": null, "e": 1585, "s": 1364, "text": "In example 2 we will make the header filed equal to None. This will create a default header in the output. And take the first line of the text file as data entry. The created header name will be a number starting from 0." }, { "code": null, "e": 1593, "s": 1585, "text": "Python3" }, { "code": "# Read Text Files with Pandas using read_csv() # importing pandasimport pandas as pd # read text file into pandas DataFrame and# create headerdf = pd.read_csv(\"gfg.txt\", sep=\" \", header=None) # display DataFrameprint(df)", "e": 1817, "s": 1593, "text": null }, { "code": null, "e": 1825, "s": 1817, "text": "Output:" }, { "code": null, "e": 1836, "s": 1825, "text": "Example 3:" }, { "code": null, "e": 2032, "s": 1836, "text": "In the above output, we can see it creates a header starting from number 0. But we can also give names to the header. In this example, we will see how to create a header with a name using pandas." }, { "code": null, "e": 2040, "s": 2032, "text": "Python3" }, { "code": "# Read Text Files with Pandas using read_csv() # importing pandasimport pandas as pd # read text file into pandas DataFrame and create # header with namesdf = pd.read_csv(\"gfg.txt\", sep=\" \", header=None, names=[\"Team1\", \"Team2\"]) # display DataFrameprint(df)", "e": 2319, "s": 2040, "text": null }, { "code": null, "e": 2327, "s": 2319, "text": "Output:" }, { "code": null, "e": 2680, "s": 2327, "text": "We can read data from a text file using read_table() in pandas. This function reads a general delimited file to a DataFrame object. This function is essentially the same as the read_csv() function but with the delimiter = ‘\\t’, instead of a comma by default. We will read data with the read_table function making separator equal to a single space(‘ ‘)." }, { "code": null, "e": 2689, "s": 2680, "text": "Syntax: " }, { "code": null, "e": 2745, "s": 2689, "text": "data=pandas.read_table('filename.txt', delimiter = ' ')" }, { "code": null, "e": 2754, "s": 2745, "text": "Example:" }, { "code": null, "e": 2762, "s": 2754, "text": "Python3" }, { "code": "# Read Text Files with Pandas using read_table() # importing pandasimport pandas as pd # read text file into pandas DataFramedf = pd.read_table(\"gfg.txt\", delimiter=\" \") # display DataFrameprint(df)", "e": 2964, "s": 2762, "text": null }, { "code": null, "e": 3417, "s": 2964, "text": "The fwf in the read_fwf() function stands for fixed-width lines. We can use this function to load DataFrames from files. This function also supports text files. We will read data from the text files using the read_fef() function with pandas. It also supports optionally iterating or breaking the file into chunks. Since the columns in the text file were separated with a fixed width, this read_fef() read the contents effectively into separate columns." }, { "code": null, "e": 3426, "s": 3417, "text": "Syntax: " }, { "code": null, "e": 3463, "s": 3426, "text": "data=pandas.read_fwf('filename.txt')" }, { "code": null, "e": 3472, "s": 3463, "text": "Example:" }, { "code": null, "e": 3480, "s": 3472, "text": "Python3" }, { "code": "# Read Text Files with Pandas using read_fwf() # importing pandasimport pandas as pd # read text file into pandas DataFramedf = pd.read_fwf(\"gfg.txt\") # display DataFrameprint(df)", "e": 3663, "s": 3480, "text": null }, { "code": null, "e": 3671, "s": 3663, "text": "Output:" }, { "code": null, "e": 3678, "s": 3671, "text": "Picked" }, { "code": null, "e": 3695, "s": 3678, "text": "Python pandas-io" }, { "code": null, "e": 3709, "s": 3695, "text": "Python-pandas" }, { "code": null, "e": 3716, "s": 3709, "text": "Python" }, { "code": null, "e": 3814, "s": 3716, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 3832, "s": 3814, "text": "Python Dictionary" }, { "code": null, "e": 3874, "s": 3832, "text": "Different ways to create Pandas Dataframe" }, { "code": null, "e": 3896, "s": 3874, "text": "Enumerate() in Python" }, { "code": null, "e": 3922, "s": 3896, "text": "Python String | replace()" }, { "code": null, "e": 3954, "s": 3922, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 3983, "s": 3954, "text": "*args and **kwargs in Python" }, { "code": null, "e": 4013, "s": 3983, "text": "Iterate over a list in Python" }, { "code": null, "e": 4040, "s": 4013, "text": "Python Classes and Objects" }, { "code": null, "e": 4076, "s": 4040, "text": "Convert integer to string in Python" } ]
Point Clipping Algorithm in Computer Graphics
20 Apr, 2022 Clipping: In computer graphics our screen act as a 2-D coordinate system. it is not necessary that each and every point can be viewed on our viewing pane(i.e. our computer screen). We can view points, which lie in particular range (0,0) and (Xmax, Ymax). So, clipping is a procedure that identifies those portions of a picture that are either inside or outside of our viewing pane. In case of point clipping, we only show/print points on our window which are in range of our viewing pane, others points which are outside the range are discarded. Example Input : Output : Point Clipping Algorithm: Get the minimum and maximum coordinates of both viewing pane.Get the coordinates for a point.Check whether given input lies between minimum and maximum coordinate of viewing pane.If yes display the point which lies inside the region otherwise discard it. Get the minimum and maximum coordinates of both viewing pane. Get the coordinates for a point. Check whether given input lies between minimum and maximum coordinate of viewing pane. If yes display the point which lies inside the region otherwise discard it. C++ C Java Python3 C# // C++ program for point clipping Algorithm#include <bits/stdc++.h>using namespace std; // Function for point clippingvoid pointClip(int XY[][2], int n, int Xmin, int Ymin, int Xmax, int Ymax){ /*************** Code for graphics view // initialize graphics mode detectgraph(&gm,&gr); initgraph(&gm,&gr,"d:\\tc\\BGI"); for (int i=0; i<n; i++) { if ( (XY[i][0] >= Xmin) && (XY[i][0] <= Xmax)) { if ( (XY[i][1] >= Ymin) && (XY[i][1] <= Ymax)) putpixel(XY[i][0],XY[i][1],3); } } **********************/ /**** Arithmetic view ****/ cout << "Point inside the viewing pane:" << endl; for (int i = 0; i < n; i++) { if ((XY[i][0] >= Xmin) && (XY[i][0] <= Xmax)) { if ((XY[i][1] >= Ymin) && (XY[i][1] <= Ymax)) cout <<"[" << XY[i][0] <<","<<XY[i][1]<<"] "; } } // print point coordinate outside viewing pane cout<<"\n"<< endl; cout << "Point outside the viewing pane:"<<endl; for (int i = 0; i < n; i++) { if ((XY[i][0] < Xmin) || (XY[i][0] > Xmax)) cout << "[" << XY[i][0] << "," << XY[i][1] << "] "; if ((XY[i][1] < Ymin) || (XY[i][1] > Ymax)) cout << "[" << XY[i][0] << "," << XY[i][1] << "] "; }} // Driver codeint main(){ int XY[6][2] = {{10, 10}, {-10, 10}, {400, 100}, {100, 400}, {400, 400}, {100, 40}}; // getmaxx() & getmaxy() will return Xmax, Ymax // value if graphics.h is included int Xmin = 0; int Xmax = 350; int Ymin = 0; int Ymax = 350; pointClip(XY, 6, Xmin, Ymin, Xmax, Ymax); return 0;} // This code is contributed by SHUBHAMSINGH10 // C program for point clipping Algorithm#include<stdio.h>//#include<graphics.h> // Function for point clippingvoid pointClip(int XY[][2], int n, int Xmin, int Ymin, int Xmax, int Ymax){ /*************** Code for graphics view // initialize graphics mode detectgraph(&gm,&gr); initgraph(&gm,&gr,"d:\\tc\\BGI"); for (int i=0; i<n; i++) { if ( (XY[i][0] >= Xmin) && (XY[i][0] <= Xmax)) { if ( (XY[i][1] >= Ymin) && (XY[i][1] <= Ymax)) putpixel(XY[i][0],XY[i][1],3); } } **********************/ /**** Arithmetic view ****/ printf ("Point inside the viewing pane:\n"); for (int i=0; i<n; i++) { if ((XY[i][0] >= Xmin) && (XY[i][0] <= Xmax)) { if ((XY[i][1] >= Ymin) && (XY[i][1] <= Ymax)) printf ("[%d, %d] ", XY[i][0], XY[i][1]); } } // print point coordinate outside viewing pane printf ("\nPoint outside the viewing pane:\n"); for (int i=0; i<n; i++) { if ((XY[i][0] < Xmin) || (XY[i][0] > Xmax)) printf ("[%d, %d] ", XY[i][0], XY[i][1]); if ((XY[i][1] < Ymin) || (XY[i][1] > Ymax)) printf ("[%d, %d] ", XY[i][0], XY[i][1]); }} // Driver codeint main(){ int XY[6][2] = {{10,10}, {-10,10}, {400,100}, {100,400}, {400,400}, {100,40}}; // getmaxx() & getmaxy() will return Xmax, Ymax // value if graphics.h is included int Xmin = 0; int Xmax = 350; int Ymin = 0; int Ymax = 350; pointClip(XY, 6, Xmin, Ymin, Xmax, Ymax); return 0;} // Java program for point clipping Algorithmclass GFG{ // Function for point clippingstatic void pointClip(int XY[][], int n, int Xmin, int Ymin, int Xmax, int Ymax){ /*************** Code for graphics view // initialize graphics mode detectgraph(&gm,&gr); initgraph(&gm,&gr,"d:\\tc\\BGI"); for (int i=0; i<n; i++) { if ( (XY[i][0] >= Xmin) && (XY[i][0] <= Xmax)) { if ( (XY[i][1] >= Ymin) && (XY[i][1] <= Ymax)) putpixel(XY[i][0],XY[i][1],3); } } **********************/ /**** Arithmetic view ****/ System.out.printf ("Point inside the viewing pane:\n"); for (int i = 0; i < n; i++) { if ((XY[i][0] >= Xmin) && (XY[i][0] <= Xmax)) { if ((XY[i][1] >= Ymin) && (XY[i][1] <= Ymax)) System.out.printf ("[%d, %d] ", XY[i][0], XY[i][1]); } } // print point coordinate outside viewing pane System.out.printf ("\nPoint outside the viewing pane:\n"); for (int i=0; i<n; i++) { if ((XY[i][0] < Xmin) || (XY[i][0] > Xmax)) System.out.printf ("[%d, %d] ", XY[i][0], XY[i][1]); if ((XY[i][1] < Ymin) || (XY[i][1] > Ymax)) System.out.printf ("[%d, %d] ", XY[i][0], XY[i][1]); }} // Driver codepublic static void main(String[] args){ int XY[][] = {{10,10}, {-10,10}, {400,100}, {100,400}, {400,400}, {100,40}}; // getmaxx() & getmaxy() will return Xmax, Ymax // value if graphics.h is included int Xmin = 0; int Xmax = 350; int Ymin = 0; int Ymax = 350; pointClip(XY, 6, Xmin, Ymin, Xmax, Ymax);}} /* This code contributed by PrinciRaj1992 */ # Python3 program for point clipping Algorithm # Function for point clippingdef pointClip(XY, n, Xmin, Ymin, Xmax, Ymax): """************** Code for graphics view # initialize graphics mode detectgraph(&gm, &gr) initgraph(&gm, &gr, "d:\\tc\\BGI") for (i=0 i<n i++) if ((XY[i][0] >= Xmin) and (XY[i][0] <= Xmax)) if ((XY[i][1] >= Ymin) and (XY[i][1] <= Ymax)) putpixel(XY[i][0], XY[i][1], 3) *********************""" """*** Arithmetic view ***""" print("Point inside the viewing pane:") for i in range(n): if ((XY[i][0] >= Xmin) and (XY[i][0] <= Xmax)): if ((XY[i][1] >= Ymin) and (XY[i][1] <= Ymax)): print("[", XY[i][0], ", ", XY[i][1], "]", sep = "", end = " ") # prpocoordinate outside viewing pane print("\n\nPoint outside the viewing pane:") for i in range(n): if ((XY[i][0] < Xmin) or (XY[i][0] > Xmax)) : print("[", XY[i][0], ", ", XY[i][1], "]", sep = "", end = " ") if ((XY[i][1] < Ymin) or (XY[i][1] > Ymax)) : print("[", XY[i][0], ", ", XY[i][1], "]", sep = "", end = " ") # Driver Codeif __name__ == '__main__': XY = [[10, 10], [-10, 10], [400, 100], [100, 400], [400, 400], [100, 40]] # getmaxx() & getmaxy() will return Xmax, # Ymax value if graphics.h is included Xmin = 0 Xmax = 350 Ymin = 0 Ymax = 350 pointClip(XY, 6, Xmin, Ymin, Xmax, Ymax) # This code is contributed by# SHUBHAMSINGH10 // C# program for point clipping Algorithmusing System; class GFG{ // Function for point clippingstatic void pointClip(int [,]XY, int n, int Xmin, int Ymin, int Xmax, int Ymax){ /*************** Code for graphics view // initialize graphics mode detectgraph(&gm,&gr); initgraph(&gm,&gr,"d:\\tc\\BGI"); for (int i=0; i<n; i++) { if ( (XY[i,0] >= Xmin) && (XY[i,0] <= Xmax)) { if ( (XY[i,1] >= Ymin) && (XY[i,1] <= Ymax)) putpixel(XY[i,0],XY[i,1],3); } } **********************/ /**** Arithmetic view ****/ Console.Write("Point inside the viewing pane:\n"); for (int i = 0; i < n; i++) { if ((XY[i, 0] >= Xmin) && (XY[i, 0] <= Xmax)) { if ((XY[i, 1] >= Ymin) && (XY[i, 1] <= Ymax)) Console.Write("[{0}, {1}] ", XY[i, 0], XY[i, 1]); } } // print point coordinate outside viewing pane Console.Write("\nPoint outside the viewing pane:\n"); for (int i = 0; i < n; i++) { if ((XY[i, 0] < Xmin) || (XY[i, 0] > Xmax)) Console.Write("[{0}, {1}] ", XY[i, 0], XY[i, 1]); if ((XY[i, 1] < Ymin) || (XY[i, 1] > Ymax)) Console.Write("[{0}, {1}] ", XY[i, 0], XY[i, 1]); }} // Driver codepublic static void Main(String[] args){ int [,]XY = {{10, 10}, {-10, 10}, {400, 100}, {100, 400}, {400, 400}, {100, 40}}; // getmaxx() & getmaxy() will return Xmax, Ymax // value if graphics.h is included int Xmin = 0; int Xmax = 350; int Ymin = 0; int Ymax = 350; pointClip(XY, 6, Xmin, Ymin, Xmax, Ymax);}} // This code contributed by Rajput-Ji Output: Point inside the viewing pane: [10, 10] [100, 40] Point outside the viewing pane: [-10, 10] [400, 100] [100, 400] [400, 400] [400, 400] Time Complexity: O(N)Auxiliary Space: O(1) Related Post : Line Clipping | Set 1 (Cohen–Sutherland Algorithm) Polygon Clipping | Sutherland–Hodgman AlgorithmThis article is contributed by Shivam Pradhan (anuj_charm). If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. princiraj1992 Rajput-Ji SHUBHAMSINGH10 pankajsharmagfg surinderdawra388 computer-graphics Algorithms Algorithms Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Types of Complexity Classes | P, NP, CoNP, NP hard and NP complete Hash Functions and list/types of Hash functions How to Start Learning DSA? Complete Roadmap To Learn DSA From Scratch Minimum cost to reach the top of the floor by climbing stairs Difference between NP hard and NP complete problem Binary Search In JavaScript Algorithms Design Techniques What is Hashing | A Complete Tutorial Print all shortest paths between given source and destination in an undirected graph
[ { "code": null, "e": 53, "s": 25, "text": "\n20 Apr, 2022" }, { "code": null, "e": 609, "s": 53, "text": "Clipping: In computer graphics our screen act as a 2-D coordinate system. it is not necessary that each and every point can be viewed on our viewing pane(i.e. our computer screen). We can view points, which lie in particular range (0,0) and (Xmax, Ymax). So, clipping is a procedure that identifies those portions of a picture that are either inside or outside of our viewing pane. In case of point clipping, we only show/print points on our window which are in range of our viewing pane, others points which are outside the range are discarded. Example " }, { "code": null, "e": 628, "s": 609, "text": "Input :\n \nOutput :" }, { "code": null, "e": 656, "s": 628, "text": "Point Clipping Algorithm: " }, { "code": null, "e": 911, "s": 656, "text": "Get the minimum and maximum coordinates of both viewing pane.Get the coordinates for a point.Check whether given input lies between minimum and maximum coordinate of viewing pane.If yes display the point which lies inside the region otherwise discard it." }, { "code": null, "e": 973, "s": 911, "text": "Get the minimum and maximum coordinates of both viewing pane." }, { "code": null, "e": 1006, "s": 973, "text": "Get the coordinates for a point." }, { "code": null, "e": 1093, "s": 1006, "text": "Check whether given input lies between minimum and maximum coordinate of viewing pane." }, { "code": null, "e": 1169, "s": 1093, "text": "If yes display the point which lies inside the region otherwise discard it." }, { "code": null, "e": 1177, "s": 1173, "text": "C++" }, { "code": null, "e": 1179, "s": 1177, "text": "C" }, { "code": null, "e": 1184, "s": 1179, "text": "Java" }, { "code": null, "e": 1192, "s": 1184, "text": "Python3" }, { "code": null, "e": 1195, "s": 1192, "text": "C#" }, { "code": "// C++ program for point clipping Algorithm#include <bits/stdc++.h>using namespace std; // Function for point clippingvoid pointClip(int XY[][2], int n, int Xmin, int Ymin, int Xmax, int Ymax){ /*************** Code for graphics view // initialize graphics mode detectgraph(&gm,&gr); initgraph(&gm,&gr,\"d:\\\\tc\\\\BGI\"); for (int i=0; i<n; i++) { if ( (XY[i][0] >= Xmin) && (XY[i][0] <= Xmax)) { if ( (XY[i][1] >= Ymin) && (XY[i][1] <= Ymax)) putpixel(XY[i][0],XY[i][1],3); } } **********************/ /**** Arithmetic view ****/ cout << \"Point inside the viewing pane:\" << endl; for (int i = 0; i < n; i++) { if ((XY[i][0] >= Xmin) && (XY[i][0] <= Xmax)) { if ((XY[i][1] >= Ymin) && (XY[i][1] <= Ymax)) cout <<\"[\" << XY[i][0] <<\",\"<<XY[i][1]<<\"] \"; } } // print point coordinate outside viewing pane cout<<\"\\n\"<< endl; cout << \"Point outside the viewing pane:\"<<endl; for (int i = 0; i < n; i++) { if ((XY[i][0] < Xmin) || (XY[i][0] > Xmax)) cout << \"[\" << XY[i][0] << \",\" << XY[i][1] << \"] \"; if ((XY[i][1] < Ymin) || (XY[i][1] > Ymax)) cout << \"[\" << XY[i][0] << \",\" << XY[i][1] << \"] \"; }} // Driver codeint main(){ int XY[6][2] = {{10, 10}, {-10, 10}, {400, 100}, {100, 400}, {400, 400}, {100, 40}}; // getmaxx() & getmaxy() will return Xmax, Ymax // value if graphics.h is included int Xmin = 0; int Xmax = 350; int Ymin = 0; int Ymax = 350; pointClip(XY, 6, Xmin, Ymin, Xmax, Ymax); return 0;} // This code is contributed by SHUBHAMSINGH10", "e": 2885, "s": 1195, "text": null }, { "code": "// C program for point clipping Algorithm#include<stdio.h>//#include<graphics.h> // Function for point clippingvoid pointClip(int XY[][2], int n, int Xmin, int Ymin, int Xmax, int Ymax){ /*************** Code for graphics view // initialize graphics mode detectgraph(&gm,&gr); initgraph(&gm,&gr,\"d:\\\\tc\\\\BGI\"); for (int i=0; i<n; i++) { if ( (XY[i][0] >= Xmin) && (XY[i][0] <= Xmax)) { if ( (XY[i][1] >= Ymin) && (XY[i][1] <= Ymax)) putpixel(XY[i][0],XY[i][1],3); } } **********************/ /**** Arithmetic view ****/ printf (\"Point inside the viewing pane:\\n\"); for (int i=0; i<n; i++) { if ((XY[i][0] >= Xmin) && (XY[i][0] <= Xmax)) { if ((XY[i][1] >= Ymin) && (XY[i][1] <= Ymax)) printf (\"[%d, %d] \", XY[i][0], XY[i][1]); } } // print point coordinate outside viewing pane printf (\"\\nPoint outside the viewing pane:\\n\"); for (int i=0; i<n; i++) { if ((XY[i][0] < Xmin) || (XY[i][0] > Xmax)) printf (\"[%d, %d] \", XY[i][0], XY[i][1]); if ((XY[i][1] < Ymin) || (XY[i][1] > Ymax)) printf (\"[%d, %d] \", XY[i][0], XY[i][1]); }} // Driver codeint main(){ int XY[6][2] = {{10,10}, {-10,10}, {400,100}, {100,400}, {400,400}, {100,40}}; // getmaxx() & getmaxy() will return Xmax, Ymax // value if graphics.h is included int Xmin = 0; int Xmax = 350; int Ymin = 0; int Ymax = 350; pointClip(XY, 6, Xmin, Ymin, Xmax, Ymax); return 0;}", "e": 4460, "s": 2885, "text": null }, { "code": "// Java program for point clipping Algorithmclass GFG{ // Function for point clippingstatic void pointClip(int XY[][], int n, int Xmin, int Ymin, int Xmax, int Ymax){ /*************** Code for graphics view // initialize graphics mode detectgraph(&gm,&gr); initgraph(&gm,&gr,\"d:\\\\tc\\\\BGI\"); for (int i=0; i<n; i++) { if ( (XY[i][0] >= Xmin) && (XY[i][0] <= Xmax)) { if ( (XY[i][1] >= Ymin) && (XY[i][1] <= Ymax)) putpixel(XY[i][0],XY[i][1],3); } } **********************/ /**** Arithmetic view ****/ System.out.printf (\"Point inside the viewing pane:\\n\"); for (int i = 0; i < n; i++) { if ((XY[i][0] >= Xmin) && (XY[i][0] <= Xmax)) { if ((XY[i][1] >= Ymin) && (XY[i][1] <= Ymax)) System.out.printf (\"[%d, %d] \", XY[i][0], XY[i][1]); } } // print point coordinate outside viewing pane System.out.printf (\"\\nPoint outside the viewing pane:\\n\"); for (int i=0; i<n; i++) { if ((XY[i][0] < Xmin) || (XY[i][0] > Xmax)) System.out.printf (\"[%d, %d] \", XY[i][0], XY[i][1]); if ((XY[i][1] < Ymin) || (XY[i][1] > Ymax)) System.out.printf (\"[%d, %d] \", XY[i][0], XY[i][1]); }} // Driver codepublic static void main(String[] args){ int XY[][] = {{10,10}, {-10,10}, {400,100}, {100,400}, {400,400}, {100,40}}; // getmaxx() & getmaxy() will return Xmax, Ymax // value if graphics.h is included int Xmin = 0; int Xmax = 350; int Ymin = 0; int Ymax = 350; pointClip(XY, 6, Xmin, Ymin, Xmax, Ymax);}} /* This code contributed by PrinciRaj1992 */", "e": 6148, "s": 4460, "text": null }, { "code": "# Python3 program for point clipping Algorithm # Function for point clippingdef pointClip(XY, n, Xmin, Ymin, Xmax, Ymax): \"\"\"************** Code for graphics view # initialize graphics mode detectgraph(&gm, &gr) initgraph(&gm, &gr, \"d:\\\\tc\\\\BGI\") for (i=0 i<n i++) if ((XY[i][0] >= Xmin) and (XY[i][0] <= Xmax)) if ((XY[i][1] >= Ymin) and (XY[i][1] <= Ymax)) putpixel(XY[i][0], XY[i][1], 3) *********************\"\"\" \"\"\"*** Arithmetic view ***\"\"\" print(\"Point inside the viewing pane:\") for i in range(n): if ((XY[i][0] >= Xmin) and (XY[i][0] <= Xmax)): if ((XY[i][1] >= Ymin) and (XY[i][1] <= Ymax)): print(\"[\", XY[i][0], \", \", XY[i][1], \"]\", sep = \"\", end = \" \") # prpocoordinate outside viewing pane print(\"\\n\\nPoint outside the viewing pane:\") for i in range(n): if ((XY[i][0] < Xmin) or (XY[i][0] > Xmax)) : print(\"[\", XY[i][0], \", \", XY[i][1], \"]\", sep = \"\", end = \" \") if ((XY[i][1] < Ymin) or (XY[i][1] > Ymax)) : print(\"[\", XY[i][0], \", \", XY[i][1], \"]\", sep = \"\", end = \" \") # Driver Codeif __name__ == '__main__': XY = [[10, 10], [-10, 10], [400, 100], [100, 400], [400, 400], [100, 40]] # getmaxx() & getmaxy() will return Xmax, # Ymax value if graphics.h is included Xmin = 0 Xmax = 350 Ymin = 0 Ymax = 350 pointClip(XY, 6, Xmin, Ymin, Xmax, Ymax) # This code is contributed by# SHUBHAMSINGH10", "e": 7738, "s": 6148, "text": null }, { "code": "// C# program for point clipping Algorithmusing System; class GFG{ // Function for point clippingstatic void pointClip(int [,]XY, int n, int Xmin, int Ymin, int Xmax, int Ymax){ /*************** Code for graphics view // initialize graphics mode detectgraph(&gm,&gr); initgraph(&gm,&gr,\"d:\\\\tc\\\\BGI\"); for (int i=0; i<n; i++) { if ( (XY[i,0] >= Xmin) && (XY[i,0] <= Xmax)) { if ( (XY[i,1] >= Ymin) && (XY[i,1] <= Ymax)) putpixel(XY[i,0],XY[i,1],3); } } **********************/ /**** Arithmetic view ****/ Console.Write(\"Point inside the viewing pane:\\n\"); for (int i = 0; i < n; i++) { if ((XY[i, 0] >= Xmin) && (XY[i, 0] <= Xmax)) { if ((XY[i, 1] >= Ymin) && (XY[i, 1] <= Ymax)) Console.Write(\"[{0}, {1}] \", XY[i, 0], XY[i, 1]); } } // print point coordinate outside viewing pane Console.Write(\"\\nPoint outside the viewing pane:\\n\"); for (int i = 0; i < n; i++) { if ((XY[i, 0] < Xmin) || (XY[i, 0] > Xmax)) Console.Write(\"[{0}, {1}] \", XY[i, 0], XY[i, 1]); if ((XY[i, 1] < Ymin) || (XY[i, 1] > Ymax)) Console.Write(\"[{0}, {1}] \", XY[i, 0], XY[i, 1]); }} // Driver codepublic static void Main(String[] args){ int [,]XY = {{10, 10}, {-10, 10}, {400, 100}, {100, 400}, {400, 400}, {100, 40}}; // getmaxx() & getmaxy() will return Xmax, Ymax // value if graphics.h is included int Xmin = 0; int Xmax = 350; int Ymin = 0; int Ymax = 350; pointClip(XY, 6, Xmin, Ymin, Xmax, Ymax);}} // This code contributed by Rajput-Ji", "e": 9414, "s": 7738, "text": null }, { "code": null, "e": 9424, "s": 9414, "text": "Output: " }, { "code": null, "e": 9563, "s": 9424, "text": "Point inside the viewing pane:\n[10, 10] [100, 40] \n\nPoint outside the viewing pane:\n[-10, 10] [400, 100] [100, 400] [400, 400] [400, 400] " }, { "code": null, "e": 10155, "s": 9563, "text": "Time Complexity: O(N)Auxiliary Space: O(1) Related Post : Line Clipping | Set 1 (Cohen–Sutherland Algorithm) Polygon Clipping | Sutherland–Hodgman AlgorithmThis article is contributed by Shivam Pradhan (anuj_charm). If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. " }, { "code": null, "e": 10169, "s": 10155, "text": "princiraj1992" }, { "code": null, "e": 10179, "s": 10169, "text": "Rajput-Ji" }, { "code": null, "e": 10194, "s": 10179, "text": "SHUBHAMSINGH10" }, { "code": null, "e": 10210, "s": 10194, "text": "pankajsharmagfg" }, { "code": null, "e": 10227, "s": 10210, "text": "surinderdawra388" }, { "code": null, "e": 10245, "s": 10227, "text": "computer-graphics" }, { "code": null, "e": 10256, "s": 10245, "text": "Algorithms" }, { "code": null, "e": 10267, "s": 10256, "text": "Algorithms" }, { "code": null, "e": 10365, "s": 10267, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 10432, "s": 10365, "text": "Types of Complexity Classes | P, NP, CoNP, NP hard and NP complete" }, { "code": null, "e": 10480, "s": 10432, "text": "Hash Functions and list/types of Hash functions" }, { "code": null, "e": 10507, "s": 10480, "text": "How to Start Learning DSA?" }, { "code": null, "e": 10550, "s": 10507, "text": "Complete Roadmap To Learn DSA From Scratch" }, { "code": null, "e": 10612, "s": 10550, "text": "Minimum cost to reach the top of the floor by climbing stairs" }, { "code": null, "e": 10663, "s": 10612, "text": "Difference between NP hard and NP complete problem" }, { "code": null, "e": 10691, "s": 10663, "text": "Binary Search In JavaScript" }, { "code": null, "e": 10720, "s": 10691, "text": "Algorithms Design Techniques" }, { "code": null, "e": 10758, "s": 10720, "text": "What is Hashing | A Complete Tutorial" } ]
GATE | GATE CS 2012 | Question 65
22 Jul, 2021 Consider the 3 processes, P1, P2 and P3 shown in the table. Process Arrival time Time Units Required P1 0 5 P2 1 7 P3 3 4 The completion order of the 3 processes under the policies FCFS and RR2 (round robin scheduling with CPU quantum of 2 time units) are(A) FCFS: P1, P2, P3 RR2: P1, P2, P3 (B) FCFS: P1, P3, P2 RR2: P1, P3, P2 (C) FCFS: P1, P2, P3 RR2: P1, P3, P2 (D) FCFS: P1, P3, P2 RR2: P1, P2, P3 Answer: (C)Explanation: FCFS is clear. In RR, time slot is of 2 units. Processes are assigned in following order p1, p2, p1, p3, p2, p1, p3, p2, p2 This question involves the concept of ready queue. At t=2, p2 starts and p1 is sent to the ready queue and at t=3 p3 arrives so then the job p3 is queued in ready queue after p1. So at t=4, again p1 is executed then p3 is executed for first time at t=6. Watch GeeksforGeeks Video Explanation : CPU Scheduling GATE Previous Year Questions Part-II with Viomesh Singh - YouTubeGeeksforGeeks GATE Computer Science17.5K subscribersCPU Scheduling GATE Previous Year Questions Part-II with Viomesh SinghWatch 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:002:16 / 49:57•Live•<div class="player-unavailable"><h1 class="message">An error occurred.</h1><div class="submessage"><a href="https://www.youtube.com/watch?v=maVQoJuMAlM" target="_blank">Try watching this video on www.youtube.com</a>, or enable JavaScript if it is disabled in your browser.</div></div>Quiz of this Question GATE-CS-2012 GATE-GATE CS 2012 GATE Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 54, "s": 26, "text": "\n22 Jul, 2021" }, { "code": null, "e": 114, "s": 54, "text": "Consider the 3 processes, P1, P2 and P3 shown in the table." }, { "code": null, "e": 320, "s": 114, "text": "Process Arrival time Time Units Required\n P1 0 5\n P2 1 7\n P3 3 4" }, { "code": null, "e": 457, "s": 320, "text": "The completion order of the 3 processes under the policies FCFS and RR2 (round robin scheduling with CPU quantum of 2 time units) are(A)" }, { "code": null, "e": 491, "s": 457, "text": "FCFS: P1, P2, P3\n RR2: P1, P2, P3" }, { "code": null, "e": 495, "s": 491, "text": "(B)" }, { "code": null, "e": 530, "s": 495, "text": " FCFS: P1, P3, P2\n RR2: P1, P3, P2" }, { "code": null, "e": 534, "s": 530, "text": "(C)" }, { "code": null, "e": 568, "s": 534, "text": "FCFS: P1, P2, P3\n RR2: P1, P3, P2" }, { "code": null, "e": 572, "s": 568, "text": "(D)" }, { "code": null, "e": 606, "s": 572, "text": "FCFS: P1, P3, P2 \nRR2: P1, P2, P3" }, { "code": null, "e": 630, "s": 606, "text": "Answer: (C)Explanation:" }, { "code": null, "e": 761, "s": 630, "text": "FCFS is clear. \n\nIn RR, time slot is of 2 units. \n\nProcesses are assigned in following order\np1, p2, p1, p3, p2, p1, p3, p2, p2\n" }, { "code": null, "e": 1015, "s": 761, "text": "This question involves the concept of ready queue. At t=2, p2 starts and p1 is sent to the ready queue and at t=3 p3 arrives so then the job p3 is queued in ready queue after p1. So at t=4, again p1 is executed then p3 is executed for first time at t=6." }, { "code": null, "e": 1055, "s": 1015, "text": "Watch GeeksforGeeks Video Explanation :" }, { "code": null, "e": 2026, "s": 1055, "text": "CPU Scheduling GATE Previous Year Questions Part-II with Viomesh Singh - YouTubeGeeksforGeeks GATE Computer Science17.5K subscribersCPU Scheduling GATE Previous Year Questions Part-II with Viomesh SinghWatch 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:002:16 / 49:57•Live•<div class=\"player-unavailable\"><h1 class=\"message\">An error occurred.</h1><div class=\"submessage\"><a href=\"https://www.youtube.com/watch?v=maVQoJuMAlM\" target=\"_blank\">Try watching this video on www.youtube.com</a>, or enable JavaScript if it is disabled in your browser.</div></div>Quiz of this Question" }, { "code": null, "e": 2039, "s": 2026, "text": "GATE-CS-2012" }, { "code": null, "e": 2057, "s": 2039, "text": "GATE-GATE CS 2012" }, { "code": null, "e": 2062, "s": 2057, "text": "GATE" } ]
How to add Statefull component without constructor class in React?
11 Feb, 2022 Generally, we set the initial state of the component inside the constructor class and change the state using the setState method. In React basically, we write HTML-looking code called JSX. JSX is not a valid JavaScript code but to make the developer’s life easier BABEL takes all the responsibility to convert JSX into valid JavaScript code and allow the developers to write code in HTML-looking syntax. Similarly, the state can’t be initialized without constructor class, when we initialize state outside constructor class again Bable read the syntax and understands there is a need to create constructor inside the class and do all the required hard works behind the scene. This is called a class property proposal. Syntax: Initialize state outside the constructor class using syntax. state = {stateName1:stateValue1, stateName2:stateName2, ....... stateNamek:stateValuek} Example 1: This example illustrates how to class property proposal to initialize state without constructor index.js: Javascript import React from 'react'import ReactDOM from 'react-dom'import App from './App' ReactDOM.render(<App />, document.querySelector('#root')) Filename – App.js Javascript import React, { Component } from 'react' class App extends Component { // The class property proposal // The state initialization without // constructor class state = {msg : 'Hi, There!'} handleClick(){ // Changing state this.setState({msg : 'Welcome to the React world!'}) } render(){ return ( <div> <h2>Message :</h2> <p>{this.state.msg}</p> {/* Set click handler */} <button onClick={() => this.handleClick()}> Click here! </button> </div> ) }} export default App Output: Example 2: This example illustrates how to class property proposal to initialize state without constructor index.js: Javascript import React from 'react'import ReactDOM from 'react-dom'import App from './App' ReactDOM.render(<App />, document.querySelector('#root')) App.js: Javascript import React, { Component } from 'react' class App extends Component { static defaultProps = { courseContent : [ 'JSX', 'React Props', 'React State', 'React Lifecycle Methods', 'React Event Handlers', 'React Router', 'React Hooks', 'Readux', 'React Context' ] } // The class property proposal // The state initialization without // constructor class state = {msg : 'React Course', content:''} renderContent(){ return ( <ul> {this.props.courseContent.map(content => ( <li>{content}</li> ))} </ul> ) } handleClick(){ //changing state this.setState({ msg : 'Course Content', content : this.renderContent() }) } render(){ return ( <div> <h2>Message :</h2> <p>{this.state.msg}</p> <p>{this.state.content}</p> {/* set click handler */} <button onClick={() => this.handleClick()}> Click here to know contents! </button> </div> ) }} export default App Output: punamsingh628700 rkbhola5 react-js JavaScript Web Technologies Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 53, "s": 25, "text": "\n11 Feb, 2022" }, { "code": null, "e": 771, "s": 53, "text": "Generally, we set the initial state of the component inside the constructor class and change the state using the setState method. In React basically, we write HTML-looking code called JSX. JSX is not a valid JavaScript code but to make the developer’s life easier BABEL takes all the responsibility to convert JSX into valid JavaScript code and allow the developers to write code in HTML-looking syntax. Similarly, the state can’t be initialized without constructor class, when we initialize state outside constructor class again Bable read the syntax and understands there is a need to create constructor inside the class and do all the required hard works behind the scene. This is called a class property proposal." }, { "code": null, "e": 840, "s": 771, "text": "Syntax: Initialize state outside the constructor class using syntax." }, { "code": null, "e": 958, "s": 840, "text": "state = {stateName1:stateValue1, \n stateName2:stateName2, \n ....... \n stateNamek:stateValuek}" }, { "code": null, "e": 1066, "s": 958, "text": "Example 1: This example illustrates how to class property proposal to initialize state without constructor " }, { "code": null, "e": 1076, "s": 1066, "text": "index.js:" }, { "code": null, "e": 1087, "s": 1076, "text": "Javascript" }, { "code": "import React from 'react'import ReactDOM from 'react-dom'import App from './App' ReactDOM.render(<App />, document.querySelector('#root'))", "e": 1226, "s": 1087, "text": null }, { "code": null, "e": 1247, "s": 1229, "text": "Filename – App.js" }, { "code": null, "e": 1260, "s": 1249, "text": "Javascript" }, { "code": "import React, { Component } from 'react' class App extends Component { // The class property proposal // The state initialization without // constructor class state = {msg : 'Hi, There!'} handleClick(){ // Changing state this.setState({msg : 'Welcome to the React world!'}) } render(){ return ( <div> <h2>Message :</h2> <p>{this.state.msg}</p> {/* Set click handler */} <button onClick={() => this.handleClick()}> Click here! </button> </div> ) }} export default App", "e": 1823, "s": 1260, "text": null }, { "code": null, "e": 1834, "s": 1826, "text": "Output:" }, { "code": null, "e": 1946, "s": 1838, "text": "Example 2: This example illustrates how to class property proposal to initialize state without constructor " }, { "code": null, "e": 1958, "s": 1948, "text": "index.js:" }, { "code": null, "e": 1971, "s": 1960, "text": "Javascript" }, { "code": "import React from 'react'import ReactDOM from 'react-dom'import App from './App' ReactDOM.render(<App />, document.querySelector('#root'))", "e": 2110, "s": 1971, "text": null }, { "code": null, "e": 2121, "s": 2113, "text": "App.js:" }, { "code": null, "e": 2134, "s": 2123, "text": "Javascript" }, { "code": "import React, { Component } from 'react' class App extends Component { static defaultProps = { courseContent : [ 'JSX', 'React Props', 'React State', 'React Lifecycle Methods', 'React Event Handlers', 'React Router', 'React Hooks', 'Readux', 'React Context' ] } // The class property proposal // The state initialization without // constructor class state = {msg : 'React Course', content:''} renderContent(){ return ( <ul> {this.props.courseContent.map(content => ( <li>{content}</li> ))} </ul> ) } handleClick(){ //changing state this.setState({ msg : 'Course Content', content : this.renderContent() }) } render(){ return ( <div> <h2>Message :</h2> <p>{this.state.msg}</p> <p>{this.state.content}</p> {/* set click handler */} <button onClick={() => this.handleClick()}> Click here to know contents! </button> </div> ) }} export default App", "e": 3168, "s": 2134, "text": null }, { "code": null, "e": 3180, "s": 3171, "text": "Output: " }, { "code": null, "e": 3201, "s": 3184, "text": "punamsingh628700" }, { "code": null, "e": 3210, "s": 3201, "text": "rkbhola5" }, { "code": null, "e": 3219, "s": 3210, "text": "react-js" }, { "code": null, "e": 3230, "s": 3219, "text": "JavaScript" }, { "code": null, "e": 3247, "s": 3230, "text": "Web Technologies" } ]
Java Program to Add two Complex Numbers
15 Dec, 2020 Complex numbers are numbers that consist of two parts — a real number and an imaginary number. Complex numbers are the building blocks of more intricate math, such as algebra. The standard format for complex numbers is a + bi, with the real number first and the imaginary number last. General form for any complex number is: a+ib Where "a" is real number and "b" is Imaginary number. Construction of Complex number For creating a complex numbers, we will pass imaginary numbers and real numbers as parameters for constructors. Java // Java program to construct the complex number class ComplexNumber { // variables to hold real and imaginary part of complex // number int real, image; // Constructor which will be used while creating complex // number public ComplexNumber(int r, int i) { this.real = r; this.image = i; } // function to print real number public void showC() { System.out.println(this.real + " +i " + this.image); } // we will implement this function for addition public complex add(ComplexNumber, ComplexNumber);} Add function Basically, addition of two complex numbers is done by adding real part of the first complex number with real part of the second complex number. And adding imaginary part of the first complex number with the second which results into the third complex number. So that means our add() will return another complex number. Ex. addition of two complex numbers (a1) + (b1)i —–(1) (a2)+ (b2)i —–(2) adding (1) and (2) will look like (a1+a2) + (b1+b2)i Function Definition: ComplexNumber add(ComplexNumber n1, ComplexNumber n2){ ComplexNumber res = new ComplexNumber(0,0); //creating blank complex number // adding real parts of both complex numbers res.real = n1.real + n2.real; // adding imaginary parts res.image = n1.image + n2.image; // returning result return res; } Code: Java // Java program to add two complex numbers class ComplexNumber { // variables to hold real and imaginary part of complex // number int real, image; // Constructor which will be used while creating complex // number public ComplexNumber(int r, int i) { this.real = r; this.image = i; } // function to print real number public void showC() { System.out.print(this.real + " +i" + this.image); } // function for addition public static ComplexNumber add(ComplexNumber n1, ComplexNumber n2) { // creating blank complex number // to store result ComplexNumber res = new ComplexNumber(0, 0); // adding real parts of both complex numbers res.real = n1.real + n2.real; // adding imaginary parts res.image = n1.image + n2.image; // returning result return res; } public static void main(String arg[]) { // creating two complex numbers ComplexNumber c1 = new ComplexNumber(4, 5); ComplexNumber c2 = new ComplexNumber(10, 5); // printing complex numbers System.out.print("first Complex number: "); c1.showC(); System.out.print("\nSecond Complex number: "); c2.showC(); // calling add() to perform addition ComplexNumber res = add(c1, c2); // displaying addition System.out.println("\nAddition is :"); res.showC(); }} first Complex number: 4 +i5 Second Complex number: 10 +i5 Addition is : 14 +i10 Picked Technical Scripter 2020 Java Java Programs Technical Scripter Java Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Stream In Java 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": 54, "s": 26, "text": "\n15 Dec, 2020" }, { "code": null, "e": 339, "s": 54, "text": "Complex numbers are numbers that consist of two parts — a real number and an imaginary number. Complex numbers are the building blocks of more intricate math, such as algebra. The standard format for complex numbers is a + bi, with the real number first and the imaginary number last." }, { "code": null, "e": 379, "s": 339, "text": "General form for any complex number is:" }, { "code": null, "e": 439, "s": 379, "text": "a+ib\n\nWhere \"a\" is real number and \"b\" is Imaginary number." }, { "code": null, "e": 470, "s": 439, "text": "Construction of Complex number" }, { "code": null, "e": 582, "s": 470, "text": "For creating a complex numbers, we will pass imaginary numbers and real numbers as parameters for constructors." }, { "code": null, "e": 587, "s": 582, "text": "Java" }, { "code": "// Java program to construct the complex number class ComplexNumber { // variables to hold real and imaginary part of complex // number int real, image; // Constructor which will be used while creating complex // number public ComplexNumber(int r, int i) { this.real = r; this.image = i; } // function to print real number public void showC() { System.out.println(this.real + \" +i \" + this.image); } // we will implement this function for addition public complex add(ComplexNumber, ComplexNumber);}", "e": 1159, "s": 587, "text": null }, { "code": null, "e": 1173, "s": 1159, "text": " Add function" }, { "code": null, "e": 1317, "s": 1173, "text": "Basically, addition of two complex numbers is done by adding real part of the first complex number with real part of the second complex number." }, { "code": null, "e": 1432, "s": 1317, "text": "And adding imaginary part of the first complex number with the second which results into the third complex number." }, { "code": null, "e": 1492, "s": 1432, "text": "So that means our add() will return another complex number." }, { "code": null, "e": 1530, "s": 1494, "text": "Ex. addition of two complex numbers" }, { "code": null, "e": 1549, "s": 1530, "text": "(a1) + (b1)i —–(1)" }, { "code": null, "e": 1567, "s": 1549, "text": "(a2)+ (b2)i —–(2)" }, { "code": null, "e": 1601, "s": 1567, "text": "adding (1) and (2) will look like" }, { "code": null, "e": 1620, "s": 1601, "text": "(a1+a2) + (b1+b2)i" }, { "code": null, "e": 1642, "s": 1620, "text": "Function Definition: " }, { "code": null, "e": 1971, "s": 1642, "text": "ComplexNumber add(ComplexNumber n1, ComplexNumber n2){\n \n ComplexNumber res = new ComplexNumber(0,0); //creating blank complex number \n \n // adding real parts of both complex numbers\n res.real = n1.real + n2.real;\n \n // adding imaginary parts\n res.image = n1.image + n2.image;\n \n // returning result\n return res;\n\n}" }, { "code": null, "e": 1980, "s": 1971, "text": " Code: " }, { "code": null, "e": 1985, "s": 1980, "text": "Java" }, { "code": "// Java program to add two complex numbers class ComplexNumber { // variables to hold real and imaginary part of complex // number int real, image; // Constructor which will be used while creating complex // number public ComplexNumber(int r, int i) { this.real = r; this.image = i; } // function to print real number public void showC() { System.out.print(this.real + \" +i\" + this.image); } // function for addition public static ComplexNumber add(ComplexNumber n1, ComplexNumber n2) { // creating blank complex number // to store result ComplexNumber res = new ComplexNumber(0, 0); // adding real parts of both complex numbers res.real = n1.real + n2.real; // adding imaginary parts res.image = n1.image + n2.image; // returning result return res; } public static void main(String arg[]) { // creating two complex numbers ComplexNumber c1 = new ComplexNumber(4, 5); ComplexNumber c2 = new ComplexNumber(10, 5); // printing complex numbers System.out.print(\"first Complex number: \"); c1.showC(); System.out.print(\"\\nSecond Complex number: \"); c2.showC(); // calling add() to perform addition ComplexNumber res = add(c1, c2); // displaying addition System.out.println(\"\\nAddition is :\"); res.showC(); }}", "e": 3495, "s": 1985, "text": null }, { "code": null, "e": 3575, "s": 3495, "text": "first Complex number: 4 +i5\nSecond Complex number: 10 +i5\nAddition is :\n14 +i10" }, { "code": null, "e": 3584, "s": 3577, "text": "Picked" }, { "code": null, "e": 3608, "s": 3584, "text": "Technical Scripter 2020" }, { "code": null, "e": 3613, "s": 3608, "text": "Java" }, { "code": null, "e": 3627, "s": 3613, "text": "Java Programs" }, { "code": null, "e": 3646, "s": 3627, "text": "Technical Scripter" }, { "code": null, "e": 3651, "s": 3646, "text": "Java" }, { "code": null, "e": 3749, "s": 3651, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 3764, "s": 3749, "text": "Stream In Java" }, { "code": null, "e": 3785, "s": 3764, "text": "Introduction to Java" }, { "code": null, "e": 3806, "s": 3785, "text": "Constructors in Java" }, { "code": null, "e": 3825, "s": 3806, "text": "Exceptions in Java" }, { "code": null, "e": 3842, "s": 3825, "text": "Generics in Java" }, { "code": null, "e": 3868, "s": 3842, "text": "Java Programming Examples" }, { "code": null, "e": 3902, "s": 3868, "text": "Convert Double to Integer in Java" }, { "code": null, "e": 3949, "s": 3902, "text": "Implementing a Linked List in Java using Class" }, { "code": null, "e": 3987, "s": 3949, "text": "Factory method design pattern in Java" } ]
PostgreSQL – NTILE Function
08 Oct, 2021 In PostgreSQL, the NTILE() function is used to divide ordered rows in the partition into a specified number of ranked buckets. Buckets are nothing but ranked groups. The syntax of the NTILE() looks like below: Syntax: NTILE(buckets) OVER ( [PARTITION BY partition_expression, ... ] [ORDER BY sort_expression [ASC | DESC], ...] ) Let’s analyze the above syntax: The buckets are the number of ranked groups. It can either be a number or an expression but the expression must evaluate a positive integer value. The PARTITION BY is an optional clause distributes rows into partitions. The ORDER BY clause is used to sort rows in each partition. Example 1: First, create a table named sales_stats that stores the sales revenue by employees: CREATE TABLE sales_stats( name VARCHAR(100) NOT NULL, year SMALLINT NOT NULL CHECK (year > 0), amount DECIMAL(10, 2) CHECK (amount >= 0), PRIMARY KEY (name, year) ); Second, insert some rows into the sales_stats table: INSERT INTO sales_stats(name, year, amount) VALUES ('Raju kumar', 2018, 120000), ('Alibaba', 2018, 110000), ('Gabbar Singh', 2018, 150000), ('Kadar Khan', 2018, 30000), ('Amrish Puri', 2018, 200000), ('Raju kumar', 2019, 150000), ('Alibaba', 2019, 130000), ('Gabbar Singh', 2019, 180000), ('Kadar Khan', 2019, 25000), ('Amrish Puri', 2019, 270000); The below statement uses the NTILE() function to distribute rows into 3 buckets: SELECT name, amount, NTILE(3) OVER( ORDER BY amount ) FROM sales_stats WHERE year = 2019; Output: Example 2: The below query uses the NTILE() function to divide rows in the sales_stats table into two partitions and 3 buckets for each: SELECT name, amount, NTILE(3) OVER( PARTITION BY year ORDER BY amount ) FROM sales_stats; Output: sooda367 PostgreSQL-function PostgreSQL-Window-function PostgreSQL Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n08 Oct, 2021" }, { "code": null, "e": 194, "s": 28, "text": "In PostgreSQL, the NTILE() function is used to divide ordered rows in the partition into a specified number of ranked buckets. Buckets are nothing but ranked groups." }, { "code": null, "e": 238, "s": 194, "text": "The syntax of the NTILE() looks like below:" }, { "code": null, "e": 365, "s": 238, "text": "Syntax:\nNTILE(buckets) OVER (\n [PARTITION BY partition_expression, ... ]\n [ORDER BY sort_expression [ASC | DESC], ...]\n)" }, { "code": null, "e": 397, "s": 365, "text": "Let’s analyze the above syntax:" }, { "code": null, "e": 544, "s": 397, "text": "The buckets are the number of ranked groups. It can either be a number or an expression but the expression must evaluate a positive integer value." }, { "code": null, "e": 617, "s": 544, "text": "The PARTITION BY is an optional clause distributes rows into partitions." }, { "code": null, "e": 677, "s": 617, "text": "The ORDER BY clause is used to sort rows in each partition." }, { "code": null, "e": 688, "s": 677, "text": "Example 1:" }, { "code": null, "e": 773, "s": 688, "text": "First, create a table named sales_stats that stores the sales revenue by employees:" }, { "code": null, "e": 955, "s": 773, "text": "CREATE TABLE sales_stats(\n name VARCHAR(100) NOT NULL,\n year SMALLINT NOT NULL CHECK (year > 0),\n amount DECIMAL(10, 2) CHECK (amount >= 0),\n PRIMARY KEY (name, year)\n);" }, { "code": null, "e": 1008, "s": 955, "text": "Second, insert some rows into the sales_stats table:" }, { "code": null, "e": 1402, "s": 1008, "text": "INSERT INTO \n sales_stats(name, year, amount)\nVALUES\n ('Raju kumar', 2018, 120000),\n ('Alibaba', 2018, 110000),\n ('Gabbar Singh', 2018, 150000),\n ('Kadar Khan', 2018, 30000),\n ('Amrish Puri', 2018, 200000),\n ('Raju kumar', 2019, 150000),\n ('Alibaba', 2019, 130000),\n ('Gabbar Singh', 2019, 180000),\n ('Kadar Khan', 2019, 25000),\n ('Amrish Puri', 2019, 270000);" }, { "code": null, "e": 1483, "s": 1402, "text": "The below statement uses the NTILE() function to distribute rows into 3 buckets:" }, { "code": null, "e": 1606, "s": 1483, "text": "SELECT \n name,\n amount,\n NTILE(3) OVER(\n ORDER BY amount\n )\nFROM\n sales_stats\nWHERE\n year = 2019;" }, { "code": null, "e": 1614, "s": 1606, "text": "Output:" }, { "code": null, "e": 1625, "s": 1614, "text": "Example 2:" }, { "code": null, "e": 1751, "s": 1625, "text": "The below query uses the NTILE() function to divide rows in the sales_stats table into two partitions and 3 buckets for each:" }, { "code": null, "e": 1878, "s": 1751, "text": "SELECT \n name,\n amount,\n NTILE(3) OVER(\n PARTITION BY year\n ORDER BY amount\n )\nFROM\n sales_stats;" }, { "code": null, "e": 1886, "s": 1878, "text": "Output:" }, { "code": null, "e": 1895, "s": 1886, "text": "sooda367" }, { "code": null, "e": 1915, "s": 1895, "text": "PostgreSQL-function" }, { "code": null, "e": 1942, "s": 1915, "text": "PostgreSQL-Window-function" }, { "code": null, "e": 1953, "s": 1942, "text": "PostgreSQL" } ]
Program to add two binary strings
30 Jun, 2022 Given two binary strings, return their sum (also a binary string). Example: Input: a = "11", b = "1" Output: "100" We strongly recommend you to minimize your browser and try this yourself first The idea is to start from the last characters of two strings and compute the digit sum one by one. If the sum becomes more than 1, then store carry for the next digits. C Java Python3 C# PHP Javascript // C++ program to add two binary strings#include <bits/stdc++.h>using namespace std; // This function adds two binary strings and return// result as a third stringstring addBinary(string A, string B){ // If the length of string A is greater than the length // of B then just swap the string by calling the // same function and make sure to return the function // otherwise recursion will occur which leads to // calling the same function twice if (A.length() > B.length()) return addBinary(B, A); // Calculating the difference between the length of the // two strings. int diff = B.length() - A.length(); // Initialise the padding string which is used to store // zeroes that should be added as prefix to the string // which has length smaller than the other string. string padding; for (int i = 0; i < diff; i++) padding.push_back('0'); A = padding + A; string res; char carry = '0'; for (int i = A.length() - 1; i >= 0; i--) { // This if condition solves 110 111 possible cases if (A[i] == '1' && B[i] == '1') { if (carry == '1') res.push_back('1'), carry = '1'; else res.push_back('0'), carry = '1'; } // This if condition solves 000 001 possible cases else if (A[i] == '0' && B[i] == '0') { if (carry == '1') res.push_back('1'), carry = '0'; else res.push_back('0'), carry = '0'; } // This if condition solves 100 101 010 011 possible // cases else if (A[i] != B[i]) { if (carry == '1') res.push_back('0'), carry = '1'; else res.push_back('1'), carry = '0'; } } // If at the end their is carry then just add it to the // result if (carry == '1') res.push_back(carry); // reverse the result reverse(res.begin(), res.end()); // To remove leading zeroes int index = 0; while (index + 1 < res.length() && res[index] == '0') index++; return (res.substr(index));} // Driver programint main(){ string a = "1101", b = "100"; cout << addBinary(a, b) << endl; return 0;} // java program to add// two binary strings public class GFG { // This function adds two // binary strings and return // result as a third string static String addBinary(String a, String b) { //If the inputs are 0 if(a.charAt(0) == '0' && b.charAt(0) == '0'){ return "0"; } // Initialize result StringBuilder result = new StringBuilder(""); // Initialize digit sum int s = 0; // Traverse both strings starting // from last characters int i = a.length() - 1, j = b.length() - 1; while (i >= 0 || j >= 0 || s == 1) { // Comput sum of last // digits and carry s += ((i >= 0)? a.charAt(i) - '0': 0); s += ((j >= 0)? b.charAt(j) - '0': 0); // If current digit sum is // 1 or 3, add 1 to result result.append((char)(s % 2 + '0')); // Compute carry s /= 2; // Move to next digits i--; j--; } // Remove leading zeros, if any int start = result.length()-1; while(start >=0 && result.charAt(start) == '0') { start--; } if(start != result.length()-1) { result.delete(start+1,result.length()); } return result.reverse().toString(); } //Driver code public static void main(String args[]) { String a = "1101", b="100"; System.out.print(addBinary(a, b)); }} // This code is contributed by Sam007. # Python Solution for above problem: # This function adds two binary# strings return the resulting stringdef add_binary_nums(x, y): max_len = max(len(x), len(y)) x = x.zfill(max_len) y = y.zfill(max_len) # initialize the result result = '' # initialize the carry carry = 0 # Traverse the string for i in range(max_len - 1, -1, -1): r = carry r += 1 if x[i] == '1' else 0 r += 1 if y[i] == '1' else 0 result = ('1' if r % 2 == 1 else '0') + result carry = 0 if r < 2 else 1 # Compute the carry. if carry !=0 : result = '1' + result return result.zfill(max_len) # Driver codeprint(add_binary_nums('1101', '100')) # This code is contributed# by Anand Khatri // C# program to add// two binary stringsusing System; class GFG { // This function adds two // binary strings and return // result as a third string static string addBinary(string a, string b) { // Initialize result string result = ""; // Initialize digit sum int s = 0; // Traverse both strings starting // from last characters int i = a.Length - 1, j = b.Length - 1; while (i >= 0 || j >= 0 || s == 1) { // Comput sum of last // digits and carry s += ((i >= 0)? a[i] - '0': 0); s += ((j >= 0)? b[j] - '0': 0); // If current digit sum is // 1 or 3, add 1 to result result = (char)(s % 2 + '0') + result; // Compute carry s /= 2; // Move to next digits i--; j--; } return result; } // Driver Code public static void Main(){ string a = "1101", b="100"; Console.Write( addBinary(a, b));}} // This code is contributed by Sam007 <?php// PHP program to add two binary strings // This function adds two binary strings// and return result as a third stringfunction addBinary($a, $b){ $result = ""; // Initialize result $s = 0; // Initialize digit sum // Traverse both strings starting // from last characters $i = strlen($a) - 1; $j = strlen($b) - 1; while ($i >= 0 || $j >= 0 || $s == 1) { // Comput sum of last digits and carry $s += (($i >= 0)? ord($a[$i]) - ord('0'): 0); $s += (($j >= 0)? ord($b[$j]) - ord('0'): 0); // If current digit sum is 1 or 3, // add 1 to result $result = chr($s % 2 + ord('0')) . $result; // Compute carry $s = (int)($s / 2); // Move to next digits $i--; $j--; } return $result;} // Driver Code$a = "1101";$b = "100";echo addBinary($a, $b); // This code is contributed by mits?> <script> // Javascript program to add// two binary strings // This function adds two// binary strings and return// result as a third stringfunction addBinary(a, b){ // Initialize result var result = ""; // Initialize digit sum var s = 0; // Traverse both strings starting // from last characters var i = a.length - 1, j = b.length - 1; while (i >= 0 || j >= 0 || s == 1) { // Comput sum of last // digits and carry s += ((i >= 0)? a.charAt(i).charCodeAt(0) - '0'.charCodeAt(0): 0); s += ((j >= 0)? b.charAt(j).charCodeAt(0) - '0'.charCodeAt(0): 0); // If current digit sum is // 1 or 3, add 1 to result result = String.fromCharCode(parseInt(s % 2) + '0'.charCodeAt(0)) + result; // Compute carry s = parseInt(s/2); // Move to next digits i--; j--; } return result;} //Driver codevar a = "1101", b="100"; document.write(addBinary(a, b)); // This code is contributed by Amit Katiyar </script> 10001 Time Complexity: O(max(L1, L2)), where L1 and L2 are the lengths of strings a and b respectively. Auxiliary Space: O(max(L1, L2)), where L1 and L2 are the lengths of strings a and b respectively. Add two binary strings | GeeksforGeeks - YouTubeGeeksforGeeks529K subscribersAdd two binary strings | 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 / 1:54•Live•<div class="player-unavailable"><h1 class="message">An error occurred.</h1><div class="submessage"><a href="https://www.youtube.com/watch?v=TraAvM7JxL4" target="_blank">Try watching this video on www.youtube.com</a>, or enable JavaScript if it is disabled in your browser.</div></div> Sam007 anandkhatri Mithun Kumar shubham_singh Akanksha_Rai amit143katiyar adityakumar129 rupeswarofficial sumitgumber28 sweetyty ankita_saini shivamanandrj9 hardikkoriintern sepidehfallah2 Facebook Microsoft Mathematical Strings Microsoft Facebook Strings 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++ Sieve of Eratosthenes Prime Numbers Program to find GCD or HCF of two numbers Write a program to reverse an array or string Reverse a string in Java Check for Balanced Brackets in an expression (well-formedness) using Stack Different Methods to Reverse a String in C++ Python program to check if a string is palindrome or not
[ { "code": null, "e": 54, "s": 26, "text": "\n30 Jun, 2022" }, { "code": null, "e": 121, "s": 54, "text": "Given two binary strings, return their sum (also a binary string)." }, { "code": null, "e": 131, "s": 121, "text": "Example: " }, { "code": null, "e": 172, "s": 131, "text": "Input: a = \"11\", b = \"1\"\nOutput: \"100\" " }, { "code": null, "e": 252, "s": 172, "text": "We strongly recommend you to minimize your browser and try this yourself first " }, { "code": null, "e": 422, "s": 252, "text": "The idea is to start from the last characters of two strings and compute the digit sum one by one. If the sum becomes more than 1, then store carry for the next digits. " }, { "code": null, "e": 424, "s": 422, "text": "C" }, { "code": null, "e": 429, "s": 424, "text": "Java" }, { "code": null, "e": 437, "s": 429, "text": "Python3" }, { "code": null, "e": 440, "s": 437, "text": "C#" }, { "code": null, "e": 444, "s": 440, "text": "PHP" }, { "code": null, "e": 455, "s": 444, "text": "Javascript" }, { "code": "// C++ program to add two binary strings#include <bits/stdc++.h>using namespace std; // This function adds two binary strings and return// result as a third stringstring addBinary(string A, string B){ // If the length of string A is greater than the length // of B then just swap the string by calling the // same function and make sure to return the function // otherwise recursion will occur which leads to // calling the same function twice if (A.length() > B.length()) return addBinary(B, A); // Calculating the difference between the length of the // two strings. int diff = B.length() - A.length(); // Initialise the padding string which is used to store // zeroes that should be added as prefix to the string // which has length smaller than the other string. string padding; for (int i = 0; i < diff; i++) padding.push_back('0'); A = padding + A; string res; char carry = '0'; for (int i = A.length() - 1; i >= 0; i--) { // This if condition solves 110 111 possible cases if (A[i] == '1' && B[i] == '1') { if (carry == '1') res.push_back('1'), carry = '1'; else res.push_back('0'), carry = '1'; } // This if condition solves 000 001 possible cases else if (A[i] == '0' && B[i] == '0') { if (carry == '1') res.push_back('1'), carry = '0'; else res.push_back('0'), carry = '0'; } // This if condition solves 100 101 010 011 possible // cases else if (A[i] != B[i]) { if (carry == '1') res.push_back('0'), carry = '1'; else res.push_back('1'), carry = '0'; } } // If at the end their is carry then just add it to the // result if (carry == '1') res.push_back(carry); // reverse the result reverse(res.begin(), res.end()); // To remove leading zeroes int index = 0; while (index + 1 < res.length() && res[index] == '0') index++; return (res.substr(index));} // Driver programint main(){ string a = \"1101\", b = \"100\"; cout << addBinary(a, b) << endl; return 0;}", "e": 2673, "s": 455, "text": null }, { "code": "// java program to add// two binary strings public class GFG { // This function adds two // binary strings and return // result as a third string static String addBinary(String a, String b) { //If the inputs are 0 if(a.charAt(0) == '0' && b.charAt(0) == '0'){ return \"0\"; } // Initialize result StringBuilder result = new StringBuilder(\"\"); // Initialize digit sum int s = 0; // Traverse both strings starting // from last characters int i = a.length() - 1, j = b.length() - 1; while (i >= 0 || j >= 0 || s == 1) { // Comput sum of last // digits and carry s += ((i >= 0)? a.charAt(i) - '0': 0); s += ((j >= 0)? b.charAt(j) - '0': 0); // If current digit sum is // 1 or 3, add 1 to result result.append((char)(s % 2 + '0')); // Compute carry s /= 2; // Move to next digits i--; j--; } // Remove leading zeros, if any int start = result.length()-1; while(start >=0 && result.charAt(start) == '0') { start--; } if(start != result.length()-1) { result.delete(start+1,result.length()); } return result.reverse().toString(); } //Driver code public static void main(String args[]) { String a = \"1101\", b=\"100\"; System.out.print(addBinary(a, b)); }} // This code is contributed by Sam007.", "e": 4282, "s": 2673, "text": null }, { "code": "# Python Solution for above problem: # This function adds two binary# strings return the resulting stringdef add_binary_nums(x, y): max_len = max(len(x), len(y)) x = x.zfill(max_len) y = y.zfill(max_len) # initialize the result result = '' # initialize the carry carry = 0 # Traverse the string for i in range(max_len - 1, -1, -1): r = carry r += 1 if x[i] == '1' else 0 r += 1 if y[i] == '1' else 0 result = ('1' if r % 2 == 1 else '0') + result carry = 0 if r < 2 else 1 # Compute the carry. if carry !=0 : result = '1' + result return result.zfill(max_len) # Driver codeprint(add_binary_nums('1101', '100')) # This code is contributed# by Anand Khatri", "e": 5103, "s": 4282, "text": null }, { "code": "// C# program to add// two binary stringsusing System; class GFG { // This function adds two // binary strings and return // result as a third string static string addBinary(string a, string b) { // Initialize result string result = \"\"; // Initialize digit sum int s = 0; // Traverse both strings starting // from last characters int i = a.Length - 1, j = b.Length - 1; while (i >= 0 || j >= 0 || s == 1) { // Comput sum of last // digits and carry s += ((i >= 0)? a[i] - '0': 0); s += ((j >= 0)? b[j] - '0': 0); // If current digit sum is // 1 or 3, add 1 to result result = (char)(s % 2 + '0') + result; // Compute carry s /= 2; // Move to next digits i--; j--; } return result; } // Driver Code public static void Main(){ string a = \"1101\", b=\"100\"; Console.Write( addBinary(a, b));}} // This code is contributed by Sam007", "e": 6228, "s": 5103, "text": null }, { "code": "<?php// PHP program to add two binary strings // This function adds two binary strings// and return result as a third stringfunction addBinary($a, $b){ $result = \"\"; // Initialize result $s = 0; // Initialize digit sum // Traverse both strings starting // from last characters $i = strlen($a) - 1; $j = strlen($b) - 1; while ($i >= 0 || $j >= 0 || $s == 1) { // Comput sum of last digits and carry $s += (($i >= 0)? ord($a[$i]) - ord('0'): 0); $s += (($j >= 0)? ord($b[$j]) - ord('0'): 0); // If current digit sum is 1 or 3, // add 1 to result $result = chr($s % 2 + ord('0')) . $result; // Compute carry $s = (int)($s / 2); // Move to next digits $i--; $j--; } return $result;} // Driver Code$a = \"1101\";$b = \"100\";echo addBinary($a, $b); // This code is contributed by mits?>", "e": 7164, "s": 6228, "text": null }, { "code": "<script> // Javascript program to add// two binary strings // This function adds two// binary strings and return// result as a third stringfunction addBinary(a, b){ // Initialize result var result = \"\"; // Initialize digit sum var s = 0; // Traverse both strings starting // from last characters var i = a.length - 1, j = b.length - 1; while (i >= 0 || j >= 0 || s == 1) { // Comput sum of last // digits and carry s += ((i >= 0)? a.charAt(i).charCodeAt(0) - '0'.charCodeAt(0): 0); s += ((j >= 0)? b.charAt(j).charCodeAt(0) - '0'.charCodeAt(0): 0); // If current digit sum is // 1 or 3, add 1 to result result = String.fromCharCode(parseInt(s % 2) + '0'.charCodeAt(0)) + result; // Compute carry s = parseInt(s/2); // Move to next digits i--; j--; } return result;} //Driver codevar a = \"1101\", b=\"100\"; document.write(addBinary(a, b)); // This code is contributed by Amit Katiyar </script>", "e": 8218, "s": 7164, "text": null }, { "code": null, "e": 8224, "s": 8218, "text": "10001" }, { "code": null, "e": 8421, "s": 8224, "text": "Time Complexity: O(max(L1, L2)), where L1 and L2 are the lengths of strings a and b respectively. Auxiliary Space: O(max(L1, L2)), where L1 and L2 are the lengths of strings a and b respectively. " }, { "code": null, "e": 9283, "s": 8421, "text": "Add two binary strings | GeeksforGeeks - YouTubeGeeksforGeeks529K subscribersAdd two binary strings | 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 / 1:54•Live•<div class=\"player-unavailable\"><h1 class=\"message\">An error occurred.</h1><div class=\"submessage\"><a href=\"https://www.youtube.com/watch?v=TraAvM7JxL4\" 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": 9290, "s": 9283, "text": "Sam007" }, { "code": null, "e": 9302, "s": 9290, "text": "anandkhatri" }, { "code": null, "e": 9315, "s": 9302, "text": "Mithun Kumar" }, { "code": null, "e": 9329, "s": 9315, "text": "shubham_singh" }, { "code": null, "e": 9342, "s": 9329, "text": "Akanksha_Rai" }, { "code": null, "e": 9357, "s": 9342, "text": "amit143katiyar" }, { "code": null, "e": 9372, "s": 9357, "text": "adityakumar129" }, { "code": null, "e": 9389, "s": 9372, "text": "rupeswarofficial" }, { "code": null, "e": 9403, "s": 9389, "text": "sumitgumber28" }, { "code": null, "e": 9412, "s": 9403, "text": "sweetyty" }, { "code": null, "e": 9425, "s": 9412, "text": "ankita_saini" }, { "code": null, "e": 9440, "s": 9425, "text": "shivamanandrj9" }, { "code": null, "e": 9457, "s": 9440, "text": "hardikkoriintern" }, { "code": null, "e": 9472, "s": 9457, "text": "sepidehfallah2" }, { "code": null, "e": 9481, "s": 9472, "text": "Facebook" }, { "code": null, "e": 9491, "s": 9481, "text": "Microsoft" }, { "code": null, "e": 9504, "s": 9491, "text": "Mathematical" }, { "code": null, "e": 9512, "s": 9504, "text": "Strings" }, { "code": null, "e": 9522, "s": 9512, "text": "Microsoft" }, { "code": null, "e": 9531, "s": 9522, "text": "Facebook" }, { "code": null, "e": 9539, "s": 9531, "text": "Strings" }, { "code": null, "e": 9552, "s": 9539, "text": "Mathematical" }, { "code": null, "e": 9650, "s": 9552, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 9674, "s": 9650, "text": "Merge two sorted arrays" }, { "code": null, "e": 9695, "s": 9674, "text": "Operators in C / C++" }, { "code": null, "e": 9717, "s": 9695, "text": "Sieve of Eratosthenes" }, { "code": null, "e": 9731, "s": 9717, "text": "Prime Numbers" }, { "code": null, "e": 9773, "s": 9731, "text": "Program to find GCD or HCF of two numbers" }, { "code": null, "e": 9819, "s": 9773, "text": "Write a program to reverse an array or string" }, { "code": null, "e": 9844, "s": 9819, "text": "Reverse a string in Java" }, { "code": null, "e": 9919, "s": 9844, "text": "Check for Balanced Brackets in an expression (well-formedness) using Stack" }, { "code": null, "e": 9964, "s": 9919, "text": "Different Methods to Reverse a String in C++" } ]
HIVE Overview
03 Oct, 2019 From the beginning of the Internet’s conventional breakout, many search engine provider companies and e-commerce companies/organizations struggled with regular growth in data day by day. Even some social networking sites like Facebook, Twitter, Instagram, etc. also undergo the same problem. Today, numerous associations understand that the information they gather is a profitable asset for understanding their customers, the impact of their activities in the market, their performance and the effectiveness of their infrastructure, etc. So this is where Hadoop emerged as a preserver which provide us with an efficient way to handle huge datasets using HDFS(Hadoop Distributed File System) and imposes MapReduce for separating calculation errands into units that can be dispersed around a cluster of hardware(commodity hardware) providing scalability(horizontal).Some big challenges need to be resolved like: How would someone move existing data structure to Hadoop when that framework depends on Relational database system and the Structured Query Language (SQL)? And what about data security, where both master database creators, and admins, and some regular users who use SQL to take information from their data warehouse?This where the role of HIVE comes into the picture. Hive provides a SQL dialect known as Hive Query Language abbreviated as HQL to retrieve or modify the data. which is stored in the Hadoop. Apache Hive is an open-source data warehouse system built on top of Hadoop Cluster for querying and analyzing large datasets stored in the Hadoop distributed file system. HiveQL automatically converts SQL-like queries into MapReduce jobs. The HIVE is developed by the Data Infrastructure team of Facebook. At Facebook, Hive’s Hadoop cluster is capable to store more than 2 Petabytes of raw data, and daily it processes and loads around 15 Terabytes of data. Now it is being used by many companies also. Later, the Apache Foundation took over Hive and developed it further and made it an Open Source. It is also used and developed by other companies like Netflix, Financial Industry Regulatory Authority (FINRA), etc. Hive is a declarative SQL based language, mainly used for data analysis and creating reports. Hive operates on the server-side of a cluster.Hive provides schema flexibility and evolution along with data summarization, querying of data, and analysis in a much easier manner.In Hive, we can make two types of tables – partitioned and bucketed which make it feasible to process data stored in HDFS and improves the performance as well.Hive tables are defined directly in the Hadoop File System(HDFS).In Hive, we have JDBC/ODBC driversHive is fast and scalable, and easy to learn.Hive has a rule-based optimizer for optimizing plans.Using Hive we can also execute Ad-hoc queries to analyze data. METASTORE – It is used to store metadata of tables schema, time of creation, location, etc. It also provides metadata partition to help the driver to keep the track of the progress of various datasets distributed over the cluster. The metadata helps the driver to keep track of the data and it is crucial. Hence, a backup server regularly replicates the data which can be retrieved in case of data loss. DRIVER – It acts as a controller. The driver starts the execution of the statement by creating sessions and monitors the life cycle and progress of execution. It also stores metadata generated during the execution of an HQL query. COMPILER – It is used to compile a Hive query, which converts the query to an execution plan. This plan contains the tasks and steps needed to be performed by the Hadoop MapReduce to get the output as translated by the query. OPTIMIZER – It optimizes and performs transformations on an execution plan to get an optimized Directed Acyclic Graph abbreviated as DAG. Transformation such as converting a pipeline of joins to a single join, and splitting the tasks, such as applying a transformation on data before a reduce operation, to provide better performance and scalability. EXECUTOR – It executes tasks after compilation and optimization have been done. It interacts with the job tracker of Hadoop to schedule tasks to be run. It takes care of pipelining the tasks by making sure that a task with dependency gets executed only if all other prerequisites are run. CLI, UI, and Thrift Server – It is used to provide a user interface to an external user to interact with Hive by writing queries, instructions and monitoring the process. Thrift server allows external clients to interact with Hive over a network, similar to the JDBC or ODBC protocol. First of all, the user submits their query and CLI sends that query to the Driver.Then the driver takes the help of query compiler to check syntax.Then compiler request for Metadata by sending a metadata request to Metastore.In response to that request, metastore sends metadata to the compiler.Then compiler resends the plan to the driver after checking requirements.The Driver sends the plan to the execution engine.Execution engine sends the job to Job tracker and assigns the job to Task Tracker. Here, the query executes MapReduce job. And in meantime execution engine executes metadata operations with Metastore.Then the execution engine fetches the results from the Data Node and sends those results to the driver.At last, the driver sends the results to the hive interface. First of all, the user submits their query and CLI sends that query to the Driver. Then the driver takes the help of query compiler to check syntax. Then compiler request for Metadata by sending a metadata request to Metastore. In response to that request, metastore sends metadata to the compiler. Then compiler resends the plan to the driver after checking requirements. The Driver sends the plan to the execution engine. Execution engine sends the job to Job tracker and assigns the job to Task Tracker. Here, the query executes MapReduce job. And in meantime execution engine executes metadata operations with Metastore. Then the execution engine fetches the results from the Data Node and sends those results to the driver. At last, the driver sends the results to the hive interface. Hive Metastore is the central repository for metadata. It stores metadata for Hive tables (like their schema and location) and partitions in a relational database. It provides client access to this information by using the metastore service API.Modes: Embedded: In Hive by default, metastore service and hive services run in the same JVM. In this mode, Data in the local file system are stored using the embedded derby database. Local: Hive is a SQL based framework, that should have multiple sessions. In Local mode, multiple Hive sessions are allowed. This can be achieved by using any JDBC application like MySQL that runs in a separate JVM. Remote: In this mode, metastore and hive services run in a separate JVM. Thrift network APIs are used by different processes to communicate among them. HIVE APIsHive APIs are exposed for the developers who are want to integrate their applications and framework with Hive ecosystem. Here are some of the APIs- HCatalog CLI (Command Based) – It is a query-based API which means that it only permits execution and submission of HQL.Metastore (JAVA) – It is a Thrift based API which is implemented by IMetaStoreClient interface using JAVA. This API decouples metastore storage layer from Hive Internals.Streaming Data Ingest (JAVA) – It is used to write the continuous streaming data into transactional tables using ACID properties of Hive.Streaming Mutation (JAVA) – It is used in transformational operations like Update, Insert, Delete to convert it into transactional tables as well using ACID property.Hive-JDBC ( JDBC) – It is used to support the functionality of JDBC in Hive. HCatalog CLI (Command Based) – It is a query-based API which means that it only permits execution and submission of HQL. Metastore (JAVA) – It is a Thrift based API which is implemented by IMetaStoreClient interface using JAVA. This API decouples metastore storage layer from Hive Internals. Streaming Data Ingest (JAVA) – It is used to write the continuous streaming data into transactional tables using ACID properties of Hive. Streaming Mutation (JAVA) – It is used in transformational operations like Update, Insert, Delete to convert it into transactional tables as well using ACID property. Hive-JDBC ( JDBC) – It is used to support the functionality of JDBC in Hive. Limitations –Apache Hive has some limitations also: Read-only views are allowed but materialized views are not allowed.It does not support triggers.Apache Hive queries have very high latency.No difference between NULL and null values. Read-only views are allowed but materialized views are not allowed. It does not support triggers. Apache Hive queries have very high latency. No difference between NULL and null values. How HIVE is different from RDBMS ? RDBMS supports schema on Write whereas Hive provides schema on Read.In Hive, we can write once but in RDBMS we can write as many times as we want.Hive can handle big datasets whereas RDBMS can’t handle beyond 10TB.Hive is highly scalable but scalability in RDBMS costs a lost.Hive has a feature of Bucketing which is not there in RDBMS. RDBMS supports schema on Write whereas Hive provides schema on Read. In Hive, we can write once but in RDBMS we can write as many times as we want. Hive can handle big datasets whereas RDBMS can’t handle beyond 10TB. Hive is highly scalable but scalability in RDBMS costs a lost. Hive has a feature of Bucketing which is not there in RDBMS. Hadoop Hadoop Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Difference Between Hadoop and Spark Architecture of HBase Hadoop Streaming Using Python - Word Count Problem MapReduce Architecture Hive - Load Data Into Table What is Big Data? Hadoop - Different Modes of Operation Applications of Big Data How to Create Table in Hive? Anatomy of File Read and Write in HDFS
[ { "code": null, "e": 28, "s": 0, "text": "\n03 Oct, 2019" }, { "code": null, "e": 1684, "s": 28, "text": "From the beginning of the Internet’s conventional breakout, many search engine provider companies and e-commerce companies/organizations struggled with regular growth in data day by day. Even some social networking sites like Facebook, Twitter, Instagram, etc. also undergo the same problem. Today, numerous associations understand that the information they gather is a profitable asset for understanding their customers, the impact of their activities in the market, their performance and the effectiveness of their infrastructure, etc. So this is where Hadoop emerged as a preserver which provide us with an efficient way to handle huge datasets using HDFS(Hadoop Distributed File System) and imposes MapReduce for separating calculation errands into units that can be dispersed around a cluster of hardware(commodity hardware) providing scalability(horizontal).Some big challenges need to be resolved like: How would someone move existing data structure to Hadoop when that framework depends on Relational database system and the Structured Query Language (SQL)? And what about data security, where both master database creators, and admins, and some regular users who use SQL to take information from their data warehouse?This where the role of HIVE comes into the picture. Hive provides a SQL dialect known as Hive Query Language abbreviated as HQL to retrieve or modify the data. which is stored in the Hadoop. Apache Hive is an open-source data warehouse system built on top of Hadoop Cluster for querying and analyzing large datasets stored in the Hadoop distributed file system. HiveQL automatically converts SQL-like queries into MapReduce jobs." }, { "code": null, "e": 2162, "s": 1684, "text": "The HIVE is developed by the Data Infrastructure team of Facebook. At Facebook, Hive’s Hadoop cluster is capable to store more than 2 Petabytes of raw data, and daily it processes and loads around 15 Terabytes of data. Now it is being used by many companies also. Later, the Apache Foundation took over Hive and developed it further and made it an Open Source. It is also used and developed by other companies like Netflix, Financial Industry Regulatory Authority (FINRA), etc." }, { "code": null, "e": 2854, "s": 2162, "text": "Hive is a declarative SQL based language, mainly used for data analysis and creating reports. Hive operates on the server-side of a cluster.Hive provides schema flexibility and evolution along with data summarization, querying of data, and analysis in a much easier manner.In Hive, we can make two types of tables – partitioned and bucketed which make it feasible to process data stored in HDFS and improves the performance as well.Hive tables are defined directly in the Hadoop File System(HDFS).In Hive, we have JDBC/ODBC driversHive is fast and scalable, and easy to learn.Hive has a rule-based optimizer for optimizing plans.Using Hive we can also execute Ad-hoc queries to analyze data." }, { "code": null, "e": 3258, "s": 2854, "text": "METASTORE – It is used to store metadata of tables schema, time of creation, location, etc. It also provides metadata partition to help the driver to keep the track of the progress of various datasets distributed over the cluster. The metadata helps the driver to keep track of the data and it is crucial. Hence, a backup server regularly replicates the data which can be retrieved in case of data loss." }, { "code": null, "e": 3489, "s": 3258, "text": "DRIVER – It acts as a controller. The driver starts the execution of the statement by creating sessions and monitors the life cycle and progress of execution. It also stores metadata generated during the execution of an HQL query." }, { "code": null, "e": 3715, "s": 3489, "text": "COMPILER – It is used to compile a Hive query, which converts the query to an execution plan. This plan contains the tasks and steps needed to be performed by the Hadoop MapReduce to get the output as translated by the query." }, { "code": null, "e": 4066, "s": 3715, "text": "OPTIMIZER – It optimizes and performs transformations on an execution plan to get an optimized Directed Acyclic Graph abbreviated as DAG. Transformation such as converting a pipeline of joins to a single join, and splitting the tasks, such as applying a transformation on data before a reduce operation, to provide better performance and scalability." }, { "code": null, "e": 4355, "s": 4066, "text": "EXECUTOR – It executes tasks after compilation and optimization have been done. It interacts with the job tracker of Hadoop to schedule tasks to be run. It takes care of pipelining the tasks by making sure that a task with dependency gets executed only if all other prerequisites are run." }, { "code": null, "e": 4640, "s": 4355, "text": "CLI, UI, and Thrift Server – It is used to provide a user interface to an external user to interact with Hive by writing queries, instructions and monitoring the process. Thrift server allows external clients to interact with Hive over a network, similar to the JDBC or ODBC protocol." }, { "code": null, "e": 5422, "s": 4640, "text": "First of all, the user submits their query and CLI sends that query to the Driver.Then the driver takes the help of query compiler to check syntax.Then compiler request for Metadata by sending a metadata request to Metastore.In response to that request, metastore sends metadata to the compiler.Then compiler resends the plan to the driver after checking requirements.The Driver sends the plan to the execution engine.Execution engine sends the job to Job tracker and assigns the job to Task Tracker. Here, the query executes MapReduce job. And in meantime execution engine executes metadata operations with Metastore.Then the execution engine fetches the results from the Data Node and sends those results to the driver.At last, the driver sends the results to the hive interface." }, { "code": null, "e": 5505, "s": 5422, "text": "First of all, the user submits their query and CLI sends that query to the Driver." }, { "code": null, "e": 5571, "s": 5505, "text": "Then the driver takes the help of query compiler to check syntax." }, { "code": null, "e": 5650, "s": 5571, "text": "Then compiler request for Metadata by sending a metadata request to Metastore." }, { "code": null, "e": 5721, "s": 5650, "text": "In response to that request, metastore sends metadata to the compiler." }, { "code": null, "e": 5795, "s": 5721, "text": "Then compiler resends the plan to the driver after checking requirements." }, { "code": null, "e": 5846, "s": 5795, "text": "The Driver sends the plan to the execution engine." }, { "code": null, "e": 6047, "s": 5846, "text": "Execution engine sends the job to Job tracker and assigns the job to Task Tracker. Here, the query executes MapReduce job. And in meantime execution engine executes metadata operations with Metastore." }, { "code": null, "e": 6151, "s": 6047, "text": "Then the execution engine fetches the results from the Data Node and sends those results to the driver." }, { "code": null, "e": 6212, "s": 6151, "text": "At last, the driver sends the results to the hive interface." }, { "code": null, "e": 6466, "s": 6214, "text": "Hive Metastore is the central repository for metadata. It stores metadata for Hive tables (like their schema and location) and partitions in a relational database. It provides client access to this information by using the metastore service API.Modes:" }, { "code": null, "e": 6643, "s": 6466, "text": "Embedded: In Hive by default, metastore service and hive services run in the same JVM. In this mode, Data in the local file system are stored using the embedded derby database." }, { "code": null, "e": 6859, "s": 6643, "text": "Local: Hive is a SQL based framework, that should have multiple sessions. In Local mode, multiple Hive sessions are allowed. This can be achieved by using any JDBC application like MySQL that runs in a separate JVM." }, { "code": null, "e": 7011, "s": 6859, "text": "Remote: In this mode, metastore and hive services run in a separate JVM. Thrift network APIs are used by different processes to communicate among them." }, { "code": null, "e": 7168, "s": 7011, "text": "HIVE APIsHive APIs are exposed for the developers who are want to integrate their applications and framework with Hive ecosystem. Here are some of the APIs-" }, { "code": null, "e": 7838, "s": 7168, "text": "HCatalog CLI (Command Based) – It is a query-based API which means that it only permits execution and submission of HQL.Metastore (JAVA) – It is a Thrift based API which is implemented by IMetaStoreClient interface using JAVA. This API decouples metastore storage layer from Hive Internals.Streaming Data Ingest (JAVA) – It is used to write the continuous streaming data into transactional tables using ACID properties of Hive.Streaming Mutation (JAVA) – It is used in transformational operations like Update, Insert, Delete to convert it into transactional tables as well using ACID property.Hive-JDBC ( JDBC) – It is used to support the functionality of JDBC in Hive." }, { "code": null, "e": 7959, "s": 7838, "text": "HCatalog CLI (Command Based) – It is a query-based API which means that it only permits execution and submission of HQL." }, { "code": null, "e": 8130, "s": 7959, "text": "Metastore (JAVA) – It is a Thrift based API which is implemented by IMetaStoreClient interface using JAVA. This API decouples metastore storage layer from Hive Internals." }, { "code": null, "e": 8268, "s": 8130, "text": "Streaming Data Ingest (JAVA) – It is used to write the continuous streaming data into transactional tables using ACID properties of Hive." }, { "code": null, "e": 8435, "s": 8268, "text": "Streaming Mutation (JAVA) – It is used in transformational operations like Update, Insert, Delete to convert it into transactional tables as well using ACID property." }, { "code": null, "e": 8512, "s": 8435, "text": "Hive-JDBC ( JDBC) – It is used to support the functionality of JDBC in Hive." }, { "code": null, "e": 8565, "s": 8512, "text": " Limitations –Apache Hive has some limitations also:" }, { "code": null, "e": 8748, "s": 8565, "text": "Read-only views are allowed but materialized views are not allowed.It does not support triggers.Apache Hive queries have very high latency.No difference between NULL and null values." }, { "code": null, "e": 8816, "s": 8748, "text": "Read-only views are allowed but materialized views are not allowed." }, { "code": null, "e": 8846, "s": 8816, "text": "It does not support triggers." }, { "code": null, "e": 8890, "s": 8846, "text": "Apache Hive queries have very high latency." }, { "code": null, "e": 8934, "s": 8890, "text": "No difference between NULL and null values." }, { "code": null, "e": 8970, "s": 8934, "text": " How HIVE is different from RDBMS ?" }, { "code": null, "e": 9307, "s": 8970, "text": "RDBMS supports schema on Write whereas Hive provides schema on Read.In Hive, we can write once but in RDBMS we can write as many times as we want.Hive can handle big datasets whereas RDBMS can’t handle beyond 10TB.Hive is highly scalable but scalability in RDBMS costs a lost.Hive has a feature of Bucketing which is not there in RDBMS." }, { "code": null, "e": 9376, "s": 9307, "text": "RDBMS supports schema on Write whereas Hive provides schema on Read." }, { "code": null, "e": 9455, "s": 9376, "text": "In Hive, we can write once but in RDBMS we can write as many times as we want." }, { "code": null, "e": 9524, "s": 9455, "text": "Hive can handle big datasets whereas RDBMS can’t handle beyond 10TB." }, { "code": null, "e": 9587, "s": 9524, "text": "Hive is highly scalable but scalability in RDBMS costs a lost." }, { "code": null, "e": 9648, "s": 9587, "text": "Hive has a feature of Bucketing which is not there in RDBMS." }, { "code": null, "e": 9655, "s": 9648, "text": "Hadoop" }, { "code": null, "e": 9662, "s": 9655, "text": "Hadoop" }, { "code": null, "e": 9760, "s": 9662, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 9796, "s": 9760, "text": "Difference Between Hadoop and Spark" }, { "code": null, "e": 9818, "s": 9796, "text": "Architecture of HBase" }, { "code": null, "e": 9869, "s": 9818, "text": "Hadoop Streaming Using Python - Word Count Problem" }, { "code": null, "e": 9892, "s": 9869, "text": "MapReduce Architecture" }, { "code": null, "e": 9920, "s": 9892, "text": "Hive - Load Data Into Table" }, { "code": null, "e": 9938, "s": 9920, "text": "What is Big Data?" }, { "code": null, "e": 9976, "s": 9938, "text": "Hadoop - Different Modes of Operation" }, { "code": null, "e": 10001, "s": 9976, "text": "Applications of Big Data" }, { "code": null, "e": 10030, "s": 10001, "text": "How to Create Table in Hive?" } ]
PostgreSQL – Temporary Table
28 Aug, 2020 A temporary table, as the name implies, is a short-lived table that exists for the duration of a database session. PostgreSQL automatically drops the temporary tables at the end of a session or a transaction. Syntax: CREATE TEMPORARY TABLE temp_table( ... ); or, CREATE TEMP TABLE temp_table( ... ); A temporary table is visible only to the session that creates it. In other words, it remains invisible to other sessions. Example: First, we create a new database test as follows: CREATE DATABASE test; Next, create a temporary table named mytemp as follows: CREATE TEMP TABLE mytemp(c INT); Then, launch another session that connects to the test database and query data from the mytemp table: SELECT * FROM mytemp; It will raise an error as the second session cannot see mytemp table. So, quit all sessions after that as follows: \q Finally, login to the database server again and query data from the mytemp table: SELECT * FROM mytemp; The mytemp table does not exist because it has been dropped automatically when the session ended, therefore, PostgreSQL issued an error. Output: postgreSQL-managing-table PostgreSQL Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n28 Aug, 2020" }, { "code": null, "e": 237, "s": 28, "text": "A temporary table, as the name implies, is a short-lived table that exists for the duration of a database session. PostgreSQL automatically drops the temporary tables at the end of a session or a transaction." }, { "code": null, "e": 336, "s": 237, "text": "Syntax:\nCREATE TEMPORARY TABLE temp_table(\n ...\n);\n\nor,\n\nCREATE TEMP TABLE temp_table(\n ...\n);" }, { "code": null, "e": 458, "s": 336, "text": "A temporary table is visible only to the session that creates it. In other words, it remains invisible to other sessions." }, { "code": null, "e": 467, "s": 458, "text": "Example:" }, { "code": null, "e": 516, "s": 467, "text": "First, we create a new database test as follows:" }, { "code": null, "e": 538, "s": 516, "text": "CREATE DATABASE test;" }, { "code": null, "e": 594, "s": 538, "text": "Next, create a temporary table named mytemp as follows:" }, { "code": null, "e": 627, "s": 594, "text": "CREATE TEMP TABLE mytemp(c INT);" }, { "code": null, "e": 729, "s": 627, "text": "Then, launch another session that connects to the test database and query data from the mytemp table:" }, { "code": null, "e": 751, "s": 729, "text": "SELECT * FROM mytemp;" }, { "code": null, "e": 866, "s": 751, "text": "It will raise an error as the second session cannot see mytemp table. So, quit all sessions after that as follows:" }, { "code": null, "e": 869, "s": 866, "text": "\\q" }, { "code": null, "e": 951, "s": 869, "text": "Finally, login to the database server again and query data from the mytemp table:" }, { "code": null, "e": 973, "s": 951, "text": "SELECT * FROM mytemp;" }, { "code": null, "e": 1110, "s": 973, "text": "The mytemp table does not exist because it has been dropped automatically when the session ended, therefore, PostgreSQL issued an error." }, { "code": null, "e": 1118, "s": 1110, "text": "Output:" }, { "code": null, "e": 1144, "s": 1118, "text": "postgreSQL-managing-table" }, { "code": null, "e": 1155, "s": 1144, "text": "PostgreSQL" } ]
Python | os.pipe() method
29 Jul, 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. All functions in os module raise OSError in the case of invalid or inaccessible file names and paths, or other arguments that have the correct type but are not accepted by the operating system. os.pipe() method in Python is used to create a pipe. A pipe is a method to pass information from one process to another process. It offers only one-way communication and the passed information is held by the system until it is read by the receiving process. Syntax: os.pipe() Parameter: No parameter is required Return Type: This method returns a pair of file descriptors (r, w) usable for reading and writing, respectively. # Python program to explain os.pipe() method # importing os module import os # Create a piper, w = os.pipe() # The returned file descriptor r and w# can be used for reading and# writing respectively. # We will create a child process# and using these file descriptor# the parent process will write # some text and child process will# read the text written by the parent process # Create a child processpid = os.fork() # pid greater than 0 represents# the parent processif pid > 0: # This is the parent process # Closes file descriptor r os.close(r) # Write some text to file descriptor w print("Parent process is writing") text = b"Hello child process" os.write(w, text) print("Written text:", text.decode()) else: # This is the parent process # Closes file descriptor w os.close(w) # Read the text written by parent process print("\nChild Process is reading") r = os.fdopen(r) print("Read text:", r.read()) Parent process is writing Text written: Hello child process Child Process is reading Text read: Hello child process shubham_singh python-os-module Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n29 Jul, 2019" }, { "code": null, "e": 247, "s": 28, "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." }, { "code": null, "e": 441, "s": 247, "text": "All functions in os module raise OSError in the case of invalid or inaccessible file names and paths, or other arguments that have the correct type but are not accepted by the operating system." }, { "code": null, "e": 699, "s": 441, "text": "os.pipe() method in Python is used to create a pipe. A pipe is a method to pass information from one process to another process. It offers only one-way communication and the passed information is held by the system until it is read by the receiving process." }, { "code": null, "e": 717, "s": 699, "text": "Syntax: os.pipe()" }, { "code": null, "e": 753, "s": 717, "text": "Parameter: No parameter is required" }, { "code": null, "e": 866, "s": 753, "text": "Return Type: This method returns a pair of file descriptors (r, w) usable for reading and writing, respectively." }, { "code": "# Python program to explain os.pipe() method # importing os module import os # Create a piper, w = os.pipe() # The returned file descriptor r and w# can be used for reading and# writing respectively. # We will create a child process# and using these file descriptor# the parent process will write # some text and child process will# read the text written by the parent process # Create a child processpid = os.fork() # pid greater than 0 represents# the parent processif pid > 0: # This is the parent process # Closes file descriptor r os.close(r) # Write some text to file descriptor w print(\"Parent process is writing\") text = b\"Hello child process\" os.write(w, text) print(\"Written text:\", text.decode()) else: # This is the parent process # Closes file descriptor w os.close(w) # Read the text written by parent process print(\"\\nChild Process is reading\") r = os.fdopen(r) print(\"Read text:\", r.read())", "e": 1845, "s": 866, "text": null }, { "code": null, "e": 1963, "s": 1845, "text": "Parent process is writing\nText written: Hello child process\n\nChild Process is reading\nText read: Hello child process\n" }, { "code": null, "e": 1977, "s": 1963, "text": "shubham_singh" }, { "code": null, "e": 1994, "s": 1977, "text": "python-os-module" }, { "code": null, "e": 2001, "s": 1994, "text": "Python" } ]
Extending a Class in Scala
29 Mar, 2019 Extending a class in Scala user can design an inherited class. To extend a class in Scala we use extends keyword. there are two restrictions to extend a class in Scala : To override method in scala override keyword is required. Only the primary constructor can pass parameters to the base constructor. Syntax: class base_class_name extends derived_class_name { // Methods and fields } Example: // Scala program of extending a class // Base class class Geeks1{ var Name: String = "chaitanyashah"} // Derived class // Using extends keyword class Geeks2 extends Geeks1{ var Article_no: Int = 30 // Method def details() { println("Author name: " + Name); println("Total numbers of articles: " + Article_no); } } // Creating objectobject GFG { // Driver code def main(args: Array[String]) { // Creating object of derived class val ob = new Geeks2(); ob.details(); } } Output: Author name: chaitanyashah Total numbers of articles: 30 In the above example Geeks1 is the base class and Geeks2 is the derived class which is derived from Geeks1 using extends keyword. In the main method when we create the object of Geeks2 class, a copy of all the methods and fields of the base class acquires memory in this object. That is why by using the object of the derived class we can also access the members of the base class. Example: // Scala program of extending a class // Base classclass Parent { var Name1: String = "geek1" var Name2: String = "geek2"} // Derived from the parent class class Child1 extends Parent { var Age: Int = 32 def details1() { println(" Name: " + Name1) println(" Age: " + Age) } } // Derived from Parent class class Child2 extends Parent { var Height: Int = 164 // Method def details2() { println(" Name: " + Name2) println(" Height: " + Height) } } // Creating objectobject GFG { // Driver code def main(args: Array[String]) { // Creating objects of both derived classes val ob1 = new Child1(); val ob2 = new Child2(); ob1.details1(); ob2.details2(); } } Output: Name: geek1 Age: 32 Name: geek2 Height: 164 In the above example Parent is the base class Child1 and Child2 are the derived class which is derived from Parent using extends keyword. In the main method when we create the objects of Child1 and Child2 class a copy of all the methods and fields of the base class acquires memory in this object.Example: // Scala program of extending a class // Base classclass Bicycle (val gearVal:Int, val speedVal: Int){ // the Bicycle class has two fields var gear: Int = gearVal var speed: Int = speedVal // the Bicycle class has two methods def applyBreak(decrement: Int) { gear = gear - decrement println("new gear value: " + gear); } def speedUp(increment: Int) { speed = speed + increment; println("new speed value: " + speed); }} // Derived classclass MountainBike(override val gearVal: Int, override val speedVal: Int, val startHeightVal : Int) extends Bicycle(gearVal, speedVal){ // the MountainBike subclass adds one more field var startHeight: Int = startHeightVal // the MountainBike subclass adds one more method def addHeight(newVal: Int) { startHeight = startHeight + newVal println("new startHeight : " + startHeight); }} // Creating objectobject GFG { // Main method def main(args: Array[String]) { val bike = new MountainBike(10, 20, 15); bike.addHeight(10); bike.speedUp(5); bike.applyBreak(5); }} Output: new startHeight : 25 new speed value: 25 new gear value: 5 In above program, when an object of MountainBike class is created, a copy of the all methods and fields of the superclass acquire memory in this object. Picked Scala Scala-OOPS Scala Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n29 Mar, 2019" }, { "code": null, "e": 198, "s": 28, "text": "Extending a class in Scala user can design an inherited class. To extend a class in Scala we use extends keyword. there are two restrictions to extend a class in Scala :" }, { "code": null, "e": 256, "s": 198, "text": "To override method in scala override keyword is required." }, { "code": null, "e": 330, "s": 256, "text": "Only the primary constructor can pass parameters to the base constructor." }, { "code": null, "e": 338, "s": 330, "text": "Syntax:" }, { "code": null, "e": 418, "s": 338, "text": "class base_class_name extends derived_class_name\n{\n // Methods and fields\n}\n" }, { "code": null, "e": 427, "s": 418, "text": "Example:" }, { "code": "// Scala program of extending a class // Base class class Geeks1{ var Name: String = \"chaitanyashah\"} // Derived class // Using extends keyword class Geeks2 extends Geeks1{ var Article_no: Int = 30 // Method def details() { println(\"Author name: \" + Name); println(\"Total numbers of articles: \" + Article_no); } } // Creating objectobject GFG { // Driver code def main(args: Array[String]) { // Creating object of derived class val ob = new Geeks2(); ob.details(); } } ", "e": 1003, "s": 427, "text": null }, { "code": null, "e": 1011, "s": 1003, "text": "Output:" }, { "code": null, "e": 1069, "s": 1011, "text": "Author name: chaitanyashah\nTotal numbers of articles: 30\n" }, { "code": null, "e": 1451, "s": 1069, "text": "In the above example Geeks1 is the base class and Geeks2 is the derived class which is derived from Geeks1 using extends keyword. In the main method when we create the object of Geeks2 class, a copy of all the methods and fields of the base class acquires memory in this object. That is why by using the object of the derived class we can also access the members of the base class." }, { "code": null, "e": 1460, "s": 1451, "text": "Example:" }, { "code": "// Scala program of extending a class // Base classclass Parent { var Name1: String = \"geek1\" var Name2: String = \"geek2\"} // Derived from the parent class class Child1 extends Parent { var Age: Int = 32 def details1() { println(\" Name: \" + Name1) println(\" Age: \" + Age) } } // Derived from Parent class class Child2 extends Parent { var Height: Int = 164 // Method def details2() { println(\" Name: \" + Name2) println(\" Height: \" + Height) } } // Creating objectobject GFG { // Driver code def main(args: Array[String]) { // Creating objects of both derived classes val ob1 = new Child1(); val ob2 = new Child2(); ob1.details1(); ob2.details2(); } } ", "e": 2270, "s": 1460, "text": null }, { "code": null, "e": 2278, "s": 2270, "text": "Output:" }, { "code": null, "e": 2323, "s": 2278, "text": "Name: geek1\nAge: 32\nName: geek2\nHeight: 164\n" }, { "code": null, "e": 2629, "s": 2323, "text": "In the above example Parent is the base class Child1 and Child2 are the derived class which is derived from Parent using extends keyword. In the main method when we create the objects of Child1 and Child2 class a copy of all the methods and fields of the base class acquires memory in this object.Example:" }, { "code": "// Scala program of extending a class // Base classclass Bicycle (val gearVal:Int, val speedVal: Int){ // the Bicycle class has two fields var gear: Int = gearVal var speed: Int = speedVal // the Bicycle class has two methods def applyBreak(decrement: Int) { gear = gear - decrement println(\"new gear value: \" + gear); } def speedUp(increment: Int) { speed = speed + increment; println(\"new speed value: \" + speed); }} // Derived classclass MountainBike(override val gearVal: Int, override val speedVal: Int, val startHeightVal : Int) extends Bicycle(gearVal, speedVal){ // the MountainBike subclass adds one more field var startHeight: Int = startHeightVal // the MountainBike subclass adds one more method def addHeight(newVal: Int) { startHeight = startHeight + newVal println(\"new startHeight : \" + startHeight); }} // Creating objectobject GFG { // Main method def main(args: Array[String]) { val bike = new MountainBike(10, 20, 15); bike.addHeight(10); bike.speedUp(5); bike.applyBreak(5); }}", "e": 3817, "s": 2629, "text": null }, { "code": null, "e": 3825, "s": 3817, "text": "Output:" }, { "code": null, "e": 3885, "s": 3825, "text": "new startHeight : 25\nnew speed value: 25\nnew gear value: 5\n" }, { "code": null, "e": 4038, "s": 3885, "text": "In above program, when an object of MountainBike class is created, a copy of the all methods and fields of the superclass acquire memory in this object." }, { "code": null, "e": 4045, "s": 4038, "text": "Picked" }, { "code": null, "e": 4051, "s": 4045, "text": "Scala" }, { "code": null, "e": 4062, "s": 4051, "text": "Scala-OOPS" }, { "code": null, "e": 4068, "s": 4062, "text": "Scala" } ]
How to divide text into two columns layout using CSS ?
01 Sep, 2020 The purpose of this article is to divide the text into two columns by using the CSS column property. This property is used to set the number of columns and the width of these columns. Syntax: columns: column-width columns-count | auto | initial | inherit; Example: HTML <!DOCTYPE html><html> <head> <style> body { text-align: center; color: green; } .GFG { -webkit-columns: 40px 2; /* Chrome, Safari, Opera */ -moz-columns: 60px 2; /* Firefox */ columns: 60px 2; } </style></head> <body> <h1> How to divide the text in the division element into two columns using css? </h1> <div class="GFG"> <h2>Welcome to the world of Geeks!!</h2> 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. <p> <strong>Our team includes:</strong> <p> Sandeep Jain: 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. </p> <p> Vaibhav Bajpai: Amazed by computer science, he is a technology enthusiast who enjoys being a part of a development. Off from work, you canfind him in love with movies, food, and friends. </p> <p> Shikhar Goel: A Computer Science graduate who likes to make things simpler. When he's not working, you can find him surfing the web, learning facts, tricks and life hacks. He also enjoys movies in his leisure time. </p> <p> Dharmesh Singh: A software developer who is always trying to push boundaries in search of great breakthroughs. Off from his desk, you can find him cheering up his buddies and enjoying life. </p> <p> Shubham Baranwal: A passionate developer who always tries to learn new technology and software. In his free time, either he reads some articles or learns some other stuff. </p> </div></body> </html> Output: Supported Browsers are listed below: Google Chrome 43.0 Internet Explorer 10.0 Firefox 16.0 Opera 30.0 Safari 9.0 CSS-Misc HTML-Misc CSS HTML Web Technologies Web technologies Questions HTML Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n01 Sep, 2020" }, { "code": null, "e": 212, "s": 28, "text": "The purpose of this article is to divide the text into two columns by using the CSS column property. This property is used to set the number of columns and the width of these columns." }, { "code": null, "e": 220, "s": 212, "text": "Syntax:" }, { "code": null, "e": 284, "s": 220, "text": "columns: column-width columns-count | auto | initial | inherit;" }, { "code": null, "e": 293, "s": 284, "text": "Example:" }, { "code": null, "e": 298, "s": 293, "text": "HTML" }, { "code": " <!DOCTYPE html><html> <head> <style> body { text-align: center; color: green; } .GFG { -webkit-columns: 40px 2; /* Chrome, Safari, Opera */ -moz-columns: 60px 2; /* Firefox */ columns: 60px 2; } </style></head> <body> <h1> How to divide the text in the division element into two columns using css? </h1> <div class=\"GFG\"> <h2>Welcome to the world of Geeks!!</h2> 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. <p> <strong>Our team includes:</strong> <p> Sandeep Jain: 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. </p> <p> Vaibhav Bajpai: Amazed by computer science, he is a technology enthusiast who enjoys being a part of a development. Off from work, you canfind him in love with movies, food, and friends. </p> <p> Shikhar Goel: A Computer Science graduate who likes to make things simpler. When he's not working, you can find him surfing the web, learning facts, tricks and life hacks. He also enjoys movies in his leisure time. </p> <p> Dharmesh Singh: A software developer who is always trying to push boundaries in search of great breakthroughs. Off from his desk, you can find him cheering up his buddies and enjoying life. </p> <p> Shubham Baranwal: A passionate developer who always tries to learn new technology and software. In his free time, either he reads some articles or learns some other stuff. </p> </div></body> </html> ", "e": 2684, "s": 298, "text": null }, { "code": null, "e": 2692, "s": 2684, "text": "Output:" }, { "code": null, "e": 2729, "s": 2692, "text": "Supported Browsers are listed below:" }, { "code": null, "e": 2748, "s": 2729, "text": "Google Chrome 43.0" }, { "code": null, "e": 2771, "s": 2748, "text": "Internet Explorer 10.0" }, { "code": null, "e": 2784, "s": 2771, "text": "Firefox 16.0" }, { "code": null, "e": 2795, "s": 2784, "text": "Opera 30.0" }, { "code": null, "e": 2806, "s": 2795, "text": "Safari 9.0" }, { "code": null, "e": 2815, "s": 2806, "text": "CSS-Misc" }, { "code": null, "e": 2825, "s": 2815, "text": "HTML-Misc" }, { "code": null, "e": 2829, "s": 2825, "text": "CSS" }, { "code": null, "e": 2834, "s": 2829, "text": "HTML" }, { "code": null, "e": 2851, "s": 2834, "text": "Web Technologies" }, { "code": null, "e": 2878, "s": 2851, "text": "Web technologies Questions" }, { "code": null, "e": 2883, "s": 2878, "text": "HTML" } ]
How to use *ngIf else in AngularJS ?
05 Jun, 2020 Introduction: The ngIf directive is used to show or hide parts of an angular application. It can be added to any tags, it is a normal HTML tag, template, or selectors. It is a structural directive meaning that it includes templates based on a condition constrained to boolean. When the expression evaluates to true it runs/displays the template given in the “then” clause. Or when the expression evaluates to false it displays the template given in the “else” clause. If there is nothing in else clause, it will by default display blank. Syntax: ngIf with an "else" block <div *ngIf="condition; else elseStatement"> when condition is true.</div><ng-template #elseStatement> when condition is false.</ng-template><!--It can be seen that the else clause refers to ng-template, with the label #elseStatement --> It internally creates two <ng-template>, one for “then” statement and another for “else”. So when the condition is true for ngIf, the content of the unlabelled <ng-template> gets displayed. And when false, the labelled <ng-template> runs. Approach: As we know, ngIf else statement works on a variable that has a boolean type. Create an angular app and move to src/app. First, we need to define a variable say “check” in app.component.ts with a value true or false.<!-- Define a variable say "check" with value true/false in app.component.ts -->import { Component } from '@angular/core'; @Component({ selector: 'app-root', templateUrl: './app.component.html', styleUrls: ['./app.component.css']}) export class AppComponent { check:boolean = true;}After defining a variable, move to app.component.html and create two divisions using bootstrap classes. Move into the angular app and write command npm install bootstrap. The first division is for the “true” condition and the one inside <ng-template> is for the false condition. We have declared check to be true so we get a green division saying condition true. If the check was false, a red division saying condition false would be displayed.<!-- *ngIf else --><div class="container-fluid"> <div class="row bg-success text-light h1 justify-content-center align-items-center" *ngIf="check; else elseStatement" style="height:150px">Condition true </div> <ng-template #elseStatement> <div class="row bg-danger text-light h1 d-flex justify-content-center align-items-center" style="height:150px">Condition false </div> </ng-template></div> As we know, ngIf else statement works on a variable that has a boolean type. Create an angular app and move to src/app. First, we need to define a variable say “check” in app.component.ts with a value true or false.<!-- Define a variable say "check" with value true/false in app.component.ts -->import { Component } from '@angular/core'; @Component({ selector: 'app-root', templateUrl: './app.component.html', styleUrls: ['./app.component.css']}) export class AppComponent { check:boolean = true;} <!-- Define a variable say "check" with value true/false in app.component.ts -->import { Component } from '@angular/core'; @Component({ selector: 'app-root', templateUrl: './app.component.html', styleUrls: ['./app.component.css']}) export class AppComponent { check:boolean = true;} After defining a variable, move to app.component.html and create two divisions using bootstrap classes. Move into the angular app and write command npm install bootstrap. The first division is for the “true” condition and the one inside <ng-template> is for the false condition. We have declared check to be true so we get a green division saying condition true. If the check was false, a red division saying condition false would be displayed.<!-- *ngIf else --><div class="container-fluid"> <div class="row bg-success text-light h1 justify-content-center align-items-center" *ngIf="check; else elseStatement" style="height:150px">Condition true </div> <ng-template #elseStatement> <div class="row bg-danger text-light h1 d-flex justify-content-center align-items-center" style="height:150px">Condition false </div> </ng-template></div> <!-- *ngIf else --><div class="container-fluid"> <div class="row bg-success text-light h1 justify-content-center align-items-center" *ngIf="check; else elseStatement" style="height:150px">Condition true </div> <ng-template #elseStatement> <div class="row bg-danger text-light h1 d-flex justify-content-center align-items-center" style="height:150px">Condition false </div> </ng-template></div> Output: Output: Advantages: Programming language’s "if" block supports logical operators so it does "ngIf". It has support for all the logical operators like AND, OR, NOT, etc. ngIf helps to avoid can’t read property error of undefined. Suppose there is a bound property called “student”. We are trying to access the “name” sub-property of the student which has value “Santosh”. If the student is null, it will return error undefined. So if we check for null before accessing sub-property, we will prevent error using *ngIf.<!--This may error--><div> {{student.name}}</div> <!--check using ngIf--><p *ngIf="student"> {{student.name}}</p>Output:Santosh <!--This may error--><div> {{student.name}}</div> <!--check using ngIf--><p *ngIf="student"> {{student.name}}</p> Output: Santosh ngIf vs Hidden: You might wonder why do we have to use ngIf when we have hidden attribute in HTML5. Yes, they do the same work but there is still a difference. The hidden attribute hides the selected element from the DOM but the element still exists in the DOM. Whereas ngIf gets rid of the selected part from the DOM. It doesn’t intervene with CSS.<!--check is defined in component.ts with value true (boolean)--><div [hidden]="!check"> Show this only if "check" is true</div>Output:Show this only if "check" is true <!--check is defined in component.ts with value true (boolean)--><div [hidden]="!check"> Show this only if "check" is true</div> Output: Show this only if "check" is true AngularJS-Misc Picked AngularJS Web Technologies Web technologies Questions Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n05 Jun, 2020" }, { "code": null, "e": 566, "s": 28, "text": "Introduction: The ngIf directive is used to show or hide parts of an angular application. It can be added to any tags, it is a normal HTML tag, template, or selectors. It is a structural directive meaning that it includes templates based on a condition constrained to boolean. When the expression evaluates to true it runs/displays the template given in the “then” clause. Or when the expression evaluates to false it displays the template given in the “else” clause. If there is nothing in else clause, it will by default display blank." }, { "code": null, "e": 574, "s": 566, "text": "Syntax:" }, { "code": null, "e": 600, "s": 574, "text": "ngIf with an \"else\" block" }, { "code": "<div *ngIf=\"condition; else elseStatement\"> when condition is true.</div><ng-template #elseStatement> when condition is false.</ng-template><!--It can be seen that the else clause refers to ng-template, with the label #elseStatement -->", "e": 850, "s": 600, "text": null }, { "code": null, "e": 1089, "s": 850, "text": "It internally creates two <ng-template>, one for “then” statement and another for “else”. So when the condition is true for ngIf, the content of the unlabelled <ng-template> gets displayed. And when false, the labelled <ng-template> runs." }, { "code": null, "e": 1099, "s": 1089, "text": "Approach:" }, { "code": null, "e": 2540, "s": 1099, "text": "As we know, ngIf else statement works on a variable that has a boolean type. Create an angular app and move to src/app. First, we need to define a variable say “check” in app.component.ts with a value true or false.<!-- Define a variable say \"check\" with value true/false in app.component.ts -->import { Component } from '@angular/core'; @Component({ selector: 'app-root', templateUrl: './app.component.html', styleUrls: ['./app.component.css']}) export class AppComponent { check:boolean = true;}After defining a variable, move to app.component.html and create two divisions using bootstrap classes. Move into the angular app and write command npm install bootstrap. The first division is for the “true” condition and the one inside <ng-template> is for the false condition. We have declared check to be true so we get a green division saying condition true. If the check was false, a red division saying condition false would be displayed.<!-- *ngIf else --><div class=\"container-fluid\"> <div class=\"row bg-success text-light h1 justify-content-center align-items-center\" *ngIf=\"check; else elseStatement\" style=\"height:150px\">Condition true </div> <ng-template #elseStatement> <div class=\"row bg-danger text-light h1 d-flex justify-content-center align-items-center\" style=\"height:150px\">Condition false </div> </ng-template></div>" }, { "code": null, "e": 3048, "s": 2540, "text": "As we know, ngIf else statement works on a variable that has a boolean type. Create an angular app and move to src/app. First, we need to define a variable say “check” in app.component.ts with a value true or false.<!-- Define a variable say \"check\" with value true/false in app.component.ts -->import { Component } from '@angular/core'; @Component({ selector: 'app-root', templateUrl: './app.component.html', styleUrls: ['./app.component.css']}) export class AppComponent { check:boolean = true;}" }, { "code": "<!-- Define a variable say \"check\" with value true/false in app.component.ts -->import { Component } from '@angular/core'; @Component({ selector: 'app-root', templateUrl: './app.component.html', styleUrls: ['./app.component.css']}) export class AppComponent { check:boolean = true;}", "e": 3341, "s": 3048, "text": null }, { "code": null, "e": 4275, "s": 3341, "text": "After defining a variable, move to app.component.html and create two divisions using bootstrap classes. Move into the angular app and write command npm install bootstrap. The first division is for the “true” condition and the one inside <ng-template> is for the false condition. We have declared check to be true so we get a green division saying condition true. If the check was false, a red division saying condition false would be displayed.<!-- *ngIf else --><div class=\"container-fluid\"> <div class=\"row bg-success text-light h1 justify-content-center align-items-center\" *ngIf=\"check; else elseStatement\" style=\"height:150px\">Condition true </div> <ng-template #elseStatement> <div class=\"row bg-danger text-light h1 d-flex justify-content-center align-items-center\" style=\"height:150px\">Condition false </div> </ng-template></div>" }, { "code": "<!-- *ngIf else --><div class=\"container-fluid\"> <div class=\"row bg-success text-light h1 justify-content-center align-items-center\" *ngIf=\"check; else elseStatement\" style=\"height:150px\">Condition true </div> <ng-template #elseStatement> <div class=\"row bg-danger text-light h1 d-flex justify-content-center align-items-center\" style=\"height:150px\">Condition false </div> </ng-template></div>", "e": 4765, "s": 4275, "text": null }, { "code": null, "e": 4773, "s": 4765, "text": "Output:" }, { "code": null, "e": 4781, "s": 4773, "text": "Output:" }, { "code": null, "e": 4793, "s": 4781, "text": "Advantages:" }, { "code": null, "e": 4942, "s": 4793, "text": "Programming language’s \"if\" block supports logical operators so it does \"ngIf\". It has support for all the logical operators like AND, OR, NOT, etc." }, { "code": null, "e": 5420, "s": 4942, "text": "ngIf helps to avoid can’t read property error of undefined. Suppose there is a bound property called “student”. We are trying to access the “name” sub-property of the student which has value “Santosh”. If the student is null, it will return error undefined. So if we check for null before accessing sub-property, we will prevent error using *ngIf.<!--This may error--><div> {{student.name}}</div> <!--check using ngIf--><p *ngIf=\"student\"> {{student.name}}</p>Output:Santosh" }, { "code": "<!--This may error--><div> {{student.name}}</div> <!--check using ngIf--><p *ngIf=\"student\"> {{student.name}}</p>", "e": 5537, "s": 5420, "text": null }, { "code": null, "e": 5545, "s": 5537, "text": "Output:" }, { "code": null, "e": 5553, "s": 5545, "text": "Santosh" }, { "code": null, "e": 6076, "s": 5553, "text": "ngIf vs Hidden: You might wonder why do we have to use ngIf when we have hidden attribute in HTML5. Yes, they do the same work but there is still a difference. The hidden attribute hides the selected element from the DOM but the element still exists in the DOM. Whereas ngIf gets rid of the selected part from the DOM. It doesn’t intervene with CSS.<!--check is defined in component.ts with value true (boolean)--><div [hidden]=\"!check\"> Show this only if \"check\" is true</div>Output:Show this only if \"check\" is true" }, { "code": "<!--check is defined in component.ts with value true (boolean)--><div [hidden]=\"!check\"> Show this only if \"check\" is true</div>", "e": 6210, "s": 6076, "text": null }, { "code": null, "e": 6218, "s": 6210, "text": "Output:" }, { "code": null, "e": 6252, "s": 6218, "text": "Show this only if \"check\" is true" }, { "code": null, "e": 6267, "s": 6252, "text": "AngularJS-Misc" }, { "code": null, "e": 6274, "s": 6267, "text": "Picked" }, { "code": null, "e": 6284, "s": 6274, "text": "AngularJS" }, { "code": null, "e": 6301, "s": 6284, "text": "Web Technologies" }, { "code": null, "e": 6328, "s": 6301, "text": "Web technologies Questions" } ]
Hashing in Java
18 Nov, 2021 In hashing there is a hash function that maps keys to some values. But these hashing function may lead to collision that is two or more keys are mapped to same value. Chain hashing avoids collision. The idea is to make each cell of hash table point to a linked list of records that have same hash function value.Let’s create a hash function, such that our hash table has ‘N’ number of buckets. To insert a node into the hash table, we need to find the hash index for the given key. And it could be calculated using the hash function. Example: hashIndex = key % noOfBucketsInsert: Move to the bucket corresponds to the above calculated hash index and insert the new node at the end of the list.Delete: To delete a node from hash table, calculate the hash index for the key, move to the bucket corresponds to the calculated hash index, search the list in the current bucket to find and remove the node with the given key (if found). Please refer Hashing | Set 2 (Separate Chaining) for details. With help of HashTable (A synchronized implementation of hashing) Java // Java program to demonstrate working of HashTableimport java.util.*; class GFG { public static void main(String args[]) { // Create a HashTable to store // String values corresponding to integer keys Hashtable<Integer, String> hm = new Hashtable<Integer, String>(); // Input the values hm.put(1, "Geeks"); hm.put(12, "forGeeks"); hm.put(15, "A computer"); hm.put(3, "Portal"); // Printing the Hashtable System.out.println(hm); }} {15=A computer, 3=Portal, 12=forGeeks, 1=Geeks} With the help of HashMap (A non-synchronized faster implementation of hashing) Java // Java program to create HashMap from an array// by taking the elements as Keys and// the frequencies as the Values import java.util.*; class GFG { // Function to create HashMap from array static void createHashMap(int arr[]) { // Creates an empty HashMap HashMap<Integer, Integer> hmap = new HashMap<Integer, Integer>(); // Traverse through the given array for (int i = 0; i < arr.length; i++) { // Get if the element is present Integer c = hmap.get(arr[i]); // If this is first occurrence of element // Insert the element if (hmap.get(arr[i]) == null) { hmap.put(arr[i], 1); } // If elements already exists in hash map // Increment the count of element by 1 else { hmap.put(arr[i], ++c); } } // Print HashMap System.out.println(hmap); } // Driver method to test above method public static void main(String[] args) { int arr[] = { 10, 34, 5, 10, 3, 5, 10 }; createHashMap(arr); }} {34=1, 3=1, 5=2, 10=3} With the help of LinkedHashMap (Similar to HashMap, but keeps order of elements) Java // Java program to demonstrate working of LinkedHashMapimport java.util.*; public class BasicLinkedHashMap{ public static void main(String a[]) { LinkedHashMap<String, String> lhm = new LinkedHashMap<String, String>(); lhm.put("one", "practice.geeksforgeeks.org"); lhm.put("two", "code.geeksforgeeks.org"); lhm.put("four", "quiz.geeksforgeeks.org"); // It prints the elements in same order // as they were inserted System.out.println(lhm); System.out.println("Getting value for key 'one': " + lhm.get("one")); System.out.println("Size of the map: " + lhm.size()); System.out.println("Is map empty? " + lhm.isEmpty()); System.out.println("Contains key 'two'? "+ lhm.containsKey("two")); System.out.println("Contains value 'practice.geeks" +"forgeeks.org'? "+ lhm.containsValue("practice"+ ".geeksforgeeks.org")); System.out.println("delete element 'one': " + lhm.remove("one")); System.out.println(lhm); }} {one=practice.geeksforgeeks.org, two=code.geeksforgeeks.org, four=quiz.geeksforgeeks.org} Getting value for key 'one': practice.geeksforgeeks.org Size of the map: 3 Is map empty? false Contains key 'two'? true Contains value 'practice.geeksforgeeks.org'? true delete element 'one': practice.geeksforgeeks.org {two=code.geeksforgeeks.org, four=quiz.geeksforgeeks.org} With the help of ConcurretHashMap(Similar to Hashtable, Synchronized, but faster as multiple locks are used) Java // Java program to demonstrate working of ConcurrentHashMap import java.util.concurrent.*;class ConcurrentHashMapDemo { public static void main(String[] args) { ConcurrentHashMap<Integer, String> m = new ConcurrentHashMap<Integer, String>(); m.put(100, "Hello"); m.put(101, "Geeks"); m.put(102, "Geeks"); // Printing the ConcurrentHashMap System.out.println("ConcurentHashMap: " + m); // Adding Hello at 101 key // This is already present in ConcurrentHashMap object // Therefore its better to use putIfAbsent for such cases m.putIfAbsent(101, "Hello"); // Printing the ConcurrentHashMap System.out.println("\nConcurentHashMap: " + m); // Trying to remove entry for 101 key // since it is present m.remove(101, "Geeks"); // Printing the ConcurrentHashMap System.out.println("\nConcurentHashMap: " + m); // replacing the value for key 101 // from "Hello" to "For" m.replace(100, "Hello", "For"); // Printing the ConcurrentHashMap System.out.println("\nConcurentHashMap: " + m); }} ConcurentHashMap: {100=Hello, 101=Geeks, 102=Geeks} ConcurentHashMap: {100=Hello, 101=Geeks, 102=Geeks} ConcurentHashMap: {100=Hello, 102=Geeks} ConcurentHashMap: {100=For, 102=Geeks} With the help of HashSet (Similar to HashMap, but maintains only keys, not pair) Java // Java program to demonstrate working of HashSetimport java.util.*; class Test { public static void main(String[] args) { HashSet<String> h = new HashSet<String>(); // Adding elements into HashSet using add() h.add("India"); h.add("Australia"); h.add("South Africa"); h.add("India"); // adding duplicate elements // Displaying the HashSet System.out.println(h); // Checking if India is present or not System.out.println("\nHashSet contains India or not:" + h.contains("India")); // Removing items from HashSet using remove() h.remove("Australia"); // Printing the HashSet System.out.println("\nList after removing Australia:" + h); // Iterating over hash set items System.out.println("\nIterating over list:"); Iterator<String> i = h.iterator(); while (i.hasNext()) System.out.println(i.next()); }} [South Africa, Australia, India] HashSet contains India or not:true List after removing Australia:[South Africa, India] Iterating over list: South Africa India With the help of LinkedHashSet (Similar to LinkedHashMap, but maintains only keys, not pair) Java // Java program to demonstrate working of LinkedHashSet import java.util.LinkedHashSet; public class Demo { public static void main(String[] args) { LinkedHashSet<String> linkedset = new LinkedHashSet<String>(); // Adding element to LinkedHashSet linkedset.add("A"); linkedset.add("B"); linkedset.add("C"); linkedset.add("D"); // This will not add new element as A already exists linkedset.add("A"); linkedset.add("E"); System.out.println("Size of LinkedHashSet = " + linkedset.size()); System.out.println("Original LinkedHashSet:" + linkedset); System.out.println("Removing D from LinkedHashSet: " + linkedset.remove("D")); System.out.println("Trying to Remove Z which is not "+ "present: " + linkedset.remove("Z")); System.out.println("Checking if A is present=" + linkedset.contains("A")); System.out.println("Updated LinkedHashSet: " + linkedset); } } Size of LinkedHashSet = 5 Original LinkedHashSet:[A, B, C, D, E] Removing D from LinkedHashSet: true Trying to Remove Z which is not present: false Checking if A is present=true Updated LinkedHashSet: [A, B, C, E] With the help of TreeSet (Implements the SortedSet interface, Objects are stored in a sorted and ascending order). Java // Java program to demonstrate working of TreeSet import java.util.*; class TreeSetDemo { public static void main(String[] args) { TreeSet<String> ts1 = new TreeSet<String>(); // Elements are added using add() method ts1.add("A"); ts1.add("B"); ts1.add("C"); // Duplicates will not get insert ts1.add("C"); // Elements get stored in default natural // Sorting Order(Ascending) System.out.println("TreeSet: " + ts1); // Checking if A is present or not System.out.println("\nTreeSet contains A or not:" + ts1.contains("A")); // Removing items from TreeSet using remove() ts1.remove("A"); // Printing the TreeSet System.out.println("\nTreeSet after removing A:" + ts1); // Iterating over TreeSet items System.out.println("\nIterating over TreeSet:"); Iterator<String> i = ts1.iterator(); while (i.hasNext()) System.out.println(i.next()); }} Output: TreeSet: [A, B, C] TreeSet contains A or not:true TreeSet after removing A:[B, C] Iterating over TreeSet: B C RishabhPrabhu kashishsoda Java-ConcurrentHashMap Java-HashMap java-hashset Java-HashTable Java-LinkedHashMap java-LinkedHashSet Hash Java Java Programs Hash Java Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 54, "s": 26, "text": "\n18 Nov, 2021" }, { "code": null, "e": 987, "s": 54, "text": "In hashing there is a hash function that maps keys to some values. But these hashing function may lead to collision that is two or more keys are mapped to same value. Chain hashing avoids collision. The idea is to make each cell of hash table point to a linked list of records that have same hash function value.Let’s create a hash function, such that our hash table has ‘N’ number of buckets. To insert a node into the hash table, we need to find the hash index for the given key. And it could be calculated using the hash function. Example: hashIndex = key % noOfBucketsInsert: Move to the bucket corresponds to the above calculated hash index and insert the new node at the end of the list.Delete: To delete a node from hash table, calculate the hash index for the key, move to the bucket corresponds to the calculated hash index, search the list in the current bucket to find and remove the node with the given key (if found). " }, { "code": null, "e": 1050, "s": 987, "text": "Please refer Hashing | Set 2 (Separate Chaining) for details. " }, { "code": null, "e": 1116, "s": 1050, "text": "With help of HashTable (A synchronized implementation of hashing)" }, { "code": null, "e": 1121, "s": 1116, "text": "Java" }, { "code": "// Java program to demonstrate working of HashTableimport java.util.*; class GFG { public static void main(String args[]) { // Create a HashTable to store // String values corresponding to integer keys Hashtable<Integer, String> hm = new Hashtable<Integer, String>(); // Input the values hm.put(1, \"Geeks\"); hm.put(12, \"forGeeks\"); hm.put(15, \"A computer\"); hm.put(3, \"Portal\"); // Printing the Hashtable System.out.println(hm); }}", "e": 1646, "s": 1121, "text": null }, { "code": null, "e": 1694, "s": 1646, "text": "{15=A computer, 3=Portal, 12=forGeeks, 1=Geeks}" }, { "code": null, "e": 1775, "s": 1696, "text": "With the help of HashMap (A non-synchronized faster implementation of hashing)" }, { "code": null, "e": 1780, "s": 1775, "text": "Java" }, { "code": "// Java program to create HashMap from an array// by taking the elements as Keys and// the frequencies as the Values import java.util.*; class GFG { // Function to create HashMap from array static void createHashMap(int arr[]) { // Creates an empty HashMap HashMap<Integer, Integer> hmap = new HashMap<Integer, Integer>(); // Traverse through the given array for (int i = 0; i < arr.length; i++) { // Get if the element is present Integer c = hmap.get(arr[i]); // If this is first occurrence of element // Insert the element if (hmap.get(arr[i]) == null) { hmap.put(arr[i], 1); } // If elements already exists in hash map // Increment the count of element by 1 else { hmap.put(arr[i], ++c); } } // Print HashMap System.out.println(hmap); } // Driver method to test above method public static void main(String[] args) { int arr[] = { 10, 34, 5, 10, 3, 5, 10 }; createHashMap(arr); }}", "e": 2897, "s": 1780, "text": null }, { "code": null, "e": 2920, "s": 2897, "text": "{34=1, 3=1, 5=2, 10=3}" }, { "code": null, "e": 3003, "s": 2922, "text": "With the help of LinkedHashMap (Similar to HashMap, but keeps order of elements)" }, { "code": null, "e": 3008, "s": 3003, "text": "Java" }, { "code": "// Java program to demonstrate working of LinkedHashMapimport java.util.*; public class BasicLinkedHashMap{ public static void main(String a[]) { LinkedHashMap<String, String> lhm = new LinkedHashMap<String, String>(); lhm.put(\"one\", \"practice.geeksforgeeks.org\"); lhm.put(\"two\", \"code.geeksforgeeks.org\"); lhm.put(\"four\", \"quiz.geeksforgeeks.org\"); // It prints the elements in same order // as they were inserted System.out.println(lhm); System.out.println(\"Getting value for key 'one': \" + lhm.get(\"one\")); System.out.println(\"Size of the map: \" + lhm.size()); System.out.println(\"Is map empty? \" + lhm.isEmpty()); System.out.println(\"Contains key 'two'? \"+ lhm.containsKey(\"two\")); System.out.println(\"Contains value 'practice.geeks\" +\"forgeeks.org'? \"+ lhm.containsValue(\"practice\"+ \".geeksforgeeks.org\")); System.out.println(\"delete element 'one': \" + lhm.remove(\"one\")); System.out.println(lhm); }}", "e": 4169, "s": 3008, "text": null }, { "code": null, "e": 4536, "s": 4169, "text": "{one=practice.geeksforgeeks.org, two=code.geeksforgeeks.org, four=quiz.geeksforgeeks.org}\nGetting value for key 'one': practice.geeksforgeeks.org\nSize of the map: 3\nIs map empty? false\nContains key 'two'? true\nContains value 'practice.geeksforgeeks.org'? true\ndelete element 'one': practice.geeksforgeeks.org\n{two=code.geeksforgeeks.org, four=quiz.geeksforgeeks.org}" }, { "code": null, "e": 4647, "s": 4538, "text": "With the help of ConcurretHashMap(Similar to Hashtable, Synchronized, but faster as multiple locks are used)" }, { "code": null, "e": 4652, "s": 4647, "text": "Java" }, { "code": "// Java program to demonstrate working of ConcurrentHashMap import java.util.concurrent.*;class ConcurrentHashMapDemo { public static void main(String[] args) { ConcurrentHashMap<Integer, String> m = new ConcurrentHashMap<Integer, String>(); m.put(100, \"Hello\"); m.put(101, \"Geeks\"); m.put(102, \"Geeks\"); // Printing the ConcurrentHashMap System.out.println(\"ConcurentHashMap: \" + m); // Adding Hello at 101 key // This is already present in ConcurrentHashMap object // Therefore its better to use putIfAbsent for such cases m.putIfAbsent(101, \"Hello\"); // Printing the ConcurrentHashMap System.out.println(\"\\nConcurentHashMap: \" + m); // Trying to remove entry for 101 key // since it is present m.remove(101, \"Geeks\"); // Printing the ConcurrentHashMap System.out.println(\"\\nConcurentHashMap: \" + m); // replacing the value for key 101 // from \"Hello\" to \"For\" m.replace(100, \"Hello\", \"For\"); // Printing the ConcurrentHashMap System.out.println(\"\\nConcurentHashMap: \" + m); }}", "e": 5820, "s": 4652, "text": null }, { "code": null, "e": 6007, "s": 5820, "text": "ConcurentHashMap: {100=Hello, 101=Geeks, 102=Geeks}\n\nConcurentHashMap: {100=Hello, 101=Geeks, 102=Geeks}\n\nConcurentHashMap: {100=Hello, 102=Geeks}\n\nConcurentHashMap: {100=For, 102=Geeks}" }, { "code": null, "e": 6090, "s": 6009, "text": "With the help of HashSet (Similar to HashMap, but maintains only keys, not pair)" }, { "code": null, "e": 6095, "s": 6090, "text": "Java" }, { "code": "// Java program to demonstrate working of HashSetimport java.util.*; class Test { public static void main(String[] args) { HashSet<String> h = new HashSet<String>(); // Adding elements into HashSet using add() h.add(\"India\"); h.add(\"Australia\"); h.add(\"South Africa\"); h.add(\"India\"); // adding duplicate elements // Displaying the HashSet System.out.println(h); // Checking if India is present or not System.out.println(\"\\nHashSet contains India or not:\" + h.contains(\"India\")); // Removing items from HashSet using remove() h.remove(\"Australia\"); // Printing the HashSet System.out.println(\"\\nList after removing Australia:\" + h); // Iterating over hash set items System.out.println(\"\\nIterating over list:\"); Iterator<String> i = h.iterator(); while (i.hasNext()) System.out.println(i.next()); }}", "e": 7073, "s": 6095, "text": null }, { "code": null, "e": 7236, "s": 7073, "text": "[South Africa, Australia, India]\n\nHashSet contains India or not:true\n\nList after removing Australia:[South Africa, India]\n\nIterating over list:\nSouth Africa\nIndia" }, { "code": null, "e": 7331, "s": 7238, "text": "With the help of LinkedHashSet (Similar to LinkedHashMap, but maintains only keys, not pair)" }, { "code": null, "e": 7336, "s": 7331, "text": "Java" }, { "code": "// Java program to demonstrate working of LinkedHashSet import java.util.LinkedHashSet; public class Demo { public static void main(String[] args) { LinkedHashSet<String> linkedset = new LinkedHashSet<String>(); // Adding element to LinkedHashSet linkedset.add(\"A\"); linkedset.add(\"B\"); linkedset.add(\"C\"); linkedset.add(\"D\"); // This will not add new element as A already exists linkedset.add(\"A\"); linkedset.add(\"E\"); System.out.println(\"Size of LinkedHashSet = \" + linkedset.size()); System.out.println(\"Original LinkedHashSet:\" + linkedset); System.out.println(\"Removing D from LinkedHashSet: \" + linkedset.remove(\"D\")); System.out.println(\"Trying to Remove Z which is not \"+ \"present: \" + linkedset.remove(\"Z\")); System.out.println(\"Checking if A is present=\" + linkedset.contains(\"A\")); System.out.println(\"Updated LinkedHashSet: \" + linkedset); } } ", "e": 8493, "s": 7336, "text": null }, { "code": null, "e": 8707, "s": 8493, "text": "Size of LinkedHashSet = 5\nOriginal LinkedHashSet:[A, B, C, D, E]\nRemoving D from LinkedHashSet: true\nTrying to Remove Z which is not present: false\nChecking if A is present=true\nUpdated LinkedHashSet: [A, B, C, E]" }, { "code": null, "e": 8824, "s": 8709, "text": "With the help of TreeSet (Implements the SortedSet interface, Objects are stored in a sorted and ascending order)." }, { "code": null, "e": 8829, "s": 8824, "text": "Java" }, { "code": "// Java program to demonstrate working of TreeSet import java.util.*; class TreeSetDemo { public static void main(String[] args) { TreeSet<String> ts1 = new TreeSet<String>(); // Elements are added using add() method ts1.add(\"A\"); ts1.add(\"B\"); ts1.add(\"C\"); // Duplicates will not get insert ts1.add(\"C\"); // Elements get stored in default natural // Sorting Order(Ascending) System.out.println(\"TreeSet: \" + ts1); // Checking if A is present or not System.out.println(\"\\nTreeSet contains A or not:\" + ts1.contains(\"A\")); // Removing items from TreeSet using remove() ts1.remove(\"A\"); // Printing the TreeSet System.out.println(\"\\nTreeSet after removing A:\" + ts1); // Iterating over TreeSet items System.out.println(\"\\nIterating over TreeSet:\"); Iterator<String> i = ts1.iterator(); while (i.hasNext()) System.out.println(i.next()); }}", "e": 9868, "s": 8829, "text": null }, { "code": null, "e": 9877, "s": 9868, "text": "Output: " }, { "code": null, "e": 9990, "s": 9877, "text": "TreeSet: [A, B, C]\n\nTreeSet contains A or not:true\n\nTreeSet after removing A:[B, C]\n\nIterating over TreeSet:\nB\nC" }, { "code": null, "e": 10004, "s": 9990, "text": "RishabhPrabhu" }, { "code": null, "e": 10016, "s": 10004, "text": "kashishsoda" }, { "code": null, "e": 10039, "s": 10016, "text": "Java-ConcurrentHashMap" }, { "code": null, "e": 10052, "s": 10039, "text": "Java-HashMap" }, { "code": null, "e": 10065, "s": 10052, "text": "java-hashset" }, { "code": null, "e": 10080, "s": 10065, "text": "Java-HashTable" }, { "code": null, "e": 10099, "s": 10080, "text": "Java-LinkedHashMap" }, { "code": null, "e": 10118, "s": 10099, "text": "java-LinkedHashSet" }, { "code": null, "e": 10123, "s": 10118, "text": "Hash" }, { "code": null, "e": 10128, "s": 10123, "text": "Java" }, { "code": null, "e": 10142, "s": 10128, "text": "Java Programs" }, { "code": null, "e": 10147, "s": 10142, "text": "Hash" }, { "code": null, "e": 10152, "s": 10147, "text": "Java" } ]
String concatenation in Julia
25 Aug, 2020 String concatenation in Julia is a way of appending two or more strings into a single string whether it is character by character or using some special characters end to end. There are many ways to perform string concatenation. Example: Input: str1 = 'Geeks' str2 = 'for' str3 = 'Geeks' Output: 'GeeksforGeeks' The different ways in which we can concatenate strings in Julia are : Using * operator Using ^ operator Using string() function It is used to concatenate different strings and/or characters into a single string. We can concatenate two or more strings in Julia using * operator. Example: Julia # creating string 1s1 = "Hello " # creating string 2s2 = "World !" # concatenating the stringss = s1 * s2 # printing the concatenated stringprint(s) Output: This operator repeats the specified string with the specified number of times. It is used when there is a need to concatenate a single string multiple times. Example: Julia # creating strings1 = "Hello " # concatenating the strings = s1 ^ 5 # printing the concatenated stringprint(s) Output: Julia provides a pre-defined string() function for the concatenation of strings. This function takes all the strings to be concatenated as arguments and returns a single concatenated string. string(string1, string2, string3, string4, ...) Example 1: Julia # creating string 1s1 = "Hello " # creating string 2s2 = "World !" # concatenating the stringss = string(s1, s2) # printing the concatenated stringprint(s) Output: Example 2: Julia # creating 3 stringss1 = "I"s2 = "Love"s3 = "Julia" # concatenating the stringsstring(s1, " ", s2, " ", s3) # printing the concatenated stringprint(s) Output: Concatenated strings can be stored in a File by using the write() function. Here, firstly the concatenation is done and then the file is first opened into ‘w’ i.e. write mode and the concatenated string is stored with the use of write(). Example: Julia # creating 3 stringss1 = "I"s2 = "Love"s3 = "Julia" # concatenating the stringss = s1 * " " * s2 * " " * s3 # storing string s in a fileopen("myfile.txt", "w") do io write(io, s) end; Output: Picked Julia Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n25 Aug, 2020" }, { "code": null, "e": 256, "s": 28, "text": "String concatenation in Julia is a way of appending two or more strings into a single string whether it is character by character or using some special characters end to end. There are many ways to perform string concatenation." }, { "code": null, "e": 266, "s": 256, "text": "Example: " }, { "code": null, "e": 343, "s": 266, "text": "Input: str1 = 'Geeks'\nstr2 = 'for'\nstr3 = 'Geeks' \n\nOutput: 'GeeksforGeeks'\n" }, { "code": null, "e": 414, "s": 343, "text": "The different ways in which we can concatenate strings in Julia are : " }, { "code": null, "e": 431, "s": 414, "text": "Using * operator" }, { "code": null, "e": 448, "s": 431, "text": "Using ^ operator" }, { "code": null, "e": 472, "s": 448, "text": "Using string() function" }, { "code": null, "e": 622, "s": 472, "text": "It is used to concatenate different strings and/or characters into a single string. We can concatenate two or more strings in Julia using * operator." }, { "code": null, "e": 632, "s": 622, "text": "Example: " }, { "code": null, "e": 638, "s": 632, "text": "Julia" }, { "code": "# creating string 1s1 = \"Hello \" # creating string 2s2 = \"World !\" # concatenating the stringss = s1 * s2 # printing the concatenated stringprint(s)", "e": 790, "s": 638, "text": null }, { "code": null, "e": 799, "s": 790, "text": "Output: " }, { "code": null, "e": 957, "s": 799, "text": "This operator repeats the specified string with the specified number of times. It is used when there is a need to concatenate a single string multiple times." }, { "code": null, "e": 967, "s": 957, "text": "Example: " }, { "code": null, "e": 973, "s": 967, "text": "Julia" }, { "code": "# creating strings1 = \"Hello \" # concatenating the strings = s1 ^ 5 # printing the concatenated stringprint(s)", "e": 1086, "s": 973, "text": null }, { "code": null, "e": 1095, "s": 1086, "text": "Output: " }, { "code": null, "e": 1287, "s": 1095, "text": "Julia provides a pre-defined string() function for the concatenation of strings. This function takes all the strings to be concatenated as arguments and returns a single concatenated string. " }, { "code": null, "e": 1335, "s": 1287, "text": "string(string1, string2, string3, string4, ...)" }, { "code": null, "e": 1347, "s": 1335, "text": "Example 1: " }, { "code": null, "e": 1353, "s": 1347, "text": "Julia" }, { "code": "# creating string 1s1 = \"Hello \" # creating string 2s2 = \"World !\" # concatenating the stringss = string(s1, s2) # printing the concatenated stringprint(s)", "e": 1512, "s": 1353, "text": null }, { "code": null, "e": 1521, "s": 1512, "text": "Output: " }, { "code": null, "e": 1533, "s": 1521, "text": "Example 2: " }, { "code": null, "e": 1539, "s": 1533, "text": "Julia" }, { "code": "# creating 3 stringss1 = \"I\"s2 = \"Love\"s3 = \"Julia\" # concatenating the stringsstring(s1, \" \", s2, \" \", s3) # printing the concatenated stringprint(s)", "e": 1692, "s": 1539, "text": null }, { "code": null, "e": 1700, "s": 1692, "text": "Output:" }, { "code": null, "e": 1938, "s": 1700, "text": "Concatenated strings can be stored in a File by using the write() function. Here, firstly the concatenation is done and then the file is first opened into ‘w’ i.e. write mode and the concatenated string is stored with the use of write()." }, { "code": null, "e": 1948, "s": 1938, "text": "Example: " }, { "code": null, "e": 1954, "s": 1948, "text": "Julia" }, { "code": "# creating 3 stringss1 = \"I\"s2 = \"Love\"s3 = \"Julia\" # concatenating the stringss = s1 * \" \" * s2 * \" \" * s3 # storing string s in a fileopen(\"myfile.txt\", \"w\") do io write(io, s) end;", "e": 2154, "s": 1954, "text": null }, { "code": null, "e": 2163, "s": 2154, "text": "Output: " }, { "code": null, "e": 2170, "s": 2163, "text": "Picked" }, { "code": null, "e": 2176, "s": 2170, "text": "Julia" } ]
Calculate Number of Cycles and Average Operand Fetch Rate of the Machine
04 Oct, 2021 In this article, we will know how to calculate the average operand fetch rate of the machine when the machine uses different operand accessing modes. Example-1 : Consider a hypothetical machine that uses different operand accessing mode is given below. Assume the 3 clock cycles consumed for memory access, 2 clock cycles consumed for arithmetic computation, 0 clock cycle consumed when data is present in the register or Instruction itself, What is the average operand fetch rate of the machine? Solution : In Indexed Addressing mode, if nothing is specified then we assume “Base Address is given directly into the instruction and Index value is stored into the Index Register“. Now, If we look at the given operand accessing mode with their number of cycle required to execute according to the given question we can see that – Immediate Accessing Mode needs no reference or 0 Cycles. Register Accessing Mode needs a 0-reg reference or 0 Cycles. Direct Accessing Mode needs a 1-memory reference or 3 Cycles. Memory Indirect Accessing Mode needs a 2-memory reference. OR 3*2 Cycles (1-memory reference has 3 cycles so 2-mem reference has 3*2 cycles). Indexed Accessing Mode needs 1-reg reference and 1-mem reference and 1-arithmetic calculation. OR 5 Cycles (1-memory reference has 3 cycles and 1-arithmetic calculation has 2 cycles). We can get the total average number of cycles required to execute one instruction by taking the sum of products of frequency and number of cycles. The total average number of Cycle required to execute one instruction = (0.25\times0) + (0.28\times0) + (0.18\times3) + (0.14\times6) + (0.15\times5) = 2.13 Cycles Now it is known that the time taken to complete one cycle is = 1/1GHz = 1 nanosecond Average time required to execute one instructions = 2.13 ∗ 1 = 2.13 nanosecond So, 2.13 nanoseconds are required for = 1 instruction. 1 second is required for = 1 / (2.13 * 10^(-9)) = 0.469483568 * 10^9 Instructions = 469.483568 MIPS (Million Instructions Per Second). In general we take operation fetch rate in MIPS. Example-2 : Consider a hypothetical machine that uses different operand accessing mode is given below. Calculate Cycle per Instructions or CPI. Solution : In computer architecture, cycles per instruction are one aspect of a processor’s performance: the average number of clock cycles per instruction for a program or program fragment. It is the multiplicative inverse of instructions per cycle. It is given that – ALU Instruction consumes 4 cycles Load Instruction consumes 3 cycles Store Instruction consumes 2 cycles Branch Instruction consumes 2 cycles So, we can get CPI by taking the product of cycles and frequency. CPI = 4*0.45 + 3*0.35 + 2*0.1 + 2*0.1 = 3.25 Cycles/Instruction graghav3110 Computer Organization & Architecture GATE CS Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Direct Access Media (DMA) Controller in Computer Architecture Control Characters Pin diagram of 8086 microprocessor Architecture of 8085 microprocessor Computer Organization and Architecture | Pipelining | Set 2 (Dependencies and Data Hazard) Layers of OSI Model ACID Properties in DBMS Types of Operating Systems TCP/IP Model Page Replacement Algorithms in Operating Systems
[ { "code": null, "e": 54, "s": 26, "text": "\n04 Oct, 2021" }, { "code": null, "e": 205, "s": 54, "text": "In this article, we will know how to calculate the average operand fetch rate of the machine when the machine uses different operand accessing modes. " }, { "code": null, "e": 554, "s": 205, "text": "Example-1 : Consider a hypothetical machine that uses different operand accessing mode is given below. Assume the 3 clock cycles consumed for memory access, 2 clock cycles consumed for arithmetic computation, 0 clock cycle consumed when data is present in the register or Instruction itself, What is the average operand fetch rate of the machine? " }, { "code": null, "e": 887, "s": 554, "text": "Solution : In Indexed Addressing mode, if nothing is specified then we assume “Base Address is given directly into the instruction and Index value is stored into the Index Register“. Now, If we look at the given operand accessing mode with their number of cycle required to execute according to the given question we can see that – " }, { "code": null, "e": 1395, "s": 887, "text": "Immediate Accessing Mode needs no reference or 0 Cycles. Register Accessing Mode needs a 0-reg reference or 0 Cycles. Direct Accessing Mode needs a 1-memory reference or 3 Cycles. Memory Indirect Accessing Mode needs a 2-memory reference. OR 3*2 Cycles (1-memory reference has 3 cycles so 2-mem reference has 3*2 cycles). Indexed Accessing Mode needs 1-reg reference and 1-mem reference and 1-arithmetic calculation. OR 5 Cycles (1-memory reference has 3 cycles and 1-arithmetic calculation has 2 cycles). " }, { "code": null, "e": 1613, "s": 1395, "text": "We can get the total average number of cycles required to execute one instruction by taking the sum of products of frequency and number of cycles. The total average number of Cycle required to execute one instruction " }, { "code": null, "e": 1707, "s": 1613, "text": "= (0.25\\times0) + (0.28\\times0) + (0.18\\times3) + (0.14\\times6) + (0.15\\times5)\n= 2.13 Cycles" }, { "code": null, "e": 1769, "s": 1707, "text": "Now it is known that the time taken to complete one cycle is " }, { "code": null, "e": 1793, "s": 1769, "text": "= 1/1GHz = 1 nanosecond" }, { "code": null, "e": 1844, "s": 1793, "text": "Average time required to execute one instructions " }, { "code": null, "e": 1873, "s": 1844, "text": "= 2.13 ∗ 1 = 2.13 nanosecond" }, { "code": null, "e": 1929, "s": 1873, "text": "So, 2.13 nanoseconds are required for = 1 instruction. " }, { "code": null, "e": 1955, "s": 1929, "text": "1 second is required for " }, { "code": null, "e": 2115, "s": 1955, "text": "= 1 / (2.13 * 10^(-9)) \n= 0.469483568 * 10^9 Instructions\n= 469.483568 MIPS (Million Instructions Per Second).\nIn general we take operation fetch rate in MIPS." }, { "code": null, "e": 2260, "s": 2115, "text": "Example-2 : Consider a hypothetical machine that uses different operand accessing mode is given below. Calculate Cycle per Instructions or CPI. " }, { "code": null, "e": 2531, "s": 2260, "text": "Solution : In computer architecture, cycles per instruction are one aspect of a processor’s performance: the average number of clock cycles per instruction for a program or program fragment. It is the multiplicative inverse of instructions per cycle. It is given that – " }, { "code": null, "e": 2673, "s": 2531, "text": "ALU Instruction consumes 4 cycles\nLoad Instruction consumes 3 cycles\nStore Instruction consumes 2 cycles\nBranch Instruction consumes 2 cycles" }, { "code": null, "e": 2740, "s": 2673, "text": "So, we can get CPI by taking the product of cycles and frequency. " }, { "code": null, "e": 2805, "s": 2740, "text": "CPI = 4*0.45 + 3*0.35 + 2*0.1 + 2*0.1 \n= 3.25 Cycles/Instruction" }, { "code": null, "e": 2817, "s": 2805, "text": "graghav3110" }, { "code": null, "e": 2854, "s": 2817, "text": "Computer Organization & Architecture" }, { "code": null, "e": 2862, "s": 2854, "text": "GATE CS" }, { "code": null, "e": 2960, "s": 2862, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 3022, "s": 2960, "text": "Direct Access Media (DMA) Controller in Computer Architecture" }, { "code": null, "e": 3041, "s": 3022, "text": "Control Characters" }, { "code": null, "e": 3076, "s": 3041, "text": "Pin diagram of 8086 microprocessor" }, { "code": null, "e": 3112, "s": 3076, "text": "Architecture of 8085 microprocessor" }, { "code": null, "e": 3203, "s": 3112, "text": "Computer Organization and Architecture | Pipelining | Set 2 (Dependencies and Data Hazard)" }, { "code": null, "e": 3223, "s": 3203, "text": "Layers of OSI Model" }, { "code": null, "e": 3247, "s": 3223, "text": "ACID Properties in DBMS" }, { "code": null, "e": 3274, "s": 3247, "text": "Types of Operating Systems" }, { "code": null, "e": 3287, "s": 3274, "text": "TCP/IP Model" } ]
Program to check if water tank overflows when n solid balls are dipped in the water tank
22 Jun, 2022 Given the dimensions of cylindrical water tank, spherical solid balls and the amount of water present in the tank check if water tank will overflow when balls are dipped in the water tank. Examples : input : H = 10, r = 5 h = 5 N = 2, R = 2 output : Not in overflow state Explanation : water tank capacity = 3.14 * r * r * H = 3.14 * 5 * 5 * 10 = 785 volume of water in tank = 3.14 * r * r * h = 3.14 * 5 * 5 * 5 = 392.5 Volume of balls = N * (4/3) * 3.14 * R * R * R = 2 * (4/3) * 3.14 * 2 * 2 * 2 = 67.02 Total volume of water + dip balls = 392.5 + 67.02 = 459.52 Total volume (459.02) < tank capacity (785) So, there is no overflow in tank input : H = 5, r = 3 h = 3 N = 3, R = 2 output : Overflow Explanation: water tank capacity = 3.14 * r * r * H = 3.14 * 3 * 3 * 5 = 141.3 volume of water in tank = 3.14 * r * r * h = 3.14 * 3 * 3 * 3 = 84.78 volume of balls = N * (4/3) * 3.14 * R * R * R = 3 * (4/3) * 3.14 * 2 * 2 * 2 = 100.48 Total volume of water + dip balls = 84.78 + 100.48 = 185.26 Total volume (185.26) > tank capacity (141.3) So, tank will overflow Approach: When solid balls are dipped in water, level of water increases, hence volume of water will also increase. Increasing in water volume = Total volume of dip ballsVolume of Cylinder = 3.14 * r * r * h where: r: radius of tank h: height of tankNumber of balls are n Balls have shape of Sphere Volume of Sphere = (4/3) * 3.14 * R * R * R Where R: Sphere’s(solid ball) radiusAfter dipping all balls, if the total volume of water and all balls is less than or equal to the total volume of tank capacity then there will no overflow in tank, otherwise there will be overflow.Below is the implementation of above approach: C++ Java Python3 C# PHP Javascript // C++ Program to check if water tank// overflows when n solid balls are// dipped in the water tank#include <bits/stdc++.h>using namespace std; // function to find if tak will// overflow or notvoid overflow(int H, int r, int h, int N, int R){ // cylinder capacity float tank_cap = 3.14 * r * r * H; // volume of water in tank float water_vol = 3.14 * r * r * h; // volume of n balls float balls_vol = N * (4 / 3) * 3.14 * R * R * R; // total volume of water // and n dipped balls float vol = water_vol + balls_vol; /* condition to check if tank is in overflow state or not */ if (vol > tank_cap) { cout << "Overflow" << endl; } else { cout << "Not in overflow state" << endl; }} // main functionint main(){ // giving dimensions int H = 10, r = 5, h = 5, N = 2, R = 2; // calling function overflow(H, r, h, N, R); return 0;} // JAVA Code for Program to check if// water tank overflowsimport java.util.*; class GFG { // function to find if tak will // overflow or not static void overflow(int H, int r, int h, int N, int R) { // cylinder capacity double tank_cap = 3.14 * r * r * H; // volume of water in tank double water_vol = 3.14 * r * r * h; // volume of n balls double balls_vol = N * (4 / 3) * 3.14 * R * R * R; // total volume of water // and n dipped balls double vol = water_vol + balls_vol; /* condition to check if tank is in overflow state or not */ if (vol > tank_cap) { System.out.println("Overflow"); } else { System.out.println("Not in overflow state"); } } /* Driver program to test above function */ public static void main(String[] args) { // giving dimensions int H = 10, r = 5, h = 5, N = 2, R = 2; // calling function overflow(H, r, h, N, R); }} // This code is contributed by Arnav Kr. Mandal. # Python code to check if water tank# overflows when n solid balls are# dipped in the water tank # function to find if tak will# overflow or notdef overflow( H, r, h, N, R ): # cylinder capacity tank_cap = 3.14 * r * r * H # volume of water in tank water_vol = 3.14 * r * r * h # volume of n balls balls_vol = N * (4 / 3) * 3.14 * R * R * R # total volume of water # and n dipped balls vol = water_vol + balls_vol # condition to check if tank is in # overflow state or not if vol > tank_cap: print("Overflow") else: print("Not in overflow state") # Driver code # giving dimensionsH = 10r = 5h = 5N = 2R = 2 # calling functionoverflow (H, r, h, N, R) # This code is contributed by "Sharad_Bhardwaj". // C# Code for Program to check if// water tank overflowsusing System; class GFG { // function to find if tak will // overflow or not static void overflow(int H, int r, int h, int N, int R) { // cylinder capacity double tank_cap = 3.14 * r * r * H; // volume of water in tank double water_vol = 3.14 * r * r * h; // volume of n balls double balls_vol = N * (4 / 3) * 3.14 * R * R * R; // total volume of water // and n dipped balls double vol = water_vol + balls_vol; /* condition to check if tank is in overflow state or not */ if (vol > tank_cap) { Console.WriteLine("Overflow"); } else { Console.WriteLine("Not in overflow state"); } } /* Driver program to test above function */ public static void Main() { // giving dimensions int H = 10, r = 5, h = 5, N = 2, R = 2; // calling function overflow(H, r, h, N, R); }} // This code is contributed by vt_M. <?php// PHP Program to check if water tank// overflows when n solid balls are// dipped in the water tank // function to find if tank// will overflow or not function overflow($H, $r, $h, $N, $R){ // cylinder capacity $tank_cap = 3.14 * $r * $r * $H; // volume of water in tank $water_vol = 3.14 * $r * $r * $h; // volume of n balls $balls_vol = $N * (4/3) * 3.14 * $R * $R * $R; // total volume of water // and n dipped balls $vol = $water_vol + $balls_vol; // condition to check if tank // is in overflow state or not if($vol > $tank_cap) { echo "Overflow", "\n"; } else { echo "Not in overflow state", "\n"; }} // Driver Code// giving dimensions$H = 10; $r = 5; $h = 5;$N = 2; $R = 2; // calling function overflow ($H, $r, $h, $N, $R); // This code is contributed by aj_36?> <script> // JavaScript program for Program to check if// water tank overflows // function to find if tak will // overflow or not function overflow(H, r, h, N, R) { // cylinder capacity let tank_cap = 3.14 * r * r * H; // volume of water in tank let water_vol = 3.14 * r * r * h; // volume of n balls let balls_vol = N * (4 / 3) * 3.14 * R * R * R; // total volume of water // and n dipped balls let vol = water_vol + balls_vol; /* condition to check if tank is in overflow state or not */ if (vol > tank_cap) { document.write("Overflow"); } else { document.write("Not in overflow state"); } } // Driver Code // giving dimensions let H = 10, r = 5, h = 5, N = 2, R = 2; // calling function overflow(H, r, h, N, R); // This code is contributed by chinmoy1997pal.</script> Output : Not in overflow state Time Complexity: O(1) Auxiliary Space: O(1) jit_t chinmoy1997pal mailaruyashaswi Geometric Mathematical Technical Scripter Mathematical Geometric Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Program for distance between two points on earth Optimum location of point to minimize total distance Line Clipping | Set 1 (Cohen–Sutherland Algorithm) Convex Hull | Set 1 (Jarvis's Algorithm or Wrapping) Check whether a given point lies inside a triangle or not Program for Fibonacci numbers Set in C++ Standard Template Library (STL) Write a program to print all permutations of a given string C++ Data Types Merge two sorted arrays
[ { "code": null, "e": 52, "s": 24, "text": "\n22 Jun, 2022" }, { "code": null, "e": 254, "s": 52, "text": "Given the dimensions of cylindrical water tank, spherical solid balls and the amount of water present in the tank check if water tank will overflow when balls are dipped in the water tank. Examples : " }, { "code": null, "e": 1476, "s": 254, "text": "input : H = 10, r = 5\n h = 5\n N = 2, R = 2\noutput : Not in overflow state\nExplanation :\nwater tank capacity = 3.14 * r * r * H\n = 3.14 * 5 * 5 * 10\n = 785 \n\nvolume of water in tank = 3.14 * r * r * h\n = 3.14 * 5 * 5 * 5\n = 392.5\n \nVolume of balls = N * (4/3) * 3.14 * R * R * R\n = 2 * (4/3) * 3.14 * 2 * 2 * 2\n = 67.02\nTotal volume of water + dip balls = 392.5 + 67.02\n = 459.52\n\nTotal volume (459.02) < tank capacity (785)\nSo, there is no overflow in tank\n\ninput : H = 5, r = 3 \n h = 3\n N = 3, R = 2\noutput : Overflow\nExplanation:\nwater tank capacity = 3.14 * r * r * H\n = 3.14 * 3 * 3 * 5\n = 141.3\n\nvolume of water in tank = 3.14 * r * r * h\n = 3.14 * 3 * 3 * 3\n = 84.78\n\nvolume of balls = N * (4/3) * 3.14 * R * R * R\n = 3 * (4/3) * 3.14 * 2 * 2 * 2\n = 100.48\n\nTotal volume of water + dip balls = 84.78 + 100.48\n = 185.26\n\nTotal volume (185.26) > tank capacity (141.3)\nSo, tank will overflow" }, { "code": null, "e": 2101, "s": 1476, "text": "Approach: When solid balls are dipped in water, level of water increases, hence volume of water will also increase. Increasing in water volume = Total volume of dip ballsVolume of Cylinder = 3.14 * r * r * h where: r: radius of tank h: height of tankNumber of balls are n Balls have shape of Sphere Volume of Sphere = (4/3) * 3.14 * R * R * R Where R: Sphere’s(solid ball) radiusAfter dipping all balls, if the total volume of water and all balls is less than or equal to the total volume of tank capacity then there will no overflow in tank, otherwise there will be overflow.Below is the implementation of above approach: " }, { "code": null, "e": 2105, "s": 2101, "text": "C++" }, { "code": null, "e": 2110, "s": 2105, "text": "Java" }, { "code": null, "e": 2118, "s": 2110, "text": "Python3" }, { "code": null, "e": 2121, "s": 2118, "text": "C#" }, { "code": null, "e": 2125, "s": 2121, "text": "PHP" }, { "code": null, "e": 2136, "s": 2125, "text": "Javascript" }, { "code": "// C++ Program to check if water tank// overflows when n solid balls are// dipped in the water tank#include <bits/stdc++.h>using namespace std; // function to find if tak will// overflow or notvoid overflow(int H, int r, int h, int N, int R){ // cylinder capacity float tank_cap = 3.14 * r * r * H; // volume of water in tank float water_vol = 3.14 * r * r * h; // volume of n balls float balls_vol = N * (4 / 3) * 3.14 * R * R * R; // total volume of water // and n dipped balls float vol = water_vol + balls_vol; /* condition to check if tank is in overflow state or not */ if (vol > tank_cap) { cout << \"Overflow\" << endl; } else { cout << \"Not in overflow state\" << endl; }} // main functionint main(){ // giving dimensions int H = 10, r = 5, h = 5, N = 2, R = 2; // calling function overflow(H, r, h, N, R); return 0;}", "e": 3071, "s": 2136, "text": null }, { "code": "// JAVA Code for Program to check if// water tank overflowsimport java.util.*; class GFG { // function to find if tak will // overflow or not static void overflow(int H, int r, int h, int N, int R) { // cylinder capacity double tank_cap = 3.14 * r * r * H; // volume of water in tank double water_vol = 3.14 * r * r * h; // volume of n balls double balls_vol = N * (4 / 3) * 3.14 * R * R * R; // total volume of water // and n dipped balls double vol = water_vol + balls_vol; /* condition to check if tank is in overflow state or not */ if (vol > tank_cap) { System.out.println(\"Overflow\"); } else { System.out.println(\"Not in overflow state\"); } } /* Driver program to test above function */ public static void main(String[] args) { // giving dimensions int H = 10, r = 5, h = 5, N = 2, R = 2; // calling function overflow(H, r, h, N, R); }} // This code is contributed by Arnav Kr. Mandal.", "e": 4187, "s": 3071, "text": null }, { "code": "# Python code to check if water tank# overflows when n solid balls are# dipped in the water tank # function to find if tak will# overflow or notdef overflow( H, r, h, N, R ): # cylinder capacity tank_cap = 3.14 * r * r * H # volume of water in tank water_vol = 3.14 * r * r * h # volume of n balls balls_vol = N * (4 / 3) * 3.14 * R * R * R # total volume of water # and n dipped balls vol = water_vol + balls_vol # condition to check if tank is in # overflow state or not if vol > tank_cap: print(\"Overflow\") else: print(\"Not in overflow state\") # Driver code # giving dimensionsH = 10r = 5h = 5N = 2R = 2 # calling functionoverflow (H, r, h, N, R) # This code is contributed by \"Sharad_Bhardwaj\".", "e": 4960, "s": 4187, "text": null }, { "code": "// C# Code for Program to check if// water tank overflowsusing System; class GFG { // function to find if tak will // overflow or not static void overflow(int H, int r, int h, int N, int R) { // cylinder capacity double tank_cap = 3.14 * r * r * H; // volume of water in tank double water_vol = 3.14 * r * r * h; // volume of n balls double balls_vol = N * (4 / 3) * 3.14 * R * R * R; // total volume of water // and n dipped balls double vol = water_vol + balls_vol; /* condition to check if tank is in overflow state or not */ if (vol > tank_cap) { Console.WriteLine(\"Overflow\"); } else { Console.WriteLine(\"Not in overflow state\"); } } /* Driver program to test above function */ public static void Main() { // giving dimensions int H = 10, r = 5, h = 5, N = 2, R = 2; // calling function overflow(H, r, h, N, R); }} // This code is contributed by vt_M.", "e": 6041, "s": 4960, "text": null }, { "code": "<?php// PHP Program to check if water tank// overflows when n solid balls are// dipped in the water tank // function to find if tank// will overflow or not function overflow($H, $r, $h, $N, $R){ // cylinder capacity $tank_cap = 3.14 * $r * $r * $H; // volume of water in tank $water_vol = 3.14 * $r * $r * $h; // volume of n balls $balls_vol = $N * (4/3) * 3.14 * $R * $R * $R; // total volume of water // and n dipped balls $vol = $water_vol + $balls_vol; // condition to check if tank // is in overflow state or not if($vol > $tank_cap) { echo \"Overflow\", \"\\n\"; } else { echo \"Not in overflow state\", \"\\n\"; }} // Driver Code// giving dimensions$H = 10; $r = 5; $h = 5;$N = 2; $R = 2; // calling function overflow ($H, $r, $h, $N, $R); // This code is contributed by aj_36?>", "e": 7007, "s": 6041, "text": null }, { "code": "<script> // JavaScript program for Program to check if// water tank overflows // function to find if tak will // overflow or not function overflow(H, r, h, N, R) { // cylinder capacity let tank_cap = 3.14 * r * r * H; // volume of water in tank let water_vol = 3.14 * r * r * h; // volume of n balls let balls_vol = N * (4 / 3) * 3.14 * R * R * R; // total volume of water // and n dipped balls let vol = water_vol + balls_vol; /* condition to check if tank is in overflow state or not */ if (vol > tank_cap) { document.write(\"Overflow\"); } else { document.write(\"Not in overflow state\"); } } // Driver Code // giving dimensions let H = 10, r = 5, h = 5, N = 2, R = 2; // calling function overflow(H, r, h, N, R); // This code is contributed by chinmoy1997pal.</script>", "e": 8001, "s": 7007, "text": null }, { "code": null, "e": 8012, "s": 8001, "text": "Output : " }, { "code": null, "e": 8034, "s": 8012, "text": "Not in overflow state" }, { "code": null, "e": 8056, "s": 8034, "text": "Time Complexity: O(1)" }, { "code": null, "e": 8079, "s": 8056, "text": "Auxiliary Space: O(1) " }, { "code": null, "e": 8085, "s": 8079, "text": "jit_t" }, { "code": null, "e": 8100, "s": 8085, "text": "chinmoy1997pal" }, { "code": null, "e": 8116, "s": 8100, "text": "mailaruyashaswi" }, { "code": null, "e": 8126, "s": 8116, "text": "Geometric" }, { "code": null, "e": 8139, "s": 8126, "text": "Mathematical" }, { "code": null, "e": 8158, "s": 8139, "text": "Technical Scripter" }, { "code": null, "e": 8171, "s": 8158, "text": "Mathematical" }, { "code": null, "e": 8181, "s": 8171, "text": "Geometric" }, { "code": null, "e": 8279, "s": 8181, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 8328, "s": 8279, "text": "Program for distance between two points on earth" }, { "code": null, "e": 8381, "s": 8328, "text": "Optimum location of point to minimize total distance" }, { "code": null, "e": 8432, "s": 8381, "text": "Line Clipping | Set 1 (Cohen–Sutherland Algorithm)" }, { "code": null, "e": 8485, "s": 8432, "text": "Convex Hull | Set 1 (Jarvis's Algorithm or Wrapping)" }, { "code": null, "e": 8543, "s": 8485, "text": "Check whether a given point lies inside a triangle or not" }, { "code": null, "e": 8573, "s": 8543, "text": "Program for Fibonacci numbers" }, { "code": null, "e": 8616, "s": 8573, "text": "Set in C++ Standard Template Library (STL)" }, { "code": null, "e": 8676, "s": 8616, "text": "Write a program to print all permutations of a given string" }, { "code": null, "e": 8691, "s": 8676, "text": "C++ Data Types" } ]