title
stringlengths
3
221
text
stringlengths
17
477k
parsed
listlengths
0
3.17k
Multi-Line Comment in Shell Script
09 Feb, 2022 Comments are quite a crucial part of a program or a code-base. It helps in understanding the code, improves code-readability, and also helps in enhancing the structure of the program. We often write single-line comments in our programs as they are quite self-explanatory and require few words to describe the flow of the program or any message about the particular section. There are rare cases where we want several lines of messages or comment on an entire code block for debugging or any other reasons. We need to have a multiline comment in our program. There are two different ways to use multi-line comment in Shell Scripts: Method 1: Using <<comment: In Shell or Bash shell, we can comment on multiple lines using << and name of comment. we start a comment block with << and name anything to the block and wherever we want to stop the comment, we will simply type the name of the comment. <<comment "Code" or "Comments" comment The word “comment” can be anything but it should be the same for ending the comment block. #!/bin/bash echo "Sample code" x=4 if [[ $x -le 10 ]];then echo "Less than 10" if <<com echo"This doesn't echo" echo"Even this doesn't" com echo "OK, this is echoing after <<com !" Output: Method 2: Using : ‘ : There is also another way to comment in Bash using : ‘ operator. : ' Code or Comment here ' Code: #!/bin/bash echo "Sample code" x=4 if [[ $x -le 10 ]];then echo "Less than 10" if : ' echo"This doesn't echo" echo"Even this doesn't" ' echo "OK, this is working with : '" Output: So this script also comments multiple lines, we need to be careful here with including a space before the end block ‘ , otherwise it would not work. It also applies to the start comment block : ‘, there is a space in between those characters. rkbhola5 Picked Shell Script Linux-Unix Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. ZIP command in Linux with examples tar command in Linux with examples curl command in Linux with Examples Conditional Statements | Shell Script Tail command in Linux with examples TCP Server-Client implementation in C Docker - COPY Instruction UDP Server-Client implementation in C scp command in Linux with Examples echo command in Linux with Examples
[ { "code": null, "e": 52, "s": 24, "text": "\n09 Feb, 2022" }, { "code": null, "e": 612, "s": 52, "text": "Comments are quite a crucial part of a program or a code-base. It helps in understanding the code, improves code-readability, and also helps in enhancing the structure of the program. We often write single-line comments in our programs as they are quite self-explanatory and require few words to describe the flow of the program or any message about the particular section. There are rare cases where we want several lines of messages or comment on an entire code block for debugging or any other reasons. We need to have a multiline comment in our program. " }, { "code": null, "e": 685, "s": 612, "text": "There are two different ways to use multi-line comment in Shell Scripts:" }, { "code": null, "e": 712, "s": 685, "text": "Method 1: Using <<comment:" }, { "code": null, "e": 951, "s": 712, "text": "In Shell or Bash shell, we can comment on multiple lines using << and name of comment. we start a comment block with << and name anything to the block and wherever we want to stop the comment, we will simply type the name of the comment." }, { "code": null, "e": 991, "s": 951, "text": "<<comment\n \"Code\" or \"Comments\"\ncomment" }, { "code": null, "e": 1082, "s": 991, "text": "The word “comment” can be anything but it should be the same for ending the comment block." }, { "code": null, "e": 1269, "s": 1082, "text": "#!/bin/bash\necho \"Sample code\"\nx=4\nif [[ $x -le 10 ]];then\n echo \"Less than 10\"\nif\n\n<<com\necho\"This doesn't echo\"\n\necho\"Even this doesn't\"\ncom\necho \"OK, this is echoing after <<com !\"" }, { "code": null, "e": 1277, "s": 1269, "text": "Output:" }, { "code": null, "e": 1301, "s": 1277, "text": "Method 2: Using : ‘ : " }, { "code": null, "e": 1366, "s": 1301, "text": "There is also another way to comment in Bash using : ‘ operator." }, { "code": null, "e": 1395, "s": 1366, "text": ": '\n\nCode or Comment here\n '" }, { "code": null, "e": 1401, "s": 1395, "text": "Code:" }, { "code": null, "e": 1580, "s": 1401, "text": "#!/bin/bash\necho \"Sample code\"\nx=4\nif [[ $x -le 10 ]];then\n echo \"Less than 10\"\nif\n\n: '\necho\"This doesn't echo\"\n\necho\"Even this doesn't\"\n '\necho \"OK, this is working with : '\"" }, { "code": null, "e": 1588, "s": 1580, "text": "Output:" }, { "code": null, "e": 1831, "s": 1588, "text": "So this script also comments multiple lines, we need to be careful here with including a space before the end block ‘ , otherwise it would not work. It also applies to the start comment block : ‘, there is a space in between those characters." }, { "code": null, "e": 1840, "s": 1831, "text": "rkbhola5" }, { "code": null, "e": 1847, "s": 1840, "text": "Picked" }, { "code": null, "e": 1860, "s": 1847, "text": "Shell Script" }, { "code": null, "e": 1871, "s": 1860, "text": "Linux-Unix" }, { "code": null, "e": 1969, "s": 1871, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 2004, "s": 1969, "text": "ZIP command in Linux with examples" }, { "code": null, "e": 2039, "s": 2004, "text": "tar command in Linux with examples" }, { "code": null, "e": 2075, "s": 2039, "text": "curl command in Linux with Examples" }, { "code": null, "e": 2113, "s": 2075, "text": "Conditional Statements | Shell Script" }, { "code": null, "e": 2149, "s": 2113, "text": "Tail command in Linux with examples" }, { "code": null, "e": 2187, "s": 2149, "text": "TCP Server-Client implementation in C" }, { "code": null, "e": 2213, "s": 2187, "text": "Docker - COPY Instruction" }, { "code": null, "e": 2251, "s": 2213, "text": "UDP Server-Client implementation in C" }, { "code": null, "e": 2286, "s": 2251, "text": "scp command in Linux with Examples" } ]
Seeds (Or Seed Roots) of a number
04 May, 2021 A Seed of a number n is a number x such that multiplication of x with its digits is equal to n. The task is to find all seeds of a given number n. If no seed exists, then print the same.Examples: Input : n = 138 Output : 23 23 is a seed of 138 because 23*2*3 is equal to 138 Input : n = 4977 Output : 79 711 79 is a seed of 4977 because 79 * 7 * 9 = 4977. 711 is also a seed of 4977 because 711 * 1 * 1 * 7 = 4977 Input : n = 9 Output : No seed exists Input : n = 738 Output : 123 Asked in Epic The idea is to traverse all numbers from 1 to n/2. For every number being traversed, find product of digits with the number. An important optimization done in below program is to avoid re-computations of digit products. We store the products in an array. If a product has already been computed, we return it, else we compute it.Below is the implementation of the idea. C++ Java Python3 C# PHP Javascript // C++ program to find Seed of a number#include <bits/stdc++.h>using namespace std;const int MAX = 10000; int prodDig[MAX]; // Stores product of digits of x in prodDig[x]int getDigitProduct(int x){ // If x has single digit if (x < 10) return x; // If digit product is already computed if (prodDig[x] != 0) return prodDig[x]; // If digit product is not computed before. int prod = (x % 10) * getDigitProduct(x/10); return (prodDig[x] = prod);} // Prints all seeds of nvoid findSeed(int n){ // Find all seeds using prodDig[] vector<int> res; for (int i=1; i<=n/2; i++) if (i*getDigitProduct(i) == n) res.push_back(i); // If there was no seed if (res.size() == 0) { cout << "NO seed exists\n"; return; } // Print seeds for (int i=0; i<res.size(); i++) cout << res[i] << " ";} // Driver codeint main(){ long long int n = 138; findSeed(n); return 0;} // Java program to find Seed of a numberimport java.util.*; class GFg{static int MAX = 10000;static int[] prodDig=new int[MAX]; // Stores product of digits of x in prodDig[x]static int getDigitProduct(int x){ // If x has single digit if (x < 10) return x; // If digit product is already computed if (prodDig[x] != 0) return prodDig[x]; // If digit product is not computed before. int prod = (x % 10) * getDigitProduct(x/10); return (prodDig[x] = prod);} // Prints all seeds of nstatic void findSeed(int n){ // Find all seeds using prodDig[] List<Integer> res = new ArrayList<Integer>(); for (int i=1; i<=n/2; i++) if (i*getDigitProduct(i) == n) res.add(i); // If there was no seed if (res.size() == 0) { System.out.println("NO seed exists"); return; } // Print seeds for (int i=0; i<res.size(); i++) System.out.print(res.get(i)+" ");} // Driver codepublic static void main(String[] args){ int n = 138; findSeed(n); }}// this code is contributed by mits # Python3 program to find Seed of a number MAX = 10000; prodDig = [0] * MAX; # Stores product of digits of# x in prodDig[x]def getDigitProduct(x): # If x has single digit if (x < 10): return x; # If digit product is already computed if (prodDig[x] != 0): return prodDig[x]; # If digit product is not computed before. prod = (int(x % 10) * getDigitProduct(int(x / 10))); prodDig[x] = prod; return prod; # Prints all seeds of ndef findSeed(n): # Find all seeds using prodDig[] res = []; for i in range(1, int(n / 2 + 2)): if (i * getDigitProduct(i) == n): res.append(i); # If there was no seed if (len(res) == 0): print("NO seed exists"); return; # Print seeds for i in range(len(res)): print(res[i], end = " "); # Driver coden = 138;findSeed(n); # This code is contributed by mits // C# program to find Seed of a numberusing System;using System.Collections; class GFG{ static int MAX = 10000;static int[] prodDig=new int[MAX]; // Stores product of digits of x in prodDig[x]static int getDigitProduct(int x){ // If x has single digit if (x < 10) return x; // If digit product is already computed if (prodDig[x] != 0) return prodDig[x]; // If digit product is not computed before. int prod = (x % 10) * getDigitProduct(x/10); return (prodDig[x] = prod);} // Prints all seeds of nstatic void findSeed(int n){ // Find all seeds using prodDig[] ArrayList res = new ArrayList(); for (int i=1; i<=n/2; i++) if (i*getDigitProduct(i) == n) res.Add(i); // If there was no seed if (res.Count == 0) { Console.WriteLine("NO seed exists"); return; } // Print seeds for (int i=0; i<res.Count; i++) Console.WriteLine(res[i]+" ");} // Driver codestatic void Main(){ int n = 138; findSeed(n); }}// this code is contributed by mits <?php// PHP program to find Seed of a number $MAX = 10000; $prodDig = array_fill(0, $MAX, 0); // Stores product of digits of x in prodDig[x]function getDigitProduct($x){ global $prodDig; // If x has single digit if ($x < 10) return $x; // If digit product is already computed if ($prodDig[$x] != 0) return $prodDig[$x]; // If digit product is not computed before. $prod = (int)($x % 10) * getDigitProduct((int)($x / 10)); $prodDig[$x] = $prod; return $prod;} // Prints all seeds of nfunction findSeed($n){ // Find all seeds using prodDig[] $res = array(); for ($i = 1; $i <= (int)($n / 2 + 1); $i++) if ($i * getDigitProduct($i) == $n) array_push($res, $i); // If there was no seed if (count($res) == 0) { echo "NO seed exists\n"; return; } // Print seeds for ($i = 0; $i < count($res); $i++) echo $res[$i] . " ";} // Driver code$n = 138;findSeed($n); // This code is contributed by mits?> <script> // Javascript program to find Seed of a number var MAX = 10000;var prodDig=Array.from({length: MAX}, (_, i) => 0); // Stores product of digits of x in prodDig[x]function getDigitProduct(x){ // If x has single digit if (x < 10) return x; // If digit product is already computed if (prodDig[x] != 0) return prodDig[x]; // If digit product is not computed before. var prod = (x % 10) * getDigitProduct(parseInt(x/10)); return (prodDig[x] = prod);} // Prints all seeds of nfunction findSeed(n){ // Find all seeds using prodDig var res = []; for (var i=1; i<=parseInt(n/2); i++) if (i*getDigitProduct(i) == n) res.push(i); // If there was no seed if (res.length == 0) { document.write("NO seed exists"); return; } // Print seeds for (i=0; i<res.length; i++) document.write(res[i]+" ");} // Driver codevar n = 138;findSeed(n); // This code is contributed by 29AjayKumar </script> Output : 23 Further Optimization : We can further optimize above code. The idea is to make a call to getDigitProduct(i) only if i is divisible by n. Please refer https://ide.geeksforgeeks.org/oLYduu for implementation.This article is contributed by Rakesh Kumar. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. Mithun Kumar 29AjayKumar number-digits Mathematical Mathematical Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Algorithm to solve Rubik's Cube Merge two sorted arrays with O(1) extra space Program to print prime numbers from 1 to N. Find next greater number with same set of digits Segment Tree | Set 1 (Sum of given range) Check if a number is Palindrome Count ways to reach the n'th stair Count all possible paths from top left to bottom right of a mXn matrix Fizz Buzz Implementation Product of Array except itself
[ { "code": null, "e": 52, "s": 24, "text": "\n04 May, 2021" }, { "code": null, "e": 250, "s": 52, "text": "A Seed of a number n is a number x such that multiplication of x with its digits is equal to n. The task is to find all seeds of a given number n. If no seed exists, then print the same.Examples: " }, { "code": null, "e": 544, "s": 250, "text": "Input : n = 138\nOutput : 23 \n23 is a seed of 138 because\n23*2*3 is equal to 138\n\nInput : n = 4977\nOutput : 79 711 \n79 is a seed of 4977 because\n79 * 7 * 9 = 4977.\n711 is also a seed of 4977 because\n711 * 1 * 1 * 7 = 4977\n\nInput : n = 9\nOutput : No seed exists\n\nInput : n = 738\nOutput : 123 " }, { "code": null, "e": 559, "s": 544, "text": "Asked in Epic " }, { "code": null, "e": 930, "s": 559, "text": "The idea is to traverse all numbers from 1 to n/2. For every number being traversed, find product of digits with the number. An important optimization done in below program is to avoid re-computations of digit products. We store the products in an array. If a product has already been computed, we return it, else we compute it.Below is the implementation of the idea. " }, { "code": null, "e": 934, "s": 930, "text": "C++" }, { "code": null, "e": 939, "s": 934, "text": "Java" }, { "code": null, "e": 947, "s": 939, "text": "Python3" }, { "code": null, "e": 950, "s": 947, "text": "C#" }, { "code": null, "e": 954, "s": 950, "text": "PHP" }, { "code": null, "e": 965, "s": 954, "text": "Javascript" }, { "code": "// C++ program to find Seed of a number#include <bits/stdc++.h>using namespace std;const int MAX = 10000; int prodDig[MAX]; // Stores product of digits of x in prodDig[x]int getDigitProduct(int x){ // If x has single digit if (x < 10) return x; // If digit product is already computed if (prodDig[x] != 0) return prodDig[x]; // If digit product is not computed before. int prod = (x % 10) * getDigitProduct(x/10); return (prodDig[x] = prod);} // Prints all seeds of nvoid findSeed(int n){ // Find all seeds using prodDig[] vector<int> res; for (int i=1; i<=n/2; i++) if (i*getDigitProduct(i) == n) res.push_back(i); // If there was no seed if (res.size() == 0) { cout << \"NO seed exists\\n\"; return; } // Print seeds for (int i=0; i<res.size(); i++) cout << res[i] << \" \";} // Driver codeint main(){ long long int n = 138; findSeed(n); return 0;}", "e": 1923, "s": 965, "text": null }, { "code": "// Java program to find Seed of a numberimport java.util.*; class GFg{static int MAX = 10000;static int[] prodDig=new int[MAX]; // Stores product of digits of x in prodDig[x]static int getDigitProduct(int x){ // If x has single digit if (x < 10) return x; // If digit product is already computed if (prodDig[x] != 0) return prodDig[x]; // If digit product is not computed before. int prod = (x % 10) * getDigitProduct(x/10); return (prodDig[x] = prod);} // Prints all seeds of nstatic void findSeed(int n){ // Find all seeds using prodDig[] List<Integer> res = new ArrayList<Integer>(); for (int i=1; i<=n/2; i++) if (i*getDigitProduct(i) == n) res.add(i); // If there was no seed if (res.size() == 0) { System.out.println(\"NO seed exists\"); return; } // Print seeds for (int i=0; i<res.size(); i++) System.out.print(res.get(i)+\" \");} // Driver codepublic static void main(String[] args){ int n = 138; findSeed(n); }}// this code is contributed by mits", "e": 2980, "s": 1923, "text": null }, { "code": "# Python3 program to find Seed of a number MAX = 10000; prodDig = [0] * MAX; # Stores product of digits of# x in prodDig[x]def getDigitProduct(x): # If x has single digit if (x < 10): return x; # If digit product is already computed if (prodDig[x] != 0): return prodDig[x]; # If digit product is not computed before. prod = (int(x % 10) * getDigitProduct(int(x / 10))); prodDig[x] = prod; return prod; # Prints all seeds of ndef findSeed(n): # Find all seeds using prodDig[] res = []; for i in range(1, int(n / 2 + 2)): if (i * getDigitProduct(i) == n): res.append(i); # If there was no seed if (len(res) == 0): print(\"NO seed exists\"); return; # Print seeds for i in range(len(res)): print(res[i], end = \" \"); # Driver coden = 138;findSeed(n); # This code is contributed by mits", "e": 3880, "s": 2980, "text": null }, { "code": "// C# program to find Seed of a numberusing System;using System.Collections; class GFG{ static int MAX = 10000;static int[] prodDig=new int[MAX]; // Stores product of digits of x in prodDig[x]static int getDigitProduct(int x){ // If x has single digit if (x < 10) return x; // If digit product is already computed if (prodDig[x] != 0) return prodDig[x]; // If digit product is not computed before. int prod = (x % 10) * getDigitProduct(x/10); return (prodDig[x] = prod);} // Prints all seeds of nstatic void findSeed(int n){ // Find all seeds using prodDig[] ArrayList res = new ArrayList(); for (int i=1; i<=n/2; i++) if (i*getDigitProduct(i) == n) res.Add(i); // If there was no seed if (res.Count == 0) { Console.WriteLine(\"NO seed exists\"); return; } // Print seeds for (int i=0; i<res.Count; i++) Console.WriteLine(res[i]+\" \");} // Driver codestatic void Main(){ int n = 138; findSeed(n); }}// this code is contributed by mits", "e": 4920, "s": 3880, "text": null }, { "code": "<?php// PHP program to find Seed of a number $MAX = 10000; $prodDig = array_fill(0, $MAX, 0); // Stores product of digits of x in prodDig[x]function getDigitProduct($x){ global $prodDig; // If x has single digit if ($x < 10) return $x; // If digit product is already computed if ($prodDig[$x] != 0) return $prodDig[$x]; // If digit product is not computed before. $prod = (int)($x % 10) * getDigitProduct((int)($x / 10)); $prodDig[$x] = $prod; return $prod;} // Prints all seeds of nfunction findSeed($n){ // Find all seeds using prodDig[] $res = array(); for ($i = 1; $i <= (int)($n / 2 + 1); $i++) if ($i * getDigitProduct($i) == $n) array_push($res, $i); // If there was no seed if (count($res) == 0) { echo \"NO seed exists\\n\"; return; } // Print seeds for ($i = 0; $i < count($res); $i++) echo $res[$i] . \" \";} // Driver code$n = 138;findSeed($n); // This code is contributed by mits?>", "e": 5936, "s": 4920, "text": null }, { "code": "<script> // Javascript program to find Seed of a number var MAX = 10000;var prodDig=Array.from({length: MAX}, (_, i) => 0); // Stores product of digits of x in prodDig[x]function getDigitProduct(x){ // If x has single digit if (x < 10) return x; // If digit product is already computed if (prodDig[x] != 0) return prodDig[x]; // If digit product is not computed before. var prod = (x % 10) * getDigitProduct(parseInt(x/10)); return (prodDig[x] = prod);} // Prints all seeds of nfunction findSeed(n){ // Find all seeds using prodDig var res = []; for (var i=1; i<=parseInt(n/2); i++) if (i*getDigitProduct(i) == n) res.push(i); // If there was no seed if (res.length == 0) { document.write(\"NO seed exists\"); return; } // Print seeds for (i=0; i<res.length; i++) document.write(res[i]+\" \");} // Driver codevar n = 138;findSeed(n); // This code is contributed by 29AjayKumar </script>", "e": 6928, "s": 5936, "text": null }, { "code": null, "e": 6938, "s": 6928, "text": "Output : " }, { "code": null, "e": 6941, "s": 6938, "text": "23" }, { "code": null, "e": 7567, "s": 6941, "text": "Further Optimization : We can further optimize above code. The idea is to make a call to getDigitProduct(i) only if i is divisible by n. Please refer https://ide.geeksforgeeks.org/oLYduu for implementation.This article is contributed by Rakesh Kumar. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. " }, { "code": null, "e": 7580, "s": 7567, "text": "Mithun Kumar" }, { "code": null, "e": 7592, "s": 7580, "text": "29AjayKumar" }, { "code": null, "e": 7606, "s": 7592, "text": "number-digits" }, { "code": null, "e": 7619, "s": 7606, "text": "Mathematical" }, { "code": null, "e": 7632, "s": 7619, "text": "Mathematical" }, { "code": null, "e": 7730, "s": 7632, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 7762, "s": 7730, "text": "Algorithm to solve Rubik's Cube" }, { "code": null, "e": 7808, "s": 7762, "text": "Merge two sorted arrays with O(1) extra space" }, { "code": null, "e": 7852, "s": 7808, "text": "Program to print prime numbers from 1 to N." }, { "code": null, "e": 7901, "s": 7852, "text": "Find next greater number with same set of digits" }, { "code": null, "e": 7943, "s": 7901, "text": "Segment Tree | Set 1 (Sum of given range)" }, { "code": null, "e": 7975, "s": 7943, "text": "Check if a number is Palindrome" }, { "code": null, "e": 8010, "s": 7975, "text": "Count ways to reach the n'th stair" }, { "code": null, "e": 8081, "s": 8010, "text": "Count all possible paths from top left to bottom right of a mXn matrix" }, { "code": null, "e": 8106, "s": 8081, "text": "Fizz Buzz Implementation" } ]
Minimum number of deletions and insertions to transform one string into another
05 Jan, 2022 Given two strings ‘str1’ and ‘str2’ of size m and n respectively. The task is to remove/delete and insert the minimum number of characters from/in str1 to transform it into str2. It could be possible that the same character needs to be removed/deleted from one point of str1 and inserted to some another point. Example 1: Input : str1 = "heap", str2 = "pea" Output : Minimum Deletion = 2 and Minimum Insertion = 1 Explanation: p and h deleted from heap Then, p is inserted at the beginning One thing to note, though p was required yet it was removed/deleted first from its position and then it is inserted to some other position. Thus, p contributes one to the deletion_count and one to the insertion_count. Example 2: Input : str1 = "geeksforgeeks", str2 = "geeks" Output : Minimum Deletion = 8 Minimum Insertion = 0 Simple Approach: A simple approach is to consider all subsequences of str1 and for each subsequence calculate minimum deletions and insertions so as to transform it into str2. A very complex method and the time complexity of this solution is exponential. Efficient Approach: An efficient approach uses the concept of finding the length of the longest common subsequence of the given two sequences. Algorithm: str1 and str2 be the given strings. m and n be their lengths respectively. len be the length of the longest common subsequence of str1 and str2 minimum number of deletions minDel = m – len minimum number of Insertions minInsert = n – len Below is the implementation of the above code: C++ Java Python3 C# Javascript // Dynamic Programming C++ implementation to find// minimum number of deletions and insertions#include <bits/stdc++.h> using namespace std; // Returns length of longest common subsequence// for str1[0..m-1], str2[0..n-1]int lcs(string str1, string str2, int m, int n){ int L[m + 1][n + 1]; int i, j; // Following steps build L[m+1][n+1] in bottom // up fashion. Note that L[i][j] contains // length of LCS of str1[0..i-1] and str2[0..j-1] for (i = 0; i <= m; i++) { for (j = 0; j <= n; j++) { if (i == 0 || j == 0) L[i][j] = 0; else if (str1.at(i - 1) == str2.at(j - 1)) L[i][j] = L[i - 1][j - 1] + 1; else L[i][j] = max(L[i - 1][j], L[i][j - 1]); } } // L[m][n] contains length of LCS // for X[0..n-1] and Y[0..m-1] return L[m][n];} // function to find minimum number// of deletions and insertionsvoid printMinDelAndInsert(string str1, string str2){ int m = str1.size(); int n = str2.size(); int len = lcs(str1, str2, m, n); cout << "Minimum number of deletions = " << (m - len) << endl; cout << "Minimum number of insertions = " << (n - len) << endl;} // Driver Codeint main(){ string str1 = "heap"; string str2 = "pea"; // Function Call printMinDelAndInsert(str1, str2); return 0;} // Dynamic Programming Java implementation// to find minimum number of deletions and// insertionsimport java.io.*; class GFG { // Returns length of length common // subsequence for str1[0..m-1], // str2[0..n-1] static int lcs(String str1, String str2, int m, int n) { int L[][] = new int[m + 1][n + 1]; int i, j; // Following steps build L[m+1][n+1] in // bottom up fashion. Note that L[i][j] // contains length of LCS of str1[0..i-1] // and str2[0..j-1] for (i = 0; i <= m; i++) { for (j = 0; j <= n; j++) { if (i == 0 || j == 0) L[i][j] = 0; else if (str1.charAt(i - 1) == str2.charAt(j - 1)) L[i][j] = L[i - 1][j - 1] + 1; else L[i][j] = Math.max(L[i - 1][j], L[i][j - 1]); } } // L[m][n] contains length of LCS // for X[0..n-1] and Y[0..m-1] return L[m][n]; } // function to find minimum number // of deletions and insertions static void printMinDelAndInsert(String str1, String str2) { int m = str1.length(); int n = str2.length(); int len = lcs(str1, str2, m, n); System.out.println("Minimum number of " + "deletions = "); System.out.println(m - len); System.out.println("Minimum number of " + "insertions = "); System.out.println(n - len); } // Driver code public static void main(String[] args) { String str1 = new String("heap"); String str2 = new String("pea"); // Function Call printMinDelAndInsert(str1, str2); }}// This code is contributed by Prerna Saini # Dynamic Programming Python3# implementation to find minimum# number of deletions and insertions # Returns length of length# common subsequence for# str1[0..m-1], str2[0..n-1] def lcs(str1, str2, m, n): L = [[0 for i in range(n + 1)] for i in range(m + 1)] # Following steps build L[m+1][n+1] # in bottom up fashion. Note that # L[i][j] contains length of LCS # of str1[0..i-1] and str2[0..j-1] for i in range(m + 1): for j in range(n + 1): if (i == 0 or j == 0): L[i][j] = 0 elif(str1[i - 1] == str2[j - 1]): L[i][j] = L[i - 1][j - 1] + 1 else: L[i][j] = max(L[i - 1][j], L[i][j - 1]) # L[m][n] contains length of LCS # for X[0..n-1] and Y[0..m-1] return L[m][n] # function to find minimum number# of deletions and insertions def printMinDelAndInsert(str1, str2): m = len(str1) n = len(str2) leng = lcs(str1, str2, m, n) print("Minimum number of deletions = ", m - leng, sep=' ') print("Minimum number of insertions = ", n - leng, sep=' ') # Driver Codestr1 = "heap"str2 = "pea" # Function CallprintMinDelAndInsert(str1, str2) # This code is contributed# by sahilshelangia // Dynamic Programming C# implementation// to find minimum number of deletions and// insertionsusing System; class GFG { // Returns length of length common // subsequence for str1[0..m-1], // str2[0..n-1] static int lcs(string str1, string str2, int m, int n) { int[, ] L = new int[m + 1, n + 1]; int i, j; // Following steps build L[m+1][n+1] in // bottom up fashion. Note that L[i][j] // contains length of LCS of str1[0..i-1] // and str2[0..j-1] for (i = 0; i <= m; i++) { for (j = 0; j <= n; j++) { if (i == 0 || j == 0) L[i, j] = 0; else if (str1[i - 1] == str2[j - 1]) L[i, j] = L[i - 1, j - 1] + 1; else L[i, j] = Math.Max(L[i - 1, j], L[i, j - 1]); } } // L[m][n] contains length of LCS // for X[0..n-1] and Y[0..m-1] return L[m, n]; } // function to find minimum number // of deletions and insertions static void printMinDelAndInsert(string str1, string str2) { int m = str1.Length; int n = str2.Length; int len = lcs(str1, str2, m, n); Console.Write("Minimum number of " + "deletions = "); Console.WriteLine(m - len); Console.Write("Minimum number of " + "insertions = "); Console.Write(n - len); } // Driver code public static void Main() { string str1 = new string("heap"); string str2 = new string("pea"); // Function Call printMinDelAndInsert(str1, str2); }} // This code is contributed by nitin mittal. <script> // Dynamic Programming Javascript implementation // to find minimum number of deletions and // insertions // Returns length of length common // subsequence for str1[0..m-1], // str2[0..n-1] function lcs(str1, str2, m, n) { let L = new Array(m + 1); let i, j; for (i = 0; i <= m; i++) { L[i] = new Array(n + 1); for (j = 0; j <= n; j++) { L[i][j] = 0; } } // Following steps build L[m+1][n+1] in // bottom up fashion. Note that L[i][j] // contains length of LCS of str1[0..i-1] // and str2[0..j-1] for (i = 0; i <= m; i++) { for (j = 0; j <= n; j++) { if (i == 0 || j == 0) L[i][j] = 0; else if (str1[i - 1] == str2[j - 1]) L[i][j] = L[i - 1][j - 1] + 1; else L[i][j] = Math.max(L[i - 1][j], L[i][j - 1]); } } // L[m][n] contains length of LCS // for X[0..n-1] and Y[0..m-1] return L[m][n]; } // function to find minimum number // of deletions and insertions function printMinDelAndInsert(str1, str2) { let m = str1.length; let n = str2.length; let len = lcs(str1, str2, m, n); document.write("Minimum number of " + "deletions = "); document.write((m - len) + "</br>"); document.write("Minimum number of " + "insertions = "); document.write((n - len) + "</br>"); } let str1 = "heap"; let str2 = "pea"; // Function Call printMinDelAndInsert(str1, str2); // This code is contributed by rameshtravel07.</script> Minimum number of deletions = 2 Minimum number of insertions = 1 Time Complexity: O(m * n) This method also uses the idea of finding the length of the longest common subsequence of the given two sequences. But this approach is using a top-down approach using memoization. C++ // Dynamic Programming C++ implementation to find// minimum number of deletions and insertions// using memoization technique#include <bits/stdc++.h> using namespace std; int dp[1001][1001]; // Returns length of longest common subsequenceint lcs(string& s1, string& s2, int i, int j){ if (i == 0 || j == 0) { return 0; } if (dp[i][j] != -1) { return dp[i][j]; } if (s1[i - 1] == s2[j - 1]) { return dp[i][j] = 1 + lcs(s1, s2, i - 1, j - 1); } else { return dp[i][j] = max(lcs(s1, s2, i, j - 1), lcs(s1, s2, i - 1, j)); }} // function to find minimum number// of deletions and insertionsvoid printMinDelAndInsert(string str1, string str2){ int m = str1.size(); int n = str2.size(); dp[m][n]; // initialising dp array as -1 memset(dp, -1, sizeof(dp)); int len = lcs(str1, str2, m, n); cout << "Minimum number of deletions = " << (m - len) << endl; cout << "Minimum number of insertions = " << (n - len) << endl;} // driver codeint main(){ string str1 = "heap"; string str2 = "pea"; // Function Call printMinDelAndInsert(str1, str2); return 0;} // This code is contributed by Arun Bang. Minimum number of deletions = 2 Minimum number of insertions = 1 Time complexity: O(m * n)This article is contributed by Ayush Jauhari. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to review-team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. nitin mittal sahilshelangia arstheking97 rameshtravel07 arunbang17 LCS Dynamic Programming Dynamic Programming LCS Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Subset Sum Problem | DP-25 Find if there is a path between two vertices in an undirected graph Floyd Warshall Algorithm | DP-16 Coin Change | DP-7 Matrix Chain Multiplication | DP-8 Bellman–Ford Algorithm | DP-23 Travelling Salesman Problem | Set 1 (Naive and Dynamic Programming) Sieve of Eratosthenes Find minimum number of coins that make a given value Minimum number of jumps to reach end
[ { "code": null, "e": 54, "s": 26, "text": "\n05 Jan, 2022" }, { "code": null, "e": 365, "s": 54, "text": "Given two strings ‘str1’ and ‘str2’ of size m and n respectively. The task is to remove/delete and insert the minimum number of characters from/in str1 to transform it into str2. It could be possible that the same character needs to be removed/deleted from one point of str1 and inserted to some another point." }, { "code": null, "e": 377, "s": 365, "text": "Example 1: " }, { "code": null, "e": 766, "s": 377, "text": "Input : \nstr1 = \"heap\", str2 = \"pea\" \nOutput : \nMinimum Deletion = 2 and\nMinimum Insertion = 1\nExplanation:\np and h deleted from heap\nThen, p is inserted at the beginning\nOne thing to note, though p was required yet\nit was removed/deleted first from its position and\nthen it is inserted to some other position.\nThus, p contributes one to the deletion_count\nand one to the insertion_count." }, { "code": null, "e": 778, "s": 766, "text": "Example 2: " }, { "code": null, "e": 886, "s": 778, "text": "Input : \nstr1 = \"geeksforgeeks\", str2 = \"geeks\"\nOutput : \nMinimum Deletion = 8\nMinimum Insertion = 0 " }, { "code": null, "e": 903, "s": 886, "text": "Simple Approach:" }, { "code": null, "e": 1142, "s": 903, "text": "A simple approach is to consider all subsequences of str1 and for each subsequence calculate minimum deletions and insertions so as to transform it into str2. A very complex method and the time complexity of this solution is exponential. " }, { "code": null, "e": 1162, "s": 1142, "text": "Efficient Approach:" }, { "code": null, "e": 1285, "s": 1162, "text": "An efficient approach uses the concept of finding the length of the longest common subsequence of the given two sequences." }, { "code": null, "e": 1297, "s": 1285, "text": "Algorithm: " }, { "code": null, "e": 1333, "s": 1297, "text": "str1 and str2 be the given strings." }, { "code": null, "e": 1372, "s": 1333, "text": "m and n be their lengths respectively." }, { "code": null, "e": 1441, "s": 1372, "text": "len be the length of the longest common subsequence of str1 and str2" }, { "code": null, "e": 1486, "s": 1441, "text": "minimum number of deletions minDel = m – len" }, { "code": null, "e": 1535, "s": 1486, "text": "minimum number of Insertions minInsert = n – len" }, { "code": null, "e": 1582, "s": 1535, "text": "Below is the implementation of the above code:" }, { "code": null, "e": 1586, "s": 1582, "text": "C++" }, { "code": null, "e": 1591, "s": 1586, "text": "Java" }, { "code": null, "e": 1599, "s": 1591, "text": "Python3" }, { "code": null, "e": 1602, "s": 1599, "text": "C#" }, { "code": null, "e": 1613, "s": 1602, "text": "Javascript" }, { "code": "// Dynamic Programming C++ implementation to find// minimum number of deletions and insertions#include <bits/stdc++.h> using namespace std; // Returns length of longest common subsequence// for str1[0..m-1], str2[0..n-1]int lcs(string str1, string str2, int m, int n){ int L[m + 1][n + 1]; int i, j; // Following steps build L[m+1][n+1] in bottom // up fashion. Note that L[i][j] contains // length of LCS of str1[0..i-1] and str2[0..j-1] for (i = 0; i <= m; i++) { for (j = 0; j <= n; j++) { if (i == 0 || j == 0) L[i][j] = 0; else if (str1.at(i - 1) == str2.at(j - 1)) L[i][j] = L[i - 1][j - 1] + 1; else L[i][j] = max(L[i - 1][j], L[i][j - 1]); } } // L[m][n] contains length of LCS // for X[0..n-1] and Y[0..m-1] return L[m][n];} // function to find minimum number// of deletions and insertionsvoid printMinDelAndInsert(string str1, string str2){ int m = str1.size(); int n = str2.size(); int len = lcs(str1, str2, m, n); cout << \"Minimum number of deletions = \" << (m - len) << endl; cout << \"Minimum number of insertions = \" << (n - len) << endl;} // Driver Codeint main(){ string str1 = \"heap\"; string str2 = \"pea\"; // Function Call printMinDelAndInsert(str1, str2); return 0;}", "e": 2978, "s": 1613, "text": null }, { "code": "// Dynamic Programming Java implementation// to find minimum number of deletions and// insertionsimport java.io.*; class GFG { // Returns length of length common // subsequence for str1[0..m-1], // str2[0..n-1] static int lcs(String str1, String str2, int m, int n) { int L[][] = new int[m + 1][n + 1]; int i, j; // Following steps build L[m+1][n+1] in // bottom up fashion. Note that L[i][j] // contains length of LCS of str1[0..i-1] // and str2[0..j-1] for (i = 0; i <= m; i++) { for (j = 0; j <= n; j++) { if (i == 0 || j == 0) L[i][j] = 0; else if (str1.charAt(i - 1) == str2.charAt(j - 1)) L[i][j] = L[i - 1][j - 1] + 1; else L[i][j] = Math.max(L[i - 1][j], L[i][j - 1]); } } // L[m][n] contains length of LCS // for X[0..n-1] and Y[0..m-1] return L[m][n]; } // function to find minimum number // of deletions and insertions static void printMinDelAndInsert(String str1, String str2) { int m = str1.length(); int n = str2.length(); int len = lcs(str1, str2, m, n); System.out.println(\"Minimum number of \" + \"deletions = \"); System.out.println(m - len); System.out.println(\"Minimum number of \" + \"insertions = \"); System.out.println(n - len); } // Driver code public static void main(String[] args) { String str1 = new String(\"heap\"); String str2 = new String(\"pea\"); // Function Call printMinDelAndInsert(str1, str2); }}// This code is contributed by Prerna Saini", "e": 4839, "s": 2978, "text": null }, { "code": "# Dynamic Programming Python3# implementation to find minimum# number of deletions and insertions # Returns length of length# common subsequence for# str1[0..m-1], str2[0..n-1] def lcs(str1, str2, m, n): L = [[0 for i in range(n + 1)] for i in range(m + 1)] # Following steps build L[m+1][n+1] # in bottom up fashion. Note that # L[i][j] contains length of LCS # of str1[0..i-1] and str2[0..j-1] for i in range(m + 1): for j in range(n + 1): if (i == 0 or j == 0): L[i][j] = 0 elif(str1[i - 1] == str2[j - 1]): L[i][j] = L[i - 1][j - 1] + 1 else: L[i][j] = max(L[i - 1][j], L[i][j - 1]) # L[m][n] contains length of LCS # for X[0..n-1] and Y[0..m-1] return L[m][n] # function to find minimum number# of deletions and insertions def printMinDelAndInsert(str1, str2): m = len(str1) n = len(str2) leng = lcs(str1, str2, m, n) print(\"Minimum number of deletions = \", m - leng, sep=' ') print(\"Minimum number of insertions = \", n - leng, sep=' ') # Driver Codestr1 = \"heap\"str2 = \"pea\" # Function CallprintMinDelAndInsert(str1, str2) # This code is contributed# by sahilshelangia", "e": 6102, "s": 4839, "text": null }, { "code": "// Dynamic Programming C# implementation// to find minimum number of deletions and// insertionsusing System; class GFG { // Returns length of length common // subsequence for str1[0..m-1], // str2[0..n-1] static int lcs(string str1, string str2, int m, int n) { int[, ] L = new int[m + 1, n + 1]; int i, j; // Following steps build L[m+1][n+1] in // bottom up fashion. Note that L[i][j] // contains length of LCS of str1[0..i-1] // and str2[0..j-1] for (i = 0; i <= m; i++) { for (j = 0; j <= n; j++) { if (i == 0 || j == 0) L[i, j] = 0; else if (str1[i - 1] == str2[j - 1]) L[i, j] = L[i - 1, j - 1] + 1; else L[i, j] = Math.Max(L[i - 1, j], L[i, j - 1]); } } // L[m][n] contains length of LCS // for X[0..n-1] and Y[0..m-1] return L[m, n]; } // function to find minimum number // of deletions and insertions static void printMinDelAndInsert(string str1, string str2) { int m = str1.Length; int n = str2.Length; int len = lcs(str1, str2, m, n); Console.Write(\"Minimum number of \" + \"deletions = \"); Console.WriteLine(m - len); Console.Write(\"Minimum number of \" + \"insertions = \"); Console.Write(n - len); } // Driver code public static void Main() { string str1 = new string(\"heap\"); string str2 = new string(\"pea\"); // Function Call printMinDelAndInsert(str1, str2); }} // This code is contributed by nitin mittal.", "e": 7878, "s": 6102, "text": null }, { "code": "<script> // Dynamic Programming Javascript implementation // to find minimum number of deletions and // insertions // Returns length of length common // subsequence for str1[0..m-1], // str2[0..n-1] function lcs(str1, str2, m, n) { let L = new Array(m + 1); let i, j; for (i = 0; i <= m; i++) { L[i] = new Array(n + 1); for (j = 0; j <= n; j++) { L[i][j] = 0; } } // Following steps build L[m+1][n+1] in // bottom up fashion. Note that L[i][j] // contains length of LCS of str1[0..i-1] // and str2[0..j-1] for (i = 0; i <= m; i++) { for (j = 0; j <= n; j++) { if (i == 0 || j == 0) L[i][j] = 0; else if (str1[i - 1] == str2[j - 1]) L[i][j] = L[i - 1][j - 1] + 1; else L[i][j] = Math.max(L[i - 1][j], L[i][j - 1]); } } // L[m][n] contains length of LCS // for X[0..n-1] and Y[0..m-1] return L[m][n]; } // function to find minimum number // of deletions and insertions function printMinDelAndInsert(str1, str2) { let m = str1.length; let n = str2.length; let len = lcs(str1, str2, m, n); document.write(\"Minimum number of \" + \"deletions = \"); document.write((m - len) + \"</br>\"); document.write(\"Minimum number of \" + \"insertions = \"); document.write((n - len) + \"</br>\"); } let str1 = \"heap\"; let str2 = \"pea\"; // Function Call printMinDelAndInsert(str1, str2); // This code is contributed by rameshtravel07.</script>", "e": 9746, "s": 7878, "text": null }, { "code": null, "e": 9812, "s": 9746, "text": "Minimum number of deletions = 2\nMinimum number of insertions = 1\n" }, { "code": null, "e": 9838, "s": 9812, "text": "Time Complexity: O(m * n)" }, { "code": null, "e": 10019, "s": 9838, "text": "This method also uses the idea of finding the length of the longest common subsequence of the given two sequences. But this approach is using a top-down approach using memoization." }, { "code": null, "e": 10023, "s": 10019, "text": "C++" }, { "code": "// Dynamic Programming C++ implementation to find// minimum number of deletions and insertions// using memoization technique#include <bits/stdc++.h> using namespace std; int dp[1001][1001]; // Returns length of longest common subsequenceint lcs(string& s1, string& s2, int i, int j){ if (i == 0 || j == 0) { return 0; } if (dp[i][j] != -1) { return dp[i][j]; } if (s1[i - 1] == s2[j - 1]) { return dp[i][j] = 1 + lcs(s1, s2, i - 1, j - 1); } else { return dp[i][j] = max(lcs(s1, s2, i, j - 1), lcs(s1, s2, i - 1, j)); }} // function to find minimum number// of deletions and insertionsvoid printMinDelAndInsert(string str1, string str2){ int m = str1.size(); int n = str2.size(); dp[m][n]; // initialising dp array as -1 memset(dp, -1, sizeof(dp)); int len = lcs(str1, str2, m, n); cout << \"Minimum number of deletions = \" << (m - len) << endl; cout << \"Minimum number of insertions = \" << (n - len) << endl;} // driver codeint main(){ string str1 = \"heap\"; string str2 = \"pea\"; // Function Call printMinDelAndInsert(str1, str2); return 0;} // This code is contributed by Arun Bang.", "e": 11252, "s": 10023, "text": null }, { "code": null, "e": 11318, "s": 11252, "text": "Minimum number of deletions = 2\nMinimum number of insertions = 1\n" }, { "code": null, "e": 11765, "s": 11318, "text": "Time complexity: O(m * n)This article is contributed by Ayush Jauhari. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to review-team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. " }, { "code": null, "e": 11778, "s": 11765, "text": "nitin mittal" }, { "code": null, "e": 11793, "s": 11778, "text": "sahilshelangia" }, { "code": null, "e": 11806, "s": 11793, "text": "arstheking97" }, { "code": null, "e": 11821, "s": 11806, "text": "rameshtravel07" }, { "code": null, "e": 11832, "s": 11821, "text": "arunbang17" }, { "code": null, "e": 11836, "s": 11832, "text": "LCS" }, { "code": null, "e": 11856, "s": 11836, "text": "Dynamic Programming" }, { "code": null, "e": 11876, "s": 11856, "text": "Dynamic Programming" }, { "code": null, "e": 11880, "s": 11876, "text": "LCS" }, { "code": null, "e": 11978, "s": 11880, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 12005, "s": 11978, "text": "Subset Sum Problem | DP-25" }, { "code": null, "e": 12073, "s": 12005, "text": "Find if there is a path between two vertices in an undirected graph" }, { "code": null, "e": 12106, "s": 12073, "text": "Floyd Warshall Algorithm | DP-16" }, { "code": null, "e": 12125, "s": 12106, "text": "Coin Change | DP-7" }, { "code": null, "e": 12160, "s": 12125, "text": "Matrix Chain Multiplication | DP-8" }, { "code": null, "e": 12191, "s": 12160, "text": "Bellman–Ford Algorithm | DP-23" }, { "code": null, "e": 12259, "s": 12191, "text": "Travelling Salesman Problem | Set 1 (Naive and Dynamic Programming)" }, { "code": null, "e": 12281, "s": 12259, "text": "Sieve of Eratosthenes" }, { "code": null, "e": 12334, "s": 12281, "text": "Find minimum number of coins that make a given value" } ]
Stock buy and sell | Practice | GeeksforGeeks
The cost of stock on each day is given in an array A[] of size N. Find all the days on which you buy and sell the stock so that in between those days your profit is maximum. Note: There may be multiple possible solutions. Return any one of them. Any correct solution will result in an output of 1, whereas wrong solutions will result in an output of 0. Example 1: Input: N = 7 A[] = {100,180,260,310,40,535,695} Output: 1 Explanation: One possible solution is (0 3) (4 6) We can buy stock on day 0, and sell it on 3rd day, which will give us maximum profit. Now, we buy stock on day 4 and sell it on day 6. Example 2: Input: N = 5 A[] = {4,2,2,2,4} Output: 1 Explanation: There are multiple possible solutions. one of them is (3 4) We can buy stock on day 3, and sell it on 4th day, which will give us maximum profit. Your Task: The task is to complete the function stockBuySell() which takes an array A[] and N as input parameters and finds the days of buying and selling stock. The function must return a 2D list of integers containing all the buy-sell pairs i.e. first value of pair will represent the day on which you buy the stock and second value represent the day on which you sell that stock. If there is No Profit, return an empty list. Note: Since there can be multiple solutions, the driver code will return 1 if your answer is correct, otherwise, it will return 0. In case there's no profit the driver code will return the string "No Profit" for a correct solution. Expected Time Complexity: O(N) Expected Auxiliary Space: O(N) Constraints: 2 ≤ N ≤ 106 0 ≤ A[i] ≤ 106 0 adityatis211 day ago Simple CPP solution class Solution{public: vector<vector<int> > stockBuySell(vector<int> A, int n){ vector<vector<int>>v; vector<int> a; int i = 0 ; while(i<n-1) { a.clear(); while((i < n -1 ) && A[i] >= A[ i + 1]) i++; if(i == n -1 ) break; a.push_back(i); i++; while((i < n) && A[i] >= A[i - 1]) i++; a.push_back(i - 1); v.push_back(a); } return v; }}; 0 likhithsasank2 days ago class Solution{ //Function to find the days of buying and selling stock for max profit. ArrayList<ArrayList<Integer> > stockBuySell(int A[], int n) { ArrayList<ArrayList<Integer>> ans=new ArrayList<>(); for(int i=1;i<n;i++){ if(A[i]>A[i-1]){ ans.add(new ArrayList<>(Arrays.asList(i-1,i))); } } return ans; }} 0 avanshul00012 days ago Here's my solutionclass Solution{ ArrayList<ArrayList<Integer>> stockBuySell(int A[], int n) { ArrayList<ArrayList<Integer>> list = new ArrayList<>(); if(n == 0){ return list; } int idx = 0; int min = A[idx]; int max = 0; for(int i=1; i<n; i++){ if(A[i] < min){ min = A[i]; idx = i; } if(A[i] > min){ ArrayList<Integer> al = new ArrayList<>(); al.add(idx); al.add(i); list.add(al); min = A[i]; idx = i; } } return list; }} +1 ruchikajamwal03192 days ago //User function template for C++ class Solution{public: //Function to find the days of buying and selling stock for max profit. vector<vector<int> > stockBuySell(vector<int> A, int n){ // code here vector<vector<int>> temp; for(int i = 0; i < n-1; i++){ if(A[i] < A[i+1]){ temp.push_back({i,i+1}); } } return temp; }}; 0 tarun3143 days ago Either change the question or give more clarity .It's so confusing 0 pradhanrahul33464 days ago ArrayList<ArrayList<Integer> > stockBuySell(int arr[], int n) { // code here ArrayList<ArrayList<Integer> > array_list = new ArrayList<ArrayList<Integer>>(); int j=0; for(int i=1;i<n;i++){ if(arr[i-1]<arr[i]){ array_list.add(new ArrayList<Integer>()); array_list.get(j).add(0, i-1); array_list.get(j).add(1, i); j++; } } return array_list; } 0 shaikhamaan37864 days ago Easiest Solution Ever. C++ class Solution{ public: //Function to find the days of buying and selling stock for max profit. vector<vector<int> > stockBuySell(vector<int> A, int n){ vector<vector<int>> temp; for(int i = 0; i < n-1; i++){ if(A[i] < A[i+1]){ temp.push_back({i,i+1}); } } return temp; } }; Python def stockBuySell(self, A, n): temp = [] for i in range(n-1): if A[i] < A[i+1]: temp.append([i,i+1]) return temp +6 bsyed1766 days ago please make the question clear...@admin +1 proudtobe7271 week ago class Solution{ public: //Function to find the days of buying and selling stock for max profit. vector<vector<int> > stockBuySell(vector<int> A, int n) { vector<vector<int>> v; vector<int> temp; int low=0,high=0; for(int i=0;i<(n-1);i++) { low=i; high=i; while(A[i+1]>A[i] && i<(n-1)) { ++high; ++i; } if(low!=high) v.push_back({low,high}); } return v; } }; 0 abhinayabhi1411 week ago class Solution{public: //Function to find the days of buying and selling stock for max profit. vector<vector<int> > stockBuySell(vector<int> A, int n){ // code here vector<vector<int>>arr; vector<int>vec; for(int i=0; i<n-1; i++) { int low=i; int high=i; while(A[i+1]>A[i] && i<n-1) { high++; i++; } if(low!=high) { vec.push_back(low); vec.push_back(high); arr.push_back(vec); vec.pop_back(); vec.pop_back(); } } return arr; }}; We strongly recommend solving this problem on your own before viewing its editorial. Do you still want to view the editorial? Login to access your submissions. Problem Contest Reset the IDE using the second button on the top right corner. Avoid using static/global variables in your code as your code is tested against multiple test cases and these tend to retain their previous values. Passing the Sample/Custom Test cases does not guarantee the correctness of code. On submission, your code is tested against multiple test cases consisting of all possible corner cases and stress constraints. You can access the hints to get an idea about what is expected of you as well as the final solution code. You can view the solutions submitted by other users from the submission tab. Make sure you are not using ad-blockers. Disable browser extensions. We recommend using latest version of your browser for best experience. Avoid using static/global variables in coding problems as your code is tested against multiple test cases and these tend to retain their previous values. Passing the Sample/Custom Test cases in coding problems does not guarantee the correctness of code. On submission, your code is tested against multiple test cases consisting of all possible corner cases and stress constraints.
[ { "code": null, "e": 603, "s": 238, "text": "The cost of stock on each day is given in an array A[] of size N. Find all the days on which you buy and sell the stock so that in between those days your profit is maximum.\nNote: There may be multiple possible solutions. Return any one of them. Any correct solution will result in an output of 1, whereas wrong solutions will result in an output of 0.\n\nExample 1:" }, { "code": null, "e": 849, "s": 603, "text": "Input:\nN = 7\nA[] = {100,180,260,310,40,535,695}\nOutput:\n1\nExplanation:\nOne possible solution is (0 3) (4 6)\nWe can buy stock on day 0,\nand sell it on 3rd day, which will \ngive us maximum profit. Now, we buy \nstock on day 4 and sell it on day 6.\n" }, { "code": null, "e": 860, "s": 849, "text": "Example 2:" }, { "code": null, "e": 1061, "s": 860, "text": "Input:\nN = 5\nA[] = {4,2,2,2,4}\nOutput:\n1\nExplanation:\nThere are multiple possible solutions.\none of them is (3 4)\nWe can buy stock on day 3,\nand sell it on 4th day, which will \ngive us maximum profit." }, { "code": null, "e": 1491, "s": 1061, "text": "\nYour Task:\nThe task is to complete the function stockBuySell() which takes an array A[] and N as input parameters and finds the days of buying and selling stock. The function must return a 2D list of integers containing all the buy-sell pairs i.e. first value of pair will represent the day on which you buy the stock and second value represent the day on which you sell that stock. If there is No Profit, return an empty list. " }, { "code": null, "e": 1725, "s": 1493, "text": "Note: Since there can be multiple solutions, the driver code will return 1 if your answer is correct, otherwise, it will return 0. In case there's no profit the driver code will return the string \"No Profit\" for a correct solution." }, { "code": null, "e": 1788, "s": 1725, "text": "\nExpected Time Complexity: O(N)\nExpected Auxiliary Space: O(N)" }, { "code": null, "e": 1829, "s": 1788, "text": "\nConstraints:\n2 ≤ N ≤ 106\n0 ≤ A[i] ≤ 106" }, { "code": null, "e": 1831, "s": 1829, "text": "0" }, { "code": null, "e": 1852, "s": 1831, "text": "adityatis211 day ago" }, { "code": null, "e": 1873, "s": 1852, "text": "Simple CPP solution " }, { "code": null, "e": 2434, "s": 1875, "text": "class Solution{public: vector<vector<int> > stockBuySell(vector<int> A, int n){ vector<vector<int>>v; vector<int> a; int i = 0 ; while(i<n-1) { a.clear(); while((i < n -1 ) && A[i] >= A[ i + 1]) i++; if(i == n -1 ) break; a.push_back(i); i++; while((i < n) && A[i] >= A[i - 1]) i++; a.push_back(i - 1); v.push_back(a); } return v; }};" }, { "code": null, "e": 2436, "s": 2434, "text": "0" }, { "code": null, "e": 2460, "s": 2436, "text": "likhithsasank2 days ago" }, { "code": null, "e": 2846, "s": 2460, "text": "class Solution{ //Function to find the days of buying and selling stock for max profit. ArrayList<ArrayList<Integer> > stockBuySell(int A[], int n) { ArrayList<ArrayList<Integer>> ans=new ArrayList<>(); for(int i=1;i<n;i++){ if(A[i]>A[i-1]){ ans.add(new ArrayList<>(Arrays.asList(i-1,i))); } } return ans; }}" }, { "code": null, "e": 2848, "s": 2846, "text": "0" }, { "code": null, "e": 2871, "s": 2848, "text": "avanshul00012 days ago" }, { "code": null, "e": 3560, "s": 2871, "text": "Here's my solutionclass Solution{ ArrayList<ArrayList<Integer>> stockBuySell(int A[], int n) { ArrayList<ArrayList<Integer>> list = new ArrayList<>(); if(n == 0){ return list; } int idx = 0; int min = A[idx]; int max = 0; for(int i=1; i<n; i++){ if(A[i] < min){ min = A[i]; idx = i; } if(A[i] > min){ ArrayList<Integer> al = new ArrayList<>(); al.add(idx); al.add(i); list.add(al); min = A[i]; idx = i; } } return list; }}" }, { "code": null, "e": 3563, "s": 3560, "text": "+1" }, { "code": null, "e": 3591, "s": 3563, "text": "ruchikajamwal03192 days ago" }, { "code": null, "e": 3624, "s": 3591, "text": "//User function template for C++" }, { "code": null, "e": 3994, "s": 3624, "text": "class Solution{public: //Function to find the days of buying and selling stock for max profit. vector<vector<int> > stockBuySell(vector<int> A, int n){ // code here vector<vector<int>> temp; for(int i = 0; i < n-1; i++){ if(A[i] < A[i+1]){ temp.push_back({i,i+1}); } } return temp; }};" }, { "code": null, "e": 3996, "s": 3994, "text": "0" }, { "code": null, "e": 4015, "s": 3996, "text": "tarun3143 days ago" }, { "code": null, "e": 4084, "s": 4015, "text": "Either change the question or give more clarity .It's so confusing " }, { "code": null, "e": 4086, "s": 4084, "text": "0" }, { "code": null, "e": 4113, "s": 4086, "text": "pradhanrahul33464 days ago" }, { "code": null, "e": 4558, "s": 4113, "text": " ArrayList<ArrayList<Integer> > stockBuySell(int arr[], int n) { // code here ArrayList<ArrayList<Integer> > array_list = new ArrayList<ArrayList<Integer>>(); int j=0; for(int i=1;i<n;i++){ if(arr[i-1]<arr[i]){ array_list.add(new ArrayList<Integer>()); array_list.get(j).add(0, i-1); array_list.get(j).add(1, i); j++; } }" }, { "code": null, "e": 4588, "s": 4558, "text": " return array_list; }" }, { "code": null, "e": 4590, "s": 4588, "text": "0" }, { "code": null, "e": 4616, "s": 4590, "text": "shaikhamaan37864 days ago" }, { "code": null, "e": 4639, "s": 4616, "text": "Easiest Solution Ever." }, { "code": null, "e": 4645, "s": 4641, "text": "C++" }, { "code": null, "e": 5022, "s": 4645, "text": "class Solution{\npublic:\n //Function to find the days of buying and selling stock for max profit.\n vector<vector<int> > stockBuySell(vector<int> A, int n){\n vector<vector<int>> temp;\n \n for(int i = 0; i < n-1; i++){\n if(A[i] < A[i+1]){\n temp.push_back({i,i+1});\n }\n }\n \n return temp;\n }\n};" }, { "code": null, "e": 5031, "s": 5024, "text": "Python" }, { "code": null, "e": 5170, "s": 5031, "text": "def stockBuySell(self, A, n):\n temp = []\n for i in range(n-1):\n if A[i] < A[i+1]:\n temp.append([i,i+1])\n \n return temp" }, { "code": null, "e": 5173, "s": 5170, "text": "+6" }, { "code": null, "e": 5192, "s": 5173, "text": "bsyed1766 days ago" }, { "code": null, "e": 5232, "s": 5192, "text": "please make the question clear...@admin" }, { "code": null, "e": 5235, "s": 5232, "text": "+1" }, { "code": null, "e": 5258, "s": 5235, "text": "proudtobe7271 week ago" }, { "code": null, "e": 5796, "s": 5258, "text": "class Solution{\npublic:\n //Function to find the days of buying and selling stock for max profit.\n vector<vector<int> > stockBuySell(vector<int> A, int n)\n {\n vector<vector<int>> v;\n vector<int> temp;\n int low=0,high=0;\n \n for(int i=0;i<(n-1);i++)\n {\n low=i;\n high=i;\n while(A[i+1]>A[i] && i<(n-1))\n {\n ++high;\n ++i;\n }\n if(low!=high)\n v.push_back({low,high});\n }\n return v;\n }\n};" }, { "code": null, "e": 5798, "s": 5796, "text": "0" }, { "code": null, "e": 5823, "s": 5798, "text": "abhinayabhi1411 week ago" }, { "code": null, "e": 6433, "s": 5823, "text": "class Solution{public: //Function to find the days of buying and selling stock for max profit. vector<vector<int> > stockBuySell(vector<int> A, int n){ // code here vector<vector<int>>arr; vector<int>vec; for(int i=0; i<n-1; i++) { int low=i; int high=i; while(A[i+1]>A[i] && i<n-1) { high++; i++; } if(low!=high) { vec.push_back(low); vec.push_back(high); arr.push_back(vec); vec.pop_back(); vec.pop_back(); } } return arr; }};" }, { "code": null, "e": 6579, "s": 6433, "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": 6615, "s": 6579, "text": " Login to access your submissions. " }, { "code": null, "e": 6625, "s": 6615, "text": "\nProblem\n" }, { "code": null, "e": 6635, "s": 6625, "text": "\nContest\n" }, { "code": null, "e": 6698, "s": 6635, "text": "Reset the IDE using the second button on the top right corner." }, { "code": null, "e": 6883, "s": 6698, "text": "Avoid using static/global variables in your code as your code is tested \n against multiple test cases and these tend to retain their previous values." }, { "code": null, "e": 7167, "s": 6883, "text": "Passing the Sample/Custom Test cases does not guarantee the correctness of code.\n On submission, your code is tested against multiple test cases consisting of all\n possible corner cases and stress constraints." }, { "code": null, "e": 7313, "s": 7167, "text": "You can access the hints to get an idea about what is expected of you as well as\n the final solution code." }, { "code": null, "e": 7390, "s": 7313, "text": "You can view the solutions submitted by other users from the submission tab." }, { "code": null, "e": 7431, "s": 7390, "text": "Make sure you are not using ad-blockers." }, { "code": null, "e": 7459, "s": 7431, "text": "Disable browser extensions." }, { "code": null, "e": 7530, "s": 7459, "text": "We recommend using latest version of your browser for best experience." }, { "code": null, "e": 7717, "s": 7530, "text": "Avoid using static/global variables in coding problems as your code is tested \n against multiple test cases and these tend to retain their previous values." } ]
Matplotlib.axes.Axes.contour() in Python
13 Apr, 2020 Matplotlib is a library in Python and it is numerical – mathematical extension for NumPy library. The Axes Class contains most of the figure elements: Axis, Tick, Line2D, Text, Polygon, etc., and sets the coordinate system. And the instances of Axes supports callbacks through a callbacks attribute. The Axes.contour() function in axes module of matplotlib library is used to Plot contours. contourdraw contour lines. Syntax: Axes.contour(self, *args, data=None, **kwargs) contour([X, Y, ] Z, [levels], **kwargs) Parameters: This method accept the following parameters that are described below: X, Y: These parameter are the coordinates of the values in Z. Z : This parameter is the height values over which the contour is drawn. levels : This parameter is used to determine the numbers and positions of the contour lines / regions. Returns: This returns the following: c :This returns the QuadContourSet. Below examples illustrate the matplotlib.axes.Axes.contour() function in matplotlib.axes: Example-1: # Implementation of matplotlib functionimport numpy as npimport matplotlib.pyplot as pltimport matplotlib.ticker as tickerimport matplotlib delta = 0.15x = np.arange(-0.5, 2.5, delta)y = np.arange(-1.0, 3.0, delta)X, Y = np.meshgrid(x, y)Z = (np.exp(-X**2 - Y**2) - np.exp(-(X - 1)**2 - (Y - 1)**2)) fig1, ax1 = plt.subplots()CS1 = ax1.contour(X, Y, Z) fmt = {}strs = ['1', '2', '3', '4', '5', '6', '7']for l, s in zip(CS1.levels, strs): fmt[l] = sax1.clabel(CS1, CS1.levels, inline = True, fmt = fmt, fontsize = 10) ax1.set_title('matplotlib.axes.Axes.contour() Example')plt.show() Output: Example-2: # Implementation of matplotlib functionimport matplotlibimport numpy as npimport matplotlib.cm as cmimport matplotlib.pyplot as plt delta = 0.25x = np.arange(-5.0, 5.0, delta)y = np.arange(-3.3, 5.5, delta)X, Y = np.meshgrid(x, y)Z = (np.exp(-X**2 - Y**2) - np.exp(-(X - 1)**2 - (Y - 1)**2)) * 3 fig, ax = plt.subplots()im = ax.imshow(Z, interpolation ='bilinear', origin ='lower', cmap ="Greens", extent =(-3, 3, -2, 2)) levels = np.arange(-1.2, 1.6, 0.2)CS = ax.contour(Z, levels, origin ='lower', cmap ='Blues', linewidths = 2, extent =(-3, 3, -2, 2))zc = CS.collections[6]plt.setp(zc, linewidth = 4) ax.clabel(CS, levels, inline = 1, fmt ='% 1.1f', fontsize = 14)ax.set_title('matplotlib.axes.Axes.contour() Example')plt.show() Output: Python-matplotlib Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n13 Apr, 2020" }, { "code": null, "e": 328, "s": 28, "text": "Matplotlib is a library in Python and it is numerical – mathematical extension for NumPy library. The Axes Class contains most of the figure elements: Axis, Tick, Line2D, Text, Polygon, etc., and sets the coordinate system. And the instances of Axes supports callbacks through a callbacks attribute." }, { "code": null, "e": 446, "s": 328, "text": "The Axes.contour() function in axes module of matplotlib library is used to Plot contours. contourdraw contour lines." }, { "code": null, "e": 454, "s": 446, "text": "Syntax:" }, { "code": null, "e": 541, "s": 454, "text": "Axes.contour(self, *args, data=None, **kwargs)\ncontour([X, Y, ] Z, [levels], **kwargs)" }, { "code": null, "e": 623, "s": 541, "text": "Parameters: This method accept the following parameters that are described below:" }, { "code": null, "e": 685, "s": 623, "text": "X, Y: These parameter are the coordinates of the values in Z." }, { "code": null, "e": 758, "s": 685, "text": "Z : This parameter is the height values over which the contour is drawn." }, { "code": null, "e": 861, "s": 758, "text": "levels : This parameter is used to determine the numbers and positions of the contour lines / regions." }, { "code": null, "e": 898, "s": 861, "text": "Returns: This returns the following:" }, { "code": null, "e": 934, "s": 898, "text": "c :This returns the QuadContourSet." }, { "code": null, "e": 1024, "s": 934, "text": "Below examples illustrate the matplotlib.axes.Axes.contour() function in matplotlib.axes:" }, { "code": null, "e": 1035, "s": 1024, "text": "Example-1:" }, { "code": "# Implementation of matplotlib functionimport numpy as npimport matplotlib.pyplot as pltimport matplotlib.ticker as tickerimport matplotlib delta = 0.15x = np.arange(-0.5, 2.5, delta)y = np.arange(-1.0, 3.0, delta)X, Y = np.meshgrid(x, y)Z = (np.exp(-X**2 - Y**2) - np.exp(-(X - 1)**2 - (Y - 1)**2)) fig1, ax1 = plt.subplots()CS1 = ax1.contour(X, Y, Z) fmt = {}strs = ['1', '2', '3', '4', '5', '6', '7']for l, s in zip(CS1.levels, strs): fmt[l] = sax1.clabel(CS1, CS1.levels, inline = True, fmt = fmt, fontsize = 10) ax1.set_title('matplotlib.axes.Axes.contour() Example')plt.show()", "e": 1635, "s": 1035, "text": null }, { "code": null, "e": 1643, "s": 1635, "text": "Output:" }, { "code": null, "e": 1654, "s": 1643, "text": "Example-2:" }, { "code": "# Implementation of matplotlib functionimport matplotlibimport numpy as npimport matplotlib.cm as cmimport matplotlib.pyplot as plt delta = 0.25x = np.arange(-5.0, 5.0, delta)y = np.arange(-3.3, 5.5, delta)X, Y = np.meshgrid(x, y)Z = (np.exp(-X**2 - Y**2) - np.exp(-(X - 1)**2 - (Y - 1)**2)) * 3 fig, ax = plt.subplots()im = ax.imshow(Z, interpolation ='bilinear', origin ='lower', cmap =\"Greens\", extent =(-3, 3, -2, 2)) levels = np.arange(-1.2, 1.6, 0.2)CS = ax.contour(Z, levels, origin ='lower', cmap ='Blues', linewidths = 2, extent =(-3, 3, -2, 2))zc = CS.collections[6]plt.setp(zc, linewidth = 4) ax.clabel(CS, levels, inline = 1, fmt ='% 1.1f', fontsize = 14)ax.set_title('matplotlib.axes.Axes.contour() Example')plt.show()", "e": 2428, "s": 1654, "text": null }, { "code": null, "e": 2436, "s": 2428, "text": "Output:" }, { "code": null, "e": 2454, "s": 2436, "text": "Python-matplotlib" }, { "code": null, "e": 2461, "s": 2454, "text": "Python" } ]
Implementation of K Nearest Neighbors
08 Dec, 2021 Prerequisite: K nearest neighbors Introduction Say we are given a data set of items, each having numerically valued features (like Height, Weight, Age, etc). If the count of features is n, we can represent the items as points in an n-dimensional grid. Given a new item, we can calculate the distance from the item to every other item in the set. We pick the k closest neighbors and we see where most of these neighbors are classified in. We classify the new item there.So the problem becomes how we can calculate the distances between items. The solution to this depends on the data set. If the values are real we usually use the Euclidean distance. If the values are categorical or binary, we usually use the Hamming distance.Algorithm: Given a new item: 1. Find distances between new item and all other items 2. Pick k shorter distances 3. Pick the most common class in these k distances 4. That class is where we will classify the new item Reading Data Let our input file be in the following format: Height, Weight, Age, Class 1.70, 65, 20, Programmer 1.90, 85, 33, Builder 1.78, 76, 31, Builder 1.73, 74, 24, Programmer 1.81, 75, 35, Builder 1.73, 70, 75, Scientist 1.80, 71, 63, Scientist 1.75, 69, 25, Programmer Each item is a line and under “Class” we see where the item is classified in. The values under the feature names (“Height” etc.) are the value the item has for that feature. All the values and features are separated by commas.Place these data files in the working directory data2 and data. Choose one and paste the contents as-is into a text file named data.We will read from the file (named “data.txt”) and we will split the input by lines: f = open('data.txt', 'r'); lines = f.read().splitlines(); f.close(); The first line of the file holds the feature names, with the keyword “Class” at the end. We want to store the feature names into a list: # Split the first line by commas, # remove the first element and # save the rest into a list. The # list now holds the feature # names of the data set. features = lines[0].split(', ')[:-1]; Then we move on to the data set itself. We will save the items into a list, named items, whose elements are dictionaries (one for each item). The keys to these item-dictionaries are the feature names, plus “Class” to hold the item class. In the end, we want to shuffle the items in the list (this is a safety measure, in case the items are in a weird order). Python3 items = []; for i in range(1, len(lines)): line = lines[i].split(', '); itemFeatures = {"Class" : line[-1]}; # Iterate through the features for j in range(len(features)): # Get the feature at index j f = features[j]; # The first item in the line # is the class, skip it v = float(line[j]); # Add feature to dict itemFeatures[f] = v; # Append temp dict to items items.append(itemFeatures); shuffle(items); Classifying the data With the data stored into items, we now start building our classifier. For the classifier, we will create a new function, Classify. It will take as input the item we want to classify, the items list, and k, the number of the closest neighbors.If k is greater than the length of the data set, we do not go ahead with the classifying, as we cannot have more closest neighbors than the total amount of items in the data set. (alternatively, we could set k as the items length instead of returning an error message) if(k > len(Items)): # k is larger than list # length, abort return "k larger than list length"; We want to calculate the distance between the item to be classified and all the items in the training set, in the end keeping the k shortest distances. To keep the current closest neighbors we use a list, called neighbors. Each element in the least holds two values, one for the distance from the item to be classified and another for the class the neighbor is in. We will calculate distance via the generalized Euclidean formula (for n dimensions). Then, we will pick the class that appears most of the time in neighbors and that will be our pick. In code: Python3 def Classify(nItem, k, Items): if(k > len(Items)): # k is larger than list # length, abort return "k larger than list length"; # Hold nearest neighbors. # First item is distance, # second class neighbors = []; for item in Items: # Find Euclidean Distance distance = EuclideanDistance(nItem, item); # Update neighbors, either adding # the current item in neighbors # or not. neighbors = UpdateNeighbors(neighbors, item, distance, k); # Count the number of each # class in neighbors count = CalculateNeighborsClass(neighbors, k); # Find the max in count, aka the # class with the most appearances. return FindMax(count); The external functions we need to implement are EuclideanDistance, UpdateNeighbors, CalculateNeighborsClass, and FindMax. Finding Euclidean Distance The generalized Euclidean formula for two vectors x and y is this: distance = sqrt{(x_{1}-y_{1})^2 + (x_{2}-y_{2})^2 + ... + (x_{n}-y_{n})^2} In code: Python3 def EuclideanDistance(x, y): # The sum of the squared # differences of the elements S = 0; for key in x.keys(): S += math.pow(x[key]-y[key], 2); # The square root of the sum return math.sqrt(S); Updating Neighbors We have our neighbors list (which should at most have a length of k) and we want to add an item to the list with a given distance. First, we will check if neighbors have a length of k. If it has less, we add the item to it regardless of the distance (as we need to fill the list up to k before we start rejecting items). If not, we will check if the item has a shorter distance than the item with the max distance in the list. If that is true, we will replace the item with max distance with the new item.To find the max distance item more quickly, we will keep the list sorted in ascending order. So, the last item in the list will have the max distance. We will replace it with a new item and we will sort it again.To speed this process up, we can implement an Insertion Sort where we insert new items in the list without having to sort the entire list. The code for this though is rather long and, although simple, will bog the tutorial down. Python3 def UpdateNeighbors(neighbors, item, distance, k): if(len(neighbors) > distance): # If yes, replace the last # element with new item neighbors[-1] = [distance, item["Class"]]; neighbors = sorted(neighbors); return neighbors; CalculateNeighborsClass Here we will calculate the class that appears most often in neighbors. For that, we will use another dictionary, called count, where the keys are the class names appearing in neighbors. If a key doesn’t exist, we will add it, otherwise, we will increment its value. pyth Python3 def CalculateNeighborsClass(neighbors, k): count = {}; for i in range(k): if(neighbors[i][1] not in count): # The class at the ith index # is not in the count dict. # Initialize it to 1. count[neighbors[i][1]] = 1; else: # Found another item of class # c[i]. Increment its counter. count[neighbors[i][1]] += 1; return count; FindMax We will input to this function the dictionary count we build in CalculateNeighborsClass and we will return its max. Python3 def FindMax(countList): # Hold the max maximum = -1; # Hold the classification classification = ""; for key in countList.keys(): if(countList[key] > maximum): maximum = countList[key]; classification = key; return classification, maximum; Conclusion With that, this kNN tutorial is finished.You can now classify new items, setting k as you see fit. Usually, for k an odd number is used, but that is not necessary. To classify a new item, you need to create a dictionary with keys the feature names, and the values that characterize the item. An example of classification: newItem = {'Height' : 1.74, 'Weight' : 67, 'Age' : 22}; print Classify(newItem, 3, items); The complete code of the above approach is given below:- Python3 # Python Program to illustrate# KNN algorithm # For pow and sqrtimport mathfrom random import shuffle ###_Reading_### def ReadData(fileName): # Read the file, splitting by lines f = open(fileName, 'r') lines = f.read().splitlines() f.close() # Split the first line by commas, # remove the first element and save # the rest into a list. The list # holds the feature names of the # data set. features = lines[0].split(', ')[:-1] items = [] for i in range(1, len(lines)): line = lines[i].split(', ') itemFeatures = {'Class': line[-1]} for j in range(len(features)): # Get the feature at index j f = features[j] # Convert feature value to float v = float(line[j]) # Add feature value to dict itemFeatures[f] = v items.append(itemFeatures) shuffle(items) return items ###_Auxiliary Function_### def EuclideanDistance(x, y): # The sum of the squared differences # of the elements S = 0 for key in x.keys(): S += math.pow(x[key] - y[key], 2) # The square root of the sum return math.sqrt(S) def CalculateNeighborsClass(neighbors, k): count = {} for i in range(k): if neighbors[i][1] not in count: # The class at the ith index is # not in the count dict. # Initialize it to 1. count[neighbors[i][1]] = 1 else: # Found another item of class # c[i]. Increment its counter. count[neighbors[i][1]] += 1 return count def FindMax(Dict): # Find max in dictionary, return # max value and max index maximum = -1 classification = '' for key in Dict.keys(): if Dict[key] > maximum: maximum = Dict[key] classification = key return (classification, maximum) ###_Core Functions_### def Classify(nItem, k, Items): # Hold nearest neighbours. First item # is distance, second class neighbors = [] for item in Items: # Find Euclidean Distance distance = EuclideanDistance(nItem, item) # Update neighbors, either adding the # current item in neighbors or not. neighbors = UpdateNeighbors(neighbors, item, distance, k) # Count the number of each class # in neighbors count = CalculateNeighborsClass(neighbors, k) # Find the max in count, aka the # class with the most appearances return FindMax(count) def UpdateNeighbors(neighbors, item, distance, k, ): if len(neighbors) < k: # List is not full, add # new item and sort neighbors.append([distance, item['Class']]) neighbors = sorted(neighbors) else: # List is full Check if new # item should be entered if neighbors[-1][0] > distance: # If yes, replace the # last element with new item neighbors[-1] = [distance, item['Class']] neighbors = sorted(neighbors) return neighbors ###_Evaluation Functions_### def K_FoldValidation(K, k, Items): if K > len(Items): return -1 # The number of correct classifications correct = 0 # The total number of classifications total = len(Items) * (K - 1) # The length of a fold l = int(len(Items) / K) for i in range(K): # Split data into training set # and test set trainingSet = Items[i * l:(i + 1) * l] testSet = Items[:i * l] + Items[(i + 1) * l:] for item in testSet: itemClass = item['Class'] itemFeatures = {} # Get feature values for key in item: if key != 'Class': # If key isn't "Class", add # it to itemFeatures itemFeatures[key] = item[key] # Categorize item based on # its feature values guess = Classify(itemFeatures, k, trainingSet)[0] if guess == itemClass: # Guessed correctly correct += 1 accuracy = correct / float(total) return accuracy def Evaluate(K, k, items, iterations): # Run algorithm the number of # iterations, pick average accuracy = 0 for i in range(iterations): shuffle(items) accuracy += K_FoldValidation(K, k, items) print accuracy / float(iterations) ###_Main_### def main(): items = ReadData('data.txt') Evaluate(5, 5, items, 100) if __name__ == '__main__': main() Output: 0.9375 The output can vary from machine to machine. The code includes a Fold Validation function, but it is unrelated to the algorithm, it is there for calculating the accuracy of the algorithm. punamsingh628700 amartyaghoshgfg Algorithms Machine Learning Algorithms Machine Learning 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 CPU Scheduling in Operating Systems Understanding Time Complexity with Simple Examples Naive Bayes Classifiers Decision Tree Agents in Artificial Intelligence Removing stop words with NLTK in Python Search Algorithms in AI
[ { "code": null, "e": 54, "s": 26, "text": "\n08 Dec, 2021" }, { "code": null, "e": 90, "s": 54, "text": "Prerequisite: K nearest neighbors " }, { "code": null, "e": 103, "s": 90, "text": "Introduction" }, { "code": null, "e": 796, "s": 103, "text": "Say we are given a data set of items, each having numerically valued features (like Height, Weight, Age, etc). If the count of features is n, we can represent the items as points in an n-dimensional grid. Given a new item, we can calculate the distance from the item to every other item in the set. We pick the k closest neighbors and we see where most of these neighbors are classified in. We classify the new item there.So the problem becomes how we can calculate the distances between items. The solution to this depends on the data set. If the values are real we usually use the Euclidean distance. If the values are categorical or binary, we usually use the Hamming distance.Algorithm: " }, { "code": null, "e": 1017, "s": 796, "text": "Given a new item:\n 1. Find distances between new item and all other items\n 2. Pick k shorter distances\n 3. Pick the most common class in these k distances\n 4. That class is where we will classify the new item" }, { "code": null, "e": 1032, "s": 1019, "text": "Reading Data" }, { "code": null, "e": 1080, "s": 1032, "text": "Let our input file be in the following format: " }, { "code": null, "e": 1296, "s": 1080, "text": "Height, Weight, Age, Class\n1.70, 65, 20, Programmer\n1.90, 85, 33, Builder\n1.78, 76, 31, Builder\n1.73, 74, 24, Programmer\n1.81, 75, 35, Builder\n1.73, 70, 75, Scientist\n1.80, 71, 63, Scientist\n1.75, 69, 25, Programmer" }, { "code": null, "e": 1739, "s": 1296, "text": "Each item is a line and under “Class” we see where the item is classified in. The values under the feature names (“Height” etc.) are the value the item has for that feature. All the values and features are separated by commas.Place these data files in the working directory data2 and data. Choose one and paste the contents as-is into a text file named data.We will read from the file (named “data.txt”) and we will split the input by lines: " }, { "code": null, "e": 1808, "s": 1739, "text": "f = open('data.txt', 'r');\nlines = f.read().splitlines();\nf.close();" }, { "code": null, "e": 1946, "s": 1808, "text": "The first line of the file holds the feature names, with the keyword “Class” at the end. We want to store the feature names into a list: " }, { "code": null, "e": 2138, "s": 1946, "text": "# Split the first line by commas,\n# remove the first element and \n# save the rest into a list. The\n# list now holds the feature \n# names of the data set.\nfeatures = lines[0].split(', ')[:-1];" }, { "code": null, "e": 2499, "s": 2138, "text": "Then we move on to the data set itself. We will save the items into a list, named items, whose elements are dictionaries (one for each item). The keys to these item-dictionaries are the feature names, plus “Class” to hold the item class. In the end, we want to shuffle the items in the list (this is a safety measure, in case the items are in a weird order). " }, { "code": null, "e": 2507, "s": 2499, "text": "Python3" }, { "code": "items = []; for i in range(1, len(lines)): line = lines[i].split(', '); itemFeatures = {\"Class\" : line[-1]}; # Iterate through the features for j in range(len(features)): # Get the feature at index j f = features[j]; # The first item in the line # is the class, skip it v = float(line[j]); # Add feature to dict itemFeatures[f] = v; # Append temp dict to items items.append(itemFeatures); shuffle(items);", "e": 3021, "s": 2507, "text": null }, { "code": null, "e": 3042, "s": 3021, "text": "Classifying the data" }, { "code": null, "e": 3555, "s": 3042, "text": "With the data stored into items, we now start building our classifier. For the classifier, we will create a new function, Classify. It will take as input the item we want to classify, the items list, and k, the number of the closest neighbors.If k is greater than the length of the data set, we do not go ahead with the classifying, as we cannot have more closest neighbors than the total amount of items in the data set. (alternatively, we could set k as the items length instead of returning an error message) " }, { "code": null, "e": 3684, "s": 3555, "text": "if(k > len(Items)):\n \n # k is larger than list\n # length, abort\n return \"k larger than list length\";" }, { "code": null, "e": 4244, "s": 3684, "text": "We want to calculate the distance between the item to be classified and all the items in the training set, in the end keeping the k shortest distances. To keep the current closest neighbors we use a list, called neighbors. Each element in the least holds two values, one for the distance from the item to be classified and another for the class the neighbor is in. We will calculate distance via the generalized Euclidean formula (for n dimensions). Then, we will pick the class that appears most of the time in neighbors and that will be our pick. In code: " }, { "code": null, "e": 4252, "s": 4244, "text": "Python3" }, { "code": "def Classify(nItem, k, Items): if(k > len(Items)): # k is larger than list # length, abort return \"k larger than list length\"; # Hold nearest neighbors. # First item is distance, # second class neighbors = []; for item in Items: # Find Euclidean Distance distance = EuclideanDistance(nItem, item); # Update neighbors, either adding # the current item in neighbors # or not. neighbors = UpdateNeighbors(neighbors, item, distance, k); # Count the number of each # class in neighbors count = CalculateNeighborsClass(neighbors, k); # Find the max in count, aka the # class with the most appearances. return FindMax(count);", "e": 4995, "s": 4252, "text": null }, { "code": null, "e": 5118, "s": 4995, "text": "The external functions we need to implement are EuclideanDistance, UpdateNeighbors, CalculateNeighborsClass, and FindMax. " }, { "code": null, "e": 5145, "s": 5118, "text": "Finding Euclidean Distance" }, { "code": null, "e": 5213, "s": 5145, "text": "The generalized Euclidean formula for two vectors x and y is this: " }, { "code": null, "e": 5288, "s": 5213, "text": "distance = sqrt{(x_{1}-y_{1})^2 + (x_{2}-y_{2})^2 + ... + (x_{n}-y_{n})^2}" }, { "code": null, "e": 5298, "s": 5288, "text": "In code: " }, { "code": null, "e": 5306, "s": 5298, "text": "Python3" }, { "code": "def EuclideanDistance(x, y): # The sum of the squared # differences of the elements S = 0; for key in x.keys(): S += math.pow(x[key]-y[key], 2); # The square root of the sum return math.sqrt(S);", "e": 5537, "s": 5306, "text": null }, { "code": null, "e": 5556, "s": 5537, "text": "Updating Neighbors" }, { "code": null, "e": 6504, "s": 5556, "text": "We have our neighbors list (which should at most have a length of k) and we want to add an item to the list with a given distance. First, we will check if neighbors have a length of k. If it has less, we add the item to it regardless of the distance (as we need to fill the list up to k before we start rejecting items). If not, we will check if the item has a shorter distance than the item with the max distance in the list. If that is true, we will replace the item with max distance with the new item.To find the max distance item more quickly, we will keep the list sorted in ascending order. So, the last item in the list will have the max distance. We will replace it with a new item and we will sort it again.To speed this process up, we can implement an Insertion Sort where we insert new items in the list without having to sort the entire list. The code for this though is rather long and, although simple, will bog the tutorial down. " }, { "code": null, "e": 6512, "s": 6504, "text": "Python3" }, { "code": "def UpdateNeighbors(neighbors, item, distance, k): if(len(neighbors) > distance): # If yes, replace the last # element with new item neighbors[-1] = [distance, item[\"Class\"]]; neighbors = sorted(neighbors); return neighbors;", "e": 6806, "s": 6512, "text": null }, { "code": null, "e": 6830, "s": 6806, "text": "CalculateNeighborsClass" }, { "code": null, "e": 7098, "s": 6830, "text": "Here we will calculate the class that appears most often in neighbors. For that, we will use another dictionary, called count, where the keys are the class names appearing in neighbors. If a key doesn’t exist, we will add it, otherwise, we will increment its value. " }, { "code": null, "e": 7103, "s": 7098, "text": "pyth" }, { "code": null, "e": 7111, "s": 7103, "text": "Python3" }, { "code": "def CalculateNeighborsClass(neighbors, k): count = {}; for i in range(k): if(neighbors[i][1] not in count): # The class at the ith index # is not in the count dict. # Initialize it to 1. count[neighbors[i][1]] = 1; else: # Found another item of class # c[i]. Increment its counter. count[neighbors[i][1]] += 1; return count;", "e": 7573, "s": 7111, "text": null }, { "code": null, "e": 7581, "s": 7573, "text": "FindMax" }, { "code": null, "e": 7698, "s": 7581, "text": "We will input to this function the dictionary count we build in CalculateNeighborsClass and we will return its max. " }, { "code": null, "e": 7706, "s": 7698, "text": "Python3" }, { "code": "def FindMax(countList): # Hold the max maximum = -1; # Hold the classification classification = \"\"; for key in countList.keys(): if(countList[key] > maximum): maximum = countList[key]; classification = key; return classification, maximum;", "e": 8015, "s": 7706, "text": null }, { "code": null, "e": 8026, "s": 8015, "text": "Conclusion" }, { "code": null, "e": 8349, "s": 8026, "text": "With that, this kNN tutorial is finished.You can now classify new items, setting k as you see fit. Usually, for k an odd number is used, but that is not necessary. To classify a new item, you need to create a dictionary with keys the feature names, and the values that characterize the item. An example of classification: " }, { "code": null, "e": 8440, "s": 8349, "text": "newItem = {'Height' : 1.74, 'Weight' : 67, 'Age' : 22};\nprint Classify(newItem, 3, items);" }, { "code": null, "e": 8499, "s": 8440, "text": "The complete code of the above approach is given below:- " }, { "code": null, "e": 8507, "s": 8499, "text": "Python3" }, { "code": "# Python Program to illustrate# KNN algorithm # For pow and sqrtimport mathfrom random import shuffle ###_Reading_### def ReadData(fileName): # Read the file, splitting by lines f = open(fileName, 'r') lines = f.read().splitlines() f.close() # Split the first line by commas, # remove the first element and save # the rest into a list. The list # holds the feature names of the # data set. features = lines[0].split(', ')[:-1] items = [] for i in range(1, len(lines)): line = lines[i].split(', ') itemFeatures = {'Class': line[-1]} for j in range(len(features)): # Get the feature at index j f = features[j] # Convert feature value to float v = float(line[j]) # Add feature value to dict itemFeatures[f] = v items.append(itemFeatures) shuffle(items) return items ###_Auxiliary Function_### def EuclideanDistance(x, y): # The sum of the squared differences # of the elements S = 0 for key in x.keys(): S += math.pow(x[key] - y[key], 2) # The square root of the sum return math.sqrt(S) def CalculateNeighborsClass(neighbors, k): count = {} for i in range(k): if neighbors[i][1] not in count: # The class at the ith index is # not in the count dict. # Initialize it to 1. count[neighbors[i][1]] = 1 else: # Found another item of class # c[i]. Increment its counter. count[neighbors[i][1]] += 1 return count def FindMax(Dict): # Find max in dictionary, return # max value and max index maximum = -1 classification = '' for key in Dict.keys(): if Dict[key] > maximum: maximum = Dict[key] classification = key return (classification, maximum) ###_Core Functions_### def Classify(nItem, k, Items): # Hold nearest neighbours. First item # is distance, second class neighbors = [] for item in Items: # Find Euclidean Distance distance = EuclideanDistance(nItem, item) # Update neighbors, either adding the # current item in neighbors or not. neighbors = UpdateNeighbors(neighbors, item, distance, k) # Count the number of each class # in neighbors count = CalculateNeighborsClass(neighbors, k) # Find the max in count, aka the # class with the most appearances return FindMax(count) def UpdateNeighbors(neighbors, item, distance, k, ): if len(neighbors) < k: # List is not full, add # new item and sort neighbors.append([distance, item['Class']]) neighbors = sorted(neighbors) else: # List is full Check if new # item should be entered if neighbors[-1][0] > distance: # If yes, replace the # last element with new item neighbors[-1] = [distance, item['Class']] neighbors = sorted(neighbors) return neighbors ###_Evaluation Functions_### def K_FoldValidation(K, k, Items): if K > len(Items): return -1 # The number of correct classifications correct = 0 # The total number of classifications total = len(Items) * (K - 1) # The length of a fold l = int(len(Items) / K) for i in range(K): # Split data into training set # and test set trainingSet = Items[i * l:(i + 1) * l] testSet = Items[:i * l] + Items[(i + 1) * l:] for item in testSet: itemClass = item['Class'] itemFeatures = {} # Get feature values for key in item: if key != 'Class': # If key isn't \"Class\", add # it to itemFeatures itemFeatures[key] = item[key] # Categorize item based on # its feature values guess = Classify(itemFeatures, k, trainingSet)[0] if guess == itemClass: # Guessed correctly correct += 1 accuracy = correct / float(total) return accuracy def Evaluate(K, k, items, iterations): # Run algorithm the number of # iterations, pick average accuracy = 0 for i in range(iterations): shuffle(items) accuracy += K_FoldValidation(K, k, items) print accuracy / float(iterations) ###_Main_### def main(): items = ReadData('data.txt') Evaluate(5, 5, items, 100) if __name__ == '__main__': main()", "e": 13115, "s": 8507, "text": null }, { "code": null, "e": 13124, "s": 13115, "text": "Output: " }, { "code": null, "e": 13131, "s": 13124, "text": "0.9375" }, { "code": null, "e": 13319, "s": 13131, "text": "The output can vary from machine to machine. The code includes a Fold Validation function, but it is unrelated to the algorithm, it is there for calculating the accuracy of the algorithm." }, { "code": null, "e": 13336, "s": 13319, "text": "punamsingh628700" }, { "code": null, "e": 13352, "s": 13336, "text": "amartyaghoshgfg" }, { "code": null, "e": 13363, "s": 13352, "text": "Algorithms" }, { "code": null, "e": 13380, "s": 13363, "text": "Machine Learning" }, { "code": null, "e": 13391, "s": 13380, "text": "Algorithms" }, { "code": null, "e": 13408, "s": 13391, "text": "Machine Learning" }, { "code": null, "e": 13506, "s": 13408, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 13531, "s": 13506, "text": "DSA Sheet by Love Babbar" }, { "code": null, "e": 13580, "s": 13531, "text": "SDE SHEET - A Complete Guide for SDE Preparation" }, { "code": null, "e": 13618, "s": 13580, "text": "What is Hashing | A Complete Tutorial" }, { "code": null, "e": 13654, "s": 13618, "text": "CPU Scheduling in Operating Systems" }, { "code": null, "e": 13705, "s": 13654, "text": "Understanding Time Complexity with Simple Examples" }, { "code": null, "e": 13729, "s": 13705, "text": "Naive Bayes Classifiers" }, { "code": null, "e": 13743, "s": 13729, "text": "Decision Tree" }, { "code": null, "e": 13777, "s": 13743, "text": "Agents in Artificial Intelligence" }, { "code": null, "e": 13817, "s": 13777, "text": "Removing stop words with NLTK in Python" } ]
Power BI – Maps, Scatterplots and Interactive BI Reports
14 Feb, 2022 Prerequisite: Power BI – Timeseries, Aggregation, and Filters This article discusses some important concepts used to create interactive dashboards so as to make large business intelligence decisions. We will be discussing the following topics : MapsScatter plotsInteractive BI Reports Maps Scatter plots Interactive BI Reports Dataset Used: The Excel file ‘AmazingMartGeo‘ contains the 2 datasets- ListOfOrdersOrderBreakdown. ListOfOrders OrderBreakdown. On uploading the dataset in Power BI, it gets automatically joined. (You can read about different types of JOINS IN SQL to know the different ways datasets can be joined together). You can download the dataset from here: DATASET. The datasets are joined as shown in Fig 1. Fig 1: Power BI: Joins b/w datasets Maps: Using a Power BI map is a great way to visualize data that represent locations. With visually appealing maps and easy-to-understand content, your users will be able to gain more insight into your data. Before using Maps in Power BI, we need to first understand how to create and work with Hierarchies within the given dataset. Steps Involved: Step 1 - Select and expand the 'ListOfOrders' dataset from Fields panel. Step 2 - Select 'state' and 'city' columns one by one and drag and drop them into 'country' column. This will create a new hierarchy column in the dataset. Rename it as 'Geography'. (As showm in fig 2) Fig 2: Power BI: Creating Hierarchies After creating the Geography hierarchy, follow the steps given below to create a Map in Power BI. Steps Involved: Step 1 - Select 'Map' from Visualization panel and drag & drop it into report view. Step 2 - Drag Geography from Fields panel and drop into the Location. Step 3 - Drag lat and lon from Fields panel and drop into Langitude and Longitude. (As shown in fig 3) Fig 3: Power BI: Map If we perform Drilling into this map and expand down levels into the hierarchy, we can we the states and cities involved in the dataset as well. (As shown in Fig 4) Fig 4: Power BI: Drilling into hierarchies Calculated Columns vs Calculated Measures: Fig 5: Power BI: Column vs Measure Now that we understand the major differences between Column and Measure, let us create a calculated measure of our own. Steps Involved Step 1 - Go to 'OrderBreakdown' dataset in Fields panel and expand it. Step 2 - Right click on it and click on 'New Measure'. Step 3 - Now go the 'Formula Bar' under the Power BI Ribbon and type the following code. This will create a calculated measure (ProfitMargin) in the OrderBreakdown dataset. (as shown in Fig 6) Fig 6: Power BI: Creating calculated measures Scatter Plots: A Scatter Chart or Scatter plot is a very useful tool to visualize the relationship between two sets of data. It has two value axes to show- Horizontal axis: a set of numerical data. Vertical axis: a set of numerical values. Steps Involved: Step 1 - Select the scatter chart from the Visualization panel and drag it into the report view. Step 2 - From the Fields section, expand 'OrderBreakdown' dataset. Then drag and drop 2.a - Sales to x-axis 2.b - Profit to y-axis 2.c - Customer Name to details (As shown in Fig 7) Fig 7 : Power BI : Scatter Charts Step 3 - Now, go to Format --> Data colors --> Default color --> Conditional formatting. Step 4 - Do the following : 4.a - Set Based on field to ProfitMargin. 4.b - Set Min/Max colors for ProfitMargin. 4.c - Press OK. (As shown in fig 8) Fig 8 : Power BI : Conditional Formatting On following the above steps, we get a schematic, color coded Scatter plot. (As shown in Fig 9) Fig 9 : Power BI: Formatted Scatter Chart Introduction to an Interactive Business Intelligence Report: An Interactive BI Report provides a new way to display your Excel data in a variety of eye-catching, interactive reports. You can add various multiple visualizations to get important information out of the report. Here is an example BI Report containing maps, scatter plots, slicers and donut chart. Steps Involved: Step 1 - Create a new page. Step 2 - Simply copy your previous visualizations (Map and Scatter plot) and paste it onto the new page. Step 3 - Drag and drop two slicers from Visualization pane. Then, from the 'ListOfOrders' dataset drag and drop : 3.a - OrderDate into first slicer. 3.b - Region into second slicer. (As shown in Fig 10) Fig 10: Power BI: Interactive BI Report Note: You can always go to the Format panel of each of these visualizations and change its aspects like Text size, color etc. as per your preferences. Donut Chart: A doughnut chart is similar to a pie chart as it shows the relationship of parts to a whole. The only difference is that the centre is blank and allows space for a label or icon. Steps Involved: Step 1 - Select 2 Donut chart from the Visualization panel and drag it into the Report view. Step 2 - Select OrderDate from'ListOfOrders' dataset and drag it into the donut chart. Step 3 - Select Profit from 'ListOfOrders' dataset and drag it into the values section. (as shown in Fig 11) Fig 11: Power BI: Donut Chart Making Interactive BI Reports is an important skill used by businessmen around the world to make important company decisions. Above is one of the examples of making a Report on Power BI. You can use various visualizations. Combine them with filters and slicers to create a business intelligence report of your own. For doubts/queries, comment below. surindertarika1234 sumitgumber28 Power-BI Machine Learning Machine Learning Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n14 Feb, 2022" }, { "code": null, "e": 91, "s": 28, "text": "Prerequisite: Power BI – Timeseries, Aggregation, and Filters " }, { "code": null, "e": 276, "s": 91, "text": "This article discusses some important concepts used to create interactive dashboards so as to make large business intelligence decisions. We will be discussing the following topics : " }, { "code": null, "e": 316, "s": 276, "text": "MapsScatter plotsInteractive BI Reports" }, { "code": null, "e": 321, "s": 316, "text": "Maps" }, { "code": null, "e": 335, "s": 321, "text": "Scatter plots" }, { "code": null, "e": 358, "s": 335, "text": "Interactive BI Reports" }, { "code": null, "e": 431, "s": 358, "text": "Dataset Used: The Excel file ‘AmazingMartGeo‘ contains the 2 datasets- " }, { "code": null, "e": 459, "s": 431, "text": "ListOfOrdersOrderBreakdown." }, { "code": null, "e": 472, "s": 459, "text": "ListOfOrders" }, { "code": null, "e": 488, "s": 472, "text": "OrderBreakdown." }, { "code": null, "e": 762, "s": 488, "text": "On uploading the dataset in Power BI, it gets automatically joined. (You can read about different types of JOINS IN SQL to know the different ways datasets can be joined together). You can download the dataset from here: DATASET. The datasets are joined as shown in Fig 1. " }, { "code": null, "e": 798, "s": 762, "text": "Fig 1: Power BI: Joins b/w datasets" }, { "code": null, "e": 1133, "s": 798, "text": "Maps: Using a Power BI map is a great way to visualize data that represent locations. With visually appealing maps and easy-to-understand content, your users will be able to gain more insight into your data. Before using Maps in Power BI, we need to first understand how to create and work with Hierarchies within the given dataset. " }, { "code": null, "e": 1438, "s": 1133, "text": "Steps Involved: \n\nStep 1 - Select and expand the 'ListOfOrders' dataset from Fields panel.\nStep 2 - Select 'state' and 'city' columns one by one and drag and drop them\n into 'country' column.\n\nThis will create a new hierarchy column in the dataset. Rename it as 'Geography'.\n(As showm in fig 2) " }, { "code": null, "e": 1476, "s": 1438, "text": "Fig 2: Power BI: Creating Hierarchies" }, { "code": null, "e": 1575, "s": 1476, "text": "After creating the Geography hierarchy, follow the steps given below to create a Map in Power BI. " }, { "code": null, "e": 1851, "s": 1575, "text": "Steps Involved: \n\nStep 1 - Select 'Map' from Visualization panel and drag & drop it into report view.\nStep 2 - Drag Geography from Fields panel and drop into the Location.\nStep 3 - Drag lat and lon from Fields panel and drop into Langitude and Longitude.\n\n(As shown in fig 3)" }, { "code": null, "e": 1872, "s": 1851, "text": "Fig 3: Power BI: Map" }, { "code": null, "e": 2040, "s": 1874, "text": "If we perform Drilling into this map and expand down levels into the hierarchy, we can we the states and cities involved in the dataset as well. (As shown in Fig 4) " }, { "code": null, "e": 2085, "s": 2042, "text": "Fig 4: Power BI: Drilling into hierarchies" }, { "code": null, "e": 2131, "s": 2087, "text": "Calculated Columns vs Calculated Measures: " }, { "code": null, "e": 2169, "s": 2133, "text": "Fig 5: Power BI: Column vs Measure " }, { "code": null, "e": 2293, "s": 2171, "text": "Now that we understand the major differences between Column and Measure, let us create a calculated measure of our own. " }, { "code": null, "e": 2528, "s": 2295, "text": "Steps Involved\n\nStep 1 - Go to 'OrderBreakdown' dataset in Fields panel and expand it.\nStep 2 - Right click on it and click on 'New Measure'.\nStep 3 - Now go the 'Formula Bar' under the Power BI Ribbon and type the following code.\n " }, { "code": null, "e": 2634, "s": 2530, "text": "This will create a calculated measure (ProfitMargin) in the OrderBreakdown dataset. (as shown in Fig 6)" }, { "code": null, "e": 2680, "s": 2634, "text": "Fig 6: Power BI: Creating calculated measures" }, { "code": null, "e": 2840, "s": 2682, "text": "Scatter Plots: A Scatter Chart or Scatter plot is a very useful tool to visualize the relationship between two sets of data. It has two value axes to show- " }, { "code": null, "e": 2882, "s": 2840, "text": "Horizontal axis: a set of numerical data." }, { "code": null, "e": 2924, "s": 2882, "text": "Vertical axis: a set of numerical values." }, { "code": null, "e": 3237, "s": 2924, "text": "Steps Involved: \n\nStep 1 - Select the scatter chart from the Visualization panel and drag it into the report view.\n \nStep 2 - From the Fields section, expand 'OrderBreakdown' dataset. Then drag and drop\n 2.a - Sales to x-axis\n 2.b - Profit to y-axis\n 2.c - Customer Name to details\n\n(As shown in Fig 7)" }, { "code": null, "e": 3271, "s": 3237, "text": "Fig 7 : Power BI : Scatter Charts" }, { "code": null, "e": 3527, "s": 3271, "text": "Step 3 - Now, go to Format --> Data colors --> Default color --> Conditional formatting. \n\nStep 4 - Do the following : \n 4.a - Set Based on field to ProfitMargin.\n 4.b - Set Min/Max colors for ProfitMargin.\n 4.c - Press OK.\n\n(As shown in fig 8)" }, { "code": null, "e": 3569, "s": 3527, "text": "Fig 8 : Power BI : Conditional Formatting" }, { "code": null, "e": 3665, "s": 3569, "text": "On following the above steps, we get a schematic, color coded Scatter plot. (As shown in Fig 9)" }, { "code": null, "e": 3707, "s": 3665, "text": "Fig 9 : Power BI: Formatted Scatter Chart" }, { "code": null, "e": 4070, "s": 3707, "text": "Introduction to an Interactive Business Intelligence Report: An Interactive BI Report provides a new way to display your Excel data in a variety of eye-catching, interactive reports. You can add various multiple visualizations to get important information out of the report. Here is an example BI Report containing maps, scatter plots, slicers and donut chart. " }, { "code": null, "e": 4432, "s": 4070, "text": "Steps Involved:\nStep 1 - Create a new page.\nStep 2 - Simply copy your previous visualizations (Map and Scatter plot) and paste it onto the new page.\nStep 3 - Drag and drop two slicers from Visualization pane. Then, from the 'ListOfOrders' dataset drag and drop :\n 3.a - OrderDate into first slicer.\n 3.b - Region into second slicer. \n\n(As shown in Fig 10)" }, { "code": null, "e": 4472, "s": 4432, "text": "Fig 10: Power BI: Interactive BI Report" }, { "code": null, "e": 4628, "s": 4472, "text": "Note: You can always go to the Format panel of each of these visualizations and change its aspects like Text size, color etc. as per your preferences. " }, { "code": null, "e": 4823, "s": 4628, "text": "Donut Chart: A doughnut chart is similar to a pie chart as it shows the relationship of parts to a whole. The only difference is that the centre is blank and allows space for a label or icon. " }, { "code": null, "e": 5133, "s": 4823, "text": "Steps Involved: \nStep 1 - Select 2 Donut chart from the Visualization panel and drag it into the Report view.\nStep 2 - Select OrderDate from'ListOfOrders' dataset and drag it into the donut chart.\nStep 3 - Select Profit from 'ListOfOrders' dataset and drag it into the values section.\n \n(as shown in Fig 11) " }, { "code": null, "e": 5163, "s": 5133, "text": "Fig 11: Power BI: Donut Chart" }, { "code": null, "e": 5513, "s": 5163, "text": "Making Interactive BI Reports is an important skill used by businessmen around the world to make important company decisions. Above is one of the examples of making a Report on Power BI. You can use various visualizations. Combine them with filters and slicers to create a business intelligence report of your own. For doubts/queries, comment below." }, { "code": null, "e": 5532, "s": 5513, "text": "surindertarika1234" }, { "code": null, "e": 5546, "s": 5532, "text": "sumitgumber28" }, { "code": null, "e": 5555, "s": 5546, "text": "Power-BI" }, { "code": null, "e": 5572, "s": 5555, "text": "Machine Learning" }, { "code": null, "e": 5589, "s": 5572, "text": "Machine Learning" } ]
How to get the number of days in a specified month using JavaScript ?
30 May, 2019 Given a month and the task is to determine the number of days of that month using JavaScript. JavaScript getDate() Method: This method returns the number of days in a month (from 1 to 31) for the defined date.Syntax:Date.getDate()Return value: It returns a number, from 1 to 31, representing the day of the month. Syntax: Date.getDate() Return value: It returns a number, from 1 to 31, representing the day of the month. JavaScript getFullYear() Method: This method returns the year (four digits for dates between year 1000 and 9999) of the defined date.Syntax:Date.getFullYear()Return value: It returns a number, representing the year of the defined date Syntax: Date.getFullYear() Return value: It returns a number, representing the year of the defined date JavaScript getMonth() Method: This method returns the month (from 0 to 11) for the defined date, based on to local time.Syntax:Date.getMonth()Return value: It returns a number, from 0 to 11, representing the month. Syntax: Date.getMonth() Return value: It returns a number, from 0 to 11, representing the month. Example 1: This example gets the days in the month (february) of the year (2020) by passing the month (1-12) and year to the function daysInMonth. <!DOCTYPE HTML> <html> <head> <title> Get number of days in a specified month </title> </head> <body style = "text-align:center;"> <h1 style = "color:green;" > GeeksForGeeks </h1> <p id = "GFG_UP" style = "font-size: 15px; font-weight: bold;"> </p> <button onclick = "GFG_Fun()"> click here </button> <p id = "GFG_DOWN" style = "color:green; font-size: 20px; font-weight: bold;"> </p> <script> var up = document.getElementById('GFG_UP'); up.innerHTML = "Click on button to get the" + " number of days in specified month"; var down = document.getElementById('GFG_DOWN'); function daysInMonth (month, year) { return new Date(year, month, 0).getDate(); } function GFG_Fun() { var date = new Date(); var month = 2; var year = 2020; down.innerHTML = "Number of days in " + month + "nd month of the year " + year +" is "+ daysInMonth(month, year); } </script> </body> </html> Output: Before clicking on the button: After clicking on the button: Example 2: This example gets the days in the current month of the current year by passing the month (1-12) and year to the function daysInMonth. <!DOCTYPE HTML> <html> <head> <title> Get number of days in a specified month </title> </head> <body style = "text-align:center;"> <h1 style = "color:green;" > GeeksForGeeks </h1> <p id = "GFG_UP" style = "font-size: 15px; font-weight: bold;"> </p> <button onclick = "GFG_Fun()"> click here </button> <p id = "GFG_DOWN" style = "color:green; font-size: 20px; font-weight: bold;"> </p> <script> var up = document.getElementById('GFG_UP'); up.innerHTML = "Click on button to get the number" + " of days in specified month"; var down = document.getElementById('GFG_DOWN'); function daysInMonth (month, year) { return new Date(year, month, 0).getDate(); } function GFG_Fun() { var date = new Date(); var month = date.getMonth() + 1; var year = date.getFullYear(); down.innerHTML = "Number of days in " + month + "th month of the year " + year +" is "+ daysInMonth(month, year); } </script> </body> </html> Output: Before clicking on the button: After clicking on the button: javascript-date JavaScript Web Technologies Web technologies Questions Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Difference between var, let and const keywords in JavaScript Differences between Functional Components and Class Components in React Remove elements from a JavaScript Array Roadmap to Learn JavaScript For Beginners Difference Between PUT and PATCH Request Installation of Node.js on Linux Top 10 Projects For Beginners To Practice HTML and CSS Skills Difference between var, let and const keywords in JavaScript How to insert spaces/tabs in text using HTML/CSS? How to fetch data from an API in ReactJS ?
[ { "code": null, "e": 28, "s": 0, "text": "\n30 May, 2019" }, { "code": null, "e": 122, "s": 28, "text": "Given a month and the task is to determine the number of days of that month using JavaScript." }, { "code": null, "e": 342, "s": 122, "text": "JavaScript getDate() Method: This method returns the number of days in a month (from 1 to 31) for the defined date.Syntax:Date.getDate()Return value: It returns a number, from 1 to 31, representing the day of the month." }, { "code": null, "e": 350, "s": 342, "text": "Syntax:" }, { "code": null, "e": 365, "s": 350, "text": "Date.getDate()" }, { "code": null, "e": 449, "s": 365, "text": "Return value: It returns a number, from 1 to 31, representing the day of the month." }, { "code": null, "e": 684, "s": 449, "text": "JavaScript getFullYear() Method: This method returns the year (four digits for dates between year 1000 and 9999) of the defined date.Syntax:Date.getFullYear()Return value: It returns a number, representing the year of the defined date" }, { "code": null, "e": 692, "s": 684, "text": "Syntax:" }, { "code": null, "e": 711, "s": 692, "text": "Date.getFullYear()" }, { "code": null, "e": 788, "s": 711, "text": "Return value: It returns a number, representing the year of the defined date" }, { "code": null, "e": 1003, "s": 788, "text": "JavaScript getMonth() Method: This method returns the month (from 0 to 11) for the defined date, based on to local time.Syntax:Date.getMonth()Return value: It returns a number, from 0 to 11, representing the month." }, { "code": null, "e": 1011, "s": 1003, "text": "Syntax:" }, { "code": null, "e": 1027, "s": 1011, "text": "Date.getMonth()" }, { "code": null, "e": 1100, "s": 1027, "text": "Return value: It returns a number, from 0 to 11, representing the month." }, { "code": null, "e": 1247, "s": 1100, "text": "Example 1: This example gets the days in the month (february) of the year (2020) by passing the month (1-12) and year to the function daysInMonth." }, { "code": "<!DOCTYPE HTML> <html> <head> <title> Get number of days in a specified month </title> </head> <body style = \"text-align:center;\"> <h1 style = \"color:green;\" > GeeksForGeeks </h1> <p id = \"GFG_UP\" style = \"font-size: 15px; font-weight: bold;\"> </p> <button onclick = \"GFG_Fun()\"> click here </button> <p id = \"GFG_DOWN\" style = \"color:green; font-size: 20px; font-weight: bold;\"> </p> <script> var up = document.getElementById('GFG_UP'); up.innerHTML = \"Click on button to get the\" + \" number of days in specified month\"; var down = document.getElementById('GFG_DOWN'); function daysInMonth (month, year) { return new Date(year, month, 0).getDate(); } function GFG_Fun() { var date = new Date(); var month = 2; var year = 2020; down.innerHTML = \"Number of days in \" + month + \"nd month of the year \" + year +\" is \"+ daysInMonth(month, year); } </script> </body> </html> ", "e": 2652, "s": 1247, "text": null }, { "code": null, "e": 2660, "s": 2652, "text": "Output:" }, { "code": null, "e": 2691, "s": 2660, "text": "Before clicking on the button:" }, { "code": null, "e": 2721, "s": 2691, "text": "After clicking on the button:" }, { "code": null, "e": 2866, "s": 2721, "text": "Example 2: This example gets the days in the current month of the current year by passing the month (1-12) and year to the function daysInMonth." }, { "code": "<!DOCTYPE HTML> <html> <head> <title> Get number of days in a specified month </title> </head> <body style = \"text-align:center;\"> <h1 style = \"color:green;\" > GeeksForGeeks </h1> <p id = \"GFG_UP\" style = \"font-size: 15px; font-weight: bold;\"> </p> <button onclick = \"GFG_Fun()\"> click here </button> <p id = \"GFG_DOWN\" style = \"color:green; font-size: 20px; font-weight: bold;\"> </p> <script> var up = document.getElementById('GFG_UP'); up.innerHTML = \"Click on button to get the number\" + \" of days in specified month\"; var down = document.getElementById('GFG_DOWN'); function daysInMonth (month, year) { return new Date(year, month, 0).getDate(); } function GFG_Fun() { var date = new Date(); var month = date.getMonth() + 1; var year = date.getFullYear(); down.innerHTML = \"Number of days in \" + month + \"th month of the year \" + year +\" is \"+ daysInMonth(month, year); } </script> </body> </html> ", "e": 4289, "s": 2866, "text": null }, { "code": null, "e": 4297, "s": 4289, "text": "Output:" }, { "code": null, "e": 4328, "s": 4297, "text": "Before clicking on the button:" }, { "code": null, "e": 4358, "s": 4328, "text": "After clicking on the button:" }, { "code": null, "e": 4374, "s": 4358, "text": "javascript-date" }, { "code": null, "e": 4385, "s": 4374, "text": "JavaScript" }, { "code": null, "e": 4402, "s": 4385, "text": "Web Technologies" }, { "code": null, "e": 4429, "s": 4402, "text": "Web technologies Questions" }, { "code": null, "e": 4527, "s": 4429, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 4588, "s": 4527, "text": "Difference between var, let and const keywords in JavaScript" }, { "code": null, "e": 4660, "s": 4588, "text": "Differences between Functional Components and Class Components in React" }, { "code": null, "e": 4700, "s": 4660, "text": "Remove elements from a JavaScript Array" }, { "code": null, "e": 4742, "s": 4700, "text": "Roadmap to Learn JavaScript For Beginners" }, { "code": null, "e": 4783, "s": 4742, "text": "Difference Between PUT and PATCH Request" }, { "code": null, "e": 4816, "s": 4783, "text": "Installation of Node.js on Linux" }, { "code": null, "e": 4878, "s": 4816, "text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills" }, { "code": null, "e": 4939, "s": 4878, "text": "Difference between var, let and const keywords in JavaScript" }, { "code": null, "e": 4989, "s": 4939, "text": "How to insert spaces/tabs in text using HTML/CSS?" } ]
C++ Tuple Library - tie
It constructs a tuple object whose elements are references to the arguments in args, in the same order. Following is the declaration for std::tie. template<class... Types> tuple<Types&...> tie (Types&... args) noexcept; template<class... Types> tuple<Types&...> tie (Types&... args) noexcept; template<class... Types> constexpr tuple<Types&...> tie (Types&... args) noexcept; args − It contains list of elements that the constructed tuple shall contain. It returns a tuple with lvalue references to args. No-throw guarantee − this member function never throws exceptions. None introduced by this call. In below example for std::tie. #include <iostream> #include <tuple> int main () { int myint; char mychar; std::tuple<int,float,char> mytuple; mytuple = std::make_tuple (10, 2.6, 'a'); std::tie (myint, std::ignore, mychar) = mytuple; std::cout << "myint contains: " << myint << '\n'; std::cout << "mychar contains: " << mychar << '\n'; return 0; } The output should be like this − myint contains: 10 mychar contains: a Print Add Notes Bookmark this page
[ { "code": null, "e": 2707, "s": 2603, "text": "It constructs a tuple object whose elements are references to the arguments in args, in the same order." }, { "code": null, "e": 2750, "s": 2707, "text": "Following is the declaration for std::tie." }, { "code": null, "e": 2828, "s": 2750, "text": "\t\ntemplate<class... Types>\n tuple<Types&...> tie (Types&... args) noexcept;" }, { "code": null, "e": 2904, "s": 2828, "text": "template<class... Types>\n tuple<Types&...> tie (Types&... args) noexcept;" }, { "code": null, "e": 2990, "s": 2904, "text": "template<class... Types>\n constexpr tuple<Types&...> tie (Types&... args) noexcept;" }, { "code": null, "e": 3068, "s": 2990, "text": "args − It contains list of elements that the constructed tuple shall contain." }, { "code": null, "e": 3119, "s": 3068, "text": "It returns a tuple with lvalue references to args." }, { "code": null, "e": 3186, "s": 3119, "text": "No-throw guarantee − this member function never throws exceptions." }, { "code": null, "e": 3216, "s": 3186, "text": "None introduced by this call." }, { "code": null, "e": 3247, "s": 3216, "text": "In below example for std::tie." }, { "code": null, "e": 3593, "s": 3247, "text": "#include <iostream>\n#include <tuple>\n\nint main () {\n int myint;\n char mychar;\n\n std::tuple<int,float,char> mytuple;\n\n mytuple = std::make_tuple (10, 2.6, 'a');\n\n std::tie (myint, std::ignore, mychar) = mytuple;\n\n std::cout << \"myint contains: \" << myint << '\\n';\n std::cout << \"mychar contains: \" << mychar << '\\n';\n\n return 0;\n}" }, { "code": null, "e": 3626, "s": 3593, "text": "The output should be like this −" }, { "code": null, "e": 3665, "s": 3626, "text": "myint contains: 10\nmychar contains: a\n" }, { "code": null, "e": 3672, "s": 3665, "text": " Print" }, { "code": null, "e": 3683, "s": 3672, "text": " Add Notes" } ]
How to Deploy a Pre-trained Keras Model with OpenCV and Flask | by Jacob Tadesse | Towards Data Science
In this post, I will share how to deploy a pre-trained model to a locally hosted computer with Flask, OpenCV and Keras. I initially deployed this model on PythonAnywhere using Flask, Keras and jquery. The application was designed for remote school classroom or workplace settings that require students or employees to shave their facial hair. The application allowed users to upload a photo, and click a button to send a post request with the encoded image data to the backend of the website. The image transformation and classification were handled on the backend, and the results were returned to the front-end in an html response. The response updated the page dynamically, as Shaved or Unshaved. The backend of the application was built in Flask, but I wanted to allow a live video stream that would detect a user’s face, labeling the classification on screen. So since I already had a model and a basic Flask framework, I wanted to use OpenCV to do the rest on my local machine. If you have a model, you can follow the same format, but if you do not, I would recommend reading my previous blog posts (Building a Convolutional Neural Network to Recognize Shaved vs UnShaved Faces & How to Split a Pickled Model File to Bypass Upload Limits on PythonAnywhere). OpenCV (Open Source Computer Vision Library) is an open source computer vision and machine learning software library. OpenCV was built to provide a common infrastructure for computer vision applications and to accelerate the use of machine perception in the commercial products. https://opencv.org/about/ After reading documentation, watching YouTube videos, and reading blog posts, I found a very helpful article, COVID-19: Face Mask Detection using TensorFlow and OpenCV by Gurucharan M K. While Gurucharan used OpenCV to detect Face Masks for COVID-19, I wanted to use a similar format to detect if a faces first, then determine if the face was shaved or not. The most helpful piece to my puzzle was detecting the faces first, and this was accomplished by using the Face detection program the Haar Feature-based Cascade Classifiers for detecting the features of a face. face_classifier = cv2.CascadeClassifier('haarcascade_frontalface_default.xml') Haar Cascade is a machine learning object detection algorithm used to identify objects in an image or video and based on the concept of ​​ features proposed by Paul Viola and Michael Jones in their paper “Rapid Object Detection using a Boosted Cascade of Simple Features” in 2001 http://www.willberger.org/cascade-haar-explained/ Video Capture video = cv2.VideoCapture(0) Stop Video video.release() Display Video (rval, im) =video.read() Flip Video im = cv2.flip(im, 1, 1) Resize Video mini = cv2.resize(im, (im.shape[1] // 4, im.shape[0] // 4)) Detect Faces faces = face_classifier.detectMultiScale(mini) Flask is a micro web framework written in Python. It is classified as a microframework because it does not require particular tools or libraries. It has no database abstraction layer, form validation, or any other components where pre-existing third-party libraries provide common functions. Anmol Behl has a well-written article entitled, “Video Streaming Using Flask and OpenCV“. Following this article, I was able to build out an html webpage template, as well as the routes needed to stream video for each frame’s predictions to the browser using the computer’s built-in camera. The html page was similar to the page I built before, without the jquery. Here is the simple index.html code I used to display the homepage: <!DOCTYPE html><html lang="en"> <head> <title>Shaved or Not_Shaved </title></head> </head> <body> <center><h1>Shaved or Not_Shaved Streaming App Demo</h1></center> <center><img id="bg" src="{{ url_for('video_feed') }}"></center> <video id="video" autoplay>Video Stream not available.</video> </body></html> To build out the routes, I used the following code to handle when the page was loaded, as well as the video camera images pulled from our camera.py file that is initialized when the website is loaded. Here is the Flask code I used in the main.py file: from flask import Flask, render_template, Responsefrom camera import VideoCameraimport osos.environ['TF_CPP_MIN_LOG_LEVEL'] = '2'app = Flask(__name__)@app.route('/')def index(): # rendering webpage return render_template('index.html')def gen(camera): while True: #get camera frame frame = camera.get_frame() yield (b'--frame\r\n' b'Content-Type: image/jpeg\r\n\r\n' + frame + b'\r\n\r\n')@app.route('/video_feed')def video_feed(): return Response(gen(VideoCamera()), mimetype='multipart/x-mixed-replace; boundary=frame')if __name__ == '__main__': # defining server ip address and port app.run(host='0.0.0.0',port='5000', debug=True) Keras is a deep learning API written in Python, running on top of the machine learning platform TensorFlow. It was developed with a focus on enabling fast experimentation. Being able to go from idea to result as fast as possible is key to doing good research. https://keras.io/about/ Since Keras runs on top of TensorFlow, we can utilize the Graph and Session methods from the TensorFlow module. While the detail of graph and session is outside of the scope of this article, you can still use the following code when deploying your model to be accessible during scheduled sessions. import picklefrom keras import backend as Kfrom tensorflow import Graph, Sessionglobal loaded_modelgraph1 = Graph()with graph1.as_default(): session1 = Session(graph=graph1) with session1.as_default(): loaded_model = pickle.load(open('Combined_Model.p', 'rb')) The final piece is our camera.py file. In this example, our file will contain a function to join our split model into one pickle file. We will use a class VideoCamera to initiallize the camera when the app loads, and also combine the face detection program with our pre-trained Keras model. import cv2import numpy as npimport picklefrom keras import backend as Kfrom tensorflow import Graph, Session# defining face detectorclassifier=cv2.CascadeClassifier('haarcascade_frontalface_default.xml')size = 4labels_dict={0:'shaved',1:'not_shaved'}color_dict={0:(0,255,0),1:(0,0,255)}global loaded_modelgraph1 = Graph()with graph1.as_default(): session1 = Session(graph=graph1) with session1.as_default(): loaded_model = pickle.load(open('Combined_Model.p', 'rb'))class VideoCamera(object): def __init__(self): # capturing video self.video = cv2.VideoCapture(0) def __del__(self): # releasing camera self.video.release() def get_frame(self): # extracting frames (rval, im) = self.video.read() im = cv2.flip(im, 1, 1) mini = cv2.resize(im, (im.shape[1] // size, im.shape[0] // size)) faces = classifier.detectMultiScale(mini) for f in faces: (x, y, w, h) = [v * size for v in f] #Scale the shapesize backup #Save just the rectangle faces in SubRecFaces face_img = im[y:y+h, x:x+w] resized=cv2.resize(face_img,(300,300)) normalized=resized/255.0 reshaped=np.reshape(normalized,(1,300,300,3)) reshaped = np.vstack([reshaped]) K.set_session(session1) with graph1.as_default(): results=loaded_model.predict(reshaped) if results >.5: result = np.array([[1]]) else: result = np.array([[0]]) label = np.argmax(result) cv2.rectangle(im,(x,y),(x+w,y+h),color_dict[result[label][0]],2) cv2.rectangle(im,(x,y-40),(x+w,y),color_dict[result[label][0]],-1) cv2.putText(im, labels_dict[result[label][0]], (x, y-10),cv2.FONT_HERSHEY_SIMPLEX,0.8,(255,255,255),2) # encode OpenCV raw frame to jpg and displaying it ret, jpeg = cv2.imencode('.jpg', im) return jpeg.tobytes() Please note that this application is limited to your local computer. I hope this article is helpful. I would love to deploy this model publicly using Node.js, Tensorflow.js and OpenCV.js, but this is outside the scope of this article. If I get 100 comments, I will make that my next post! https://github.com/cousinskeeta/shavedVnotShaved_opencv COVID-19: Face Mask Detection using TensorFlow and OpenCV by Gurucharan M K Video Streaming Using Flask and OpenCV by Anmol Behl
[ { "code": null, "e": 514, "s": 171, "text": "In this post, I will share how to deploy a pre-trained model to a locally hosted computer with Flask, OpenCV and Keras. I initially deployed this model on PythonAnywhere using Flask, Keras and jquery. The application was designed for remote school classroom or workplace settings that require students or employees to shave their facial hair." }, { "code": null, "e": 871, "s": 514, "text": "The application allowed users to upload a photo, and click a button to send a post request with the encoded image data to the backend of the website. The image transformation and classification were handled on the backend, and the results were returned to the front-end in an html response. The response updated the page dynamically, as Shaved or Unshaved." }, { "code": null, "e": 1155, "s": 871, "text": "The backend of the application was built in Flask, but I wanted to allow a live video stream that would detect a user’s face, labeling the classification on screen. So since I already had a model and a basic Flask framework, I wanted to use OpenCV to do the rest on my local machine." }, { "code": null, "e": 1435, "s": 1155, "text": "If you have a model, you can follow the same format, but if you do not, I would recommend reading my previous blog posts (Building a Convolutional Neural Network to Recognize Shaved vs UnShaved Faces & How to Split a Pickled Model File to Bypass Upload Limits on PythonAnywhere)." }, { "code": null, "e": 1714, "s": 1435, "text": "OpenCV (Open Source Computer Vision Library) is an open source computer vision and machine learning software library. OpenCV was built to provide a common infrastructure for computer vision applications and to accelerate the use of machine perception in the commercial products." }, { "code": null, "e": 1740, "s": 1714, "text": "https://opencv.org/about/" }, { "code": null, "e": 2098, "s": 1740, "text": "After reading documentation, watching YouTube videos, and reading blog posts, I found a very helpful article, COVID-19: Face Mask Detection using TensorFlow and OpenCV by Gurucharan M K. While Gurucharan used OpenCV to detect Face Masks for COVID-19, I wanted to use a similar format to detect if a faces first, then determine if the face was shaved or not." }, { "code": null, "e": 2308, "s": 2098, "text": "The most helpful piece to my puzzle was detecting the faces first, and this was accomplished by using the Face detection program the Haar Feature-based Cascade Classifiers for detecting the features of a face." }, { "code": null, "e": 2387, "s": 2308, "text": "face_classifier = cv2.CascadeClassifier('haarcascade_frontalface_default.xml')" }, { "code": null, "e": 2667, "s": 2387, "text": "Haar Cascade is a machine learning object detection algorithm used to identify objects in an image or video and based on the concept of ​​ features proposed by Paul Viola and Michael Jones in their paper “Rapid Object Detection using a Boosted Cascade of Simple Features” in 2001" }, { "code": null, "e": 2717, "s": 2667, "text": "http://www.willberger.org/cascade-haar-explained/" }, { "code": null, "e": 2731, "s": 2717, "text": "Video Capture" }, { "code": null, "e": 2759, "s": 2731, "text": "video = cv2.VideoCapture(0)" }, { "code": null, "e": 2770, "s": 2759, "text": "Stop Video" }, { "code": null, "e": 2786, "s": 2770, "text": "video.release()" }, { "code": null, "e": 2800, "s": 2786, "text": "Display Video" }, { "code": null, "e": 2825, "s": 2800, "text": "(rval, im) =video.read()" }, { "code": null, "e": 2836, "s": 2825, "text": "Flip Video" }, { "code": null, "e": 2860, "s": 2836, "text": "im = cv2.flip(im, 1, 1)" }, { "code": null, "e": 2873, "s": 2860, "text": "Resize Video" }, { "code": null, "e": 2933, "s": 2873, "text": "mini = cv2.resize(im, (im.shape[1] // 4, im.shape[0] // 4))" }, { "code": null, "e": 2946, "s": 2933, "text": "Detect Faces" }, { "code": null, "e": 2993, "s": 2946, "text": "faces = face_classifier.detectMultiScale(mini)" }, { "code": null, "e": 3285, "s": 2993, "text": "Flask is a micro web framework written in Python. It is classified as a microframework because it does not require particular tools or libraries. It has no database abstraction layer, form validation, or any other components where pre-existing third-party libraries provide common functions." }, { "code": null, "e": 3576, "s": 3285, "text": "Anmol Behl has a well-written article entitled, “Video Streaming Using Flask and OpenCV“. Following this article, I was able to build out an html webpage template, as well as the routes needed to stream video for each frame’s predictions to the browser using the computer’s built-in camera." }, { "code": null, "e": 3650, "s": 3576, "text": "The html page was similar to the page I built before, without the jquery." }, { "code": null, "e": 3717, "s": 3650, "text": "Here is the simple index.html code I used to display the homepage:" }, { "code": null, "e": 4040, "s": 3717, "text": "<!DOCTYPE html><html lang=\"en\"> <head> <title>Shaved or Not_Shaved </title></head> </head> <body> <center><h1>Shaved or Not_Shaved Streaming App Demo</h1></center> <center><img id=\"bg\" src=\"{{ url_for('video_feed') }}\"></center> <video id=\"video\" autoplay>Video Stream not available.</video> </body></html>" }, { "code": null, "e": 4241, "s": 4040, "text": "To build out the routes, I used the following code to handle when the page was loaded, as well as the video camera images pulled from our camera.py file that is initialized when the website is loaded." }, { "code": null, "e": 4292, "s": 4241, "text": "Here is the Flask code I used in the main.py file:" }, { "code": null, "e": 4997, "s": 4292, "text": "from flask import Flask, render_template, Responsefrom camera import VideoCameraimport osos.environ['TF_CPP_MIN_LOG_LEVEL'] = '2'app = Flask(__name__)@app.route('/')def index(): # rendering webpage return render_template('index.html')def gen(camera): while True: #get camera frame frame = camera.get_frame() yield (b'--frame\\r\\n' b'Content-Type: image/jpeg\\r\\n\\r\\n' + frame + b'\\r\\n\\r\\n')@app.route('/video_feed')def video_feed(): return Response(gen(VideoCamera()), mimetype='multipart/x-mixed-replace; boundary=frame')if __name__ == '__main__': # defining server ip address and port app.run(host='0.0.0.0',port='5000', debug=True)" }, { "code": null, "e": 5257, "s": 4997, "text": "Keras is a deep learning API written in Python, running on top of the machine learning platform TensorFlow. It was developed with a focus on enabling fast experimentation. Being able to go from idea to result as fast as possible is key to doing good research." }, { "code": null, "e": 5281, "s": 5257, "text": "https://keras.io/about/" }, { "code": null, "e": 5579, "s": 5281, "text": "Since Keras runs on top of TensorFlow, we can utilize the Graph and Session methods from the TensorFlow module. While the detail of graph and session is outside of the scope of this article, you can still use the following code when deploying your model to be accessible during scheduled sessions." }, { "code": null, "e": 5841, "s": 5579, "text": "import picklefrom keras import backend as Kfrom tensorflow import Graph, Sessionglobal loaded_modelgraph1 = Graph()with graph1.as_default():\tsession1 = Session(graph=graph1)\twith session1.as_default():\t\tloaded_model = pickle.load(open('Combined_Model.p', 'rb'))" }, { "code": null, "e": 6132, "s": 5841, "text": "The final piece is our camera.py file. In this example, our file will contain a function to join our split model into one pickle file. We will use a class VideoCamera to initiallize the camera when the app loads, and also combine the face detection program with our pre-trained Keras model." }, { "code": null, "e": 8104, "s": 6132, "text": "import cv2import numpy as npimport picklefrom keras import backend as Kfrom tensorflow import Graph, Session# defining face detectorclassifier=cv2.CascadeClassifier('haarcascade_frontalface_default.xml')size = 4labels_dict={0:'shaved',1:'not_shaved'}color_dict={0:(0,255,0),1:(0,0,255)}global loaded_modelgraph1 = Graph()with graph1.as_default():\tsession1 = Session(graph=graph1)\twith session1.as_default():\t\tloaded_model = pickle.load(open('Combined_Model.p', 'rb'))class VideoCamera(object): def __init__(self): # capturing video self.video = cv2.VideoCapture(0) def __del__(self): # releasing camera self.video.release() def get_frame(self): # extracting frames (rval, im) = self.video.read() im = cv2.flip(im, 1, 1) mini = cv2.resize(im, (im.shape[1] // size, im.shape[0] // size)) faces = classifier.detectMultiScale(mini) for f in faces: (x, y, w, h) = [v * size for v in f] #Scale the shapesize backup #Save just the rectangle faces in SubRecFaces face_img = im[y:y+h, x:x+w] resized=cv2.resize(face_img,(300,300)) normalized=resized/255.0 reshaped=np.reshape(normalized,(1,300,300,3)) reshaped = np.vstack([reshaped]) K.set_session(session1) with graph1.as_default(): results=loaded_model.predict(reshaped) if results >.5: result = np.array([[1]]) else: result = np.array([[0]]) label = np.argmax(result) cv2.rectangle(im,(x,y),(x+w,y+h),color_dict[result[label][0]],2) cv2.rectangle(im,(x,y-40),(x+w,y),color_dict[result[label][0]],-1) cv2.putText(im, labels_dict[result[label][0]], (x, y-10),cv2.FONT_HERSHEY_SIMPLEX,0.8,(255,255,255),2) # encode OpenCV raw frame to jpg and displaying it ret, jpeg = cv2.imencode('.jpg', im) return jpeg.tobytes()" }, { "code": null, "e": 8393, "s": 8104, "text": "Please note that this application is limited to your local computer. I hope this article is helpful. I would love to deploy this model publicly using Node.js, Tensorflow.js and OpenCV.js, but this is outside the scope of this article. If I get 100 comments, I will make that my next post!" }, { "code": null, "e": 8449, "s": 8393, "text": "https://github.com/cousinskeeta/shavedVnotShaved_opencv" }, { "code": null, "e": 8525, "s": 8449, "text": "COVID-19: Face Mask Detection using TensorFlow and OpenCV by Gurucharan M K" } ]
C program to sort an array in descending order
Sort the given array in descending or ascending order based on the code that has been written. An array is a group of related data items which share’s a common name. A particular value in an array is identified with the help of its "index number". The syntax for declaring an array is as follows − datatype array_name [size]; For example, float marks [50] It declares ‘marks’ to be an array containing 50 float elements. int number[10] It declares the ‘number’ as an array to contain a maximum of 10 integer constants. Each element is identified by using an "array index". Accessing array elements is easy by using the array index. Following is the C program to sort an array in descending order − Live Demo #include <stdio.h> void main (){ int num[20]; int i, j, a, n; printf("enter number of elements in an array\n"); scanf("%d", &n); printf("Enter the elements\n"); for (i = 0; i < n; ++i) scanf("%d", &num[i]); for (i = 0; i < n; ++i){ for (j = i + 1; j < n; ++j){ if (num[i] < num[j]){ a = num[i]; num[i] = num[j]; num[j] = a; } } } printf("The numbers in descending order is:\n"); for (i = 0; i < n; ++i){ printf("%d\n", num[i]); } } When the above program is executed, it produces the following result − enter number of elements in an array 4 Enter the elements 11 34 67 89 The numbers in descending order is: 89 67 34 11
[ { "code": null, "e": 1157, "s": 1062, "text": "Sort the given array in descending or ascending order based on the code that has been written." }, { "code": null, "e": 1310, "s": 1157, "text": "An array is a group of related data items which share’s a common name. A particular value in an array is identified with the help of its \"index number\"." }, { "code": null, "e": 1360, "s": 1310, "text": "The syntax for declaring an array is as follows −" }, { "code": null, "e": 1388, "s": 1360, "text": "datatype array_name [size];" }, { "code": null, "e": 1401, "s": 1388, "text": "For example," }, { "code": null, "e": 1418, "s": 1401, "text": "float marks [50]" }, { "code": null, "e": 1483, "s": 1418, "text": "It declares ‘marks’ to be an array containing 50 float elements." }, { "code": null, "e": 1498, "s": 1483, "text": "int number[10]" }, { "code": null, "e": 1581, "s": 1498, "text": "It declares the ‘number’ as an array to contain a maximum of 10 integer constants." }, { "code": null, "e": 1635, "s": 1581, "text": "Each element is identified by using an \"array index\"." }, { "code": null, "e": 1694, "s": 1635, "text": "Accessing array elements is easy by using the array index." }, { "code": null, "e": 1760, "s": 1694, "text": "Following is the C program to sort an array in descending order −" }, { "code": null, "e": 1771, "s": 1760, "text": " Live Demo" }, { "code": null, "e": 2314, "s": 1771, "text": "#include <stdio.h>\nvoid main (){\n int num[20];\n int i, j, a, n;\n printf(\"enter number of elements in an array\\n\");\n scanf(\"%d\", &n);\n printf(\"Enter the elements\\n\");\n for (i = 0; i < n; ++i)\n scanf(\"%d\", &num[i]);\n for (i = 0; i < n; ++i){\n for (j = i + 1; j < n; ++j){\n if (num[i] < num[j]){\n a = num[i];\n num[i] = num[j];\n num[j] = a;\n }\n }\n }\n printf(\"The numbers in descending order is:\\n\");\n for (i = 0; i < n; ++i){\n printf(\"%d\\n\", num[i]);\n }\n}" }, { "code": null, "e": 2385, "s": 2314, "text": "When the above program is executed, it produces the following result −" }, { "code": null, "e": 2503, "s": 2385, "text": "enter number of elements in an array\n4\nEnter the elements\n11\n34\n67\n89\nThe numbers in descending order is:\n89\n67\n34\n11" } ]
Bootstrap 5 List group - GeeksforGeeks
11 Sep, 2020 Bootstrap 5 is the latest major release by Bootstrap in which they have revamped the UI and made various changes. List groups are a flexible and powerful component for displaying a series of content. These can be modified and extended to support just about any content within. Use .list-group and .list-group-item classes to create a list of items. The .list-group class is used with <ul> element and .list-group-item is used with <li> element. Syntax: <div class="list-group"> Contents... <div> Example: <!DOCTYPE html><html> <head> <!-- Load Bootstrap --> <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/5.0.0-alpha1/css/bootstrap.min.css" integrity="sha384-r4NyP46KrjDleawBgD5tp8Y7UzmLA05oM1iAEQ17CSuDqnUK2+k9luXQOfXJCJ4I" crossorigin="anonymous" /> <script src="https://cdn.jsdelivr.net/npm/popper.js@1.16.0/dist/umd/popper.min.js" integrity="sha384-Q6E9RHvbIyZFJoft+2mJbHaEWldlvI9IOYy5n3zV9zzTtmI3UksdQRVvoxMfooAo" crossorigin="anonymous"></script> <script src="https://stackpath.bootstrapcdn.com/bootstrap/5.0.0-alpha1/js/bootstrap.min.js" integrity="sha384-oesi62hOLfzrys4LxRF63OJCXdXDipiYWBnvTl9Y9/TRlw5xlKIEHpNyvvDShgf/" crossorigin="anonymous"></script> </head> <body style="text-align: center;"> <div class="container mt-3" style="width: 700px;"> <h1 style="color: green;"> GeeksforGeeks </h1> <ul class="list-group"> <li class="list-group-item"> Data Structure</li> <li class="list-group-item"> Operating System</li> <li class="list-group-item"> Algorithm</li> </ul> </div> </body></html> Output: Active list item: The .active class is used to highlight the current item.Example: <!DOCTYPE html><html> <head> <!-- Load Bootstrap --> <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/5.0.0-alpha1/css/bootstrap.min.css" integrity="sha384-r4NyP46KrjDleawBgD5tp8Y7UzmLA05oM1iAEQ17CSuDqnUK2+k9luXQOfXJCJ4I" crossorigin="anonymous" /> <script src="https://cdn.jsdelivr.net/npm/popper.js@1.16.0/dist/umd/popper.min.js" integrity="sha384-Q6E9RHvbIyZFJoft+2mJbHaEWldlvI9IOYy5n3zV9zzTtmI3UksdQRVvoxMfooAo" crossorigin="anonymous"></script> <script src="https://stackpath.bootstrapcdn.com/bootstrap/5.0.0-alpha1/js/bootstrap.min.js" integrity="sha384-oesi62hOLfzrys4LxRF63OJCXdXDipiYWBnvTl9Y9/TRlw5xlKIEHpNyvvDShgf/" crossorigin="anonymous"></script> </head> <body style="text-align: center;"> <div class="container mt-3" style="width: 700px;"> <h1 style="color: green;"> GeeksforGeeks </h1> <ul class="list-group"> <li class="list-group-item active"> Data Structure</li> <li class="list-group-item"> Operating System</li> <li class="list-group-item"> Algorithm</li> </ul> </div> </body></html> Output: List Group With Linked Items: Use <div> and <a> tag instead of <ul> and <li> to create a list of group with linked items. The .list-group-item-action class is used to set the hover effect to change the background color to gray.Example: <!DOCTYPE html><html> <head> <!-- Load Bootstrap --> <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/5.0.0-alpha1/css/bootstrap.min.css" integrity="sha384-r4NyP46KrjDleawBgD5tp8Y7UzmLA05oM1iAEQ17CSuDqnUK2+k9luXQOfXJCJ4I" crossorigin="anonymous" /> <script src="https://cdn.jsdelivr.net/npm/popper.js@1.16.0/dist/umd/popper.min.js" integrity="sha384-Q6E9RHvbIyZFJoft+2mJbHaEWldlvI9IOYy5n3zV9zzTtmI3UksdQRVvoxMfooAo" crossorigin="anonymous"></script> <script src="https://stackpath.bootstrapcdn.com/bootstrap/5.0.0-alpha1/js/bootstrap.min.js" integrity="sha384-oesi62hOLfzrys4LxRF63OJCXdXDipiYWBnvTl9Y9/TRlw5xlKIEHpNyvvDShgf/" crossorigin="anonymous"></script> </head> <body style="text-align: center;"> <div class="container mt-3" style="width: 700px;"> <h1 style="color: green;"> GeeksforGeeks </h1> <div class="container"> <div class="list-group"> <a href="#" class="list-group-item list-group-item-action"> Data Structure </a> <a href="#" class="list-group-item list-group-item-action"> Operating System </a> <a href="#" class="list-group-item list-group-item-action"> Algorithm </a> </div> </div> </div> </body></html> Output: Disabled Item: The .disabled class is used to disable the text content. This class set the text color to light. When used on links, it will remove the hover effect.Example: <!DOCTYPE html><html> <head> <!-- Load Bootstrap --> <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/5.0.0-alpha1/css/bootstrap.min.css" integrity="sha384-r4NyP46KrjDleawBgD5tp8Y7UzmLA05oM1iAEQ17CSuDqnUK2+k9luXQOfXJCJ4I" crossorigin="anonymous" /> <script src="https://cdn.jsdelivr.net/npm/popper.js@1.16.0/dist/umd/popper.min.js" integrity="sha384-Q6E9RHvbIyZFJoft+2mJbHaEWldlvI9IOYy5n3zV9zzTtmI3UksdQRVvoxMfooAo" crossorigin="anonymous"></script> <script src="https://stackpath.bootstrapcdn.com/bootstrap/5.0.0-alpha1/js/bootstrap.min.js" integrity="sha384-oesi62hOLfzrys4LxRF63OJCXdXDipiYWBnvTl9Y9/TRlw5xlKIEHpNyvvDShgf/" crossorigin="anonymous"></script> </head> <body style="text-align: center;"> <div class="container mt-3" style="width: 700px;"> <h1 style="color: green;"> GeeksforGeeks </h1> <div class="container"> <div class="list-group"> <a href="#" class="list-group-item disabled"> Android </a> <a href="#" class="list-group-item"> Web </a> <a href="#" class="list-group-item disabled"> AI </a> </div> </div> </div> </body></html> Output: Flush/Remove Borders: The .list-group-flush class is used to remove some borders and rounded corners.Example: <!DOCTYPE html><html> <head> <!-- Load Bootstrap --> <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/5.0.0-alpha1/css/bootstrap.min.css" integrity="sha384-r4NyP46KrjDleawBgD5tp8Y7UzmLA05oM1iAEQ17CSuDqnUK2+k9luXQOfXJCJ4I" crossorigin="anonymous"> <script src="https://cdn.jsdelivr.net/npm/popper.js@1.16.0/dist/umd/popper.min.js" integrity="sha384-Q6E9RHvbIyZFJoft+2mJbHaEWldlvI9IOYy5n3zV9zzTtmI3UksdQRVvoxMfooAo" crossorigin="anonymous"></script> <script src="https://stackpath.bootstrapcdn.com/bootstrap/5.0.0-alpha1/js/bootstrap.min.js" integrity="sha384-oesi62hOLfzrys4LxRF63OJCXdXDipiYWBnvTl9Y9/TRlw5xlKIEHpNyvvDShgf/" crossorigin="anonymous"></script></head> <body style="text-align:center;"> <div class="container mt-3" style="width:700px;"> <h1 style="color:green;"> GeeksforGeeks </h1> <div class="container"> <ul class="list-group list-group-flush"> <a href="#" class="list-group-item"> Android </a> <a href="#" class="list-group-item"> Web </a> <a href="#" class="list-group-item"> AI </a> </div> </div> </body> </html> Output: Horizontal List Groups: The .list-group-horizontal class is used to display the list of items horizontally instead of vertically.Example: <!DOCTYPE html><html> <head> <!-- Load Bootstrap --> <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/5.0.0-alpha1/css/bootstrap.min.css" integrity="sha384-r4NyP46KrjDleawBgD5tp8Y7UzmLA05oM1iAEQ17CSuDqnUK2+k9luXQOfXJCJ4I" crossorigin="anonymous"> <script src="https://cdn.jsdelivr.net/npm/popper.js@1.16.0/dist/umd/popper.min.js" integrity="sha384-Q6E9RHvbIyZFJoft+2mJbHaEWldlvI9IOYy5n3zV9zzTtmI3UksdQRVvoxMfooAo" crossorigin="anonymous"></script> <script src="https://stackpath.bootstrapcdn.com/bootstrap/5.0.0-alpha1/js/bootstrap.min.js" integrity="sha384-oesi62hOLfzrys4LxRF63OJCXdXDipiYWBnvTl9Y9/TRlw5xlKIEHpNyvvDShgf/" crossorigin="anonymous"></script></head> <body style="text-align:center;"> <div class="container mt-3" style="width:700px;"> <h1 style="color:green;"> GeeksforGeeks </h1> <div class="container"> <ul class="list-group list-group-horizontal"> <a href="#" class="list-group-item"> Android </a> <a href="#" class="list-group-item"> Web </a> <a href="#" class="list-group-item"> AI </a> </div> </div></body> </html> Output: Contextual Classes: It is used to set the color to the list of items. The classes for coloring the list-items are: .list-group-item-success, .list-group-item-secondary, .list-group-item-info, .list-group-item-warning, .list-group-item-danger, .list-group-item-primary, .list-group-item-dark and .list-group-item-light. Example: <!DOCTYPE html><html> <head> <!-- Load Bootstrap --> <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/5.0.0-alpha1/css/bootstrap.min.css" integrity="sha384-r4NyP46KrjDleawBgD5tp8Y7UzmLA05oM1iAEQ17CSuDqnUK2+k9luXQOfXJCJ4I" crossorigin="anonymous" /> <script src="https://cdn.jsdelivr.net/npm/popper.js@1.16.0/dist/umd/popper.min.js" integrity="sha384-Q6E9RHvbIyZFJoft+2mJbHaEWldlvI9IOYy5n3zV9zzTtmI3UksdQRVvoxMfooAo" crossorigin="anonymous"></script> <script src="https://stackpath.bootstrapcdn.com/bootstrap/5.0.0-alpha1/js/bootstrap.min.js" integrity="sha384-oesi62hOLfzrys4LxRF63OJCXdXDipiYWBnvTl9Y9/TRlw5xlKIEHpNyvvDShgf/" crossorigin="anonymous"></script> </head> <body style="text-align: center;"> <div class="container mt-3" style="width: 700px;"> <h1 style="color: green;"> GeeksforGeeks </h1> <ul class="list-group"> <li class="list-group-item list-group-item-primary"> Web </li> <li class="list-group-item list-group-item-secondary"> Android </li> <li class="list-group-item list-group-item-success"> AI </li> <li class="list-group-item list-group-item-warning"> Data Science </li> <li class="list-group-item list-group-item-danger"> UI/UX </li> </ul> </div> </body></html> Output: Link items with Contextual Classes: The contextual classes can be used with list of items.Example: <!DOCTYPE html><html> <head> <!-- Load Bootstrap --> <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/5.0.0-alpha1/css/bootstrap.min.css" integrity="sha384-r4NyP46KrjDleawBgD5tp8Y7UzmLA05oM1iAEQ17CSuDqnUK2+k9luXQOfXJCJ4I" crossorigin="anonymous" /> <script src="https://cdn.jsdelivr.net/npm/popper.js@1.16.0/dist/umd/popper.min.js" integrity="sha384-Q6E9RHvbIyZFJoft+2mJbHaEWldlvI9IOYy5n3zV9zzTtmI3UksdQRVvoxMfooAo" crossorigin="anonymous"></script> <script src="https://stackpath.bootstrapcdn.com/bootstrap/5.0.0-alpha1/js/bootstrap.min.js" integrity="sha384-oesi62hOLfzrys4LxRF63OJCXdXDipiYWBnvTl9Y9/TRlw5xlKIEHpNyvvDShgf/" crossorigin="anonymous"></script> </head> <body style="text-align: center;"> <div class="container mt-3" style="width: 700px;"> <h1 style="color: green;"> GeeksforGeeks </h1> <ul class="list-group"> <a class="list-group-item list-group-item-primary"> Web </a> <a class="list-group-item list-group-item-secondary"> Android </a> <a class="list-group-item list-group-item-success"> AI </a> <a class="list-group-item list-group-item-warning"> Data Science </a> <a class="list-group-item list-group-item-danger"> UI/UX </a> </ul> </div> </body></html> Output: List Group with Badges: The .badge class can be combined with utility class to add badges inside the list of group. Example: <!DOCTYPE html><html> <head> <!-- Load Bootstrap --> <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/5.0.0-alpha1/css/bootstrap.min.css" integrity="sha384-r4NyP46KrjDleawBgD5tp8Y7UzmLA05oM1iAEQ17CSuDqnUK2+k9luXQOfXJCJ4I" crossorigin="anonymous" /> <script src="https://cdn.jsdelivr.net/npm/popper.js@1.16.0/dist/umd/popper.min.js" integrity="sha384-Q6E9RHvbIyZFJoft+2mJbHaEWldlvI9IOYy5n3zV9zzTtmI3UksdQRVvoxMfooAo" crossorigin="anonymous"></script> <script src="https://stackpath.bootstrapcdn.com/bootstrap/5.0.0-alpha1/js/bootstrap.min.js" integrity="sha384-oesi62hOLfzrys4LxRF63OJCXdXDipiYWBnvTl9Y9/TRlw5xlKIEHpNyvvDShgf/" crossorigin="anonymous"></script> </head> <body style="text-align: center;"> <div class="container mt-3" style="width: 700px;"> <h1 style="color: green;"> GeeksforGeeks </h1> <ul class="list-group"> <li class="list-group-item d-flex justify-content-between align-items-center"> CPP <span class="badge bg-success"> X</span> </li> <li class="list-group-item d-flex justify-content-between align-items-center"> Python <span class="badge bg-success"> Y</span> </li> <li class="list-group-item d-flex justify-content-between align-items-center"> JavaScript <span class="badge bg-success"> Z</span> </li> </ul> </div> </body></html> Output: Bootstrap-Misc Bootstrap Web Technologies Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments How to change navigation bar color in Bootstrap ? Form validation using jQuery How to align navbar items to the right in Bootstrap 4 ? How to pass data into a bootstrap modal? How to Show Images on Click using HTML ? Top 10 Front End Developer Skills That You Need in 2022 Installation of Node.js on Linux Top 10 Projects For Beginners To Practice HTML and CSS Skills How to fetch data from an API in ReactJS ? How to insert spaces/tabs in text using HTML/CSS?
[ { "code": null, "e": 28049, "s": 28021, "text": "\n11 Sep, 2020" }, { "code": null, "e": 28494, "s": 28049, "text": "Bootstrap 5 is the latest major release by Bootstrap in which they have revamped the UI and made various changes. List groups are a flexible and powerful component for displaying a series of content. These can be modified and extended to support just about any content within. Use .list-group and .list-group-item classes to create a list of items. The .list-group class is used with <ul> element and .list-group-item is used with <li> element." }, { "code": null, "e": 28502, "s": 28494, "text": "Syntax:" }, { "code": null, "e": 28545, "s": 28502, "text": "<div class=\"list-group\"> Contents... <div>" }, { "code": null, "e": 28554, "s": 28545, "text": "Example:" }, { "code": "<!DOCTYPE html><html> <head> <!-- Load Bootstrap --> <link rel=\"stylesheet\" href=\"https://stackpath.bootstrapcdn.com/bootstrap/5.0.0-alpha1/css/bootstrap.min.css\" integrity=\"sha384-r4NyP46KrjDleawBgD5tp8Y7UzmLA05oM1iAEQ17CSuDqnUK2+k9luXQOfXJCJ4I\" crossorigin=\"anonymous\" /> <script src=\"https://cdn.jsdelivr.net/npm/popper.js@1.16.0/dist/umd/popper.min.js\" integrity=\"sha384-Q6E9RHvbIyZFJoft+2mJbHaEWldlvI9IOYy5n3zV9zzTtmI3UksdQRVvoxMfooAo\" crossorigin=\"anonymous\"></script> <script src=\"https://stackpath.bootstrapcdn.com/bootstrap/5.0.0-alpha1/js/bootstrap.min.js\" integrity=\"sha384-oesi62hOLfzrys4LxRF63OJCXdXDipiYWBnvTl9Y9/TRlw5xlKIEHpNyvvDShgf/\" crossorigin=\"anonymous\"></script> </head> <body style=\"text-align: center;\"> <div class=\"container mt-3\" style=\"width: 700px;\"> <h1 style=\"color: green;\"> GeeksforGeeks </h1> <ul class=\"list-group\"> <li class=\"list-group-item\"> Data Structure</li> <li class=\"list-group-item\"> Operating System</li> <li class=\"list-group-item\"> Algorithm</li> </ul> </div> </body></html>", "e": 29901, "s": 28554, "text": null }, { "code": null, "e": 29909, "s": 29901, "text": "Output:" }, { "code": null, "e": 29992, "s": 29909, "text": "Active list item: The .active class is used to highlight the current item.Example:" }, { "code": "<!DOCTYPE html><html> <head> <!-- Load Bootstrap --> <link rel=\"stylesheet\" href=\"https://stackpath.bootstrapcdn.com/bootstrap/5.0.0-alpha1/css/bootstrap.min.css\" integrity=\"sha384-r4NyP46KrjDleawBgD5tp8Y7UzmLA05oM1iAEQ17CSuDqnUK2+k9luXQOfXJCJ4I\" crossorigin=\"anonymous\" /> <script src=\"https://cdn.jsdelivr.net/npm/popper.js@1.16.0/dist/umd/popper.min.js\" integrity=\"sha384-Q6E9RHvbIyZFJoft+2mJbHaEWldlvI9IOYy5n3zV9zzTtmI3UksdQRVvoxMfooAo\" crossorigin=\"anonymous\"></script> <script src=\"https://stackpath.bootstrapcdn.com/bootstrap/5.0.0-alpha1/js/bootstrap.min.js\" integrity=\"sha384-oesi62hOLfzrys4LxRF63OJCXdXDipiYWBnvTl9Y9/TRlw5xlKIEHpNyvvDShgf/\" crossorigin=\"anonymous\"></script> </head> <body style=\"text-align: center;\"> <div class=\"container mt-3\" style=\"width: 700px;\"> <h1 style=\"color: green;\"> GeeksforGeeks </h1> <ul class=\"list-group\"> <li class=\"list-group-item active\"> Data Structure</li> <li class=\"list-group-item\"> Operating System</li> <li class=\"list-group-item\"> Algorithm</li> </ul> </div> </body></html>", "e": 31351, "s": 29992, "text": null }, { "code": null, "e": 31359, "s": 31351, "text": "Output:" }, { "code": null, "e": 31595, "s": 31359, "text": "List Group With Linked Items: Use <div> and <a> tag instead of <ul> and <li> to create a list of group with linked items. The .list-group-item-action class is used to set the hover effect to change the background color to gray.Example:" }, { "code": "<!DOCTYPE html><html> <head> <!-- Load Bootstrap --> <link rel=\"stylesheet\" href=\"https://stackpath.bootstrapcdn.com/bootstrap/5.0.0-alpha1/css/bootstrap.min.css\" integrity=\"sha384-r4NyP46KrjDleawBgD5tp8Y7UzmLA05oM1iAEQ17CSuDqnUK2+k9luXQOfXJCJ4I\" crossorigin=\"anonymous\" /> <script src=\"https://cdn.jsdelivr.net/npm/popper.js@1.16.0/dist/umd/popper.min.js\" integrity=\"sha384-Q6E9RHvbIyZFJoft+2mJbHaEWldlvI9IOYy5n3zV9zzTtmI3UksdQRVvoxMfooAo\" crossorigin=\"anonymous\"></script> <script src=\"https://stackpath.bootstrapcdn.com/bootstrap/5.0.0-alpha1/js/bootstrap.min.js\" integrity=\"sha384-oesi62hOLfzrys4LxRF63OJCXdXDipiYWBnvTl9Y9/TRlw5xlKIEHpNyvvDShgf/\" crossorigin=\"anonymous\"></script> </head> <body style=\"text-align: center;\"> <div class=\"container mt-3\" style=\"width: 700px;\"> <h1 style=\"color: green;\"> GeeksforGeeks </h1> <div class=\"container\"> <div class=\"list-group\"> <a href=\"#\" class=\"list-group-item list-group-item-action\"> Data Structure </a> <a href=\"#\" class=\"list-group-item list-group-item-action\"> Operating System </a> <a href=\"#\" class=\"list-group-item list-group-item-action\"> Algorithm </a> </div> </div> </div> </body></html>", "e": 33349, "s": 31595, "text": null }, { "code": null, "e": 33357, "s": 33349, "text": "Output:" }, { "code": null, "e": 33530, "s": 33357, "text": "Disabled Item: The .disabled class is used to disable the text content. This class set the text color to light. When used on links, it will remove the hover effect.Example:" }, { "code": "<!DOCTYPE html><html> <head> <!-- Load Bootstrap --> <link rel=\"stylesheet\" href=\"https://stackpath.bootstrapcdn.com/bootstrap/5.0.0-alpha1/css/bootstrap.min.css\" integrity=\"sha384-r4NyP46KrjDleawBgD5tp8Y7UzmLA05oM1iAEQ17CSuDqnUK2+k9luXQOfXJCJ4I\" crossorigin=\"anonymous\" /> <script src=\"https://cdn.jsdelivr.net/npm/popper.js@1.16.0/dist/umd/popper.min.js\" integrity=\"sha384-Q6E9RHvbIyZFJoft+2mJbHaEWldlvI9IOYy5n3zV9zzTtmI3UksdQRVvoxMfooAo\" crossorigin=\"anonymous\"></script> <script src=\"https://stackpath.bootstrapcdn.com/bootstrap/5.0.0-alpha1/js/bootstrap.min.js\" integrity=\"sha384-oesi62hOLfzrys4LxRF63OJCXdXDipiYWBnvTl9Y9/TRlw5xlKIEHpNyvvDShgf/\" crossorigin=\"anonymous\"></script> </head> <body style=\"text-align: center;\"> <div class=\"container mt-3\" style=\"width: 700px;\"> <h1 style=\"color: green;\"> GeeksforGeeks </h1> <div class=\"container\"> <div class=\"list-group\"> <a href=\"#\" class=\"list-group-item disabled\"> Android </a> <a href=\"#\" class=\"list-group-item\"> Web </a> <a href=\"#\" class=\"list-group-item disabled\"> AI </a> </div> </div> </div> </body></html>", "e": 35117, "s": 33530, "text": null }, { "code": null, "e": 35125, "s": 35117, "text": "Output:" }, { "code": null, "e": 35235, "s": 35125, "text": "Flush/Remove Borders: The .list-group-flush class is used to remove some borders and rounded corners.Example:" }, { "code": "<!DOCTYPE html><html> <head> <!-- Load Bootstrap --> <link rel=\"stylesheet\" href=\"https://stackpath.bootstrapcdn.com/bootstrap/5.0.0-alpha1/css/bootstrap.min.css\" integrity=\"sha384-r4NyP46KrjDleawBgD5tp8Y7UzmLA05oM1iAEQ17CSuDqnUK2+k9luXQOfXJCJ4I\" crossorigin=\"anonymous\"> <script src=\"https://cdn.jsdelivr.net/npm/popper.js@1.16.0/dist/umd/popper.min.js\" integrity=\"sha384-Q6E9RHvbIyZFJoft+2mJbHaEWldlvI9IOYy5n3zV9zzTtmI3UksdQRVvoxMfooAo\" crossorigin=\"anonymous\"></script> <script src=\"https://stackpath.bootstrapcdn.com/bootstrap/5.0.0-alpha1/js/bootstrap.min.js\" integrity=\"sha384-oesi62hOLfzrys4LxRF63OJCXdXDipiYWBnvTl9Y9/TRlw5xlKIEHpNyvvDShgf/\" crossorigin=\"anonymous\"></script></head> <body style=\"text-align:center;\"> <div class=\"container mt-3\" style=\"width:700px;\"> <h1 style=\"color:green;\"> GeeksforGeeks </h1> <div class=\"container\"> <ul class=\"list-group list-group-flush\"> <a href=\"#\" class=\"list-group-item\"> Android </a> <a href=\"#\" class=\"list-group-item\"> Web </a> <a href=\"#\" class=\"list-group-item\"> AI </a> </div> </div> </body> </html>", "e": 36665, "s": 35235, "text": null }, { "code": null, "e": 36673, "s": 36665, "text": "Output:" }, { "code": null, "e": 36811, "s": 36673, "text": "Horizontal List Groups: The .list-group-horizontal class is used to display the list of items horizontally instead of vertically.Example:" }, { "code": "<!DOCTYPE html><html> <head> <!-- Load Bootstrap --> <link rel=\"stylesheet\" href=\"https://stackpath.bootstrapcdn.com/bootstrap/5.0.0-alpha1/css/bootstrap.min.css\" integrity=\"sha384-r4NyP46KrjDleawBgD5tp8Y7UzmLA05oM1iAEQ17CSuDqnUK2+k9luXQOfXJCJ4I\" crossorigin=\"anonymous\"> <script src=\"https://cdn.jsdelivr.net/npm/popper.js@1.16.0/dist/umd/popper.min.js\" integrity=\"sha384-Q6E9RHvbIyZFJoft+2mJbHaEWldlvI9IOYy5n3zV9zzTtmI3UksdQRVvoxMfooAo\" crossorigin=\"anonymous\"></script> <script src=\"https://stackpath.bootstrapcdn.com/bootstrap/5.0.0-alpha1/js/bootstrap.min.js\" integrity=\"sha384-oesi62hOLfzrys4LxRF63OJCXdXDipiYWBnvTl9Y9/TRlw5xlKIEHpNyvvDShgf/\" crossorigin=\"anonymous\"></script></head> <body style=\"text-align:center;\"> <div class=\"container mt-3\" style=\"width:700px;\"> <h1 style=\"color:green;\"> GeeksforGeeks </h1> <div class=\"container\"> <ul class=\"list-group list-group-horizontal\"> <a href=\"#\" class=\"list-group-item\"> Android </a> <a href=\"#\" class=\"list-group-item\"> Web </a> <a href=\"#\" class=\"list-group-item\"> AI </a> </div> </div></body> </html>", "e": 38241, "s": 36811, "text": null }, { "code": null, "e": 38249, "s": 38241, "text": "Output:" }, { "code": null, "e": 38568, "s": 38249, "text": "Contextual Classes: It is used to set the color to the list of items. The classes for coloring the list-items are: .list-group-item-success, .list-group-item-secondary, .list-group-item-info, .list-group-item-warning, .list-group-item-danger, .list-group-item-primary, .list-group-item-dark and .list-group-item-light." }, { "code": null, "e": 38577, "s": 38568, "text": "Example:" }, { "code": "<!DOCTYPE html><html> <head> <!-- Load Bootstrap --> <link rel=\"stylesheet\" href=\"https://stackpath.bootstrapcdn.com/bootstrap/5.0.0-alpha1/css/bootstrap.min.css\" integrity=\"sha384-r4NyP46KrjDleawBgD5tp8Y7UzmLA05oM1iAEQ17CSuDqnUK2+k9luXQOfXJCJ4I\" crossorigin=\"anonymous\" /> <script src=\"https://cdn.jsdelivr.net/npm/popper.js@1.16.0/dist/umd/popper.min.js\" integrity=\"sha384-Q6E9RHvbIyZFJoft+2mJbHaEWldlvI9IOYy5n3zV9zzTtmI3UksdQRVvoxMfooAo\" crossorigin=\"anonymous\"></script> <script src=\"https://stackpath.bootstrapcdn.com/bootstrap/5.0.0-alpha1/js/bootstrap.min.js\" integrity=\"sha384-oesi62hOLfzrys4LxRF63OJCXdXDipiYWBnvTl9Y9/TRlw5xlKIEHpNyvvDShgf/\" crossorigin=\"anonymous\"></script> </head> <body style=\"text-align: center;\"> <div class=\"container mt-3\" style=\"width: 700px;\"> <h1 style=\"color: green;\"> GeeksforGeeks </h1> <ul class=\"list-group\"> <li class=\"list-group-item list-group-item-primary\"> Web </li> <li class=\"list-group-item list-group-item-secondary\"> Android </li> <li class=\"list-group-item list-group-item-success\"> AI </li> <li class=\"list-group-item list-group-item-warning\"> Data Science </li> <li class=\"list-group-item list-group-item-danger\"> UI/UX </li> </ul> </div> </body></html>", "e": 40402, "s": 38577, "text": null }, { "code": null, "e": 40410, "s": 40402, "text": "Output:" }, { "code": null, "e": 40509, "s": 40410, "text": "Link items with Contextual Classes: The contextual classes can be used with list of items.Example:" }, { "code": "<!DOCTYPE html><html> <head> <!-- Load Bootstrap --> <link rel=\"stylesheet\" href=\"https://stackpath.bootstrapcdn.com/bootstrap/5.0.0-alpha1/css/bootstrap.min.css\" integrity=\"sha384-r4NyP46KrjDleawBgD5tp8Y7UzmLA05oM1iAEQ17CSuDqnUK2+k9luXQOfXJCJ4I\" crossorigin=\"anonymous\" /> <script src=\"https://cdn.jsdelivr.net/npm/popper.js@1.16.0/dist/umd/popper.min.js\" integrity=\"sha384-Q6E9RHvbIyZFJoft+2mJbHaEWldlvI9IOYy5n3zV9zzTtmI3UksdQRVvoxMfooAo\" crossorigin=\"anonymous\"></script> <script src=\"https://stackpath.bootstrapcdn.com/bootstrap/5.0.0-alpha1/js/bootstrap.min.js\" integrity=\"sha384-oesi62hOLfzrys4LxRF63OJCXdXDipiYWBnvTl9Y9/TRlw5xlKIEHpNyvvDShgf/\" crossorigin=\"anonymous\"></script> </head> <body style=\"text-align: center;\"> <div class=\"container mt-3\" style=\"width: 700px;\"> <h1 style=\"color: green;\"> GeeksforGeeks </h1> <ul class=\"list-group\"> <a class=\"list-group-item list-group-item-primary\"> Web </a> <a class=\"list-group-item list-group-item-secondary\"> Android </a> <a class=\"list-group-item list-group-item-success\"> AI </a> <a class=\"list-group-item list-group-item-warning\"> Data Science </a> <a class=\"list-group-item list-group-item-danger\"> UI/UX </a> </ul> </div> </body></html>", "e": 42311, "s": 40509, "text": null }, { "code": null, "e": 42319, "s": 42311, "text": "Output:" }, { "code": null, "e": 42435, "s": 42319, "text": "List Group with Badges: The .badge class can be combined with utility class to add badges inside the list of group." }, { "code": null, "e": 42444, "s": 42435, "text": "Example:" }, { "code": "<!DOCTYPE html><html> <head> <!-- Load Bootstrap --> <link rel=\"stylesheet\" href=\"https://stackpath.bootstrapcdn.com/bootstrap/5.0.0-alpha1/css/bootstrap.min.css\" integrity=\"sha384-r4NyP46KrjDleawBgD5tp8Y7UzmLA05oM1iAEQ17CSuDqnUK2+k9luXQOfXJCJ4I\" crossorigin=\"anonymous\" /> <script src=\"https://cdn.jsdelivr.net/npm/popper.js@1.16.0/dist/umd/popper.min.js\" integrity=\"sha384-Q6E9RHvbIyZFJoft+2mJbHaEWldlvI9IOYy5n3zV9zzTtmI3UksdQRVvoxMfooAo\" crossorigin=\"anonymous\"></script> <script src=\"https://stackpath.bootstrapcdn.com/bootstrap/5.0.0-alpha1/js/bootstrap.min.js\" integrity=\"sha384-oesi62hOLfzrys4LxRF63OJCXdXDipiYWBnvTl9Y9/TRlw5xlKIEHpNyvvDShgf/\" crossorigin=\"anonymous\"></script> </head> <body style=\"text-align: center;\"> <div class=\"container mt-3\" style=\"width: 700px;\"> <h1 style=\"color: green;\"> GeeksforGeeks </h1> <ul class=\"list-group\"> <li class=\"list-group-item d-flex justify-content-between align-items-center\"> CPP <span class=\"badge bg-success\"> X</span> </li> <li class=\"list-group-item d-flex justify-content-between align-items-center\"> Python <span class=\"badge bg-success\"> Y</span> </li> <li class=\"list-group-item d-flex justify-content-between align-items-center\"> JavaScript <span class=\"badge bg-success\"> Z</span> </li> </ul> </div> </body></html>", "e": 44441, "s": 42444, "text": null }, { "code": null, "e": 44449, "s": 44441, "text": "Output:" }, { "code": null, "e": 44464, "s": 44449, "text": "Bootstrap-Misc" }, { "code": null, "e": 44474, "s": 44464, "text": "Bootstrap" }, { "code": null, "e": 44491, "s": 44474, "text": "Web Technologies" }, { "code": null, "e": 44589, "s": 44491, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 44598, "s": 44589, "text": "Comments" }, { "code": null, "e": 44611, "s": 44598, "text": "Old Comments" }, { "code": null, "e": 44661, "s": 44611, "text": "How to change navigation bar color in Bootstrap ?" }, { "code": null, "e": 44690, "s": 44661, "text": "Form validation using jQuery" }, { "code": null, "e": 44746, "s": 44690, "text": "How to align navbar items to the right in Bootstrap 4 ?" }, { "code": null, "e": 44787, "s": 44746, "text": "How to pass data into a bootstrap modal?" }, { "code": null, "e": 44828, "s": 44787, "text": "How to Show Images on Click using HTML ?" }, { "code": null, "e": 44884, "s": 44828, "text": "Top 10 Front End Developer Skills That You Need in 2022" }, { "code": null, "e": 44917, "s": 44884, "text": "Installation of Node.js on Linux" }, { "code": null, "e": 44979, "s": 44917, "text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills" }, { "code": null, "e": 45022, "s": 44979, "text": "How to fetch data from an API in ReactJS ?" } ]
How to place text over an image with HTML and CSS?
Following is the code to place text over an image using HTML and CSS − Live Demo <!DOCTYPE html> <html> <head> <meta name="viewport" content="width=device-width, initial-scale=1"> <style> h1{ text-align: center; } .imageContainer { margin-left:36%; display: inline-block; position: relative; text-align: center; color: rgb(64, 11, 124); } .caption{ font-size: 25px; font-weight: bolder; font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif; } .BL { position: absolute; bottom: 8px; left: 16px; } .TL{ position: absolute; top: 8px; left: 16px; } .TR { position: absolute; top: 8px; right: 16px; } .BR { position: absolute; bottom: 8px; right: 16px; } .center { position: absolute; top: 50%; left: 50%; transform: translate(-50%, -50%); } </style> </head> <body> <h1>Place text on image example</h1> <div class="imageContainer"> <img src="https://i.picsum.photos/id/59/500/500.jpg"> <div class="caption BL">Bottom Left Text</div> <div class="caption TL" >Top Left Text</div> <div class="caption TR">Top Right Text</div> <div class="caption BR">Bottom Right Text</div> <div class="caption center">Centered Text</div> </div> </body> </html> The above code will produce the following output −
[ { "code": null, "e": 1133, "s": 1062, "text": "Following is the code to place text over an image using HTML and CSS −" }, { "code": null, "e": 1144, "s": 1133, "text": " Live Demo" }, { "code": null, "e": 2283, "s": 1144, "text": "<!DOCTYPE html>\n<html>\n<head>\n<meta name=\"viewport\" content=\"width=device-width, initial-scale=1\">\n<style>\nh1{\n text-align: center;\n}\n.imageContainer {\n margin-left:36%;\n display: inline-block;\n position: relative;\n text-align: center;\n color: rgb(64, 11, 124);\n}\n.caption{\n font-size: 25px;\n font-weight: bolder;\n font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;\n}\n.BL {\n position: absolute;\n bottom: 8px;\n left: 16px;\n}\n.TL{\n position: absolute;\n top: 8px;\n left: 16px;\n}\n.TR {\n position: absolute;\n top: 8px;\n right: 16px;\n}\n.BR {\n position: absolute;\n bottom: 8px;\n right: 16px;\n}\n.center {\n position: absolute;\n top: 50%;\n left: 50%;\n transform: translate(-50%, -50%);\n}\n</style>\n</head>\n<body>\n<h1>Place text on image example</h1>\n<div class=\"imageContainer\">\n<img src=\"https://i.picsum.photos/id/59/500/500.jpg\">\n<div class=\"caption BL\">Bottom Left Text</div>\n<div class=\"caption TL\" >Top Left Text</div>\n<div class=\"caption TR\">Top Right Text</div>\n<div class=\"caption BR\">Bottom Right Text</div>\n<div class=\"caption center\">Centered Text</div>\n</div>\n</body>\n</html>" }, { "code": null, "e": 2334, "s": 2283, "text": "The above code will produce the following output −" } ]
math.max() function in Lua programming
There are several occurrences when we want to get the max value from a given series of numbers and then use that value later on. The Maximum value from the series of different numbers is the value that is the maximum of all the numbers that are present in that series. Lua provides us with a math.max() function that we can use to find the max value out of different numbers that we pass to it as arguments. Let’s consider a simple example where we will make use of the math.max() function in Lua − Live Demo a = 10 b = 11 c = 12 print(math.max(a,b,c)) 12 It should be noted that if we try to pass the same numbers to the math.max() function then the output will be the same number itself. Consider the example shown below − Live Demo d = 11 e = 11 print(math.max(d,e)) 11 We can also pass negative numbers in the math.max() function as an argument. Consider the example shown below − Live Demo f = -10 g = -5 print(math.max(f,g)) -5
[ { "code": null, "e": 1316, "s": 1187, "text": "There are several occurrences when we want to get the max value from a given series of numbers and then use that value later on." }, { "code": null, "e": 1456, "s": 1316, "text": "The Maximum value from the series of different numbers is the value that is the maximum of all the numbers that are present in that series." }, { "code": null, "e": 1595, "s": 1456, "text": "Lua provides us with a math.max() function that we can use to find the max value out of different numbers that we pass to it as arguments." }, { "code": null, "e": 1686, "s": 1595, "text": "Let’s consider a simple example where we will make use of the math.max() function in Lua −" }, { "code": null, "e": 1697, "s": 1686, "text": " Live Demo" }, { "code": null, "e": 1741, "s": 1697, "text": "a = 10\nb = 11\nc = 12\nprint(math.max(a,b,c))" }, { "code": null, "e": 1744, "s": 1741, "text": "12" }, { "code": null, "e": 1878, "s": 1744, "text": "It should be noted that if we try to pass the same numbers to the math.max() function then the output will be the same number itself." }, { "code": null, "e": 1913, "s": 1878, "text": "Consider the example shown below −" }, { "code": null, "e": 1924, "s": 1913, "text": " Live Demo" }, { "code": null, "e": 1959, "s": 1924, "text": "d = 11\ne = 11\nprint(math.max(d,e))" }, { "code": null, "e": 1962, "s": 1959, "text": "11" }, { "code": null, "e": 2039, "s": 1962, "text": "We can also pass negative numbers in the math.max() function as an argument." }, { "code": null, "e": 2074, "s": 2039, "text": "Consider the example shown below −" }, { "code": null, "e": 2085, "s": 2074, "text": " Live Demo" }, { "code": null, "e": 2121, "s": 2085, "text": "f = -10\ng = -5\nprint(math.max(f,g))" }, { "code": null, "e": 2124, "s": 2121, "text": "-5" } ]
Print consecutive characters together in a line
07 Jul, 2022 Given a sequence of characters, print consecutive sequence of characters in a line, otherwise print it in a new line. Examples: Input : ABCXYZACCD Output : ABC XYZ A C CD Input : ABCZYXACCD Output: ABC ZYX A C CD The idea is to traverse string from left to right. For every traversed character, print it in a line if it is consecutive to previous one, else print a new line character. Implementation: C++ Java Python3 C# Javascript // C++ program to print consecutive characters// together in a line.#include <iostream>using namespace std; void print(string str){ cout << str[0]; for (int i=1; str[i]!='\0'; i++) { if ((str[i] == str[i-1]+1) || (str[i] == str[i-1]-1)) cout << str[i]; else cout << "\n" << str[i];; }} // Driver codeint main(){ string str = "ABCXYZACCD"; print(str); return 0;} // Java program to print consecutive characters// together in a line.class GFG { static void print(String str1) { char str[] = str1.toCharArray(); System.out.print(str[0]); for (int i = 1; i < str.length; i++) { if ((str[i] == str[i - 1] + 1) || (str[i] == str[i - 1] - 1)) { System.out.print(str[i]); } else { System.out.print("\n" + str[i]); } } } // Driver code public static void main(String[] args) { String str = "ABCXYZACCD"; print(str); }} // This code is contributed by 29AjayKumar # Python3 program to print consecutive characters# together in a line.def _print(string): print(string[0], end = "") for i in range(1, len(string)): if (ord(string[i]) == ord(string[i - 1]) + 1 or ord(string[i]) == ord(string[i - 1]) - 1): print(string[i], end = "") else: print() print(string[i], end = "") # Driver Codeif __name__ == "__main__": string = "ABCXYZACCD" _print(string) # This code is contributed by# sanjeev2552 // C# program to print consecutive characters// together in a line.using System; class GFG{ static void print(String str1) { char []str = str1.ToCharArray(); Console.Write(str[0]); for (int i = 1; i < str.Length; i++) { if ((str[i] == str[i - 1] + 1) || (str[i] == str[i - 1] - 1)) { Console.Write(str[i]); } else { Console.Write("\n" + str[i]); } } } // Driver code public static void Main() { String str = "ABCXYZACCD"; print(str); }} // This code is contributed by PrinciRaj1992 <script> // Javascript program to print consecutive// characters together in a line.function print(str1){ let str = str1.split(""); document.write(str[0]); for(let i = 1; i < str.length; i++) { if ((str[i].charCodeAt(0) == str[i - 1].charCodeAt(0) + 1) || (str[i].charCodeAt(0) == str[i - 1].charCodeAt(0) - 1)) { document.write(str[i]); } else { document.write("<br>" + str[i]); } }} // Driver codelet str = "ABCXYZACCD";print(str); // This code is contributed by rag2127 </script> ABC XYZ A C CD Time Complexity : O(n) This article is contributed by Rakesh Kumar. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to review-team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks. 29AjayKumar princiraj1992 VishalBachchas sanjeev2552 rag2127 hardikkoriintern Strings Strings Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 52, "s": 24, "text": "\n07 Jul, 2022" }, { "code": null, "e": 170, "s": 52, "text": "Given a sequence of characters, print consecutive sequence of characters in a line, otherwise print it in a new line." }, { "code": null, "e": 181, "s": 170, "text": "Examples: " }, { "code": null, "e": 336, "s": 181, "text": "Input : ABCXYZACCD\nOutput : ABC\n XYZ\n A\n C\n CD\n\nInput : ABCZYXACCD\nOutput: ABC\n ZYX\n A\n C\n CD" }, { "code": null, "e": 509, "s": 336, "text": "The idea is to traverse string from left to right. For every traversed character, print it in a line if it is consecutive to previous one, else print a new line character. " }, { "code": null, "e": 525, "s": 509, "text": "Implementation:" }, { "code": null, "e": 529, "s": 525, "text": "C++" }, { "code": null, "e": 534, "s": 529, "text": "Java" }, { "code": null, "e": 542, "s": 534, "text": "Python3" }, { "code": null, "e": 545, "s": 542, "text": "C#" }, { "code": null, "e": 556, "s": 545, "text": "Javascript" }, { "code": "// C++ program to print consecutive characters// together in a line.#include <iostream>using namespace std; void print(string str){ cout << str[0]; for (int i=1; str[i]!='\\0'; i++) { if ((str[i] == str[i-1]+1) || (str[i] == str[i-1]-1)) cout << str[i]; else cout << \"\\n\" << str[i];; }} // Driver codeint main(){ string str = \"ABCXYZACCD\"; print(str); return 0;}", "e": 986, "s": 556, "text": null }, { "code": "// Java program to print consecutive characters// together in a line.class GFG { static void print(String str1) { char str[] = str1.toCharArray(); System.out.print(str[0]); for (int i = 1; i < str.length; i++) { if ((str[i] == str[i - 1] + 1) || (str[i] == str[i - 1] - 1)) { System.out.print(str[i]); } else { System.out.print(\"\\n\" + str[i]); } } } // Driver code public static void main(String[] args) { String str = \"ABCXYZACCD\"; print(str); }} // This code is contributed by 29AjayKumar", "e": 1614, "s": 986, "text": null }, { "code": "# Python3 program to print consecutive characters# together in a line.def _print(string): print(string[0], end = \"\") for i in range(1, len(string)): if (ord(string[i]) == ord(string[i - 1]) + 1 or ord(string[i]) == ord(string[i - 1]) - 1): print(string[i], end = \"\") else: print() print(string[i], end = \"\") # Driver Codeif __name__ == \"__main__\": string = \"ABCXYZACCD\" _print(string) # This code is contributed by# sanjeev2552", "e": 2114, "s": 1614, "text": null }, { "code": "// C# program to print consecutive characters// together in a line.using System; class GFG{ static void print(String str1) { char []str = str1.ToCharArray(); Console.Write(str[0]); for (int i = 1; i < str.Length; i++) { if ((str[i] == str[i - 1] + 1) || (str[i] == str[i - 1] - 1)) { Console.Write(str[i]); } else { Console.Write(\"\\n\" + str[i]); } } } // Driver code public static void Main() { String str = \"ABCXYZACCD\"; print(str); }} // This code is contributed by PrinciRaj1992", "e": 2783, "s": 2114, "text": null }, { "code": "<script> // Javascript program to print consecutive// characters together in a line.function print(str1){ let str = str1.split(\"\"); document.write(str[0]); for(let i = 1; i < str.length; i++) { if ((str[i].charCodeAt(0) == str[i - 1].charCodeAt(0) + 1) || (str[i].charCodeAt(0) == str[i - 1].charCodeAt(0) - 1)) { document.write(str[i]); } else { document.write(\"<br>\" + str[i]); } }} // Driver codelet str = \"ABCXYZACCD\";print(str); // This code is contributed by rag2127 </script>", "e": 3377, "s": 2783, "text": null }, { "code": null, "e": 3392, "s": 3377, "text": "ABC\nXYZ\nA\nC\nCD" }, { "code": null, "e": 3416, "s": 3392, "text": "Time Complexity : O(n) " }, { "code": null, "e": 3713, "s": 3416, "text": "This article is contributed by Rakesh Kumar. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to review-team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks. " }, { "code": null, "e": 3725, "s": 3713, "text": "29AjayKumar" }, { "code": null, "e": 3739, "s": 3725, "text": "princiraj1992" }, { "code": null, "e": 3754, "s": 3739, "text": "VishalBachchas" }, { "code": null, "e": 3766, "s": 3754, "text": "sanjeev2552" }, { "code": null, "e": 3774, "s": 3766, "text": "rag2127" }, { "code": null, "e": 3791, "s": 3774, "text": "hardikkoriintern" }, { "code": null, "e": 3799, "s": 3791, "text": "Strings" }, { "code": null, "e": 3807, "s": 3799, "text": "Strings" } ]
Traveling Salesman Problem using Branch And Bound
25 Mar, 2022 Given a set of cities and distance between every pair of cities, the problem is to find the shortest possible tour that visits every city exactly once and returns to the starting point. For example, consider the graph shown in figure on right side. A TSP tour in the graph is 0-1-3-2-0. The cost of the tour is 10+25+30+15 which is 80.We have discussed following solutions 1) Naive and Dynamic Programming 2) Approximate solution using MST Branch and Bound Solution As seen in the previous articles, in Branch and Bound method, for current node in tree, we compute a bound on best possible solution that we can get if we down this node. If the bound on best possible solution itself is worse than current best (best computed so far), then we ignore the subtree rooted with the node. Note that the cost through a node includes two costs. 1) Cost of reaching the node from the root (When we reach a node, we have this cost computed) 2) Cost of reaching an answer from current node to a leaf (We compute a bound on this cost to decide whether to ignore subtree with this node or not). In cases of a maximization problem, an upper bound tells us the maximum possible solution if we follow the given node. For example in 0/1 knapsack we used Greedy approach to find an upper bound. In cases of a minimization problem, a lower bound tells us the minimum possible solution if we follow the given node. For example, in Job Assignment Problem, we get a lower bound by assigning least cost job to a worker. In branch and bound, the challenging part is figuring out a way to compute a bound on best possible solution. Below is an idea used to compute bounds for Traveling salesman problem.Cost of any tour can be written as below. Cost of a tour T = (1/2) * ∑ (Sum of cost of two edges adjacent to u and in the tour T) where u ∈ V For every vertex u, if we consider two edges through it in T, and sum their costs. The overall sum for all vertices would be twice of cost of tour T (We have considered every edge twice.) (Sum of two tour edges adjacent to u) >= (sum of minimum weight two edges adjacent to u) Cost of any tour >= 1/2) * ∑ (Sum of cost of two minimum weight edges adjacent to u) where u ∈ V For example, consider the above shown graph. Below are minimum cost two edges adjacent to every node. Node Least cost edges Total cost 0 (0, 1), (0, 2) 25 1 (0, 1), (1, 3) 35 2 (0, 2), (2, 3) 45 3 (0, 3), (1, 3) 45 Thus a lower bound on the cost of any tour = 1/2(25 + 35 + 45 + 45) = 75 Refer this for one more example. Now we have an idea about computation of lower bound. Let us see how to how to apply it state space search tree. We start enumerating all possible nodes (preferably in lexicographical order)1. The Root Node: Without loss of generality, we assume we start at vertex “0” for which the lower bound has been calculated above.Dealing with Level 2: The next level enumerates all possible vertices we can go to (keeping in mind that in any path a vertex has to occur only once) which are, 1, 2, 3... n (Note that the graph is complete). Consider we are calculating for vertex 1, Since we moved from 0 to 1, our tour has now included the edge 0-1. This allows us to make necessary changes in the lower bound of the root. Lower Bound for vertex 1 = Old lower bound - ((minimum edge cost of 0 + minimum edge cost of 1) / 2) + (edge cost 0-1) How does it work? To include edge 0-1, we add the edge cost of 0-1, and subtract an edge weight such that the lower bound remains as tight as possible which would be the sum of the minimum edges of 0 and 1 divided by 2. Clearly, the edge subtracted can’t be smaller than this.Dealing with other levels: As we move on to the next level, we again enumerate all possible vertices. For the above case going further after 1, we check out for 2, 3, 4, ...n. Consider lower bound for 2 as we moved from 1 to 1, we include the edge 1-2 to the tour and alter the new lower bound for this node. Lower bound(2) = Old lower bound - ((second minimum edge cost of 1 + minimum edge cost of 2)/2) + edge cost 1-2) Note: The only change in the formula is that this time we have included second minimum edge cost for 1, because the minimum edge cost has already been subtracted in previous level. C++ Java Python3 // C++ program to solve Traveling Salesman Problem// using Branch and Bound.#include <bits/stdc++.h>using namespace std;const int N = 4; // final_path[] stores the final solution ie, the// path of the salesman.int final_path[N+1]; // visited[] keeps track of the already visited nodes// in a particular pathbool visited[N]; // Stores the final minimum weight of shortest tour.int final_res = INT_MAX; // Function to copy temporary solution to// the final solutionvoid copyToFinal(int curr_path[]){ for (int i=0; i<N; i++) final_path[i] = curr_path[i]; final_path[N] = curr_path[0];} // Function to find the minimum edge cost// having an end at the vertex iint firstMin(int adj[N][N], int i){ int min = INT_MAX; for (int k=0; k<N; k++) if (adj[i][k]<min && i != k) min = adj[i][k]; return min;} // function to find the second minimum edge cost// having an end at the vertex iint secondMin(int adj[N][N], int i){ int first = INT_MAX, second = INT_MAX; for (int j=0; j<N; j++) { if (i == j) continue; if (adj[i][j] <= first) { second = first; first = adj[i][j]; } else if (adj[i][j] <= second && adj[i][j] != first) second = adj[i][j]; } return second;} // function that takes as arguments:// curr_bound -> lower bound of the root node// curr_weight-> stores the weight of the path so far// level-> current level while moving in the search// space tree// curr_path[] -> where the solution is being stored which// would later be copied to final_path[]void TSPRec(int adj[N][N], int curr_bound, int curr_weight, int level, int curr_path[]){ // base case is when we have reached level N which // means we have covered all the nodes once if (level==N) { // check if there is an edge from last vertex in // path back to the first vertex if (adj[curr_path[level-1]][curr_path[0]] != 0) { // curr_res has the total weight of the // solution we got int curr_res = curr_weight + adj[curr_path[level-1]][curr_path[0]]; // Update final result and final path if // current result is better. if (curr_res < final_res) { copyToFinal(curr_path); final_res = curr_res; } } return; } // for any other level iterate for all vertices to // build the search space tree recursively for (int i=0; i<N; i++) { // Consider next vertex if it is not same (diagonal // entry in adjacency matrix and not visited // already) if (adj[curr_path[level-1]][i] != 0 && visited[i] == false) { int temp = curr_bound; curr_weight += adj[curr_path[level-1]][i]; // different computation of curr_bound for // level 2 from the other levels if (level==1) curr_bound -= ((firstMin(adj, curr_path[level-1]) + firstMin(adj, i))/2); else curr_bound -= ((secondMin(adj, curr_path[level-1]) + firstMin(adj, i))/2); // curr_bound + curr_weight is the actual lower bound // for the node that we have arrived on // If current lower bound < final_res, we need to explore // the node further if (curr_bound + curr_weight < final_res) { curr_path[level] = i; visited[i] = true; // call TSPRec for the next level TSPRec(adj, curr_bound, curr_weight, level+1, curr_path); } // Else we have to prune the node by resetting // all changes to curr_weight and curr_bound curr_weight -= adj[curr_path[level-1]][i]; curr_bound = temp; // Also reset the visited array memset(visited, false, sizeof(visited)); for (int j=0; j<=level-1; j++) visited[curr_path[j]] = true; } }} // This function sets up final_path[] void TSP(int adj[N][N]){ int curr_path[N+1]; // Calculate initial lower bound for the root node // using the formula 1/2 * (sum of first min + // second min) for all edges. // Also initialize the curr_path and visited array int curr_bound = 0; memset(curr_path, -1, sizeof(curr_path)); memset(visited, 0, sizeof(curr_path)); // Compute initial bound for (int i=0; i<N; i++) curr_bound += (firstMin(adj, i) + secondMin(adj, i)); // Rounding off the lower bound to an integer curr_bound = (curr_bound&1)? curr_bound/2 + 1 : curr_bound/2; // We start at vertex 1 so the first vertex // in curr_path[] is 0 visited[0] = true; curr_path[0] = 0; // Call to TSPRec for curr_weight equal to // 0 and level 1 TSPRec(adj, curr_bound, 0, 1, curr_path);} // Driver codeint main(){ //Adjacency matrix for the given graph int adj[N][N] = { {0, 10, 15, 20}, {10, 0, 35, 25}, {15, 35, 0, 30}, {20, 25, 30, 0} }; TSP(adj); printf("Minimum cost : %d\n", final_res); printf("Path Taken : "); for (int i=0; i<=N; i++) printf("%d ", final_path[i]); return 0;} // Java program to solve Traveling Salesman Problem// using Branch and Bound.import java.util.*; class GFG{ static int N = 4; // final_path[] stores the final solution ie, the // path of the salesman. static int final_path[] = new int[N + 1]; // visited[] keeps track of the already visited nodes // in a particular path static boolean visited[] = new boolean[N]; // Stores the final minimum weight of shortest tour. static int final_res = Integer.MAX_VALUE; // Function to copy temporary solution to // the final solution static void copyToFinal(int curr_path[]) { for (int i = 0; i < N; i++) final_path[i] = curr_path[i]; final_path[N] = curr_path[0]; } // Function to find the minimum edge cost // having an end at the vertex i static int firstMin(int adj[][], int i) { int min = Integer.MAX_VALUE; for (int k = 0; k < N; k++) if (adj[i][k] < min && i != k) min = adj[i][k]; return min; } // function to find the second minimum edge cost // having an end at the vertex i static int secondMin(int adj[][], int i) { int first = Integer.MAX_VALUE, second = Integer.MAX_VALUE; for (int j=0; j<N; j++) { if (i == j) continue; if (adj[i][j] <= first) { second = first; first = adj[i][j]; } else if (adj[i][j] <= second && adj[i][j] != first) second = adj[i][j]; } return second; } // function that takes as arguments: // curr_bound -> lower bound of the root node // curr_weight-> stores the weight of the path so far // level-> current level while moving in the search // space tree // curr_path[] -> where the solution is being stored which // would later be copied to final_path[] static void TSPRec(int adj[][], int curr_bound, int curr_weight, int level, int curr_path[]) { // base case is when we have reached level N which // means we have covered all the nodes once if (level == N) { // check if there is an edge from last vertex in // path back to the first vertex if (adj[curr_path[level - 1]][curr_path[0]] != 0) { // curr_res has the total weight of the // solution we got int curr_res = curr_weight + adj[curr_path[level-1]][curr_path[0]]; // Update final result and final path if // current result is better. if (curr_res < final_res) { copyToFinal(curr_path); final_res = curr_res; } } return; } // for any other level iterate for all vertices to // build the search space tree recursively for (int i = 0; i < N; i++) { // Consider next vertex if it is not same (diagonal // entry in adjacency matrix and not visited // already) if (adj[curr_path[level-1]][i] != 0 && visited[i] == false) { int temp = curr_bound; curr_weight += adj[curr_path[level - 1]][i]; // different computation of curr_bound for // level 2 from the other levels if (level==1) curr_bound -= ((firstMin(adj, curr_path[level - 1]) + firstMin(adj, i))/2); else curr_bound -= ((secondMin(adj, curr_path[level - 1]) + firstMin(adj, i))/2); // curr_bound + curr_weight is the actual lower bound // for the node that we have arrived on // If current lower bound < final_res, we need to explore // the node further if (curr_bound + curr_weight < final_res) { curr_path[level] = i; visited[i] = true; // call TSPRec for the next level TSPRec(adj, curr_bound, curr_weight, level + 1, curr_path); } // Else we have to prune the node by resetting // all changes to curr_weight and curr_bound curr_weight -= adj[curr_path[level-1]][i]; curr_bound = temp; // Also reset the visited array Arrays.fill(visited,false); for (int j = 0; j <= level - 1; j++) visited[curr_path[j]] = true; } } } // This function sets up final_path[] static void TSP(int adj[][]) { int curr_path[] = new int[N + 1]; // Calculate initial lower bound for the root node // using the formula 1/2 * (sum of first min + // second min) for all edges. // Also initialize the curr_path and visited array int curr_bound = 0; Arrays.fill(curr_path, -1); Arrays.fill(visited, false); // Compute initial bound for (int i = 0; i < N; i++) curr_bound += (firstMin(adj, i) + secondMin(adj, i)); // Rounding off the lower bound to an integer curr_bound = (curr_bound==1)? curr_bound/2 + 1 : curr_bound/2; // We start at vertex 1 so the first vertex // in curr_path[] is 0 visited[0] = true; curr_path[0] = 0; // Call to TSPRec for curr_weight equal to // 0 and level 1 TSPRec(adj, curr_bound, 0, 1, curr_path); } // Driver code public static void main(String[] args) { //Adjacency matrix for the given graph int adj[][] = {{0, 10, 15, 20}, {10, 0, 35, 25}, {15, 35, 0, 30}, {20, 25, 30, 0} }; TSP(adj); System.out.printf("Minimum cost : %d\n", final_res); System.out.printf("Path Taken : "); for (int i = 0; i <= N; i++) { System.out.printf("%d ", final_path[i]); } }} /* This code contributed by PrinciRaj1992 */ # Python3 program to solve # Traveling Salesman Problem using # Branch and Bound.import mathmaxsize = float('inf') # Function to copy temporary solution# to the final solutiondef copyToFinal(curr_path): final_path[:N + 1] = curr_path[:] final_path[N] = curr_path[0] # Function to find the minimum edge cost # having an end at the vertex idef firstMin(adj, i): min = maxsize for k in range(N): if adj[i][k] < min and i != k: min = adj[i][k] return min # function to find the second minimum edge # cost having an end at the vertex idef secondMin(adj, i): first, second = maxsize, maxsize for j in range(N): if i == j: continue if adj[i][j] <= first: second = first first = adj[i][j] elif(adj[i][j] <= second and adj[i][j] != first): second = adj[i][j] return second # function that takes as arguments:# curr_bound -> lower bound of the root node# curr_weight-> stores the weight of the path so far# level-> current level while moving# in the search space tree# curr_path[] -> where the solution is being stored# which would later be copied to final_path[]def TSPRec(adj, curr_bound, curr_weight, level, curr_path, visited): global final_res # base case is when we have reached level N # which means we have covered all the nodes once if level == N: # check if there is an edge from # last vertex in path back to the first vertex if adj[curr_path[level - 1]][curr_path[0]] != 0: # curr_res has the total weight # of the solution we got curr_res = curr_weight + adj[curr_path[level - 1]]\ [curr_path[0]] if curr_res < final_res: copyToFinal(curr_path) final_res = curr_res return # for any other level iterate for all vertices # to build the search space tree recursively for i in range(N): # Consider next vertex if it is not same # (diagonal entry in adjacency matrix and # not visited already) if (adj[curr_path[level-1]][i] != 0 and visited[i] == False): temp = curr_bound curr_weight += adj[curr_path[level - 1]][i] # different computation of curr_bound # for level 2 from the other levels if level == 1: curr_bound -= ((firstMin(adj, curr_path[level - 1]) + firstMin(adj, i)) / 2) else: curr_bound -= ((secondMin(adj, curr_path[level - 1]) + firstMin(adj, i)) / 2) # curr_bound + curr_weight is the actual lower bound # for the node that we have arrived on. # If current lower bound < final_res, # we need to explore the node further if curr_bound + curr_weight < final_res: curr_path[level] = i visited[i] = True # call TSPRec for the next level TSPRec(adj, curr_bound, curr_weight, level + 1, curr_path, visited) # Else we have to prune the node by resetting # all changes to curr_weight and curr_bound curr_weight -= adj[curr_path[level - 1]][i] curr_bound = temp # Also reset the visited array visited = [False] * len(visited) for j in range(level): if curr_path[j] != -1: visited[curr_path[j]] = True # This function sets up final_pathdef TSP(adj): # Calculate initial lower bound for the root node # using the formula 1/2 * (sum of first min + # second min) for all edges. Also initialize the # curr_path and visited array curr_bound = 0 curr_path = [-1] * (N + 1) visited = [False] * N # Compute initial bound for i in range(N): curr_bound += (firstMin(adj, i) + secondMin(adj, i)) # Rounding off the lower bound to an integer curr_bound = math.ceil(curr_bound / 2) # We start at vertex 1 so the first vertex # in curr_path[] is 0 visited[0] = True curr_path[0] = 0 # Call to TSPRec for curr_weight # equal to 0 and level 1 TSPRec(adj, curr_bound, 0, 1, curr_path, visited) # Driver code # Adjacency matrix for the given graphadj = [[0, 10, 15, 20], [10, 0, 35, 25], [15, 35, 0, 30], [20, 25, 30, 0]]N = 4 # final_path[] stores the final solution # i.e. the // path of the salesman.final_path = [None] * (N + 1) # visited[] keeps track of the already# visited nodes in a particular pathvisited = [False] * N # Stores the final minimum weight# of shortest tour.final_res = maxsize TSP(adj) print("Minimum cost :", final_res)print("Path Taken : ", end = ' ')for i in range(N + 1): print(final_path[i], end = ' ') # This code is contributed by ng24_7 Output : Minimum cost : 80 Path Taken : 0 1 3 2 0 Time Complexity: The worst case complexity of Branch and Bound remains same as that of the Brute Force clearly because in worst case, we may never get a chance to prune a node. Whereas, in practice it performs very well depending on the different instance of the TSP. The complexity also depends on the choice of the bounding function as they are the ones deciding how many nodes to be pruned.References: http://lcm.csa.iisc.ernet.in/dsa/node187.htmlThis article is contributed by Anurag Rai. If you like GeeksforGeeks and would like to contribute, you can also write an article and mail your article to review-team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. princiraj1992 naina024 simmytarika5 ghosttribe7 Branch and Bound Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 52, "s": 24, "text": "\n25 Mar, 2022" }, { "code": null, "e": 239, "s": 52, "text": "Given a set of cities and distance between every pair of cities, the problem is to find the shortest possible tour that visits every city exactly once and returns to the starting point. " }, { "code": null, "e": 1138, "s": 239, "text": "For example, consider the graph shown in figure on right side. A TSP tour in the graph is 0-1-3-2-0. The cost of the tour is 10+25+30+15 which is 80.We have discussed following solutions 1) Naive and Dynamic Programming 2) Approximate solution using MST Branch and Bound Solution As seen in the previous articles, in Branch and Bound method, for current node in tree, we compute a bound on best possible solution that we can get if we down this node. If the bound on best possible solution itself is worse than current best (best computed so far), then we ignore the subtree rooted with the node. Note that the cost through a node includes two costs. 1) Cost of reaching the node from the root (When we reach a node, we have this cost computed) 2) Cost of reaching an answer from current node to a leaf (We compute a bound on this cost to decide whether to ignore subtree with this node or not). " }, { "code": null, "e": 1333, "s": 1138, "text": "In cases of a maximization problem, an upper bound tells us the maximum possible solution if we follow the given node. For example in 0/1 knapsack we used Greedy approach to find an upper bound." }, { "code": null, "e": 1553, "s": 1333, "text": "In cases of a minimization problem, a lower bound tells us the minimum possible solution if we follow the given node. For example, in Job Assignment Problem, we get a lower bound by assigning least cost job to a worker." }, { "code": null, "e": 1777, "s": 1553, "text": "In branch and bound, the challenging part is figuring out a way to compute a bound on best possible solution. Below is an idea used to compute bounds for Traveling salesman problem.Cost of any tour can be written as below. " }, { "code": null, "e": 2470, "s": 1777, "text": "Cost of a tour T = (1/2) * ∑ (Sum of cost of two edges\n adjacent to u and in the\n tour T) \n where u ∈ V\nFor every vertex u, if we consider two edges through it in T,\nand sum their costs. The overall sum for all vertices would\nbe twice of cost of tour T (We have considered every edge \ntwice.)\n\n(Sum of two tour edges adjacent to u) >= (sum of minimum weight\n two edges adjacent to\n u)\n\nCost of any tour >= 1/2) * ∑ (Sum of cost of two minimum\n weight edges adjacent to u) \n where u ∈ V" }, { "code": null, "e": 2574, "s": 2470, "text": "For example, consider the above shown graph. Below are minimum cost two edges adjacent to every node. " }, { "code": null, "e": 2885, "s": 2574, "text": "Node Least cost edges Total cost \n0 (0, 1), (0, 2) 25\n1 (0, 1), (1, 3) 35\n2 (0, 2), (2, 3) 45\n3 (0, 3), (1, 3) 45\n\nThus a lower bound on the cost of any tour = \n 1/2(25 + 35 + 45 + 45)\n = 75\nRefer this for one more example." }, { "code": null, "e": 3600, "s": 2885, "text": "Now we have an idea about computation of lower bound. Let us see how to how to apply it state space search tree. We start enumerating all possible nodes (preferably in lexicographical order)1. The Root Node: Without loss of generality, we assume we start at vertex “0” for which the lower bound has been calculated above.Dealing with Level 2: The next level enumerates all possible vertices we can go to (keeping in mind that in any path a vertex has to occur only once) which are, 1, 2, 3... n (Note that the graph is complete). Consider we are calculating for vertex 1, Since we moved from 0 to 1, our tour has now included the edge 0-1. This allows us to make necessary changes in the lower bound of the root. " }, { "code": null, "e": 3763, "s": 3600, "text": "Lower Bound for vertex 1 = \n Old lower bound - ((minimum edge cost of 0 + \n minimum edge cost of 1) / 2) \n + (edge cost 0-1)" }, { "code": null, "e": 4349, "s": 3763, "text": "How does it work? To include edge 0-1, we add the edge cost of 0-1, and subtract an edge weight such that the lower bound remains as tight as possible which would be the sum of the minimum edges of 0 and 1 divided by 2. Clearly, the edge subtracted can’t be smaller than this.Dealing with other levels: As we move on to the next level, we again enumerate all possible vertices. For the above case going further after 1, we check out for 2, 3, 4, ...n. Consider lower bound for 2 as we moved from 1 to 1, we include the edge 1-2 to the tour and alter the new lower bound for this node. " }, { "code": null, "e": 4515, "s": 4349, "text": "Lower bound(2) = \n Old lower bound - ((second minimum edge cost of 1 + \n minimum edge cost of 2)/2)\n + edge cost 1-2)" }, { "code": null, "e": 4698, "s": 4515, "text": "Note: The only change in the formula is that this time we have included second minimum edge cost for 1, because the minimum edge cost has already been subtracted in previous level. " }, { "code": null, "e": 4702, "s": 4698, "text": "C++" }, { "code": null, "e": 4707, "s": 4702, "text": "Java" }, { "code": null, "e": 4715, "s": 4707, "text": "Python3" }, { "code": "// C++ program to solve Traveling Salesman Problem// using Branch and Bound.#include <bits/stdc++.h>using namespace std;const int N = 4; // final_path[] stores the final solution ie, the// path of the salesman.int final_path[N+1]; // visited[] keeps track of the already visited nodes// in a particular pathbool visited[N]; // Stores the final minimum weight of shortest tour.int final_res = INT_MAX; // Function to copy temporary solution to// the final solutionvoid copyToFinal(int curr_path[]){ for (int i=0; i<N; i++) final_path[i] = curr_path[i]; final_path[N] = curr_path[0];} // Function to find the minimum edge cost// having an end at the vertex iint firstMin(int adj[N][N], int i){ int min = INT_MAX; for (int k=0; k<N; k++) if (adj[i][k]<min && i != k) min = adj[i][k]; return min;} // function to find the second minimum edge cost// having an end at the vertex iint secondMin(int adj[N][N], int i){ int first = INT_MAX, second = INT_MAX; for (int j=0; j<N; j++) { if (i == j) continue; if (adj[i][j] <= first) { second = first; first = adj[i][j]; } else if (adj[i][j] <= second && adj[i][j] != first) second = adj[i][j]; } return second;} // function that takes as arguments:// curr_bound -> lower bound of the root node// curr_weight-> stores the weight of the path so far// level-> current level while moving in the search// space tree// curr_path[] -> where the solution is being stored which// would later be copied to final_path[]void TSPRec(int adj[N][N], int curr_bound, int curr_weight, int level, int curr_path[]){ // base case is when we have reached level N which // means we have covered all the nodes once if (level==N) { // check if there is an edge from last vertex in // path back to the first vertex if (adj[curr_path[level-1]][curr_path[0]] != 0) { // curr_res has the total weight of the // solution we got int curr_res = curr_weight + adj[curr_path[level-1]][curr_path[0]]; // Update final result and final path if // current result is better. if (curr_res < final_res) { copyToFinal(curr_path); final_res = curr_res; } } return; } // for any other level iterate for all vertices to // build the search space tree recursively for (int i=0; i<N; i++) { // Consider next vertex if it is not same (diagonal // entry in adjacency matrix and not visited // already) if (adj[curr_path[level-1]][i] != 0 && visited[i] == false) { int temp = curr_bound; curr_weight += adj[curr_path[level-1]][i]; // different computation of curr_bound for // level 2 from the other levels if (level==1) curr_bound -= ((firstMin(adj, curr_path[level-1]) + firstMin(adj, i))/2); else curr_bound -= ((secondMin(adj, curr_path[level-1]) + firstMin(adj, i))/2); // curr_bound + curr_weight is the actual lower bound // for the node that we have arrived on // If current lower bound < final_res, we need to explore // the node further if (curr_bound + curr_weight < final_res) { curr_path[level] = i; visited[i] = true; // call TSPRec for the next level TSPRec(adj, curr_bound, curr_weight, level+1, curr_path); } // Else we have to prune the node by resetting // all changes to curr_weight and curr_bound curr_weight -= adj[curr_path[level-1]][i]; curr_bound = temp; // Also reset the visited array memset(visited, false, sizeof(visited)); for (int j=0; j<=level-1; j++) visited[curr_path[j]] = true; } }} // This function sets up final_path[] void TSP(int adj[N][N]){ int curr_path[N+1]; // Calculate initial lower bound for the root node // using the formula 1/2 * (sum of first min + // second min) for all edges. // Also initialize the curr_path and visited array int curr_bound = 0; memset(curr_path, -1, sizeof(curr_path)); memset(visited, 0, sizeof(curr_path)); // Compute initial bound for (int i=0; i<N; i++) curr_bound += (firstMin(adj, i) + secondMin(adj, i)); // Rounding off the lower bound to an integer curr_bound = (curr_bound&1)? curr_bound/2 + 1 : curr_bound/2; // We start at vertex 1 so the first vertex // in curr_path[] is 0 visited[0] = true; curr_path[0] = 0; // Call to TSPRec for curr_weight equal to // 0 and level 1 TSPRec(adj, curr_bound, 0, 1, curr_path);} // Driver codeint main(){ //Adjacency matrix for the given graph int adj[N][N] = { {0, 10, 15, 20}, {10, 0, 35, 25}, {15, 35, 0, 30}, {20, 25, 30, 0} }; TSP(adj); printf(\"Minimum cost : %d\\n\", final_res); printf(\"Path Taken : \"); for (int i=0; i<=N; i++) printf(\"%d \", final_path[i]); return 0;}", "e": 10157, "s": 4715, "text": null }, { "code": "// Java program to solve Traveling Salesman Problem// using Branch and Bound.import java.util.*; class GFG{ static int N = 4; // final_path[] stores the final solution ie, the // path of the salesman. static int final_path[] = new int[N + 1]; // visited[] keeps track of the already visited nodes // in a particular path static boolean visited[] = new boolean[N]; // Stores the final minimum weight of shortest tour. static int final_res = Integer.MAX_VALUE; // Function to copy temporary solution to // the final solution static void copyToFinal(int curr_path[]) { for (int i = 0; i < N; i++) final_path[i] = curr_path[i]; final_path[N] = curr_path[0]; } // Function to find the minimum edge cost // having an end at the vertex i static int firstMin(int adj[][], int i) { int min = Integer.MAX_VALUE; for (int k = 0; k < N; k++) if (adj[i][k] < min && i != k) min = adj[i][k]; return min; } // function to find the second minimum edge cost // having an end at the vertex i static int secondMin(int adj[][], int i) { int first = Integer.MAX_VALUE, second = Integer.MAX_VALUE; for (int j=0; j<N; j++) { if (i == j) continue; if (adj[i][j] <= first) { second = first; first = adj[i][j]; } else if (adj[i][j] <= second && adj[i][j] != first) second = adj[i][j]; } return second; } // function that takes as arguments: // curr_bound -> lower bound of the root node // curr_weight-> stores the weight of the path so far // level-> current level while moving in the search // space tree // curr_path[] -> where the solution is being stored which // would later be copied to final_path[] static void TSPRec(int adj[][], int curr_bound, int curr_weight, int level, int curr_path[]) { // base case is when we have reached level N which // means we have covered all the nodes once if (level == N) { // check if there is an edge from last vertex in // path back to the first vertex if (adj[curr_path[level - 1]][curr_path[0]] != 0) { // curr_res has the total weight of the // solution we got int curr_res = curr_weight + adj[curr_path[level-1]][curr_path[0]]; // Update final result and final path if // current result is better. if (curr_res < final_res) { copyToFinal(curr_path); final_res = curr_res; } } return; } // for any other level iterate for all vertices to // build the search space tree recursively for (int i = 0; i < N; i++) { // Consider next vertex if it is not same (diagonal // entry in adjacency matrix and not visited // already) if (adj[curr_path[level-1]][i] != 0 && visited[i] == false) { int temp = curr_bound; curr_weight += adj[curr_path[level - 1]][i]; // different computation of curr_bound for // level 2 from the other levels if (level==1) curr_bound -= ((firstMin(adj, curr_path[level - 1]) + firstMin(adj, i))/2); else curr_bound -= ((secondMin(adj, curr_path[level - 1]) + firstMin(adj, i))/2); // curr_bound + curr_weight is the actual lower bound // for the node that we have arrived on // If current lower bound < final_res, we need to explore // the node further if (curr_bound + curr_weight < final_res) { curr_path[level] = i; visited[i] = true; // call TSPRec for the next level TSPRec(adj, curr_bound, curr_weight, level + 1, curr_path); } // Else we have to prune the node by resetting // all changes to curr_weight and curr_bound curr_weight -= adj[curr_path[level-1]][i]; curr_bound = temp; // Also reset the visited array Arrays.fill(visited,false); for (int j = 0; j <= level - 1; j++) visited[curr_path[j]] = true; } } } // This function sets up final_path[] static void TSP(int adj[][]) { int curr_path[] = new int[N + 1]; // Calculate initial lower bound for the root node // using the formula 1/2 * (sum of first min + // second min) for all edges. // Also initialize the curr_path and visited array int curr_bound = 0; Arrays.fill(curr_path, -1); Arrays.fill(visited, false); // Compute initial bound for (int i = 0; i < N; i++) curr_bound += (firstMin(adj, i) + secondMin(adj, i)); // Rounding off the lower bound to an integer curr_bound = (curr_bound==1)? curr_bound/2 + 1 : curr_bound/2; // We start at vertex 1 so the first vertex // in curr_path[] is 0 visited[0] = true; curr_path[0] = 0; // Call to TSPRec for curr_weight equal to // 0 and level 1 TSPRec(adj, curr_bound, 0, 1, curr_path); } // Driver code public static void main(String[] args) { //Adjacency matrix for the given graph int adj[][] = {{0, 10, 15, 20}, {10, 0, 35, 25}, {15, 35, 0, 30}, {20, 25, 30, 0} }; TSP(adj); System.out.printf(\"Minimum cost : %d\\n\", final_res); System.out.printf(\"Path Taken : \"); for (int i = 0; i <= N; i++) { System.out.printf(\"%d \", final_path[i]); } }} /* This code contributed by PrinciRaj1992 */", "e": 16522, "s": 10157, "text": null }, { "code": "# Python3 program to solve # Traveling Salesman Problem using # Branch and Bound.import mathmaxsize = float('inf') # Function to copy temporary solution# to the final solutiondef copyToFinal(curr_path): final_path[:N + 1] = curr_path[:] final_path[N] = curr_path[0] # Function to find the minimum edge cost # having an end at the vertex idef firstMin(adj, i): min = maxsize for k in range(N): if adj[i][k] < min and i != k: min = adj[i][k] return min # function to find the second minimum edge # cost having an end at the vertex idef secondMin(adj, i): first, second = maxsize, maxsize for j in range(N): if i == j: continue if adj[i][j] <= first: second = first first = adj[i][j] elif(adj[i][j] <= second and adj[i][j] != first): second = adj[i][j] return second # function that takes as arguments:# curr_bound -> lower bound of the root node# curr_weight-> stores the weight of the path so far# level-> current level while moving# in the search space tree# curr_path[] -> where the solution is being stored# which would later be copied to final_path[]def TSPRec(adj, curr_bound, curr_weight, level, curr_path, visited): global final_res # base case is when we have reached level N # which means we have covered all the nodes once if level == N: # check if there is an edge from # last vertex in path back to the first vertex if adj[curr_path[level - 1]][curr_path[0]] != 0: # curr_res has the total weight # of the solution we got curr_res = curr_weight + adj[curr_path[level - 1]]\\ [curr_path[0]] if curr_res < final_res: copyToFinal(curr_path) final_res = curr_res return # for any other level iterate for all vertices # to build the search space tree recursively for i in range(N): # Consider next vertex if it is not same # (diagonal entry in adjacency matrix and # not visited already) if (adj[curr_path[level-1]][i] != 0 and visited[i] == False): temp = curr_bound curr_weight += adj[curr_path[level - 1]][i] # different computation of curr_bound # for level 2 from the other levels if level == 1: curr_bound -= ((firstMin(adj, curr_path[level - 1]) + firstMin(adj, i)) / 2) else: curr_bound -= ((secondMin(adj, curr_path[level - 1]) + firstMin(adj, i)) / 2) # curr_bound + curr_weight is the actual lower bound # for the node that we have arrived on. # If current lower bound < final_res, # we need to explore the node further if curr_bound + curr_weight < final_res: curr_path[level] = i visited[i] = True # call TSPRec for the next level TSPRec(adj, curr_bound, curr_weight, level + 1, curr_path, visited) # Else we have to prune the node by resetting # all changes to curr_weight and curr_bound curr_weight -= adj[curr_path[level - 1]][i] curr_bound = temp # Also reset the visited array visited = [False] * len(visited) for j in range(level): if curr_path[j] != -1: visited[curr_path[j]] = True # This function sets up final_pathdef TSP(adj): # Calculate initial lower bound for the root node # using the formula 1/2 * (sum of first min + # second min) for all edges. Also initialize the # curr_path and visited array curr_bound = 0 curr_path = [-1] * (N + 1) visited = [False] * N # Compute initial bound for i in range(N): curr_bound += (firstMin(adj, i) + secondMin(adj, i)) # Rounding off the lower bound to an integer curr_bound = math.ceil(curr_bound / 2) # We start at vertex 1 so the first vertex # in curr_path[] is 0 visited[0] = True curr_path[0] = 0 # Call to TSPRec for curr_weight # equal to 0 and level 1 TSPRec(adj, curr_bound, 0, 1, curr_path, visited) # Driver code # Adjacency matrix for the given graphadj = [[0, 10, 15, 20], [10, 0, 35, 25], [15, 35, 0, 30], [20, 25, 30, 0]]N = 4 # final_path[] stores the final solution # i.e. the // path of the salesman.final_path = [None] * (N + 1) # visited[] keeps track of the already# visited nodes in a particular pathvisited = [False] * N # Stores the final minimum weight# of shortest tour.final_res = maxsize TSP(adj) print(\"Minimum cost :\", final_res)print(\"Path Taken : \", end = ' ')for i in range(N + 1): print(final_path[i], end = ' ') # This code is contributed by ng24_7", "e": 21558, "s": 16522, "text": null }, { "code": null, "e": 21569, "s": 21558, "text": "Output : " }, { "code": null, "e": 21611, "s": 21569, "text": "Minimum cost : 80\nPath Taken : 0 1 3 2 0 " }, { "code": null, "e": 22451, "s": 21611, "text": "Time Complexity: The worst case complexity of Branch and Bound remains same as that of the Brute Force clearly because in worst case, we may never get a chance to prune a node. Whereas, in practice it performs very well depending on the different instance of the TSP. The complexity also depends on the choice of the bounding function as they are the ones deciding how many nodes to be pruned.References: http://lcm.csa.iisc.ernet.in/dsa/node187.htmlThis article is contributed by Anurag Rai. If you like GeeksforGeeks and would like to contribute, you can also write an article and mail your article to review-team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. " }, { "code": null, "e": 22465, "s": 22451, "text": "princiraj1992" }, { "code": null, "e": 22474, "s": 22465, "text": "naina024" }, { "code": null, "e": 22487, "s": 22474, "text": "simmytarika5" }, { "code": null, "e": 22499, "s": 22487, "text": "ghosttribe7" }, { "code": null, "e": 22516, "s": 22499, "text": "Branch and Bound" } ]
Find the average of an unknown number of inputs in Python
03 Dec, 2021 Prerequisites: *args and **kwargs in PythonThe special syntax *args in function definitions in python is used to pass a variable number of arguments to a function. It is used to pass a non-keyworded, variable-length argument list. The syntax is to use the symbol * to take in a variable number of arguments; by convention, it is often used with the word args. In this article, the task is to find the average of the unknown number of inputs.Examples: Input : 1, 2, 3 Output : 2.00 Input : 2, 6, 4, 8 Output: 5.00 Below is the implementation. Python3 # function that takes arbitrary# number of inputsdef avgfun(*n): sums = 0 for t in n: sums = sums + t avg = sums / len(n) return avg # Driver Coderesult1 = avgfun(1, 2, 3)result2 = avgfun(2, 6, 4, 8) # Printing average of the listprint(round(result1, 2))print(round(result2, 2)) Output: 2.0 5.0 clintra Python function-programs Python-Functions Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to Install PIP on Windows ? Python Classes and Objects Python OOPs Concepts Introduction To PYTHON How to drop one or multiple columns in Pandas Dataframe Python | os.path.join() method Check if element exists in list in Python How To Convert Python Dictionary To JSON? Python | Get unique values from a list Python | datetime.timedelta() function
[ { "code": null, "e": 53, "s": 25, "text": "\n03 Dec, 2021" }, { "code": null, "e": 506, "s": 53, "text": "Prerequisites: *args and **kwargs in PythonThe special syntax *args in function definitions in python is used to pass a variable number of arguments to a function. It is used to pass a non-keyworded, variable-length argument list. The syntax is to use the symbol * to take in a variable number of arguments; by convention, it is often used with the word args. In this article, the task is to find the average of the unknown number of inputs.Examples: " }, { "code": null, "e": 569, "s": 506, "text": "Input : 1, 2, 3\nOutput : 2.00\n\nInput : 2, 6, 4, 8\nOutput: 5.00" }, { "code": null, "e": 600, "s": 569, "text": "Below is the implementation. " }, { "code": null, "e": 608, "s": 600, "text": "Python3" }, { "code": "# function that takes arbitrary# number of inputsdef avgfun(*n): sums = 0 for t in n: sums = sums + t avg = sums / len(n) return avg # Driver Coderesult1 = avgfun(1, 2, 3)result2 = avgfun(2, 6, 4, 8) # Printing average of the listprint(round(result1, 2))print(round(result2, 2))", "e": 913, "s": 608, "text": null }, { "code": null, "e": 922, "s": 913, "text": "Output: " }, { "code": null, "e": 930, "s": 922, "text": "2.0\n5.0" }, { "code": null, "e": 940, "s": 932, "text": "clintra" }, { "code": null, "e": 965, "s": 940, "text": "Python function-programs" }, { "code": null, "e": 982, "s": 965, "text": "Python-Functions" }, { "code": null, "e": 989, "s": 982, "text": "Python" }, { "code": null, "e": 1087, "s": 989, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 1119, "s": 1087, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 1146, "s": 1119, "text": "Python Classes and Objects" }, { "code": null, "e": 1167, "s": 1146, "text": "Python OOPs Concepts" }, { "code": null, "e": 1190, "s": 1167, "text": "Introduction To PYTHON" }, { "code": null, "e": 1246, "s": 1190, "text": "How to drop one or multiple columns in Pandas Dataframe" }, { "code": null, "e": 1277, "s": 1246, "text": "Python | os.path.join() method" }, { "code": null, "e": 1319, "s": 1277, "text": "Check if element exists in list in Python" }, { "code": null, "e": 1361, "s": 1319, "text": "How To Convert Python Dictionary To JSON?" }, { "code": null, "e": 1400, "s": 1361, "text": "Python | Get unique values from a list" } ]
SQL Clusters
09 Oct, 2020 In this article, we are going to cover the SQL cluster and will also cover some advantages and disadvantages of SQL clusters. Let’s discuss one by one. Clusters in SQL are used to store data that is from different tables in the same physical data blocks. They are used if records from those tables are frequently queried together. By storing same data blocks, the number of database block reads needed to full fill such queries decreases which improves performance. Each cluster stores tables data and maintains a clustered index to sort data. Columns within the cluster index are called clustered keys. These determine the physical placement of rows within the cluster. Cluster key is usually a foreign key of one table that references the primary key of another table in cluster. The first cluster is created. Then cluster index is created on cluster key columns. After cluster key index is created, data can be entered into tables stored in clusters. As rows are inserted database stores cluster key and its associated rows in each of the cluster’s blocks. Syntax : CREATE CLUSTER <Cluster Name> (<Column> <Data Type> [, <Column> <Data Type> ] . . . . . ) [<Other Options >] Example – create table branch_master ( "branch_code" varchar(10) PRIMARY KEY, "branch_name" varchar(15) ); Now, Consider the above created table and let’s create the cluster for the same.Creating a Cluster : create cluster branch_info ( "branch_code" varchar(10) ); Advantages of clusters : Disk I/O is reduced.Access time improves for joins of clustered tables.As all rows in clustered tables use the same columns as common primary key, this yields storage benefit. Disk I/O is reduced. Access time improves for joins of clustered tables. As all rows in clustered tables use the same columns as common primary key, this yields storage benefit. Disadvantages of clusters : Reduces performance of INSERT statements as compared to storing the table separately with its own index.Columns that are often updated are not good candidates for cluster key. Reduces performance of INSERT statements as compared to storing the table separately with its own index. Columns that are often updated are not good candidates for cluster key. DBMS SQL DBMS SQL Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n09 Oct, 2020" }, { "code": null, "e": 180, "s": 28, "text": "In this article, we are going to cover the SQL cluster and will also cover some advantages and disadvantages of SQL clusters. Let’s discuss one by one." }, { "code": null, "e": 494, "s": 180, "text": "Clusters in SQL are used to store data that is from different tables in the same physical data blocks. They are used if records from those tables are frequently queried together. By storing same data blocks, the number of database block reads needed to full fill such queries decreases which improves performance." }, { "code": null, "e": 572, "s": 494, "text": "Each cluster stores tables data and maintains a clustered index to sort data." }, { "code": null, "e": 699, "s": 572, "text": "Columns within the cluster index are called clustered keys. These determine the physical placement of rows within the cluster." }, { "code": null, "e": 810, "s": 699, "text": "Cluster key is usually a foreign key of one table that references the primary key of another table in cluster." }, { "code": null, "e": 1088, "s": 810, "text": "The first cluster is created. Then cluster index is created on cluster key columns. After cluster key index is created, data can be entered into tables stored in clusters. As rows are inserted database stores cluster key and its associated rows in each of the cluster’s blocks." }, { "code": null, "e": 1097, "s": 1088, "text": "Syntax :" }, { "code": null, "e": 1209, "s": 1097, "text": "CREATE CLUSTER <Cluster Name> \n(<Column> <Data Type> \n[, <Column> <Data Type> ] . . . . . )\n[<Other Options >]\n" }, { "code": null, "e": 1219, "s": 1209, "text": "Example –" }, { "code": null, "e": 1320, "s": 1219, "text": "create table branch_master \n( \n\"branch_code\" varchar(10) PRIMARY KEY, \n\"branch_name\" varchar(15)\n);\n" }, { "code": null, "e": 1421, "s": 1320, "text": "Now, Consider the above created table and let’s create the cluster for the same.Creating a Cluster :" }, { "code": null, "e": 1481, "s": 1421, "text": "create cluster branch_info\n( \n\"branch_code\" varchar(10)\n);\n" }, { "code": null, "e": 1506, "s": 1481, "text": "Advantages of clusters :" }, { "code": null, "e": 1682, "s": 1506, "text": "Disk I/O is reduced.Access time improves for joins of clustered tables.As all rows in clustered tables use the same columns as common primary key, this yields storage benefit." }, { "code": null, "e": 1703, "s": 1682, "text": "Disk I/O is reduced." }, { "code": null, "e": 1755, "s": 1703, "text": "Access time improves for joins of clustered tables." }, { "code": null, "e": 1860, "s": 1755, "text": "As all rows in clustered tables use the same columns as common primary key, this yields storage benefit." }, { "code": null, "e": 1888, "s": 1860, "text": "Disadvantages of clusters :" }, { "code": null, "e": 2064, "s": 1888, "text": "Reduces performance of INSERT statements as compared to storing the table separately with its own index.Columns that are often updated are not good candidates for cluster key." }, { "code": null, "e": 2169, "s": 2064, "text": "Reduces performance of INSERT statements as compared to storing the table separately with its own index." }, { "code": null, "e": 2241, "s": 2169, "text": "Columns that are often updated are not good candidates for cluster key." }, { "code": null, "e": 2246, "s": 2241, "text": "DBMS" }, { "code": null, "e": 2250, "s": 2246, "text": "SQL" }, { "code": null, "e": 2255, "s": 2250, "text": "DBMS" }, { "code": null, "e": 2259, "s": 2255, "text": "SQL" } ]
HTML | <td> width Attribute
29 Jul, 2021 The HTML <td> width Attribute is used to specify the width of a table cell. If width attribute is not set then it takes default width according to content. Syntax: <td width="pixels | %"> Attribute Values: pixels: It sets the width of table in terms of pixels. %: It sets the width of table in terms of percentage (%). Note: The <td> width Attribute is not supported by HTML 5. Example: <!DOCTYPE html><html> <head> <title> HTML td width Attribute </title></head> <body> <h1>GeeksforGeeks</h1> <h2>HTML td width Attribute</h2> <table border="1" width="500"> <tr> <th>NAME</th> <th>AGE</th> <th>BRANCH</th> </tr> <tr> <td width="50%">BITTU</td> <td width="20%">22</td> <td width="30%">CSE</td> </tr> <tr> <td>RAKESH</td> <td>25</td> <td>EC</td> </tr> </table></body> </html> Output: Supported Browsers: The browser supported by HTML <td> width Attribute are listed below: Google Chrome Internet Explorer Firefox Safari Opera HTML is the foundation of webpages, is used for webpage development by structuring websites and web apps.You can learn HTML from the ground up by following this HTML Tutorial and HTML Examples. HTML-Attributes HTML Web Technologies HTML Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to update Node.js and NPM to next version ? REST API (Introduction) CSS to put icon inside an input element in a form Design a Tribute Page using HTML & CSS Types of CSS (Cascading Style Sheet) Installation of Node.js on Linux Difference between var, let and const keywords in JavaScript How to fetch data from an API in ReactJS ? Differences between Functional Components and Class Components in React Remove elements from a JavaScript Array
[ { "code": null, "e": 28, "s": 0, "text": "\n29 Jul, 2021" }, { "code": null, "e": 184, "s": 28, "text": "The HTML <td> width Attribute is used to specify the width of a table cell. If width attribute is not set then it takes default width according to content." }, { "code": null, "e": 192, "s": 184, "text": "Syntax:" }, { "code": null, "e": 216, "s": 192, "text": "<td width=\"pixels | %\">" }, { "code": null, "e": 234, "s": 216, "text": "Attribute Values:" }, { "code": null, "e": 289, "s": 234, "text": "pixels: It sets the width of table in terms of pixels." }, { "code": null, "e": 347, "s": 289, "text": "%: It sets the width of table in terms of percentage (%)." }, { "code": null, "e": 406, "s": 347, "text": "Note: The <td> width Attribute is not supported by HTML 5." }, { "code": null, "e": 415, "s": 406, "text": "Example:" }, { "code": "<!DOCTYPE html><html> <head> <title> HTML td width Attribute </title></head> <body> <h1>GeeksforGeeks</h1> <h2>HTML td width Attribute</h2> <table border=\"1\" width=\"500\"> <tr> <th>NAME</th> <th>AGE</th> <th>BRANCH</th> </tr> <tr> <td width=\"50%\">BITTU</td> <td width=\"20%\">22</td> <td width=\"30%\">CSE</td> </tr> <tr> <td>RAKESH</td> <td>25</td> <td>EC</td> </tr> </table></body> </html>", "e": 990, "s": 415, "text": null }, { "code": null, "e": 998, "s": 990, "text": "Output:" }, { "code": null, "e": 1087, "s": 998, "text": "Supported Browsers: The browser supported by HTML <td> width Attribute are listed below:" }, { "code": null, "e": 1101, "s": 1087, "text": "Google Chrome" }, { "code": null, "e": 1119, "s": 1101, "text": "Internet Explorer" }, { "code": null, "e": 1127, "s": 1119, "text": "Firefox" }, { "code": null, "e": 1134, "s": 1127, "text": "Safari" }, { "code": null, "e": 1140, "s": 1134, "text": "Opera" }, { "code": null, "e": 1334, "s": 1140, "text": "HTML is the foundation of webpages, is used for webpage development by structuring websites and web apps.You can learn HTML from the ground up by following this HTML Tutorial and HTML Examples." }, { "code": null, "e": 1350, "s": 1334, "text": "HTML-Attributes" }, { "code": null, "e": 1355, "s": 1350, "text": "HTML" }, { "code": null, "e": 1372, "s": 1355, "text": "Web Technologies" }, { "code": null, "e": 1377, "s": 1372, "text": "HTML" }, { "code": null, "e": 1475, "s": 1377, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 1523, "s": 1475, "text": "How to update Node.js and NPM to next version ?" }, { "code": null, "e": 1547, "s": 1523, "text": "REST API (Introduction)" }, { "code": null, "e": 1597, "s": 1547, "text": "CSS to put icon inside an input element in a form" }, { "code": null, "e": 1636, "s": 1597, "text": "Design a Tribute Page using HTML & CSS" }, { "code": null, "e": 1673, "s": 1636, "text": "Types of CSS (Cascading Style Sheet)" }, { "code": null, "e": 1706, "s": 1673, "text": "Installation of Node.js on Linux" }, { "code": null, "e": 1767, "s": 1706, "text": "Difference between var, let and const keywords in JavaScript" }, { "code": null, "e": 1810, "s": 1767, "text": "How to fetch data from an API in ReactJS ?" }, { "code": null, "e": 1882, "s": 1810, "text": "Differences between Functional Components and Class Components in React" } ]
Reloading modules in Python
27 Oct, 2016 reload() reloads a previously imported module. This is useful if you have edited the module source file using an external editor and want to try out the new version without leaving the Python interpreter. The return value is the module object. Note: The argument should be a module which has been successfully imported. Usage: For Python2.x reload(module) For above 2.x and <=Python3.3 import imp imp.reload(module) For >=Python3.4 import importlib importlib.reload(module) For more information, check out reload(). This article is contributed by Sri Sanketh Uppalapati. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Python Dictionary Different ways to create Pandas Dataframe Enumerate() in Python Read a file line by line in Python Python String | replace() How to Install PIP on Windows ? *args and **kwargs in Python Python Classes and Objects Iterate over a list in Python Convert integer to string in Python
[ { "code": null, "e": 52, "s": 24, "text": "\n27 Oct, 2016" }, { "code": null, "e": 296, "s": 52, "text": "reload() reloads a previously imported module. This is useful if you have edited the module source file using an external editor and want to try out the new version without leaving the Python interpreter. The return value is the module object." }, { "code": null, "e": 372, "s": 296, "text": "Note: The argument should be a module which has been successfully imported." }, { "code": null, "e": 379, "s": 372, "text": "Usage:" }, { "code": null, "e": 393, "s": 379, "text": "For Python2.x" }, { "code": null, "e": 409, "s": 393, "text": "reload(module)\n" }, { "code": null, "e": 439, "s": 409, "text": "For above 2.x and <=Python3.3" }, { "code": null, "e": 470, "s": 439, "text": "import imp\nimp.reload(module)\n" }, { "code": null, "e": 486, "s": 470, "text": "For >=Python3.4" }, { "code": null, "e": 529, "s": 486, "text": "import importlib\nimportlib.reload(module)\n" }, { "code": null, "e": 571, "s": 529, "text": "For more information, check out reload()." }, { "code": null, "e": 881, "s": 571, "text": "This article is contributed by Sri Sanketh Uppalapati. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks." }, { "code": null, "e": 1006, "s": 881, "text": "Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above." }, { "code": null, "e": 1013, "s": 1006, "text": "Python" }, { "code": null, "e": 1111, "s": 1013, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 1129, "s": 1111, "text": "Python Dictionary" }, { "code": null, "e": 1171, "s": 1129, "text": "Different ways to create Pandas Dataframe" }, { "code": null, "e": 1193, "s": 1171, "text": "Enumerate() in Python" }, { "code": null, "e": 1228, "s": 1193, "text": "Read a file line by line in Python" }, { "code": null, "e": 1254, "s": 1228, "text": "Python String | replace()" }, { "code": null, "e": 1286, "s": 1254, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 1315, "s": 1286, "text": "*args and **kwargs in Python" }, { "code": null, "e": 1342, "s": 1315, "text": "Python Classes and Objects" }, { "code": null, "e": 1372, "s": 1342, "text": "Iterate over a list in Python" } ]
SQL | Character Functions with Examples
21 Mar, 2018 Character functions accept character inputs and can return either characters or number values as output. SQL provides a number of different character datatypes which includes – CHAR, VARCHAR, VARCHAR2, LONG, RAW, and LONG RAW. The various datatypes are categorized into three different datatypes : VARCHAR2 – A variable-length character datatype whose data is converted by the RDBMS.CHAR – The fixed-length datatype.RAW – A variable-length datatype whose data is not converted by the RDBMS, but left in “raw” form. VARCHAR2 – A variable-length character datatype whose data is converted by the RDBMS. CHAR – The fixed-length datatype. RAW – A variable-length datatype whose data is not converted by the RDBMS, but left in “raw” form. Note : When a character function returns a character value, that value is always of type VARCHAR2 ( variable length ), with the following two exceptions: UPPER and LOWER. These functions convert to upper and to lower case, respectively, and return the CHAR values ( fixed length ) if the strings they are called on to convert are fixed-length CHAR arguments. Character Functions SQL provides a rich set of character functions that allow you to get information about strings and modify the contents of those strings in multiple ways. Character functions are of the following two types:1. Case-Manipulative Functions (LOWER, UPPER and INITCAP)2. Character-Manipulative Functions (CONCAT, LENGTH, SUBSTR, INSTR, LPAD, RPAD, TRIM and REPLACE) Case-Manipulative Functions LOWER : This function converts alpha character values to lowercase. LOWER will actually return a fixed-length string if the incoming string is fixed-length. LOWER will not change any characters in the string that are not letters, since case is irrelevant for numbers and special characters, such as the dollar sign ( $ ) or modulus ( % ).Syntax:LOWER(SQL course)Input1: SELECT LOWER('GEEKSFORGEEKS') FROM DUAL; Output1: geeksforgeeks Input2: SELECT LOWER('DATABASE@456') FROM DUAL; Output2: database@456UPPER : This function converts alpha character values to uppercase. Also UPPER function too, will actually return a fixed-length string if the incoming string is fixed-length. UPPER will not change any characters in the string that are not letters, since case is irrelevant for numbers and special characters, such as the dollar sign ( $ ) or modulus ( % ).Syntax:UPPER(SQL course)Input1: SELECT UPPER('geeksforgeeks') FROM DUAL; Output1: GEEKSFORGEEKS Input2: SELECT UPPER('dbms$508%7') FROM DUAL; Output2: DBMS$508%7INITCAP : This function converts alpha character values to uppercase for the first letter of each word and all others in lowercase. The words in the string is must be separated by either # or _ or space.Syntax:INITCAP(SQL course)Input1: SELECT INITCAP('geeksforgeeks is a computer science portal for geeks') FROM DUAL; Output1: Geeksforgeeks Is A Computer Science Portal For Geeks Input2: SELECT INITCAP('PRACTICE_CODING_FOR_EFFICIENCY') FROM DUAL; Output2: Practice_Coding_For_Efficiency LOWER : This function converts alpha character values to lowercase. LOWER will actually return a fixed-length string if the incoming string is fixed-length. LOWER will not change any characters in the string that are not letters, since case is irrelevant for numbers and special characters, such as the dollar sign ( $ ) or modulus ( % ).Syntax:LOWER(SQL course)Input1: SELECT LOWER('GEEKSFORGEEKS') FROM DUAL; Output1: geeksforgeeks Input2: SELECT LOWER('DATABASE@456') FROM DUAL; Output2: database@456 LOWER(SQL course) Input1: SELECT LOWER('GEEKSFORGEEKS') FROM DUAL; Output1: geeksforgeeks Input2: SELECT LOWER('DATABASE@456') FROM DUAL; Output2: database@456 UPPER : This function converts alpha character values to uppercase. Also UPPER function too, will actually return a fixed-length string if the incoming string is fixed-length. UPPER will not change any characters in the string that are not letters, since case is irrelevant for numbers and special characters, such as the dollar sign ( $ ) or modulus ( % ).Syntax:UPPER(SQL course)Input1: SELECT UPPER('geeksforgeeks') FROM DUAL; Output1: GEEKSFORGEEKS Input2: SELECT UPPER('dbms$508%7') FROM DUAL; Output2: DBMS$508%7 UPPER(SQL course) Input1: SELECT UPPER('geeksforgeeks') FROM DUAL; Output1: GEEKSFORGEEKS Input2: SELECT UPPER('dbms$508%7') FROM DUAL; Output2: DBMS$508%7 INITCAP : This function converts alpha character values to uppercase for the first letter of each word and all others in lowercase. The words in the string is must be separated by either # or _ or space.Syntax:INITCAP(SQL course)Input1: SELECT INITCAP('geeksforgeeks is a computer science portal for geeks') FROM DUAL; Output1: Geeksforgeeks Is A Computer Science Portal For Geeks Input2: SELECT INITCAP('PRACTICE_CODING_FOR_EFFICIENCY') FROM DUAL; Output2: Practice_Coding_For_Efficiency INITCAP(SQL course) Input1: SELECT INITCAP('geeksforgeeks is a computer science portal for geeks') FROM DUAL; Output1: Geeksforgeeks Is A Computer Science Portal For Geeks Input2: SELECT INITCAP('PRACTICE_CODING_FOR_EFFICIENCY') FROM DUAL; Output2: Practice_Coding_For_Efficiency Character-Manipulative Functions CONCAT : This function always appends ( concatenates ) string2 to the end of string1. If either of the string is NULL, CONCAT function returns the non-NULL argument. If both strings are NULL, CONCAT returns NULL.Syntax: CONCAT('String1', 'String2')Input1: SELECT CONCAT('computer' ,'science') FROM DUAL; Output1: computerscience Input2: SELECT CONCAT( NULL ,'Android') FROM DUAL; Output2: Android Input3: SELECT CONCAT( NULL ,NULL ) FROM DUAL; Output3: - LENGTH : This function returns the length of the input string. If the input string is NULL, then LENGTH function returns NULL and not Zero. Also, if the input string contains extra spaces at the start, or in between or at the end of the string, then the LENGTH function includes the extra spaces too and returns the complete length of the string.Syntax:LENGTH(Column|Expression)Input1: SELECT LENGTH('Learning Is Fun') FROM DUAL; Output1: 15 Input2: SELECT LENGTH(' Write an Interview Experience ') FROM DUAL; Output2: 34 Input3: SELECT LENGTH('') FROM DUAL; or SELECT LENGTH( NULL ) FROM DUAL; Output3: - SUBSTR : This function returns a portion of a string from a given start point to an end point. If a substring length is not given, then SUBSTR returns all the characters till the end of string (from the starting position specified).Syntax:SUBSTR('String',start-index,length_of_extracted_string)Input1: SELECT SUBSTR('Database Management System', 9) FROM DUAL; Output1: Management System Input2: SELECT SUBSTR('Database Management System', 9, 7) FROM DUAL; Output2: Manage INSTR : This function returns numeric position of a character or a string in a given string. Optionally, you can provide a position m to start searching, and the occurrence n of string. Also, if the starting position is not given, then it starts search from index 1, by default. If after searching in the string, no match is found then, INSTR function returns 0.Syntax: INSTR(Column|Expression, 'String', [,m], [n])Input: SELECT INSTR('Google apps are great applications','app',1,2) FROM DUAL; Output: 23 LPAD and RPAD : These functions return the strings padded to the left or right ( as per the use ) ; hence the “L” in “LPAD” and the “R” in “RPAD” ; to a specified length, and with a specified pad string. If the pad string is not specified, then the given string is padded on the left or right ( as per the use ) with spaces.Syntax:LPAD(Column|Expression, n, 'String') Syntax: RPAD(Column|Expression, n, 'String')LPAD Input1: SELECT LPAD('100',5,'*') FROM DUAL; LPAD Output1: **100 LPAD Input2: SELECT LPAD('hello', 21, 'geek') FROM DUAL; LPAD Output2: geekgeekgeekgeekhello RPAD Input1: SELECT RPAD('5000',7,'*') FROM DUAL; RPAD Output1: 5000*** RPAD Input1: SELECT RPAD('earn', 19, 'money') FROM DUAL; RPAD Output1: earnmoneymoneymoneyTRIM : This function trims the string input from the start or end (or both). If no string or char is specified to be trimmed from the string and there exists some extra space at start or end of the string, then those extra spaces are trimmed off.Syntax: TRIM(Leading|Trailing|Both, trim_character FROM trim_source)Input1: SELECT TRIM('G' FROM 'GEEKS') FROM DUAL; Output1: EEKS Input2: SELECT TRIM(' geeksforgeeks ') FROM DUAL; Output2:geeksforgeeksREPLACE : This function searches for a character string and, if found, replaces it with a given replacement string at all the occurrences of the string. REPLACE is useful for searching patterns of characters and then changing all instances of that pattern in a single function call.If a replacement string is not given, then REPLACE function removes all the occurrences of that character string in the input string. If neither a match string nor a replacement string is specified, then REPLACE returns NULL.Syntax: REPLACE(Text, search_string, replacement_string)Input1: SELECT REPLACE('DATA MANAGEMENT', 'DATA','DATABASE') FROM DUAL; Output1: DATABASE MANAGEMENT Input2: SELECT REPLACE('abcdeabcccabdddeeabcc', 'abc') FROM DUAL; Output2: deccabdddeec CONCAT : This function always appends ( concatenates ) string2 to the end of string1. If either of the string is NULL, CONCAT function returns the non-NULL argument. If both strings are NULL, CONCAT returns NULL.Syntax: CONCAT('String1', 'String2')Input1: SELECT CONCAT('computer' ,'science') FROM DUAL; Output1: computerscience Input2: SELECT CONCAT( NULL ,'Android') FROM DUAL; Output2: Android Input3: SELECT CONCAT( NULL ,NULL ) FROM DUAL; Output3: - CONCAT('String1', 'String2') Input1: SELECT CONCAT('computer' ,'science') FROM DUAL; Output1: computerscience Input2: SELECT CONCAT( NULL ,'Android') FROM DUAL; Output2: Android Input3: SELECT CONCAT( NULL ,NULL ) FROM DUAL; Output3: - LENGTH : This function returns the length of the input string. If the input string is NULL, then LENGTH function returns NULL and not Zero. Also, if the input string contains extra spaces at the start, or in between or at the end of the string, then the LENGTH function includes the extra spaces too and returns the complete length of the string.Syntax:LENGTH(Column|Expression)Input1: SELECT LENGTH('Learning Is Fun') FROM DUAL; Output1: 15 Input2: SELECT LENGTH(' Write an Interview Experience ') FROM DUAL; Output2: 34 Input3: SELECT LENGTH('') FROM DUAL; or SELECT LENGTH( NULL ) FROM DUAL; Output3: - LENGTH(Column|Expression) Input1: SELECT LENGTH('Learning Is Fun') FROM DUAL; Output1: 15 Input2: SELECT LENGTH(' Write an Interview Experience ') FROM DUAL; Output2: 34 Input3: SELECT LENGTH('') FROM DUAL; or SELECT LENGTH( NULL ) FROM DUAL; Output3: - SUBSTR : This function returns a portion of a string from a given start point to an end point. If a substring length is not given, then SUBSTR returns all the characters till the end of string (from the starting position specified).Syntax:SUBSTR('String',start-index,length_of_extracted_string)Input1: SELECT SUBSTR('Database Management System', 9) FROM DUAL; Output1: Management System Input2: SELECT SUBSTR('Database Management System', 9, 7) FROM DUAL; Output2: Manage SUBSTR('String',start-index,length_of_extracted_string) Input1: SELECT SUBSTR('Database Management System', 9) FROM DUAL; Output1: Management System Input2: SELECT SUBSTR('Database Management System', 9, 7) FROM DUAL; Output2: Manage INSTR : This function returns numeric position of a character or a string in a given string. Optionally, you can provide a position m to start searching, and the occurrence n of string. Also, if the starting position is not given, then it starts search from index 1, by default. If after searching in the string, no match is found then, INSTR function returns 0.Syntax: INSTR(Column|Expression, 'String', [,m], [n])Input: SELECT INSTR('Google apps are great applications','app',1,2) FROM DUAL; Output: 23 Syntax: INSTR(Column|Expression, 'String', [,m], [n]) Input: SELECT INSTR('Google apps are great applications','app',1,2) FROM DUAL; Output: 23 LPAD and RPAD : These functions return the strings padded to the left or right ( as per the use ) ; hence the “L” in “LPAD” and the “R” in “RPAD” ; to a specified length, and with a specified pad string. If the pad string is not specified, then the given string is padded on the left or right ( as per the use ) with spaces.Syntax:LPAD(Column|Expression, n, 'String') Syntax: RPAD(Column|Expression, n, 'String')LPAD Input1: SELECT LPAD('100',5,'*') FROM DUAL; LPAD Output1: **100 LPAD Input2: SELECT LPAD('hello', 21, 'geek') FROM DUAL; LPAD Output2: geekgeekgeekgeekhello RPAD Input1: SELECT RPAD('5000',7,'*') FROM DUAL; RPAD Output1: 5000*** RPAD Input1: SELECT RPAD('earn', 19, 'money') FROM DUAL; RPAD Output1: earnmoneymoneymoney LPAD(Column|Expression, n, 'String') Syntax: RPAD(Column|Expression, n, 'String') LPAD Input1: SELECT LPAD('100',5,'*') FROM DUAL; LPAD Output1: **100 LPAD Input2: SELECT LPAD('hello', 21, 'geek') FROM DUAL; LPAD Output2: geekgeekgeekgeekhello RPAD Input1: SELECT RPAD('5000',7,'*') FROM DUAL; RPAD Output1: 5000*** RPAD Input1: SELECT RPAD('earn', 19, 'money') FROM DUAL; RPAD Output1: earnmoneymoneymoney TRIM : This function trims the string input from the start or end (or both). If no string or char is specified to be trimmed from the string and there exists some extra space at start or end of the string, then those extra spaces are trimmed off.Syntax: TRIM(Leading|Trailing|Both, trim_character FROM trim_source)Input1: SELECT TRIM('G' FROM 'GEEKS') FROM DUAL; Output1: EEKS Input2: SELECT TRIM(' geeksforgeeks ') FROM DUAL; Output2:geeksforgeeks Syntax: TRIM(Leading|Trailing|Both, trim_character FROM trim_source)Input1: SELECT TRIM('G' FROM 'GEEKS') FROM DUAL; Output1: EEKS Input2: SELECT TRIM(' geeksforgeeks ') FROM DUAL; Output2:geeksforgeeks TRIM(Leading|Trailing|Both, trim_character FROM trim_source) Input1: SELECT TRIM('G' FROM 'GEEKS') FROM DUAL; Output1: EEKS Input2: SELECT TRIM(' geeksforgeeks ') FROM DUAL; Output2:geeksforgeeks REPLACE : This function searches for a character string and, if found, replaces it with a given replacement string at all the occurrences of the string. REPLACE is useful for searching patterns of characters and then changing all instances of that pattern in a single function call.If a replacement string is not given, then REPLACE function removes all the occurrences of that character string in the input string. If neither a match string nor a replacement string is specified, then REPLACE returns NULL.Syntax: REPLACE(Text, search_string, replacement_string)Input1: SELECT REPLACE('DATA MANAGEMENT', 'DATA','DATABASE') FROM DUAL; Output1: DATABASE MANAGEMENT Input2: SELECT REPLACE('abcdeabcccabdddeeabcc', 'abc') FROM DUAL; Output2: deccabdddeec Syntax: REPLACE(Text, search_string, replacement_string) Input1: SELECT REPLACE('DATA MANAGEMENT', 'DATA','DATABASE') FROM DUAL; Output1: DATABASE MANAGEMENT Input2: SELECT REPLACE('abcdeabcccabdddeeabcc', 'abc') FROM DUAL; Output2: deccabdddeec This article is contributed by Anshika Goyal. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. SQL-Functions SQL SQL Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 53, "s": 25, "text": "\n21 Mar, 2018" }, { "code": null, "e": 351, "s": 53, "text": "Character functions accept character inputs and can return either characters or number values as output. SQL provides a number of different character datatypes which includes – CHAR, VARCHAR, VARCHAR2, LONG, RAW, and LONG RAW. The various datatypes are categorized into three different datatypes :" }, { "code": null, "e": 568, "s": 351, "text": "VARCHAR2 – A variable-length character datatype whose data is converted by the RDBMS.CHAR – The fixed-length datatype.RAW – A variable-length datatype whose data is not converted by the RDBMS, but left in “raw” form." }, { "code": null, "e": 654, "s": 568, "text": "VARCHAR2 – A variable-length character datatype whose data is converted by the RDBMS." }, { "code": null, "e": 688, "s": 654, "text": "CHAR – The fixed-length datatype." }, { "code": null, "e": 787, "s": 688, "text": "RAW – A variable-length datatype whose data is not converted by the RDBMS, but left in “raw” form." }, { "code": null, "e": 1146, "s": 787, "text": "Note : When a character function returns a character value, that value is always of type VARCHAR2 ( variable length ), with the following two exceptions: UPPER and LOWER. These functions convert to upper and to lower case, respectively, and return the CHAR values ( fixed length ) if the strings they are called on to convert are fixed-length CHAR arguments." }, { "code": null, "e": 1166, "s": 1146, "text": "Character Functions" }, { "code": null, "e": 1526, "s": 1166, "text": "SQL provides a rich set of character functions that allow you to get information about strings and modify the contents of those strings in multiple ways. Character functions are of the following two types:1. Case-Manipulative Functions (LOWER, UPPER and INITCAP)2. Character-Manipulative Functions (CONCAT, LENGTH, SUBSTR, INSTR, LPAD, RPAD, TRIM and REPLACE)" }, { "code": null, "e": 1554, "s": 1526, "text": "Case-Manipulative Functions" }, { "code": null, "e": 3068, "s": 1554, "text": "LOWER : This function converts alpha character values to lowercase. LOWER will actually return a fixed-length string if the incoming string is fixed-length. LOWER will not change any characters in the string that are not letters, since case is irrelevant for numbers and special characters, such as the dollar sign ( $ ) or modulus ( % ).Syntax:LOWER(SQL course)Input1: SELECT LOWER('GEEKSFORGEEKS') FROM DUAL;\nOutput1: geeksforgeeks\n\nInput2: SELECT LOWER('DATABASE@456') FROM DUAL;\nOutput2: database@456UPPER : This function converts alpha character values to uppercase. Also UPPER function too, will actually return a fixed-length string if the incoming string is fixed-length. UPPER will not change any characters in the string that are not letters, since case is irrelevant for numbers and special characters, such as the dollar sign ( $ ) or modulus ( % ).Syntax:UPPER(SQL course)Input1: SELECT UPPER('geeksforgeeks') FROM DUAL;\nOutput1: GEEKSFORGEEKS\n\nInput2: SELECT UPPER('dbms$508%7') FROM DUAL;\nOutput2: DBMS$508%7INITCAP : This function converts alpha character values to uppercase for the first letter of each word and all others in lowercase. The words in the string is must be separated by either # or _ or space.Syntax:INITCAP(SQL course)Input1: SELECT INITCAP('geeksforgeeks is a computer science portal for geeks') FROM DUAL;\nOutput1: Geeksforgeeks Is A Computer Science Portal For Geeks \n\nInput2: SELECT INITCAP('PRACTICE_CODING_FOR_EFFICIENCY') FROM DUAL;\nOutput2: Practice_Coding_For_Efficiency" }, { "code": null, "e": 3573, "s": 3068, "text": "LOWER : This function converts alpha character values to lowercase. LOWER will actually return a fixed-length string if the incoming string is fixed-length. LOWER will not change any characters in the string that are not letters, since case is irrelevant for numbers and special characters, such as the dollar sign ( $ ) or modulus ( % ).Syntax:LOWER(SQL course)Input1: SELECT LOWER('GEEKSFORGEEKS') FROM DUAL;\nOutput1: geeksforgeeks\n\nInput2: SELECT LOWER('DATABASE@456') FROM DUAL;\nOutput2: database@456" }, { "code": null, "e": 3591, "s": 3573, "text": "LOWER(SQL course)" }, { "code": null, "e": 3734, "s": 3591, "text": "Input1: SELECT LOWER('GEEKSFORGEEKS') FROM DUAL;\nOutput1: geeksforgeeks\n\nInput2: SELECT LOWER('DATABASE@456') FROM DUAL;\nOutput2: database@456" }, { "code": null, "e": 4254, "s": 3734, "text": "UPPER : This function converts alpha character values to uppercase. Also UPPER function too, will actually return a fixed-length string if the incoming string is fixed-length. UPPER will not change any characters in the string that are not letters, since case is irrelevant for numbers and special characters, such as the dollar sign ( $ ) or modulus ( % ).Syntax:UPPER(SQL course)Input1: SELECT UPPER('geeksforgeeks') FROM DUAL;\nOutput1: GEEKSFORGEEKS\n\nInput2: SELECT UPPER('dbms$508%7') FROM DUAL;\nOutput2: DBMS$508%7" }, { "code": null, "e": 4272, "s": 4254, "text": "UPPER(SQL course)" }, { "code": null, "e": 4411, "s": 4272, "text": "Input1: SELECT UPPER('geeksforgeeks') FROM DUAL;\nOutput1: GEEKSFORGEEKS\n\nInput2: SELECT UPPER('dbms$508%7') FROM DUAL;\nOutput2: DBMS$508%7" }, { "code": null, "e": 4902, "s": 4411, "text": "INITCAP : This function converts alpha character values to uppercase for the first letter of each word and all others in lowercase. The words in the string is must be separated by either # or _ or space.Syntax:INITCAP(SQL course)Input1: SELECT INITCAP('geeksforgeeks is a computer science portal for geeks') FROM DUAL;\nOutput1: Geeksforgeeks Is A Computer Science Portal For Geeks \n\nInput2: SELECT INITCAP('PRACTICE_CODING_FOR_EFFICIENCY') FROM DUAL;\nOutput2: Practice_Coding_For_Efficiency" }, { "code": null, "e": 4922, "s": 4902, "text": "INITCAP(SQL course)" }, { "code": null, "e": 5184, "s": 4922, "text": "Input1: SELECT INITCAP('geeksforgeeks is a computer science portal for geeks') FROM DUAL;\nOutput1: Geeksforgeeks Is A Computer Science Portal For Geeks \n\nInput2: SELECT INITCAP('PRACTICE_CODING_FOR_EFFICIENCY') FROM DUAL;\nOutput2: Practice_Coding_For_Efficiency" }, { "code": null, "e": 5217, "s": 5184, "text": "Character-Manipulative Functions" }, { "code": null, "e": 9231, "s": 5217, "text": "CONCAT : This function always appends ( concatenates ) string2 to the end of string1. If either of the string is NULL, CONCAT function returns the non-NULL argument. If both strings are NULL, CONCAT returns NULL.Syntax: CONCAT('String1', 'String2')Input1: SELECT CONCAT('computer' ,'science') FROM DUAL;\nOutput1: computerscience\n\nInput2: SELECT CONCAT( NULL ,'Android') FROM DUAL;\nOutput2: Android \n\nInput3: SELECT CONCAT( NULL ,NULL ) FROM DUAL;\nOutput3: - LENGTH : This function returns the length of the input string. If the input string is NULL, then LENGTH function returns NULL and not Zero. Also, if the input string contains extra spaces at the start, or in between or at the end of the string, then the LENGTH function includes the extra spaces too and returns the complete length of the string.Syntax:LENGTH(Column|Expression)Input1: SELECT LENGTH('Learning Is Fun') FROM DUAL;\nOutput1: 15 \n\nInput2: SELECT LENGTH(' Write an Interview Experience ') FROM DUAL;\nOutput2: 34\n \nInput3: SELECT LENGTH('') FROM DUAL; or SELECT LENGTH( NULL ) FROM DUAL;\nOutput3: - SUBSTR : This function returns a portion of a string from a given start point to an end point. If a substring length is not given, then SUBSTR returns all the characters till the end of string (from the starting position specified).Syntax:SUBSTR('String',start-index,length_of_extracted_string)Input1: SELECT SUBSTR('Database Management System', 9) FROM DUAL;\nOutput1: Management System\n\nInput2: SELECT SUBSTR('Database Management System', 9, 7) FROM DUAL;\nOutput2: Manage INSTR : This function returns numeric position of a character or a string in a given string. Optionally, you can provide a position m to start searching, and the occurrence n of string. Also, if the starting position is not given, then it starts search from index 1, by default. If after searching in the string, no match is found then, INSTR function returns 0.Syntax: INSTR(Column|Expression, 'String', [,m], [n])Input: SELECT INSTR('Google apps are great applications','app',1,2) FROM DUAL;\nOutput: 23 LPAD and RPAD : These functions return the strings padded to the left or right ( as per the use ) ; hence the “L” in “LPAD” and the “R” in “RPAD” ; to a specified length, and with a specified pad string. If the pad string is not specified, then the given string is padded on the left or right ( as per the use ) with spaces.Syntax:LPAD(Column|Expression, n, 'String')\nSyntax: RPAD(Column|Expression, n, 'String')LPAD Input1: SELECT LPAD('100',5,'*') FROM DUAL;\nLPAD Output1: **100\n\nLPAD Input2: SELECT LPAD('hello', 21, 'geek') FROM DUAL;\nLPAD Output2: geekgeekgeekgeekhello\n\nRPAD Input1: SELECT RPAD('5000',7,'*') FROM DUAL;\nRPAD Output1: 5000*** \n\nRPAD Input1: SELECT RPAD('earn', 19, 'money') FROM DUAL;\nRPAD Output1: earnmoneymoneymoneyTRIM : This function trims the string input from the start or end (or both). If no string or char is specified to be trimmed from the string and there exists some extra space at start or end of the string, then those extra spaces are trimmed off.Syntax: TRIM(Leading|Trailing|Both, trim_character FROM trim_source)Input1: SELECT TRIM('G' FROM 'GEEKS') FROM DUAL;\nOutput1: EEKS\n\nInput2: SELECT TRIM(' geeksforgeeks ') FROM DUAL; \nOutput2:geeksforgeeksREPLACE : This function searches for a character string and, if found, replaces it with a given replacement string at all the occurrences of the string. REPLACE is useful for searching patterns of characters and then changing all instances of that pattern in a single function call.If a replacement string is not given, then REPLACE function removes all the occurrences of that character string in the input string. If neither a match string nor a replacement string is specified, then REPLACE returns NULL.Syntax: REPLACE(Text, search_string, replacement_string)Input1: SELECT REPLACE('DATA MANAGEMENT', 'DATA','DATABASE') FROM DUAL;\nOutput1: DATABASE MANAGEMENT \n\nInput2: SELECT REPLACE('abcdeabcccabdddeeabcc', 'abc') FROM DUAL; \nOutput2: deccabdddeec" }, { "code": null, "e": 9690, "s": 9231, "text": "CONCAT : This function always appends ( concatenates ) string2 to the end of string1. If either of the string is NULL, CONCAT function returns the non-NULL argument. If both strings are NULL, CONCAT returns NULL.Syntax: CONCAT('String1', 'String2')Input1: SELECT CONCAT('computer' ,'science') FROM DUAL;\nOutput1: computerscience\n\nInput2: SELECT CONCAT( NULL ,'Android') FROM DUAL;\nOutput2: Android \n\nInput3: SELECT CONCAT( NULL ,NULL ) FROM DUAL;\nOutput3: - " }, { "code": null, "e": 9720, "s": 9690, "text": " CONCAT('String1', 'String2')" }, { "code": null, "e": 9931, "s": 9720, "text": "Input1: SELECT CONCAT('computer' ,'science') FROM DUAL;\nOutput1: computerscience\n\nInput2: SELECT CONCAT( NULL ,'Android') FROM DUAL;\nOutput2: Android \n\nInput3: SELECT CONCAT( NULL ,NULL ) FROM DUAL;\nOutput3: - " }, { "code": null, "e": 10545, "s": 9931, "text": "LENGTH : This function returns the length of the input string. If the input string is NULL, then LENGTH function returns NULL and not Zero. Also, if the input string contains extra spaces at the start, or in between or at the end of the string, then the LENGTH function includes the extra spaces too and returns the complete length of the string.Syntax:LENGTH(Column|Expression)Input1: SELECT LENGTH('Learning Is Fun') FROM DUAL;\nOutput1: 15 \n\nInput2: SELECT LENGTH(' Write an Interview Experience ') FROM DUAL;\nOutput2: 34\n \nInput3: SELECT LENGTH('') FROM DUAL; or SELECT LENGTH( NULL ) FROM DUAL;\nOutput3: - " }, { "code": null, "e": 10571, "s": 10545, "text": "LENGTH(Column|Expression)" }, { "code": null, "e": 10807, "s": 10571, "text": "Input1: SELECT LENGTH('Learning Is Fun') FROM DUAL;\nOutput1: 15 \n\nInput2: SELECT LENGTH(' Write an Interview Experience ') FROM DUAL;\nOutput2: 34\n \nInput3: SELECT LENGTH('') FROM DUAL; or SELECT LENGTH( NULL ) FROM DUAL;\nOutput3: - " }, { "code": null, "e": 11281, "s": 10807, "text": "SUBSTR : This function returns a portion of a string from a given start point to an end point. If a substring length is not given, then SUBSTR returns all the characters till the end of string (from the starting position specified).Syntax:SUBSTR('String',start-index,length_of_extracted_string)Input1: SELECT SUBSTR('Database Management System', 9) FROM DUAL;\nOutput1: Management System\n\nInput2: SELECT SUBSTR('Database Management System', 9, 7) FROM DUAL;\nOutput2: Manage " }, { "code": null, "e": 11337, "s": 11281, "text": "SUBSTR('String',start-index,length_of_extracted_string)" }, { "code": null, "e": 11517, "s": 11337, "text": "Input1: SELECT SUBSTR('Database Management System', 9) FROM DUAL;\nOutput1: Management System\n\nInput2: SELECT SUBSTR('Database Management System', 9, 7) FROM DUAL;\nOutput2: Manage " }, { "code": null, "e": 12023, "s": 11517, "text": "INSTR : This function returns numeric position of a character or a string in a given string. Optionally, you can provide a position m to start searching, and the occurrence n of string. Also, if the starting position is not given, then it starts search from index 1, by default. If after searching in the string, no match is found then, INSTR function returns 0.Syntax: INSTR(Column|Expression, 'String', [,m], [n])Input: SELECT INSTR('Google apps are great applications','app',1,2) FROM DUAL;\nOutput: 23 " }, { "code": null, "e": 12077, "s": 12023, "text": "Syntax: INSTR(Column|Expression, 'String', [,m], [n])" }, { "code": null, "e": 12168, "s": 12077, "text": "Input: SELECT INSTR('Google apps are great applications','app',1,2) FROM DUAL;\nOutput: 23 " }, { "code": null, "e": 12909, "s": 12168, "text": "LPAD and RPAD : These functions return the strings padded to the left or right ( as per the use ) ; hence the “L” in “LPAD” and the “R” in “RPAD” ; to a specified length, and with a specified pad string. If the pad string is not specified, then the given string is padded on the left or right ( as per the use ) with spaces.Syntax:LPAD(Column|Expression, n, 'String')\nSyntax: RPAD(Column|Expression, n, 'String')LPAD Input1: SELECT LPAD('100',5,'*') FROM DUAL;\nLPAD Output1: **100\n\nLPAD Input2: SELECT LPAD('hello', 21, 'geek') FROM DUAL;\nLPAD Output2: geekgeekgeekgeekhello\n\nRPAD Input1: SELECT RPAD('5000',7,'*') FROM DUAL;\nRPAD Output1: 5000*** \n\nRPAD Input1: SELECT RPAD('earn', 19, 'money') FROM DUAL;\nRPAD Output1: earnmoneymoneymoney" }, { "code": null, "e": 12991, "s": 12909, "text": "LPAD(Column|Expression, n, 'String')\nSyntax: RPAD(Column|Expression, n, 'String')" }, { "code": null, "e": 13320, "s": 12991, "text": "LPAD Input1: SELECT LPAD('100',5,'*') FROM DUAL;\nLPAD Output1: **100\n\nLPAD Input2: SELECT LPAD('hello', 21, 'geek') FROM DUAL;\nLPAD Output2: geekgeekgeekgeekhello\n\nRPAD Input1: SELECT RPAD('5000',7,'*') FROM DUAL;\nRPAD Output1: 5000*** \n\nRPAD Input1: SELECT RPAD('earn', 19, 'money') FROM DUAL;\nRPAD Output1: earnmoneymoneymoney" }, { "code": null, "e": 13780, "s": 13320, "text": "TRIM : This function trims the string input from the start or end (or both). If no string or char is specified to be trimmed from the string and there exists some extra space at start or end of the string, then those extra spaces are trimmed off.Syntax: TRIM(Leading|Trailing|Both, trim_character FROM trim_source)Input1: SELECT TRIM('G' FROM 'GEEKS') FROM DUAL;\nOutput1: EEKS\n\nInput2: SELECT TRIM(' geeksforgeeks ') FROM DUAL; \nOutput2:geeksforgeeks" }, { "code": null, "e": 13994, "s": 13780, "text": "Syntax: TRIM(Leading|Trailing|Both, trim_character FROM trim_source)Input1: SELECT TRIM('G' FROM 'GEEKS') FROM DUAL;\nOutput1: EEKS\n\nInput2: SELECT TRIM(' geeksforgeeks ') FROM DUAL; \nOutput2:geeksforgeeks" }, { "code": null, "e": 14055, "s": 13994, "text": "TRIM(Leading|Trailing|Both, trim_character FROM trim_source)" }, { "code": null, "e": 14201, "s": 14055, "text": "Input1: SELECT TRIM('G' FROM 'GEEKS') FROM DUAL;\nOutput1: EEKS\n\nInput2: SELECT TRIM(' geeksforgeeks ') FROM DUAL; \nOutput2:geeksforgeeks" }, { "code": null, "e": 14967, "s": 14201, "text": "REPLACE : This function searches for a character string and, if found, replaces it with a given replacement string at all the occurrences of the string. REPLACE is useful for searching patterns of characters and then changing all instances of that pattern in a single function call.If a replacement string is not given, then REPLACE function removes all the occurrences of that character string in the input string. If neither a match string nor a replacement string is specified, then REPLACE returns NULL.Syntax: REPLACE(Text, search_string, replacement_string)Input1: SELECT REPLACE('DATA MANAGEMENT', 'DATA','DATABASE') FROM DUAL;\nOutput1: DATABASE MANAGEMENT \n\nInput2: SELECT REPLACE('abcdeabcccabdddeeabcc', 'abc') FROM DUAL; \nOutput2: deccabdddeec" }, { "code": null, "e": 14975, "s": 14967, "text": "Syntax:" }, { "code": null, "e": 15025, "s": 14975, "text": " REPLACE(Text, search_string, replacement_string)" }, { "code": null, "e": 15228, "s": 15025, "text": "Input1: SELECT REPLACE('DATA MANAGEMENT', 'DATA','DATABASE') FROM DUAL;\nOutput1: DATABASE MANAGEMENT \n\nInput2: SELECT REPLACE('abcdeabcccabdddeeabcc', 'abc') FROM DUAL; \nOutput2: deccabdddeec" }, { "code": null, "e": 15529, "s": 15228, "text": "This article is contributed by Anshika Goyal. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks." }, { "code": null, "e": 15654, "s": 15529, "text": "Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above." }, { "code": null, "e": 15668, "s": 15654, "text": "SQL-Functions" }, { "code": null, "e": 15672, "s": 15668, "text": "SQL" }, { "code": null, "e": 15676, "s": 15672, "text": "SQL" } ]
PySpark – Read CSV file into DataFrame
25 Oct, 2021 In this article, we are going to see how to read CSV files into Dataframe. For this, we will use Pyspark and Python. Files Used: authors book_author books Here we are going to read a single CSV into dataframe using spark.read.csv and then create dataframe with this data using .toPandas(). Python3 from pyspark.sql import SparkSession spark = SparkSession.builder.appName( 'Read CSV File into DataFrame').getOrCreate() authors = spark.read.csv('/content/authors.csv', sep=',', inferSchema=True, header=True) df = authors.toPandas()df.head() Output: Here, we passed our CSV file authors.csv. Second, we passed the delimiter used in the CSV file. Here the delimiter is comma ‘,‘. Next, we set the inferSchema attribute as True, this will go through the CSV file and automatically adapt its schema into PySpark Dataframe. Then, we converted the PySpark Dataframe to Pandas Dataframe df using toPandas() method. To read multiple CSV files, we will pass a python list of paths of the CSV files as string type. Python3 from pyspark.sql import SparkSession spark = SparkSession.builder.appName('Read Multiple CSV Files').getOrCreate() path = ['/content/authors.csv', '/content/book_author.csv'] files = spark.read.csv(path, sep=',', inferSchema=True, header=True) df1 = files.toPandas()display(df1.head())display(df1.tail()) Output: Here, we imported authors.csv and book_author.csv present in the same current working directory having delimiter as comma ‘,‘ and the first row as Header. To read all CSV files in the directory, we will use * for considering each file in the directory. Python3 from pyspark.sql import SparkSession spark = SparkSession.builder.appName( 'Read All CSV Files in Directory').getOrCreate() file2 = spark.read.csv('/content/*.csv', sep=',', inferSchema=True, header=True) df1 = file2.toPandas()display(df1.head())display(df1.tail()) Output: This will read all the CSV files present in the current working directory, having delimiter as comma ‘,‘ and the first row as Header. rahuls66 Blogathon-2021 Picked Python-Pyspark Blogathon Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to Import JSON Data into SQL Server? SQL Query to Convert Datetime to Date Python program to convert XML to Dictionary Scrape LinkedIn Using Selenium And Beautiful Soup in Python How to toggle password visibility in forms using Bootstrap-icons ? Read JSON file using Python Adding new column to existing DataFrame in Pandas Python map() function How to get column names in Pandas dataframe
[ { "code": null, "e": 52, "s": 24, "text": "\n25 Oct, 2021" }, { "code": null, "e": 169, "s": 52, "text": "In this article, we are going to see how to read CSV files into Dataframe. For this, we will use Pyspark and Python." }, { "code": null, "e": 181, "s": 169, "text": "Files Used:" }, { "code": null, "e": 189, "s": 181, "text": "authors" }, { "code": null, "e": 201, "s": 189, "text": "book_author" }, { "code": null, "e": 207, "s": 201, "text": "books" }, { "code": null, "e": 342, "s": 207, "text": "Here we are going to read a single CSV into dataframe using spark.read.csv and then create dataframe with this data using .toPandas()." }, { "code": null, "e": 350, "s": 342, "text": "Python3" }, { "code": "from pyspark.sql import SparkSession spark = SparkSession.builder.appName( 'Read CSV File into DataFrame').getOrCreate() authors = spark.read.csv('/content/authors.csv', sep=',', inferSchema=True, header=True) df = authors.toPandas()df.head()", "e": 620, "s": 350, "text": null }, { "code": null, "e": 628, "s": 620, "text": "Output:" }, { "code": null, "e": 987, "s": 628, "text": "Here, we passed our CSV file authors.csv. Second, we passed the delimiter used in the CSV file. Here the delimiter is comma ‘,‘. Next, we set the inferSchema attribute as True, this will go through the CSV file and automatically adapt its schema into PySpark Dataframe. Then, we converted the PySpark Dataframe to Pandas Dataframe df using toPandas() method." }, { "code": null, "e": 1085, "s": 987, "text": "To read multiple CSV files, we will pass a python list of paths of the CSV files as string type. " }, { "code": null, "e": 1093, "s": 1085, "text": "Python3" }, { "code": "from pyspark.sql import SparkSession spark = SparkSession.builder.appName('Read Multiple CSV Files').getOrCreate() path = ['/content/authors.csv', '/content/book_author.csv'] files = spark.read.csv(path, sep=',', inferSchema=True, header=True) df1 = files.toPandas()display(df1.head())display(df1.tail())", "e": 1427, "s": 1093, "text": null }, { "code": null, "e": 1435, "s": 1427, "text": "Output:" }, { "code": null, "e": 1590, "s": 1435, "text": "Here, we imported authors.csv and book_author.csv present in the same current working directory having delimiter as comma ‘,‘ and the first row as Header." }, { "code": null, "e": 1688, "s": 1590, "text": "To read all CSV files in the directory, we will use * for considering each file in the directory." }, { "code": null, "e": 1696, "s": 1688, "text": "Python3" }, { "code": "from pyspark.sql import SparkSession spark = SparkSession.builder.appName( 'Read All CSV Files in Directory').getOrCreate() file2 = spark.read.csv('/content/*.csv', sep=',', inferSchema=True, header=True) df1 = file2.toPandas()display(df1.head())display(df1.tail())", "e": 1984, "s": 1696, "text": null }, { "code": null, "e": 1992, "s": 1984, "text": "Output:" }, { "code": null, "e": 2126, "s": 1992, "text": "This will read all the CSV files present in the current working directory, having delimiter as comma ‘,‘ and the first row as Header." }, { "code": null, "e": 2135, "s": 2126, "text": "rahuls66" }, { "code": null, "e": 2150, "s": 2135, "text": "Blogathon-2021" }, { "code": null, "e": 2157, "s": 2150, "text": "Picked" }, { "code": null, "e": 2172, "s": 2157, "text": "Python-Pyspark" }, { "code": null, "e": 2182, "s": 2172, "text": "Blogathon" }, { "code": null, "e": 2189, "s": 2182, "text": "Python" }, { "code": null, "e": 2287, "s": 2189, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 2328, "s": 2287, "text": "How to Import JSON Data into SQL Server?" }, { "code": null, "e": 2366, "s": 2328, "text": "SQL Query to Convert Datetime to Date" }, { "code": null, "e": 2410, "s": 2366, "text": "Python program to convert XML to Dictionary" }, { "code": null, "e": 2470, "s": 2410, "text": "Scrape LinkedIn Using Selenium And Beautiful Soup in Python" }, { "code": null, "e": 2537, "s": 2470, "text": "How to toggle password visibility in forms using Bootstrap-icons ?" }, { "code": null, "e": 2565, "s": 2537, "text": "Read JSON file using Python" }, { "code": null, "e": 2615, "s": 2565, "text": "Adding new column to existing DataFrame in Pandas" }, { "code": null, "e": 2637, "s": 2615, "text": "Python map() function" } ]
Image Processing without OpenCV | Python
23 Jun, 2021 We know OpenCV is widely used to operate on images and has a wide spectrum of functions to do so. But what if we want to process the image files without using any external library like OpenCV. Let’s see how can we do this. Nearest Neighbour interpolation is the simplest way of interpolation. This method simply determines the “nearest” neighboring pixel and assumes the intensity value of it.Consider a small image which is ‘w’ pixels wide by ‘h’ pixels high, which we want to re-size to ‘p’ pixels wide by ‘q’ pixels high, assuming that p>m and q>n. Now, we need two scaling constants: scale_x = p/w scale_y = q/h Now, we simply loop through all the pixels in the output image, addressing the source pixels to copy from by scaling our control variables by scale_x and scale_y, and rounding the resulting scaled index values.Pictorial representation : Image of 3X3 pixel (total 9 pixels), now if we want to increase the size of image up to 6X6 then, according to nearest neighboring algorithm 6/3 (i.e 2) pixels should have the same RGB value as that of the pixel in original Image. Program for scaling an Image: Python3 # using matplotlib and numpy import matplotlib.image as imgimport numpy as npy # provide the location of image for readingm = img.imread("taj.png"); # determining the length of original imagew, h = m.shape[:2]; # xNew and yNew are new width and# height of image requiredafter scalingxNew = int(w * 1 / 2);yNew = int(h * 1 / 2); # calculating the scaling factor# work for more than 2 pixelxScale = xNew/(w-1);yScale = yNew/(h-1); # using numpy taking a matrix of xNew# width and yNew height with# 4 attribute [alpha, B, G, B] valuesnewImage = npy.zeros([xNew, yNew, 4]); for i in range(xNew-1): for j in range(yNew-1): newImage[i + 1, j + 1]= m[1 + int(i / xScale), 1 + int(j / yScale)] # Save the image after scalingimg.imsave('scaled.png', newImage); Output: Using the average value method, this method highlights the intensity of the pixel rather than showing what RGB values it consists. When we calculate the average value of RGB and assign It to RGB value of pixel, Since the RGB value of the pixel is same, it will not be able to create any color since all the colors are formed due different ratio of RGB value since in this case ratio will be 1:1:1. Hence Image then formed will look as gray Image.Pictorial representation : Program for Gray scaling an Image : Python3 # using numpyimport numpy as npy # using matplotlibimport matplotlib.image as img # using statistics to import mean# for mean calculationfrom statistics import mean m = img.imread("taj.png") # determining width and height of original imagew, h = m.shape[:2] # new Image dimension with 4 attribute in each pixelnewImage = npy.zeros([w, h, 4])print( w )print( h ) for i in range(w): for j in range(h): # ratio of RGB will be between 0 and 1 lst = [float(m[i][j][0]), float(m[i][j][1]), float(m[i][j][2])] avg = float(mean(lst)) newImage[i][j][0] = avg newImage[i][j][1] = avg newImage[i][j][2] = avg newImage[i][j][3] = 1 # alpha value to be 1 # Save image using imsaveimg.imsave('grayedImage.png', newImage) Output: Cropping is basically removing the unwanted pixel. This can be done by taking required pixel in a different Image grid whose size is as required after cropping. Consider an Image of size 10 X 10 pixel and if we require to crop only the center of image with 4 X 4 pixel then we need to collect the pixel values from (10-4)/2 starting from (3, 3) up to 4 pixel in x direction and 4 pixel in y direction.Pictorial representation : Program for cropping an Image : Python3 # using matplotlib and numpyimport matplotlib.image as imgimport numpy as npy # reading image in variable mm = img.imread("taj.png") # determining dimension of image width(w) height(h)w, h = m.shape[:2] # required image size after croppingxNew = int(w * 1 / 4)yNew = int(h * 1 / 4)newImage = npy.zeros([xNew, yNew, 4]) # print width height of original imageprint(w)print(h) for i in range(1, xNew): for j in range(1, yNew): # cropping start from 100, 100 pixel of original image newImage[i, j]= m[100 + i, 100 + j] # save imageimg.imsave('cropped.png', newImage) Output: ruhelaa48 Image-Processing OpenCV Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Python Dictionary Different ways to create Pandas Dataframe Enumerate() in Python Read a file line by line in Python Python String | replace() How to Install PIP on Windows ? *args and **kwargs in Python Python Classes and Objects Iterate over a list in Python Python OOPs Concepts
[ { "code": null, "e": 54, "s": 26, "text": "\n23 Jun, 2021" }, { "code": null, "e": 279, "s": 54, "text": "We know OpenCV is widely used to operate on images and has a wide spectrum of functions to do so. But what if we want to process the image files without using any external library like OpenCV. Let’s see how can we do this. " }, { "code": null, "e": 645, "s": 279, "text": "Nearest Neighbour interpolation is the simplest way of interpolation. This method simply determines the “nearest” neighboring pixel and assumes the intensity value of it.Consider a small image which is ‘w’ pixels wide by ‘h’ pixels high, which we want to re-size to ‘p’ pixels wide by ‘q’ pixels high, assuming that p>m and q>n. Now, we need two scaling constants: " }, { "code": null, "e": 673, "s": 645, "text": "scale_x = p/w\nscale_y = q/h" }, { "code": null, "e": 1142, "s": 673, "text": "Now, we simply loop through all the pixels in the output image, addressing the source pixels to copy from by scaling our control variables by scale_x and scale_y, and rounding the resulting scaled index values.Pictorial representation : Image of 3X3 pixel (total 9 pixels), now if we want to increase the size of image up to 6X6 then, according to nearest neighboring algorithm 6/3 (i.e 2) pixels should have the same RGB value as that of the pixel in original Image. " }, { "code": null, "e": 1174, "s": 1142, "text": "Program for scaling an Image: " }, { "code": null, "e": 1182, "s": 1174, "text": "Python3" }, { "code": "# using matplotlib and numpy import matplotlib.image as imgimport numpy as npy # provide the location of image for readingm = img.imread(\"taj.png\"); # determining the length of original imagew, h = m.shape[:2]; # xNew and yNew are new width and# height of image requiredafter scalingxNew = int(w * 1 / 2);yNew = int(h * 1 / 2); # calculating the scaling factor# work for more than 2 pixelxScale = xNew/(w-1);yScale = yNew/(h-1); # using numpy taking a matrix of xNew# width and yNew height with# 4 attribute [alpha, B, G, B] valuesnewImage = npy.zeros([xNew, yNew, 4]); for i in range(xNew-1): for j in range(yNew-1): newImage[i + 1, j + 1]= m[1 + int(i / xScale), 1 + int(j / yScale)] # Save the image after scalingimg.imsave('scaled.png', newImage);", "e": 1974, "s": 1182, "text": null }, { "code": null, "e": 1984, "s": 1974, "text": "Output: " }, { "code": null, "e": 2463, "s": 1988, "text": "Using the average value method, this method highlights the intensity of the pixel rather than showing what RGB values it consists. When we calculate the average value of RGB and assign It to RGB value of pixel, Since the RGB value of the pixel is same, it will not be able to create any color since all the colors are formed due different ratio of RGB value since in this case ratio will be 1:1:1. Hence Image then formed will look as gray Image.Pictorial representation : " }, { "code": null, "e": 2501, "s": 2463, "text": "Program for Gray scaling an Image : " }, { "code": null, "e": 2509, "s": 2501, "text": "Python3" }, { "code": "# using numpyimport numpy as npy # using matplotlibimport matplotlib.image as img # using statistics to import mean# for mean calculationfrom statistics import mean m = img.imread(\"taj.png\") # determining width and height of original imagew, h = m.shape[:2] # new Image dimension with 4 attribute in each pixelnewImage = npy.zeros([w, h, 4])print( w )print( h ) for i in range(w): for j in range(h): # ratio of RGB will be between 0 and 1 lst = [float(m[i][j][0]), float(m[i][j][1]), float(m[i][j][2])] avg = float(mean(lst)) newImage[i][j][0] = avg newImage[i][j][1] = avg newImage[i][j][2] = avg newImage[i][j][3] = 1 # alpha value to be 1 # Save image using imsaveimg.imsave('grayedImage.png', newImage)", "e": 3253, "s": 2509, "text": null }, { "code": null, "e": 3263, "s": 3253, "text": "Output: " }, { "code": null, "e": 3697, "s": 3267, "text": "Cropping is basically removing the unwanted pixel. This can be done by taking required pixel in a different Image grid whose size is as required after cropping. Consider an Image of size 10 X 10 pixel and if we require to crop only the center of image with 4 X 4 pixel then we need to collect the pixel values from (10-4)/2 starting from (3, 3) up to 4 pixel in x direction and 4 pixel in y direction.Pictorial representation : " }, { "code": null, "e": 3731, "s": 3697, "text": "Program for cropping an Image : " }, { "code": null, "e": 3739, "s": 3731, "text": "Python3" }, { "code": "# using matplotlib and numpyimport matplotlib.image as imgimport numpy as npy # reading image in variable mm = img.imread(\"taj.png\") # determining dimension of image width(w) height(h)w, h = m.shape[:2] # required image size after croppingxNew = int(w * 1 / 4)yNew = int(h * 1 / 4)newImage = npy.zeros([xNew, yNew, 4]) # print width height of original imageprint(w)print(h) for i in range(1, xNew): for j in range(1, yNew): # cropping start from 100, 100 pixel of original image newImage[i, j]= m[100 + i, 100 + j] # save imageimg.imsave('cropped.png', newImage)", "e": 4318, "s": 3739, "text": null }, { "code": null, "e": 4328, "s": 4318, "text": "Output: " }, { "code": null, "e": 4343, "s": 4333, "text": "ruhelaa48" }, { "code": null, "e": 4360, "s": 4343, "text": "Image-Processing" }, { "code": null, "e": 4367, "s": 4360, "text": "OpenCV" }, { "code": null, "e": 4374, "s": 4367, "text": "Python" }, { "code": null, "e": 4472, "s": 4374, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 4490, "s": 4472, "text": "Python Dictionary" }, { "code": null, "e": 4532, "s": 4490, "text": "Different ways to create Pandas Dataframe" }, { "code": null, "e": 4554, "s": 4532, "text": "Enumerate() in Python" }, { "code": null, "e": 4589, "s": 4554, "text": "Read a file line by line in Python" }, { "code": null, "e": 4615, "s": 4589, "text": "Python String | replace()" }, { "code": null, "e": 4647, "s": 4615, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 4676, "s": 4647, "text": "*args and **kwargs in Python" }, { "code": null, "e": 4703, "s": 4676, "text": "Python Classes and Objects" }, { "code": null, "e": 4733, "s": 4703, "text": "Iterate over a list in Python" } ]
Minimum Bitwise OR operations to make any two array elements equal
18 Nov, 2021 Given an array arr[] of integers and an integer K, we can perform the Bitwise OR operation between any array element and K any number of times. The task is to print the minimum number of such operations required to make any two elements of the array equal. If it is not possible to make any two elements of the array equal after performing the above-mentioned operation then print -1.Examples: Input: arr[] = {1, 9, 4, 3}, K = 3 Output: 1 We can OR a[0] with x, which makes it 3 which is equal to a[3]Input : arr[] = {13, 26, 21, 15}, K = 13 Output : -1 Approach: The key observation is that if it is possible to make the desired array then the answer will be either 0, 1 or 2. It will never exceed 2. Because, if (x | k) = y then, no matter how many times you perform (y | k) it’ll always give y as the result. The answer will be 0, if there are already equal elements in the array. For the answer to be 1, we will create a new array b[] which holds b[i] = (a[i] | K), Now, for each a[i] we will check if there is any index j such that i != j and a[i] = b[j]. If yes, then the answer will be 1. For the answer to be 2, we will check for an index i in the new array b[], if there is any index j such that i != j and b[i] = b[j]. If yes, then the answer will be 2. If any of the above conditions is not satisfied then the answer will be -1. Below is the implementation of the above approach: C++ Java Python3 C# Javascript // C++ implementation of the approach#include <bits/stdc++.h>using namespace std; // Function to return the count of// minimum operations requiredint minOperations(int a[], int n, int K){ unordered_map<int, bool> map; for (int i = 0; i < n; i++) { // Check if the initial array // already contains an equal pair if (map[a[i]]) return 0; map[a[i]] = true; } // Create new array with OR operations int b[n]; for (int i = 0; i < n; i++) b[i] = a[i] | K; // Clear the map map.clear(); // Check if the solution // is a single operation for (int i = 0; i < n; i++) { // If Bitwise OR operation between // 'k' and a[i] gives // a number other than a[i] if (a[i] != b[i]) map[b[i]] = true; } // Check if any of the a[i] // gets equal to any other element // of the array after the operation for (int i = 0; i < n; i++) // Single operation // will be enough if (map[a[i]]) return 1; // Clear the map map.clear(); // Check if the solution // is two operations for (int i = 0; i < n; i++) { // Check if the array 'b' // contains duplicates if (map[b[i]]) return 2; map[b[i]] = true; } // Otherwise it is impossible to // create such an array with // Bitwise OR operations return -1;} // Driver codeint main(){ int K = 3; int a[] = { 1, 9, 4, 3 }; int n = sizeof(a) / sizeof(a[0]); // Function call to compute the result cout << minOperations(a, n, K); return 0;} // Java implementation of the approachimport java.util.HashMap; class GFG{ // Function to return the count of // minimum operations required public static int minOperations(int[] a, int n, int K) { HashMap<Integer, Boolean> map = new HashMap<>(); for (int i = 0; i < n; i++) { // Check if the initial array // already contains an equal pair if (map.containsKey(a[i])) return 0; map.put(a[i], true); } // Create new array with OR operations int[] b = new int[n]; for (int i = 0; i < n; i++) b[i] = a[i] | K; // Clear the map map.clear(); // Check if the solution // is a single operation for (int i = 0; i < n; i++) { // If Bitwise OR operation between // 'k' and a[i] gives // a number other than a[i] if (a[i] != b[i]) map.put(b[i], true); } // Check if any of the a[i] // gets equal to any other element // of the array after the operation for (int i = 0; i < n; i++) { // Single operation // will be enough if (map.containsKey(a[i])) return 1; } // Clear the map map.clear(); // Check if the solution // is two operations for (int i = 0; i < n; i++) { // Check if the array 'b' // contains duplicates if (map.containsKey(b[i])) return 2; map.put(b[i], true); } // Otherwise it is impossible to // create such an array with // Bitwise OR operations return -1; } // Driver code public static void main(String[] args) { int K = 3; int[] a = { 1, 9, 4, 3 }; int n = a.length; System.out.println(minOperations(a, n, K)); }} // This code is contributed by// sanjeev2552 # Python3 implementation of the approach # Function to return the count of# minimum operations requireddef minOperations(a, n, K) : map = dict.fromkeys(a,0) ; for i in range(n) : # Check if the initial array # already contains an equal pair if (map[a[i]]) : return 0; map[a[i]] = True; # Create new array with OR operations b = [0]*n; for i in range(n) : b[i] = a[i] | K; # Clear the map map.clear(); # Check if the solution # is a single operation for i in range(n) : # If Bitwise OR operation between # 'k' and a[i] gives # a number other than a[i] if (a[i] != b[i]) : map[b[i]] = True; # Check if any of the a[i] # gets equal to any other element # of the array after the operation for i in range(n) : # Single operation # will be enough if a[i] not in map : pass elif (map[a[i]]) : return 1; # Clear the map map.clear(); # Check if the solution # is two operations for i in range(n) : # Check if the array 'b' # contains duplicates if (map[b[i]]) : return 2; map[b[i]] = true; # Otherwise it is impossible to # create such an array with # Bitwise OR operations return -1; # Driver codeif __name__ == "__main__" : K = 3; a = [ 1, 9, 4, 3 ]; n = len(a); # Function call to compute the result print(minOperations(a, n, K)); # This code is contributed by AnkitRai01 // C# implementation of the approachusing System;using System.Collections.Generic; class GFG{ // Function to return the count of // minimum operations required public static int minOperations(int[] a, int n, int K) { Dictionary<int, Boolean> map = new Dictionary<int, Boolean>(); for (int i = 0; i < n; i++) { // Check if the initial array // already contains an equal pair if (map.ContainsKey(a[i])) return 0; map.Add(a[i], true); } // Create new array with OR operations int[] b = new int[n]; for (int i = 0; i < n; i++) b[i] = a[i] | K; // Clear the map map.Clear(); // Check if the solution // is a single operation for (int i = 0; i < n; i++) { // If Bitwise OR operation between // 'k' and a[i] gives // a number other than a[i] if (a[i] != b[i]) map.Add(b[i], true); } // Check if any of the a[i] // gets equal to any other element // of the array after the operation for (int i = 0; i < n; i++) { // Single operation // will be enough if (map.ContainsKey(a[i])) return 1; } // Clear the map map.Clear(); // Check if the solution // is two operations for (int i = 0; i < n; i++) { // Check if the array 'b' // contains duplicates if (map.ContainsKey(b[i])) return 2; map.Add(b[i], true); } // Otherwise it is impossible to // create such an array with // Bitwise OR operations return -1; } // Driver code public static void Main(String[] args) { int K = 3; int[] a = { 1, 9, 4, 3 }; int n = a.Length; Console.WriteLine(minOperations(a, n, K)); }} // This code is contributed by 29AjayKumar <script> // JavaScript implementation of the approach // Function to return the count of// minimum operations requiredfunction minOperations(a, n, K) { let map = new Map(); for (let i = 0; i < n; i++) { // Check if the initial array // already contains an equal pair if (map.has(a[i])) return 0; map.set(a[i], true); } // Create new array with OR operations let b = new Array(n); for (let i = 0; i < n; i++) b[i] = a[i] | K; // Clear the map map.clear(); // Check if the solution // is a single operation for (let i = 0; i < n; i++) { // If Bitwise OR operation between // 'k' and a[i] gives // a number other than a[i] if (a[i] != b[i]) map.set(b[i], true); } // Check if any of the a[i] // gets equal to any other element // of the array after the operation for (let i = 0; i < n; i++) // Single operation // will be enough if (map.has(a[i])) return 1; // Clear the map map.clear(); // Check if the solution // is two operations for (let i = 0; i < n; i++) { // Check if the array 'b' // contains duplicates if (map.has(b[i])) return 2; map.set(b[i], true); } // Otherwise it is impossible to // create such an array with // Bitwise OR operations return -1;} // Driver code let K = 3;let a = [1, 9, 4, 3];let n = a.length; // Function call to compute the resultdocument.write(minOperations(a, n, K)); // This code is contributed by gfgking </script> 1 Time Complexity: O(n) Auxiliary Space: O(n) ankthon sanjeev2552 29AjayKumar gfgking subhammahato348 Bit Algorithms Bitwise-OR Arrays Bit Magic Arrays Bit Magic 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 Bitwise Operators in C/C++ Left Shift and Right Shift Operators in C/C++ Travelling Salesman Problem | Set 1 (Naive and Dynamic Programming) How to swap two numbers without using a temporary variable? Program to find whether a given number is power of 2
[ { "code": null, "e": 28, "s": 0, "text": "\n18 Nov, 2021" }, { "code": null, "e": 424, "s": 28, "text": "Given an array arr[] of integers and an integer K, we can perform the Bitwise OR operation between any array element and K any number of times. The task is to print the minimum number of such operations required to make any two elements of the array equal. If it is not possible to make any two elements of the array equal after performing the above-mentioned operation then print -1.Examples: " }, { "code": null, "e": 586, "s": 424, "text": "Input: arr[] = {1, 9, 4, 3}, K = 3 Output: 1 We can OR a[0] with x, which makes it 3 which is equal to a[3]Input : arr[] = {13, 26, 21, 15}, K = 13 Output : -1 " }, { "code": null, "e": 737, "s": 588, "text": "Approach: The key observation is that if it is possible to make the desired array then the answer will be either 0, 1 or 2. It will never exceed 2. " }, { "code": null, "e": 849, "s": 737, "text": "Because, if (x | k) = y then, no matter how many times you perform (y | k) it’ll always give y as the result. " }, { "code": null, "e": 923, "s": 851, "text": "The answer will be 0, if there are already equal elements in the array." }, { "code": null, "e": 1135, "s": 923, "text": "For the answer to be 1, we will create a new array b[] which holds b[i] = (a[i] | K), Now, for each a[i] we will check if there is any index j such that i != j and a[i] = b[j]. If yes, then the answer will be 1." }, { "code": null, "e": 1303, "s": 1135, "text": "For the answer to be 2, we will check for an index i in the new array b[], if there is any index j such that i != j and b[i] = b[j]. If yes, then the answer will be 2." }, { "code": null, "e": 1379, "s": 1303, "text": "If any of the above conditions is not satisfied then the answer will be -1." }, { "code": null, "e": 1432, "s": 1379, "text": "Below is the implementation of the above approach: " }, { "code": null, "e": 1436, "s": 1432, "text": "C++" }, { "code": null, "e": 1441, "s": 1436, "text": "Java" }, { "code": null, "e": 1449, "s": 1441, "text": "Python3" }, { "code": null, "e": 1452, "s": 1449, "text": "C#" }, { "code": null, "e": 1463, "s": 1452, "text": "Javascript" }, { "code": "// C++ implementation of the approach#include <bits/stdc++.h>using namespace std; // Function to return the count of// minimum operations requiredint minOperations(int a[], int n, int K){ unordered_map<int, bool> map; for (int i = 0; i < n; i++) { // Check if the initial array // already contains an equal pair if (map[a[i]]) return 0; map[a[i]] = true; } // Create new array with OR operations int b[n]; for (int i = 0; i < n; i++) b[i] = a[i] | K; // Clear the map map.clear(); // Check if the solution // is a single operation for (int i = 0; i < n; i++) { // If Bitwise OR operation between // 'k' and a[i] gives // a number other than a[i] if (a[i] != b[i]) map[b[i]] = true; } // Check if any of the a[i] // gets equal to any other element // of the array after the operation for (int i = 0; i < n; i++) // Single operation // will be enough if (map[a[i]]) return 1; // Clear the map map.clear(); // Check if the solution // is two operations for (int i = 0; i < n; i++) { // Check if the array 'b' // contains duplicates if (map[b[i]]) return 2; map[b[i]] = true; } // Otherwise it is impossible to // create such an array with // Bitwise OR operations return -1;} // Driver codeint main(){ int K = 3; int a[] = { 1, 9, 4, 3 }; int n = sizeof(a) / sizeof(a[0]); // Function call to compute the result cout << minOperations(a, n, K); return 0;}", "e": 3082, "s": 1463, "text": null }, { "code": "// Java implementation of the approachimport java.util.HashMap; class GFG{ // Function to return the count of // minimum operations required public static int minOperations(int[] a, int n, int K) { HashMap<Integer, Boolean> map = new HashMap<>(); for (int i = 0; i < n; i++) { // Check if the initial array // already contains an equal pair if (map.containsKey(a[i])) return 0; map.put(a[i], true); } // Create new array with OR operations int[] b = new int[n]; for (int i = 0; i < n; i++) b[i] = a[i] | K; // Clear the map map.clear(); // Check if the solution // is a single operation for (int i = 0; i < n; i++) { // If Bitwise OR operation between // 'k' and a[i] gives // a number other than a[i] if (a[i] != b[i]) map.put(b[i], true); } // Check if any of the a[i] // gets equal to any other element // of the array after the operation for (int i = 0; i < n; i++) { // Single operation // will be enough if (map.containsKey(a[i])) return 1; } // Clear the map map.clear(); // Check if the solution // is two operations for (int i = 0; i < n; i++) { // Check if the array 'b' // contains duplicates if (map.containsKey(b[i])) return 2; map.put(b[i], true); } // Otherwise it is impossible to // create such an array with // Bitwise OR operations return -1; } // Driver code public static void main(String[] args) { int K = 3; int[] a = { 1, 9, 4, 3 }; int n = a.length; System.out.println(minOperations(a, n, K)); }} // This code is contributed by// sanjeev2552", "e": 5077, "s": 3082, "text": null }, { "code": "# Python3 implementation of the approach # Function to return the count of# minimum operations requireddef minOperations(a, n, K) : map = dict.fromkeys(a,0) ; for i in range(n) : # Check if the initial array # already contains an equal pair if (map[a[i]]) : return 0; map[a[i]] = True; # Create new array with OR operations b = [0]*n; for i in range(n) : b[i] = a[i] | K; # Clear the map map.clear(); # Check if the solution # is a single operation for i in range(n) : # If Bitwise OR operation between # 'k' and a[i] gives # a number other than a[i] if (a[i] != b[i]) : map[b[i]] = True; # Check if any of the a[i] # gets equal to any other element # of the array after the operation for i in range(n) : # Single operation # will be enough if a[i] not in map : pass elif (map[a[i]]) : return 1; # Clear the map map.clear(); # Check if the solution # is two operations for i in range(n) : # Check if the array 'b' # contains duplicates if (map[b[i]]) : return 2; map[b[i]] = true; # Otherwise it is impossible to # create such an array with # Bitwise OR operations return -1; # Driver codeif __name__ == \"__main__\" : K = 3; a = [ 1, 9, 4, 3 ]; n = len(a); # Function call to compute the result print(minOperations(a, n, K)); # This code is contributed by AnkitRai01", "e": 6661, "s": 5077, "text": null }, { "code": "// C# implementation of the approachusing System;using System.Collections.Generic; class GFG{ // Function to return the count of // minimum operations required public static int minOperations(int[] a, int n, int K) { Dictionary<int, Boolean> map = new Dictionary<int, Boolean>(); for (int i = 0; i < n; i++) { // Check if the initial array // already contains an equal pair if (map.ContainsKey(a[i])) return 0; map.Add(a[i], true); } // Create new array with OR operations int[] b = new int[n]; for (int i = 0; i < n; i++) b[i] = a[i] | K; // Clear the map map.Clear(); // Check if the solution // is a single operation for (int i = 0; i < n; i++) { // If Bitwise OR operation between // 'k' and a[i] gives // a number other than a[i] if (a[i] != b[i]) map.Add(b[i], true); } // Check if any of the a[i] // gets equal to any other element // of the array after the operation for (int i = 0; i < n; i++) { // Single operation // will be enough if (map.ContainsKey(a[i])) return 1; } // Clear the map map.Clear(); // Check if the solution // is two operations for (int i = 0; i < n; i++) { // Check if the array 'b' // contains duplicates if (map.ContainsKey(b[i])) return 2; map.Add(b[i], true); } // Otherwise it is impossible to // create such an array with // Bitwise OR operations return -1; } // Driver code public static void Main(String[] args) { int K = 3; int[] a = { 1, 9, 4, 3 }; int n = a.Length; Console.WriteLine(minOperations(a, n, K)); }} // This code is contributed by 29AjayKumar", "e": 8787, "s": 6661, "text": null }, { "code": "<script> // JavaScript implementation of the approach // Function to return the count of// minimum operations requiredfunction minOperations(a, n, K) { let map = new Map(); for (let i = 0; i < n; i++) { // Check if the initial array // already contains an equal pair if (map.has(a[i])) return 0; map.set(a[i], true); } // Create new array with OR operations let b = new Array(n); for (let i = 0; i < n; i++) b[i] = a[i] | K; // Clear the map map.clear(); // Check if the solution // is a single operation for (let i = 0; i < n; i++) { // If Bitwise OR operation between // 'k' and a[i] gives // a number other than a[i] if (a[i] != b[i]) map.set(b[i], true); } // Check if any of the a[i] // gets equal to any other element // of the array after the operation for (let i = 0; i < n; i++) // Single operation // will be enough if (map.has(a[i])) return 1; // Clear the map map.clear(); // Check if the solution // is two operations for (let i = 0; i < n; i++) { // Check if the array 'b' // contains duplicates if (map.has(b[i])) return 2; map.set(b[i], true); } // Otherwise it is impossible to // create such an array with // Bitwise OR operations return -1;} // Driver code let K = 3;let a = [1, 9, 4, 3];let n = a.length; // Function call to compute the resultdocument.write(minOperations(a, n, K)); // This code is contributed by gfgking </script>", "e": 10385, "s": 8787, "text": null }, { "code": null, "e": 10387, "s": 10385, "text": "1" }, { "code": null, "e": 10411, "s": 10389, "text": "Time Complexity: O(n)" }, { "code": null, "e": 10433, "s": 10411, "text": "Auxiliary Space: O(n)" }, { "code": null, "e": 10441, "s": 10433, "text": "ankthon" }, { "code": null, "e": 10453, "s": 10441, "text": "sanjeev2552" }, { "code": null, "e": 10465, "s": 10453, "text": "29AjayKumar" }, { "code": null, "e": 10473, "s": 10465, "text": "gfgking" }, { "code": null, "e": 10489, "s": 10473, "text": "subhammahato348" }, { "code": null, "e": 10504, "s": 10489, "text": "Bit Algorithms" }, { "code": null, "e": 10515, "s": 10504, "text": "Bitwise-OR" }, { "code": null, "e": 10522, "s": 10515, "text": "Arrays" }, { "code": null, "e": 10532, "s": 10522, "text": "Bit Magic" }, { "code": null, "e": 10539, "s": 10532, "text": "Arrays" }, { "code": null, "e": 10549, "s": 10539, "text": "Bit Magic" }, { "code": null, "e": 10647, "s": 10549, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 10715, "s": 10647, "text": "Maximum and minimum of an array using minimum number of comparisons" }, { "code": null, "e": 10759, "s": 10715, "text": "Top 50 Array Coding Problems for Interviews" }, { "code": null, "e": 10791, "s": 10759, "text": "Multidimensional Arrays in Java" }, { "code": null, "e": 10839, "s": 10791, "text": "Stack Data Structure (Introduction and Program)" }, { "code": null, "e": 10853, "s": 10839, "text": "Linear Search" }, { "code": null, "e": 10880, "s": 10853, "text": "Bitwise Operators in C/C++" }, { "code": null, "e": 10926, "s": 10880, "text": "Left Shift and Right Shift Operators in C/C++" }, { "code": null, "e": 10994, "s": 10926, "text": "Travelling Salesman Problem | Set 1 (Naive and Dynamic Programming)" }, { "code": null, "e": 11054, "s": 10994, "text": "How to swap two numbers without using a temporary variable?" } ]
GATE | GATE-CS-2006 | Question 1
28 Jun, 2021 Consider the polynomial p(x) = a0 + a1x + a2x2 + a3x3 , where ai ≠ 0 ∀i. The minimum number of multiplications needed to evaluate p on an input x is:(A) 3(B) 4(C) 6(D) 9Answer: (A)Explanation:Background Explanation :Horner’s rule for polynomial division is an algorithm used to simplify the process of evaluating a polynomial f(x) at a certain value x = x0 by dividing the polynomial into monomials (polynomials of the 1st degree). Each monomial involves a maximum of one multiplication and one addition processes. The result obtained from one monomial is added to the result obtained from the next monomial and so forth in an accumulative addition fashion. To explain the above, let is re-write the polynomial in its expanded form; f(x0) = a0 + a1x0+ a2x0^2+ ... + anx0^n This can, also, be written as: f(x0) = a0 + x0(a1+ x0(a2+ x0(a3+ ... + (an-1 + anx0)....) The algorithm proposed by this rule is based on evaluating the monomials formed above startingfrom the one in the inner-most parenthesis and move out to evaluate the monomials in the outerparenthesis. Solution :Using Horner’s Rule, we can write the polynomial as followinga0 + (a1 + (a2 + a3x)x)x In the above form, we need to do only 3 multiplications p = a3 X x ------------ (1) q = (a2 + p) X x ---------(2) r = (a1 + q) X x ---------(3) result = a0 + r Reference :https://www.geeksforgeeks.org/horners-method-polynomial-evaluation/This solution is contributed by Nitika Bansal.Quiz of this Question GATE-CS-2006 GATE-GATE-CS-2006 GATE Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. GATE | GATE-CS-2014-(Set-1) | Question 65 GATE | Gate IT 2005 | Question 11 GATE | GATE MOCK 2017 | Question 45 GATE | GATE-CS-2004 | Question 90 GATE | GATE-CS-2000 | Question 2 GATE | GATE CS 2013 | Question 50 GATE | GATE CS 2012 | Question 65 GATE | GATE-CS-2003 | Question 64 GATE | GATE-CS-2004 | Question 90 GATE | GATE-CS-2015 (Set 1) | Question 30
[ { "code": null, "e": 54, "s": 26, "text": "\n28 Jun, 2021" }, { "code": null, "e": 788, "s": 54, "text": "Consider the polynomial p(x) = a0 + a1x + a2x2 + a3x3 , where ai ≠ 0 ∀i. The minimum number of multiplications needed to evaluate p on an input x is:(A) 3(B) 4(C) 6(D) 9Answer: (A)Explanation:Background Explanation :Horner’s rule for polynomial division is an algorithm used to simplify the process of evaluating a polynomial f(x) at a certain value x = x0 by dividing the polynomial into monomials (polynomials of the 1st degree). Each monomial involves a maximum of one multiplication and one addition processes. The result obtained from one monomial is added to the result obtained from the next monomial and so forth in an accumulative addition fashion. To explain the above, let is re-write the polynomial in its expanded form;" }, { "code": null, "e": 828, "s": 788, "text": "f(x0) = a0 + a1x0+ a2x0^2+ ... + anx0^n" }, { "code": null, "e": 859, "s": 828, "text": "This can, also, be written as:" }, { "code": null, "e": 918, "s": 859, "text": "f(x0) = a0 + x0(a1+ x0(a2+ x0(a3+ ... + (an-1 + anx0)....)" }, { "code": null, "e": 1119, "s": 918, "text": "The algorithm proposed by this rule is based on evaluating the monomials formed above startingfrom the one in the inner-most parenthesis and move out to evaluate the monomials in the outerparenthesis." }, { "code": null, "e": 1215, "s": 1119, "text": "Solution :Using Horner’s Rule, we can write the polynomial as followinga0 + (a1 + (a2 + a3x)x)x" }, { "code": null, "e": 1271, "s": 1215, "text": "In the above form, we need to do only 3 multiplications" }, { "code": null, "e": 1385, "s": 1271, "text": "\np = a3 X x ------------ (1)\n\nq = (a2 + p) X x ---------(2)\n\nr = (a1 + q) X x ---------(3)\n\nresult = a0 + r " }, { "code": null, "e": 1531, "s": 1385, "text": "Reference :https://www.geeksforgeeks.org/horners-method-polynomial-evaluation/This solution is contributed by Nitika Bansal.Quiz of this Question" }, { "code": null, "e": 1544, "s": 1531, "text": "GATE-CS-2006" }, { "code": null, "e": 1562, "s": 1544, "text": "GATE-GATE-CS-2006" }, { "code": null, "e": 1567, "s": 1562, "text": "GATE" }, { "code": null, "e": 1665, "s": 1567, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 1707, "s": 1665, "text": "GATE | GATE-CS-2014-(Set-1) | Question 65" }, { "code": null, "e": 1741, "s": 1707, "text": "GATE | Gate IT 2005 | Question 11" }, { "code": null, "e": 1777, "s": 1741, "text": "GATE | GATE MOCK 2017 | Question 45" }, { "code": null, "e": 1811, "s": 1777, "text": "GATE | GATE-CS-2004 | Question 90" }, { "code": null, "e": 1844, "s": 1811, "text": "GATE | GATE-CS-2000 | Question 2" }, { "code": null, "e": 1878, "s": 1844, "text": "GATE | GATE CS 2013 | Question 50" }, { "code": null, "e": 1912, "s": 1878, "text": "GATE | GATE CS 2012 | Question 65" }, { "code": null, "e": 1946, "s": 1912, "text": "GATE | GATE-CS-2003 | Question 64" }, { "code": null, "e": 1980, "s": 1946, "text": "GATE | GATE-CS-2004 | Question 90" } ]
null=True – Django Built-in Field Validation
13 Feb, 2020 Built-in Field Validations in Django models are the default validations that come predefined to all Django fields. Every field comes in with built-in validations from Django validators. One can also add more built-in field validations for applying or removing certain constraints on a particular field. null=True will make the field accept NULL values. Blank values for Django field types such as DateTimeField or ForeignKey will be stored as NULL in the database. Syntax field_name = models.Field(null = True) Illustration of null=True using an Example. Consider a project named geeksforgeeks having an app named geeks. Refer to the following articles to check how to create a project and an app in Django. How to Create a Basic Project using MVT in Django? How to Create an App in Django ? Enter the following code into models.py file of geeks app. We will be using CharField for experimenting for all field options. from django.db import modelsfrom django.db.models import Model# Create your models here. class GeeksModel(Model): geeks_field = models.CharField(max_length = 200, null = True) After running makemigrations and migrate on Django and rendering the above model, let us try to create an instance using None from Django shell. To start Django shell, enter the command, Python manage.py shell Now let us try to create instance of GeeksModel using None. # importing required modelfrom geeks.models import GeeksModel # creating instance of GeeksModels = GeeksModel.objects.create(geeks_field = None) # saving current model instances.save() Let us check in admin interface if the instance of model is created.Therefore, null=True modifies the field to accept NULL values or in python’s terms None Values. Avoid using null on string-based fields such as CharField and TextField. If a string-based field has null=True, that means it has two possible values for “no data”: NULL, and the empty string. In most cases, it’s redundant to have two possible values for “no data;” the Django convention is to use the empty string, not NULL. One exception is when a CharField has both unique=True and blank=True set. In this situation, null=True is required to avoid unique constraint violations when saving multiple objects with blank values. For both string-based and non-string-based fields, one will also need to set blank=True if you wish to permit empty values in forms, as the null parameter only affects database storage (see blank). NaveenArora Django-models Python Django Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n13 Feb, 2020" }, { "code": null, "e": 493, "s": 28, "text": "Built-in Field Validations in Django models are the default validations that come predefined to all Django fields. Every field comes in with built-in validations from Django validators. One can also add more built-in field validations for applying or removing certain constraints on a particular field. null=True will make the field accept NULL values. Blank values for Django field types such as DateTimeField or ForeignKey will be stored as NULL in the database." }, { "code": null, "e": 500, "s": 493, "text": "Syntax" }, { "code": null, "e": 539, "s": 500, "text": "field_name = models.Field(null = True)" }, { "code": null, "e": 649, "s": 539, "text": "Illustration of null=True using an Example. Consider a project named geeksforgeeks having an app named geeks." }, { "code": null, "e": 736, "s": 649, "text": "Refer to the following articles to check how to create a project and an app in Django." }, { "code": null, "e": 787, "s": 736, "text": "How to Create a Basic Project using MVT in Django?" }, { "code": null, "e": 820, "s": 787, "text": "How to Create an App in Django ?" }, { "code": null, "e": 947, "s": 820, "text": "Enter the following code into models.py file of geeks app. We will be using CharField for experimenting for all field options." }, { "code": "from django.db import modelsfrom django.db.models import Model# Create your models here. class GeeksModel(Model): geeks_field = models.CharField(max_length = 200, null = True)", "e": 1127, "s": 947, "text": null }, { "code": null, "e": 1314, "s": 1127, "text": "After running makemigrations and migrate on Django and rendering the above model, let us try to create an instance using None from Django shell. To start Django shell, enter the command," }, { "code": null, "e": 1337, "s": 1314, "text": "Python manage.py shell" }, { "code": null, "e": 1397, "s": 1337, "text": "Now let us try to create instance of GeeksModel using None." }, { "code": "# importing required modelfrom geeks.models import GeeksModel # creating instance of GeeksModels = GeeksModel.objects.create(geeks_field = None) # saving current model instances.save()", "e": 1584, "s": 1397, "text": null }, { "code": null, "e": 1748, "s": 1584, "text": "Let us check in admin interface if the instance of model is created.Therefore, null=True modifies the field to accept NULL values or in python’s terms None Values." }, { "code": null, "e": 2276, "s": 1748, "text": "Avoid using null on string-based fields such as CharField and TextField. If a string-based field has null=True, that means it has two possible values for “no data”: NULL, and the empty string. In most cases, it’s redundant to have two possible values for “no data;” the Django convention is to use the empty string, not NULL. One exception is when a CharField has both unique=True and blank=True set. In this situation, null=True is required to avoid unique constraint violations when saving multiple objects with blank values." }, { "code": null, "e": 2474, "s": 2276, "text": "For both string-based and non-string-based fields, one will also need to set blank=True if you wish to permit empty values in forms, as the null parameter only affects database storage (see blank)." }, { "code": null, "e": 2486, "s": 2474, "text": "NaveenArora" }, { "code": null, "e": 2500, "s": 2486, "text": "Django-models" }, { "code": null, "e": 2514, "s": 2500, "text": "Python Django" }, { "code": null, "e": 2521, "s": 2514, "text": "Python" } ]
Scope of Variables In Java
28 Jun, 2021 Scope of a variable is the part of the program where the variable is accessible. Like C/C++, in Java, all identifiers are lexically (or statically) scoped, i.e.scope of a variable can determined at compile time and independent of function call stack. Java programs are organized in the form of classes. Every class is part of some package. Java scope rules can be covered under following categories. Member Variables (Class Level Scope) These variables must be declared inside class (outside any function). They can be directly accessed anywhere in class. Let’s take a look at an example: public class Test { // All variables defined directly inside a class // are member variables int a; private String b; void method1() {....} int method2() {....} char c; } We can declare class variables anywhere in class, but outside methods. Access specified of member variables doesn’t affect scope of them within a class. Member variables can be accessed outside a class with following rules Modifier Package Subclass World public Yes Yes Yes protected Yes Yes No Default (no modifier) Yes No No private No No No Local Variables (Method Level Scope) Variables declared inside a method have method level scope and can’t be accessed outside the method. public class Test { void method1() { // Local variable (Method level scope) int x; } } Note : Local variables don’t exist after method’s execution is over. Here’s another example of method scope, except this time the variable got passed in as a parameter to the method: class Test { private int x; public void setX(int x) { this.x = x; } } The above code uses this keyword to differentiate between the local and class variables. As an exercise, predict the output of following Java program. Java public class Test{ static int x = 11; private int y = 33; public void method1(int x) { Test t = new Test(); this.x = 22; y = 44; System.out.println("Test.x: " + Test.x); System.out.println("t.x: " + t.x); System.out.println("t.y: " + t.y); System.out.println("y: " + y); } public static void main(String args[]) { Test t = new Test(); t.method1(5); }} Output: Test.x: 22 t.x: 22 t.y: 33 y: 44 Loop Variables (Block Scope) A variable declared inside pair of brackets “{” and “}” in a method has scope within the brackets only. Java public class Test{ public static void main(String args[]) { { // The variable x has scope within // brackets int x = 10; System.out.println(x); } // Uncommenting below line would produce // error since variable x is out of scope. // System.out.println(x); }} Output: 10 As another example, consider following program with a for loop. Java class Test{ public static void main(String args[]) { for (int x = 0; x < 4; x++) { System.out.println(x); } // Will produce error System.out.println(x); }} Output: 11: error: cannot find symbol System.out.println(x); The right way of doing above is, Java // Above program after correcting the errorclass Test{ public static void main(String args[]) { int x; for (x = 0; x < 4; x++) { System.out.println(x); } System.out.println(x); }} Output: 0 1 2 3 4 Let’s look at tricky example of loop scope. Predict the output of following program. You may be surprised if you are regular C/C++ programmer. Java class Test{ public static void main(String args[]) { int a = 5; for (int a = 0; a < 5; a++) { System.out.println(a); } }} Output : 6: error: variable a is already defined in method go(int) for (int a = 0; a < 5; a++) ^ 1 error Note:- In C++, it will run. But in java it is an error because in java, the name of the variable of inner and outer loop must be different.A similar program in C++ works. See this. As an exercise, predict the output of the following Java program. Java class Test{ public static void main(String args[]) { { int x = 5; { int x = 10; System.out.println(x); } } }} Q. From the above knowledge, tell whether the below code will run or not. Java class Test { public static void main(String args[]) { for (int i = 1; i <= 10; i++) { System.out.println(i); } int i = 20; System.out.println(i); }} Output : 1 2 3 4 5 6 7 8 9 10 20 Yes, it will run! See the program carefully, inner loop will terminate before the outer loop variable is declared.So the inner loop variable is destroyed first and then the new variable of same name has been created. Some Important Points about Variable scope in Java: In general, a set of curly brackets { } defines a scope. In Java we can usually access a variable as long as it was defined within the same set of brackets as the code we are writing or within any curly brackets inside of the curly brackets where the variable was defined. Any variable defined in a class outside of any method can be used by all member methods. When a method has the same local variable as a member, “this” keyword can be used to reference the current class variable. For a variable to be read after the termination of a loop, It must be declared before the body of the loop. This article is contributed by Rishabh Mahrsee. If you like GeeksforGeeks and would like to contribute, you can also write an article and mail your article to review-team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above ShreyasWaghmare AnshulVaidya iam_chandan17 aadarsh baid Java School Programming Java Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Split() String method in Java with examples Arrays.sort() in Java with examples Reverse a string in Java How to iterate any Map in Java Stream In Java Python Dictionary Reverse a string in Java Arrays in C/C++ Introduction To PYTHON Inheritance in C++
[ { "code": null, "e": 52, "s": 24, "text": "\n28 Jun, 2021" }, { "code": null, "e": 453, "s": 52, "text": "Scope of a variable is the part of the program where the variable is accessible. Like C/C++, in Java, all identifiers are lexically (or statically) scoped, i.e.scope of a variable can determined at compile time and independent of function call stack. Java programs are organized in the form of classes. Every class is part of some package. Java scope rules can be covered under following categories. " }, { "code": null, "e": 490, "s": 453, "text": "Member Variables (Class Level Scope)" }, { "code": null, "e": 643, "s": 490, "text": "These variables must be declared inside class (outside any function). They can be directly accessed anywhere in class. Let’s take a look at an example: " }, { "code": null, "e": 843, "s": 643, "text": "public class Test\n{\n // All variables defined directly inside a class \n // are member variables\n int a;\n private String b;\n void method1() {....}\n int method2() {....}\n char c;\n}" }, { "code": null, "e": 914, "s": 843, "text": "We can declare class variables anywhere in class, but outside methods." }, { "code": null, "e": 996, "s": 914, "text": "Access specified of member variables doesn’t affect scope of them within a class." }, { "code": null, "e": 1066, "s": 996, "text": "Member variables can be accessed outside a class with following rules" }, { "code": null, "e": 1266, "s": 1066, "text": "Modifier Package Subclass World\n\npublic Yes Yes Yes\n\nprotected Yes Yes No\n\nDefault (no\nmodifier) Yes No No\n\nprivate No No No" }, { "code": null, "e": 1303, "s": 1266, "text": "Local Variables (Method Level Scope)" }, { "code": null, "e": 1405, "s": 1303, "text": "Variables declared inside a method have method level scope and can’t be accessed outside the method. " }, { "code": null, "e": 1519, "s": 1405, "text": "public class Test\n{\n void method1() \n {\n // Local variable (Method level scope)\n int x;\n }\n}" }, { "code": null, "e": 1589, "s": 1519, "text": "Note : Local variables don’t exist after method’s execution is over. " }, { "code": null, "e": 1704, "s": 1589, "text": "Here’s another example of method scope, except this time the variable got passed in as a parameter to the method: " }, { "code": null, "e": 1798, "s": 1704, "text": "class Test\n{\n private int x;\n public void setX(int x)\n {\n this.x = x;\n }\n}" }, { "code": null, "e": 1887, "s": 1798, "text": "The above code uses this keyword to differentiate between the local and class variables." }, { "code": null, "e": 1951, "s": 1887, "text": "As an exercise, predict the output of following Java program. " }, { "code": null, "e": 1956, "s": 1951, "text": "Java" }, { "code": "public class Test{ static int x = 11; private int y = 33; public void method1(int x) { Test t = new Test(); this.x = 22; y = 44; System.out.println(\"Test.x: \" + Test.x); System.out.println(\"t.x: \" + t.x); System.out.println(\"t.y: \" + t.y); System.out.println(\"y: \" + y); } public static void main(String args[]) { Test t = new Test(); t.method1(5); }}", "e": 2397, "s": 1956, "text": null }, { "code": null, "e": 2406, "s": 2397, "text": "Output: " }, { "code": null, "e": 2439, "s": 2406, "text": "Test.x: 22\nt.x: 22\nt.y: 33\ny: 44" }, { "code": null, "e": 2572, "s": 2439, "text": "Loop Variables (Block Scope) A variable declared inside pair of brackets “{” and “}” in a method has scope within the brackets only." }, { "code": null, "e": 2577, "s": 2572, "text": "Java" }, { "code": "public class Test{ public static void main(String args[]) { { // The variable x has scope within // brackets int x = 10; System.out.println(x); } // Uncommenting below line would produce // error since variable x is out of scope. // System.out.println(x); }}", "e": 2934, "s": 2577, "text": null }, { "code": null, "e": 2943, "s": 2934, "text": "Output: " }, { "code": null, "e": 2946, "s": 2943, "text": "10" }, { "code": null, "e": 3011, "s": 2946, "text": "As another example, consider following program with a for loop. " }, { "code": null, "e": 3016, "s": 3011, "text": "Java" }, { "code": "class Test{ public static void main(String args[]) { for (int x = 0; x < 4; x++) { System.out.println(x); } // Will produce error System.out.println(x); }}", "e": 3228, "s": 3016, "text": null }, { "code": null, "e": 3237, "s": 3228, "text": "Output: " }, { "code": null, "e": 3304, "s": 3237, "text": "11: error: cannot find symbol\n System.out.println(x); " }, { "code": null, "e": 3338, "s": 3304, "text": "The right way of doing above is, " }, { "code": null, "e": 3343, "s": 3338, "text": "Java" }, { "code": "// Above program after correcting the errorclass Test{ public static void main(String args[]) { int x; for (x = 0; x < 4; x++) { System.out.println(x); } System.out.println(x); }}", "e": 3578, "s": 3343, "text": null }, { "code": null, "e": 3587, "s": 3578, "text": "Output: " }, { "code": null, "e": 3597, "s": 3587, "text": "0\n1\n2\n3\n4" }, { "code": null, "e": 3741, "s": 3597, "text": "Let’s look at tricky example of loop scope. Predict the output of following program. You may be surprised if you are regular C/C++ programmer. " }, { "code": null, "e": 3746, "s": 3741, "text": "Java" }, { "code": "class Test{ public static void main(String args[]) { int a = 5; for (int a = 0; a < 5; a++) { System.out.println(a); } }}", "e": 3916, "s": 3746, "text": null }, { "code": null, "e": 3925, "s": 3916, "text": "Output :" }, { "code": null, "e": 4051, "s": 3925, "text": "6: error: variable a is already defined in method go(int)\n for (int a = 0; a < 5; a++) \n ^\n1 error" }, { "code": null, "e": 4232, "s": 4051, "text": "Note:- In C++, it will run. But in java it is an error because in java, the name of the variable of inner and outer loop must be different.A similar program in C++ works. See this." }, { "code": null, "e": 4299, "s": 4232, "text": "As an exercise, predict the output of the following Java program. " }, { "code": null, "e": 4304, "s": 4299, "text": "Java" }, { "code": "class Test{ public static void main(String args[]) { { int x = 5; { int x = 10; System.out.println(x); } } }}", "e": 4500, "s": 4304, "text": null }, { "code": null, "e": 4574, "s": 4500, "text": "Q. From the above knowledge, tell whether the below code will run or not." }, { "code": null, "e": 4579, "s": 4574, "text": "Java" }, { "code": "class Test { public static void main(String args[]) { for (int i = 1; i <= 10; i++) { System.out.println(i); } int i = 20; System.out.println(i); }}", "e": 4776, "s": 4579, "text": null }, { "code": null, "e": 4786, "s": 4776, "text": "Output : " }, { "code": null, "e": 4810, "s": 4786, "text": "1\n2\n3\n4\n5\n6\n7\n8\n9\n10\n20" }, { "code": null, "e": 5027, "s": 4810, "text": "Yes, it will run! See the program carefully, inner loop will terminate before the outer loop variable is declared.So the inner loop variable is destroyed first and then the new variable of same name has been created." }, { "code": null, "e": 5081, "s": 5027, "text": "Some Important Points about Variable scope in Java: " }, { "code": null, "e": 5138, "s": 5081, "text": "In general, a set of curly brackets { } defines a scope." }, { "code": null, "e": 5354, "s": 5138, "text": "In Java we can usually access a variable as long as it was defined within the same set of brackets as the code we are writing or within any curly brackets inside of the curly brackets where the variable was defined." }, { "code": null, "e": 5443, "s": 5354, "text": "Any variable defined in a class outside of any method can be used by all member methods." }, { "code": null, "e": 5566, "s": 5443, "text": "When a method has the same local variable as a member, “this” keyword can be used to reference the current class variable." }, { "code": null, "e": 5674, "s": 5566, "text": "For a variable to be read after the termination of a loop, It must be declared before the body of the loop." }, { "code": null, "e": 5945, "s": 5674, "text": " This article is contributed by Rishabh Mahrsee. If you like GeeksforGeeks and would like to contribute, you can also write an article and mail your article to review-team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks." }, { "code": null, "e": 6069, "s": 5945, "text": "Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above" }, { "code": null, "e": 6087, "s": 6071, "text": "ShreyasWaghmare" }, { "code": null, "e": 6100, "s": 6087, "text": "AnshulVaidya" }, { "code": null, "e": 6114, "s": 6100, "text": "iam_chandan17" }, { "code": null, "e": 6127, "s": 6114, "text": "aadarsh baid" }, { "code": null, "e": 6132, "s": 6127, "text": "Java" }, { "code": null, "e": 6151, "s": 6132, "text": "School Programming" }, { "code": null, "e": 6156, "s": 6151, "text": "Java" }, { "code": null, "e": 6254, "s": 6156, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 6298, "s": 6254, "text": "Split() String method in Java with examples" }, { "code": null, "e": 6334, "s": 6298, "text": "Arrays.sort() in Java with examples" }, { "code": null, "e": 6359, "s": 6334, "text": "Reverse a string in Java" }, { "code": null, "e": 6390, "s": 6359, "text": "How to iterate any Map in Java" }, { "code": null, "e": 6405, "s": 6390, "text": "Stream In Java" }, { "code": null, "e": 6423, "s": 6405, "text": "Python Dictionary" }, { "code": null, "e": 6448, "s": 6423, "text": "Reverse a string in Java" }, { "code": null, "e": 6464, "s": 6448, "text": "Arrays in C/C++" }, { "code": null, "e": 6487, "s": 6464, "text": "Introduction To PYTHON" } ]
How to define dimensions of an empty DataFrame in R ?
21 Apr, 2021 An empty data frame in R Programming Language corresponds to the tabular structure where the axes are of length 0, i.e. it does not contain any data items. It is basically a tabular structure organized into rows and columns consisting of all empty data vectors. A data frame can be empty in the following cases : A data frame with empty vectors. Creating a data frame of NULL entries. An empty data frame can be created by using only 0-length variables for column names. The data types can also be declared for these columns to specify the type of data if we wish to. In this case, the dimensions of the data frame are 0 x number of columns, but the data frame is considered empty, since it doesn’t contain any entries. Syntax: data.frame(column1 = data_type(col1),...) Example R # declaring a data frame with 2 columns and# declaring data type of both the columns data_frame <- data.frame(col1 = character(0), col2 = numeric(0)) # printing data frameprint ("Data Frame : ")print (data_frame) Output [1] “Data Frame : “ [1] col1 col2 <0 rows> (or 0-length row.names) In case, a single type of data type is to be assigned to all the columns of the data frame, the data type can be declared after all the columns are initialized with NA values. Example R # declaring an empty data framedata_frame1 <- data.frame(col1=NA, col2=NA, col3=NA, col4=NA)[numeric(0), ] # printing data frameprint ("Data Frame :")print (data_frame1) Output [1] “Data Frame : “ [1] col1 col2 col3 col4 <0 rows> (or 0-length row.names) This is just another way of interpreting empty dataframe. Here, the values it stores will be NULL, but the dimension will be like a regular dataframe with values. A matrix with the required dimensions can be created. It is filled with NA or missing values. Since, the matrices and data frames are interconvertible into each other, it can then be converted to data frame. The dimensions of the data frame are equivalent to the length of the axes declared for matrix. A matrix can be declared using matrix() function in R. Example: R # declaring a data frame with 2 columns# and declaring data type of both the # columns mat <- matrix(NA, nrow = 5, ncol = 2) # converting matrix to data framedata_frame <- data.frame(mat) # printing data frameprint ("Data Frame : ")print (data_frame) # printing dimensionsdim(data_frame) Output [1] “Data Frame : “ X1 X2 1 NA NA 2 NA NA 3 NA NA 4 NA NA 5 NA NA [1] 5 2 Picked R DataFrame-Programs R-DataFrame R Language R Programs Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Filter data by multiple conditions in R using Dplyr How to Replace specific values in column in R DataFrame ? Change Color of Bars in Barchart using ggplot2 in R How to Split Column Into Multiple Columns in R DataFrame? Group by function in R using Dplyr How to Replace specific values in column in R DataFrame ? How to Split Column Into Multiple Columns in R DataFrame? How to change Row Names of DataFrame in R ? How to filter R DataFrame by values in a column? Remove rows with NA in one column of R DataFrame
[ { "code": null, "e": 28, "s": 0, "text": "\n21 Apr, 2021" }, { "code": null, "e": 342, "s": 28, "text": "An empty data frame in R Programming Language corresponds to the tabular structure where the axes are of length 0, i.e. it does not contain any data items. It is basically a tabular structure organized into rows and columns consisting of all empty data vectors. A data frame can be empty in the following cases : " }, { "code": null, "e": 375, "s": 342, "text": "A data frame with empty vectors." }, { "code": null, "e": 414, "s": 375, "text": "Creating a data frame of NULL entries." }, { "code": null, "e": 750, "s": 414, "text": "An empty data frame can be created by using only 0-length variables for column names. The data types can also be declared for these columns to specify the type of data if we wish to. In this case, the dimensions of the data frame are 0 x number of columns, but the data frame is considered empty, since it doesn’t contain any entries. " }, { "code": null, "e": 758, "s": 750, "text": "Syntax:" }, { "code": null, "e": 800, "s": 758, "text": "data.frame(column1 = data_type(col1),...)" }, { "code": null, "e": 808, "s": 800, "text": "Example" }, { "code": null, "e": 810, "s": 808, "text": "R" }, { "code": "# declaring a data frame with 2 columns and# declaring data type of both the columns data_frame <- data.frame(col1 = character(0), col2 = numeric(0)) # printing data frameprint (\"Data Frame : \")print (data_frame)", "e": 1024, "s": 810, "text": null }, { "code": null, "e": 1031, "s": 1024, "text": "Output" }, { "code": null, "e": 1051, "s": 1031, "text": "[1] “Data Frame : “" }, { "code": null, "e": 1065, "s": 1051, "text": "[1] col1 col2" }, { "code": null, "e": 1098, "s": 1065, "text": "<0 rows> (or 0-length row.names)" }, { "code": null, "e": 1275, "s": 1098, "text": "In case, a single type of data type is to be assigned to all the columns of the data frame, the data type can be declared after all the columns are initialized with NA values. " }, { "code": null, "e": 1283, "s": 1275, "text": "Example" }, { "code": null, "e": 1285, "s": 1283, "text": "R" }, { "code": "# declaring an empty data framedata_frame1 <- data.frame(col1=NA, col2=NA, col3=NA, col4=NA)[numeric(0), ] # printing data frameprint (\"Data Frame :\")print (data_frame1)", "e": 1456, "s": 1285, "text": null }, { "code": null, "e": 1463, "s": 1456, "text": "Output" }, { "code": null, "e": 1483, "s": 1463, "text": "[1] “Data Frame : “" }, { "code": null, "e": 1507, "s": 1483, "text": "[1] col1 col2 col3 col4" }, { "code": null, "e": 1540, "s": 1507, "text": "<0 rows> (or 0-length row.names)" }, { "code": null, "e": 2062, "s": 1540, "text": "This is just another way of interpreting empty dataframe. Here, the values it stores will be NULL, but the dimension will be like a regular dataframe with values. A matrix with the required dimensions can be created. It is filled with NA or missing values. Since, the matrices and data frames are interconvertible into each other, it can then be converted to data frame. The dimensions of the data frame are equivalent to the length of the axes declared for matrix. A matrix can be declared using matrix() function in R. " }, { "code": null, "e": 2071, "s": 2062, "text": "Example:" }, { "code": null, "e": 2073, "s": 2071, "text": "R" }, { "code": "# declaring a data frame with 2 columns# and declaring data type of both the # columns mat <- matrix(NA, nrow = 5, ncol = 2) # converting matrix to data framedata_frame <- data.frame(mat) # printing data frameprint (\"Data Frame : \")print (data_frame) # printing dimensionsdim(data_frame)", "e": 2364, "s": 2073, "text": null }, { "code": null, "e": 2371, "s": 2364, "text": "Output" }, { "code": null, "e": 2391, "s": 2371, "text": "[1] “Data Frame : “" }, { "code": null, "e": 2398, "s": 2391, "text": " X1 X2" }, { "code": null, "e": 2406, "s": 2398, "text": "1 NA NA" }, { "code": null, "e": 2414, "s": 2406, "text": "2 NA NA" }, { "code": null, "e": 2422, "s": 2414, "text": "3 NA NA" }, { "code": null, "e": 2430, "s": 2422, "text": "4 NA NA" }, { "code": null, "e": 2438, "s": 2430, "text": "5 NA NA" }, { "code": null, "e": 2446, "s": 2438, "text": "[1] 5 2" }, { "code": null, "e": 2453, "s": 2446, "text": "Picked" }, { "code": null, "e": 2474, "s": 2453, "text": "R DataFrame-Programs" }, { "code": null, "e": 2486, "s": 2474, "text": "R-DataFrame" }, { "code": null, "e": 2497, "s": 2486, "text": "R Language" }, { "code": null, "e": 2508, "s": 2497, "text": "R Programs" }, { "code": null, "e": 2606, "s": 2508, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 2658, "s": 2606, "text": "Filter data by multiple conditions in R using Dplyr" }, { "code": null, "e": 2716, "s": 2658, "text": "How to Replace specific values in column in R DataFrame ?" }, { "code": null, "e": 2768, "s": 2716, "text": "Change Color of Bars in Barchart using ggplot2 in R" }, { "code": null, "e": 2826, "s": 2768, "text": "How to Split Column Into Multiple Columns in R DataFrame?" }, { "code": null, "e": 2861, "s": 2826, "text": "Group by function in R using Dplyr" }, { "code": null, "e": 2919, "s": 2861, "text": "How to Replace specific values in column in R DataFrame ?" }, { "code": null, "e": 2977, "s": 2919, "text": "How to Split Column Into Multiple Columns in R DataFrame?" }, { "code": null, "e": 3021, "s": 2977, "text": "How to change Row Names of DataFrame in R ?" }, { "code": null, "e": 3070, "s": 3021, "text": "How to filter R DataFrame by values in a column?" } ]
CRLF Injection Attack
07 Sep, 2020 CRLF is the acronym used to refer to Carriage Return (\r) Line Feed (\n). As one might notice from the symbols in the brackets, “Carriage Return” refers to the end of a line, and “Line Feed” refers to the new line. Hence, both CR and LF are used to denote the ending point of a line. When a user requests content on a website, the server returns the website content along with the HTTP headers. The headers and the contents are separated by a defined combination of CR and LF. It is because of CRLF that a server knows where a new header begins or ends. A Carriage Return Line Feed (CRLF) Injection vulnerability is a type of Server Side Injection which occurs when an attacker inserts the CRLF characters in an input field to deceive the server by making it think that an object has terminated and a new one has begun. This happens when the web application doesn’t sanitize user input for CRLF characters. It has a medium severity rating (P3 according to Bugcrowd’s VRT). CRLF Injection attack has two most important use cases: Log Splitting: The attacker inserts an end of line character and an extra line to falsify the log file entries in order to deceive the system administrators by hiding other attacks. HTTP Response Splitting: CRLF injection is used to add HTTP headers to the HTTP response and, for example, perform an XSS attack that leads to information disclosure. Example: A simple GET request can be crafted as follows: GET /%0d%0aSet-Cookie:CRLFInjection=PreritPathak HTTP/1.1 Note: %0d and %0a are encoded forms of \r and \n respectively. If the web application is vulnerable, an attacker will be able to set a cookie on the website. CRLF Injection allows the attacker to set fake cookies, steal CSRF tokens, disclose user information by injecting a script (XSS) and perform a variety of other attacks. It also allows attackers to deactivate & bypass security measures like XSS filters & Same Origin Policy (SOP), making them susceptible to the following attacks: 1. XSS or Cross Site ScriptingXSS or Cross Site Scripting is a security vulnerability which allows an attacker to inject malicious JavaScript code into the web application. The following GET requests are crafted in an attempt chain CRLF Injection with XSS. By Popping an alert containing sensitive user information www.target.com/%3f%0d%0aLocation:%0d%0aContent-Type:text/html%0d%0aX-XSS-Protection%3a0%0d%0a%0d%0a%3Cscript%3Ealert%28document.domain%29%3C/script%3E By Disabling XSS Protection www.target.com/%0d%0aContent-Length:35%0d%0aX-XSS-Protection:0%0d%0a%0d%0a23 2. Cookie InjectionHTTP Response Splitting allows an attacker to set malicious cookies on the victim’s browser. In most cases, the following GET request will result in a 307 Redirect, and thus the victim will be redirected to target.com & the URL won’t contain the Set-Cookie parameter. In the background however, the cookie will be set. www.target.com/%0d%0aSet-Cookie:CRLFInjection=MaliciousCookieSet 3. Phishing AttacksAn attacker can set the Location header which would redirect the victim to the evil website. This website can be developed to look just like the target website and when the victim enters their credentials, they’ll be sent to the attacker. The location header can be set as: GET /%0d%0aLocation:%20https://evil.com HTTP/1.1 4. Session FixationSimilar to the Cookie Injection attack, here the attacker sets a user’s session id to a particular value. This link is sent to the victim and when the victim logs in using this session, the attacker can also log in by using the same session id. www.target.com/%0d%0aSet-Cookie:session_id=942.... 5. HTTP Header InjectionAn attacker can leverage the CRLF injection to inject HTTP Headers in an application in order to defeat security mechanisms such XSS filters or the same-origin-policy. www.target.com/%0d%0aHackersHeader:NewHeader CORS (Cross Origin Resource Sharing) activating headers can be injected & the attacker can use JavaScript to access sensitive resources that are otherwise protected by SOP (Same Origin Policy) which prevents sites from different origins to access each other. 6. Web Cache poisoningWeb-cache poisoning is a technique due to which an attacker can serve poisoned content by manipulating a web cache. In order to successfully exploit this issue, an attacker would need to poison the vulnerable website’s caching proxy, syndicators, content delivery networks (CDNs) or other caching mechanisms in-between the client and the server. After a successful web cache poisoning, the victim will have no idea about the malicious content being served to them by the cache. The below is an example of how an attacker could potentially exploit a host header injection (using CRLF) by poisoning a web-cache. For the following Request: $ telnet www.target.com 80 Trying x.x.x.x... Connected to www.target.com. Escape character is '^]'. GET /%0d%0aX-Forwarded-Host:hacker.com HTTP/1.1 //or Host Host: target.com There would be the following response: HTTP/1.1 200 OK html <title>Example</title><script src="http://hacker.com/script.js"> 1. Injecting a fake HTTP response header: Content-Length: 10 Now, the web browser will only parse the next 10 bytes. 2. Injecting a fake HTTP response header: Content-Length: 0 This is treated as a terminated response & the web browsers begin parsing a new response. A developer should keep the following things in mind to prevent CRLF injection: Sanitization of user input. Encode CR & LF characters (\r, \n) so that even when they’re supplied, they aren’t recognized by the server. Validate the user input before they reach the response headers (e.g. by using methods like StringEscapeUtils.escapeJava()). An unnecessary header should be disabled.The following table emphasizes the severity of CRLF injection according to various industry standards: Cyber-security Information-Security Advanced Computer Subject Linux-Unix Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. System Design Tutorial ML | Linear Regression Reinforcement learning Docker - COPY Instruction Supervised and Unsupervised learning Sed Command in Linux/Unix with examples AWK command in Unix/Linux with examples grep command in Unix/Linux cut command in Linux with examples cp command in Linux with examples
[ { "code": null, "e": 28, "s": 0, "text": "\n07 Sep, 2020" }, { "code": null, "e": 1001, "s": 28, "text": "CRLF is the acronym used to refer to Carriage Return (\\r) Line Feed (\\n). As one might notice from the symbols in the brackets, “Carriage Return” refers to the end of a line, and “Line Feed” refers to the new line. Hence, both CR and LF are used to denote the ending point of a line. When a user requests content on a website, the server returns the website content along with the HTTP headers. The headers and the contents are separated by a defined combination of CR and LF. It is because of CRLF that a server knows where a new header begins or ends. A Carriage Return Line Feed (CRLF) Injection vulnerability is a type of Server Side Injection which occurs when an attacker inserts the CRLF characters in an input field to deceive the server by making it think that an object has terminated and a new one has begun. This happens when the web application doesn’t sanitize user input for CRLF characters. It has a medium severity rating (P3 according to Bugcrowd’s VRT)." }, { "code": null, "e": 1057, "s": 1001, "text": "CRLF Injection attack has two most important use cases:" }, { "code": null, "e": 1239, "s": 1057, "text": "Log Splitting: The attacker inserts an end of line character and an extra line to falsify the log file entries in order to deceive the system administrators by hiding other attacks." }, { "code": null, "e": 1406, "s": 1239, "text": "HTTP Response Splitting: CRLF injection is used to add HTTP headers to the HTTP response and, for example, perform an XSS attack that leads to information disclosure." }, { "code": null, "e": 1416, "s": 1406, "text": "Example: " }, { "code": null, "e": 1464, "s": 1416, "text": "A simple GET request can be crafted as follows:" }, { "code": null, "e": 1523, "s": 1464, "text": "GET /%0d%0aSet-Cookie:CRLFInjection=PreritPathak HTTP/1.1\n" }, { "code": null, "e": 1682, "s": 1523, "text": "Note: %0d and %0a are encoded forms of \\r and \\n respectively. If the web application is vulnerable, an attacker will be able to set a cookie on the website. " }, { "code": null, "e": 2012, "s": 1682, "text": "CRLF Injection allows the attacker to set fake cookies, steal CSRF tokens, disclose user information by injecting a script (XSS) and perform a variety of other attacks. It also allows attackers to deactivate & bypass security measures like XSS filters & Same Origin Policy (SOP), making them susceptible to the following attacks:" }, { "code": null, "e": 2328, "s": 2012, "text": "1. XSS or Cross Site ScriptingXSS or Cross Site Scripting is a security vulnerability which allows an attacker to inject malicious JavaScript code into the web application. The following GET requests are crafted in an attempt chain CRLF Injection with XSS. By Popping an alert containing sensitive user information " }, { "code": null, "e": 2480, "s": 2328, "text": "www.target.com/%3f%0d%0aLocation:%0d%0aContent-Type:text/html%0d%0aX-XSS-Protection%3a0%0d%0a%0d%0a%3Cscript%3Ealert%28document.domain%29%3C/script%3E\n" }, { "code": null, "e": 2509, "s": 2480, "text": "By Disabling XSS Protection " }, { "code": null, "e": 2587, "s": 2509, "text": "www.target.com/%0d%0aContent-Length:35%0d%0aX-XSS-Protection:0%0d%0a%0d%0a23\n" }, { "code": null, "e": 2926, "s": 2587, "text": "2. Cookie InjectionHTTP Response Splitting allows an attacker to set malicious cookies on the victim’s browser. In most cases, the following GET request will result in a 307 Redirect, and thus the victim will be redirected to target.com & the URL won’t contain the Set-Cookie parameter. In the background however, the cookie will be set. " }, { "code": null, "e": 2992, "s": 2926, "text": "www.target.com/%0d%0aSet-Cookie:CRLFInjection=MaliciousCookieSet\n" }, { "code": null, "e": 3285, "s": 2992, "text": "3. Phishing AttacksAn attacker can set the Location header which would redirect the victim to the evil website. This website can be developed to look just like the target website and when the victim enters their credentials, they’ll be sent to the attacker. The location header can be set as:" }, { "code": null, "e": 3335, "s": 3285, "text": "GET /%0d%0aLocation:%20https://evil.com HTTP/1.1\n" }, { "code": null, "e": 3600, "s": 3335, "text": "4. Session FixationSimilar to the Cookie Injection attack, here the attacker sets a user’s session id to a particular value. This link is sent to the victim and when the victim logs in using this session, the attacker can also log in by using the same session id. " }, { "code": null, "e": 3652, "s": 3600, "text": "www.target.com/%0d%0aSet-Cookie:session_id=942....\n" }, { "code": null, "e": 3845, "s": 3652, "text": "5. HTTP Header InjectionAn attacker can leverage the CRLF injection to inject HTTP Headers in an application in order to defeat security mechanisms such XSS filters or the same-origin-policy. " }, { "code": null, "e": 3891, "s": 3845, "text": "www.target.com/%0d%0aHackersHeader:NewHeader\n" }, { "code": null, "e": 4782, "s": 3891, "text": "CORS (Cross Origin Resource Sharing) activating headers can be injected & the attacker can use JavaScript to access sensitive resources that are otherwise protected by SOP (Same Origin Policy) which prevents sites from different origins to access each other. 6. Web Cache poisoningWeb-cache poisoning is a technique due to which an attacker can serve poisoned content by manipulating a web cache. In order to successfully exploit this issue, an attacker would need to poison the vulnerable website’s caching proxy, syndicators, content delivery networks (CDNs) or other caching mechanisms in-between the client and the server. After a successful web cache poisoning, the victim will have no idea about the malicious content being served to them by the cache. The below is an example of how an attacker could potentially exploit a host header injection (using CRLF) by poisoning a web-cache." }, { "code": null, "e": 4810, "s": 4782, "text": "For the following Request: " }, { "code": null, "e": 4990, "s": 4810, "text": "$ telnet www.target.com 80\nTrying x.x.x.x...\nConnected to www.target.com.\nEscape character is '^]'.\nGET /%0d%0aX-Forwarded-Host:hacker.com HTTP/1.1 //or Host\nHost: target.com\n" }, { "code": null, "e": 5030, "s": 4990, "text": "There would be the following response: " }, { "code": null, "e": 5047, "s": 5030, "text": "HTTP/1.1 200 OK\n" }, { "code": null, "e": 5052, "s": 5047, "text": "html" }, { "code": "<title>Example</title><script src=\"http://hacker.com/script.js\">", "e": 5117, "s": 5052, "text": null }, { "code": null, "e": 5160, "s": 5117, "text": "1. Injecting a fake HTTP response header: " }, { "code": null, "e": 5180, "s": 5160, "text": "Content-Length: 10\n" }, { "code": null, "e": 5279, "s": 5180, "text": "Now, the web browser will only parse the next 10 bytes. 2. Injecting a fake HTTP response header: " }, { "code": null, "e": 5298, "s": 5279, "text": "Content-Length: 0\n" }, { "code": null, "e": 5388, "s": 5298, "text": "This is treated as a terminated response & the web browsers begin parsing a new response." }, { "code": null, "e": 5468, "s": 5388, "text": "A developer should keep the following things in mind to prevent CRLF injection:" }, { "code": null, "e": 5496, "s": 5468, "text": "Sanitization of user input." }, { "code": null, "e": 5605, "s": 5496, "text": "Encode CR & LF characters (\\r, \\n) so that even when they’re supplied, they aren’t recognized by the server." }, { "code": null, "e": 5729, "s": 5605, "text": "Validate the user input before they reach the response headers (e.g. by using methods like StringEscapeUtils.escapeJava())." }, { "code": null, "e": 5875, "s": 5729, "text": "An unnecessary header should be disabled.The following table emphasizes the severity of CRLF injection according to various industry standards: " }, { "code": null, "e": 5890, "s": 5875, "text": "Cyber-security" }, { "code": null, "e": 5911, "s": 5890, "text": "Information-Security" }, { "code": null, "e": 5937, "s": 5911, "text": "Advanced Computer Subject" }, { "code": null, "e": 5948, "s": 5937, "text": "Linux-Unix" }, { "code": null, "e": 6046, "s": 5948, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 6069, "s": 6046, "text": "System Design Tutorial" }, { "code": null, "e": 6092, "s": 6069, "text": "ML | Linear Regression" }, { "code": null, "e": 6115, "s": 6092, "text": "Reinforcement learning" }, { "code": null, "e": 6141, "s": 6115, "text": "Docker - COPY Instruction" }, { "code": null, "e": 6178, "s": 6141, "text": "Supervised and Unsupervised learning" }, { "code": null, "e": 6218, "s": 6178, "text": "Sed Command in Linux/Unix with examples" }, { "code": null, "e": 6258, "s": 6218, "text": "AWK command in Unix/Linux with examples" }, { "code": null, "e": 6285, "s": 6258, "text": "grep command in Unix/Linux" }, { "code": null, "e": 6320, "s": 6285, "text": "cut command in Linux with examples" } ]
JQuery | inArray() method
22 Apr, 2020 This inArray() Method in jQuery is used to search for a specific value in an array and return its index (or -1 if not found). Syntax: jQuery.inArray(val, arr [, Index]) Parameters: The inArray() method accepts few parameters that are mentioned above and described below: val: The value to search in an array. arr: Any array like object. Index: Index of the array from which to begin search. Return Value: It returns the index of the element in an array. Example 1: In this example, the inArray() method searches the element ‘geek’ in the array.<!DOCTYPE HTML> <html> <head> <title> JQuery | inArray() method </title> <script src = "https://ajax.googleapis.com/ajax/libs/jquery/3.4.0/jquery.min.js"> </script></head> <body style="text-align:center;"> <h1 style="color: green"> GeeksForGeeks </h1> <p id="GFG_UP"></p> <button onclick="gfg_Run()"> Click Here </button> <p id="GFG_DOWN" style="color:green;"></p> <script> var el_up = document.getElementById("GFG_UP"); var el_down = document.getElementById("GFG_DOWN"); var arr = ["GFG", "GeeksForGeeks", "Geek", "Geeks"]; var val = "Geek"; el_up.innerHTML = "Click on the button to " + "search the element.<br>" + "Array - [" + arr + "]<br>Element - '" + val + "'"; function gfg_Run() { el_down.innerHTML = $.inArray(val, arr); } </script> </body> </html> <!DOCTYPE HTML> <html> <head> <title> JQuery | inArray() method </title> <script src = "https://ajax.googleapis.com/ajax/libs/jquery/3.4.0/jquery.min.js"> </script></head> <body style="text-align:center;"> <h1 style="color: green"> GeeksForGeeks </h1> <p id="GFG_UP"></p> <button onclick="gfg_Run()"> Click Here </button> <p id="GFG_DOWN" style="color:green;"></p> <script> var el_up = document.getElementById("GFG_UP"); var el_down = document.getElementById("GFG_DOWN"); var arr = ["GFG", "GeeksForGeeks", "Geek", "Geeks"]; var val = "Geek"; el_up.innerHTML = "Click on the button to " + "search the element.<br>" + "Array - [" + arr + "]<br>Element - '" + val + "'"; function gfg_Run() { el_down.innerHTML = $.inArray(val, arr); } </script> </body> </html> Output: Example 2: In this example, the inArray() method searches the element ‘geek’ in the array as in the previous example. But, index attribute is also passed to search the element from index 3 and return -1.<!DOCTYPE HTML> <html> <head> <title> JQuery | inArray() method </title> <script src = "https://ajax.googleapis.com/ajax/libs/jquery/3.4.0/jquery.min.js"> </script></head> <body style="text-align:center;"> <h1 style="color: green"> GeeksForGeeks </h1> <p id="GFG_UP"></p> <button onclick="gfg_Run()"> Click Here </button> <p id="GFG_DOWN" style="color:green;"></p> <script> var el_up = document.getElementById("GFG_UP"); var el_down = document.getElementById("GFG_DOWN"); var arr = ["GFG", "GeeksForGeeks", "Geek", "Geeks"]; var val = "Geek"; el_up.innerHTML = "Click on the button to search" + "the element.<br>Array - [" + arr + "]<br>Element - '" + val + "'"; function gfg_Run() { el_down.innerHTML = $.inArray(val, arr, 3); } </script> </body> </html> <!DOCTYPE HTML> <html> <head> <title> JQuery | inArray() method </title> <script src = "https://ajax.googleapis.com/ajax/libs/jquery/3.4.0/jquery.min.js"> </script></head> <body style="text-align:center;"> <h1 style="color: green"> GeeksForGeeks </h1> <p id="GFG_UP"></p> <button onclick="gfg_Run()"> Click Here </button> <p id="GFG_DOWN" style="color:green;"></p> <script> var el_up = document.getElementById("GFG_UP"); var el_down = document.getElementById("GFG_DOWN"); var arr = ["GFG", "GeeksForGeeks", "Geek", "Geeks"]; var val = "Geek"; el_up.innerHTML = "Click on the button to search" + "the element.<br>Array - [" + arr + "]<br>Element - '" + val + "'"; function gfg_Run() { el_down.innerHTML = $.inArray(val, arr, 3); } </script> </body> </html> Output: jQuery-Methods JavaScript JQuery Web Technologies Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Difference between var, let and const keywords in JavaScript Differences between Functional Components and Class Components in React Remove elements from a JavaScript Array Difference Between PUT and PATCH Request How to Open URL in New Tab using JavaScript ? JQuery | Set the value of an input text field Form validation using jQuery How to change selected value of a drop-down list using jQuery? How to add options to a select element using jQuery? How to fetch data from JSON file and display in HTML table using jQuery ?
[ { "code": null, "e": 28, "s": 0, "text": "\n22 Apr, 2020" }, { "code": null, "e": 154, "s": 28, "text": "This inArray() Method in jQuery is used to search for a specific value in an array and return its index (or -1 if not found)." }, { "code": null, "e": 162, "s": 154, "text": "Syntax:" }, { "code": null, "e": 198, "s": 162, "text": "jQuery.inArray(val, arr [, Index])\n" }, { "code": null, "e": 300, "s": 198, "text": "Parameters: The inArray() method accepts few parameters that are mentioned above and described below:" }, { "code": null, "e": 338, "s": 300, "text": "val: The value to search in an array." }, { "code": null, "e": 366, "s": 338, "text": "arr: Any array like object." }, { "code": null, "e": 420, "s": 366, "text": "Index: Index of the array from which to begin search." }, { "code": null, "e": 483, "s": 420, "text": "Return Value: It returns the index of the element in an array." }, { "code": null, "e": 1604, "s": 483, "text": "Example 1: In this example, the inArray() method searches the element ‘geek’ in the array.<!DOCTYPE HTML> <html> <head> <title> JQuery | inArray() method </title> <script src = \"https://ajax.googleapis.com/ajax/libs/jquery/3.4.0/jquery.min.js\"> </script></head> <body style=\"text-align:center;\"> <h1 style=\"color: green\"> GeeksForGeeks </h1> <p id=\"GFG_UP\"></p> <button onclick=\"gfg_Run()\"> Click Here </button> <p id=\"GFG_DOWN\" style=\"color:green;\"></p> <script> var el_up = document.getElementById(\"GFG_UP\"); var el_down = document.getElementById(\"GFG_DOWN\"); var arr = [\"GFG\", \"GeeksForGeeks\", \"Geek\", \"Geeks\"]; var val = \"Geek\"; el_up.innerHTML = \"Click on the button to \" + \"search the element.<br>\" + \"Array - [\" + arr + \"]<br>Element - '\" + val + \"'\"; function gfg_Run() { el_down.innerHTML = $.inArray(val, arr); } </script> </body> </html>" }, { "code": "<!DOCTYPE HTML> <html> <head> <title> JQuery | inArray() method </title> <script src = \"https://ajax.googleapis.com/ajax/libs/jquery/3.4.0/jquery.min.js\"> </script></head> <body style=\"text-align:center;\"> <h1 style=\"color: green\"> GeeksForGeeks </h1> <p id=\"GFG_UP\"></p> <button onclick=\"gfg_Run()\"> Click Here </button> <p id=\"GFG_DOWN\" style=\"color:green;\"></p> <script> var el_up = document.getElementById(\"GFG_UP\"); var el_down = document.getElementById(\"GFG_DOWN\"); var arr = [\"GFG\", \"GeeksForGeeks\", \"Geek\", \"Geeks\"]; var val = \"Geek\"; el_up.innerHTML = \"Click on the button to \" + \"search the element.<br>\" + \"Array - [\" + arr + \"]<br>Element - '\" + val + \"'\"; function gfg_Run() { el_down.innerHTML = $.inArray(val, arr); } </script> </body> </html>", "e": 2635, "s": 1604, "text": null }, { "code": null, "e": 2643, "s": 2635, "text": "Output:" }, { "code": null, "e": 3812, "s": 2643, "text": "Example 2: In this example, the inArray() method searches the element ‘geek’ in the array as in the previous example. But, index attribute is also passed to search the element from index 3 and return -1.<!DOCTYPE HTML> <html> <head> <title> JQuery | inArray() method </title> <script src = \"https://ajax.googleapis.com/ajax/libs/jquery/3.4.0/jquery.min.js\"> </script></head> <body style=\"text-align:center;\"> <h1 style=\"color: green\"> GeeksForGeeks </h1> <p id=\"GFG_UP\"></p> <button onclick=\"gfg_Run()\"> Click Here </button> <p id=\"GFG_DOWN\" style=\"color:green;\"></p> <script> var el_up = document.getElementById(\"GFG_UP\"); var el_down = document.getElementById(\"GFG_DOWN\"); var arr = [\"GFG\", \"GeeksForGeeks\", \"Geek\", \"Geeks\"]; var val = \"Geek\"; el_up.innerHTML = \"Click on the button to search\" + \"the element.<br>Array - [\" + arr + \"]<br>Element - '\" + val + \"'\"; function gfg_Run() { el_down.innerHTML = $.inArray(val, arr, 3); } </script> </body> </html>" }, { "code": "<!DOCTYPE HTML> <html> <head> <title> JQuery | inArray() method </title> <script src = \"https://ajax.googleapis.com/ajax/libs/jquery/3.4.0/jquery.min.js\"> </script></head> <body style=\"text-align:center;\"> <h1 style=\"color: green\"> GeeksForGeeks </h1> <p id=\"GFG_UP\"></p> <button onclick=\"gfg_Run()\"> Click Here </button> <p id=\"GFG_DOWN\" style=\"color:green;\"></p> <script> var el_up = document.getElementById(\"GFG_UP\"); var el_down = document.getElementById(\"GFG_DOWN\"); var arr = [\"GFG\", \"GeeksForGeeks\", \"Geek\", \"Geeks\"]; var val = \"Geek\"; el_up.innerHTML = \"Click on the button to search\" + \"the element.<br>Array - [\" + arr + \"]<br>Element - '\" + val + \"'\"; function gfg_Run() { el_down.innerHTML = $.inArray(val, arr, 3); } </script> </body> </html>", "e": 4778, "s": 3812, "text": null }, { "code": null, "e": 4786, "s": 4778, "text": "Output:" }, { "code": null, "e": 4801, "s": 4786, "text": "jQuery-Methods" }, { "code": null, "e": 4812, "s": 4801, "text": "JavaScript" }, { "code": null, "e": 4819, "s": 4812, "text": "JQuery" }, { "code": null, "e": 4836, "s": 4819, "text": "Web Technologies" }, { "code": null, "e": 4934, "s": 4836, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 4995, "s": 4934, "text": "Difference between var, let and const keywords in JavaScript" }, { "code": null, "e": 5067, "s": 4995, "text": "Differences between Functional Components and Class Components in React" }, { "code": null, "e": 5107, "s": 5067, "text": "Remove elements from a JavaScript Array" }, { "code": null, "e": 5148, "s": 5107, "text": "Difference Between PUT and PATCH Request" }, { "code": null, "e": 5194, "s": 5148, "text": "How to Open URL in New Tab using JavaScript ?" }, { "code": null, "e": 5240, "s": 5194, "text": "JQuery | Set the value of an input text field" }, { "code": null, "e": 5269, "s": 5240, "text": "Form validation using jQuery" }, { "code": null, "e": 5332, "s": 5269, "text": "How to change selected value of a drop-down list using jQuery?" }, { "code": null, "e": 5385, "s": 5332, "text": "How to add options to a select element using jQuery?" } ]
Convert First letter of every word to Uppercase in R Programming – str_to_title() Function
03 Jun, 2020 str_to_title() Function in R Language is used to convert the first letter of every word of a string to Uppercase and the rest of the letters are converted to lower case. Note: This function uses 'stringr' library. Syntax: str_to_title(string) Parameter:string: string to be converted Example 1: # R Program to illustrate # the use of str_to_title function # Loading Librarylibrary(stringr) # Creating a stringstr <- "geeks for geeks" # Calling str_to_title() functionstr_to_title(str) Output: [1] "Geeks For Geeks" Example 2: # R Program to illustrate # the use of str_to_title function # Loading Librarylibrary(stringr) # Creating a stringstr <- "GEEKS FOR GEEKS" # Calling str_to_title() functionstr_to_title(str) Output: [1] "Geeks For Geeks" R String-Functions R Language Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Filter data by multiple conditions in R using Dplyr Change Color of Bars in Barchart using ggplot2 in R How to Split Column Into Multiple Columns in R DataFrame? Loops in R (for, while, repeat) Group by function in R using Dplyr How to change Row Names of DataFrame in R ? How to Change Axis Scales in R Plots? How to filter R DataFrame by values in a column? R - if statement Remove rows with NA in one column of R DataFrame
[ { "code": null, "e": 28, "s": 0, "text": "\n03 Jun, 2020" }, { "code": null, "e": 198, "s": 28, "text": "str_to_title() Function in R Language is used to convert the first letter of every word of a string to Uppercase and the rest of the letters are converted to lower case." }, { "code": null, "e": 242, "s": 198, "text": "Note: This function uses 'stringr' library." }, { "code": null, "e": 271, "s": 242, "text": "Syntax: str_to_title(string)" }, { "code": null, "e": 312, "s": 271, "text": "Parameter:string: string to be converted" }, { "code": null, "e": 323, "s": 312, "text": "Example 1:" }, { "code": "# R Program to illustrate # the use of str_to_title function # Loading Librarylibrary(stringr) # Creating a stringstr <- \"geeks for geeks\" # Calling str_to_title() functionstr_to_title(str) ", "e": 517, "s": 323, "text": null }, { "code": null, "e": 525, "s": 517, "text": "Output:" }, { "code": null, "e": 548, "s": 525, "text": "[1] \"Geeks For Geeks\"\n" }, { "code": null, "e": 559, "s": 548, "text": "Example 2:" }, { "code": "# R Program to illustrate # the use of str_to_title function # Loading Librarylibrary(stringr) # Creating a stringstr <- \"GEEKS FOR GEEKS\" # Calling str_to_title() functionstr_to_title(str) ", "e": 753, "s": 559, "text": null }, { "code": null, "e": 761, "s": 753, "text": "Output:" }, { "code": null, "e": 784, "s": 761, "text": "[1] \"Geeks For Geeks\"\n" }, { "code": null, "e": 803, "s": 784, "text": "R String-Functions" }, { "code": null, "e": 814, "s": 803, "text": "R Language" }, { "code": null, "e": 912, "s": 814, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 964, "s": 912, "text": "Filter data by multiple conditions in R using Dplyr" }, { "code": null, "e": 1016, "s": 964, "text": "Change Color of Bars in Barchart using ggplot2 in R" }, { "code": null, "e": 1074, "s": 1016, "text": "How to Split Column Into Multiple Columns in R DataFrame?" }, { "code": null, "e": 1106, "s": 1074, "text": "Loops in R (for, while, repeat)" }, { "code": null, "e": 1141, "s": 1106, "text": "Group by function in R using Dplyr" }, { "code": null, "e": 1185, "s": 1141, "text": "How to change Row Names of DataFrame in R ?" }, { "code": null, "e": 1223, "s": 1185, "text": "How to Change Axis Scales in R Plots?" }, { "code": null, "e": 1272, "s": 1223, "text": "How to filter R DataFrame by values in a column?" }, { "code": null, "e": 1289, "s": 1272, "text": "R - if statement" } ]
Dplyr – Groupby on multiple columns using variable names in R
23 Sep, 2021 The group_by() method is used to group the data contained in the data frame based on the columns specified as arguments to the function call. The group_by() function takes as an argument, the across and all of the methods which has to be applied on the specified grouping over all the columns of the data frame. Syntax: group_by(col1, col2,..) This is followed by the application of summarize() function, which is used to generate summary statistics over the applied column. The column is renamed with the specified new name. The new column can be assigned any of the aggregate methods like mean(), sum(), etc. Let us first look at a simpler approach, and apply groupby to only one column. Example: Groupby on single column using variable names R library(data.table)library(dplyr) # creating first data framedata_frame <- data.table(col1 = rep(LETTERS[1:3],each=2), col2 = c(1,1,3,4,5,6), col3 = 1 ) print ("Original DataFrame")print (data_frame) # deciding the column to group bygrp <- c('col1') # calculating mean of col2 based on col1 groupdata_frame %>% group_by(across(all_of(grp))) %>% summarize(mean_col2 = mean(col2)) Output [1] "Original DataFrame" col1 col2 col3 1: A 1 1 2: A 1 1 3: B 3 1 4: B 4 1 5: C 5 1 6: C 6 1 # A tibble: 3 x 2 col1 mean_col2 <chr> <dbl> 1 A 1 2 B 3.5 3 C 5.5 Since there are three groups, A, B, and C, the mean is calculated for each of these three groups. Example: Applying group_by over multiple columns using the variable name R library(data.table)library(dplyr) # creating first data framedata_frame <- data.table(col1 = rep(LETTERS[1:3],each=2), col2 = c(1,1,3,4,5,6), col3 = 1 ) print ("Original DataFrame")print (data_frame) # deciding the column to group bygrp <- c('col1','col2') # calculating mean of col2 based on col1 groupdata_frame %>% group_by(across(all_of(grp))) %>% summarize(mean_col2 = sum(col2)) Output # A tibble: 5 x 3 # Groups: col1 [3] col1 col2 mean_col2 <chr> <dbl> <dbl> 1 A 1 2 2 B 3 3 3 B 4 4 4 C 5 5 5 C 6 6 Picked R Dplyr R Language Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n23 Sep, 2021" }, { "code": null, "e": 341, "s": 28, "text": "The group_by() method is used to group the data contained in the data frame based on the columns specified as arguments to the function call. The group_by() function takes as an argument, the across and all of the methods which has to be applied on the specified grouping over all the columns of the data frame. " }, { "code": null, "e": 349, "s": 341, "text": "Syntax:" }, { "code": null, "e": 373, "s": 349, "text": "group_by(col1, col2,..)" }, { "code": null, "e": 719, "s": 373, "text": "This is followed by the application of summarize() function, which is used to generate summary statistics over the applied column. The column is renamed with the specified new name. The new column can be assigned any of the aggregate methods like mean(), sum(), etc. Let us first look at a simpler approach, and apply groupby to only one column." }, { "code": null, "e": 774, "s": 719, "text": "Example: Groupby on single column using variable names" }, { "code": null, "e": 776, "s": 774, "text": "R" }, { "code": "library(data.table)library(dplyr) # creating first data framedata_frame <- data.table(col1 = rep(LETTERS[1:3],each=2), col2 = c(1,1,3,4,5,6), col3 = 1 ) print (\"Original DataFrame\")print (data_frame) # deciding the column to group bygrp <- c('col1') # calculating mean of col2 based on col1 groupdata_frame %>% group_by(across(all_of(grp))) %>% summarize(mean_col2 = mean(col2))", "e": 1234, "s": 776, "text": null }, { "code": null, "e": 1241, "s": 1234, "text": "Output" }, { "code": null, "e": 1510, "s": 1241, "text": "[1] \"Original DataFrame\" \ncol1 col2 col3 \n1: A 1 1 \n2: A 1 1 \n3: B 3 1 \n4: B 4 1 \n5: C 5 1 \n6: C 6 1 \n# A tibble: 3 x 2 \ncol1 mean_col2 \n<chr> <dbl> \n1 A 1 \n2 B 3.5 \n3 C 5.5" }, { "code": null, "e": 1609, "s": 1510, "text": "Since there are three groups, A, B, and C, the mean is calculated for each of these three groups. " }, { "code": null, "e": 1682, "s": 1609, "text": "Example: Applying group_by over multiple columns using the variable name" }, { "code": null, "e": 1684, "s": 1682, "text": "R" }, { "code": "library(data.table)library(dplyr) # creating first data framedata_frame <- data.table(col1 = rep(LETTERS[1:3],each=2), col2 = c(1,1,3,4,5,6), col3 = 1 ) print (\"Original DataFrame\")print (data_frame) # deciding the column to group bygrp <- c('col1','col2') # calculating mean of col2 based on col1 groupdata_frame %>% group_by(across(all_of(grp))) %>% summarize(mean_col2 = sum(col2))", "e": 2148, "s": 1684, "text": null }, { "code": null, "e": 2155, "s": 2148, "text": "Output" }, { "code": null, "e": 2370, "s": 2155, "text": "# A tibble: 5 x 3 \n# Groups: col1 [3] \ncol1 col2 mean_col2 \n<chr> <dbl> <dbl> \n1 A 1 2 \n2 B 3 3 \n3 B 4 4 \n4 C 5 5 \n5 C 6 6" }, { "code": null, "e": 2377, "s": 2370, "text": "Picked" }, { "code": null, "e": 2385, "s": 2377, "text": "R Dplyr" }, { "code": null, "e": 2396, "s": 2385, "text": "R Language" } ]
Tensorflow | tf.data.Dataset.reduce()
03 Oct, 2019 With the help of tf.data.Dataset.reduce() method, we can get the reduced transformation of all the elements in the dataset by using tf.data.Dataset.reduce() method. Syntax : tf.data.Dataset.reduce()Return : Return combined single result after transformation. Note :These given examples will demonstrate the use of new version of tensorflow 2.0, so if you want to run these examples please run the following commands in command prompt. pip install tensorflow==2.0.0-rc2 Example #1 :In this example we can see that by using tf.data.Dataset.reduce() method, we are able to get the reduced transformation of all the elements from the dataset. # import tensorflowimport tensorflow as tf # using tf.data.Dataset.reduce() methodgfg = tf.data.Dataset.from_tensor_slices([1, 2, 3, 4, 5]) print(gfg.reduce(0, lambda x, y: x + y).numpy()) Output : 15 Example #2 : # import tensorflowimport tensorflow as tf # using tf.data.Dataset.reduce() methodgfg = tf.data.Dataset.from_tensor_slices([[5, 10], [3, 6]]) print(gfg.reduce(0, lambda x, y: x * y).numpy()) Output : [15, 60] Tensorflow Python Technical Scripter Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to Install PIP on Windows ? Python Classes and Objects Python OOPs Concepts Introduction To PYTHON How to drop one or multiple columns in Pandas Dataframe Check if element exists in list in Python Python | os.path.join() method How To Convert Python Dictionary To JSON? Python | Get unique values from a list Defaultdict in Python
[ { "code": null, "e": 28, "s": 0, "text": "\n03 Oct, 2019" }, { "code": null, "e": 193, "s": 28, "text": "With the help of tf.data.Dataset.reduce() method, we can get the reduced transformation of all the elements in the dataset by using tf.data.Dataset.reduce() method." }, { "code": null, "e": 287, "s": 193, "text": "Syntax : tf.data.Dataset.reduce()Return : Return combined single result after transformation." }, { "code": null, "e": 463, "s": 287, "text": "Note :These given examples will demonstrate the use of new version of tensorflow 2.0, so if you want to run these examples please run the following commands in command prompt." }, { "code": null, "e": 497, "s": 463, "text": "pip install tensorflow==2.0.0-rc2" }, { "code": null, "e": 667, "s": 497, "text": "Example #1 :In this example we can see that by using tf.data.Dataset.reduce() method, we are able to get the reduced transformation of all the elements from the dataset." }, { "code": "# import tensorflowimport tensorflow as tf # using tf.data.Dataset.reduce() methodgfg = tf.data.Dataset.from_tensor_slices([1, 2, 3, 4, 5]) print(gfg.reduce(0, lambda x, y: x + y).numpy())", "e": 858, "s": 667, "text": null }, { "code": null, "e": 867, "s": 858, "text": "Output :" }, { "code": null, "e": 870, "s": 867, "text": "15" }, { "code": null, "e": 883, "s": 870, "text": "Example #2 :" }, { "code": "# import tensorflowimport tensorflow as tf # using tf.data.Dataset.reduce() methodgfg = tf.data.Dataset.from_tensor_slices([[5, 10], [3, 6]]) print(gfg.reduce(0, lambda x, y: x * y).numpy())", "e": 1076, "s": 883, "text": null }, { "code": null, "e": 1085, "s": 1076, "text": "Output :" }, { "code": null, "e": 1094, "s": 1085, "text": "[15, 60]" }, { "code": null, "e": 1105, "s": 1094, "text": "Tensorflow" }, { "code": null, "e": 1112, "s": 1105, "text": "Python" }, { "code": null, "e": 1131, "s": 1112, "text": "Technical Scripter" }, { "code": null, "e": 1229, "s": 1131, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 1261, "s": 1229, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 1288, "s": 1261, "text": "Python Classes and Objects" }, { "code": null, "e": 1309, "s": 1288, "text": "Python OOPs Concepts" }, { "code": null, "e": 1332, "s": 1309, "text": "Introduction To PYTHON" }, { "code": null, "e": 1388, "s": 1332, "text": "How to drop one or multiple columns in Pandas Dataframe" }, { "code": null, "e": 1430, "s": 1388, "text": "Check if element exists in list in Python" }, { "code": null, "e": 1461, "s": 1430, "text": "Python | os.path.join() method" }, { "code": null, "e": 1503, "s": 1461, "text": "How To Convert Python Dictionary To JSON?" }, { "code": null, "e": 1542, "s": 1503, "text": "Python | Get unique values from a list" } ]
WebViewScaffold in Flutter
30 Aug, 2020 WebViewScaffold is the flutter WebView plugin. If you want to open any web page without using your device’s browser then you can do it easily using WebViewScaffold widget. url: The url which we want to search. appBar: The add appBar in our flutter application. withZoom: If you allow your web page to zoom-in or zoom-out then put it true otherwise false. initialChild: It is used to add your own widget while webpage loads. hidden: If true then show us CircularProgressIndicator while webpage loads. Example: main.dart Dart import 'package:flutter/material.dart';import 'package:flutter_webview_plugin/flutter_webview_plugin.dart'; void main()=> runApp(MaterialApp( home:MyHomePage(), debugShowCheckedModeBanner: false, theme:ThemeData( primarySwatch: Colors.blue ))); class MyHomePage extends StatefulWidget { @override _MyHomePageState createState() => _MyHomePageState();} class _MyHomePageState extends State { TextEditingController controller=TextEditingController(); FlutterWebviewPlugin flutterWebviewPlugin= FlutterWebviewPlugin(); var url= "https://google.com"; @override void initState() { super.initState(); flutterWebviewPlugin.onStateChanged.listen((WebViewStateChanged wvs) {}); } searchURL(){ setState(() { url = "https://www."+controller.text; flutterWebviewPlugin.reloadUrl(url); controller.text=url; }); } @override Widget build(BuildContext context) { return WebviewScaffold( url: url, withZoom: true, hidden: true, // initialChild: Container( // child:Center(child: Text("Loading"),) // ), appBar: AppBar( backgroundColor: Colors.green, leading: Icon(Icons.search), title: TextField( controller: controller, textInputAction: TextInputAction.search, onSubmitted:(url)=>searchURL(), style: TextStyle( color: Colors.white ), decoration: InputDecoration( hintText: "Search Here", hintStyle: TextStyle(color: Colors.white) ), ), actions: [ IconButton(icon: Icon(Icons.arrow_back), onPressed: (){ flutterWebviewPlugin.goBack(); controller.text=""; } ), IconButton(icon: Icon(Icons.arrow_forward), onPressed: searchURL,), ], ), ); }} Output: Add flutter_webview_plugin in dependencies in pubspec.yaml file.Now come back to main.dart file.initially url is “https://google.com” and when app starts, this url will be loaded.When user type the url and press enter then searchURL() will be called and requested url will be loaded.If user wants to go back, press arrow_back key.If you want to add your own initial child then uncomment the initialChild and add your widget.set withZoom = true if you allow your webpage to zoom-in or zoom-out. Add flutter_webview_plugin in dependencies in pubspec.yaml file. Now come back to main.dart file. initially url is “https://google.com” and when app starts, this url will be loaded. When user type the url and press enter then searchURL() will be called and requested url will be loaded. If user wants to go back, press arrow_back key. If you want to add your own initial child then uncomment the initialChild and add your widget. set withZoom = true if you allow your webpage to zoom-in or zoom-out. Articles Dart Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 54, "s": 26, "text": "\n30 Aug, 2020" }, { "code": null, "e": 226, "s": 54, "text": "WebViewScaffold is the flutter WebView plugin. If you want to open any web page without using your device’s browser then you can do it easily using WebViewScaffold widget." }, { "code": null, "e": 264, "s": 226, "text": "url: The url which we want to search." }, { "code": null, "e": 315, "s": 264, "text": "appBar: The add appBar in our flutter application." }, { "code": null, "e": 409, "s": 315, "text": "withZoom: If you allow your web page to zoom-in or zoom-out then put it true otherwise false." }, { "code": null, "e": 478, "s": 409, "text": "initialChild: It is used to add your own widget while webpage loads." }, { "code": null, "e": 554, "s": 478, "text": "hidden: If true then show us CircularProgressIndicator while webpage loads." }, { "code": null, "e": 563, "s": 554, "text": "Example:" }, { "code": null, "e": 573, "s": 563, "text": "main.dart" }, { "code": null, "e": 578, "s": 573, "text": "Dart" }, { "code": "import 'package:flutter/material.dart';import 'package:flutter_webview_plugin/flutter_webview_plugin.dart'; void main()=> runApp(MaterialApp( home:MyHomePage(), debugShowCheckedModeBanner: false, theme:ThemeData( primarySwatch: Colors.blue ))); class MyHomePage extends StatefulWidget { @override _MyHomePageState createState() => _MyHomePageState();} class _MyHomePageState extends State { TextEditingController controller=TextEditingController(); FlutterWebviewPlugin flutterWebviewPlugin= FlutterWebviewPlugin(); var url= \"https://google.com\"; @override void initState() { super.initState(); flutterWebviewPlugin.onStateChanged.listen((WebViewStateChanged wvs) {}); } searchURL(){ setState(() { url = \"https://www.\"+controller.text; flutterWebviewPlugin.reloadUrl(url); controller.text=url; }); } @override Widget build(BuildContext context) { return WebviewScaffold( url: url, withZoom: true, hidden: true, // initialChild: Container( // child:Center(child: Text(\"Loading\"),) // ), appBar: AppBar( backgroundColor: Colors.green, leading: Icon(Icons.search), title: TextField( controller: controller, textInputAction: TextInputAction.search, onSubmitted:(url)=>searchURL(), style: TextStyle( color: Colors.white ), decoration: InputDecoration( hintText: \"Search Here\", hintStyle: TextStyle(color: Colors.white) ), ), actions: [ IconButton(icon: Icon(Icons.arrow_back), onPressed: (){ flutterWebviewPlugin.goBack(); controller.text=\"\"; } ), IconButton(icon: Icon(Icons.arrow_forward), onPressed: searchURL,), ], ), ); }}", "e": 2420, "s": 578, "text": null }, { "code": null, "e": 2428, "s": 2420, "text": "Output:" }, { "code": null, "e": 2923, "s": 2428, "text": "Add flutter_webview_plugin in dependencies in pubspec.yaml file.Now come back to main.dart file.initially url is “https://google.com” and when app starts, this url will be loaded.When user type the url and press enter then searchURL() will be called and requested url will be loaded.If user wants to go back, press arrow_back key.If you want to add your own initial child then uncomment the initialChild and add your widget.set withZoom = true if you allow your webpage to zoom-in or zoom-out." }, { "code": null, "e": 2988, "s": 2923, "text": "Add flutter_webview_plugin in dependencies in pubspec.yaml file." }, { "code": null, "e": 3021, "s": 2988, "text": "Now come back to main.dart file." }, { "code": null, "e": 3105, "s": 3021, "text": "initially url is “https://google.com” and when app starts, this url will be loaded." }, { "code": null, "e": 3210, "s": 3105, "text": "When user type the url and press enter then searchURL() will be called and requested url will be loaded." }, { "code": null, "e": 3259, "s": 3210, "text": "If user wants to go back, press arrow_back key." }, { "code": null, "e": 3354, "s": 3259, "text": "If you want to add your own initial child then uncomment the initialChild and add your widget." }, { "code": null, "e": 3424, "s": 3354, "text": "set withZoom = true if you allow your webpage to zoom-in or zoom-out." }, { "code": null, "e": 3433, "s": 3424, "text": "Articles" }, { "code": null, "e": 3438, "s": 3433, "text": "Dart" } ]
Splitting a PDF into many using Java
08 Dec, 2020 Program to split the PDF document into multiple PDFs. Below is the implementation for the same using JAVA. The prerequisite of this topic is that you have already installed apache library Approach: Load the PDF from the computer.Load the PDF using the class called PDDocument.Use load() function of PDdocument class to load the file. Load the PDF using the class called PDDocument. Use load() function of PDdocument class to load the file. Run the Splitter Class to split PDF.Splitter is a class used to split PDF.Use Split() function of the splitter class to split the PDF. Splitter is a class used to split PDF. Use Split() function of the splitter class to split the PDF. Using Iterator to count pages.Split the pages into many so that count the pages after the split() function, and use that to create a finite number of splits PDF.Save all the PDFs.Close the document. Split the pages into many so that count the pages after the split() function, and use that to create a finite number of splits PDF. Save all the PDFs. Close the document. Below is the implementation of the above approach: Java // Splitting a PDF in to many using Javaimport org.apache.pdfbox.multipdf.Splitter;import org.apache.pdfbox.pdmodel.PDDocument; import java.io.File;import java.io.IOException;import java.util.List;import java.util.Iterator; public class SplitPdf { public static void main(String[] args) throws IOException { // Loading PDF File pdffile = new File("C:/Desktop/Java/sample.pdf"); PDDocument document = PDDocument.load(pdffile); // Splitter Class Splitter splitting = new Splitter(); // Splitting the pages into multiple PDFs List<PDDocument> Page = splitting.split(document); // Using a iterator to Traverse all pages Iterator<PDDocument> iteration = Page.listIterator(); // Saving each page as an individual document int j = 1; while (iteration.hasNext()) { PDDocument pd = iteration.next(); pd.save("C:/Desktop/Java/Generated/sample-" + j++ + ".pdf"); } System.out.println("Splitted Pdf Successfully."); document.close(); }} Before the execution of the program: After execution of the program: Picked Java Java Programs Java Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Stream In Java Introduction to Java Constructors in Java Exceptions in Java Generics in Java Java Programming Examples Convert Double to Integer in Java Implementing a Linked List in Java using Class Factory method design pattern in Java Java Program to Remove Duplicate Elements From the Array
[ { "code": null, "e": 54, "s": 26, "text": "\n08 Dec, 2020" }, { "code": null, "e": 243, "s": 54, "text": "Program to split the PDF document into multiple PDFs. Below is the implementation for the same using JAVA. The prerequisite of this topic is that you have already installed apache library " }, { "code": null, "e": 253, "s": 243, "text": "Approach:" }, { "code": null, "e": 390, "s": 253, "text": "Load the PDF from the computer.Load the PDF using the class called PDDocument.Use load() function of PDdocument class to load the file. " }, { "code": null, "e": 438, "s": 390, "text": "Load the PDF using the class called PDDocument." }, { "code": null, "e": 497, "s": 438, "text": "Use load() function of PDdocument class to load the file. " }, { "code": null, "e": 633, "s": 497, "text": "Run the Splitter Class to split PDF.Splitter is a class used to split PDF.Use Split() function of the splitter class to split the PDF. " }, { "code": null, "e": 672, "s": 633, "text": "Splitter is a class used to split PDF." }, { "code": null, "e": 734, "s": 672, "text": "Use Split() function of the splitter class to split the PDF. " }, { "code": null, "e": 933, "s": 734, "text": "Using Iterator to count pages.Split the pages into many so that count the pages after the split() function, and use that to create a finite number of splits PDF.Save all the PDFs.Close the document." }, { "code": null, "e": 1065, "s": 933, "text": "Split the pages into many so that count the pages after the split() function, and use that to create a finite number of splits PDF." }, { "code": null, "e": 1084, "s": 1065, "text": "Save all the PDFs." }, { "code": null, "e": 1104, "s": 1084, "text": "Close the document." }, { "code": null, "e": 1155, "s": 1104, "text": "Below is the implementation of the above approach:" }, { "code": null, "e": 1160, "s": 1155, "text": "Java" }, { "code": "// Splitting a PDF in to many using Javaimport org.apache.pdfbox.multipdf.Splitter;import org.apache.pdfbox.pdmodel.PDDocument; import java.io.File;import java.io.IOException;import java.util.List;import java.util.Iterator; public class SplitPdf { public static void main(String[] args) throws IOException { // Loading PDF File pdffile = new File(\"C:/Desktop/Java/sample.pdf\"); PDDocument document = PDDocument.load(pdffile); // Splitter Class Splitter splitting = new Splitter(); // Splitting the pages into multiple PDFs List<PDDocument> Page = splitting.split(document); // Using a iterator to Traverse all pages Iterator<PDDocument> iteration = Page.listIterator(); // Saving each page as an individual document int j = 1; while (iteration.hasNext()) { PDDocument pd = iteration.next(); pd.save(\"C:/Desktop/Java/Generated/sample-\" + j++ + \".pdf\"); } System.out.println(\"Splitted Pdf Successfully.\"); document.close(); }}", "e": 2281, "s": 1160, "text": null }, { "code": null, "e": 2318, "s": 2281, "text": "Before the execution of the program:" }, { "code": null, "e": 2352, "s": 2320, "text": "After execution of the program:" }, { "code": null, "e": 2359, "s": 2352, "text": "Picked" }, { "code": null, "e": 2364, "s": 2359, "text": "Java" }, { "code": null, "e": 2378, "s": 2364, "text": "Java Programs" }, { "code": null, "e": 2383, "s": 2378, "text": "Java" }, { "code": null, "e": 2481, "s": 2383, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 2496, "s": 2481, "text": "Stream In Java" }, { "code": null, "e": 2517, "s": 2496, "text": "Introduction to Java" }, { "code": null, "e": 2538, "s": 2517, "text": "Constructors in Java" }, { "code": null, "e": 2557, "s": 2538, "text": "Exceptions in Java" }, { "code": null, "e": 2574, "s": 2557, "text": "Generics in Java" }, { "code": null, "e": 2600, "s": 2574, "text": "Java Programming Examples" }, { "code": null, "e": 2634, "s": 2600, "text": "Convert Double to Integer in Java" }, { "code": null, "e": 2681, "s": 2634, "text": "Implementing a Linked List in Java using Class" }, { "code": null, "e": 2719, "s": 2681, "text": "Factory method design pattern in Java" } ]
Maximum prefix-sum for a given range
20 May, 2021 Given an array of n integers and q queries, each query having a range from l to r. Find the maximum prefix-sum for the range l – r.Examples: Input: a[] = {-1, 2, 3, -5} q = 2 l = 0, r = 3 l = 1, r = 3 Output: 4 5 Explanation:- The range (0, 3) in the 1st query has [-1, 2, 3, -5], since it is prefix, we have to start from -1. Hence, the max prefix sum will be -1 + 2 + 3 = 4. The range (1, 3) in the 2nd query has [2, 3, -5], since it is prefix, we have to start from 2. Hence, the max prefix sum will be 2 + 3 = 5. Input: a[] = {-2, -3, 4, -1, -2, 1, 5, -3} q = 1 l = 1 r = 7 Output: 4 Explanation:- The range (1, 7) in the 1st query has [-3, 4, -1, -2, 1, 5, -3], since it is prefix, we have to start from -3. Hence, the max prefix sum will be -3 + 4 - 1 - 2 + 1 + 5 = 4. Normal Approach: A simple solution is to run a loop from l to r and calculate max prefix sum from l to r for every query.Time Complexity: O(q * n), Auxiliary Space: O(1)Efficient Approach: An efficient approach will be to build a segment tree where each node stores two values(sum and prefix_sum), and do a range query on it to find the max prefix sum. But for building the segment tree we have to think about what to store on the nodes of the tree. For finding out the maximum prefix sum, we will require two things, one being the sum and the other prefix sum. The merging will return two things, sum of the ranges and the prefix sum that will store the max(prefix.left, prefix.sum + prefix.right) in the segment tree.If we have a deep look into it, the max prefix sum for any two range combining will either be the prefix sum from left side or the sum of left side+prefix sum of right side, whichever is max is taken into account. Representation of Segment trees:1. Leaf Nodes are the elements of the input array. 2. Each internal node represents some merging of the leaf nodes. The merging may be different for different problems. For this problem, merging is sum of leaves under a node.An array representation of tree is used to represent Segment Trees. For each node at index i, the left child is at index 2*i+1, right child at 2*i+2 and the parent is at (i-1)/2.Construction of Segment Tree from given array:We start with a segment arr[0 . . . n-1]. and every time we divide the current segment into two halves(if it has not yet become a segment of length 1), and then call the same procedure on both halves, and for each such segment, we store the sum and prefix sum in corresponding node.We then do a range query on segment tree to find out the max prefix-sum for the given range, and output the max prefix-sum.Below is the C++ implementation of above approach. CPP Java C# Python3 Javascript // CPP program to find// maximum prefix sum#include <bits/stdc++.h>using namespace std; // struct two store two values in one nodestruct Node { int sum; int prefix;}; Node tree[4 * 10000]; // function to build the segment treevoid build(int a[], int index, int beg, int end){ if (beg == end) { // If there is one element in array, // store it in current node of // segment tree tree[index].sum = a[beg]; tree[index].prefix = a[beg]; } else { int mid = (beg + end) / 2; // If there are more than one elements, // then recur for left and right subtrees build(a, 2 * index + 1, beg, mid); build(a, 2 * index + 2, mid + 1, end); // adds the sum and stores in the index // position of segment tree tree[index].sum = tree[2 * index + 1].sum + tree[2 * index + 2].sum; // stores the max of prefix-sum either // from right or from left. tree[index].prefix = max(tree[2 * index + 1].prefix, tree[2 * index + 1].sum + tree[2 * index + 2].prefix); }} // function to do the range query in the segment// tree for the maximum prefix sumNode query(int index, int beg, int end, int l, int r){ Node result; result.sum = result.prefix = -1; // If segment of this node is outside the given // range, then return the minimum value. if (beg > r || end < l) return result; // If segment of this node is a part of given // range, then return the node of the segment if (beg >= l && end <= r) return tree[index]; int mid = (beg + end) / 2; // if left segment of this node falls out of // range, then recur in the right side of // the tree if (l > mid) return query(2 * index + 2, mid + 1, end, l, r); // if right segment of this node falls out of // range, then recur in the left side of // the tree if (r <= mid) return query(2 * index + 1, beg, mid, l, r); // If a part of this segment overlaps with // the given range Node left = query(2 * index + 1, beg, mid, l, r); Node right = query(2 * index + 2, mid + 1, end, l, r); // adds the sum of the left and right // segment result.sum = left.sum + right.sum; // stores the max of prefix-sum result.prefix = max(left.prefix, left.sum + right.prefix); // returns the value return result;} // driver program to test the programint main(){ int a[] = { -2, -3, 4, -1, -2, 1, 5, -3 }; // calculates the length of array int n = sizeof(a) / sizeof(a[0]); // calls the build function to build // the segment tree build(a, 0, 0, n - 1); // find the max prefix-sum between // 3rd and 5th index of array cout << query(0, 0, n - 1, 3, 5).prefix << endl; // find the max prefix-sum between // 0th and 7th index of array cout << query(0, 0, n - 1, 1, 7).prefix << endl; return 0;} // JAVA program to find// maximum prefix sumclass GFG{ // two store two values in one nodestatic class Node{ int sum; int prefix;}; static Node []tree = new Node[4 * 10000];static{ for(int i = 0; i < tree.length; i++) tree[i] = new Node();} // function to build the segment treestatic void build(int a[], int index, int beg, int end){ if (beg == end) { // If there is one element in array, // store it in current node of // segment tree tree[index].sum = a[beg]; tree[index].prefix = a[beg]; } else { int mid = (beg + end) / 2; // If there are more than one elements, // then recur for left and right subtrees build(a, 2 * index + 1, beg, mid); build(a, 2 * index + 2, mid + 1, end); // adds the sum and stores in the index // position of segment tree tree[index].sum = tree[2 * index + 1].sum + tree[2 * index + 2].sum; // stores the max of prefix-sum either // from right or from left. tree[index].prefix = Math.max(tree[2 * index + 1].prefix, tree[2 * index + 1].sum + tree[2 * index + 2].prefix); }} // function to do the range query in the segment// tree for the maximum prefix sumstatic Node query(int index, int beg, int end, int l, int r){ Node result = new Node(); result.sum = result.prefix = -1; // If segment of this node is outside the given // range, then return the minimum value. if (beg > r || end < l) return result; // If segment of this node is a part of given // range, then return the node of the segment if (beg >= l && end <= r) return tree[index]; int mid = (beg + end) / 2; // if left segment of this node falls out of // range, then recur in the right side of // the tree if (l > mid) return query(2 * index + 2, mid + 1, end, l, r); // if right segment of this node falls out of // range, then recur in the left side of // the tree if (r <= mid) return query(2 * index + 1, beg, mid, l, r); // If a part of this segment overlaps with // the given range Node left = query(2 * index + 1, beg, mid, l, r); Node right = query(2 * index + 2, mid + 1, end, l, r); // adds the sum of the left and right // segment result.sum = left.sum + right.sum; // stores the max of prefix-sum result.prefix = Math.max(left.prefix, left.sum + right.prefix); // returns the value return result;} // Driver codepublic static void main(String[] args){ int a[] = { -2, -3, 4, -1, -2, 1, 5, -3 }; // calculates the length of array int n = a.length; // calls the build function to build // the segment tree build(a, 0, 0, n - 1); // find the max prefix-sum between // 3rd and 5th index of array System.out.print(query(0, 0, n - 1, 3, 5).prefix +"\n"); // find the max prefix-sum between // 0th and 7th index of array System.out.print(query(0, 0, n - 1, 1, 7).prefix +"\n");}} // This code is contributed by PrinciRaj1992 // C# program to find// maximum prefix sumusing System; class GFG{ // two store two values in one nodeclass Node{ public int sum; public int prefix;}; static Node []tree = new Node[4 * 10000]; // function to build the segment treestatic void build(int []a, int index, int beg, int end){ if (beg == end) { // If there is one element in array, // store it in current node of // segment tree tree[index].sum = a[beg]; tree[index].prefix = a[beg]; } else { int mid = (beg + end) / 2; // If there are more than one elements, // then recur for left and right subtrees build(a, 2 * index + 1, beg, mid); build(a, 2 * index + 2, mid + 1, end); // adds the sum and stores in the index // position of segment tree tree[index].sum = tree[2 * index + 1].sum + tree[2 * index + 2].sum; // stores the max of prefix-sum either // from right or from left. tree[index].prefix = Math.Max(tree[2 * index + 1].prefix, tree[2 * index + 1].sum + tree[2 * index + 2].prefix); }} // function to do the range query in the segment// tree for the maximum prefix sumstatic Node query(int index, int beg, int end, int l, int r){ Node result = new Node(); result.sum = result.prefix = -1; // If segment of this node is outside the given // range, then return the minimum value. if (beg > r || end < l) return result; // If segment of this node is a part of given // range, then return the node of the segment if (beg >= l && end <= r) return tree[index]; int mid = (beg + end) / 2; // if left segment of this node falls out of // range, then recur in the right side of // the tree if (l > mid) return query(2 * index + 2, mid + 1, end, l, r); // if right segment of this node falls out of // range, then recur in the left side of // the tree if (r <= mid) return query(2 * index + 1, beg, mid, l, r); // If a part of this segment overlaps with // the given range Node left = query(2 * index + 1, beg, mid, l, r); Node right = query(2 * index + 2, mid + 1, end, l, r); // adds the sum of the left and right // segment result.sum = left.sum + right.sum; // stores the max of prefix-sum result.prefix = Math.Max(left.prefix, left.sum + right.prefix); // returns the value return result;} // Driver codepublic static void Main(String[] args){ for(int i = 0; i < tree.Length; i++) tree[i] = new Node(); int []a = { -2, -3, 4, -1, -2, 1, 5, -3 }; // calculates the length of array int n = a.Length; // calls the build function to build // the segment tree build(a, 0, 0, n - 1); // find the max prefix-sum between // 3rd and 5th index of array Console.Write(query(0, 0, n - 1, 3, 5).prefix +"\n"); // find the max prefix-sum between // 0th and 7th index of array Console.Write(query(0, 0, n - 1, 1, 7).prefix +"\n");}} // This code is contributed by Rajput-Ji # Python3 program to find# maximum prefix sum # struct two store two values in one node # function to build the segment treedef build(a, index, beg, end): global tree if (beg == end): # If there is one element in array, # store it in current node of # segment tree tree[index][0] = a[beg] tree[index][1] = a[beg] else: mid = (beg + end) // 2 # If there are more than one elements, # then recur for left and right subtrees build(a, 2 * index + 1, beg, mid) build(a, 2 * index + 2, mid + 1, end) # adds the sum and stores in the index # position of segment tree tree[index][0] = tree[2 * index + 1][0] + tree[2 * index + 2][0] # stores the max of prefix-sum either # from right or from left. tree[index][1] = max(tree[2 * index + 1][1],tree[2 * index + 1][0] + tree[2 * index + 2][1]) # function to do the range query in the segment# tree for the maximum prefix sumdef query(index, beg, end, l, r): global tree result = [-1, -1] # result[0] = result[1] = -1 # If segment of this node is outside the given # range, then return the minimum value. if (beg > r or end < l): return result # If segment of this node is a part of given # range, then return the node of the segment if (beg >= l and end <= r): return tree[index] mid = (beg + end) // 2 # if left segment of this node falls out of # range, then recur in the right side of # the tree if (l > mid): return query(2 * index + 2, mid + 1, end, l, r) # if right segment of this node falls out of # range, then recur in the left side of # the tree if (r <= mid): return query(2 * index + 1, beg, mid, l, r) # If a part of this segment overlaps with # the given range left = query(2 * index + 1, beg, mid, l, r) right = query(2 * index + 2, mid + 1, end, l, r) # adds the sum of the left and right # segment result[0] = left[0] + right[0] # stores the max of prefix-sum result[1] = max(left[1], left[0] + right[1]) # returns the value return result # driver program to test the programif __name__ == '__main__': a = [-2, -3, 4, -1, -2, 1, 5, -3 ] tree = [[0,0] for i in range(4 * 10000)] # calculates the length of array n = len(a) # calls the build function to build # the segment tree build(a, 0, 0, n - 1) # find the max prefix-sum between # 3rd and 5th index of array print(query(0, 0, n - 1, 3, 5)[1]) # find the max prefix-sum between # 0th and 7th index of array print(query(0, 0, n - 1, 1, 7)[1]) # This code is contributed by mohit kumar 29. <script> // JavaScript program to find// maximum prefix sum // two store two values in one node class Node { constructor() { let sum,prefix; } } let tree=new Array(4 * 10000); for(let i = 0; i < tree.length; i++) tree[i] = new Node(); // function to build the segment tree function build(a,index,beg,end) { if (beg == end) { // If there is one element in array, // store it in current node of // segment tree tree[index].sum = a[beg]; tree[index].prefix = a[beg]; } else { let mid = Math.floor((beg + end) / 2); // If there are more than one elements, // then recur for left and right subtrees build(a, 2 * index + 1, beg, mid); build(a, 2 * index + 2, mid + 1, end); // adds the sum and stores in the index // position of segment tree tree[index].sum = tree[2 * index + 1].sum + tree[2 * index + 2].sum; // stores the max of prefix-sum either // from right or from left. tree[index].prefix = Math.max(tree[2 * index + 1].prefix, tree[2 * index + 1].sum + tree[2 * index + 2].prefix); } } // function to do the range query in the segment// tree for the maximum prefix sum function query(index,beg,end,l,r) { let result = new Node(); result.sum = result.prefix = -1; // If segment of this node is outside the given // range, then return the minimum value. if (beg > r || end < l) return result; // If segment of this node is a part of given // range, then return the node of the segment if (beg >= l && end <= r) return tree[index]; let mid = Math.floor((beg + end) / 2); // if left segment of this node falls out of // range, then recur in the right side of // the tree if (l > mid) return query(2 * index + 2, mid + 1, end, l, r); // if right segment of this node falls out of // range, then recur in the left side of // the tree if (r <= mid) return query(2 * index + 1, beg, mid, l, r); // If a part of this segment overlaps with // the given range let left = query(2 * index + 1, beg, mid, l, r); let right = query(2 * index + 2, mid + 1, end, l, r); // adds the sum of the left and right // segment result.sum = left.sum + right.sum; // stores the max of prefix-sum result.prefix = Math.max(left.prefix, left.sum + right.prefix); // returns the value return result; } // Driver code let a=[-2, -3, 4, -1, -2, 1, 5, -3]; // calculates the length of array let n = a.length; // calls the build function to build // the segment tree build(a, 0, 0, n - 1); // find the max prefix-sum between // 3rd and 5th index of array document.write(query(0, 0, n - 1, 3, 5).prefix +"<br>"); // find the max prefix-sum between // 0th and 7th index of array document.write(query(0, 0, n - 1, 1, 7).prefix +"<br>"); // This code is contributed by patel2127 </script> Output: -1 4 Time Complexity: Time Complexity for tree construction is O(n). There are total 2n-1 nodes, and value of every node is calculated only once in tree construction.Time complexity to every query is O(log n).Time complexity for the problem is O(q * log n)This article is contributed by Raja Vikramaditya. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to review-team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. shreyashagrawal ManasChhabra2 princiraj1992 Rajput-Ji mohit kumar 29 patel2127 Segment-Tree Advanced Computer Subject Arrays Arrays Segment-Tree Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. ML | Monte Carlo Tree Search (MCTS) Markov Decision Process Basics of API Testing Using Postman Copying Files to and from Docker Containers Getting Started with System Design Arrays in Java Write a program to reverse an array or string Maximum and minimum of an array using minimum number of comparisons Top 50 Array Coding Problems for Interviews Largest Sum Contiguous Subarray
[ { "code": null, "e": 52, "s": 24, "text": "\n20 May, 2021" }, { "code": null, "e": 195, "s": 52, "text": "Given an array of n integers and q queries, each query having a range from l to r. Find the maximum prefix-sum for the range l – r.Examples: " }, { "code": null, "e": 1041, "s": 195, "text": "Input: a[] = {-1, 2, 3, -5} \n q = 2\n l = 0, r = 3\n l = 1, r = 3\n\nOutput: 4\n 5\n\nExplanation:- The range (0, 3) in the 1st query has\n [-1, 2, 3, -5], since it is prefix, \n we have to start from -1. Hence, the \n max prefix sum will be -1 + 2 + 3 = 4.\n The range (1, 3) in the 2nd query has \n [2, 3, -5], since it is prefix, we \n have to start from 2. Hence, the max\n prefix sum will be 2 + 3 = 5.\n\nInput: a[] = {-2, -3, 4, -1, -2, 1, 5, -3} \n q = 1\n l = 1 r = 7 \n\nOutput: 4\n\nExplanation:- The range (1, 7) in the 1st query has \n [-3, 4, -1, -2, 1, 5, -3], since it is\n prefix, we have to start from -3. \n Hence, the max prefix sum will be \n -3 + 4 - 1 - 2 + 1 + 5 = 4." }, { "code": null, "e": 2915, "s": 1043, "text": "Normal Approach: A simple solution is to run a loop from l to r and calculate max prefix sum from l to r for every query.Time Complexity: O(q * n), Auxiliary Space: O(1)Efficient Approach: An efficient approach will be to build a segment tree where each node stores two values(sum and prefix_sum), and do a range query on it to find the max prefix sum. But for building the segment tree we have to think about what to store on the nodes of the tree. For finding out the maximum prefix sum, we will require two things, one being the sum and the other prefix sum. The merging will return two things, sum of the ranges and the prefix sum that will store the max(prefix.left, prefix.sum + prefix.right) in the segment tree.If we have a deep look into it, the max prefix sum for any two range combining will either be the prefix sum from left side or the sum of left side+prefix sum of right side, whichever is max is taken into account. Representation of Segment trees:1. Leaf Nodes are the elements of the input array. 2. Each internal node represents some merging of the leaf nodes. The merging may be different for different problems. For this problem, merging is sum of leaves under a node.An array representation of tree is used to represent Segment Trees. For each node at index i, the left child is at index 2*i+1, right child at 2*i+2 and the parent is at (i-1)/2.Construction of Segment Tree from given array:We start with a segment arr[0 . . . n-1]. and every time we divide the current segment into two halves(if it has not yet become a segment of length 1), and then call the same procedure on both halves, and for each such segment, we store the sum and prefix sum in corresponding node.We then do a range query on segment tree to find out the max prefix-sum for the given range, and output the max prefix-sum.Below is the C++ implementation of above approach. " }, { "code": null, "e": 2919, "s": 2915, "text": "CPP" }, { "code": null, "e": 2924, "s": 2919, "text": "Java" }, { "code": null, "e": 2927, "s": 2924, "text": "C#" }, { "code": null, "e": 2935, "s": 2927, "text": "Python3" }, { "code": null, "e": 2946, "s": 2935, "text": "Javascript" }, { "code": "// CPP program to find// maximum prefix sum#include <bits/stdc++.h>using namespace std; // struct two store two values in one nodestruct Node { int sum; int prefix;}; Node tree[4 * 10000]; // function to build the segment treevoid build(int a[], int index, int beg, int end){ if (beg == end) { // If there is one element in array, // store it in current node of // segment tree tree[index].sum = a[beg]; tree[index].prefix = a[beg]; } else { int mid = (beg + end) / 2; // If there are more than one elements, // then recur for left and right subtrees build(a, 2 * index + 1, beg, mid); build(a, 2 * index + 2, mid + 1, end); // adds the sum and stores in the index // position of segment tree tree[index].sum = tree[2 * index + 1].sum + tree[2 * index + 2].sum; // stores the max of prefix-sum either // from right or from left. tree[index].prefix = max(tree[2 * index + 1].prefix, tree[2 * index + 1].sum + tree[2 * index + 2].prefix); }} // function to do the range query in the segment// tree for the maximum prefix sumNode query(int index, int beg, int end, int l, int r){ Node result; result.sum = result.prefix = -1; // If segment of this node is outside the given // range, then return the minimum value. if (beg > r || end < l) return result; // If segment of this node is a part of given // range, then return the node of the segment if (beg >= l && end <= r) return tree[index]; int mid = (beg + end) / 2; // if left segment of this node falls out of // range, then recur in the right side of // the tree if (l > mid) return query(2 * index + 2, mid + 1, end, l, r); // if right segment of this node falls out of // range, then recur in the left side of // the tree if (r <= mid) return query(2 * index + 1, beg, mid, l, r); // If a part of this segment overlaps with // the given range Node left = query(2 * index + 1, beg, mid, l, r); Node right = query(2 * index + 2, mid + 1, end, l, r); // adds the sum of the left and right // segment result.sum = left.sum + right.sum; // stores the max of prefix-sum result.prefix = max(left.prefix, left.sum + right.prefix); // returns the value return result;} // driver program to test the programint main(){ int a[] = { -2, -3, 4, -1, -2, 1, 5, -3 }; // calculates the length of array int n = sizeof(a) / sizeof(a[0]); // calls the build function to build // the segment tree build(a, 0, 0, n - 1); // find the max prefix-sum between // 3rd and 5th index of array cout << query(0, 0, n - 1, 3, 5).prefix << endl; // find the max prefix-sum between // 0th and 7th index of array cout << query(0, 0, n - 1, 1, 7).prefix << endl; return 0;}", "e": 6118, "s": 2946, "text": null }, { "code": "// JAVA program to find// maximum prefix sumclass GFG{ // two store two values in one nodestatic class Node{ int sum; int prefix;}; static Node []tree = new Node[4 * 10000];static{ for(int i = 0; i < tree.length; i++) tree[i] = new Node();} // function to build the segment treestatic void build(int a[], int index, int beg, int end){ if (beg == end) { // If there is one element in array, // store it in current node of // segment tree tree[index].sum = a[beg]; tree[index].prefix = a[beg]; } else { int mid = (beg + end) / 2; // If there are more than one elements, // then recur for left and right subtrees build(a, 2 * index + 1, beg, mid); build(a, 2 * index + 2, mid + 1, end); // adds the sum and stores in the index // position of segment tree tree[index].sum = tree[2 * index + 1].sum + tree[2 * index + 2].sum; // stores the max of prefix-sum either // from right or from left. tree[index].prefix = Math.max(tree[2 * index + 1].prefix, tree[2 * index + 1].sum + tree[2 * index + 2].prefix); }} // function to do the range query in the segment// tree for the maximum prefix sumstatic Node query(int index, int beg, int end, int l, int r){ Node result = new Node(); result.sum = result.prefix = -1; // If segment of this node is outside the given // range, then return the minimum value. if (beg > r || end < l) return result; // If segment of this node is a part of given // range, then return the node of the segment if (beg >= l && end <= r) return tree[index]; int mid = (beg + end) / 2; // if left segment of this node falls out of // range, then recur in the right side of // the tree if (l > mid) return query(2 * index + 2, mid + 1, end, l, r); // if right segment of this node falls out of // range, then recur in the left side of // the tree if (r <= mid) return query(2 * index + 1, beg, mid, l, r); // If a part of this segment overlaps with // the given range Node left = query(2 * index + 1, beg, mid, l, r); Node right = query(2 * index + 2, mid + 1, end, l, r); // adds the sum of the left and right // segment result.sum = left.sum + right.sum; // stores the max of prefix-sum result.prefix = Math.max(left.prefix, left.sum + right.prefix); // returns the value return result;} // Driver codepublic static void main(String[] args){ int a[] = { -2, -3, 4, -1, -2, 1, 5, -3 }; // calculates the length of array int n = a.length; // calls the build function to build // the segment tree build(a, 0, 0, n - 1); // find the max prefix-sum between // 3rd and 5th index of array System.out.print(query(0, 0, n - 1, 3, 5).prefix +\"\\n\"); // find the max prefix-sum between // 0th and 7th index of array System.out.print(query(0, 0, n - 1, 1, 7).prefix +\"\\n\");}} // This code is contributed by PrinciRaj1992", "e": 9417, "s": 6118, "text": null }, { "code": "// C# program to find// maximum prefix sumusing System; class GFG{ // two store two values in one nodeclass Node{ public int sum; public int prefix;}; static Node []tree = new Node[4 * 10000]; // function to build the segment treestatic void build(int []a, int index, int beg, int end){ if (beg == end) { // If there is one element in array, // store it in current node of // segment tree tree[index].sum = a[beg]; tree[index].prefix = a[beg]; } else { int mid = (beg + end) / 2; // If there are more than one elements, // then recur for left and right subtrees build(a, 2 * index + 1, beg, mid); build(a, 2 * index + 2, mid + 1, end); // adds the sum and stores in the index // position of segment tree tree[index].sum = tree[2 * index + 1].sum + tree[2 * index + 2].sum; // stores the max of prefix-sum either // from right or from left. tree[index].prefix = Math.Max(tree[2 * index + 1].prefix, tree[2 * index + 1].sum + tree[2 * index + 2].prefix); }} // function to do the range query in the segment// tree for the maximum prefix sumstatic Node query(int index, int beg, int end, int l, int r){ Node result = new Node(); result.sum = result.prefix = -1; // If segment of this node is outside the given // range, then return the minimum value. if (beg > r || end < l) return result; // If segment of this node is a part of given // range, then return the node of the segment if (beg >= l && end <= r) return tree[index]; int mid = (beg + end) / 2; // if left segment of this node falls out of // range, then recur in the right side of // the tree if (l > mid) return query(2 * index + 2, mid + 1, end, l, r); // if right segment of this node falls out of // range, then recur in the left side of // the tree if (r <= mid) return query(2 * index + 1, beg, mid, l, r); // If a part of this segment overlaps with // the given range Node left = query(2 * index + 1, beg, mid, l, r); Node right = query(2 * index + 2, mid + 1, end, l, r); // adds the sum of the left and right // segment result.sum = left.sum + right.sum; // stores the max of prefix-sum result.prefix = Math.Max(left.prefix, left.sum + right.prefix); // returns the value return result;} // Driver codepublic static void Main(String[] args){ for(int i = 0; i < tree.Length; i++) tree[i] = new Node(); int []a = { -2, -3, 4, -1, -2, 1, 5, -3 }; // calculates the length of array int n = a.Length; // calls the build function to build // the segment tree build(a, 0, 0, n - 1); // find the max prefix-sum between // 3rd and 5th index of array Console.Write(query(0, 0, n - 1, 3, 5).prefix +\"\\n\"); // find the max prefix-sum between // 0th and 7th index of array Console.Write(query(0, 0, n - 1, 1, 7).prefix +\"\\n\");}} // This code is contributed by Rajput-Ji", "e": 12717, "s": 9417, "text": null }, { "code": "# Python3 program to find# maximum prefix sum # struct two store two values in one node # function to build the segment treedef build(a, index, beg, end): global tree if (beg == end): # If there is one element in array, # store it in current node of # segment tree tree[index][0] = a[beg] tree[index][1] = a[beg] else: mid = (beg + end) // 2 # If there are more than one elements, # then recur for left and right subtrees build(a, 2 * index + 1, beg, mid) build(a, 2 * index + 2, mid + 1, end) # adds the sum and stores in the index # position of segment tree tree[index][0] = tree[2 * index + 1][0] + tree[2 * index + 2][0] # stores the max of prefix-sum either # from right or from left. tree[index][1] = max(tree[2 * index + 1][1],tree[2 * index + 1][0] + tree[2 * index + 2][1]) # function to do the range query in the segment# tree for the maximum prefix sumdef query(index, beg, end, l, r): global tree result = [-1, -1] # result[0] = result[1] = -1 # If segment of this node is outside the given # range, then return the minimum value. if (beg > r or end < l): return result # If segment of this node is a part of given # range, then return the node of the segment if (beg >= l and end <= r): return tree[index] mid = (beg + end) // 2 # if left segment of this node falls out of # range, then recur in the right side of # the tree if (l > mid): return query(2 * index + 2, mid + 1, end, l, r) # if right segment of this node falls out of # range, then recur in the left side of # the tree if (r <= mid): return query(2 * index + 1, beg, mid, l, r) # If a part of this segment overlaps with # the given range left = query(2 * index + 1, beg, mid, l, r) right = query(2 * index + 2, mid + 1, end, l, r) # adds the sum of the left and right # segment result[0] = left[0] + right[0] # stores the max of prefix-sum result[1] = max(left[1], left[0] + right[1]) # returns the value return result # driver program to test the programif __name__ == '__main__': a = [-2, -3, 4, -1, -2, 1, 5, -3 ] tree = [[0,0] for i in range(4 * 10000)] # calculates the length of array n = len(a) # calls the build function to build # the segment tree build(a, 0, 0, n - 1) # find the max prefix-sum between # 3rd and 5th index of array print(query(0, 0, n - 1, 3, 5)[1]) # find the max prefix-sum between # 0th and 7th index of array print(query(0, 0, n - 1, 1, 7)[1]) # This code is contributed by mohit kumar 29.", "e": 15415, "s": 12717, "text": null }, { "code": "<script> // JavaScript program to find// maximum prefix sum // two store two values in one node class Node { constructor() { let sum,prefix; } } let tree=new Array(4 * 10000); for(let i = 0; i < tree.length; i++) tree[i] = new Node(); // function to build the segment tree function build(a,index,beg,end) { if (beg == end) { // If there is one element in array, // store it in current node of // segment tree tree[index].sum = a[beg]; tree[index].prefix = a[beg]; } else { let mid = Math.floor((beg + end) / 2); // If there are more than one elements, // then recur for left and right subtrees build(a, 2 * index + 1, beg, mid); build(a, 2 * index + 2, mid + 1, end); // adds the sum and stores in the index // position of segment tree tree[index].sum = tree[2 * index + 1].sum + tree[2 * index + 2].sum; // stores the max of prefix-sum either // from right or from left. tree[index].prefix = Math.max(tree[2 * index + 1].prefix, tree[2 * index + 1].sum + tree[2 * index + 2].prefix); } } // function to do the range query in the segment// tree for the maximum prefix sum function query(index,beg,end,l,r) { let result = new Node(); result.sum = result.prefix = -1; // If segment of this node is outside the given // range, then return the minimum value. if (beg > r || end < l) return result; // If segment of this node is a part of given // range, then return the node of the segment if (beg >= l && end <= r) return tree[index]; let mid = Math.floor((beg + end) / 2); // if left segment of this node falls out of // range, then recur in the right side of // the tree if (l > mid) return query(2 * index + 2, mid + 1, end, l, r); // if right segment of this node falls out of // range, then recur in the left side of // the tree if (r <= mid) return query(2 * index + 1, beg, mid, l, r); // If a part of this segment overlaps with // the given range let left = query(2 * index + 1, beg, mid, l, r); let right = query(2 * index + 2, mid + 1, end, l, r); // adds the sum of the left and right // segment result.sum = left.sum + right.sum; // stores the max of prefix-sum result.prefix = Math.max(left.prefix, left.sum + right.prefix); // returns the value return result; } // Driver code let a=[-2, -3, 4, -1, -2, 1, 5, -3]; // calculates the length of array let n = a.length; // calls the build function to build // the segment tree build(a, 0, 0, n - 1); // find the max prefix-sum between // 3rd and 5th index of array document.write(query(0, 0, n - 1, 3, 5).prefix +\"<br>\"); // find the max prefix-sum between // 0th and 7th index of array document.write(query(0, 0, n - 1, 1, 7).prefix +\"<br>\"); // This code is contributed by patel2127 </script>", "e": 18727, "s": 15415, "text": null }, { "code": null, "e": 18737, "s": 18727, "text": "Output: " }, { "code": null, "e": 18742, "s": 18737, "text": "-1\n4" }, { "code": null, "e": 19419, "s": 18742, "text": "Time Complexity: Time Complexity for tree construction is O(n). There are total 2n-1 nodes, and value of every node is calculated only once in tree construction.Time complexity to every query is O(log n).Time complexity for the problem is O(q * log n)This article is contributed by Raja Vikramaditya. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to review-team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. " }, { "code": null, "e": 19435, "s": 19419, "text": "shreyashagrawal" }, { "code": null, "e": 19449, "s": 19435, "text": "ManasChhabra2" }, { "code": null, "e": 19463, "s": 19449, "text": "princiraj1992" }, { "code": null, "e": 19473, "s": 19463, "text": "Rajput-Ji" }, { "code": null, "e": 19488, "s": 19473, "text": "mohit kumar 29" }, { "code": null, "e": 19498, "s": 19488, "text": "patel2127" }, { "code": null, "e": 19511, "s": 19498, "text": "Segment-Tree" }, { "code": null, "e": 19537, "s": 19511, "text": "Advanced Computer Subject" }, { "code": null, "e": 19544, "s": 19537, "text": "Arrays" }, { "code": null, "e": 19551, "s": 19544, "text": "Arrays" }, { "code": null, "e": 19564, "s": 19551, "text": "Segment-Tree" }, { "code": null, "e": 19662, "s": 19564, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 19698, "s": 19662, "text": "ML | Monte Carlo Tree Search (MCTS)" }, { "code": null, "e": 19722, "s": 19698, "text": "Markov Decision Process" }, { "code": null, "e": 19758, "s": 19722, "text": "Basics of API Testing Using Postman" }, { "code": null, "e": 19802, "s": 19758, "text": "Copying Files to and from Docker Containers" }, { "code": null, "e": 19837, "s": 19802, "text": "Getting Started with System Design" }, { "code": null, "e": 19852, "s": 19837, "text": "Arrays in Java" }, { "code": null, "e": 19898, "s": 19852, "text": "Write a program to reverse an array or string" }, { "code": null, "e": 19966, "s": 19898, "text": "Maximum and minimum of an array using minimum number of comparisons" }, { "code": null, "e": 20010, "s": 19966, "text": "Top 50 Array Coding Problems for Interviews" } ]
Semaphores Solutions in Operating System
05 Oct, 2021 A Semaphore can be described as an object that consists of a counter, a waiting list of processes, Signal and Wait functions. The most basic use of semaphore is to initialize it to 1. When a thread want to enter a critical section, it calls down and enter the section. When another thread tries to do the same thing, the operation system will put it to the sleep because the value of semaphore is already zero due to previous call to down. When first thread is finished with the critical section, it calls up, which wakes up the other thread that’s waiting to enter. Logically semaphore S is an integer variable that, apart from initialization can only be accessed through two atomic operations : Wait(S) or P : If the semaphore value is greater than 0, decrement the value. Otherwise, wait until the value is greater than 0 and then decrement it. Signal(S) or V : Increment the value of Semaphore Semaphore Solution with Busy Waiting : If a process is in critical section, the other process that tries to enter its critical section must loop continuously in the entry code. The classic definitions for wait and signal are – wait (S) { while (S<=0); S--; } signal (S) { S++; } Implementing Semaphores : Critical Section of n process problems Shared Data : semaphore mutex ; // initially mutex=1 Process P : do { wait (mutex) ; <critical section> signal (mutex) ; <remainder section> } while (1) Semaphore Solution with Block and Wake up :In Busy-wait problem processes waste CPU cycles while waiting to enter their critical sections. Modify wait operation into the block operation. The process can block itself rather than bus-waiting. Place the process into wait queue associated with the critical section. Modify signal operation into the wakeup operation. Change the state of process from wait to ready. When process executes wait operation and finds that semaphore value is not positive, the process can block itself. Block operation places the process in waiting queue associated with semaphore. A process that is blocked waiting on a semaphore should be restarted when the other process executes signal operation. The blocked process should be restarted by a wakeup operation which put that process in ready queue. To implement semaphore we define the Semaphore as record : typedef struct { int value ; struct process *L ; } semaphore ; Assume two operations : block : suspends the process that invokes it. wakeup (P) : resumes the execution of the blocked process (P) Semaphore operations defined as : wait (S) { S.value -- ; if ( S.value < 0 ) { add this process to S.L ; block ; } } signal (S) { S.value ++ ; if ( S.value <= 0 ) { removes a process P from S.L ; wakeup (P) ; } } Advantages : Semaphores are simple to implement and machine independent Corrections is easy to determine Semaphores acquire many resources simultaneously Can have many different critical sections with different semaphores No waste of resources due to busy waiting Drawbacks : Access to semaphores can come from anywhere in a program There is no linguistic connection between the semaphore and data to which the semaphore control access improper use of the semaphores will lead to deadlock or starvation There is no control or guarantee of proper usage GATE CS Operating Systems Operating Systems Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Difference between Clustered and Non-clustered index Three address code in Compiler Introduction of Process Synchronization Differences between IPv4 and IPv6 Phases of a Compiler Banker's Algorithm in Operating System Disk Scheduling Algorithms Introduction of Deadlock in Operating System Paging in Operating System File Allocation Methods
[ { "code": null, "e": 53, "s": 25, "text": "\n05 Oct, 2021" }, { "code": null, "e": 620, "s": 53, "text": "A Semaphore can be described as an object that consists of a counter, a waiting list of processes, Signal and Wait functions. The most basic use of semaphore is to initialize it to 1. When a thread want to enter a critical section, it calls down and enter the section. When another thread tries to do the same thing, the operation system will put it to the sleep because the value of semaphore is already zero due to previous call to down. When first thread is finished with the critical section, it calls up, which wakes up the other thread that’s waiting to enter." }, { "code": null, "e": 750, "s": 620, "text": "Logically semaphore S is an integer variable that, apart from initialization can only be accessed through two atomic operations :" }, { "code": null, "e": 901, "s": 750, "text": "Wait(S) or P : If the semaphore value is greater than 0, decrement the value. Otherwise, wait until the value is greater than 0 and then decrement it." }, { "code": null, "e": 951, "s": 901, "text": "Signal(S) or V : Increment the value of Semaphore" }, { "code": null, "e": 990, "s": 951, "text": "Semaphore Solution with Busy Waiting :" }, { "code": null, "e": 1178, "s": 990, "text": "If a process is in critical section, the other process that tries to enter its critical section must loop continuously in the entry code. The classic definitions for wait and signal are –" }, { "code": null, "e": 1230, "s": 1178, "text": "wait (S) {\nwhile (S<=0);\nS--;\n}\nsignal (S) {\nS++;\n}" }, { "code": null, "e": 1296, "s": 1230, "text": " Implementing Semaphores : Critical Section of n process problems" }, { "code": null, "e": 1451, "s": 1296, "text": "Shared Data : semaphore mutex ; // initially mutex=1\nProcess P :\ndo {\nwait (mutex) ;\n<critical section>\nsignal (mutex) ;\n<remainder section>\n} while (1)" }, { "code": null, "e": 1864, "s": 1451, "text": "Semaphore Solution with Block and Wake up :In Busy-wait problem processes waste CPU cycles while waiting to enter their critical sections. Modify wait operation into the block operation. The process can block itself rather than bus-waiting. Place the process into wait queue associated with the critical section. Modify signal operation into the wakeup operation. Change the state of process from wait to ready. " }, { "code": null, "e": 2278, "s": 1864, "text": "When process executes wait operation and finds that semaphore value is not positive, the process can block itself. Block operation places the process in waiting queue associated with semaphore. A process that is blocked waiting on a semaphore should be restarted when the other process executes signal operation. The blocked process should be restarted by a wakeup operation which put that process in ready queue." }, { "code": null, "e": 2338, "s": 2278, "text": "To implement semaphore we define the Semaphore as record : " }, { "code": null, "e": 2401, "s": 2338, "text": "typedef struct {\nint value ;\nstruct process *L ;\n} semaphore ;" }, { "code": null, "e": 2425, "s": 2401, "text": "Assume two operations :" }, { "code": null, "e": 2471, "s": 2425, "text": "block : suspends the process that invokes it." }, { "code": null, "e": 2533, "s": 2471, "text": "wakeup (P) : resumes the execution of the blocked process (P)" }, { "code": null, "e": 2567, "s": 2533, "text": "Semaphore operations defined as :" }, { "code": null, "e": 2668, "s": 2567, "text": "wait (S) {\nS.value -- ; \nif ( S.value < 0 ) {\nadd this process to S.L ;\nblock ;\n} }" }, { "code": null, "e": 2765, "s": 2668, "text": "signal (S) {\nS.value ++ ; \nif ( S.value <= 0 ) {\nremoves a process P from S.L ;\nwakeup (P) ;\n} }" }, { "code": null, "e": 2778, "s": 2765, "text": "Advantages :" }, { "code": null, "e": 2837, "s": 2778, "text": "Semaphores are simple to implement and machine independent" }, { "code": null, "e": 2871, "s": 2837, "text": "Corrections is easy to determine" }, { "code": null, "e": 2920, "s": 2871, "text": "Semaphores acquire many resources simultaneously" }, { "code": null, "e": 2988, "s": 2920, "text": "Can have many different critical sections with different semaphores" }, { "code": null, "e": 3030, "s": 2988, "text": "No waste of resources due to busy waiting" }, { "code": null, "e": 3042, "s": 3030, "text": "Drawbacks :" }, { "code": null, "e": 3099, "s": 3042, "text": "Access to semaphores can come from anywhere in a program" }, { "code": null, "e": 3202, "s": 3099, "text": "There is no linguistic connection between the semaphore and data to which the semaphore control access" }, { "code": null, "e": 3269, "s": 3202, "text": "improper use of the semaphores will lead to deadlock or starvation" }, { "code": null, "e": 3318, "s": 3269, "text": "There is no control or guarantee of proper usage" }, { "code": null, "e": 3326, "s": 3318, "text": "GATE CS" }, { "code": null, "e": 3344, "s": 3326, "text": "Operating Systems" }, { "code": null, "e": 3362, "s": 3344, "text": "Operating Systems" }, { "code": null, "e": 3460, "s": 3362, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 3513, "s": 3460, "text": "Difference between Clustered and Non-clustered index" }, { "code": null, "e": 3544, "s": 3513, "text": "Three address code in Compiler" }, { "code": null, "e": 3584, "s": 3544, "text": "Introduction of Process Synchronization" }, { "code": null, "e": 3618, "s": 3584, "text": "Differences between IPv4 and IPv6" }, { "code": null, "e": 3639, "s": 3618, "text": "Phases of a Compiler" }, { "code": null, "e": 3678, "s": 3639, "text": "Banker's Algorithm in Operating System" }, { "code": null, "e": 3705, "s": 3678, "text": "Disk Scheduling Algorithms" }, { "code": null, "e": 3750, "s": 3705, "text": "Introduction of Deadlock in Operating System" }, { "code": null, "e": 3777, "s": 3750, "text": "Paging in Operating System" } ]
Flood fill Algorithm | Practice | GeeksforGeeks
An image is represented by a 2-D array of integers, each integer representing the pixel value of the image. Given a coordinate (sr, sc) representing the starting pixel (row and column) of the flood fill, and a pixel value newColor, "flood fill" the image. To perform a "flood fill", consider the starting pixel, plus any pixels connected 4-directionally to the starting pixel of the same color as the starting pixel, plus any pixels connected 4-directionally to those pixels (also with the same color as the starting pixel), and so on. Replace the color of all of the aforementioned pixels with the newColor. Example 1: Input: image = {{1,1,1},{1,1,0},{1,0,1}}, sr = 1, sc = 1, newColor = 2. Output: {{2,2,2},{2,2,0},{2,0,1}} Explanation: From the center of the image (with position (sr, sc) = (1, 1)), all pixels connected by a path of the same color as the starting pixel are colored with the new color.Note the bottom corner is not colored 2, because it is not 4-directionally connected to the starting pixel. Your Task: You don't need to read or print anyhting. Your task is to complete the function floodFill() which takes image, sr, sc and newColor as input paramater and returns the image after flood filling. Expected Time Compelxity: O(n*m) Expected Space Complexity: O(n*m) 0 aligrewal2113 hours ago TC = (n*m) SC = O(1) void DFS(vector<vector<int>>& image,int i, int j, int initialColor, int newColor) { if(i<0 || j<0 || i>=image.size() || j>=image[0].size() || image[i][j] != initialColor) return; image[i][j] = newColor; DFS(image, i+1, j, initialColor, newColor); DFS(image, i, j+1, initialColor, newColor); DFS(image, i-1, j, initialColor, newColor); DFS(image, i, j-1, initialColor, newColor); } vector<vector<int>> floodFill(vector<vector<int>>& image, int sr, int sc, int newColor) { // Code here int initialColor = image[sr][sc]; if(image[sr][sc] != newColor) DFS(image, sr, sc, initialColor, newColor); return image; } +1 bhagatkumar752 days ago PYTHON CODE: Using DFS class Solution: def floodFill(self, image, sr, sc, newColor): M=len(image) N=len(image[0]) visited=[[0]*(N) for i in range(M)] def DFS(i,j,visited, newColor, M,N,oldColor): if i<0 or j<0 or i>=M or j>=N : return elif visited[i][j]==1 or image[i][j]!=oldColor: return visited[i][j]=1 image[i][j]=newColor DFS(i+1,j,visited, newColor, M,N, oldColor) DFS(i-1,j,visited, newColor, M,N ,oldColor) DFS(i,j-1,visited, newColor, M,N, oldColor) DFS(i,j+1,visited, newColor, M,N ,oldColor) oldColor=image[sr][sc] DFS(sr,sc,visited, newColor, M,N, oldColor) return image +1 bhagatkumar752 days ago PYTHON CODE: Using BFS class Solution: def floodFill(self, image, sr, sc, newColor): M=len(image) N=len(image[0]) visited=[[0]*(N) for i in range(M)] q=[] oldColor=image[sr][sc] q.append([sr,sc]) image[sr][sc]=newColor while q: temp=q.pop(0) i=temp[0] j=temp[1] if i>=0 and (j+1)>=0 and i<M and (j+1)<N and visited[i][j+1]==0 and image[i][j+1]==oldColor: q.append([i, j+1]) visited[i][j+1]=1 image[i][j+1]=newColor if i>=0 and (j-1)>=0 and i<M and (j-1)<N and visited[i][j-1]==0 and image[i][j-1]==oldColor: q.append([i, j-1]) visited[i][j-1]=1 image[i][j-1]=newColor if (i+1)>=0 and (j)>=0 and (i+1)<M and (j)<N and visited[i+1][j]==0 and image[i+1][j]==oldColor: q.append([i+1, j]) visited[i+1][j]=1 image[i+1][j]=newColor if (i-1)>=0 and (j)>=0 and (i-1)<M and (j)<N and visited[i-1][j]==0 and image[i-1][j]==oldColor: q.append([i-1, j]) visited[i-1][j]=1 image[i-1][j]=newColor return image 0 harshmaurya11520015 days ago void dfs(vector<vector<int>>& adj,vector<vector<int>>&vis,int i,int j,int c,int m,int n,int v){ if(i<0||j<0||i>m-1||j>n-1) return ; if(vis[i][j]==0) { vis[i][j]=1; if(adj[i][j]==v) { adj[i][j]=c; dfs(adj,vis,i-1,j,c,m,n,v); dfs(adj,vis,i+1,j,c,m,n,v); dfs(adj,vis,i,j-1,c,m,n,v); dfs(adj,vis,i,j+1,c,m,n,v); } } return;} vector<vector<int>> floodFill(vector<vector<int>>& image, int sr, int sc, int newColor) { int m=image.size(),n=image[0].size(); vector<vector<int>>vis(m,vector<int>(n,0)); int v=image[sr][sc]; dfs(image,vis,sr,sc, newColor,m,n,v); return image; }}; 0 bhanupragnya2 weeks ago EASY JAVA SOLUTION : class Solution { public int[][] floodFill(int[][] image, int sr, int sc, int newColor) { int c=image[sr][sc]; image[sr][sc]=newColor; if(sr<0 || sc<0 || sr==image.length || sc==image[0].length || c==newColor) return image; if((sr-1)>=0 && image[sr-1][sc]==c) image=floodFill(image,sr-1,sc,newColor); if((sr+1)<image.length && image[sr+1][sc]==c) image=floodFill(image,sr+1,sc,newColor); if((sc-1)>=0 && image[sr][sc-1]==c) image=floodFill(image,sr,sc-1,newColor); if((sc+1)<image[0].length && image[sr][sc+1]==c) image=floodFill(image,sr,sc+1,newColor); return image; } } 0 sohanpulluru2 weeks ago void dfs(vector<vector<int>>& image, int sr, int sc, int ic, int nc) { if(sr < 0 || sr >= image.size()) return; if(sc < 0 || sc >= image[0].size()) return; if(image[sr][sc] != ic) return; image[sr][sc] = nc; dfs(image, sr+1, sc, ic, nc); dfs(image, sr-1, sc, ic, nc); dfs(image, sr, sc+1, ic, nc); dfs(image, sr, sc-1, ic, nc); } vector<vector<int>> floodFill(vector<vector<int>>& image, int sr, int sc, int newColor) { // Code here if(image[sr][sc] == newColor) return image; dfs(image, sr, sc, image[sr][sc], newColor); return image; } +1 shubhamrikhari86512 weeks ago void solve(vector<vector<int>>& image, int i, int j, int n, int m, int color, int newColor) { if(i>=0 && i<n && j>=0 && j<m && image[i][j] == color) {} else { return; } image[i][j] = newColor; solve(image, i+1, j, n, m, color, newColor); solve(image, i-1, j, n, m, color, newColor); solve(image, i, j+1, n, m, color, newColor); solve(image, i, j-1, n, m, color, newColor); return; } vector<vector<int>> floodFill(vector<vector<int>>& image, int sr, int sc, int newColor) { int n = image.size(); int m = image[0].size(); int color = image[sr][sc]; if(color == newColor) { return image; } solve(image, sr, sc, n, m, color, newColor); return image; } 0 divyanshjain2003kanpur2 weeks ago Java O(n) solution using BFS: class Pair{ int i,j; Pair(int a,int b){ i=a; j=b; }}class Solution{ public int[][] bfs(int[][] image,Pair src,int newColor,int r,int c,int h) { Queue<Pair> q=new LinkedList<>(); q.add(src); if(newColor==h) return image; image[src.i][src.j]=newColor; while(!q.isEmpty()) { Pair x=q.poll(); if(x.i-1>=0 && image[x.i-1][x.j]==h) { Pair y=new Pair(x.i-1,x.j); image[x.i-1][x.j]=newColor; q.add(y); } if(x.j-1>=0 && image[x.i][x.j-1]==h) { Pair y=new Pair(x.i,x.j-1); image[x.i][x.j-1]=newColor; q.add(y); } if(x.i+1<r && image[x.i+1][x.j]==h) { Pair y=new Pair(x.i+1,x.j); image[x.i+1][x.j]=newColor; q.add(y); } if(x.j+1<c && image[x.i][x.j+1]==h) { Pair y=new Pair(x.i,x.j+1); image[x.i][x.j+1]=newColor; q.add(y); } } return image; } public int[][] floodFill(int[][] image, int sr, int sc, int newColor) { int r=image.length; int c=image[0].length; Pair src=new Pair(sr,sc); bfs(image,src,newColor,r,c,image[sr][sc]); return image; // Code here }} 0 chamoli2 weeks ago class Solution { private: void Painter(vector<vector<int>> &image,int i,int j,int color,int row,int col,int validColor){ // base case // checking if we are out of bound or image we are on is already visited or we stand on wrong pixel if(i < 0 or j < 0 or i >= row or j >= col or image[i][j] != validColor){ return; } // if image is valid image , than paint it image[i][j] = color; // travel Painter(image,i-1,j,color,row,col,validColor); // Up Painter(image,i+1,j,color,row,col,validColor); // down Painter(image,i,j-1,color,row,col,validColor); // left Painter(image,i,j+1,color,row,col,validColor); // right } public: vector<vector<int>> floodFill(vector<vector<int>>& image, int sr, int sc, int color) { // size of row and col int row = image.size(); int col = image[0].size(); // valid color which can be colored int validColor = image[sr][sc]; // if source is already painted if(validColor == color){ return image; } // calling painter function for help Painter(image,sr,sc,color,row,col,validColor); return image; } }; 0 1107khyati3 weeks ago void flood_fill(vector<vector<int>>&image,int sr,int sc,int old_color,int color) { if(sr>=image.size()||sc>=image[0].size()||sr<0||sc<0||image[sr][sc]==color||image[sr][sc]!=old_color) return; image[sr][sc]=color; flood_fill(image,sr-1,sc,old_color,color); flood_fill(image,sr,sc-1,old_color,color); flood_fill(image,sr,sc+1,old_color,color); flood_fill(image,sr+1,sc,old_color,color); } vector<vector<int>> floodFill(vector<vector<int>>& image, int sr, int sc, int newColor) { int old_color= image[sr][sc]; flood_fill(image,sr,sc,old_color,newColor); return image; } We strongly recommend solving this problem on your own before viewing its editorial. Do you still want to view the editorial? Login to access your submissions. Problem Contest Reset the IDE using the second button on the top right corner. Avoid using static/global variables in your code as your code is tested against multiple test cases and these tend to retain their previous values. Passing the Sample/Custom Test cases does not guarantee the correctness of code. On submission, your code is tested against multiple test cases consisting of all possible corner cases and stress constraints. You can access the hints to get an idea about what is expected of you as well as the final solution code. You can view the solutions submitted by other users from the submission tab. Make sure you are not using ad-blockers. Disable browser extensions. We recommend using latest version of your browser for best experience. Avoid using static/global variables in coding problems as your code is tested against multiple test cases and these tend to retain their previous values. Passing the Sample/Custom Test cases in coding problems does not guarantee the correctness of code. On submission, your code is tested against multiple test cases consisting of all possible corner cases and stress constraints.
[ { "code": null, "e": 346, "s": 238, "text": "An image is represented by a 2-D array of integers, each integer representing the pixel value of the image." }, { "code": null, "e": 494, "s": 346, "text": "Given a coordinate (sr, sc) representing the starting pixel (row and column) of the flood fill, and a pixel value newColor, \"flood fill\" the image." }, { "code": null, "e": 847, "s": 494, "text": "To perform a \"flood fill\", consider the starting pixel, plus any pixels connected 4-directionally to the starting pixel of the same color as the starting pixel, plus any pixels connected 4-directionally to those pixels (also with the same color as the starting pixel), and so on. Replace the color of all of the aforementioned pixels with the newColor." }, { "code": null, "e": 858, "s": 847, "text": "Example 1:" }, { "code": null, "e": 1257, "s": 858, "text": "Input: image = {{1,1,1},{1,1,0},{1,0,1}},\nsr = 1, sc = 1, newColor = 2.\nOutput: {{2,2,2},{2,2,0},{2,0,1}}\nExplanation: From the center of the image \n(with position (sr, sc) = (1, 1)), all \npixels connected by a path of the same color\nas the starting pixel are colored with the new \ncolor.Note the bottom corner is not colored 2, \nbecause it is not 4-directionally connected to \nthe starting pixel.\n" }, { "code": null, "e": 1465, "s": 1259, "text": "Your Task:\nYou don't need to read or print anyhting. Your task is to complete the function floodFill() which takes image, sr, sc and newColor as input paramater and returns the image after flood filling.\n " }, { "code": null, "e": 1534, "s": 1465, "text": "Expected Time Compelxity: O(n*m)\nExpected Space Complexity: O(n*m)\n " }, { "code": null, "e": 1536, "s": 1534, "text": "0" }, { "code": null, "e": 1560, "s": 1536, "text": "aligrewal2113 hours ago" }, { "code": null, "e": 1571, "s": 1560, "text": "TC = (n*m)" }, { "code": null, "e": 1581, "s": 1571, "text": "SC = O(1)" }, { "code": null, "e": 2310, "s": 1581, "text": "void DFS(vector<vector<int>>& image,int i, int j, int initialColor, int newColor)\n {\n if(i<0 || j<0 || i>=image.size() || j>=image[0].size() \n || image[i][j] != initialColor) return;\n image[i][j] = newColor;\n DFS(image, i+1, j, initialColor, newColor);\n DFS(image, i, j+1, initialColor, newColor);\n DFS(image, i-1, j, initialColor, newColor);\n DFS(image, i, j-1, initialColor, newColor); \n }\n vector<vector<int>> floodFill(vector<vector<int>>& image, int sr, int sc, int newColor) {\n // Code here \n int initialColor = image[sr][sc];\n if(image[sr][sc] != newColor)\n DFS(image, sr, sc, initialColor, newColor);\n return image;\n }" }, { "code": null, "e": 2313, "s": 2310, "text": "+1" }, { "code": null, "e": 2337, "s": 2313, "text": "bhagatkumar752 days ago" }, { "code": null, "e": 2360, "s": 2337, "text": "PYTHON CODE: Using DFS" }, { "code": null, "e": 3139, "s": 2360, "text": "class Solution:\n def floodFill(self, image, sr, sc, newColor):\n M=len(image)\n N=len(image[0])\n visited=[[0]*(N) for i in range(M)]\n \n def DFS(i,j,visited, newColor, M,N,oldColor):\n if i<0 or j<0 or i>=M or j>=N :\n return\n elif visited[i][j]==1 or image[i][j]!=oldColor:\n return\n visited[i][j]=1\n image[i][j]=newColor\n \n DFS(i+1,j,visited, newColor, M,N, oldColor)\n DFS(i-1,j,visited, newColor, M,N ,oldColor)\n DFS(i,j-1,visited, newColor, M,N, oldColor)\n DFS(i,j+1,visited, newColor, M,N ,oldColor)\n \n oldColor=image[sr][sc]\n DFS(sr,sc,visited, newColor, M,N, oldColor)\n return image" }, { "code": null, "e": 3142, "s": 3139, "text": "+1" }, { "code": null, "e": 3166, "s": 3142, "text": "bhagatkumar752 days ago" }, { "code": null, "e": 3189, "s": 3166, "text": "PYTHON CODE: Using BFS" }, { "code": null, "e": 4472, "s": 3189, "text": "class Solution:\n \n\tdef floodFill(self, image, sr, sc, newColor):\n\t\tM=len(image)\n\t\tN=len(image[0])\n visited=[[0]*(N) for i in range(M)]\n q=[]\n oldColor=image[sr][sc]\n q.append([sr,sc])\n image[sr][sc]=newColor\n while q:\n temp=q.pop(0)\n i=temp[0]\n j=temp[1]\n \n if i>=0 and (j+1)>=0 and i<M and (j+1)<N and visited[i][j+1]==0 and image[i][j+1]==oldColor:\n q.append([i, j+1])\n visited[i][j+1]=1\n image[i][j+1]=newColor\n \n if i>=0 and (j-1)>=0 and i<M and (j-1)<N and visited[i][j-1]==0 and image[i][j-1]==oldColor:\n q.append([i, j-1])\n visited[i][j-1]=1\n image[i][j-1]=newColor\n \n if (i+1)>=0 and (j)>=0 and (i+1)<M and (j)<N and visited[i+1][j]==0 and image[i+1][j]==oldColor:\n q.append([i+1, j])\n visited[i+1][j]=1\n image[i+1][j]=newColor\n \n if (i-1)>=0 and (j)>=0 and (i-1)<M and (j)<N and visited[i-1][j]==0 and image[i-1][j]==oldColor:\n q.append([i-1, j])\n visited[i-1][j]=1\n image[i-1][j]=newColor\n \n return image" }, { "code": null, "e": 4474, "s": 4472, "text": "0" }, { "code": null, "e": 4503, "s": 4474, "text": "harshmaurya11520015 days ago" }, { "code": null, "e": 5197, "s": 4503, "text": "void dfs(vector<vector<int>>& adj,vector<vector<int>>&vis,int i,int j,int c,int m,int n,int v){ if(i<0||j<0||i>m-1||j>n-1) return ; if(vis[i][j]==0) { vis[i][j]=1; if(adj[i][j]==v) { adj[i][j]=c; dfs(adj,vis,i-1,j,c,m,n,v); dfs(adj,vis,i+1,j,c,m,n,v); dfs(adj,vis,i,j-1,c,m,n,v); dfs(adj,vis,i,j+1,c,m,n,v); } } return;} vector<vector<int>> floodFill(vector<vector<int>>& image, int sr, int sc, int newColor) { int m=image.size(),n=image[0].size(); vector<vector<int>>vis(m,vector<int>(n,0)); int v=image[sr][sc]; dfs(image,vis,sr,sc, newColor,m,n,v); return image; }};" }, { "code": null, "e": 5199, "s": 5197, "text": "0" }, { "code": null, "e": 5223, "s": 5199, "text": "bhanupragnya2 weeks ago" }, { "code": null, "e": 5244, "s": 5223, "text": "EASY JAVA SOLUTION :" }, { "code": null, "e": 5902, "s": 5244, "text": "class Solution\n{\n public int[][] floodFill(int[][] image, int sr, int sc, int newColor)\n {\n\n \n int c=image[sr][sc];\n image[sr][sc]=newColor;\n if(sr<0 || sc<0 || sr==image.length || sc==image[0].length || c==newColor) return image;\n if((sr-1)>=0 && image[sr-1][sc]==c) image=floodFill(image,sr-1,sc,newColor);\n if((sr+1)<image.length && image[sr+1][sc]==c) image=floodFill(image,sr+1,sc,newColor);\n if((sc-1)>=0 && image[sr][sc-1]==c) image=floodFill(image,sr,sc-1,newColor);\n if((sc+1)<image[0].length && image[sr][sc+1]==c) image=floodFill(image,sr,sc+1,newColor);\n return image;\n }\n}" }, { "code": null, "e": 5904, "s": 5902, "text": "0" }, { "code": null, "e": 5928, "s": 5904, "text": "sohanpulluru2 weeks ago" }, { "code": null, "e": 6549, "s": 5928, "text": "void dfs(vector<vector<int>>& image, int sr, int sc, int ic, int nc) { if(sr < 0 || sr >= image.size()) return; if(sc < 0 || sc >= image[0].size()) return; if(image[sr][sc] != ic) return; image[sr][sc] = nc; dfs(image, sr+1, sc, ic, nc); dfs(image, sr-1, sc, ic, nc); dfs(image, sr, sc+1, ic, nc); dfs(image, sr, sc-1, ic, nc); } vector<vector<int>> floodFill(vector<vector<int>>& image, int sr, int sc, int newColor) { // Code here if(image[sr][sc] == newColor) return image; dfs(image, sr, sc, image[sr][sc], newColor); return image; }" }, { "code": null, "e": 6552, "s": 6549, "text": "+1" }, { "code": null, "e": 6582, "s": 6552, "text": "shubhamrikhari86512 weeks ago" }, { "code": null, "e": 7353, "s": 6582, "text": "void solve(vector<vector<int>>& image, int i, int j, int n, int m, int color, int newColor) { if(i>=0 && i<n && j>=0 && j<m && image[i][j] == color) {} else { return; } image[i][j] = newColor; solve(image, i+1, j, n, m, color, newColor); solve(image, i-1, j, n, m, color, newColor); solve(image, i, j+1, n, m, color, newColor); solve(image, i, j-1, n, m, color, newColor); return; } vector<vector<int>> floodFill(vector<vector<int>>& image, int sr, int sc, int newColor) { int n = image.size(); int m = image[0].size(); int color = image[sr][sc]; if(color == newColor) { return image; } solve(image, sr, sc, n, m, color, newColor); return image; }" }, { "code": null, "e": 7355, "s": 7353, "text": "0" }, { "code": null, "e": 7389, "s": 7355, "text": "divyanshjain2003kanpur2 weeks ago" }, { "code": null, "e": 7419, "s": 7389, "text": "Java O(n) solution using BFS:" }, { "code": null, "e": 8787, "s": 7421, "text": "class Pair{ int i,j; Pair(int a,int b){ i=a; j=b; }}class Solution{ public int[][] bfs(int[][] image,Pair src,int newColor,int r,int c,int h) { Queue<Pair> q=new LinkedList<>(); q.add(src); if(newColor==h) return image; image[src.i][src.j]=newColor; while(!q.isEmpty()) { Pair x=q.poll(); if(x.i-1>=0 && image[x.i-1][x.j]==h) { Pair y=new Pair(x.i-1,x.j); image[x.i-1][x.j]=newColor; q.add(y); } if(x.j-1>=0 && image[x.i][x.j-1]==h) { Pair y=new Pair(x.i,x.j-1); image[x.i][x.j-1]=newColor; q.add(y); } if(x.i+1<r && image[x.i+1][x.j]==h) { Pair y=new Pair(x.i+1,x.j); image[x.i+1][x.j]=newColor; q.add(y); } if(x.j+1<c && image[x.i][x.j+1]==h) { Pair y=new Pair(x.i,x.j+1); image[x.i][x.j+1]=newColor; q.add(y); } } return image; } public int[][] floodFill(int[][] image, int sr, int sc, int newColor) { int r=image.length; int c=image[0].length; Pair src=new Pair(sr,sc); bfs(image,src,newColor,r,c,image[sr][sc]); return image; // Code here }}" }, { "code": null, "e": 8789, "s": 8787, "text": "0" }, { "code": null, "e": 8808, "s": 8789, "text": "chamoli2 weeks ago" }, { "code": null, "e": 10133, "s": 8808, "text": "class Solution {\nprivate:\n void Painter(vector<vector<int>> &image,int i,int j,int color,int row,int col,int validColor){\n \n // base case\n // checking if we are out of bound or image we are on is already visited or we stand on wrong pixel\n \n if(i < 0 or j < 0 or i >= row or j >= col or image[i][j] != validColor){\n return;\n }\n \n // if image is valid image , than paint it\n image[i][j] = color;\n \n // travel \n Painter(image,i-1,j,color,row,col,validColor); // Up\n Painter(image,i+1,j,color,row,col,validColor); // down\n Painter(image,i,j-1,color,row,col,validColor); // left\n Painter(image,i,j+1,color,row,col,validColor); // right\n \n }\npublic:\n vector<vector<int>> floodFill(vector<vector<int>>& image, int sr, int sc, int color) {\n // size of row and col\n int row = image.size();\n int col = image[0].size();\n \n // valid color which can be colored\n int validColor = image[sr][sc];\n \n // if source is already painted\n if(validColor == color){\n return image;\n } \n \n // calling painter function for help\n Painter(image,sr,sc,color,row,col,validColor);\n \n return image;\n }\n};" }, { "code": null, "e": 10135, "s": 10133, "text": "0" }, { "code": null, "e": 10157, "s": 10135, "text": "1107khyati3 weeks ago" }, { "code": null, "e": 10856, "s": 10157, "text": "void flood_fill(vector<vector<int>>&image,int sr,int sc,int old_color,int color)\n {\n \n if(sr>=image.size()||sc>=image[0].size()||sr<0||sc<0||image[sr][sc]==color||image[sr][sc]!=old_color)\n return;\n image[sr][sc]=color;\n flood_fill(image,sr-1,sc,old_color,color);\n flood_fill(image,sr,sc-1,old_color,color);\n flood_fill(image,sr,sc+1,old_color,color);\n flood_fill(image,sr+1,sc,old_color,color);\n \n }\n \n \n vector<vector<int>> floodFill(vector<vector<int>>& image, int sr, int sc, int newColor)\n {\n int old_color= image[sr][sc];\n flood_fill(image,sr,sc,old_color,newColor);\n return image;\n }\n " }, { "code": null, "e": 11002, "s": 10856, "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": 11038, "s": 11002, "text": " Login to access your submissions. " }, { "code": null, "e": 11048, "s": 11038, "text": "\nProblem\n" }, { "code": null, "e": 11058, "s": 11048, "text": "\nContest\n" }, { "code": null, "e": 11121, "s": 11058, "text": "Reset the IDE using the second button on the top right corner." }, { "code": null, "e": 11306, "s": 11121, "text": "Avoid using static/global variables in your code as your code is tested \n against multiple test cases and these tend to retain their previous values." }, { "code": null, "e": 11590, "s": 11306, "text": "Passing the Sample/Custom Test cases does not guarantee the correctness of code.\n On submission, your code is tested against multiple test cases consisting of all\n possible corner cases and stress constraints." }, { "code": null, "e": 11736, "s": 11590, "text": "You can access the hints to get an idea about what is expected of you as well as\n the final solution code." }, { "code": null, "e": 11813, "s": 11736, "text": "You can view the solutions submitted by other users from the submission tab." }, { "code": null, "e": 11854, "s": 11813, "text": "Make sure you are not using ad-blockers." }, { "code": null, "e": 11882, "s": 11854, "text": "Disable browser extensions." }, { "code": null, "e": 11953, "s": 11882, "text": "We recommend using latest version of your browser for best experience." }, { "code": null, "e": 12140, "s": 11953, "text": "Avoid using static/global variables in coding problems as your code is tested \n against multiple test cases and these tend to retain their previous values." } ]
Plot a Point or a Line on an Image with Matplotlib
17 Dec, 2020 Prerequisites: Matplotlib Matplotlib and its constituents support a lot of functionality. One such functionality is that we can draw a line or a point on an image using Matplotlib in python. Import modules Read the image Plot the line or point on the image Display the plot/image. Image Used: Implementation using the above approach on the given image is provided below: Example 1 : Drawing a point on the image. Attribute used: marker It is used to define what marker type should the point be displayed in. Python3 from matplotlib import imagefrom matplotlib import pyplot as plt # to read the image stored in the working directorydata = image.imread('sunset-1404452-640x480.jpg') # to draw a point on co-ordinate (200,300)plt.plot(200, 350, marker='v', color="white")plt.imshow(data)plt.show() Output: Example 2 : Draw a line on the image To draw a line we will give the co-ordinates of two points in the plot function. Attribute used: linewidth Used to specify the width of the line. Python3 from matplotlib import imagefrom matplotlib import pyplot as plt # to read the image stored in the working directorydata = image.imread('sunset-1404452-640x480.jpg') # to draw a line from (200,300) to (500,100)x = [200, 500]y = [300, 100]plt.plot(x, y, color="white", linewidth=3)plt.imshow(data)plt.show() Output: Example 3 : Draw two intersecting lines crossing each other to make X. Python3 from matplotlib import imagefrom matplotlib import pyplot as plt # to read the image stored in the working directorydata = image.imread('sunset-1404452-640x480.jpg') # to draw first line from (100,400) to (500,100)# to draw second line from (150,100) to (450,400)x1 = [100, 500]y1 = [400, 100]x2 = [150, 450]y2 = [100, 400]plt.plot(x1, y1, x2, y2, color="white", linewidth=3)plt.axis('off')plt.imshow(data)plt.show() Output : Picked Python-matplotlib Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Read JSON file using Python Adding new column to existing DataFrame in Pandas Python map() function How to get column names in Pandas dataframe Python Dictionary Different ways to create Pandas Dataframe Taking input in Python Enumerate() in Python Read a file line by line in Python Python String | replace()
[ { "code": null, "e": 28, "s": 0, "text": "\n17 Dec, 2020" }, { "code": null, "e": 54, "s": 28, "text": "Prerequisites: Matplotlib" }, { "code": null, "e": 219, "s": 54, "text": "Matplotlib and its constituents support a lot of functionality. One such functionality is that we can draw a line or a point on an image using Matplotlib in python." }, { "code": null, "e": 234, "s": 219, "text": "Import modules" }, { "code": null, "e": 249, "s": 234, "text": "Read the image" }, { "code": null, "e": 285, "s": 249, "text": "Plot the line or point on the image" }, { "code": null, "e": 309, "s": 285, "text": "Display the plot/image." }, { "code": null, "e": 321, "s": 309, "text": "Image Used:" }, { "code": null, "e": 399, "s": 321, "text": "Implementation using the above approach on the given image is provided below:" }, { "code": null, "e": 441, "s": 399, "text": "Example 1 : Drawing a point on the image." }, { "code": null, "e": 464, "s": 441, "text": "Attribute used: marker" }, { "code": null, "e": 536, "s": 464, "text": "It is used to define what marker type should the point be displayed in." }, { "code": null, "e": 544, "s": 536, "text": "Python3" }, { "code": "from matplotlib import imagefrom matplotlib import pyplot as plt # to read the image stored in the working directorydata = image.imread('sunset-1404452-640x480.jpg') # to draw a point on co-ordinate (200,300)plt.plot(200, 350, marker='v', color=\"white\")plt.imshow(data)plt.show()", "e": 826, "s": 544, "text": null }, { "code": null, "e": 834, "s": 826, "text": "Output:" }, { "code": null, "e": 871, "s": 834, "text": "Example 2 : Draw a line on the image" }, { "code": null, "e": 952, "s": 871, "text": "To draw a line we will give the co-ordinates of two points in the plot function." }, { "code": null, "e": 978, "s": 952, "text": "Attribute used: linewidth" }, { "code": null, "e": 1017, "s": 978, "text": "Used to specify the width of the line." }, { "code": null, "e": 1025, "s": 1017, "text": "Python3" }, { "code": "from matplotlib import imagefrom matplotlib import pyplot as plt # to read the image stored in the working directorydata = image.imread('sunset-1404452-640x480.jpg') # to draw a line from (200,300) to (500,100)x = [200, 500]y = [300, 100]plt.plot(x, y, color=\"white\", linewidth=3)plt.imshow(data)plt.show()", "e": 1334, "s": 1025, "text": null }, { "code": null, "e": 1343, "s": 1334, "text": "Output: " }, { "code": null, "e": 1414, "s": 1343, "text": "Example 3 : Draw two intersecting lines crossing each other to make X." }, { "code": null, "e": 1422, "s": 1414, "text": "Python3" }, { "code": "from matplotlib import imagefrom matplotlib import pyplot as plt # to read the image stored in the working directorydata = image.imread('sunset-1404452-640x480.jpg') # to draw first line from (100,400) to (500,100)# to draw second line from (150,100) to (450,400)x1 = [100, 500]y1 = [400, 100]x2 = [150, 450]y2 = [100, 400]plt.plot(x1, y1, x2, y2, color=\"white\", linewidth=3)plt.axis('off')plt.imshow(data)plt.show()", "e": 1841, "s": 1422, "text": null }, { "code": null, "e": 1851, "s": 1841, "text": "Output : " }, { "code": null, "e": 1858, "s": 1851, "text": "Picked" }, { "code": null, "e": 1876, "s": 1858, "text": "Python-matplotlib" }, { "code": null, "e": 1883, "s": 1876, "text": "Python" }, { "code": null, "e": 1981, "s": 1883, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 2009, "s": 1981, "text": "Read JSON file using Python" }, { "code": null, "e": 2059, "s": 2009, "text": "Adding new column to existing DataFrame in Pandas" }, { "code": null, "e": 2081, "s": 2059, "text": "Python map() function" }, { "code": null, "e": 2125, "s": 2081, "text": "How to get column names in Pandas dataframe" }, { "code": null, "e": 2143, "s": 2125, "text": "Python Dictionary" }, { "code": null, "e": 2185, "s": 2143, "text": "Different ways to create Pandas Dataframe" }, { "code": null, "e": 2208, "s": 2185, "text": "Taking input in Python" }, { "code": null, "e": 2230, "s": 2208, "text": "Enumerate() in Python" }, { "code": null, "e": 2265, "s": 2230, "text": "Read a file line by line in Python" } ]
How to Download File from URL in Android Programmatically using Download Manager?
23 May, 2021 In this article, we are going to learn how to download files from an URL using Download Manager. Here we will be simply adding the link of the file available online. When we click on the Button it will be downloaded automatically to our phone storage. This is a very frequently used feature as we can use this feature to automatically download the faq section of an app. Step 1: Create a New Project To create a new project in Android Studio please refer to How to Create/Start a New Project in Android Studio. Note that select Java as the programming language. Step 2: Grant internet permission in the AndroidManifest.xml file <uses-permission android:name=”android.permission.INTERNET”/> Step 3: Working with the activity_main.xml file Navigate to the app > res > layout > activity_main.xml and add the below code to that file. Below is the code for the activity_main.xml file. XML <?xml version="1.0" encoding="utf-8"?><LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" android:layout_gravity="center" android:gravity="center" android:orientation="vertical" tools:context=".MainActivity"> <Button android:id="@+id/download" android:layout_width="match_parent" android:layout_height="wrap_content" android:text="Download Content" /> </LinearLayout> Step 4: Working with the MainActivity.java file Go to the MainActivity.java file and refer to the following code. Below is the code for the MainActivity.java file. Java import android.app.DownloadManager;import android.content.Context;import android.net.Uri;import android.os.Bundle;import android.view.View;import android.widget.Button; import androidx.appcompat.app.AppCompatActivity; public class MainActivity extends AppCompatActivity { Button button; DownloadManager manager; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); button = findViewById(R.id.download); button.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { manager = (DownloadManager) getSystemService(Context.DOWNLOAD_SERVICE); Uri uri = Uri.parse("https://www.w3.org/WAI/ER/tests/xhtml/testfiles/resources/pdf/dummy.pdf"); DownloadManager.Request request = new DownloadManager.Request(uri); request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE); long reference = manager.enqueue(request); } }); }} Output: Android Java Java Android Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to Add Views Dynamically and Store Data in Arraylist in Android? Android RecyclerView in Kotlin Android SDK and it's Components How to Communicate Between Fragments in Android? Broadcast Receiver in Android With Example Arrays in Java Split() String method in Java with examples Arrays.sort() in Java with examples Reverse a string in Java Object Oriented Programming (OOPs) Concept in Java
[ { "code": null, "e": 52, "s": 24, "text": "\n23 May, 2021" }, { "code": null, "e": 423, "s": 52, "text": "In this article, we are going to learn how to download files from an URL using Download Manager. Here we will be simply adding the link of the file available online. When we click on the Button it will be downloaded automatically to our phone storage. This is a very frequently used feature as we can use this feature to automatically download the faq section of an app." }, { "code": null, "e": 452, "s": 423, "text": "Step 1: Create a New Project" }, { "code": null, "e": 614, "s": 452, "text": "To create a new project in Android Studio please refer to How to Create/Start a New Project in Android Studio. Note that select Java as the programming language." }, { "code": null, "e": 681, "s": 614, "text": "Step 2: Grant internet permission in the AndroidManifest.xml file " }, { "code": null, "e": 743, "s": 681, "text": "<uses-permission android:name=”android.permission.INTERNET”/>" }, { "code": null, "e": 791, "s": 743, "text": "Step 3: Working with the activity_main.xml file" }, { "code": null, "e": 934, "s": 791, "text": "Navigate to the app > res > layout > activity_main.xml and add the below code to that file. Below is the code for the activity_main.xml file. " }, { "code": null, "e": 938, "s": 934, "text": "XML" }, { "code": "<?xml version=\"1.0\" encoding=\"utf-8\"?><LinearLayout xmlns:android=\"http://schemas.android.com/apk/res/android\" xmlns:tools=\"http://schemas.android.com/tools\" android:layout_width=\"match_parent\" android:layout_height=\"match_parent\" android:layout_gravity=\"center\" android:gravity=\"center\" android:orientation=\"vertical\" tools:context=\".MainActivity\"> <Button android:id=\"@+id/download\" android:layout_width=\"match_parent\" android:layout_height=\"wrap_content\" android:text=\"Download Content\" /> </LinearLayout>", "e": 1506, "s": 938, "text": null }, { "code": null, "e": 1554, "s": 1506, "text": "Step 4: Working with the MainActivity.java file" }, { "code": null, "e": 1671, "s": 1554, "text": "Go to the MainActivity.java file and refer to the following code. Below is the code for the MainActivity.java file. " }, { "code": null, "e": 1676, "s": 1671, "text": "Java" }, { "code": "import android.app.DownloadManager;import android.content.Context;import android.net.Uri;import android.os.Bundle;import android.view.View;import android.widget.Button; import androidx.appcompat.app.AppCompatActivity; public class MainActivity extends AppCompatActivity { Button button; DownloadManager manager; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); button = findViewById(R.id.download); button.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { manager = (DownloadManager) getSystemService(Context.DOWNLOAD_SERVICE); Uri uri = Uri.parse(\"https://www.w3.org/WAI/ER/tests/xhtml/testfiles/resources/pdf/dummy.pdf\"); DownloadManager.Request request = new DownloadManager.Request(uri); request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE); long reference = manager.enqueue(request); } }); }}", "e": 2794, "s": 1676, "text": null }, { "code": null, "e": 2802, "s": 2794, "text": "Output:" }, { "code": null, "e": 2810, "s": 2802, "text": "Android" }, { "code": null, "e": 2815, "s": 2810, "text": "Java" }, { "code": null, "e": 2820, "s": 2815, "text": "Java" }, { "code": null, "e": 2828, "s": 2820, "text": "Android" }, { "code": null, "e": 2926, "s": 2828, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 2995, "s": 2926, "text": "How to Add Views Dynamically and Store Data in Arraylist in Android?" }, { "code": null, "e": 3026, "s": 2995, "text": "Android RecyclerView in Kotlin" }, { "code": null, "e": 3058, "s": 3026, "text": "Android SDK and it's Components" }, { "code": null, "e": 3107, "s": 3058, "text": "How to Communicate Between Fragments in Android?" }, { "code": null, "e": 3150, "s": 3107, "text": "Broadcast Receiver in Android With Example" }, { "code": null, "e": 3165, "s": 3150, "text": "Arrays in Java" }, { "code": null, "e": 3209, "s": 3165, "text": "Split() String method in Java with examples" }, { "code": null, "e": 3245, "s": 3209, "text": "Arrays.sort() in Java with examples" }, { "code": null, "e": 3270, "s": 3245, "text": "Reverse a string in Java" } ]
MariaDB - Transactions
Transactions are sequential group operations. They function as a single unit, and do not terminate until all operations within the group execute successfully. A single failure in the group causes the entire transaction to fail, and causes it to have no impact on the database. Transactions conform to ACID (Atomicity, Consistency, Isolation, and Durability) − Atomicity − It ensures the success of all operations by aborting on failures and rolling back changes. Atomicity − It ensures the success of all operations by aborting on failures and rolling back changes. Consistency − It ensures the database applies changes on a successful transaction. Consistency − It ensures the database applies changes on a successful transaction. Isolation − It enables independent transactions operation of transactions. Isolation − It enables independent transactions operation of transactions. Durability − It ensures the persistence of a successful transaction in the event of system failure. Durability − It ensures the persistence of a successful transaction in the event of system failure. At the head of a transaction statement is the START TRANSACTION statement followed by COMMIT and ROLLBACK statements − START TRANSACTION begins the transaction. START TRANSACTION begins the transaction. COMMIT saves changes to data. COMMIT saves changes to data. ROLLBACK ends the transaction, destroying any changes. ROLLBACK ends the transaction, destroying any changes. On a successful transaction, COMMIT acts. On a failure, ROLLBACK acts. Note − Some statements cause an implicit commit, and they also cause an error when used within transactions. Examples of such statements include, but are not limited to CREATE, ALTER, and DROP. MariaDB transactions also include options like SAVEPOINT and LOCK TABLES. SAVEPOINT sets a restore point to utilize with ROLLBACK. LOCK TABLES allows controlling access to tables during sessions to prevent modifications during certain time periods. The AUTOCOMMIT variable provides control over transactions. A setting of 1 forces all operations to be considered successful transactions, and a setting of 0 causes persistence of changes to only occur on an explicit COMMIT statement. The general structure of a transaction statement consists of beginning with START TRANSACTION. The next step is inserting one or more commands/operations, inserting statements that check for errors, inserting ROLLBACK statements to manage any errors discovered and finally inserting a COMMIT statement to apply changes on successful operations. Review the example given below − START TRANSACTION; SELECT name FROM products WHERE manufacturer = 'XYZ Corp'; UPDATE spring_products SET item = name;
[ { "code": null, "e": 2773, "s": 2496, "text": "Transactions are sequential group operations. They function as a single unit, and do not terminate until all operations within the group execute successfully. A single failure in the group causes the entire transaction to fail, and causes it to have no impact on the database." }, { "code": null, "e": 2856, "s": 2773, "text": "Transactions conform to ACID (Atomicity, Consistency, Isolation, and Durability) −" }, { "code": null, "e": 2959, "s": 2856, "text": "Atomicity − It ensures the success of all operations by aborting on failures and rolling back changes." }, { "code": null, "e": 3062, "s": 2959, "text": "Atomicity − It ensures the success of all operations by aborting on failures and rolling back changes." }, { "code": null, "e": 3145, "s": 3062, "text": "Consistency − It ensures the database applies changes on a successful transaction." }, { "code": null, "e": 3228, "s": 3145, "text": "Consistency − It ensures the database applies changes on a successful transaction." }, { "code": null, "e": 3303, "s": 3228, "text": "Isolation − It enables independent transactions operation of transactions." }, { "code": null, "e": 3378, "s": 3303, "text": "Isolation − It enables independent transactions operation of transactions." }, { "code": null, "e": 3478, "s": 3378, "text": "Durability − It ensures the persistence of a successful transaction in the event of system failure." }, { "code": null, "e": 3578, "s": 3478, "text": "Durability − It ensures the persistence of a successful transaction in the event of system failure." }, { "code": null, "e": 3697, "s": 3578, "text": "At the head of a transaction statement is the START TRANSACTION statement followed by COMMIT and ROLLBACK statements −" }, { "code": null, "e": 3739, "s": 3697, "text": "START TRANSACTION begins the transaction." }, { "code": null, "e": 3781, "s": 3739, "text": "START TRANSACTION begins the transaction." }, { "code": null, "e": 3811, "s": 3781, "text": "COMMIT saves changes to data." }, { "code": null, "e": 3841, "s": 3811, "text": "COMMIT saves changes to data." }, { "code": null, "e": 3896, "s": 3841, "text": "ROLLBACK ends the transaction, destroying any changes." }, { "code": null, "e": 3951, "s": 3896, "text": "ROLLBACK ends the transaction, destroying any changes." }, { "code": null, "e": 4022, "s": 3951, "text": "On a successful transaction, COMMIT acts. On a failure, ROLLBACK acts." }, { "code": null, "e": 4216, "s": 4022, "text": "Note − Some statements cause an implicit commit, and they also cause an error when used within transactions. Examples of such statements include, but are not limited to CREATE, ALTER, and DROP." }, { "code": null, "e": 4465, "s": 4216, "text": "MariaDB transactions also include options like SAVEPOINT and LOCK TABLES. SAVEPOINT sets a restore point to utilize with ROLLBACK. LOCK TABLES allows controlling access to tables during sessions to prevent modifications during certain time periods." }, { "code": null, "e": 4700, "s": 4465, "text": "The AUTOCOMMIT variable provides control over transactions. A setting of 1 forces all operations to be considered successful transactions, and a setting of 0 causes persistence of changes to only occur on an explicit COMMIT statement." }, { "code": null, "e": 5045, "s": 4700, "text": "The general structure of a transaction statement consists of beginning with START TRANSACTION. The next step is inserting one or more commands/operations, inserting statements that check for errors, inserting ROLLBACK statements to manage any errors discovered and finally inserting a COMMIT statement to apply changes on successful operations." }, { "code": null, "e": 5078, "s": 5045, "text": "Review the example given below −" } ]
Python - Deque
A double-ended queue, or deque, has the feature of adding and removing elements from either end. The Deque module is a part of collections library. It has the methods for adding and removing elements which can be invoked directly with arguments. In the below program we import the collections module and declare a deque. Without need of any class we use the in-built implement these methods directly. import collections # Create a deque DoubleEnded = collections.deque(["Mon","Tue","Wed"]) print (DoubleEnded) # Append to the right print("Adding to the right: ") DoubleEnded.append("Thu") print (DoubleEnded) # append to the left print("Adding to the left: ") DoubleEnded.appendleft("Sun") print (DoubleEnded) # Remove from the right print("Removing from the right: ") DoubleEnded.pop() print (DoubleEnded) # Remove from the left print("Removing from the left: ") DoubleEnded.popleft() print (DoubleEnded) # Reverse the dequeue print("Reversing the deque: ") DoubleEnded.reverse() print (DoubleEnded) When the above code is executed, it produces the following result: deque(['Mon', 'Tue', 'Wed']) Adding to the right: deque(['Mon', 'Tue', 'Wed', 'Thu']) Adding to the left: deque(['Sun', 'Mon', 'Tue', 'Wed', 'Thu']) Removing from the right: deque(['Sun', 'Mon', 'Tue', 'Wed']) Removing from the left: deque(['Mon', 'Tue', 'Wed']) Reversing the deque: deque(['Wed', 'Tue', 'Mon'])
[ { "code": null, "e": 2779, "s": 2378, "text": "A double-ended queue, or deque, has the feature of adding and removing elements from either end. The Deque module is a part of collections library.\nIt has the methods for adding and removing elements which can be invoked directly with arguments. In the below program we import the collections module and declare a deque.\nWithout need of any class we use the in-built implement these methods directly." }, { "code": null, "e": 3386, "s": 2779, "text": "\n\nimport collections\n# Create a deque\nDoubleEnded = collections.deque([\"Mon\",\"Tue\",\"Wed\"])\nprint (DoubleEnded)\n\n# Append to the right\nprint(\"Adding to the right: \")\nDoubleEnded.append(\"Thu\")\nprint (DoubleEnded)\n\n# append to the left\nprint(\"Adding to the left: \")\nDoubleEnded.appendleft(\"Sun\")\nprint (DoubleEnded)\n\n# Remove from the right\nprint(\"Removing from the right: \")\nDoubleEnded.pop()\nprint (DoubleEnded)\n\n# Remove from the left\nprint(\"Removing from the left: \")\nDoubleEnded.popleft()\nprint (DoubleEnded)\n\n# Reverse the dequeue\nprint(\"Reversing the deque: \")\nDoubleEnded.reverse()\nprint (DoubleEnded)" }, { "code": null, "e": 3454, "s": 3386, "text": "When the above code is executed, it produces the following result: " } ]
How to create an empty matrix in R ?
25 Feb, 2022 The term empty matrix has no rows and no columns. A matrix that contains missing values has at least one row and column, as does a matrix that contains zeros. In this article, we are going to see how to create an empty matrix in R Programming Language. There are three ways of creating an empty matrix: Using row and column. Using only row. Using only column. Method 1: Using both row and column: Here in this, we need to pass both row and column to create an empty matrix: Syntax: matrix name = matrix(, nrow = value 1, ncol = value2) Where: Here matrix name can be any valid identifier Value 1 is for number of rows. Value 2 is for number of columns. Example 1: In the below example, we created a mat variable, After creating mat variable we are using the matrix function to create a matrix and mentioning a number of rows and columns in it. Below is the implementation: R # creating empty matrix,# storing in variable mat and passing# number of rows and columnsmat = matrix(, nrow = 1, ncol = 1) # printing empty matrix.print(mat) Output: Here we got NA as output which means not a number or not available. Example 2: R # creating empty matrix,# storing in variable mat1 and passing@ number of rows and columnsmat1 = matrix(, nrow = 10, ncol = 10) # printing empty matrix.print(mat1) Output: Method 2: Using only row : Here we need to pass the only one row to create an empty matrix Syntax: matrix name = matrix(, nrow = value 1) Where, Here matrix name can be any valid identifier value 1 is for number of rows. Example 1: R Mat<-matrix(,nrow=10) # printing empty matrix.print(Mat) Output: Method 3: Using only column. Here we need to pass the only columns to create an empty matrix. Syntax: matrix name = matrix(, ncol = value 1) Where, Here matrix name can be any valid identifier Value 1 is for number of column. Below is the implementation: R Mat<-matrix(,ncol=10) #printing empty matrix.print(Mat) Output: sweetyty vinayakmraj Picked R Matrix-Programs R-Matrix R Language R Programs Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n25 Feb, 2022" }, { "code": null, "e": 281, "s": 28, "text": "The term empty matrix has no rows and no columns. A matrix that contains missing values has at least one row and column, as does a matrix that contains zeros. In this article, we are going to see how to create an empty matrix in R Programming Language." }, { "code": null, "e": 331, "s": 281, "text": "There are three ways of creating an empty matrix:" }, { "code": null, "e": 353, "s": 331, "text": "Using row and column." }, { "code": null, "e": 369, "s": 353, "text": "Using only row." }, { "code": null, "e": 388, "s": 369, "text": "Using only column." }, { "code": null, "e": 425, "s": 388, "text": "Method 1: Using both row and column:" }, { "code": null, "e": 502, "s": 425, "text": "Here in this, we need to pass both row and column to create an empty matrix:" }, { "code": null, "e": 564, "s": 502, "text": "Syntax: matrix name = matrix(, nrow = value 1, ncol = value2)" }, { "code": null, "e": 571, "s": 564, "text": "Where:" }, { "code": null, "e": 616, "s": 571, "text": "Here matrix name can be any valid identifier" }, { "code": null, "e": 647, "s": 616, "text": "Value 1 is for number of rows." }, { "code": null, "e": 681, "s": 647, "text": "Value 2 is for number of columns." }, { "code": null, "e": 872, "s": 681, "text": "Example 1: In the below example, we created a mat variable, After creating mat variable we are using the matrix function to create a matrix and mentioning a number of rows and columns in it." }, { "code": null, "e": 901, "s": 872, "text": "Below is the implementation:" }, { "code": null, "e": 903, "s": 901, "text": "R" }, { "code": "# creating empty matrix,# storing in variable mat and passing# number of rows and columnsmat = matrix(, nrow = 1, ncol = 1) # printing empty matrix.print(mat)", "e": 1062, "s": 903, "text": null }, { "code": null, "e": 1071, "s": 1062, "text": "Output: " }, { "code": null, "e": 1139, "s": 1071, "text": "Here we got NA as output which means not a number or not available." }, { "code": null, "e": 1151, "s": 1139, "text": "Example 2: " }, { "code": null, "e": 1153, "s": 1151, "text": "R" }, { "code": "# creating empty matrix,# storing in variable mat1 and passing@ number of rows and columnsmat1 = matrix(, nrow = 10, ncol = 10) # printing empty matrix.print(mat1)", "e": 1317, "s": 1153, "text": null }, { "code": null, "e": 1326, "s": 1317, "text": "Output: " }, { "code": null, "e": 1353, "s": 1326, "text": "Method 2: Using only row :" }, { "code": null, "e": 1418, "s": 1353, "text": "Here we need to pass the only one row to create an empty matrix " }, { "code": null, "e": 1465, "s": 1418, "text": "Syntax: matrix name = matrix(, nrow = value 1)" }, { "code": null, "e": 1472, "s": 1465, "text": "Where," }, { "code": null, "e": 1517, "s": 1472, "text": "Here matrix name can be any valid identifier" }, { "code": null, "e": 1548, "s": 1517, "text": "value 1 is for number of rows." }, { "code": null, "e": 1560, "s": 1548, "text": "Example 1: " }, { "code": null, "e": 1562, "s": 1560, "text": "R" }, { "code": "Mat<-matrix(,nrow=10) # printing empty matrix.print(Mat)", "e": 1619, "s": 1562, "text": null }, { "code": null, "e": 1627, "s": 1619, "text": "Output:" }, { "code": null, "e": 1656, "s": 1627, "text": "Method 3: Using only column." }, { "code": null, "e": 1721, "s": 1656, "text": "Here we need to pass the only columns to create an empty matrix." }, { "code": null, "e": 1768, "s": 1721, "text": "Syntax: matrix name = matrix(, ncol = value 1)" }, { "code": null, "e": 1775, "s": 1768, "text": "Where," }, { "code": null, "e": 1820, "s": 1775, "text": "Here matrix name can be any valid identifier" }, { "code": null, "e": 1853, "s": 1820, "text": "Value 1 is for number of column." }, { "code": null, "e": 1882, "s": 1853, "text": "Below is the implementation:" }, { "code": null, "e": 1884, "s": 1882, "text": "R" }, { "code": "Mat<-matrix(,ncol=10) #printing empty matrix.print(Mat)", "e": 1940, "s": 1884, "text": null }, { "code": null, "e": 1948, "s": 1940, "text": "Output:" }, { "code": null, "e": 1957, "s": 1948, "text": "sweetyty" }, { "code": null, "e": 1969, "s": 1957, "text": "vinayakmraj" }, { "code": null, "e": 1976, "s": 1969, "text": "Picked" }, { "code": null, "e": 1994, "s": 1976, "text": "R Matrix-Programs" }, { "code": null, "e": 2003, "s": 1994, "text": "R-Matrix" }, { "code": null, "e": 2014, "s": 2003, "text": "R Language" }, { "code": null, "e": 2025, "s": 2014, "text": "R Programs" } ]
Stream Ciphers
16 Oct, 2020 In stream cipher, one byte is encrypted at a time while in block cipher ~128 bits are encrypted at a time. Initially, a key(k) will be supplied as input to pseudorandom bit generator and then it produces a random 8-bit output which is treated as keystream. The resulted keystream will be of size 1 byte, i.e., 8 bits. Stream Cipher follows the sequence of pseudorandom number stream.One of the benefits of following stream cipher is to make cryptanalysis more difficult, so the number of bits chosen in the Keystream must be long in order to make cryptanalysis more difficult.By making the key more longer it is also safe against brute force attacks.The longer the key the stronger security is achieved, preventing any attack.Keystream can be designed more efficiently by including more number of 1s and 0s, for making cryptanalysis more difficult.Considerable benefit of a stream cipher is, it requires few lines of code compared to block cipher. Stream Cipher follows the sequence of pseudorandom number stream. One of the benefits of following stream cipher is to make cryptanalysis more difficult, so the number of bits chosen in the Keystream must be long in order to make cryptanalysis more difficult. By making the key more longer it is also safe against brute force attacks. The longer the key the stronger security is achieved, preventing any attack. Keystream can be designed more efficiently by including more number of 1s and 0s, for making cryptanalysis more difficult. Considerable benefit of a stream cipher is, it requires few lines of code compared to block cipher. Encryption :For Encryption, Plain Text and Keystream produces Cipher Text (Same keystream will be used for decryption.). The Plaintext will undergo XOR operation with keystream bit-by-bit and produces the Cipher Text. Example – Plain Text : 10011001 Keystream : 11000011 ````````````````````` Cipher Text : 01011010 Decryption :For Decryption, Cipher Text and Keystream gives the original Plain Text (Same keystream will be used for encryption.). The Ciphertext will undergo XOR operation with keystream bit-by-bit and produces the actual Plain Text. Example – Cipher Text : 01011010 Keystream : 11000011 `````````````````````` Plain Text : 10011001 Decryption is just the reverse process of Encryption i.e. performing XOR with Cipher Text. Diagram of Stream Cipher cryptography Network-security Computer Networks cryptography Computer Networks Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. GSM in Wireless Communication Secure Socket Layer (SSL) Wireless Application Protocol Mobile Internet Protocol (or Mobile IP) Introduction of Mobile Ad hoc Network (MANET) Advanced Encryption Standard (AES) Bluetooth Intrusion Detection System (IDS) Cryptography and its Types Difference between FDMA, TDMA and CDMA
[ { "code": null, "e": 54, "s": 26, "text": "\n16 Oct, 2020" }, { "code": null, "e": 161, "s": 54, "text": "In stream cipher, one byte is encrypted at a time while in block cipher ~128 bits are encrypted at a time." }, { "code": null, "e": 311, "s": 161, "text": "Initially, a key(k) will be supplied as input to pseudorandom bit generator and then it produces a random 8-bit output which is treated as keystream." }, { "code": null, "e": 372, "s": 311, "text": "The resulted keystream will be of size 1 byte, i.e., 8 bits." }, { "code": null, "e": 1002, "s": 372, "text": "Stream Cipher follows the sequence of pseudorandom number stream.One of the benefits of following stream cipher is to make cryptanalysis more difficult, so the number of bits chosen in the Keystream must be long in order to make cryptanalysis more difficult.By making the key more longer it is also safe against brute force attacks.The longer the key the stronger security is achieved, preventing any attack.Keystream can be designed more efficiently by including more number of 1s and 0s, for making cryptanalysis more difficult.Considerable benefit of a stream cipher is, it requires few lines of code compared to block cipher." }, { "code": null, "e": 1068, "s": 1002, "text": "Stream Cipher follows the sequence of pseudorandom number stream." }, { "code": null, "e": 1262, "s": 1068, "text": "One of the benefits of following stream cipher is to make cryptanalysis more difficult, so the number of bits chosen in the Keystream must be long in order to make cryptanalysis more difficult." }, { "code": null, "e": 1337, "s": 1262, "text": "By making the key more longer it is also safe against brute force attacks." }, { "code": null, "e": 1414, "s": 1337, "text": "The longer the key the stronger security is achieved, preventing any attack." }, { "code": null, "e": 1537, "s": 1414, "text": "Keystream can be designed more efficiently by including more number of 1s and 0s, for making cryptanalysis more difficult." }, { "code": null, "e": 1637, "s": 1537, "text": "Considerable benefit of a stream cipher is, it requires few lines of code compared to block cipher." }, { "code": null, "e": 1665, "s": 1637, "text": "Encryption :For Encryption," }, { "code": null, "e": 1758, "s": 1665, "text": "Plain Text and Keystream produces Cipher Text (Same keystream will be used for decryption.)." }, { "code": null, "e": 1855, "s": 1758, "text": "The Plaintext will undergo XOR operation with keystream bit-by-bit and produces the Cipher Text." }, { "code": null, "e": 1865, "s": 1855, "text": "Example –" }, { "code": null, "e": 1955, "s": 1865, "text": "Plain Text : 10011001\nKeystream : 11000011\n`````````````````````\nCipher Text : 01011010\n" }, { "code": null, "e": 1983, "s": 1955, "text": "Decryption :For Decryption," }, { "code": null, "e": 2086, "s": 1983, "text": "Cipher Text and Keystream gives the original Plain Text (Same keystream will be used for encryption.)." }, { "code": null, "e": 2190, "s": 2086, "text": "The Ciphertext will undergo XOR operation with keystream bit-by-bit and produces the actual Plain Text." }, { "code": null, "e": 2200, "s": 2190, "text": "Example –" }, { "code": null, "e": 2294, "s": 2200, "text": "Cipher Text : 01011010\nKeystream : 11000011\n`````````````````````` \nPlain Text : 10011001\n" }, { "code": null, "e": 2385, "s": 2294, "text": "Decryption is just the reverse process of Encryption i.e. performing XOR with Cipher Text." }, { "code": null, "e": 2410, "s": 2385, "text": "Diagram of Stream Cipher" }, { "code": null, "e": 2423, "s": 2410, "text": "cryptography" }, { "code": null, "e": 2440, "s": 2423, "text": "Network-security" }, { "code": null, "e": 2458, "s": 2440, "text": "Computer Networks" }, { "code": null, "e": 2471, "s": 2458, "text": "cryptography" }, { "code": null, "e": 2489, "s": 2471, "text": "Computer Networks" }, { "code": null, "e": 2587, "s": 2489, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 2617, "s": 2587, "text": "GSM in Wireless Communication" }, { "code": null, "e": 2643, "s": 2617, "text": "Secure Socket Layer (SSL)" }, { "code": null, "e": 2673, "s": 2643, "text": "Wireless Application Protocol" }, { "code": null, "e": 2713, "s": 2673, "text": "Mobile Internet Protocol (or Mobile IP)" }, { "code": null, "e": 2759, "s": 2713, "text": "Introduction of Mobile Ad hoc Network (MANET)" }, { "code": null, "e": 2794, "s": 2759, "text": "Advanced Encryption Standard (AES)" }, { "code": null, "e": 2804, "s": 2794, "text": "Bluetooth" }, { "code": null, "e": 2837, "s": 2804, "text": "Intrusion Detection System (IDS)" }, { "code": null, "e": 2864, "s": 2837, "text": "Cryptography and its Types" } ]
How to install Python libraries without using the pip command?
06 Oct, 2021 The most common practice of installing external libraries in your system is by using the Python pip command. However, there is an alternate method of manually installing Python libraries without using the pip command. In this article, we are going to discuss how to manually install a python package. Below is the Step-by-step approach to manually install selenium library in a system. Step 1: Downloading the files Go to the https://pypi.org/ website find the package you want to install From the menu on the left-hand side click the download files button. Here I have taken the example of the selenium library. Make sure to download .tar.gz file downloading files .tar.tz Step 2: Unzip the files downloaded if they are zipped using any unzipping software. Step 3: Change the current working directory to the file containing Setup.py using the cd command. cd command Step 4: Read the installation instructions carefully and install as directed. Step 5: After changing the current working directory to the file containing Setup.py type the following command: python setup.py install setup.py Final That’s it, now you are ready to use the installed library and you can import this library in your python program. how-to-install python-utility How To Installation Guide Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n06 Oct, 2021" }, { "code": null, "e": 246, "s": 28, "text": "The most common practice of installing external libraries in your system is by using the Python pip command. However, there is an alternate method of manually installing Python libraries without using the pip command." }, { "code": null, "e": 331, "s": 246, "text": "In this article, we are going to discuss how to manually install a python package. " }, { "code": null, "e": 417, "s": 331, "text": "Below is the Step-by-step approach to manually install selenium library in a system. " }, { "code": null, "e": 447, "s": 417, "text": "Step 1: Downloading the files" }, { "code": null, "e": 520, "s": 447, "text": "Go to the https://pypi.org/ website find the package you want to install" }, { "code": null, "e": 589, "s": 520, "text": "From the menu on the left-hand side click the download files button." }, { "code": null, "e": 644, "s": 589, "text": "Here I have taken the example of the selenium library." }, { "code": null, "e": 679, "s": 644, "text": "Make sure to download .tar.gz file" }, { "code": null, "e": 697, "s": 679, "text": "downloading files" }, { "code": null, "e": 705, "s": 697, "text": ".tar.tz" }, { "code": null, "e": 789, "s": 705, "text": "Step 2: Unzip the files downloaded if they are zipped using any unzipping software." }, { "code": null, "e": 888, "s": 789, "text": "Step 3: Change the current working directory to the file containing Setup.py using the cd command." }, { "code": null, "e": 899, "s": 888, "text": "cd command" }, { "code": null, "e": 977, "s": 899, "text": "Step 4: Read the installation instructions carefully and install as directed." }, { "code": null, "e": 1090, "s": 977, "text": "Step 5: After changing the current working directory to the file containing Setup.py type the following command:" }, { "code": null, "e": 1114, "s": 1090, "text": "python setup.py install" }, { "code": null, "e": 1123, "s": 1114, "text": "setup.py" }, { "code": null, "e": 1129, "s": 1123, "text": "Final" }, { "code": null, "e": 1243, "s": 1129, "text": "That’s it, now you are ready to use the installed library and you can import this library in your python program." }, { "code": null, "e": 1258, "s": 1243, "text": "how-to-install" }, { "code": null, "e": 1273, "s": 1258, "text": "python-utility" }, { "code": null, "e": 1280, "s": 1273, "text": "How To" }, { "code": null, "e": 1299, "s": 1280, "text": "Installation Guide" }, { "code": null, "e": 1306, "s": 1299, "text": "Python" } ]
Symmetric difference of two sorted array
29 Apr, 2021 There are two sorted array arr1 and arr2. We have to find the symmetric difference of Aarr1 and arr2. Symmetric Difference basically contains all elements of two arrays except common elements. Symmetric difference of two array is the all array elements of both array except the elements that are presents in both array. SymmDiff = (arr1 - arr2) UNION (arr2 - arr1). OR SymmDiff = (arr1 UNION arr2) - (arr1 INTERSECTION arr2). Examples: Input : arr1[] = {2, 4, 5, 7, 8, 10, 12, 15}. arr2[] = {5, 8, 11, 12, 14, 15}. Output : 2 4 7 10 11 14 arr1[] - arr2[] = {2, 4, 7, 10}. arr[2] - arr1[] = {11, 14}. SymmDiff = (arr1[] - arr2[]) UNION (arr2[] - arr1[]). = {2, 4, 7, 10, 11, 14}. Input : arr1[] = {1, 3, 5, 8, 15, 27, 35}. arr2[] = {5, 7, 8, 11, 15, 18, 35}. Output : 1 3 7 11 18 27 arr1[] - arr2[] = {1, 3, 27}. arr[2] - arr1[] = {7, 11, 18}. SymmDiff = (arr1[] - arr2[]) UNION (arr2[] - arr1[]). = {1, 3, 7, 11, 18, 27}. A Simple Solution is to traverse through both arrays one by one. For every element of one array, check if it is present in other array. If yes, then ignore it, else print it. Time complexity of this solution is O(n*n)An Efficient solution for finding the symmetric difference of two sorted arrays is similar to merge process of merge sort. We traverse both arrays simultaneously and print smaller elements if current two elements do not match and move ahead in array with smaller element. Else we ignore the elements and move ahead in both arrays. C++ Java Python3 C# PHP Javascript // C++ program to find the symmetric difference// of two sorted array.#include <iostream>using namespace std;void symmDiff(int arr1[], int arr2[], int n, int m){ // Traverse both arrays simultaneously. int i = 0, j = 0; while (i < n && j < m) { // Print smaller element and move // ahead in array with smaller element if (arr1[i] < arr2[j]) { cout << arr1[i] << " "; i++; } else if (arr2[j] < arr1[i]) { cout << arr2[j] << " "; j++; } // If both elements same, move ahead // in both arrays. else { i++; j++; } } while (i < n) { cout << arr1[i] << " "; i++; } while (j < m) { cout << arr2[j] << " "; j++; }} // Driver codeint main(){ int arr1[] = { 2, 4, 5, 7, 8, 10, 12, 15 }; int arr2[] = { 5, 8, 11, 12, 14, 15 }; int n = sizeof(arr1) / sizeof(arr1[0]); int m = sizeof(arr2) / sizeof(arr2[0]); symmDiff(arr1, arr2, n, m); return 0;} // Java program to find the symmetric// difference of two sorted array.import java.util.*;class GFG { static void symmDiff(int[] arr1, int[] arr2, int n, int m) { // Traverse both arrays simultaneously. int i = 0, j = 0; while (i < n && j < m) { // Print smaller element and move // ahead in array with smaller element if (arr1[i] < arr2[j]) { System.out.print(arr1[i] + " "); i++; } else if (arr2[j] < arr1[i]) { System.out.print(arr2[j] + " "); j++; } // If both elements same, move ahead // in both arrays. else { i++; j++; } } while (i < n) { System.out.print(arr1[i] + " "); i++; } while (j < m) { System.out.print(arr2[j] + " "); j++; } } // Driver code public static void main(String[] args) { int[] arr1 = { 2, 4, 5, 7, 8, 10, 12, 15 }; int[] arr2 = { 5, 8, 11, 12, 14, 15 }; int n = arr1.length; int m = arr2.length; symmDiff(arr1, arr2, n, m); }}/* This code is contributed by Kriti Shukla */ # Python3 program to# find the symmetric# difference of two# sorted array. def symmDiff(arr1, arr2, n, m): # Traverse both arrays # simultaneously. i = 0 j = 0 while (i < n and j < m): # Print smaller element # and move ahead in # array with smaller # element if (arr1[i] < arr2[j]): print(arr1[i], end=" ") i += 1 elif (arr2[j] < arr1[i]): print(arr2[j], end=" ") j += 1 # If both elements # same, move ahead # in both arrays. else: i += 1 j += 1 while i < n: print(arr1[i], end=' ') i += 1 while j < m: print(arr2[j], end=' ') j += 1 # Driver codearr1 = [2, 4, 5, 7, 8, 10, 12, 15]arr2 = [5, 8, 11, 12, 14, 15]n = len(arr1)m = len(arr2) symmDiff(arr1, arr2, n, m) # This code is contributed by Smitha Dinesh Semwal // C# program to find the symmetric// difference of two sorted array.using System; class GFG { static void symmDiff(int[] arr1, int[] arr2, int n, int m) { // Traverse both arrays simultaneously. int i = 0, j = 0; while (i < n && j < m) { // Print smaller element and move // ahead in array with smaller element if (arr1[i] < arr2[j]) { Console.Write(arr1[i] + " "); i++; } else if (arr2[j] < arr1[i]) { Console.Write(arr2[j] + " "); j++; } // If both elements same, move ahead // in both arrays. else { i++; j++; } } while (i < n) { Console.Write(arr1[i] + " "); i++; } while (j < m) { Console.Write(arr2[j] + " "); j++; } } // Driver code public static void Main() { int[] arr1 = { 2, 4, 5, 7, 8, 10, 12, 15 }; int[] arr2 = { 5, 8, 11, 12, 14, 15 }; int n = arr1.Length; int m = arr2.Length; symmDiff(arr1, arr2, n, m); }} /* This code is contributed by vt_m*/ <?php// PHP program to find the// symmetric difference// of two sorted array.function symmDiff($arr1, $arr2, $n, $m){ // Traverse both arrays // simultaneously. $i = 0; $j = 0; while ($i < $n && $j < $m) { // Print smaller element // and move ahead in array // with smaller element if ($arr1[$i] < $arr2[$j]) { echo($arr1[$i] . " "); $i++; } else if ($arr2[$j] < $arr1[$i]) { echo($arr2[$j] . " "); $j++; } // If both elements same, // move ahead in both arrays else { $i++; $j++; } } while ($i < $n) { echo($arr1[$i] . " "); $i++; } while ($j < $m) { echo($arr2[$j] . " "); $j++; }} // Driver code$arr1 = array(2, 4, 5, 7, 8, 10, 12, 15);$arr2 = array(5, 8, 11, 12, 14, 15);$n = sizeof($arr1);$m = sizeof($arr2);symmDiff($arr1, $arr2, $n, $m); // This code is contributed by Ajit.?> <script> // Javascript program to find the symmetric // difference of two sorted array. function symmDiff(arr1, arr2, n, m) { // Traverse both arrays simultaneously. let i = 0, j = 0; while (i < n && j < m) { // Print smaller element and move // ahead in array with smaller element if (arr1[i] < arr2[j]) { document.write(arr1[i] + " "); i++; } else if (arr2[j] < arr1[i]) { document.write(arr2[j] + " "); j++; } // If both elements same, move ahead // in both arrays. else { i++; j++; } } while (i < n) { document.write(arr1[i] + " "); i++; } while (j < m) { document.write(arr2[j] + " "); j++; } } let arr1 = [ 2, 4, 5, 7, 8, 10, 12, 15 ]; let arr2 = [ 5, 8, 11, 12, 14, 15 ]; let n = arr1.length; let m = arr2.length; symmDiff(arr1, arr2, n, m); </script> Output: 2 4 7 10 11 14 Time Complexity: O(m + n).This article is contributed by Dharmendra kumar. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. jit_t banerjeesouvik18 hungrywolf decode2207 Arrays Arrays Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 53, "s": 25, "text": "\n29 Apr, 2021" }, { "code": null, "e": 247, "s": 53, "text": "There are two sorted array arr1 and arr2. We have to find the symmetric difference of Aarr1 and arr2. Symmetric Difference basically contains all elements of two arrays except common elements. " }, { "code": null, "e": 498, "s": 247, "text": "Symmetric difference of two array is the all \narray elements of both array except the elements \nthat are presents in both array.\nSymmDiff = (arr1 - arr2) UNION (arr2 - arr1). \n OR\nSymmDiff = (arr1 UNION arr2) - (arr1 INTERSECTION arr2)." }, { "code": null, "e": 510, "s": 498, "text": "Examples: " }, { "code": null, "e": 1144, "s": 510, "text": "Input : arr1[] = {2, 4, 5, 7, 8, 10, 12, 15}.\n arr2[] = {5, 8, 11, 12, 14, 15}.\nOutput : 2 4 7 10 11 14 \n arr1[] - arr2[] = {2, 4, 7, 10}.\n arr[2] - arr1[] = {11, 14}.\n SymmDiff = (arr1[] - arr2[]) UNION \n (arr2[] - arr1[]).\n = {2, 4, 7, 10, 11, 14}.\n\n\nInput : arr1[] = {1, 3, 5, 8, 15, 27, 35}.\n arr2[] = {5, 7, 8, 11, 15, 18, 35}.\nOutput : 1 3 7 11 18 27\n arr1[] - arr2[] = {1, 3, 27}.\n arr[2] - arr1[] = {7, 11, 18}.\n SymmDiff = (arr1[] - arr2[]) UNION \n (arr2[] - arr1[]).\n = {1, 3, 7, 11, 18, 27}." }, { "code": null, "e": 1693, "s": 1144, "text": "A Simple Solution is to traverse through both arrays one by one. For every element of one array, check if it is present in other array. If yes, then ignore it, else print it. Time complexity of this solution is O(n*n)An Efficient solution for finding the symmetric difference of two sorted arrays is similar to merge process of merge sort. We traverse both arrays simultaneously and print smaller elements if current two elements do not match and move ahead in array with smaller element. Else we ignore the elements and move ahead in both arrays. " }, { "code": null, "e": 1697, "s": 1693, "text": "C++" }, { "code": null, "e": 1702, "s": 1697, "text": "Java" }, { "code": null, "e": 1710, "s": 1702, "text": "Python3" }, { "code": null, "e": 1713, "s": 1710, "text": "C#" }, { "code": null, "e": 1717, "s": 1713, "text": "PHP" }, { "code": null, "e": 1728, "s": 1717, "text": "Javascript" }, { "code": "// C++ program to find the symmetric difference// of two sorted array.#include <iostream>using namespace std;void symmDiff(int arr1[], int arr2[], int n, int m){ // Traverse both arrays simultaneously. int i = 0, j = 0; while (i < n && j < m) { // Print smaller element and move // ahead in array with smaller element if (arr1[i] < arr2[j]) { cout << arr1[i] << \" \"; i++; } else if (arr2[j] < arr1[i]) { cout << arr2[j] << \" \"; j++; } // If both elements same, move ahead // in both arrays. else { i++; j++; } } while (i < n) { cout << arr1[i] << \" \"; i++; } while (j < m) { cout << arr2[j] << \" \"; j++; }} // Driver codeint main(){ int arr1[] = { 2, 4, 5, 7, 8, 10, 12, 15 }; int arr2[] = { 5, 8, 11, 12, 14, 15 }; int n = sizeof(arr1) / sizeof(arr1[0]); int m = sizeof(arr2) / sizeof(arr2[0]); symmDiff(arr1, arr2, n, m); return 0;}", "e": 2778, "s": 1728, "text": null }, { "code": "// Java program to find the symmetric// difference of two sorted array.import java.util.*;class GFG { static void symmDiff(int[] arr1, int[] arr2, int n, int m) { // Traverse both arrays simultaneously. int i = 0, j = 0; while (i < n && j < m) { // Print smaller element and move // ahead in array with smaller element if (arr1[i] < arr2[j]) { System.out.print(arr1[i] + \" \"); i++; } else if (arr2[j] < arr1[i]) { System.out.print(arr2[j] + \" \"); j++; } // If both elements same, move ahead // in both arrays. else { i++; j++; } } while (i < n) { System.out.print(arr1[i] + \" \"); i++; } while (j < m) { System.out.print(arr2[j] + \" \"); j++; } } // Driver code public static void main(String[] args) { int[] arr1 = { 2, 4, 5, 7, 8, 10, 12, 15 }; int[] arr2 = { 5, 8, 11, 12, 14, 15 }; int n = arr1.length; int m = arr2.length; symmDiff(arr1, arr2, n, m); }}/* This code is contributed by Kriti Shukla */", "e": 4063, "s": 2778, "text": null }, { "code": "# Python3 program to# find the symmetric# difference of two# sorted array. def symmDiff(arr1, arr2, n, m): # Traverse both arrays # simultaneously. i = 0 j = 0 while (i < n and j < m): # Print smaller element # and move ahead in # array with smaller # element if (arr1[i] < arr2[j]): print(arr1[i], end=\" \") i += 1 elif (arr2[j] < arr1[i]): print(arr2[j], end=\" \") j += 1 # If both elements # same, move ahead # in both arrays. else: i += 1 j += 1 while i < n: print(arr1[i], end=' ') i += 1 while j < m: print(arr2[j], end=' ') j += 1 # Driver codearr1 = [2, 4, 5, 7, 8, 10, 12, 15]arr2 = [5, 8, 11, 12, 14, 15]n = len(arr1)m = len(arr2) symmDiff(arr1, arr2, n, m) # This code is contributed by Smitha Dinesh Semwal", "e": 4974, "s": 4063, "text": null }, { "code": "// C# program to find the symmetric// difference of two sorted array.using System; class GFG { static void symmDiff(int[] arr1, int[] arr2, int n, int m) { // Traverse both arrays simultaneously. int i = 0, j = 0; while (i < n && j < m) { // Print smaller element and move // ahead in array with smaller element if (arr1[i] < arr2[j]) { Console.Write(arr1[i] + \" \"); i++; } else if (arr2[j] < arr1[i]) { Console.Write(arr2[j] + \" \"); j++; } // If both elements same, move ahead // in both arrays. else { i++; j++; } } while (i < n) { Console.Write(arr1[i] + \" \"); i++; } while (j < m) { Console.Write(arr2[j] + \" \"); j++; } } // Driver code public static void Main() { int[] arr1 = { 2, 4, 5, 7, 8, 10, 12, 15 }; int[] arr2 = { 5, 8, 11, 12, 14, 15 }; int n = arr1.Length; int m = arr2.Length; symmDiff(arr1, arr2, n, m); }} /* This code is contributed by vt_m*/", "e": 6225, "s": 4974, "text": null }, { "code": "<?php// PHP program to find the// symmetric difference// of two sorted array.function symmDiff($arr1, $arr2, $n, $m){ // Traverse both arrays // simultaneously. $i = 0; $j = 0; while ($i < $n && $j < $m) { // Print smaller element // and move ahead in array // with smaller element if ($arr1[$i] < $arr2[$j]) { echo($arr1[$i] . \" \"); $i++; } else if ($arr2[$j] < $arr1[$i]) { echo($arr2[$j] . \" \"); $j++; } // If both elements same, // move ahead in both arrays else { $i++; $j++; } } while ($i < $n) { echo($arr1[$i] . \" \"); $i++; } while ($j < $m) { echo($arr2[$j] . \" \"); $j++; }} // Driver code$arr1 = array(2, 4, 5, 7, 8, 10, 12, 15);$arr2 = array(5, 8, 11, 12, 14, 15);$n = sizeof($arr1);$m = sizeof($arr2);symmDiff($arr1, $arr2, $n, $m); // This code is contributed by Ajit.?>", "e": 7272, "s": 6225, "text": null }, { "code": "<script> // Javascript program to find the symmetric // difference of two sorted array. function symmDiff(arr1, arr2, n, m) { // Traverse both arrays simultaneously. let i = 0, j = 0; while (i < n && j < m) { // Print smaller element and move // ahead in array with smaller element if (arr1[i] < arr2[j]) { document.write(arr1[i] + \" \"); i++; } else if (arr2[j] < arr1[i]) { document.write(arr2[j] + \" \"); j++; } // If both elements same, move ahead // in both arrays. else { i++; j++; } } while (i < n) { document.write(arr1[i] + \" \"); i++; } while (j < m) { document.write(arr2[j] + \" \"); j++; } } let arr1 = [ 2, 4, 5, 7, 8, 10, 12, 15 ]; let arr2 = [ 5, 8, 11, 12, 14, 15 ]; let n = arr1.length; let m = arr2.length; symmDiff(arr1, arr2, n, m); </script>", "e": 8387, "s": 7272, "text": null }, { "code": null, "e": 8396, "s": 8387, "text": "Output: " }, { "code": null, "e": 8411, "s": 8396, "text": "2 4 7 10 11 14" }, { "code": null, "e": 8860, "s": 8411, "text": "Time Complexity: O(m + n).This article is contributed by Dharmendra kumar. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above." }, { "code": null, "e": 8866, "s": 8860, "text": "jit_t" }, { "code": null, "e": 8883, "s": 8866, "text": "banerjeesouvik18" }, { "code": null, "e": 8894, "s": 8883, "text": "hungrywolf" }, { "code": null, "e": 8905, "s": 8894, "text": "decode2207" }, { "code": null, "e": 8912, "s": 8905, "text": "Arrays" }, { "code": null, "e": 8919, "s": 8912, "text": "Arrays" } ]
Sort all even numbers in ascending order and then sort all odd numbers in descending order
08 Jul, 2022 Given an array of integers (both odd and even), sort them in such a way that the first part of the array contains odd numbers sorted in descending order, rest portion contains even numbers sorted in ascending order.Examples: Input: arr[] = {1, 2, 3, 5, 4, 7, 10}Output: arr[] = {7, 5, 3, 1, 2, 4, 10} Input: arr[] = {0, 4, 5, 3, 7, 2, 1}Output: arr[] = {7, 5, 3, 1, 0, 2, 4} Method 1 (Using Partition) Partition the input array such that all odd elements are moved to the left and all even elements on right. This step takes O(n).Once the array is partitioned, sort left and right parts individually. This step takes O(n Log n). Partition the input array such that all odd elements are moved to the left and all even elements on right. This step takes O(n). Once the array is partitioned, sort left and right parts individually. This step takes O(n Log n). Below is the implementation of the above idea. C++ Java Python C# Javascript // C++ program sort array in even and odd manner.// The odd numbers are to be sorted in descending// order and the even numbers in ascending order#include <bits/stdc++.h>using namespace std; // To do two way sort. First sort even numbers in// ascending order, then odd numbers in descending// order.void twoWaySort(int arr[], int n){ // Current indexes from left and right int l = 0, r = n - 1; // Count of odd numbers int k = 0; while (l < r) { // Find first even number // from left side. while (arr[l] % 2 != 0) { l++; k++; } // Find first odd number // from right side. while (arr[r] % 2 == 0 && l < r) r--; // Swap even number present on left and odd // number right. if (l < r) swap(arr[l], arr[r]); } // Sort odd number in descending order sort(arr, arr + k, greater<int>()); // Sort even number in ascending order sort(arr + k, arr + n);} // Driver codeint main(){ int arr[] = { 1, 3, 2, 7, 5, 4 }; int n = sizeof(arr) / sizeof(int); twoWaySort(arr, n); for (int i = 0; i < n; i++) cout << arr[i] << " "; return 0;} // Java program sort array in even and odd manner.// The odd numbers are to be sorted in descending// order and the even numbers in ascending order import java.util.Arrays;import java.util.Collections; public class GFG { // To do two way sort. First sort even numbers in // ascending order, then odd numbers in descending // order. static void twoWaySort(Integer arr[], int n) { // Current indexes from left and right int l = 0, r = n - 1; // Count of odd numbers int k = 0; while (l < r) { // Find first even number from left side. while (arr[l] % 2 != 0) { l++; k++; } // Find first odd number from right side. while (arr[r] % 2 == 0 && l < r) r--; // Swap even number present on left and odd // number right. if (l < r) { // swap arr[l] arr[r] int temp = arr[l]; arr[l] = arr[r]; arr[r] = temp; } } // Sort odd number in descending order Arrays.sort(arr, 0, k, Collections. reverseOrder()); // Sort even number in ascending order Arrays.sort(arr, k, n); } // Driver Method public static void main(String[] args) { Integer arr[] = { 1, 3, 2, 7, 5, 4 }; twoWaySort(arr, arr.length); System.out.println(Arrays.toString(arr)); }} # Python program to sort array# in even and odd manner# The odd numbers are to be# sorted in descending order# and the even numbers in# ascending order # To do two way sort. First# sort even numbers in ascending# order, then odd numbers in# descending order.def two_way_sort(arr, arr_len): # Current indexes l->left # and r->right l, r = 0, arr_len - 1 # Count of number of # odd numbers, used in # slicing the array later. k = 0 # Run till left(l) < right(r) while(l < r): # While left(l) is odd, if yes # increment the left(l) plus # odd count(k) if not break the # while for even number found # here to be swapped while(arr[l] % 2 != 0): l += 1 k += 1 # While right(r) is even, # if yes decrement right(r) # if not break the while for # odd number found here to # be swapped while(arr[r] % 2 == 0 and l < r): r -= 1 # Swap the left(l) and right(r), # which is even and odd numbers # encountered in above loops if(l < r): arr[l], arr[r] = arr[r], arr[l] # Slice the number on the # basis of odd count(k) odd = arr[:k] even = arr[k:] # Sort the odd and # even array accordingly odd.sort(reverse = True) even.sort() # Extend the odd array with # even values and return it. odd.extend(even) return odd # Driver codearr_len = 6arr = [1, 3, 2, 7, 5, 4]result = two_way_sort(arr, arr_len)for i in result: print(str(i) + " "), # This code is contributed# by JaySiyaRam // C# program sort array in even and odd manner.// The odd numbers are to be sorted in descending// order and the even numbers in ascending orderusing System;using System.Linq; class GFG { // To do two way sort. First sort even numbers in // ascending order, then odd numbers in descending // order. static void twoWaySort(int[] arr, int n) { // Current indexes from left and right int l = 0, r = n - 1; // Count of odd numbers int k = 0; while (l < r) { // Find first even number // from left side. while (arr[l] % 2 != 0) { l++; k++; } // Find first odd number from right side. while (arr[r] % 2 == 0 && l < r) r--; // Swap even number present // on left and odd // number right. if (l < r) { // swap arr[l] arr[r] int temp = arr[l]; arr[l] = arr[r]; arr[r] = temp; } } // Sort odd number in descending order Array.Sort(arr, 0, k); Array.Reverse(arr, 0, k); // Sort even number in ascending order Array.Sort(arr, k, n - k); } // Driver Method public static void Main(String[] args) { int[] arr = { 1, 3, 2, 7, 5, 4 }; twoWaySort(arr, arr.Length); Console.WriteLine(String.Join(" ", arr)); }} // This code has been contributed by 29AjayKumar <script> // Javascript program sort array// in even and odd manner.// The odd numbers are to be// sorted in descending// order and the even numbers in// ascending order // To do two way sort. // First sort even numbers in // ascending order, then odd // numbers in descending // order. function twoWaySort(arr,n) { // Current indexes from // left and right let l = 0, r = n - 1; // Count of odd numbers let k = 0; while (l < r) { // Find first even number // from left side. while (arr[l] % 2 != 0) { l++; k++; } // Find first odd number // from right side. while (arr[r] % 2 == 0 && l < r) r--; // Swap even number present // on left and odd // number right. if (l < r) { // swap arr[l] arr[r] let temp = arr[l]; arr[l] = arr[r]; arr[r] = temp; } } let odd=new Array(k); for(let i=0;i<k;i++) { odd[i]=arr[i]; } let even=new Array(n-k); for(let i=0;i<n-k;i++) { even[i]=arr[k+i]; } // Sort odd number in descending order odd.sort(function(a,b){return b-a;}); // Sort even number in ascending order even.sort(function(a,b){return a-b;}); return odd.concat(even); } // Driver Method let arr=[1, 3, 2, 7, 5, 4 ]; let ans=twoWaySort(arr, arr.length); for(let i=0;i<ans.length;i++) { document.write(ans[i]+" "); } // This code is contributed by rag2127 </script> 7 5 3 1 2 4 Time complexity: O(n log n) Auxiliary Space: O(1) Method 2 (Using negative multiplication) : Make all odd numbers negative.Sort all numbers.Revert the changes made in step 1 to get original elements back. Make all odd numbers negative. Sort all numbers. Revert the changes made in step 1 to get original elements back. Implementation: C++ Java Python3 C# PHP Javascript // C++ program sort array in even and odd manner.// The odd numbers are to be sorted in descending// order and the even numbers in ascending order#include <bits/stdc++.h>using namespace std; // To do two way sort. First sort even numbers in// ascending order, then odd numbers in descending// order.void twoWaySort(int arr[], int n){ // Make all odd numbers negative for (int i = 0; i < n; i++) if (arr[i] & 1) // Check for odd arr[i] *= -1; // Sort all numbers sort(arr, arr + n); // Retaining original array for (int i = 0; i < n; i++) if (arr[i] & 1) arr[i] *= -1;} // Driver codeint main(){ int arr[] = { 1, 3, 2, 7, 5, 4 }; int n = sizeof(arr) / sizeof(int); twoWaySort(arr, n); for (int i = 0; i < n; i++) cout << arr[i] << " "; return 0;} // Java program sort array in even and odd manner.// The odd numbers are to be sorted in descending// order and the even numbers in ascending order import java.util.Arrays; public class GFG{ // To do two way sort. First sort even numbers in // ascending order, then odd numbers in descending // order. static void twoWaySort(int arr[], int n) { // Make all odd numbers negative for (int i = 0; i < n; i++) if ((arr[i] & 1) != 0) // Check for odd arr[i] *= -1; // Sort all numbers Arrays.sort(arr); // Retaining original array for (int i = 0; i < n; i++) if ((arr[i] & 1) != 0) arr[i] *= -1; } // Driver Method public static void main(String[] args) { int arr[] = { 1, 3, 2, 7, 5, 4 }; twoWaySort(arr, arr.length); System.out.println(Arrays.toString(arr)); }} # Python 3 program to sort array in# even and odd manner. The odd# numkbers are to be sorted in# descending order and the even# numbers in ascending order # To do two way sort. First sort# even numbers in ascending order,# then odd numbers in descending order.def twoWaySort(arr, n): # Make all odd numbers negative for i in range(0, n): # Check for odd if (arr[i] & 1): arr[i] *= -1 # Sort all numbers arr.sort() # Retaining original array for i in range(0, n): if (arr[i] & 1): arr[i] *= -1 # Driver codearr = [1, 3, 2, 7, 5, 4]n = len(arr)twoWaySort(arr, n);for i in range(0, n): print(arr[i], end = " ") # This code is contributed by Smitha Dinesh Semwal // Java program sort array in even and// odd manner. The odd numbers are to// be sorted in descending order and// the even numbers in ascending orderusing System; public class GFG{ // To do two way sort. First sort // even numbers in ascending order, // then odd numbers in descending // order. static void twoWaySort(int[] arr, int n) { // Make all odd numbers negative for (int i = 0; i < n; i++) // Check for odd if ((arr[i] & 1) != 0) arr[i] *= -1; // Sort all numbers Array.Sort(arr); // Retaining original array for (int i = 0; i < n; i++) if ((arr[i] & 1) != 0) arr[i] *= -1; } // Driver Method public static void Main() { int[] arr = { 1, 3, 2, 7, 5, 4 }; twoWaySort(arr, arr.Length); for (int i = 0; i < arr.Length; i++) Console.Write(arr[i] + " "); }} // This code is contributed by Smitha <?php// PHP program sort array in even and odd manner.// The odd numbers are to be sorted in descending// order and the even numbers in ascending order // To do two way sort. First sort even numbers in// ascending order, then odd numbers in descending// order.function twoWaySort(&$arr, $n){ // Make all odd numbers negative for ($i = 0 ; $i < $n; $i++) if ($arr[$i] & 1) // Check for odd $arr[$i] *= -1; // Sort all numbers sort($arr); // Retaining original array for ($i = 0 ; $i < $n; $i++) if ($arr[$i] & 1) $arr[$i] *= -1;} // Driver code$arr = array(1, 3, 2, 7, 5, 4);$n = sizeof($arr);twoWaySort($arr, $n);for ($i = 0; $i < $n; $i++) echo $arr[$i] . " "; // This code is contributed by ita_c?> <script> // Javascript program sort array in even and odd manner.// The odd numbers are to be sorted in descending// order and the even numbers in ascending order // To do two way sort. First sort even numbers in// ascending order, then odd numbers in descending// order.function twoWaySort(arr, n){ // Make all odd numbers negative for (let i = 0; i < n; i++) if (arr[i] & 1) // Check for odd arr[i] *= -1; // Sort all numbers arr.sort((a,b) => a-b); // Retaining original array for (let i = 0; i < n; i++) if (arr[i] & 1) arr[i] *= -1;} // Driver code let arr = [ 1, 3, 2, 7, 5, 4 ]; let n = arr.length; twoWaySort(arr, n); for (let i = 0; i < n; i++) document.write(arr[i] + " "); //This code is contributed by Mayank Tyagi</script> 7 5 3 1 2 4 Time complexity: O(n log n) Auxiliary Space: O(1) This method may not work when input array contains negative numbers. However, there is a way to handle this. We count the positive odd integers in the input array then sort again. Readers may refer this for implementation. Method 3 (Using comparator): This problem can be easily solved by using the inbuilt sort function with a custom compare method. On comparing any two elements there will be three cases: When both the elements are even: In this case, the smaller element must appear in the left of the larger element in the sorted array.When both the elements are odd: The larger element must appear on left of the smaller element.One is odd and the other is even: The element which is odd must appear on the left of the even element. When both the elements are even: In this case, the smaller element must appear in the left of the larger element in the sorted array. When both the elements are odd: The larger element must appear on left of the smaller element. One is odd and the other is even: The element which is odd must appear on the left of the even element. Below is the implementation of the above approach: CPP Java Python3 C# Javascript // C++ implementation of the approach#include <bits/stdc++.h>using namespace std; // Utility function to print// the contents of the arrayvoid printArr(int arr[], int n){ for (int i = 0; i < n; i++) cout << arr[i] << " ";} // To do two way sort. Make comparator function// for the inbuilt sort function of c++ such that// odd numbers are placed before even in descending// and ascending order respectivelybool compare(int a, int b){ // If both numbers are even, // smaller number should // be placed at lower index if (a % 2 == 0 && b % 2 == 0) return a < b; // If both numbers are odd larger number // should be placed at lower index if (a % 2 != 0 && b % 2 != 0) return b < a; // If a is odd and b is even, // a should be placed before b if (a % 2 != 0) return true; // If b is odd and a is even, // b should be placed before a return false;} // Driver codeint main(){ int arr[] = { 1, 3, 2, 7, 5, 4 }; int n = sizeof(arr) / sizeof(int); // Sort the array sort(arr, arr + n, compare); // Print the sorted array printArr(arr, n); return 0;} // This code is contributed by Nikhil Yadav // Java implementation of the approachimport java.util.ArrayList;import java.util.Collections;import java.util.Comparator; class GFG{ // Utility function to print // the contents of the array static void printArr(ArrayList<Integer> arr, int n) { for (int i = 0; i < n; i++) System.out.print(arr.get(i) + " "); } // Driver code public static void main(String args[]) { ArrayList<Integer> arr = new ArrayList<Integer>(); arr.add(1); arr.add(3); arr.add(2); arr.add(7); arr.add(5); arr.add(4); int n = arr.size(); // Sort the array Collections.sort(arr, new Comparator<Integer>() { @Override public int compare(Integer a, Integer b) { // If both numbers are even, // smaller number should // be placed at lower index if (a % 2 == 0 && b % 2 == 0) return (a - b); // If both numbers are odd larger number // should be placed at lower index if (a % 2 != 0 && b % 2 != 0) return (b - a); // If a is odd and b is even, // a should be placed before b if (a % 2 != 0) return -1; // If b is odd and a is even, // b should be placed before a return 0; } }); // Print the sorted array printArr(arr, n); }} // This code is contributed by Saurabh Jaiswal # Python3 implementation of the approach # Utility function to print# the contents of the arrayfrom functools import cmp_to_key def printArr(arr, n): for i in range(n): print(arr[i], end = " ") # To do two way sort. Make comparator function # for the inbuilt sort function of c++ such that # odd numbers are placed before even in descending # and ascending order respectivelydef compare(a, b): # If both numbers are even, # smaller number should # be placed at lower index if (a % 2 == 0 and b % 2 == 0 and a < b): return -1 # If both numbers are odd larger number # should be placed at lower index if (a % 2 != 0 and b % 2 != 0 and b > a): return 1 # If a is odd and b is even, # a should be placed before b if (a % 2 != 0): return -1 # If b is odd and a is even, # b should be placed before a return 1 # Driver codearr = [1, 3, 2, 7, 5, 4]n = len(arr) # Sort the arrayarr.sort(key = cmp_to_key(compare)) # Print the sorted arrayprintArr(arr, n) # This code is contributed by shinjanpatra // C# implementation of the approachusing System;using System.Collections.Generic; public class GFG{ // Utility function to print // the contents of the array static void printArr(List<int> arr, int n) { for (int i = 0; i < n; i++) Console.Write(arr[i] + " "); } private static int Compare(int a, int b) { // If both numbers are even, // smaller number should // be placed at lower index if (a % 2 == 0 && b % 2 == 0 && a<b) return -1; // If both numbers are odd larger number // should be placed at lower index if (a % 2 != 0 && b % 2 != 0 && b>a) return 1; // If a is odd and b is even, // a should be placed before b if (a % 2 != 0) return -1; // If b is odd and a is even, // b should be placed before a return 1; } // Driver code public static void Main(String []args) { List<int> arr = new List<int>(); arr.Add(1); arr.Add(3); arr.Add(2); arr.Add(7); arr.Add(5); arr.Add(4); int n = arr.Count; // Sort the array arr.Sort(Compare); // Print the sorted array printArr(arr, n); }} // This code is contributed by 29AjayKumar <script> // JavaScript implementation of the approach // Utility function to print // the contents of the array function printArr(arr, n) { for (let i = 0; i < n; i++) document.write(arr[i] + " "); } // To do two way sort. Make comparator function // for the inbuilt sort function of c++ such that // odd numbers are placed before even in descending // and ascending order respectively function compare(a, b) { // If both numbers are even, // smaller number should // be placed at lower index if (a % 2 == 0 && b % 2 == 0 && a < b) return -1; // If both numbers are odd larger number // should be placed at lower index if (a % 2 != 0 && b % 2 != 0 && b > a) return 1; // If a is odd and b is even, // a should be placed before b if (a % 2 != 0) return -1; // If b is odd and a is even, // b should be placed before a return 1; } // Driver code var arr = [1, 3, 2, 7, 5, 4]; var n = arr.length; // Sort the array arr.sort(compare); // Print the sorted array printArr(arr, n); // This code is contributed by Potta Lokesh </script> 7 5 3 1 2 4 Time complexity : O(n*logn) [sort function has average time complexity n*logn]Auxiliary Space : O(1) Sort all even numbers in ascending order and odd numbers in descending order | GeeksforGeeks - YouTubeGeeksforGeeks529K subscribersSort all even numbers in ascending order and odd numbers in descending order | GeeksforGeeksWatch laterShareCopy linkInfoShoppingTap to unmuteIf playback doesn't begin shortly, try restarting your device.You're signed outVideos you watch may be added to the TV's watch history and influence TV recommendations. To avoid this, cancel and sign in to YouTube on your computer.CancelConfirmMore videosMore videosSwitch cameraShareInclude playlistAn error occurred while retrieving sharing information. Please try again later.Watch on0:000:000:00 / 2:16•Live•<div class="player-unavailable"><h1 class="message">An error occurred.</h1><div class="submessage"><a href="https://www.youtube.com/watch?v=ep8yXQ7xVcE" target="_blank">Try watching this video on www.youtube.com</a>, or enable JavaScript if it is disabled in your browser.</div></div> Thanks to Amandeep Singh for suggesting this solution. This article is contributed by DANISH_RAZA. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to review-team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks. Smitha Dinesh Semwal jaysiyaram ukasp 29AjayKumar nikhil3000 SujithSai ankitasharma5911 rag2127 mayanktyagi1709 lokeshpotta20 gfgking prasanna1995 surinderdawra388 shinjanpatra harendrakumar123 aditya942003patil hardikkoriintern Microsoft Zoho Arrays Sorting Zoho Microsoft Arrays Sorting Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Multidimensional Arrays in Java Introduction to Arrays K'th Smallest/Largest Element in Unsorted Array | Set 1 Subset Sum Problem | DP-25 Python | Using 2D arrays/lists the right way Merge Sort Bubble Sort Algorithm QuickSort Insertion Sort Selection Sort Algorithm
[ { "code": null, "e": 52, "s": 24, "text": "\n08 Jul, 2022" }, { "code": null, "e": 278, "s": 52, "text": "Given an array of integers (both odd and even), sort them in such a way that the first part of the array contains odd numbers sorted in descending order, rest portion contains even numbers sorted in ascending order.Examples: " }, { "code": null, "e": 354, "s": 278, "text": "Input: arr[] = {1, 2, 3, 5, 4, 7, 10}Output: arr[] = {7, 5, 3, 1, 2, 4, 10}" }, { "code": null, "e": 429, "s": 354, "text": "Input: arr[] = {0, 4, 5, 3, 7, 2, 1}Output: arr[] = {7, 5, 3, 1, 0, 2, 4} " }, { "code": null, "e": 458, "s": 429, "text": "Method 1 (Using Partition) " }, { "code": null, "e": 685, "s": 458, "text": "Partition the input array such that all odd elements are moved to the left and all even elements on right. This step takes O(n).Once the array is partitioned, sort left and right parts individually. This step takes O(n Log n)." }, { "code": null, "e": 814, "s": 685, "text": "Partition the input array such that all odd elements are moved to the left and all even elements on right. This step takes O(n)." }, { "code": null, "e": 913, "s": 814, "text": "Once the array is partitioned, sort left and right parts individually. This step takes O(n Log n)." }, { "code": null, "e": 962, "s": 913, "text": "Below is the implementation of the above idea. " }, { "code": null, "e": 966, "s": 962, "text": "C++" }, { "code": null, "e": 971, "s": 966, "text": "Java" }, { "code": null, "e": 978, "s": 971, "text": "Python" }, { "code": null, "e": 981, "s": 978, "text": "C#" }, { "code": null, "e": 992, "s": 981, "text": "Javascript" }, { "code": "// C++ program sort array in even and odd manner.// The odd numbers are to be sorted in descending// order and the even numbers in ascending order#include <bits/stdc++.h>using namespace std; // To do two way sort. First sort even numbers in// ascending order, then odd numbers in descending// order.void twoWaySort(int arr[], int n){ // Current indexes from left and right int l = 0, r = n - 1; // Count of odd numbers int k = 0; while (l < r) { // Find first even number // from left side. while (arr[l] % 2 != 0) { l++; k++; } // Find first odd number // from right side. while (arr[r] % 2 == 0 && l < r) r--; // Swap even number present on left and odd // number right. if (l < r) swap(arr[l], arr[r]); } // Sort odd number in descending order sort(arr, arr + k, greater<int>()); // Sort even number in ascending order sort(arr + k, arr + n);} // Driver codeint main(){ int arr[] = { 1, 3, 2, 7, 5, 4 }; int n = sizeof(arr) / sizeof(int); twoWaySort(arr, n); for (int i = 0; i < n; i++) cout << arr[i] << \" \"; return 0;}", "e": 2208, "s": 992, "text": null }, { "code": "// Java program sort array in even and odd manner.// The odd numbers are to be sorted in descending// order and the even numbers in ascending order import java.util.Arrays;import java.util.Collections; public class GFG { // To do two way sort. First sort even numbers in // ascending order, then odd numbers in descending // order. static void twoWaySort(Integer arr[], int n) { // Current indexes from left and right int l = 0, r = n - 1; // Count of odd numbers int k = 0; while (l < r) { // Find first even number from left side. while (arr[l] % 2 != 0) { l++; k++; } // Find first odd number from right side. while (arr[r] % 2 == 0 && l < r) r--; // Swap even number present on left and odd // number right. if (l < r) { // swap arr[l] arr[r] int temp = arr[l]; arr[l] = arr[r]; arr[r] = temp; } } // Sort odd number in descending order Arrays.sort(arr, 0, k, Collections. reverseOrder()); // Sort even number in ascending order Arrays.sort(arr, k, n); } // Driver Method public static void main(String[] args) { Integer arr[] = { 1, 3, 2, 7, 5, 4 }; twoWaySort(arr, arr.length); System.out.println(Arrays.toString(arr)); }}", "e": 3755, "s": 2208, "text": null }, { "code": "# Python program to sort array# in even and odd manner# The odd numbers are to be# sorted in descending order# and the even numbers in# ascending order # To do two way sort. First# sort even numbers in ascending# order, then odd numbers in# descending order.def two_way_sort(arr, arr_len): # Current indexes l->left # and r->right l, r = 0, arr_len - 1 # Count of number of # odd numbers, used in # slicing the array later. k = 0 # Run till left(l) < right(r) while(l < r): # While left(l) is odd, if yes # increment the left(l) plus # odd count(k) if not break the # while for even number found # here to be swapped while(arr[l] % 2 != 0): l += 1 k += 1 # While right(r) is even, # if yes decrement right(r) # if not break the while for # odd number found here to # be swapped while(arr[r] % 2 == 0 and l < r): r -= 1 # Swap the left(l) and right(r), # which is even and odd numbers # encountered in above loops if(l < r): arr[l], arr[r] = arr[r], arr[l] # Slice the number on the # basis of odd count(k) odd = arr[:k] even = arr[k:] # Sort the odd and # even array accordingly odd.sort(reverse = True) even.sort() # Extend the odd array with # even values and return it. odd.extend(even) return odd # Driver codearr_len = 6arr = [1, 3, 2, 7, 5, 4]result = two_way_sort(arr, arr_len)for i in result: print(str(i) + \" \"), # This code is contributed# by JaySiyaRam", "e": 5427, "s": 3755, "text": null }, { "code": "// C# program sort array in even and odd manner.// The odd numbers are to be sorted in descending// order and the even numbers in ascending orderusing System;using System.Linq; class GFG { // To do two way sort. First sort even numbers in // ascending order, then odd numbers in descending // order. static void twoWaySort(int[] arr, int n) { // Current indexes from left and right int l = 0, r = n - 1; // Count of odd numbers int k = 0; while (l < r) { // Find first even number // from left side. while (arr[l] % 2 != 0) { l++; k++; } // Find first odd number from right side. while (arr[r] % 2 == 0 && l < r) r--; // Swap even number present // on left and odd // number right. if (l < r) { // swap arr[l] arr[r] int temp = arr[l]; arr[l] = arr[r]; arr[r] = temp; } } // Sort odd number in descending order Array.Sort(arr, 0, k); Array.Reverse(arr, 0, k); // Sort even number in ascending order Array.Sort(arr, k, n - k); } // Driver Method public static void Main(String[] args) { int[] arr = { 1, 3, 2, 7, 5, 4 }; twoWaySort(arr, arr.Length); Console.WriteLine(String.Join(\" \", arr)); }} // This code has been contributed by 29AjayKumar", "e": 6960, "s": 5427, "text": null }, { "code": "<script> // Javascript program sort array// in even and odd manner.// The odd numbers are to be// sorted in descending// order and the even numbers in// ascending order // To do two way sort. // First sort even numbers in // ascending order, then odd // numbers in descending // order. function twoWaySort(arr,n) { // Current indexes from // left and right let l = 0, r = n - 1; // Count of odd numbers let k = 0; while (l < r) { // Find first even number // from left side. while (arr[l] % 2 != 0) { l++; k++; } // Find first odd number // from right side. while (arr[r] % 2 == 0 && l < r) r--; // Swap even number present // on left and odd // number right. if (l < r) { // swap arr[l] arr[r] let temp = arr[l]; arr[l] = arr[r]; arr[r] = temp; } } let odd=new Array(k); for(let i=0;i<k;i++) { odd[i]=arr[i]; } let even=new Array(n-k); for(let i=0;i<n-k;i++) { even[i]=arr[k+i]; } // Sort odd number in descending order odd.sort(function(a,b){return b-a;}); // Sort even number in ascending order even.sort(function(a,b){return a-b;}); return odd.concat(even); } // Driver Method let arr=[1, 3, 2, 7, 5, 4 ]; let ans=twoWaySort(arr, arr.length); for(let i=0;i<ans.length;i++) { document.write(ans[i]+\" \"); } // This code is contributed by rag2127 </script>", "e": 8779, "s": 6960, "text": null }, { "code": null, "e": 8792, "s": 8779, "text": "7 5 3 1 2 4 " }, { "code": null, "e": 8842, "s": 8792, "text": "Time complexity: O(n log n) Auxiliary Space: O(1)" }, { "code": null, "e": 8887, "s": 8842, "text": "Method 2 (Using negative multiplication) : " }, { "code": null, "e": 8999, "s": 8887, "text": "Make all odd numbers negative.Sort all numbers.Revert the changes made in step 1 to get original elements back." }, { "code": null, "e": 9030, "s": 8999, "text": "Make all odd numbers negative." }, { "code": null, "e": 9048, "s": 9030, "text": "Sort all numbers." }, { "code": null, "e": 9113, "s": 9048, "text": "Revert the changes made in step 1 to get original elements back." }, { "code": null, "e": 9129, "s": 9113, "text": "Implementation:" }, { "code": null, "e": 9133, "s": 9129, "text": "C++" }, { "code": null, "e": 9138, "s": 9133, "text": "Java" }, { "code": null, "e": 9146, "s": 9138, "text": "Python3" }, { "code": null, "e": 9149, "s": 9146, "text": "C#" }, { "code": null, "e": 9153, "s": 9149, "text": "PHP" }, { "code": null, "e": 9164, "s": 9153, "text": "Javascript" }, { "code": "// C++ program sort array in even and odd manner.// The odd numbers are to be sorted in descending// order and the even numbers in ascending order#include <bits/stdc++.h>using namespace std; // To do two way sort. First sort even numbers in// ascending order, then odd numbers in descending// order.void twoWaySort(int arr[], int n){ // Make all odd numbers negative for (int i = 0; i < n; i++) if (arr[i] & 1) // Check for odd arr[i] *= -1; // Sort all numbers sort(arr, arr + n); // Retaining original array for (int i = 0; i < n; i++) if (arr[i] & 1) arr[i] *= -1;} // Driver codeint main(){ int arr[] = { 1, 3, 2, 7, 5, 4 }; int n = sizeof(arr) / sizeof(int); twoWaySort(arr, n); for (int i = 0; i < n; i++) cout << arr[i] << \" \"; return 0;}", "e": 9988, "s": 9164, "text": null }, { "code": "// Java program sort array in even and odd manner.// The odd numbers are to be sorted in descending// order and the even numbers in ascending order import java.util.Arrays; public class GFG{ // To do two way sort. First sort even numbers in // ascending order, then odd numbers in descending // order. static void twoWaySort(int arr[], int n) { // Make all odd numbers negative for (int i = 0; i < n; i++) if ((arr[i] & 1) != 0) // Check for odd arr[i] *= -1; // Sort all numbers Arrays.sort(arr); // Retaining original array for (int i = 0; i < n; i++) if ((arr[i] & 1) != 0) arr[i] *= -1; } // Driver Method public static void main(String[] args) { int arr[] = { 1, 3, 2, 7, 5, 4 }; twoWaySort(arr, arr.length); System.out.println(Arrays.toString(arr)); }}", "e": 10897, "s": 9988, "text": null }, { "code": "# Python 3 program to sort array in# even and odd manner. The odd# numkbers are to be sorted in# descending order and the even# numbers in ascending order # To do two way sort. First sort# even numbers in ascending order,# then odd numbers in descending order.def twoWaySort(arr, n): # Make all odd numbers negative for i in range(0, n): # Check for odd if (arr[i] & 1): arr[i] *= -1 # Sort all numbers arr.sort() # Retaining original array for i in range(0, n): if (arr[i] & 1): arr[i] *= -1 # Driver codearr = [1, 3, 2, 7, 5, 4]n = len(arr)twoWaySort(arr, n);for i in range(0, n): print(arr[i], end = \" \") # This code is contributed by Smitha Dinesh Semwal", "e": 11636, "s": 10897, "text": null }, { "code": "// Java program sort array in even and// odd manner. The odd numbers are to// be sorted in descending order and// the even numbers in ascending orderusing System; public class GFG{ // To do two way sort. First sort // even numbers in ascending order, // then odd numbers in descending // order. static void twoWaySort(int[] arr, int n) { // Make all odd numbers negative for (int i = 0; i < n; i++) // Check for odd if ((arr[i] & 1) != 0) arr[i] *= -1; // Sort all numbers Array.Sort(arr); // Retaining original array for (int i = 0; i < n; i++) if ((arr[i] & 1) != 0) arr[i] *= -1; } // Driver Method public static void Main() { int[] arr = { 1, 3, 2, 7, 5, 4 }; twoWaySort(arr, arr.Length); for (int i = 0; i < arr.Length; i++) Console.Write(arr[i] + \" \"); }} // This code is contributed by Smitha", "e": 12614, "s": 11636, "text": null }, { "code": "<?php// PHP program sort array in even and odd manner.// The odd numbers are to be sorted in descending// order and the even numbers in ascending order // To do two way sort. First sort even numbers in// ascending order, then odd numbers in descending// order.function twoWaySort(&$arr, $n){ // Make all odd numbers negative for ($i = 0 ; $i < $n; $i++) if ($arr[$i] & 1) // Check for odd $arr[$i] *= -1; // Sort all numbers sort($arr); // Retaining original array for ($i = 0 ; $i < $n; $i++) if ($arr[$i] & 1) $arr[$i] *= -1;} // Driver code$arr = array(1, 3, 2, 7, 5, 4);$n = sizeof($arr);twoWaySort($arr, $n);for ($i = 0; $i < $n; $i++) echo $arr[$i] . \" \"; // This code is contributed by ita_c?>", "e": 13374, "s": 12614, "text": null }, { "code": "<script> // Javascript program sort array in even and odd manner.// The odd numbers are to be sorted in descending// order and the even numbers in ascending order // To do two way sort. First sort even numbers in// ascending order, then odd numbers in descending// order.function twoWaySort(arr, n){ // Make all odd numbers negative for (let i = 0; i < n; i++) if (arr[i] & 1) // Check for odd arr[i] *= -1; // Sort all numbers arr.sort((a,b) => a-b); // Retaining original array for (let i = 0; i < n; i++) if (arr[i] & 1) arr[i] *= -1;} // Driver code let arr = [ 1, 3, 2, 7, 5, 4 ]; let n = arr.length; twoWaySort(arr, n); for (let i = 0; i < n; i++) document.write(arr[i] + \" \"); //This code is contributed by Mayank Tyagi</script>", "e": 14190, "s": 13374, "text": null }, { "code": null, "e": 14203, "s": 14190, "text": "7 5 3 1 2 4 " }, { "code": null, "e": 14253, "s": 14203, "text": "Time complexity: O(n log n) Auxiliary Space: O(1)" }, { "code": null, "e": 14476, "s": 14253, "text": "This method may not work when input array contains negative numbers. However, there is a way to handle this. We count the positive odd integers in the input array then sort again. Readers may refer this for implementation." }, { "code": null, "e": 14662, "s": 14476, "text": "Method 3 (Using comparator): This problem can be easily solved by using the inbuilt sort function with a custom compare method. On comparing any two elements there will be three cases: " }, { "code": null, "e": 14993, "s": 14662, "text": "When both the elements are even: In this case, the smaller element must appear in the left of the larger element in the sorted array.When both the elements are odd: The larger element must appear on left of the smaller element.One is odd and the other is even: The element which is odd must appear on the left of the even element." }, { "code": null, "e": 15127, "s": 14993, "text": "When both the elements are even: In this case, the smaller element must appear in the left of the larger element in the sorted array." }, { "code": null, "e": 15222, "s": 15127, "text": "When both the elements are odd: The larger element must appear on left of the smaller element." }, { "code": null, "e": 15326, "s": 15222, "text": "One is odd and the other is even: The element which is odd must appear on the left of the even element." }, { "code": null, "e": 15378, "s": 15326, "text": "Below is the implementation of the above approach: " }, { "code": null, "e": 15382, "s": 15378, "text": "CPP" }, { "code": null, "e": 15387, "s": 15382, "text": "Java" }, { "code": null, "e": 15395, "s": 15387, "text": "Python3" }, { "code": null, "e": 15398, "s": 15395, "text": "C#" }, { "code": null, "e": 15409, "s": 15398, "text": "Javascript" }, { "code": "// C++ implementation of the approach#include <bits/stdc++.h>using namespace std; // Utility function to print// the contents of the arrayvoid printArr(int arr[], int n){ for (int i = 0; i < n; i++) cout << arr[i] << \" \";} // To do two way sort. Make comparator function// for the inbuilt sort function of c++ such that// odd numbers are placed before even in descending// and ascending order respectivelybool compare(int a, int b){ // If both numbers are even, // smaller number should // be placed at lower index if (a % 2 == 0 && b % 2 == 0) return a < b; // If both numbers are odd larger number // should be placed at lower index if (a % 2 != 0 && b % 2 != 0) return b < a; // If a is odd and b is even, // a should be placed before b if (a % 2 != 0) return true; // If b is odd and a is even, // b should be placed before a return false;} // Driver codeint main(){ int arr[] = { 1, 3, 2, 7, 5, 4 }; int n = sizeof(arr) / sizeof(int); // Sort the array sort(arr, arr + n, compare); // Print the sorted array printArr(arr, n); return 0;} // This code is contributed by Nikhil Yadav", "e": 16597, "s": 15409, "text": null }, { "code": "// Java implementation of the approachimport java.util.ArrayList;import java.util.Collections;import java.util.Comparator; class GFG{ // Utility function to print // the contents of the array static void printArr(ArrayList<Integer> arr, int n) { for (int i = 0; i < n; i++) System.out.print(arr.get(i) + \" \"); } // Driver code public static void main(String args[]) { ArrayList<Integer> arr = new ArrayList<Integer>(); arr.add(1); arr.add(3); arr.add(2); arr.add(7); arr.add(5); arr.add(4); int n = arr.size(); // Sort the array Collections.sort(arr, new Comparator<Integer>() { @Override public int compare(Integer a, Integer b) { // If both numbers are even, // smaller number should // be placed at lower index if (a % 2 == 0 && b % 2 == 0) return (a - b); // If both numbers are odd larger number // should be placed at lower index if (a % 2 != 0 && b % 2 != 0) return (b - a); // If a is odd and b is even, // a should be placed before b if (a % 2 != 0) return -1; // If b is odd and a is even, // b should be placed before a return 0; } }); // Print the sorted array printArr(arr, n); }} // This code is contributed by Saurabh Jaiswal", "e": 18170, "s": 16597, "text": null }, { "code": "# Python3 implementation of the approach # Utility function to print# the contents of the arrayfrom functools import cmp_to_key def printArr(arr, n): for i in range(n): print(arr[i], end = \" \") # To do two way sort. Make comparator function # for the inbuilt sort function of c++ such that # odd numbers are placed before even in descending # and ascending order respectivelydef compare(a, b): # If both numbers are even, # smaller number should # be placed at lower index if (a % 2 == 0 and b % 2 == 0 and a < b): return -1 # If both numbers are odd larger number # should be placed at lower index if (a % 2 != 0 and b % 2 != 0 and b > a): return 1 # If a is odd and b is even, # a should be placed before b if (a % 2 != 0): return -1 # If b is odd and a is even, # b should be placed before a return 1 # Driver codearr = [1, 3, 2, 7, 5, 4]n = len(arr) # Sort the arrayarr.sort(key = cmp_to_key(compare)) # Print the sorted arrayprintArr(arr, n) # This code is contributed by shinjanpatra", "e": 19284, "s": 18170, "text": null }, { "code": "// C# implementation of the approachusing System;using System.Collections.Generic; public class GFG{ // Utility function to print // the contents of the array static void printArr(List<int> arr, int n) { for (int i = 0; i < n; i++) Console.Write(arr[i] + \" \"); } private static int Compare(int a, int b) { // If both numbers are even, // smaller number should // be placed at lower index if (a % 2 == 0 && b % 2 == 0 && a<b) return -1; // If both numbers are odd larger number // should be placed at lower index if (a % 2 != 0 && b % 2 != 0 && b>a) return 1; // If a is odd and b is even, // a should be placed before b if (a % 2 != 0) return -1; // If b is odd and a is even, // b should be placed before a return 1; } // Driver code public static void Main(String []args) { List<int> arr = new List<int>(); arr.Add(1); arr.Add(3); arr.Add(2); arr.Add(7); arr.Add(5); arr.Add(4); int n = arr.Count; // Sort the array arr.Sort(Compare); // Print the sorted array printArr(arr, n); }} // This code is contributed by 29AjayKumar", "e": 20428, "s": 19284, "text": null }, { "code": "<script> // JavaScript implementation of the approach // Utility function to print // the contents of the array function printArr(arr, n) { for (let i = 0; i < n; i++) document.write(arr[i] + \" \"); } // To do two way sort. Make comparator function // for the inbuilt sort function of c++ such that // odd numbers are placed before even in descending // and ascending order respectively function compare(a, b) { // If both numbers are even, // smaller number should // be placed at lower index if (a % 2 == 0 && b % 2 == 0 && a < b) return -1; // If both numbers are odd larger number // should be placed at lower index if (a % 2 != 0 && b % 2 != 0 && b > a) return 1; // If a is odd and b is even, // a should be placed before b if (a % 2 != 0) return -1; // If b is odd and a is even, // b should be placed before a return 1; } // Driver code var arr = [1, 3, 2, 7, 5, 4]; var n = arr.length; // Sort the array arr.sort(compare); // Print the sorted array printArr(arr, n); // This code is contributed by Potta Lokesh </script>", "e": 21824, "s": 20428, "text": null }, { "code": null, "e": 21837, "s": 21824, "text": "7 5 3 1 2 4 " }, { "code": null, "e": 21938, "s": 21837, "text": "Time complexity : O(n*logn) [sort function has average time complexity n*logn]Auxiliary Space : O(1)" }, { "code": null, "e": 22908, "s": 21938, "text": "Sort all even numbers in ascending order and odd numbers in descending order | GeeksforGeeks - YouTubeGeeksforGeeks529K subscribersSort all even numbers in ascending order and odd numbers in descending order | GeeksforGeeksWatch laterShareCopy linkInfoShoppingTap to unmuteIf playback doesn't begin shortly, try restarting your device.You're signed outVideos you watch may be added to the TV's watch history and influence TV recommendations. To avoid this, cancel and sign in to YouTube on your computer.CancelConfirmMore videosMore videosSwitch cameraShareInclude playlistAn error occurred while retrieving sharing information. Please try again later.Watch on0:000:000:00 / 2:16•Live•<div class=\"player-unavailable\"><h1 class=\"message\">An error occurred.</h1><div class=\"submessage\"><a href=\"https://www.youtube.com/watch?v=ep8yXQ7xVcE\" 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": 22963, "s": 22908, "text": "Thanks to Amandeep Singh for suggesting this solution." }, { "code": null, "e": 23259, "s": 22963, "text": "This article is contributed by DANISH_RAZA. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to review-team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks. " }, { "code": null, "e": 23280, "s": 23259, "text": "Smitha Dinesh Semwal" }, { "code": null, "e": 23291, "s": 23280, "text": "jaysiyaram" }, { "code": null, "e": 23297, "s": 23291, "text": "ukasp" }, { "code": null, "e": 23309, "s": 23297, "text": "29AjayKumar" }, { "code": null, "e": 23320, "s": 23309, "text": "nikhil3000" }, { "code": null, "e": 23330, "s": 23320, "text": "SujithSai" }, { "code": null, "e": 23347, "s": 23330, "text": "ankitasharma5911" }, { "code": null, "e": 23355, "s": 23347, "text": "rag2127" }, { "code": null, "e": 23371, "s": 23355, "text": "mayanktyagi1709" }, { "code": null, "e": 23385, "s": 23371, "text": "lokeshpotta20" }, { "code": null, "e": 23393, "s": 23385, "text": "gfgking" }, { "code": null, "e": 23406, "s": 23393, "text": "prasanna1995" }, { "code": null, "e": 23423, "s": 23406, "text": "surinderdawra388" }, { "code": null, "e": 23436, "s": 23423, "text": "shinjanpatra" }, { "code": null, "e": 23453, "s": 23436, "text": "harendrakumar123" }, { "code": null, "e": 23471, "s": 23453, "text": "aditya942003patil" }, { "code": null, "e": 23488, "s": 23471, "text": "hardikkoriintern" }, { "code": null, "e": 23498, "s": 23488, "text": "Microsoft" }, { "code": null, "e": 23503, "s": 23498, "text": "Zoho" }, { "code": null, "e": 23510, "s": 23503, "text": "Arrays" }, { "code": null, "e": 23518, "s": 23510, "text": "Sorting" }, { "code": null, "e": 23523, "s": 23518, "text": "Zoho" }, { "code": null, "e": 23533, "s": 23523, "text": "Microsoft" }, { "code": null, "e": 23540, "s": 23533, "text": "Arrays" }, { "code": null, "e": 23548, "s": 23540, "text": "Sorting" }, { "code": null, "e": 23646, "s": 23548, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 23678, "s": 23646, "text": "Multidimensional Arrays in Java" }, { "code": null, "e": 23701, "s": 23678, "text": "Introduction to Arrays" }, { "code": null, "e": 23757, "s": 23701, "text": "K'th Smallest/Largest Element in Unsorted Array | Set 1" }, { "code": null, "e": 23784, "s": 23757, "text": "Subset Sum Problem | DP-25" }, { "code": null, "e": 23829, "s": 23784, "text": "Python | Using 2D arrays/lists the right way" }, { "code": null, "e": 23840, "s": 23829, "text": "Merge Sort" }, { "code": null, "e": 23862, "s": 23840, "text": "Bubble Sort Algorithm" }, { "code": null, "e": 23872, "s": 23862, "text": "QuickSort" }, { "code": null, "e": 23887, "s": 23872, "text": "Insertion Sort" } ]
procmail - Unix, Linux Command
Procmail should be invoked automatically over the .forward file mechanism as soon as mail arrives. Alternatively, when installed by a system administrator (and in the standard Red Hat Linux configuration), it can be invoked from within the mailer immediately. When invoked, it first sets some environment variables to default values, reads the mail message from stdin until an EOF, separates the body from the header, and then, if no command line arguments are present, it starts to look for a file named $HOME/.procmailrc. According to the processing recipes in this file, the mail message that just arrived gets distributed into the right folder (and more). If no rcfile is found, or processing of the rcfile falls off the end, procmail will store the mail in the default system mailbox. If no rcfiles and no -p have been specified on the command line, procmail will, prior to reading $HOME/.procmailrc, interpret commands from /etc/procmailrc (if present). Care must be taken when creating /etc/procmailrc, because, if circumstances permit, it will be executed with root privileges (contrary to the $HOME/.procmailrc file of course). If running suid root or with root privileges, procmail will be able to perform as a functionally enhanced, backwards compatible mail delivery agent. Procmail can also be used as a general purpose mail filter, i.e., provisions have been made to enable procmail to be invoked in a special sendmail rule. The rcfile format is described in detail in the procmailrc(5) man page. The weighted scoring technique is described in detail in the procmailsc(5) man page. Examples for rcfile recipes can be looked up in the procmailex(5) man page. Any other arguments are presumed to be rcfile paths (either absolute, or if they start with ‘./’ relative to the current directory; any other relative path is relative to $HOME, unless the -m option has been given, in which case all relative paths are relative to the current directory); procmail will start with the first one it finds on the command line. The following ones will only be parsed if the preceding ones have a not matching HOST-directive entry, or in case they should not exist. If no rcfiles are specified, it looks for $HOME/.procmailrc. If not even that can be found, processing will continue according to the default settings of the environment variables and the ones specified on the command line. Skip the rest of this EXAMPLES section unless you are a system administrator who is vaguely familiar with sendmail.cf syntax. The -m option is typically used when procmail is called from within a rule in the sendmail.cf file. In order to be able to do this it is convenient to create an extra ‘procmail’ mailer in your sendmail.cf file (in addition to the perhaps already present ‘local’ mailer that starts up procmail). To create such a ‘procmail’ mailer I’d suggest something like: Mprocmail, P=/usr/bin/procmail, F=mSDFMhun, S=11, R=21, A=procmail -m $h $g $u This enables you to use rules like the following (most likely in ruleset 0) to filter mail through the procmail mailer (please note the leading tab to continue the rule, and the tab to separate the comments): R$*<@some.where>$* $#procmail $@/etc/procmailrcs/some.rc $:$1@some.where.procmail$2 R$*<@$*.procmail>$* $1<@$2>$3 Already filtered, map back And /etc/procmailrcs/some.rc could be as simple as: SENDER = "<$1>" # fix for empty sender addresses SHIFT = 1 # remove it from $@ :0 # sink all junk mail * ^Subject:.*junk /dev/null :0 w # pass along all other mail ! -oi -f "$SENDER" "$@" :0 # sink all junk mail * ^Subject:.*junk /dev/null :0 w # pass along all other mail ! -oi -f "$SENDER" "$@" Do watch out when sending mail from within the /etc/procmailrcs/some.rc file, if you send mail to addresses which match the first rule again, you could be creating an endless mail loop. In the unlikely event that you absolutely need to kill procmail before it has finished, first try and use the regular kill command (i.e., not kill -9, see the subsection Signals for suggestions), otherwise some lockfiles might not get removed. Beware when using the -t option, if procmail repeatedly is unable to deliver the mail (e.g., due to an incorrect rcfile), the system mailqueue could fill up. This could aggravate both the local postmaster and other users. The /etc/procmailrc file might be executed with root privileges, so be very careful of what you put in it. SHELL will be equal to that of the current recipient, so if procmail has to invoke the shell, you’d better set it to some safe value first. See also : DROPPRIVS. Keep in mind that if chown(1) is permitted on files in /etc/procmailrcs/, that they can be chowned to root (or anyone else) by their current owners. For maximum security, make sure this directory is executable to root only. Procmail is not the proper tool for sharing one mailbox among many users, such as when you have one POP account for all mail to your domain. It can be done if you manage to configure your MTA to add some headers with the envelope recipient data in order to tell Procmail who a message is for, but this is usually not the right thing to do. Perhaps you want to investigate if your MTA offers ‘virtual user tables’, or check out the ‘multidrop’ facility of Fetchmail. Procmail uses the regular TERMINATE signal to terminate any runaway filter, but it does not check if the filter responds to that signal and it only sends it to the filter itself, not to any of the filter’s children. A continued Content-Length: field is not handled correctly. The embedded newlines in a continued header should be skipped when matching instead of being treated as a single space as they are now. If there is no Content-Length: field or the -Y option has been specified and procmail appends to regular mailfolders, any lines in the body of the message that look like postmarks are prepended with ‘>’ (disarms bogus mailheaders). The regular expression that is used to search for these postmarks is: ‘\nFrom ’ If the destination name used in explicit delivery mode is not in /etc/passwd, procmail will proceed as if explicit delivery mode was not in effect. If not in explicit delivery mode and should the uid procmail is running under, have no corresponding /etc/passwd entry, then HOME will default to /, LOGNAME will default to #uid, SHELL will default to /bin/sh, and ORGMAIL will default to /tmp/dead.letter. When in explicit delivery mode, procmail will generate a leading ‘From ’ line if none is present. If one is already present procmail will leave it intact. If procmail is not invoked with one of the following user or group ids : root, daemon, uucp, mail, x400, network, list, slist, lists or news, but still has to generate or accept a new ‘From ’ line, it will generate an additional ‘>From ’ line to help distinguish fake mails. For security reasons procmail will only use an absolute or $HOME-relative rcfile if it is owned by the recipient or root, not world writable, and the directory it is contained in is not world writable. The $HOME/.procmailrc file has the additional constraint of not being group-writable or in a group-writable directory. If /var/mail/$LOGNAME is a bogus mailbox (i.e., does not belong to the recipient, is unwritable, is a symbolic link or is a hard link), procmail will upon startup try to rename it into a file starting with ‘BOGUS.$LOGNAME.’ and ending in an inode-sequence-code. If this turns out to be impossible, ORGMAIL will have no initial value, and hence will inhibit delivery without a proper rcfile. If /var/mail/$LOGNAME already is a valid mailbox, but has got too loose permissions on it, procmail will correct this. To prevent procmail from doing this make sure the u+x bit is set. When delivering to directories, MH folders, or maildir folders, you don’t need to use lockfiles to prevent several concurrently running procmail programs from messing up. Delivering to MH folders is slightly more time consuming than delivering to normal directories or mailboxes, because procmail has to search for the next available number (instead of having the filename immediately available). On general failure procmail will return EX_CANTCREAT, unless option -t is specified, in which case it will return EX_TEMPFAIL. To make ‘egrepping’ of headers more consistent, procmail concatenates all continued header fields; but only internally. When delivering the mail, line breaks will appear as before. If procmail is called under a name not starting with ‘procmail’ (e.g., if it is linked to another name and invoked as such), it comes up in explicit delivery mode, and expects the recipients’ names as command line arguments (as if -d had been specified). Comsat/biff notifications are done using udp. They are sent off once when procmail generates the regular logfile entry. The notification messages have the following extended format (or as close as you can get when final delivery was not to a file): $LOGNAME@offset_of_message_in_mailbox :absolute_path_to_mailbox Whenever procmail itself opens a file to deliver to, it consistently uses the following kernel locking strategies : fcntl(2). Procmail is NFS-resistant and eight-bit clean. There exists an excellent newbie FAQ about mailfilters (and procmail in particular); it is maintained by Nancy McGough <nancym@ii.com> and can be obtained by sending a mail to mail-server@rtfm.mit.edu with the following in the body: send usenet/news.answers/mail/filtering-faq If procmail is not installed globally as the default mail delivery agent (ask your system administrator), you have to make sure it is invoked when your mail arrives. In this case your $HOME/.forward (beware, it has to be world readable) file should contain the line below. Be sure to include the single and double quotes, and unless you know your site to be running smrsh (the SendMail Restricted SHell), it must be an absolute path. " |exec /usr/bin/procmail" Some mailers (notably exim) do not currently accept the above syntax. In such case use this instead: |/usr/bin/procmail Procmail can also be invoked to postprocess an already filled system mailbox. This can be useful if you don’t want to or can’t use a $HOME/.forward file (in which case the following script could periodically be called from within cron(1), or whenever you start reading mail): #!/bin/sh ORGMAIL=/var/mail/$LOGNAME if cd $HOME && test -s $ORGMAIL && lockfile -r0 -l1024 .newmail.lock 2>/dev/null then trap "rm -f .newmail.lock" 1 2 3 13 15 umask 077 lockfile -l1024 -ml cat $ORGMAIL >>.newmail && cat /dev/null >$ORGMAIL lockfile -mu formail -s procmail <.newmail && rm -f .newmail rm -f .newmail.lock fi exit 0 ORGMAIL=/var/mail/$LOGNAME if cd $HOME && test -s $ORGMAIL && lockfile -r0 -l1024 .newmail.lock 2>/dev/null then trap "rm -f .newmail.lock" 1 2 3 13 15 umask 077 lockfile -l1024 -ml cat $ORGMAIL >>.newmail && cat /dev/null >$ORGMAIL lockfile -mu formail -s procmail <.newmail && rm -f .newmail rm -f .newmail.lock fi exit 0 PATH=/usr/local/bin:/usr/bin:/bin MAILDIR=$HOME/Mail #you’d better make sure it exists DEFAULT=$MAILDIR/mbox #completely optional LOGFILE=$MAILDIR/from #recommended :0: * ^From.*berg from_me :0 * ^Subject:.*Flame /dev/null :0: * ^From.*berg from_me :0 * ^Subject:.*Flame /dev/null Other examples for rcfile recipes can be looked up in the procmailex(5) man page. <procmail-users@procmail.org> for submitting questions/answers. for subscription requests. If you would like to stay informed about new versions and official patches send a subscription request to procmail-announce-request@procmail.org <srb@cuci.nl> <guenther@sendmail.com> Advertisements 129 Lectures 23 hours Eduonix Learning Solutions 5 Lectures 4.5 hours Frahaan Hussain 35 Lectures 2 hours Pradeep D 41 Lectures 2.5 hours Musab Zayadneh 46 Lectures 4 hours GUHARAJANM 6 Lectures 4 hours Uplatz Print Add Notes Bookmark this page
[ { "code": null, "e": 11372, "s": 10577, "text": "\nProcmail should be invoked automatically over the\n.forward file mechanism as soon as mail arrives. Alternatively, when installed by\na system administrator (and in the standard Red Hat Linux configuration), it\ncan be invoked from within the mailer immediately. When invoked, it\nfirst sets some environment variables to default values, reads the mail message from\nstdin until an EOF, separates the body from the header, and then, if no command line\narguments are present, it starts to look for a file named\n$HOME/.procmailrc. According to the processing recipes in this file,\nthe mail message that just arrived gets distributed into the right folder\n(and more). If no rcfile is found, or processing of the rcfile falls off\nthe end, procmail will store the mail in the default system\nmailbox.\n" }, { "code": null, "e": 11721, "s": 11372, "text": "\nIf no rcfiles and no\n-p have been specified on the command line, procmail will, prior to reading $HOME/.procmailrc, interpret commands from\n/etc/procmailrc (if present).\nCare must be taken when creating /etc/procmailrc, because, if circumstances permit, it will be executed with root privileges (contrary to the $HOME/.procmailrc file of course).\n" }, { "code": null, "e": 11872, "s": 11721, "text": "\nIf running suid root or with root privileges, procmail will be able to\nperform as a functionally enhanced, backwards compatible mail delivery agent.\n" }, { "code": null, "e": 12027, "s": 11872, "text": "\nProcmail can also be used as a general purpose mail filter, i.e., provisions\nhave been made to enable procmail to be invoked in a special sendmail rule.\n" }, { "code": null, "e": 12101, "s": 12027, "text": "\nThe rcfile format is described in detail in the\nprocmailrc(5)\nman page.\n" }, { "code": null, "e": 12188, "s": 12101, "text": "\nThe weighted scoring technique is described in detail in the\nprocmailsc(5)\nman page.\n" }, { "code": null, "e": 12267, "s": 12188, "text": "\nExamples for rcfile recipes can be looked up in the\nprocmailex(5)\nman page.\n\n" }, { "code": null, "e": 12767, "s": 12270, "text": "\nAny other arguments are presumed to be rcfile paths (either absolute,\nor if they start with ‘./’ relative to the current\ndirectory;\nany other relative path is relative to $HOME, unless the\n-m option has been given, in which case all relative paths are relative to the\ncurrent directory); procmail will start with the first one it finds on the\ncommand line. The following ones will only be parsed if the preceding ones\nhave a not matching HOST-directive entry, or in case they should not exist.\n" }, { "code": null, "e": 12994, "s": 12767, "text": "\nIf no rcfiles are specified, it looks for\n$HOME/.procmailrc. If not even that can be found, processing will continue according to\nthe default settings of the environment variables and the ones specified\non the command line.\n\n" }, { "code": null, "e": 13122, "s": 12994, "text": "\nSkip the rest of this EXAMPLES section unless you are a system administrator\nwho is vaguely familiar with sendmail.cf syntax.\n" }, { "code": null, "e": 13484, "s": 13122, "text": "\nThe\n-m option is typically used when procmail is called from within a rule in the\nsendmail.cf file. In order to be able to do this it is convenient to create\nan extra ‘procmail’ mailer in your sendmail.cf file (in addition to the perhaps\nalready present ‘local’ mailer that starts up procmail). To create such a\n‘procmail’ mailer I’d suggest something like:\n" }, { "code": null, "e": 13576, "s": 13488, "text": "Mprocmail, P=/usr/bin/procmail, F=mSDFMhun, S=11, R=21,\n A=procmail -m $h $g $u\n" }, { "code": null, "e": 13787, "s": 13576, "text": "\nThis enables you to use rules like the following (most likely in ruleset 0)\nto filter mail through the procmail mailer (please note the leading tab\nto continue the rule, and the tab to separate the comments):\n" }, { "code": null, "e": 13955, "s": 13791, "text": "R$*<@some.where>$*\n $#procmail $@/etc/procmailrcs/some.rc $:$1@some.where.procmail$2\nR$*<@$*.procmail>$*\n $1<@$2>$3 Already filtered, map back\n" }, { "code": null, "e": 14009, "s": 13955, "text": "\nAnd /etc/procmailrcs/some.rc could be as simple as:\n" }, { "code": null, "e": 14298, "s": 14013, "text": "SENDER = \"<$1>\" # fix for empty sender addresses\nSHIFT = 1 # remove it from $@\n\n:0 # sink all junk mail\n* ^Subject:.*junk\n/dev/null\n\n:0 w # pass along all other mail\n! -oi -f \"$SENDER\" \"$@\"\n" }, { "code": null, "e": 14381, "s": 14298, "text": "\n:0 # sink all junk mail\n* ^Subject:.*junk\n/dev/null\n" }, { "code": null, "e": 14467, "s": 14381, "text": "\n:0 w # pass along all other mail\n! -oi -f \"$SENDER\" \"$@\"\n" }, { "code": null, "e": 14656, "s": 14467, "text": "\nDo watch out when sending mail from within the /etc/procmailrcs/some.rc file,\nif you send mail to addresses which match the first rule again, you could\nbe creating an endless mail loop.\n\n" }, { "code": null, "e": 14902, "s": 14656, "text": "\nIn the unlikely event that you absolutely need to kill procmail before it has\nfinished, first try and use the regular kill command (i.e.,\nnot kill -9, see the subsection\nSignals for suggestions), otherwise some\nlockfiles might not get removed.\n" }, { "code": null, "e": 15127, "s": 14902, "text": "\nBeware when using the\n-t option, if procmail repeatedly is unable to deliver the mail (e.g., due to\nan incorrect rcfile), the system mailqueue could fill up. This could\naggravate both the local postmaster and other users.\n" }, { "code": null, "e": 15398, "s": 15127, "text": "\nThe\n/etc/procmailrc file might be executed with root privileges, so be very careful of what you put in it.\nSHELL will be equal to that of the current recipient, so if procmail has to invoke the shell, you’d better set it to some safe value first.\nSee also :\nDROPPRIVS. " }, { "code": null, "e": 15624, "s": 15398, "text": "\nKeep in mind that if\nchown(1)\nis permitted on files in\n/etc/procmailrcs/, that they can be chowned to root (or anyone else) by their current owners.\nFor maximum security, make sure this directory is\nexecutable to root only.\n" }, { "code": null, "e": 16093, "s": 15624, "text": "\nProcmail is not the proper tool for sharing one mailbox among many\nusers, such as when you have one POP account for all mail to your\ndomain. It can be done if you manage to configure your MTA to add some\nheaders with the envelope recipient data in order to tell Procmail who\na message is for, but this is usually not the right thing to do.\nPerhaps you want to investigate if your MTA offers ‘virtual user\ntables’, or check out the ‘multidrop’ facility of Fetchmail.\n\n" }, { "code": null, "e": 16311, "s": 16093, "text": "\nProcmail uses the regular TERMINATE signal to terminate any runaway filter,\nbut it does not check if the filter responds to that signal and it only sends\nit to the filter itself, not to any of the filter’s children.\n" }, { "code": null, "e": 16373, "s": 16311, "text": "\nA continued\nContent-Length: field is not handled correctly.\n" }, { "code": null, "e": 16512, "s": 16373, "text": "\nThe embedded newlines in a continued header should be skipped when\nmatching instead of being treated as a single space as they are now.\n\n" }, { "code": null, "e": 16818, "s": 16512, "text": "\nIf there is no\nContent-Length: field or the\n-Y option has been specified and procmail appends to regular mailfolders, any\nlines in the body of the message that look like postmarks are prepended with\n‘>’ (disarms bogus mailheaders). The regular expression that is used\nto search for these postmarks is:\n\n" }, { "code": null, "e": 16829, "s": 16818, "text": "‘\\nFrom ’\n" }, { "code": null, "e": 17235, "s": 16829, "text": "\nIf the destination name used in explicit delivery mode is not in /etc/passwd,\nprocmail will proceed as if explicit delivery mode was not in effect.\nIf not in explicit delivery mode and\nshould the uid procmail is running under, have no corresponding /etc/passwd\nentry, then HOME will default to /, LOGNAME will default to #uid,\nSHELL will default to /bin/sh, and ORGMAIL will default to\n/tmp/dead.letter.\n" }, { "code": null, "e": 17669, "s": 17235, "text": "\nWhen in explicit delivery mode, procmail will generate a leading ‘From ’\nline if none is present. If one is already present procmail will leave it\nintact. If procmail is not invoked with one of the following user or group ids : root, daemon, uucp, mail, x400, network, list, slist, lists or news, but still has to generate or accept a new ‘From ’ line,\nit will generate an additional ‘>From ’ line to help distinguish\nfake mails.\n" }, { "code": null, "e": 17993, "s": 17669, "text": "\nFor security reasons procmail will only use an absolute or\n$HOME-relative rcfile if it is owned by the recipient or root, not\nworld writable, and the directory it is contained in is not world\nwritable. The $HOME/.procmailrc file has the additional constraint of not\nbeing group-writable or in a group-writable directory.\n" }, { "code": null, "e": 18387, "s": 17993, "text": "\nIf /var/mail/$LOGNAME is a bogus mailbox (i.e., does not belong to the\nrecipient, is unwritable, is a symbolic link or is a hard link), procmail will\nupon startup try to rename it into a file starting\nwith ‘BOGUS.$LOGNAME.’ and\nending in an inode-sequence-code. If this turns out to be impossible,\nORGMAIL will have\nno initial value, and hence will inhibit delivery without a proper rcfile.\n" }, { "code": null, "e": 18575, "s": 18387, "text": "\nIf /var/mail/$LOGNAME already is a valid mailbox, but has got too loose\npermissions on it, procmail will correct this. To prevent procmail from doing\nthis make sure the u+x bit is set.\n" }, { "code": null, "e": 18748, "s": 18575, "text": "\nWhen delivering to directories, MH folders, or maildir folders, you\ndon’t need to use lockfiles to prevent several concurrently running procmail\nprograms from messing up.\n" }, { "code": null, "e": 18976, "s": 18748, "text": "\nDelivering to MH folders is slightly more time consuming than delivering\nto normal directories or mailboxes, because procmail has to search for\nthe next available number (instead of having the filename immediately\navailable).\n" }, { "code": null, "e": 19105, "s": 18976, "text": "\nOn general failure procmail will return EX_CANTCREAT, unless option\n-t is specified, in which case it will return EX_TEMPFAIL.\n" }, { "code": null, "e": 19289, "s": 19105, "text": "\nTo make ‘egrepping’ of headers more consistent, procmail concatenates all\ncontinued header fields; but only internally. When delivering the mail, line\nbreaks will appear as before.\n" }, { "code": null, "e": 19546, "s": 19289, "text": "\nIf procmail is called under a name not starting with ‘procmail’ (e.g., if it\nis linked to another name and invoked as such), it comes up in explicit\ndelivery mode, and expects the recipients’ names as command line arguments\n(as if -d had been specified).\n" }, { "code": null, "e": 19800, "s": 19546, "text": "\nComsat/biff notifications are done using udp. They are sent off\nonce when procmail generates the regular logfile entry. The notification\nmessages have the following extended format (or as close as you can get when\nfinal delivery was not to a file):\n\n" }, { "code": null, "e": 19865, "s": 19800, "text": "$LOGNAME@offset_of_message_in_mailbox :absolute_path_to_mailbox\n" }, { "code": null, "e": 19993, "s": 19865, "text": "\nWhenever procmail itself opens a file to deliver to, it\nconsistently uses the following kernel locking strategies :\nfcntl(2).\n" }, { "code": null, "e": 20044, "s": 19993, "text": "\nProcmail is NFS-resistant and eight-bit clean.\n\n\n" }, { "code": null, "e": 20280, "s": 20044, "text": "\nThere exists an excellent newbie FAQ about mailfilters (and procmail\nin particular); it is maintained by Nancy McGough <nancym@ii.com>\nand can be obtained by sending a mail to mail-server@rtfm.mit.edu with\nthe following in the body:\n\n" }, { "code": null, "e": 20325, "s": 20280, "text": "send usenet/news.answers/mail/filtering-faq\n" }, { "code": null, "e": 20762, "s": 20325, "text": "\nIf procmail is\nnot installed globally as the default mail delivery agent (ask your system administrator), you have to make sure it is invoked when your mail arrives.\nIn this case your $HOME/.forward (beware, it\nhas to be world readable) file should contain the line below. Be sure to include\nthe single and double quotes, and unless you know your site to be running\nsmrsh (the SendMail Restricted SHell), it must be an\nabsolute path.\n" }, { "code": null, "e": 20793, "s": 20765, "text": "\" |exec /usr/bin/procmail\"\n" }, { "code": null, "e": 20896, "s": 20793, "text": "\nSome mailers (notably exim) do not currently accept the above syntax.\nIn such case use this instead:\n" }, { "code": null, "e": 20919, "s": 20899, "text": "|/usr/bin/procmail\n" }, { "code": null, "e": 21198, "s": 20919, "text": "\nProcmail can also be invoked to postprocess an already filled system\nmailbox. This can be useful if you don’t want to or can’t use a\n$HOME/.forward file (in which case the following script could\nperiodically be called from within\ncron(1),\nor whenever you start reading mail):\n" }, { "code": null, "e": 21561, "s": 21202, "text": "#!/bin/sh\n\nORGMAIL=/var/mail/$LOGNAME\n\nif cd $HOME &&\n test -s $ORGMAIL &&\n lockfile -r0 -l1024 .newmail.lock 2>/dev/null\nthen\n trap \"rm -f .newmail.lock\" 1 2 3 13 15\n umask 077\n lockfile -l1024 -ml\n cat $ORGMAIL >>.newmail &&\n cat /dev/null >$ORGMAIL\n lockfile -mu\n formail -s procmail <.newmail &&\n rm -f .newmail\n rm -f .newmail.lock\nfi\nexit 0\n" }, { "code": null, "e": 21590, "s": 21561, "text": "\nORGMAIL=/var/mail/$LOGNAME\n" }, { "code": null, "e": 21911, "s": 21590, "text": "\nif cd $HOME &&\n test -s $ORGMAIL &&\n lockfile -r0 -l1024 .newmail.lock 2>/dev/null\nthen\n trap \"rm -f .newmail.lock\" 1 2 3 13 15\n umask 077\n lockfile -l1024 -ml\n cat $ORGMAIL >>.newmail &&\n cat /dev/null >$ORGMAIL\n lockfile -mu\n formail -s procmail <.newmail &&\n rm -f .newmail\n rm -f .newmail.lock\nfi\nexit 0\n" }, { "code": null, "e": 22150, "s": 21915, "text": "PATH=/usr/local/bin:/usr/bin:/bin\nMAILDIR=$HOME/Mail #you’d better make sure it exists\nDEFAULT=$MAILDIR/mbox #completely optional\nLOGFILE=$MAILDIR/from #recommended\n\n:0:\n* ^From.*berg\nfrom_me\n\n:0\n* ^Subject:.*Flame\n/dev/null\n" }, { "code": null, "e": 22178, "s": 22150, "text": "\n:0:\n* ^From.*berg\nfrom_me\n" }, { "code": null, "e": 22212, "s": 22178, "text": "\n:0\n* ^Subject:.*Flame\n/dev/null\n" }, { "code": null, "e": 22296, "s": 22212, "text": "\nOther examples for rcfile recipes can be looked up in the\nprocmailex(5)\nman page.\n" }, { "code": null, "e": 22362, "s": 22296, "text": "<procmail-users@procmail.org>\n\nfor submitting questions/answers.\n" }, { "code": null, "e": 22390, "s": 22362, "text": "for subscription requests.\n" }, { "code": null, "e": 22500, "s": 22390, "text": "\n\nIf you would like to stay informed about new versions and official patches send\na subscription request to\n\n" }, { "code": null, "e": 22540, "s": 22500, "text": "procmail-announce-request@procmail.org\n" }, { "code": null, "e": 22555, "s": 22540, "text": "<srb@cuci.nl>\n" }, { "code": null, "e": 22580, "s": 22555, "text": "<guenther@sendmail.com>\n" }, { "code": null, "e": 22597, "s": 22580, "text": "\nAdvertisements\n" }, { "code": null, "e": 22632, "s": 22597, "text": "\n 129 Lectures \n 23 hours \n" }, { "code": null, "e": 22660, "s": 22632, "text": " Eduonix Learning Solutions" }, { "code": null, "e": 22694, "s": 22660, "text": "\n 5 Lectures \n 4.5 hours \n" }, { "code": null, "e": 22711, "s": 22694, "text": " Frahaan Hussain" }, { "code": null, "e": 22744, "s": 22711, "text": "\n 35 Lectures \n 2 hours \n" }, { "code": null, "e": 22755, "s": 22744, "text": " Pradeep D" }, { "code": null, "e": 22790, "s": 22755, "text": "\n 41 Lectures \n 2.5 hours \n" }, { "code": null, "e": 22806, "s": 22790, "text": " Musab Zayadneh" }, { "code": null, "e": 22839, "s": 22806, "text": "\n 46 Lectures \n 4 hours \n" }, { "code": null, "e": 22851, "s": 22839, "text": " GUHARAJANM" }, { "code": null, "e": 22883, "s": 22851, "text": "\n 6 Lectures \n 4 hours \n" }, { "code": null, "e": 22891, "s": 22883, "text": " Uplatz" }, { "code": null, "e": 22898, "s": 22891, "text": " Print" }, { "code": null, "e": 22909, "s": 22898, "text": " Add Notes" } ]
io.WriteString() Function in Golang with Examples - GeeksforGeeks
05 May, 2020 In Go language, io packages supply fundamental interfaces to the I/O primitives. And its principal job is to enclose the ongoing implementations of such king of primitives. The WriteString() function in Go language is used to write the contents of the stated string “s” to the writer “w”, which takes a slice of bytes. And if “w” is implemented by StringWriter then its WriteString method is called immediately. Else, w.Write is invoked strictly once. Moreover, this function is defined under the io package. Here, you need to import the “io” package in order to use these functions. Syntax: func WriteString(w Writer, s string) (n int, err error) Here, “w” is the writer, and “s” is the string that is written to the writer. Return value: It returns the total number of bytes of the content of type int and also returns an error if any. Below examples illustrates the use of above method: Example 1: // Golang program to illustrate the usage of// io.WriteString() function // Including main packagepackage main // Importing fmt, io, and osimport ( "fmt" "io" "os") // Calling mainfunc main() { // Defining w using Stdout w := os.Stdout // Calling WriteString method with its parameters n, err := io.WriteString(w, "GfG\n") // If error is not nil then panics if err != nil { panic(err) } // Prints output fmt.Printf("n: %d\n", n)} Output: GfG n: 4 Example 2: // Golang program to illustrate the usage of// io.WriteString() function // Including main packagepackage main // Importing fmt, io, and osimport ( "fmt" "io" "os") // Calling mainfunc main() { // Defining w using Stdout w := os.Stdout // Calling WriteString method with its parameters n, err := io.WriteString(w, "GeeksforGeeks\nis\na\nCS-Portal.\n") // If error is not nil then panics if err != nil { panic(err) } // Prints output fmt.Printf("n: %d\n", n)} Output: GeeksforGeeks is a CS-Portal. n: 30 Here, in the above example, “Stdout” is used in order to create a default file descriptor where the stated content is written. Golang-io Go Language Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Time Durations in Golang How to Parse JSON in Golang? Strings in Golang Defer Keyword in Golang Structures in Golang How to iterate over an Array using for loop in Golang? Class and Object in Golang Loops in Go Language Rune in Golang time.Parse() Function in Golang With Examples
[ { "code": null, "e": 24556, "s": 24528, "text": "\n05 May, 2020" }, { "code": null, "e": 25140, "s": 24556, "text": "In Go language, io packages supply fundamental interfaces to the I/O primitives. And its principal job is to enclose the ongoing implementations of such king of primitives. The WriteString() function in Go language is used to write the contents of the stated string “s” to the writer “w”, which takes a slice of bytes. And if “w” is implemented by StringWriter then its WriteString method is called immediately. Else, w.Write is invoked strictly once. Moreover, this function is defined under the io package. Here, you need to import the “io” package in order to use these functions." }, { "code": null, "e": 25148, "s": 25140, "text": "Syntax:" }, { "code": null, "e": 25205, "s": 25148, "text": "func WriteString(w Writer, s string) (n int, err error)\n" }, { "code": null, "e": 25283, "s": 25205, "text": "Here, “w” is the writer, and “s” is the string that is written to the writer." }, { "code": null, "e": 25395, "s": 25283, "text": "Return value: It returns the total number of bytes of the content of type int and also returns an error if any." }, { "code": null, "e": 25447, "s": 25395, "text": "Below examples illustrates the use of above method:" }, { "code": null, "e": 25458, "s": 25447, "text": "Example 1:" }, { "code": "// Golang program to illustrate the usage of// io.WriteString() function // Including main packagepackage main // Importing fmt, io, and osimport ( \"fmt\" \"io\" \"os\") // Calling mainfunc main() { // Defining w using Stdout w := os.Stdout // Calling WriteString method with its parameters n, err := io.WriteString(w, \"GfG\\n\") // If error is not nil then panics if err != nil { panic(err) } // Prints output fmt.Printf(\"n: %d\\n\", n)}", "e": 25942, "s": 25458, "text": null }, { "code": null, "e": 25950, "s": 25942, "text": "Output:" }, { "code": null, "e": 25960, "s": 25950, "text": "GfG\nn: 4\n" }, { "code": null, "e": 25971, "s": 25960, "text": "Example 2:" }, { "code": "// Golang program to illustrate the usage of// io.WriteString() function // Including main packagepackage main // Importing fmt, io, and osimport ( \"fmt\" \"io\" \"os\") // Calling mainfunc main() { // Defining w using Stdout w := os.Stdout // Calling WriteString method with its parameters n, err := io.WriteString(w, \"GeeksforGeeks\\nis\\na\\nCS-Portal.\\n\") // If error is not nil then panics if err != nil { panic(err) } // Prints output fmt.Printf(\"n: %d\\n\", n)}", "e": 26484, "s": 25971, "text": null }, { "code": null, "e": 26492, "s": 26484, "text": "Output:" }, { "code": null, "e": 26529, "s": 26492, "text": "GeeksforGeeks\nis\na\nCS-Portal.\nn: 30\n" }, { "code": null, "e": 26656, "s": 26529, "text": "Here, in the above example, “Stdout” is used in order to create a default file descriptor where the stated content is written." }, { "code": null, "e": 26666, "s": 26656, "text": "Golang-io" }, { "code": null, "e": 26678, "s": 26666, "text": "Go Language" }, { "code": null, "e": 26776, "s": 26678, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 26801, "s": 26776, "text": "Time Durations in Golang" }, { "code": null, "e": 26830, "s": 26801, "text": "How to Parse JSON in Golang?" }, { "code": null, "e": 26848, "s": 26830, "text": "Strings in Golang" }, { "code": null, "e": 26872, "s": 26848, "text": "Defer Keyword in Golang" }, { "code": null, "e": 26893, "s": 26872, "text": "Structures in Golang" }, { "code": null, "e": 26948, "s": 26893, "text": "How to iterate over an Array using for loop in Golang?" }, { "code": null, "e": 26975, "s": 26948, "text": "Class and Object in Golang" }, { "code": null, "e": 26996, "s": 26975, "text": "Loops in Go Language" }, { "code": null, "e": 27011, "s": 26996, "text": "Rune in Golang" } ]
Tryit Editor v3.7
Tryit: HTML marked text
[]
Addition of 2 matrices in Java
#include <stdio.h> int main() { int m, n, c, d, first[10][10], second[10][10], sum[10][10]; printf("Enter the number of rows and columns of matrix\n"); scanf("%d%d", &m, &n); printf("Enter the elements of first matrix\n"); for (c = 0; c < m; c++) for (d = 0; d < n; d++) scanf("%d", &first[c][d]); printf("Enter the elements of second matrix\n"); for (c = 0; c < m; c++) for (d = 0 ; d < n; d++) scanf("%d", &second[c][d]); printf("Sum of entered matrices:-\n"); for (c = 0; c < m; c++) { for (d = 0 ; d < n; d++) { sum[c][d] = first[c][d] + second[c][d]; printf("%d\t", sum[c][d]); } printf("\n"); } return 0; }
[ { "code": null, "e": 1786, "s": 1062, "text": "#include <stdio.h>\nint main()\n{\n int m, n, c, d, first[10][10], second[10][10], sum[10][10];\n printf(\"Enter the number of rows and columns of matrix\\n\");\n scanf(\"%d%d\", &m, &n);\n printf(\"Enter the elements of first matrix\\n\");\n for (c = 0; c < m; c++)\n for (d = 0; d < n; d++)\n scanf(\"%d\", &first[c][d]);\n printf(\"Enter the elements of second matrix\\n\");\n for (c = 0; c < m; c++)\n for (d = 0 ; d < n; d++)\n scanf(\"%d\", &second[c][d]);\n printf(\"Sum of entered matrices:-\\n\");\n for (c = 0; c < m; c++) {\n for (d = 0 ; d < n; d++) {\n sum[c][d] = first[c][d] + second[c][d];\n printf(\"%d\\t\", sum[c][d]);\n }\n printf(\"\\n\");\n }\n return 0;\n}" } ]
Count negative elements present in every K-length subarray - GeeksforGeeks
30 Jun, 2021 Given an array arr[] of size N and an integer K, the task is to count the number of negative elements present in all K-length subarrays. Example: Input: arr[] = {-1, 2, -2, 3, 5, -7, -5}, K = 3Output: 2 1 1 1 2Explanation: First Subarray: {-1, 2, -2}. Count of negative numbers = 2.Second Subarray: {2, -2, 3}. Count of negative numbers = 1.Third Subarray: {-2, 3, 5}. Count of negative numbers = 1.Fourth Subarray: {3, 5, -7}. Count of negative numbers = 1.Fifth Subarray: {5, -7, -5}. Count of negative numbers = 2. Input: arr[] = {-1, 2, 4, 4}, K = 2Output: 1 0 0 Naive Approach: The simplest approach is to traverse the given array, considering every window of size K, and find the count of negative numbers in every window. Time Complexity: O(N*K)Auxiliary Space: O(1) Efficient Approach: This problem can be solved using the window sliding technique. Follow the steps below to solve the problem: Initialize a variable count as 0 to store the count of negative elements in a window of size K. Initialize two variables i and j as 0 to store the first and last index of the window respectively. Loop while j<N and perform the following steps:If arr[j] < 0, increment count by 1.If the size of the window, i.e, j-i+1 is equal to K, print the value of count, and check if arr[i] < 0, then decrement count by 1. Also, increment i by 1.Increment the value of j by 1. If arr[j] < 0, increment count by 1. If the size of the window, i.e, j-i+1 is equal to K, print the value of count, and check if arr[i] < 0, then decrement count by 1. Also, increment i by 1. Increment the value of j by 1. Below is the implementation of the above approach C++ Java Python3 C# Javascript // C++ program for the above approach#include<bits/stdc++.h>using namespace std; // Function to count the number of// negative elements in every window// of size Kvoid countNegative(vector<int> arr, int k){ // Initialize the window pointers int i = 0; int j = 0; // Store the count of negative numbers int count = 0; int n = arr.size(); // Traverse the array, arr[] while (j < n) { // Increase the count // if element is less then 0 if (arr[j] < 0) { count++; } // If size of the window equal to k if (j - i + 1 == k) { cout << count << " "; // If the first element of // the window is less than 0, // decrement count by 1 if (arr[i] < 0) { count--; } i++; } j++; }} // Driver Codeint main(){ // Given Input vector<int> arr{ -1, 2, -2, 3, 5, -7, -5 }; int k = 3; // Function Call countNegative(arr, k);} // This code is contributed by bgangwar59 // Java program for the above approachimport java.io.*;import java.util.*; class GFG { // Function to count the number of // negative elements in every window // of size K public static void countNegative(int[] arr, int k) { // Initialize the window pointers int i = 0; int j = 0; // Store the count of negative numbers int count = 0; int n = arr.length; // Traverse the array, arr[] while (j < n) { // Increase the count // if element is less then 0 if (arr[j] < 0) { count++; } // If size of the window equal to k if (j - i + 1 == k) { System.out.print(count + " "); // If the first element of // the window is less than 0, // decrement count by 1 if (arr[i] < 0) { count--; } i++; } j++; } } // Driver Code public static void main(String[] args) { // Given Input int[] arr = { -1, 2, -2, 3, 5, -7, -5 }; int k = 3; // Function Call countNegative(arr, k); }} # Function to count the number of# negative elements in every window# of size Kdef countNegative(arr,k): # Initialize the window pointers i = 0 j = 0 # Store the count of negative numbers count = 0 n = len(arr) while(j < n): # Increase the count # if element is less then 0 if (arr[j] < 0): count = count + 1 # If size of the window equal to k if (j - i + 1 == k): print(count,end=" ") # If the first element of # the window is less than 0, # decrement count by 1 if(arr[i] < 0): count = count - 1 i = i+1 j = j+1 # Driver Code # Given Inputarr = [-1, 2, -2, 3, 5, -7, -5]k = 3countNegative(arr, k) # This code is contributed by abhinavjain194. // C# program for the above approachusing System; class GFG{ // Function to count the number of// negative elements in every window// of size Kpublic static void countNegative(int[] arr, int k){ // Initialize the window pointers int i = 0; int j = 0; // Store the count of negative numbers int count = 0; int n = arr.Length; // Traverse the array, arr[] while (j < n) { // Increase the count // if element is less then 0 if (arr[j] < 0) { count++; } // If size of the window equal to k if (j - i + 1 == k) { Console.Write(count + " "); // If the first element of // the window is less than 0, // decrement count by 1 if (arr[i] < 0) { count--; } i++; } j++; }} // Driver Codepublic static void Main(string[] args){ // Given Input int[] arr = { -1, 2, -2, 3, 5, -7, -5 }; int k = 3; // Function Call countNegative(arr, k);}} // This code is contributed by ukasp <script>// Javascript program for the above approach // Function to count the number of// negative elements in every window// of size Kfunction countNegative(arr, k){ // Initialize the window pointers var i = 0; var j = 0; // Store the count of negative numbers var count = 0; var n = arr.length; // Traverse the array, arr[] while (j < n) { // Increase the count // if element is less then 0 if (arr[j] < 0) { count++; } // If size of the window equal to k if (j - i + 1 == k) { document.write( count + " "); // If the first element of // the window is less than 0, // decrement count by 1 if (arr[i] < 0) { count--; } i++; } j++; }} var arr = [ -1, 2, -2, 3, 5, -7, -5 ];var k = 3; // Function CallcountNegative(arr, k); //This code is contributed by SoumikMondal</script> 2 1 1 1 2 Time Complexity: O(N)Auxiliary Space: O(1) ukasp abhinavjain194 bgangwar59 SoumikMondal sliding-window subarray Arrays Searching sliding-window Arrays Searching Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Stack Data Structure (Introduction and Program) Top 50 Array Coding Problems for Interviews Introduction to Arrays Multidimensional Arrays in Java Linear Search Binary Search Linear Search Maximum and minimum of an array using minimum number of comparisons Find the Missing Number K'th Smallest/Largest Element in Unsorted Array | Set 1
[ { "code": null, "e": 25154, "s": 25126, "text": "\n30 Jun, 2021" }, { "code": null, "e": 25291, "s": 25154, "text": "Given an array arr[] of size N and an integer K, the task is to count the number of negative elements present in all K-length subarrays." }, { "code": null, "e": 25300, "s": 25291, "text": "Example:" }, { "code": null, "e": 25672, "s": 25300, "text": "Input: arr[] = {-1, 2, -2, 3, 5, -7, -5}, K = 3Output: 2 1 1 1 2Explanation: First Subarray: {-1, 2, -2}. Count of negative numbers = 2.Second Subarray: {2, -2, 3}. Count of negative numbers = 1.Third Subarray: {-2, 3, 5}. Count of negative numbers = 1.Fourth Subarray: {3, 5, -7}. Count of negative numbers = 1.Fifth Subarray: {5, -7, -5}. Count of negative numbers = 2." }, { "code": null, "e": 25721, "s": 25672, "text": "Input: arr[] = {-1, 2, 4, 4}, K = 2Output: 1 0 0" }, { "code": null, "e": 25884, "s": 25721, "text": "Naive Approach: The simplest approach is to traverse the given array, considering every window of size K, and find the count of negative numbers in every window. " }, { "code": null, "e": 25929, "s": 25884, "text": "Time Complexity: O(N*K)Auxiliary Space: O(1)" }, { "code": null, "e": 26057, "s": 25929, "text": "Efficient Approach: This problem can be solved using the window sliding technique. Follow the steps below to solve the problem:" }, { "code": null, "e": 26153, "s": 26057, "text": "Initialize a variable count as 0 to store the count of negative elements in a window of size K." }, { "code": null, "e": 26253, "s": 26153, "text": "Initialize two variables i and j as 0 to store the first and last index of the window respectively." }, { "code": null, "e": 26521, "s": 26253, "text": "Loop while j<N and perform the following steps:If arr[j] < 0, increment count by 1.If the size of the window, i.e, j-i+1 is equal to K, print the value of count, and check if arr[i] < 0, then decrement count by 1. Also, increment i by 1.Increment the value of j by 1." }, { "code": null, "e": 26558, "s": 26521, "text": "If arr[j] < 0, increment count by 1." }, { "code": null, "e": 26713, "s": 26558, "text": "If the size of the window, i.e, j-i+1 is equal to K, print the value of count, and check if arr[i] < 0, then decrement count by 1. Also, increment i by 1." }, { "code": null, "e": 26744, "s": 26713, "text": "Increment the value of j by 1." }, { "code": null, "e": 26794, "s": 26744, "text": "Below is the implementation of the above approach" }, { "code": null, "e": 26798, "s": 26794, "text": "C++" }, { "code": null, "e": 26803, "s": 26798, "text": "Java" }, { "code": null, "e": 26811, "s": 26803, "text": "Python3" }, { "code": null, "e": 26814, "s": 26811, "text": "C#" }, { "code": null, "e": 26825, "s": 26814, "text": "Javascript" }, { "code": "// C++ program for the above approach#include<bits/stdc++.h>using namespace std; // Function to count the number of// negative elements in every window// of size Kvoid countNegative(vector<int> arr, int k){ // Initialize the window pointers int i = 0; int j = 0; // Store the count of negative numbers int count = 0; int n = arr.size(); // Traverse the array, arr[] while (j < n) { // Increase the count // if element is less then 0 if (arr[j] < 0) { count++; } // If size of the window equal to k if (j - i + 1 == k) { cout << count << \" \"; // If the first element of // the window is less than 0, // decrement count by 1 if (arr[i] < 0) { count--; } i++; } j++; }} // Driver Codeint main(){ // Given Input vector<int> arr{ -1, 2, -2, 3, 5, -7, -5 }; int k = 3; // Function Call countNegative(arr, k);} // This code is contributed by bgangwar59", "e": 27928, "s": 26825, "text": null }, { "code": "// Java program for the above approachimport java.io.*;import java.util.*; class GFG { // Function to count the number of // negative elements in every window // of size K public static void countNegative(int[] arr, int k) { // Initialize the window pointers int i = 0; int j = 0; // Store the count of negative numbers int count = 0; int n = arr.length; // Traverse the array, arr[] while (j < n) { // Increase the count // if element is less then 0 if (arr[j] < 0) { count++; } // If size of the window equal to k if (j - i + 1 == k) { System.out.print(count + \" \"); // If the first element of // the window is less than 0, // decrement count by 1 if (arr[i] < 0) { count--; } i++; } j++; } } // Driver Code public static void main(String[] args) { // Given Input int[] arr = { -1, 2, -2, 3, 5, -7, -5 }; int k = 3; // Function Call countNegative(arr, k); }}", "e": 29153, "s": 27928, "text": null }, { "code": "# Function to count the number of# negative elements in every window# of size Kdef countNegative(arr,k): # Initialize the window pointers i = 0 j = 0 # Store the count of negative numbers count = 0 n = len(arr) while(j < n): # Increase the count # if element is less then 0 if (arr[j] < 0): count = count + 1 # If size of the window equal to k if (j - i + 1 == k): print(count,end=\" \") # If the first element of # the window is less than 0, # decrement count by 1 if(arr[i] < 0): count = count - 1 i = i+1 j = j+1 # Driver Code # Given Inputarr = [-1, 2, -2, 3, 5, -7, -5]k = 3countNegative(arr, k) # This code is contributed by abhinavjain194.", "e": 30048, "s": 29153, "text": null }, { "code": "// C# program for the above approachusing System; class GFG{ // Function to count the number of// negative elements in every window// of size Kpublic static void countNegative(int[] arr, int k){ // Initialize the window pointers int i = 0; int j = 0; // Store the count of negative numbers int count = 0; int n = arr.Length; // Traverse the array, arr[] while (j < n) { // Increase the count // if element is less then 0 if (arr[j] < 0) { count++; } // If size of the window equal to k if (j - i + 1 == k) { Console.Write(count + \" \"); // If the first element of // the window is less than 0, // decrement count by 1 if (arr[i] < 0) { count--; } i++; } j++; }} // Driver Codepublic static void Main(string[] args){ // Given Input int[] arr = { -1, 2, -2, 3, 5, -7, -5 }; int k = 3; // Function Call countNegative(arr, k);}} // This code is contributed by ukasp", "e": 31167, "s": 30048, "text": null }, { "code": "<script>// Javascript program for the above approach // Function to count the number of// negative elements in every window// of size Kfunction countNegative(arr, k){ // Initialize the window pointers var i = 0; var j = 0; // Store the count of negative numbers var count = 0; var n = arr.length; // Traverse the array, arr[] while (j < n) { // Increase the count // if element is less then 0 if (arr[j] < 0) { count++; } // If size of the window equal to k if (j - i + 1 == k) { document.write( count + \" \"); // If the first element of // the window is less than 0, // decrement count by 1 if (arr[i] < 0) { count--; } i++; } j++; }} var arr = [ -1, 2, -2, 3, 5, -7, -5 ];var k = 3; // Function CallcountNegative(arr, k); //This code is contributed by SoumikMondal</script>", "e": 32174, "s": 31167, "text": null }, { "code": null, "e": 32184, "s": 32174, "text": "2 1 1 1 2" }, { "code": null, "e": 32229, "s": 32186, "text": "Time Complexity: O(N)Auxiliary Space: O(1)" }, { "code": null, "e": 32237, "s": 32231, "text": "ukasp" }, { "code": null, "e": 32252, "s": 32237, "text": "abhinavjain194" }, { "code": null, "e": 32263, "s": 32252, "text": "bgangwar59" }, { "code": null, "e": 32276, "s": 32263, "text": "SoumikMondal" }, { "code": null, "e": 32291, "s": 32276, "text": "sliding-window" }, { "code": null, "e": 32300, "s": 32291, "text": "subarray" }, { "code": null, "e": 32307, "s": 32300, "text": "Arrays" }, { "code": null, "e": 32317, "s": 32307, "text": "Searching" }, { "code": null, "e": 32332, "s": 32317, "text": "sliding-window" }, { "code": null, "e": 32339, "s": 32332, "text": "Arrays" }, { "code": null, "e": 32349, "s": 32339, "text": "Searching" }, { "code": null, "e": 32447, "s": 32349, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 32456, "s": 32447, "text": "Comments" }, { "code": null, "e": 32469, "s": 32456, "text": "Old Comments" }, { "code": null, "e": 32517, "s": 32469, "text": "Stack Data Structure (Introduction and Program)" }, { "code": null, "e": 32561, "s": 32517, "text": "Top 50 Array Coding Problems for Interviews" }, { "code": null, "e": 32584, "s": 32561, "text": "Introduction to Arrays" }, { "code": null, "e": 32616, "s": 32584, "text": "Multidimensional Arrays in Java" }, { "code": null, "e": 32630, "s": 32616, "text": "Linear Search" }, { "code": null, "e": 32644, "s": 32630, "text": "Binary Search" }, { "code": null, "e": 32658, "s": 32644, "text": "Linear Search" }, { "code": null, "e": 32726, "s": 32658, "text": "Maximum and minimum of an array using minimum number of comparisons" }, { "code": null, "e": 32750, "s": 32726, "text": "Find the Missing Number" } ]
Convert an Array to a Circular Doubly Linked List - GeeksforGeeks
09 Jul, 2021 Prerequisite: Doubly Linked list, Circular Linked List, Circular Doubly Linked ListGiven an array of N elements. The task is to write a program to convert the array into a circular doubly linked list. The idea is to start traversing the array and for every array element create a new list node and assign the prev and next pointers of this node accordingly. Create a pointer start to point to the starting of the list which will initially point to NULL(Empty list). For the first element of the array, create a new node and put that node’s prev and next pointers to point to start to maintain the circular fashion of the list. For the rest of the array elements, insert those elements to the end of the created circular doubly linked list. Below is the implementation of above idea: C++ Java Python3 C# Javascript // CPP program to convert array to// circular doubly linked list #include<bits/stdc++.h>using namespace std; // Doubly linked list nodestruct node{ int data; struct node *next; struct node *prev;}; // Utility function to create a node in memorystruct node* getNode(){ return ((struct node *)malloc(sizeof(struct node)));} // Function to display the listint displayList(struct node *temp){ struct node *t = temp; if(temp == NULL) return 0; else { cout<<"The list is: "; while(temp->next != t) { cout<<temp->data<<" "; temp = temp->next; } cout<<temp->data; return 1; }} // Function to convert array into listvoid createList(int arr[], int n, struct node **start){ // Declare newNode and temporary pointer struct node *newNode,*temp; int i; // Iterate the loop until array length for(i=0;i<n;i++) { // Create new node newNode = getNode(); // Assign the array data newNode->data = arr[i]; // If it is first element // Put that node prev and next as start // as it is circular if(i==0) { *start = newNode; newNode->prev = *start; newNode->next = *start; } else { // Find the last node temp = (*start)->prev; // Add the last node to make them // in circular fashion temp->next = newNode; newNode->next = *start; newNode->prev = temp; temp = *start; temp->prev = newNode; } }} // Driver Codeint main(){ // Array to be converted int arr[] = {1,2,3,4,5}; int n = sizeof(arr) / sizeof(arr[0]); // Start Pointer struct node *start = NULL; // Create the List createList(arr, n, &start); // Display the list displayList(start); return 0;} // Java program to convert array to// circular doubly linked listclass GFG{ // Doubly linked list nodestatic class node{ int data; node next; node prev;}; // Utility function to create a node in memorystatic node getNode(){ return new node();} // Function to display the liststatic int displayList( node temp){ node t = temp; if(temp == null) return 0; else { System.out.print("The list is: "); while(temp.next != t) { System.out.print(temp.data+" "); temp = temp.next; } System.out.print(temp.data); return 1; }} // Function to convert array into liststatic node createList(int arr[], int n, node start){ // Declare newNode and temporary pointer node newNode,temp; int i; // Iterate the loop until array length for(i = 0; i < n; i++) { // Create new node newNode = getNode(); // Assign the array data newNode.data = arr[i]; // If it is first element // Put that node prev and next as start // as it is circular if(i == 0) { start = newNode; newNode.prev = start; newNode.next = start; } else { // Find the last node temp = (start).prev; // Add the last node to make them // in circular fashion temp.next = newNode; newNode.next = start; newNode.prev = temp; temp = start; temp.prev = newNode; } } return start;} // Driver Codepublic static void main(String args[]){ // Array to be converted int arr[] = {1,2,3,4,5}; int n = arr.length; // Start Pointer node start = null; // Create the List start = createList(arr, n, start); // Display the list displayList(start);}} // This code is contributed by Arnab Kundu # Python3 program to convert array to# circular doubly linked list # Node of the doubly linked listclass Node: def __init__(self, data): self.data = data self.prev = None self.next = None # Utility function to create a node in memorydef getNode(): return (Node(0)) # Function to display the listdef displayList(temp): t = temp if(temp == None): return 0 else: print("The list is: ", end = " ") while(temp.next != t): print(temp.data, end = " ") temp = temp.next print(temp.data) return 1 # Function to convert array into listdef createList(arr, n, start): # Declare newNode and temporary pointer newNode = None temp = None i = 0 # Iterate the loop until array length while(i < n): # Create new node newNode = getNode() # Assign the array data newNode.data = arr[i] # If it is first element # Put that node prev and next as start # as it is circular if(i == 0): start = newNode newNode.prev = start newNode.next = start else: # Find the last node temp = (start).prev # Add the last node to make them # in circular fashion temp.next = newNode newNode.next = start newNode.prev = temp temp = start temp.prev = newNode i = i + 1 return start # Driver Codeif __name__ == "__main__": # Array to be converted arr = [1, 2, 3, 4, 5] n = len(arr) # Start Pointer start = None # Create the List start = createList(arr, n, start) # Display the list displayList(start) # This code is contributed by Arnab Kundu // C# program to convert array to// circular doubly linked listusing System; class GFG{ // Doubly linked list nodepublic class node{ public int data; public node next; public node prev;}; // Utility function to create a node in memorystatic node getNode(){ return new node();} // Function to display the liststatic int displayList( node temp){ node t = temp; if(temp == null) return 0; else { Console.Write("The list is: "); while(temp.next != t) { Console.Write(temp.data + " "); temp = temp.next; } Console.Write(temp.data); return 1; }} // Function to convert array into liststatic node createList(int []arr, int n, node start){ // Declare newNode and temporary pointer node newNode,temp; int i; // Iterate the loop until array length for(i = 0; i < n; i++) { // Create new node newNode = getNode(); // Assign the array data newNode.data = arr[i]; // If it is first element // Put that node prev and next as start // as it is circular if(i == 0) { start = newNode; newNode.prev = start; newNode.next = start; } else { // Find the last node temp = (start).prev; // Add the last node to make them // in circular fashion temp.next = newNode; newNode.next = start; newNode.prev = temp; temp = start; temp.prev = newNode; } } return start;} // Driver Codepublic static void Main(String []args){ // Array to be converted int []arr = {1,2,3,4,5}; int n = arr.Length; // Start Pointer node start = null; // Create the List start = createList(arr, n, start); // Display the list displayList(start);}} // This code contributed by Rajput-Ji <script> // JavaScript program to convert array to// circular doubly linked list // Doubly linked list nodeclass node{ constructor() { this.data=0; this.next=this.prev=null; }} // Utility function to create a node in memoryfunction getNode(){ return new node();} // Function to display the listfunction displayList(temp){ let t = temp; if(temp == null) return 0; else { document.write("The list is: "); while(temp.next != t) { document.write(temp.data+" "); temp = temp.next; } document.write(temp.data); return 1; }} // Function to convert array into listfunction createList(arr,n,start){ // Declare newNode and temporary pointer let newNode,temp; let i; // Iterate the loop until array length for(i = 0; i < n; i++) { // Create new node newNode = getNode(); // Assign the array data newNode.data = arr[i]; // If it is first element // Put that node prev and next as start // as it is circular if(i == 0) { start = newNode; newNode.prev = start; newNode.next = start; } else { // Find the last node temp = (start).prev; // Add the last node to make them // in circular fashion temp.next = newNode; newNode.next = start; newNode.prev = temp; temp = start; temp.prev = newNode; } } return start;} // Driver Codelet arr=[1,2,3,4,5];let n = arr.length;// Start Pointerlet start = null; // Create the Liststart = createList(arr, n, start); // Display the listdisplayList(start); // This code is contributed by avanitrachhadiya2155 </script> The list is: 1 2 3 4 5 andrew1234 Rajput-Ji avanitrachhadiya2155 Arrays circular linked list doubly linked list Linked Lists Advanced Data Structure Arrays circular linked list Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Ordered Set and GNU C++ PBDS 2-3 Trees | (Search, Insert and Deletion) Extendible Hashing (Dynamic approach to DBMS) Suffix Array | Set 1 (Introduction) Difference between Backtracking and Branch-N-Bound technique Quad Tree Advantages of Trie Data Structure Implement a Phone Directory String hashing using Polynomial rolling hash function
[ { "code": null, "e": 25732, "s": 25704, "text": "\n09 Jul, 2021" }, { "code": null, "e": 25934, "s": 25732, "text": "Prerequisite: Doubly Linked list, Circular Linked List, Circular Doubly Linked ListGiven an array of N elements. The task is to write a program to convert the array into a circular doubly linked list. " }, { "code": null, "e": 26095, "s": 25936, "text": "The idea is to start traversing the array and for every array element create a new list node and assign the prev and next pointers of this node accordingly. " }, { "code": null, "e": 26203, "s": 26095, "text": "Create a pointer start to point to the starting of the list which will initially point to NULL(Empty list)." }, { "code": null, "e": 26364, "s": 26203, "text": "For the first element of the array, create a new node and put that node’s prev and next pointers to point to start to maintain the circular fashion of the list." }, { "code": null, "e": 26477, "s": 26364, "text": "For the rest of the array elements, insert those elements to the end of the created circular doubly linked list." }, { "code": null, "e": 26522, "s": 26477, "text": "Below is the implementation of above idea: " }, { "code": null, "e": 26526, "s": 26522, "text": "C++" }, { "code": null, "e": 26531, "s": 26526, "text": "Java" }, { "code": null, "e": 26539, "s": 26531, "text": "Python3" }, { "code": null, "e": 26542, "s": 26539, "text": "C#" }, { "code": null, "e": 26553, "s": 26542, "text": "Javascript" }, { "code": "// CPP program to convert array to// circular doubly linked list #include<bits/stdc++.h>using namespace std; // Doubly linked list nodestruct node{ int data; struct node *next; struct node *prev;}; // Utility function to create a node in memorystruct node* getNode(){ return ((struct node *)malloc(sizeof(struct node)));} // Function to display the listint displayList(struct node *temp){ struct node *t = temp; if(temp == NULL) return 0; else { cout<<\"The list is: \"; while(temp->next != t) { cout<<temp->data<<\" \"; temp = temp->next; } cout<<temp->data; return 1; }} // Function to convert array into listvoid createList(int arr[], int n, struct node **start){ // Declare newNode and temporary pointer struct node *newNode,*temp; int i; // Iterate the loop until array length for(i=0;i<n;i++) { // Create new node newNode = getNode(); // Assign the array data newNode->data = arr[i]; // If it is first element // Put that node prev and next as start // as it is circular if(i==0) { *start = newNode; newNode->prev = *start; newNode->next = *start; } else { // Find the last node temp = (*start)->prev; // Add the last node to make them // in circular fashion temp->next = newNode; newNode->next = *start; newNode->prev = temp; temp = *start; temp->prev = newNode; } }} // Driver Codeint main(){ // Array to be converted int arr[] = {1,2,3,4,5}; int n = sizeof(arr) / sizeof(arr[0]); // Start Pointer struct node *start = NULL; // Create the List createList(arr, n, &start); // Display the list displayList(start); return 0;}", "e": 28539, "s": 26553, "text": null }, { "code": "// Java program to convert array to// circular doubly linked listclass GFG{ // Doubly linked list nodestatic class node{ int data; node next; node prev;}; // Utility function to create a node in memorystatic node getNode(){ return new node();} // Function to display the liststatic int displayList( node temp){ node t = temp; if(temp == null) return 0; else { System.out.print(\"The list is: \"); while(temp.next != t) { System.out.print(temp.data+\" \"); temp = temp.next; } System.out.print(temp.data); return 1; }} // Function to convert array into liststatic node createList(int arr[], int n, node start){ // Declare newNode and temporary pointer node newNode,temp; int i; // Iterate the loop until array length for(i = 0; i < n; i++) { // Create new node newNode = getNode(); // Assign the array data newNode.data = arr[i]; // If it is first element // Put that node prev and next as start // as it is circular if(i == 0) { start = newNode; newNode.prev = start; newNode.next = start; } else { // Find the last node temp = (start).prev; // Add the last node to make them // in circular fashion temp.next = newNode; newNode.next = start; newNode.prev = temp; temp = start; temp.prev = newNode; } } return start;} // Driver Codepublic static void main(String args[]){ // Array to be converted int arr[] = {1,2,3,4,5}; int n = arr.length; // Start Pointer node start = null; // Create the List start = createList(arr, n, start); // Display the list displayList(start);}} // This code is contributed by Arnab Kundu", "e": 30505, "s": 28539, "text": null }, { "code": "# Python3 program to convert array to# circular doubly linked list # Node of the doubly linked listclass Node: def __init__(self, data): self.data = data self.prev = None self.next = None # Utility function to create a node in memorydef getNode(): return (Node(0)) # Function to display the listdef displayList(temp): t = temp if(temp == None): return 0 else: print(\"The list is: \", end = \" \") while(temp.next != t): print(temp.data, end = \" \") temp = temp.next print(temp.data) return 1 # Function to convert array into listdef createList(arr, n, start): # Declare newNode and temporary pointer newNode = None temp = None i = 0 # Iterate the loop until array length while(i < n): # Create new node newNode = getNode() # Assign the array data newNode.data = arr[i] # If it is first element # Put that node prev and next as start # as it is circular if(i == 0): start = newNode newNode.prev = start newNode.next = start else: # Find the last node temp = (start).prev # Add the last node to make them # in circular fashion temp.next = newNode newNode.next = start newNode.prev = temp temp = start temp.prev = newNode i = i + 1 return start # Driver Codeif __name__ == \"__main__\": # Array to be converted arr = [1, 2, 3, 4, 5] n = len(arr) # Start Pointer start = None # Create the List start = createList(arr, n, start) # Display the list displayList(start) # This code is contributed by Arnab Kundu", "e": 32395, "s": 30505, "text": null }, { "code": "// C# program to convert array to// circular doubly linked listusing System; class GFG{ // Doubly linked list nodepublic class node{ public int data; public node next; public node prev;}; // Utility function to create a node in memorystatic node getNode(){ return new node();} // Function to display the liststatic int displayList( node temp){ node t = temp; if(temp == null) return 0; else { Console.Write(\"The list is: \"); while(temp.next != t) { Console.Write(temp.data + \" \"); temp = temp.next; } Console.Write(temp.data); return 1; }} // Function to convert array into liststatic node createList(int []arr, int n, node start){ // Declare newNode and temporary pointer node newNode,temp; int i; // Iterate the loop until array length for(i = 0; i < n; i++) { // Create new node newNode = getNode(); // Assign the array data newNode.data = arr[i]; // If it is first element // Put that node prev and next as start // as it is circular if(i == 0) { start = newNode; newNode.prev = start; newNode.next = start; } else { // Find the last node temp = (start).prev; // Add the last node to make them // in circular fashion temp.next = newNode; newNode.next = start; newNode.prev = temp; temp = start; temp.prev = newNode; } } return start;} // Driver Codepublic static void Main(String []args){ // Array to be converted int []arr = {1,2,3,4,5}; int n = arr.Length; // Start Pointer node start = null; // Create the List start = createList(arr, n, start); // Display the list displayList(start);}} // This code contributed by Rajput-Ji", "e": 34405, "s": 32395, "text": null }, { "code": "<script> // JavaScript program to convert array to// circular doubly linked list // Doubly linked list nodeclass node{ constructor() { this.data=0; this.next=this.prev=null; }} // Utility function to create a node in memoryfunction getNode(){ return new node();} // Function to display the listfunction displayList(temp){ let t = temp; if(temp == null) return 0; else { document.write(\"The list is: \"); while(temp.next != t) { document.write(temp.data+\" \"); temp = temp.next; } document.write(temp.data); return 1; }} // Function to convert array into listfunction createList(arr,n,start){ // Declare newNode and temporary pointer let newNode,temp; let i; // Iterate the loop until array length for(i = 0; i < n; i++) { // Create new node newNode = getNode(); // Assign the array data newNode.data = arr[i]; // If it is first element // Put that node prev and next as start // as it is circular if(i == 0) { start = newNode; newNode.prev = start; newNode.next = start; } else { // Find the last node temp = (start).prev; // Add the last node to make them // in circular fashion temp.next = newNode; newNode.next = start; newNode.prev = temp; temp = start; temp.prev = newNode; } } return start;} // Driver Codelet arr=[1,2,3,4,5];let n = arr.length;// Start Pointerlet start = null; // Create the Liststart = createList(arr, n, start); // Display the listdisplayList(start); // This code is contributed by avanitrachhadiya2155 </script>", "e": 36279, "s": 34405, "text": null }, { "code": null, "e": 36302, "s": 36279, "text": "The list is: 1 2 3 4 5" }, { "code": null, "e": 36315, "s": 36304, "text": "andrew1234" }, { "code": null, "e": 36325, "s": 36315, "text": "Rajput-Ji" }, { "code": null, "e": 36346, "s": 36325, "text": "avanitrachhadiya2155" }, { "code": null, "e": 36353, "s": 36346, "text": "Arrays" }, { "code": null, "e": 36374, "s": 36353, "text": "circular linked list" }, { "code": null, "e": 36393, "s": 36374, "text": "doubly linked list" }, { "code": null, "e": 36406, "s": 36393, "text": "Linked Lists" }, { "code": null, "e": 36430, "s": 36406, "text": "Advanced Data Structure" }, { "code": null, "e": 36437, "s": 36430, "text": "Arrays" }, { "code": null, "e": 36458, "s": 36437, "text": "circular linked list" }, { "code": null, "e": 36556, "s": 36458, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 36585, "s": 36556, "text": "Ordered Set and GNU C++ PBDS" }, { "code": null, "e": 36627, "s": 36585, "text": "2-3 Trees | (Search, Insert and Deletion)" }, { "code": null, "e": 36673, "s": 36627, "text": "Extendible Hashing (Dynamic approach to DBMS)" }, { "code": null, "e": 36709, "s": 36673, "text": "Suffix Array | Set 1 (Introduction)" }, { "code": null, "e": 36770, "s": 36709, "text": "Difference between Backtracking and Branch-N-Bound technique" }, { "code": null, "e": 36780, "s": 36770, "text": "Quad Tree" }, { "code": null, "e": 36814, "s": 36780, "text": "Advantages of Trie Data Structure" }, { "code": null, "e": 36842, "s": 36814, "text": "Implement a Phone Directory" } ]
C# - Different Ways to Find All Substrings in a String - GeeksforGeeks
21 Oct, 2021 Given a string as an input we need to find all the substrings present in the given string. Example: Input: geeks Output: g e e k s ge ee ek ks gee eek eks geek eeks geeks Input: ab Output: a b ab Method 1: Using Substring() method We can find all the substrings from the given string using the Substring() method. This method returns a substring from the current string. It contains two parameters where the first parameter represents the starting position of the substring which has to be retrieved and the second parameter will represent the length of the substring. Here if the first parameter is equal to the length of the string then this method will return nothing. Syntax: str.Substring(strindex, strlen) where strindex is the starting index of the substring and strlen is the length of the substring. Approach To display Read the string from the user. Write the find_substrings() function to get substrings. In find_substrings() function call Substring() method to get the substrings. for(i = 1; i <= input_string.Length; i++) { for (j = 0; j <= input_string.Length - i; j++) { // Use Substring function Console.WriteLine(input_string.Substring(j, i)); } } Now show the retrieved substrings. Example: C# // C# program to display all Substrings// present in the given String using System; class GFG{ // Function to get the substringsstatic void find_substrings(string input_string){ int j = 0; int i = 0; for(i = 1; i <= input_string.Length; i++) { for(j = 0; j <= input_string.Length - i; j++) { // Using Substring() function Console.WriteLine(input_string.Substring(j, i)); } }} // Driver codepublic static void Main(){ // Declare the main string string input_string; Console.Write("Enter String : "); Console.Write("\n"); // Read the string input_string = Console.ReadLine(); // Call the function find_substrings(input_string);}} Output: Enter String : GFG G F G GF FG GFG Method 2: Using for loop We can also find substring from the given string using nested for loop. Here the outer for loop is used to select starting character, mid for loop is used to considers all characters on the right of the selected starting character as the ending character of the substring, and the inner for loop is used to print characters from the starting to the ending point. Example: C# // C# program to display all Substrings// present in the given String using System; class GFG{ // Function to print all substrings// from the given stringstatic void find_Substring(string inputstr, int n){ // Choose starting point for(int l = 1; l <= n; l++) { // Choose ending point for(int i = 0; i <= n - l; i++) { // Display the substrings int q = i + l - 1; for(int j = i; j <= q; j++) Console.Write(inputstr[j]); Console.WriteLine(); } }} // Driver codestatic public void Main (){ string inputstr = "Geeks"; // Calling function find_Substring(inputstr, inputstr.Length);}} Output: G e e k s Ge ee ek ks Gee eek eks Geek eeks Geeks CSharp-Strings-Programs Picked C# Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Extension Method in C# HashSet in C# with Examples Partial Classes in C# Top 50 C# Interview Questions & Answers C# | How to insert an element in an Array? C# | List Class C# | Inheritance Lambda Expressions in C# Linked List Implementation in C# Convert String to Character Array in C#
[ { "code": null, "e": 24222, "s": 24194, "text": "\n21 Oct, 2021" }, { "code": null, "e": 24314, "s": 24222, "text": "Given a string as an input we need to find all the substrings present in the given string. " }, { "code": null, "e": 24323, "s": 24314, "text": "Example:" }, { "code": null, "e": 24420, "s": 24323, "text": "Input:\ngeeks\nOutput:\ng\ne\ne\nk\ns\nge\nee\nek\nks\ngee\neek\neks\ngeek\neeks\ngeeks\n\nInput:\nab\nOutput:\na\nb\nab" }, { "code": null, "e": 24455, "s": 24420, "text": "Method 1: Using Substring() method" }, { "code": null, "e": 24896, "s": 24455, "text": "We can find all the substrings from the given string using the Substring() method. This method returns a substring from the current string. It contains two parameters where the first parameter represents the starting position of the substring which has to be retrieved and the second parameter will represent the length of the substring. Here if the first parameter is equal to the length of the string then this method will return nothing." }, { "code": null, "e": 24904, "s": 24896, "text": "Syntax:" }, { "code": null, "e": 24936, "s": 24904, "text": "str.Substring(strindex, strlen)" }, { "code": null, "e": 25033, "s": 24936, "text": "where strindex is the starting index of the substring and strlen is the length of the substring." }, { "code": null, "e": 25042, "s": 25033, "text": "Approach" }, { "code": null, "e": 25054, "s": 25042, "text": "To display " }, { "code": null, "e": 25085, "s": 25054, "text": "Read the string from the user." }, { "code": null, "e": 25141, "s": 25085, "text": "Write the find_substrings() function to get substrings." }, { "code": null, "e": 25218, "s": 25141, "text": "In find_substrings() function call Substring() method to get the substrings." }, { "code": null, "e": 25420, "s": 25218, "text": "for(i = 1; i <= input_string.Length; i++)\n{\n for (j = 0; j <= input_string.Length - i; j++)\n { \n // Use Substring function\n Console.WriteLine(input_string.Substring(j, i));\n }\n}" }, { "code": null, "e": 25455, "s": 25420, "text": "Now show the retrieved substrings." }, { "code": null, "e": 25464, "s": 25455, "text": "Example:" }, { "code": null, "e": 25467, "s": 25464, "text": "C#" }, { "code": "// C# program to display all Substrings// present in the given String using System; class GFG{ // Function to get the substringsstatic void find_substrings(string input_string){ int j = 0; int i = 0; for(i = 1; i <= input_string.Length; i++) { for(j = 0; j <= input_string.Length - i; j++) { // Using Substring() function Console.WriteLine(input_string.Substring(j, i)); } }} // Driver codepublic static void Main(){ // Declare the main string string input_string; Console.Write(\"Enter String : \"); Console.Write(\"\\n\"); // Read the string input_string = Console.ReadLine(); // Call the function find_substrings(input_string);}}", "e": 26218, "s": 25467, "text": null }, { "code": null, "e": 26226, "s": 26218, "text": "Output:" }, { "code": null, "e": 26261, "s": 26226, "text": "Enter String :\nGFG\nG\nF\nG\nGF\nFG\nGFG" }, { "code": null, "e": 26286, "s": 26261, "text": "Method 2: Using for loop" }, { "code": null, "e": 26650, "s": 26286, "text": "We can also find substring from the given string using nested for loop. Here the outer for loop is used to select starting character, mid for loop is used to considers all characters on the right of the selected starting character as the ending character of the substring, and the inner for loop is used to print characters from the starting to the ending point. " }, { "code": null, "e": 26659, "s": 26650, "text": "Example:" }, { "code": null, "e": 26662, "s": 26659, "text": "C#" }, { "code": "// C# program to display all Substrings// present in the given String using System; class GFG{ // Function to print all substrings// from the given stringstatic void find_Substring(string inputstr, int n){ // Choose starting point for(int l = 1; l <= n; l++) { // Choose ending point for(int i = 0; i <= n - l; i++) { // Display the substrings int q = i + l - 1; for(int j = i; j <= q; j++) Console.Write(inputstr[j]); Console.WriteLine(); } }} // Driver codestatic public void Main (){ string inputstr = \"Geeks\"; // Calling function find_Substring(inputstr, inputstr.Length);}}", "e": 27414, "s": 26662, "text": null }, { "code": null, "e": 27422, "s": 27414, "text": "Output:" }, { "code": null, "e": 27472, "s": 27422, "text": "G\ne\ne\nk\ns\nGe\nee\nek\nks\nGee\neek\neks\nGeek\neeks\nGeeks" }, { "code": null, "e": 27496, "s": 27472, "text": "CSharp-Strings-Programs" }, { "code": null, "e": 27503, "s": 27496, "text": "Picked" }, { "code": null, "e": 27506, "s": 27503, "text": "C#" }, { "code": null, "e": 27604, "s": 27506, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 27613, "s": 27604, "text": "Comments" }, { "code": null, "e": 27626, "s": 27613, "text": "Old Comments" }, { "code": null, "e": 27649, "s": 27626, "text": "Extension Method in C#" }, { "code": null, "e": 27677, "s": 27649, "text": "HashSet in C# with Examples" }, { "code": null, "e": 27699, "s": 27677, "text": "Partial Classes in C#" }, { "code": null, "e": 27739, "s": 27699, "text": "Top 50 C# Interview Questions & Answers" }, { "code": null, "e": 27782, "s": 27739, "text": "C# | How to insert an element in an Array?" }, { "code": null, "e": 27798, "s": 27782, "text": "C# | List Class" }, { "code": null, "e": 27815, "s": 27798, "text": "C# | Inheritance" }, { "code": null, "e": 27840, "s": 27815, "text": "Lambda Expressions in C#" }, { "code": null, "e": 27873, "s": 27840, "text": "Linked List Implementation in C#" } ]
How to secure database passwords in PHP? - GeeksforGeeks
24 Oct, 2021 Most of the websites are providing sing up and login facility to the user. User has to create a password and use it for login to the website. But it is very important to secure the password of the user. password_hash() function provides the facility to securely store the password of the user to the database. Syntax password_hash(Password, PASSWORD_DEFAULT) Example: First parameter Password will contain the normal password. The second Parameter will contain PASSWORD_BCRYPT to make secure otherwise it contains PASSWORD_DEFAULT as default. Let’s see the example to understand properly. dbconn.php php <?php $db_host = "localhost"; $db_name = "secure_pass"; $db_pass = ""; $db_user = "root"; $conn = mysqli_connect($db_host, $db_user, $db_pass, $db_name); if (!$conn){ die ('Failed to connect with server'); } ?> Signup Form: html <form action="index.php" method="POST"> <label for="username">Username</label> <input type="text" name="username" required><br><br> <label for="password">Password</label> <input type="password" name="password" required><br><br> <input type="submit" name="submit" value="submit"> </form> index.php php <?php //Include database connection file include 'dbconn.php'; if (isset($_POST['submit'])){ $username = $_POST['username']; // Normal Password $pass = $_POST['password']; // Securing password using password_hash $secure_pass = password_hash($pass, PASSWORD_BCRYPT); $sql = "INSERT INTO login_tb (u_username, u_password) VALUES('$username', '$secure_pass')"; $result = mysqli_query($conn, $sql); } // Include HTML sign up form include 'signup_form.php';?> Output:Password In Database. saurabh1990aror PHP-Misc Picked PHP Web Technologies Web technologies Questions Write From Home PHP Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments How to fetch data from localserver database and display on HTML table using PHP ? How to create admin login page using PHP? How to generate PDF file using PHP ? Different ways for passing data to view in Laravel How to Install php-curl in Ubuntu ? Roadmap to Become a Web Developer in 2022 Installation of Node.js on Linux Top 10 Projects For Beginners To Practice HTML and CSS Skills How to fetch data from an API in ReactJS ? How to insert spaces/tabs in text using HTML/CSS?
[ { "code": null, "e": 24892, "s": 24864, "text": "\n24 Oct, 2021" }, { "code": null, "e": 25202, "s": 24892, "text": "Most of the websites are providing sing up and login facility to the user. User has to create a password and use it for login to the website. But it is very important to secure the password of the user. password_hash() function provides the facility to securely store the password of the user to the database." }, { "code": null, "e": 25211, "s": 25202, "text": "Syntax " }, { "code": null, "e": 25253, "s": 25211, "text": "password_hash(Password, PASSWORD_DEFAULT)" }, { "code": null, "e": 25485, "s": 25253, "text": "Example: First parameter Password will contain the normal password. The second Parameter will contain PASSWORD_BCRYPT to make secure otherwise it contains PASSWORD_DEFAULT as default. Let’s see the example to understand properly. " }, { "code": null, "e": 25498, "s": 25485, "text": "dbconn.php " }, { "code": null, "e": 25502, "s": 25498, "text": "php" }, { "code": "<?php $db_host = \"localhost\"; $db_name = \"secure_pass\"; $db_pass = \"\"; $db_user = \"root\"; $conn = mysqli_connect($db_host, $db_user, $db_pass, $db_name); if (!$conn){ die ('Failed to connect with server'); } ?>", "e": 25728, "s": 25502, "text": null }, { "code": null, "e": 25743, "s": 25728, "text": "Signup Form: " }, { "code": null, "e": 25748, "s": 25743, "text": "html" }, { "code": "<form action=\"index.php\" method=\"POST\"> <label for=\"username\">Username</label> <input type=\"text\" name=\"username\" required><br><br> <label for=\"password\">Password</label> <input type=\"password\" name=\"password\" required><br><br> <input type=\"submit\" name=\"submit\" value=\"submit\"> </form>", "e": 26043, "s": 25748, "text": null }, { "code": null, "e": 26055, "s": 26043, "text": "index.php " }, { "code": null, "e": 26059, "s": 26055, "text": "php" }, { "code": "<?php //Include database connection file include 'dbconn.php'; if (isset($_POST['submit'])){ $username = $_POST['username']; // Normal Password $pass = $_POST['password']; // Securing password using password_hash $secure_pass = password_hash($pass, PASSWORD_BCRYPT); $sql = \"INSERT INTO login_tb (u_username, u_password) VALUES('$username', '$secure_pass')\"; $result = mysqli_query($conn, $sql); } // Include HTML sign up form include 'signup_form.php';?>", "e": 26552, "s": 26059, "text": null }, { "code": null, "e": 26583, "s": 26552, "text": "Output:Password In Database. " }, { "code": null, "e": 26601, "s": 26585, "text": "saurabh1990aror" }, { "code": null, "e": 26610, "s": 26601, "text": "PHP-Misc" }, { "code": null, "e": 26617, "s": 26610, "text": "Picked" }, { "code": null, "e": 26621, "s": 26617, "text": "PHP" }, { "code": null, "e": 26638, "s": 26621, "text": "Web Technologies" }, { "code": null, "e": 26665, "s": 26638, "text": "Web technologies Questions" }, { "code": null, "e": 26681, "s": 26665, "text": "Write From Home" }, { "code": null, "e": 26685, "s": 26681, "text": "PHP" }, { "code": null, "e": 26783, "s": 26685, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 26792, "s": 26783, "text": "Comments" }, { "code": null, "e": 26805, "s": 26792, "text": "Old Comments" }, { "code": null, "e": 26887, "s": 26805, "text": "How to fetch data from localserver database and display on HTML table using PHP ?" }, { "code": null, "e": 26929, "s": 26887, "text": "How to create admin login page using PHP?" }, { "code": null, "e": 26966, "s": 26929, "text": "How to generate PDF file using PHP ?" }, { "code": null, "e": 27017, "s": 26966, "text": "Different ways for passing data to view in Laravel" }, { "code": null, "e": 27053, "s": 27017, "text": "How to Install php-curl in Ubuntu ?" }, { "code": null, "e": 27095, "s": 27053, "text": "Roadmap to Become a Web Developer in 2022" }, { "code": null, "e": 27128, "s": 27095, "text": "Installation of Node.js on Linux" }, { "code": null, "e": 27190, "s": 27128, "text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills" }, { "code": null, "e": 27233, "s": 27190, "text": "How to fetch data from an API in ReactJS ?" } ]
MySQL Tryit Editor v1.0
SELECT MID("SQL Tutorial", 5, 3) AS ExtractString; ​ Edit the SQL Statement, and click "Run SQL" to see the result. This SQL-Statement is not supported in the WebSQL Database. The example still works, because it uses a modified version of SQL. Your browser does not support WebSQL. Your are now using a light-version of the Try-SQL Editor, with a read-only Database. If you switch to a browser with WebSQL support, you can try any SQL statement, and play with the Database as much as you like. The Database can also be restored at any time. Our Try-SQL Editor uses WebSQL to demonstrate SQL. A Database-object is created in your browser, for testing purposes. You can try any SQL statement, and play with the Database as much as you like. The Database can be restored at any time, simply by clicking the "Restore Database" button. WebSQL stores a Database locally, on the user's computer. Each user gets their own Database object. WebSQL is supported in Chrome, Safari, and Opera. If you use another browser you will still be able to use our Try SQL Editor, but a different version, using a server-based ASP application, with a read-only Access Database, where users are not allowed to make any changes to the data.
[ { "code": null, "e": 51, "s": 0, "text": "SELECT MID(\"SQL Tutorial\", 5, 3) AS ExtractString;" }, { "code": null, "e": 53, "s": 51, "text": "​" }, { "code": null, "e": 125, "s": 62, "text": "Edit the SQL Statement, and click \"Run SQL\" to see the result." }, { "code": null, "e": 185, "s": 125, "text": "This SQL-Statement is not supported in the WebSQL Database." }, { "code": null, "e": 253, "s": 185, "text": "The example still works, because it uses a modified version of SQL." }, { "code": null, "e": 291, "s": 253, "text": "Your browser does not support WebSQL." }, { "code": null, "e": 376, "s": 291, "text": "Your are now using a light-version of the Try-SQL Editor, with a read-only Database." }, { "code": null, "e": 550, "s": 376, "text": "If you switch to a browser with WebSQL support, you can try any SQL statement, and play with the Database as much as you like. The Database can also be restored at any time." }, { "code": null, "e": 601, "s": 550, "text": "Our Try-SQL Editor uses WebSQL to demonstrate SQL." }, { "code": null, "e": 669, "s": 601, "text": "A Database-object is created in your browser, for testing purposes." }, { "code": null, "e": 840, "s": 669, "text": "You can try any SQL statement, and play with the Database as much as you like. The Database can be restored at any time, simply by clicking the \"Restore Database\" button." }, { "code": null, "e": 940, "s": 840, "text": "WebSQL stores a Database locally, on the user's computer. Each user gets their own Database object." }, { "code": null, "e": 990, "s": 940, "text": "WebSQL is supported in Chrome, Safari, and Opera." } ]
Data Structure - Bubble Sort Algorithm
Bubble sort is a simple sorting algorithm. This sorting algorithm is comparison-based algorithm in which each pair of adjacent elements is compared and the elements are swapped if they are not in order. This algorithm is not suitable for large data sets as its average and worst case complexity are of Ο(n2) where n is the number of items. We take an unsorted array for our example. Bubble sort takes Ο(n2) time so we're keeping it short and precise. Bubble sort starts with very first two elements, comparing them to check which one is greater. In this case, value 33 is greater than 14, so it is already in sorted locations. Next, we compare 33 with 27. We find that 27 is smaller than 33 and these two values must be swapped. The new array should look like this − Next we compare 33 and 35. We find that both are in already sorted positions. Then we move to the next two values, 35 and 10. We know then that 10 is smaller 35. Hence they are not sorted. We swap these values. We find that we have reached the end of the array. After one iteration, the array should look like this − To be precise, we are now showing how an array should look like after each iteration. After the second iteration, it should look like this − Notice that after each iteration, at least one value moves at the end. And when there's no swap required, bubble sorts learns that an array is completely sorted. Now we should look into some practical aspects of bubble sort. We assume list is an array of n elements. We further assume that swap function swaps the values of the given array elements. begin BubbleSort(list) for all elements of list if list[i] > list[i+1] swap(list[i], list[i+1]) end if end for return list end BubbleSort We observe in algorithm that Bubble Sort compares each pair of array element unless the whole array is completely sorted in an ascending order. This may cause a few complexity issues like what if the array needs no more swapping as all the elements are already ascending. To ease-out the issue, we use one flag variable swapped which will help us see if any swap has happened or not. If no swap has occurred, i.e. the array requires no more processing to be sorted, it will come out of the loop. Pseudocode of BubbleSort algorithm can be written as follows − procedure bubbleSort( list : array of items ) loop = list.count; for i = 0 to loop-1 do: swapped = false for j = 0 to loop-1 do: /* compare the adjacent elements */ if list[j] > list[j+1] then /* swap them */ swap( list[j], list[j+1] ) swapped = true end if end for /*if no number was swapped that means array is sorted now, break the loop.*/ if(not swapped) then break end if end for end procedure return list One more issue we did not address in our original algorithm and its improvised pseudocode, is that, after every iteration the highest values settles down at the end of the array. Hence, the next iteration need not include already sorted elements. For this purpose, in our implementation, we restrict the inner loop to avoid already sorted values. To know about bubble sort implementation in C programming language, please click here. 42 Lectures 1.5 hours Ravi Kiran 141 Lectures 13 hours Arnab Chakraborty 26 Lectures 8.5 hours Parth Panjabi 65 Lectures 6 hours Arnab Chakraborty 75 Lectures 13 hours Eduonix Learning Solutions 64 Lectures 10.5 hours Eduonix Learning Solutions Print Add Notes Bookmark this page
[ { "code": null, "e": 2920, "s": 2580, "text": "Bubble sort is a simple sorting algorithm. This sorting algorithm is comparison-based algorithm in which each pair of adjacent elements is compared and the elements are swapped if they are not in order. This algorithm is not suitable for large data sets as its average and worst case complexity are of Ο(n2) where n is the number of items." }, { "code": null, "e": 3031, "s": 2920, "text": "We take an unsorted array for our example. Bubble sort takes Ο(n2) time so we're keeping it short and precise." }, { "code": null, "e": 3126, "s": 3031, "text": "Bubble sort starts with very first two elements, comparing them to check which one is greater." }, { "code": null, "e": 3236, "s": 3126, "text": "In this case, value 33 is greater than 14, so it is already in sorted locations. Next, we compare 33 with 27." }, { "code": null, "e": 3309, "s": 3236, "text": "We find that 27 is smaller than 33 and these two values must be swapped." }, { "code": null, "e": 3347, "s": 3309, "text": "The new array should look like this −" }, { "code": null, "e": 3425, "s": 3347, "text": "Next we compare 33 and 35. We find that both are in already sorted positions." }, { "code": null, "e": 3473, "s": 3425, "text": "Then we move to the next two values, 35 and 10." }, { "code": null, "e": 3536, "s": 3473, "text": "We know then that 10 is smaller 35. Hence they are not sorted." }, { "code": null, "e": 3664, "s": 3536, "text": "We swap these values. We find that we have reached the end of the array. After one iteration, the array should look like this −" }, { "code": null, "e": 3805, "s": 3664, "text": "To be precise, we are now showing how an array should look like after each iteration. After the second iteration, it should look like this −" }, { "code": null, "e": 3876, "s": 3805, "text": "Notice that after each iteration, at least one value moves at the end." }, { "code": null, "e": 3967, "s": 3876, "text": "And when there's no swap required, bubble sorts learns that an array is completely sorted." }, { "code": null, "e": 4030, "s": 3967, "text": "Now we should look into some practical aspects of bubble sort." }, { "code": null, "e": 4155, "s": 4030, "text": "We assume list is an array of n elements. We further assume that swap function swaps the values of the given array elements." }, { "code": null, "e": 4332, "s": 4155, "text": "begin BubbleSort(list)\n\n for all elements of list\n if list[i] > list[i+1]\n swap(list[i], list[i+1])\n end if\n end for\n \n return list\n \nend BubbleSort" }, { "code": null, "e": 4604, "s": 4332, "text": "We observe in algorithm that Bubble Sort compares each pair of array element unless the whole array is completely sorted in an ascending order. This may cause a few complexity issues like what if the array needs no more swapping as all the elements are already ascending." }, { "code": null, "e": 4828, "s": 4604, "text": "To ease-out the issue, we use one flag variable swapped which will help us see if any swap has happened or not. If no swap has occurred, i.e. the array requires no more processing to be sorted, it will come out of the loop." }, { "code": null, "e": 4891, "s": 4828, "text": "Pseudocode of BubbleSort algorithm can be written as follows −" }, { "code": null, "e": 5482, "s": 4891, "text": "procedure bubbleSort( list : array of items )\n\n loop = list.count;\n \n for i = 0 to loop-1 do:\n swapped = false\n\t\t\n for j = 0 to loop-1 do:\n \n /* compare the adjacent elements */ \n if list[j] > list[j+1] then\n /* swap them */\n swap( list[j], list[j+1] )\t\t \n swapped = true\n end if\n \n end for\n \n /*if no number was swapped that means \n array is sorted now, break the loop.*/\n \n if(not swapped) then\n break\n end if\n \n end for\n \nend procedure return list" }, { "code": null, "e": 5829, "s": 5482, "text": "One more issue we did not address in our original algorithm and its improvised pseudocode, is that, after every iteration the highest values settles down at the end of the array. Hence, the next iteration need not include already sorted elements. For this purpose, in our implementation, we restrict the inner loop to avoid already sorted values." }, { "code": null, "e": 5916, "s": 5829, "text": "To know about bubble sort implementation in C programming language, please click here." }, { "code": null, "e": 5951, "s": 5916, "text": "\n 42 Lectures \n 1.5 hours \n" }, { "code": null, "e": 5963, "s": 5951, "text": " Ravi Kiran" }, { "code": null, "e": 5998, "s": 5963, "text": "\n 141 Lectures \n 13 hours \n" }, { "code": null, "e": 6017, "s": 5998, "text": " Arnab Chakraborty" }, { "code": null, "e": 6052, "s": 6017, "text": "\n 26 Lectures \n 8.5 hours \n" }, { "code": null, "e": 6067, "s": 6052, "text": " Parth Panjabi" }, { "code": null, "e": 6100, "s": 6067, "text": "\n 65 Lectures \n 6 hours \n" }, { "code": null, "e": 6119, "s": 6100, "text": " Arnab Chakraborty" }, { "code": null, "e": 6153, "s": 6119, "text": "\n 75 Lectures \n 13 hours \n" }, { "code": null, "e": 6181, "s": 6153, "text": " Eduonix Learning Solutions" }, { "code": null, "e": 6217, "s": 6181, "text": "\n 64 Lectures \n 10.5 hours \n" }, { "code": null, "e": 6245, "s": 6217, "text": " Eduonix Learning Solutions" }, { "code": null, "e": 6252, "s": 6245, "text": " Print" }, { "code": null, "e": 6263, "s": 6252, "text": " Add Notes" } ]
C++ Interview Questions
Dear readers, these C++ Interview Questions have been designed specially to get you acquainted with the nature of questions you may encounter during your interview for the subject of C++. As per my experience good interviewers hardly plan to ask any particular question during your interview, normally questions start with some basic concept of the subject and later they continue based on further discussion and what you answer − Object Oriented Programming System. Class is a blue print which reflects the entities attributes and actions. Technically defining a class is designing an user defined data type. An instance of the class is called as object. Single, Multilevel, Multiple, Hierarchical and Hybrid. If a class member is protected then it is accessible in the inherited class. However, outside the both the private and protected members are not accessible. The process of binding the data and the functions acting on the data together in an entity (class) called as encapsulation. Abstraction refers to hiding the internal implementation and exhibiting only the necessary details. Inheritance is the process of acquiring the properties of the exiting class into the new class. The existing class is called as base/parent class and the inherited class is called as derived/child class. Declaring a variable volatile directs the compiler that the variable can be changed externally. Hence avoiding compiler optimization on the variable reference. A function prefixed with the keyword inline before the function definition is called as inline function. The inline functions are faster in execution when compared to normal functions as the compiler treats inline functions as macros. Storage class specifies the life or scope of symbols such as variable or functions. The following are storage classes supported in C++ auto, static, extern, register and mutable A constant class object’s member variable can be altered by declaring it using mutable storage class specifier. Applicable only for non-static and non-constant member variable of the class. Shallow copy does memory dumping bit-by-bit from one object to another. Deep copy is copy field by field from object to another. Deep copy is achieved using copy constructor and or overloading assignment operator. A virtual function with no function body and assigned with a value zero is called as pure virtual function. A class with at least one pure virtual function is called as abstract class. We cannot instantiate an abstract class. A reference variable is an alias name for the existing variable. Which mean both the variable name and reference variable point to the same memory location. Therefore updation on the original variable can be achieved using reference variable too. A static variable does exit though the objects for the respective class are not created. Static member variable share a common memory across all the objects created for the respective class. A static member variable can be referred using the class name itself. A static member function can be invoked using the class name as it exits before class objects comes into existence. It can access only static members of the class. wchar_t Dot (.) and Arrow ( -> ) No, Defining a class/structure is just a type definition and will not allocated memory for the same. bool, is the new primitive data type introduced in C++ language. Defining several functions with the same name with unique list of parameters is called as function overloading. Defining a new job for the existing operator w.r.t the class objects is called as operator overloading. No, it’s a class from STL (Standard template library). cin, cout, cerr and clog. Private & Protected. Scope resolution operator (::) A destructor is the member function of the class which is having the same name as the class name and prefixed with tilde (~) symbol. It gets executed automatically w.r.t the object as soon as the object loses its scope. It cannot be overloaded and the only form is without the parameters. A constructor is the member function of the class which is having the same as the class name and gets executed automatically as soon as the object for the respective class is created. Every class does have a constructor provided by the compiler if the programmer doesn’t provides one and known as default constructor. A programmer provided constructor with no parameters is called as default constructor. In such case compiler doesn’t provides the constructor. ‘new’ is the operator can be used for the same. ‘delete’ operator is used to release the dynamic memory which was created using ‘new’ operator. Yes, as C is the subset of C++, we can all the functions of C in C++ too. No, we need to use free() of C language for the same. A function which is not a member of the class but still can access all the member of the class is called so. To make it happen we need to declare within the required class following the keyword ‘friend’. A copy constructor is the constructor which take same class object reference as the parameter. It gets automatically invoked as soon as the object is initialized with another object of the same class at the time of its creation. C++ does supports exception handling. try, catch & throw are keyword used for the same. This, is the pointer variable of the compiler which always holds the current active object’s address. By default the members of struct are public and by default the members of the class are private. Yes. A variable whose scope is applicable only within a block is said so. Also a variable in C++ can be declared anywhere within the block. If the file already exists, its content will be truncated before opening the file. The scope resolution operator is used to Resolve the scope of global variables. To associate function definition to a class if the function is defined outside the class. A namespace is the logical division of the code which can be used to resolve the name conflict of the identifiers by placing them under different name space. The arguments/parameters which are sent to the main() function while executing from the command line/console are called so. All the arguments sent are the strings only. A template class is a generic class. The keyword template can be used to define a class template. The catch block with ellipses as follows catch(...) { } By default every local variable of the function is automatic (auto). In the below function both the variables ‘i’ and ‘j’ are automatic variables. void f() { int i; auto int j; } NOTE − A global variable can’t be an automatic variable. A static local variables retains its value between the function call and the default value is 0. The following function will print 1 2 3 if called thrice. void f() { static int i; ++i; printf(“%d “,i); } If a global variable is static then its visibility is limited to the same source code. Used to resolve the scope of global symbol #include <iostream> using namespace std; main() { extern int i; cout<<i<<endl; } int i = 20; The starting address of the array is called as the base address of the array. If a variable is used most frequently then it should be declared using register storage specifier, then possibly the compiler gives CPU register for its storage to speed up the look up of the variable. Yes, it can be but cannot be executed, as the execution requires main() function definition. Every local variable by default being an auto variable is stored in stack memory A class containing at least one member variable of another class type in it is called so. A C++ program consists of various tokens and a token is either a keyword, an identifier, a constant, a string literal, or a symbol. Preprocessor is a directive to the compiler to perform certain things before the actual compilation process begins. The arguments which we pass to the main() function while executing the program are called as command line arguments. The parameters are always strings held in the second argument (below in args) of the function which is array of character pointers. First argument represents the count of arguments (below in count) and updated automatically by operating system. main( int count, char *args[]) { } Call by value − We send only values to the function as parameters. We choose this if we do not want the actual parameters to be modified with formal parameters but just used. Call by value − We send only values to the function as parameters. We choose this if we do not want the actual parameters to be modified with formal parameters but just used. Call by address − We send address of the actual parameters instead of values. We choose this if we do want the actual parameters to be modified with formal parameters. Call by address − We send address of the actual parameters instead of values. We choose this if we do want the actual parameters to be modified with formal parameters. Call by reference − The actual parameters are received with the C++ new reference variables as formal parameters. We choose this if we do want the actual parameters to be modified with formal parameters. Call by reference − The actual parameters are received with the C++ new reference variables as formal parameters. We choose this if we do want the actual parameters to be modified with formal parameters. Error, It is invalid that either of the operands for the modulus operator (%) is a real number. Opiton –lm to be used as > g++ –lm <file.cpp> No, there is no such provision available. Bjarne Stroustrup. sizeof We can apply scope resolution operator (::) to the for the scope of global variable. The only two permitted operations on pointers are Comparision ii) Addition/Substraction (excluding void pointers) Comparision ii) Addition/Substraction (excluding void pointers) Function calling itself is called as recursion. Program name. Ideally it is 32 characters and also implementation dependent. By default the functions are called by value. Public, private & protected Delete[] is used to release the array allocated memory which was allocated using new[] and delete is used to release one chunk of memory which was allocated using new. Not necessarily, a class having at least one pure virtual function is abstract class too. No, it will be error as the compiler fails to do conversion. The program shall quit abruptly. No, exceptions can be handled whereas program cannot resolve errors. Defining the functions within the base and derived class with the same signature and name where the base class’s function is virtual. seekg() seekp() No, only the class member variables determines the size of the respective class object. We can create an empty class and the object size will be 1. Default namespace defined by C++. Standard template library cout is the object of ostream class. The stream ‘cout’ is by default connected to console output device. cin is the object of istream class. The stream ‘cin’ is by default connected to console input device. It is used to specify the namespace being used in. Arrow (->) operator can be used for the same If a header file is included with in < > then the compiler searches for the particular header file only with in the built in include path. If a header file is included with in “ “, then the compiler searches for the particular header file first in the current working directory, if not found then in the built in include path S++, as it is single machine instruction (INC) internally. The parameters sent to the function at calling end are called as actual parameters while at the receiving of the function definition called as formal parameters. Declaration associates type to the variable whereas definition gives the value to the variable. goto. No, it contains invalid octal digits. It will be used to undefine an existing macro definition. No, we cannot. A virtual destructor ensures that the objects resources are released in the reverse order of the object being constructed w.r.t inherited object. The objects are destroyed in the reverse order of their creation. A class members can gain accessibility over other class member by placing the class declaration prefixed with the keyword ‘friend’ in the destination class. Further you can go through your past assignments you have done with the subject and make sure you are able to speak confidently on them. If you are fresher then interviewer does not expect you will answer very complex questions, rather you have to make your basics concepts very strong. Second it really doesn't matter much if you could not answer few questions but it matters that whatever you answered, you must have answered with confidence. So just feel confident during your interview. We at tutorialspoint wish you best luck to have a good interviewer and all the very best for your future endeavor. Cheers :-) 154 Lectures 11.5 hours Arnab Chakraborty 14 Lectures 57 mins Kaushik Roy Chowdhury 30 Lectures 12.5 hours Frahaan Hussain 54 Lectures 3.5 hours Frahaan Hussain 77 Lectures 5.5 hours Frahaan Hussain 12 Lectures 3.5 hours Frahaan Hussain Print Add Notes Bookmark this page
[ { "code": null, "e": 2749, "s": 2318, "text": "Dear readers, these C++ Interview Questions have been designed specially to get you acquainted with the nature of questions you may encounter during your interview for the subject of C++. As per my experience good interviewers hardly plan to ask any particular question during your interview, normally questions start with some basic concept of the subject and later they continue based on further discussion and what you answer −" }, { "code": null, "e": 2785, "s": 2749, "text": "Object Oriented Programming System." }, { "code": null, "e": 2928, "s": 2785, "text": "Class is a blue print which reflects the entities attributes and actions. Technically defining a class is designing an user defined data type." }, { "code": null, "e": 2974, "s": 2928, "text": "An instance of the class is called as object." }, { "code": null, "e": 3029, "s": 2974, "text": "Single, Multilevel, Multiple, Hierarchical and Hybrid." }, { "code": null, "e": 3186, "s": 3029, "text": "If a class member is protected then it is accessible in the inherited class. However, outside the both the private and protected members are not accessible." }, { "code": null, "e": 3310, "s": 3186, "text": "The process of binding the data and the functions acting on the data together in an entity (class) called as encapsulation." }, { "code": null, "e": 3410, "s": 3310, "text": "Abstraction refers to hiding the internal implementation and exhibiting only the necessary details." }, { "code": null, "e": 3614, "s": 3410, "text": "Inheritance is the process of acquiring the properties of the exiting class into the new class. The existing class is called as base/parent class and the inherited class is called as derived/child class." }, { "code": null, "e": 3774, "s": 3614, "text": "Declaring a variable volatile directs the compiler that the variable can be changed externally. Hence avoiding compiler optimization on the variable reference." }, { "code": null, "e": 4009, "s": 3774, "text": "A function prefixed with the keyword inline before the function definition is called as inline function. The inline functions are faster in execution when compared to normal functions as the compiler treats inline functions as macros." }, { "code": null, "e": 4093, "s": 4009, "text": "Storage class specifies the life or scope of symbols such as variable or functions." }, { "code": null, "e": 4144, "s": 4093, "text": "The following are storage classes supported in C++" }, { "code": null, "e": 4187, "s": 4144, "text": "auto, static, extern, register and mutable" }, { "code": null, "e": 4377, "s": 4187, "text": "A constant class object’s member variable can be altered by declaring it using mutable storage class specifier. Applicable only for non-static and non-constant member variable of the class." }, { "code": null, "e": 4591, "s": 4377, "text": "Shallow copy does memory dumping bit-by-bit from one object to another. Deep copy is copy field by field from object to another. Deep copy is achieved using copy constructor and or overloading assignment operator." }, { "code": null, "e": 4699, "s": 4591, "text": "A virtual function with no function body and assigned with a value zero is called as pure virtual function." }, { "code": null, "e": 4817, "s": 4699, "text": "A class with at least one pure virtual function is called as abstract class. We cannot instantiate an abstract class." }, { "code": null, "e": 5064, "s": 4817, "text": "A reference variable is an alias name for the existing variable. Which mean both the variable name and reference variable point to the same memory location. Therefore updation on the original variable can be achieved using reference variable too." }, { "code": null, "e": 5325, "s": 5064, "text": "A static variable does exit though the objects for the respective class are not created. Static member variable share a common memory across all the objects created for the respective class. A static member variable can be referred using the class name itself." }, { "code": null, "e": 5489, "s": 5325, "text": "A static member function can be invoked using the class name as it exits before class objects comes into existence. It can access only static members of the class." }, { "code": null, "e": 5497, "s": 5489, "text": "wchar_t" }, { "code": null, "e": 5522, "s": 5497, "text": "Dot (.) and Arrow ( -> )" }, { "code": null, "e": 5623, "s": 5522, "text": "No, Defining a class/structure is just a type definition and will not allocated memory for the same." }, { "code": null, "e": 5688, "s": 5623, "text": "bool, is the new primitive data type introduced in C++ language." }, { "code": null, "e": 5800, "s": 5688, "text": "Defining several functions with the same name with unique list of parameters is called as function overloading." }, { "code": null, "e": 5904, "s": 5800, "text": "Defining a new job for the existing operator w.r.t the class objects is called as operator overloading." }, { "code": null, "e": 5959, "s": 5904, "text": "No, it’s a class from STL (Standard template library)." }, { "code": null, "e": 5985, "s": 5959, "text": "cin, cout, cerr and clog." }, { "code": null, "e": 6006, "s": 5985, "text": "Private & Protected." }, { "code": null, "e": 6037, "s": 6006, "text": "Scope resolution operator (::)" }, { "code": null, "e": 6326, "s": 6037, "text": "A destructor is the member function of the class which is having the same name as the class name and prefixed with tilde (~) symbol. It gets executed automatically w.r.t the object as soon as the object loses its scope. It cannot be overloaded and the only form is without the parameters." }, { "code": null, "e": 6510, "s": 6326, "text": "A constructor is the member function of the class which is having the same as the class name and gets executed automatically as soon as the object for the respective class is created." }, { "code": null, "e": 6787, "s": 6510, "text": "Every class does have a constructor provided by the compiler if the programmer doesn’t provides one and known as default constructor. A programmer provided constructor with no parameters is called as default constructor. In such case compiler doesn’t provides the constructor." }, { "code": null, "e": 6835, "s": 6787, "text": "‘new’ is the operator can be used for the same." }, { "code": null, "e": 6931, "s": 6835, "text": "‘delete’ operator is used to release the dynamic memory which was created using ‘new’ operator." }, { "code": null, "e": 7005, "s": 6931, "text": "Yes, as C is the subset of C++, we can all the functions of C in C++ too." }, { "code": null, "e": 7059, "s": 7005, "text": "No, we need to use free() of C language for the same." }, { "code": null, "e": 7263, "s": 7059, "text": "A function which is not a member of the class but still can access all the member of the class is called so. To make it happen we need to declare within the required class following the keyword ‘friend’." }, { "code": null, "e": 7492, "s": 7263, "text": "A copy constructor is the constructor which take same class object reference as the parameter. It gets automatically invoked as soon as the object is initialized with another object of the same class at the time of its creation." }, { "code": null, "e": 7580, "s": 7492, "text": "C++ does supports exception handling. try, catch & throw are keyword used for the same." }, { "code": null, "e": 7682, "s": 7580, "text": "This, is the pointer variable of the compiler which always holds the current active object’s address." }, { "code": null, "e": 7779, "s": 7682, "text": "By default the members of struct are public and by default the members of the class are private." }, { "code": null, "e": 7784, "s": 7779, "text": "Yes." }, { "code": null, "e": 7919, "s": 7784, "text": "A variable whose scope is applicable only within a block is said so. Also a variable in C++ can be declared anywhere within the block." }, { "code": null, "e": 8002, "s": 7919, "text": "If the file already exists, its content will be truncated before opening the file." }, { "code": null, "e": 8043, "s": 8002, "text": "The scope resolution operator is used to" }, { "code": null, "e": 8082, "s": 8043, "text": "Resolve the scope of global variables." }, { "code": null, "e": 8172, "s": 8082, "text": "To associate function definition to a class if the function is defined outside the class." }, { "code": null, "e": 8330, "s": 8172, "text": "A namespace is the logical division of the code which can be used to resolve the name conflict of the identifiers by placing them under different name space." }, { "code": null, "e": 8499, "s": 8330, "text": "The arguments/parameters which are sent to the main() function while executing from the command line/console are called so. All the arguments sent are the strings only." }, { "code": null, "e": 8597, "s": 8499, "text": "A template class is a generic class. The keyword template can be used to define a class template." }, { "code": null, "e": 8638, "s": 8597, "text": "The catch block with ellipses as follows" }, { "code": null, "e": 8654, "s": 8638, "text": "catch(...) \n{\n}" }, { "code": null, "e": 8801, "s": 8654, "text": "By default every local variable of the function is automatic (auto). In the below function both the variables ‘i’ and ‘j’ are automatic variables." }, { "code": null, "e": 8843, "s": 8801, "text": "void f() \n{\n int i;\n \n auto int j;\n}" }, { "code": null, "e": 8900, "s": 8843, "text": "NOTE − A global variable can’t be an automatic variable." }, { "code": null, "e": 9055, "s": 8900, "text": "A static local variables retains its value between the function call and the default value is 0. The following function will print 1 2 3 if called thrice." }, { "code": null, "e": 9122, "s": 9055, "text": "void f() \n{ \n static int i; \n \n ++i; \n printf(“%d “,i); \n}" }, { "code": null, "e": 9209, "s": 9122, "text": "If a global variable is static then its visibility is limited to the same source code." }, { "code": null, "e": 9252, "s": 9209, "text": "Used to resolve the scope of global symbol" }, { "code": null, "e": 9360, "s": 9252, "text": "#include <iostream>\n\nusing namespace std;\t\nmain() {\n extern int i;\n \n cout<<i<<endl;\n}\nint i = 20;" }, { "code": null, "e": 9438, "s": 9360, "text": "The starting address of the array is called as the base address of the array." }, { "code": null, "e": 9640, "s": 9438, "text": "If a variable is used most frequently then it should be declared using register storage specifier, then possibly the compiler gives CPU register for its storage to speed up the look up of the variable." }, { "code": null, "e": 9733, "s": 9640, "text": "Yes, it can be but cannot be executed, as the execution requires main() function definition." }, { "code": null, "e": 9814, "s": 9733, "text": "Every local variable by default being an auto variable is stored in stack memory" }, { "code": null, "e": 9904, "s": 9814, "text": "A class containing at least one member variable of another class type in it is called so." }, { "code": null, "e": 10036, "s": 9904, "text": "A C++ program consists of various tokens and a token is either a keyword, an identifier, a constant, a string literal, or a symbol." }, { "code": null, "e": 10152, "s": 10036, "text": "Preprocessor is a directive to the compiler to perform certain things before the actual compilation process begins." }, { "code": null, "e": 10514, "s": 10152, "text": "The arguments which we pass to the main() function while executing the program are called as command line arguments. The parameters are always strings held in the second argument (below in args) of the function which is array of character pointers. First argument represents the count of arguments (below in count) and updated automatically by operating system." }, { "code": null, "e": 10549, "s": 10514, "text": "main( int count, char *args[]) {\n}" }, { "code": null, "e": 10724, "s": 10549, "text": "Call by value − We send only values to the function as parameters. We choose this if we do not want the actual parameters to be modified with formal parameters but just used." }, { "code": null, "e": 10899, "s": 10724, "text": "Call by value − We send only values to the function as parameters. We choose this if we do not want the actual parameters to be modified with formal parameters but just used." }, { "code": null, "e": 11067, "s": 10899, "text": "Call by address − We send address of the actual parameters instead of values. We choose this if we do want the actual parameters to be modified with formal parameters." }, { "code": null, "e": 11235, "s": 11067, "text": "Call by address − We send address of the actual parameters instead of values. We choose this if we do want the actual parameters to be modified with formal parameters." }, { "code": null, "e": 11439, "s": 11235, "text": "Call by reference − The actual parameters are received with the C++ new reference variables as formal parameters. We choose this if we do want the actual parameters to be modified with formal parameters." }, { "code": null, "e": 11643, "s": 11439, "text": "Call by reference − The actual parameters are received with the C++ new reference variables as formal parameters. We choose this if we do want the actual parameters to be modified with formal parameters." }, { "code": null, "e": 11739, "s": 11643, "text": "Error, It is invalid that either of the operands for the modulus operator (%) is a real number." }, { "code": null, "e": 11786, "s": 11739, "text": "Opiton –lm to be used as > g++ –lm <file.cpp>" }, { "code": null, "e": 11828, "s": 11786, "text": "No, there is no such provision available." }, { "code": null, "e": 11847, "s": 11828, "text": "Bjarne Stroustrup." }, { "code": null, "e": 11854, "s": 11847, "text": "sizeof" }, { "code": null, "e": 11939, "s": 11854, "text": "We can apply scope resolution operator (::) to the for the scope of global variable." }, { "code": null, "e": 11990, "s": 11939, "text": "The only two permitted operations on pointers are " }, { "code": null, "e": 12054, "s": 11990, "text": "Comparision ii) Addition/Substraction (excluding void pointers)" }, { "code": null, "e": 12118, "s": 12054, "text": "Comparision ii) Addition/Substraction (excluding void pointers)" }, { "code": null, "e": 12166, "s": 12118, "text": "Function calling itself is called as recursion." }, { "code": null, "e": 12180, "s": 12166, "text": "Program name." }, { "code": null, "e": 12243, "s": 12180, "text": "Ideally it is 32 characters and also implementation dependent." }, { "code": null, "e": 12289, "s": 12243, "text": "By default the functions are called by value." }, { "code": null, "e": 12317, "s": 12289, "text": "Public, private & protected" }, { "code": null, "e": 12485, "s": 12317, "text": "Delete[] is used to release the array allocated memory which was allocated using new[] and delete is used to release one chunk of memory which was allocated using new." }, { "code": null, "e": 12575, "s": 12485, "text": "Not necessarily, a class having at least one pure virtual function is abstract class too." }, { "code": null, "e": 12636, "s": 12575, "text": "No, it will be error as the compiler fails to do conversion." }, { "code": null, "e": 12669, "s": 12636, "text": "The program shall quit abruptly." }, { "code": null, "e": 12738, "s": 12669, "text": "No, exceptions can be handled whereas program cannot resolve errors." }, { "code": null, "e": 12872, "s": 12738, "text": "Defining the functions within the base and derived class with the same signature and name where the base class’s function is virtual." }, { "code": null, "e": 12880, "s": 12872, "text": "seekg()" }, { "code": null, "e": 12888, "s": 12880, "text": "seekp()" }, { "code": null, "e": 12976, "s": 12888, "text": "No, only the class member variables determines the size of the respective class object." }, { "code": null, "e": 13036, "s": 12976, "text": "We can create an empty class and the object size will be 1." }, { "code": null, "e": 13070, "s": 13036, "text": "Default namespace defined by C++." }, { "code": null, "e": 13096, "s": 13070, "text": "Standard template library" }, { "code": null, "e": 13201, "s": 13096, "text": "cout is the object of ostream class. The stream ‘cout’ is by default connected to console output device." }, { "code": null, "e": 13303, "s": 13201, "text": "cin is the object of istream class. The stream ‘cin’ is by default connected to console input device." }, { "code": null, "e": 13354, "s": 13303, "text": "It is used to specify the namespace being used in." }, { "code": null, "e": 13399, "s": 13354, "text": "Arrow (->) operator can be used for the same" }, { "code": null, "e": 13725, "s": 13399, "text": "If a header file is included with in < > then the compiler searches for the particular header file only with in the built in include path. If a header file is included with in “ “, then the compiler searches for the particular header file first in the current working directory, if not found then in the built in include path" }, { "code": null, "e": 13784, "s": 13725, "text": "S++, as it is single machine instruction (INC) internally." }, { "code": null, "e": 13946, "s": 13784, "text": "The parameters sent to the function at calling end are called as actual parameters while at the receiving of the function definition called as formal parameters." }, { "code": null, "e": 14042, "s": 13946, "text": "Declaration associates type to the variable whereas definition gives the value to the variable." }, { "code": null, "e": 14048, "s": 14042, "text": "goto." }, { "code": null, "e": 14086, "s": 14048, "text": "No, it contains invalid octal digits." }, { "code": null, "e": 14144, "s": 14086, "text": "It will be used to undefine an existing macro definition." }, { "code": null, "e": 14159, "s": 14144, "text": "No, we cannot." }, { "code": null, "e": 14305, "s": 14159, "text": "A virtual destructor ensures that the objects resources are released in the reverse order of the object being constructed w.r.t inherited object." }, { "code": null, "e": 14371, "s": 14305, "text": "The objects are destroyed in the reverse order of their creation." }, { "code": null, "e": 14528, "s": 14371, "text": "A class members can gain accessibility over other class member by placing the class declaration prefixed with the keyword ‘friend’ in the destination class." }, { "code": null, "e": 14815, "s": 14528, "text": "Further you can go through your past assignments you have done with the subject and make sure you are able to speak confidently on them. If you are fresher then interviewer does not expect you will answer very complex questions, rather you have to make your basics concepts very strong." }, { "code": null, "e": 15145, "s": 14815, "text": "Second it really doesn't matter much if you could not answer few questions but it matters that whatever you answered, you must have answered with confidence. So just feel confident during your interview. We at tutorialspoint wish you best luck to have a good interviewer and all the very best for your future endeavor. Cheers :-)" }, { "code": null, "e": 15182, "s": 15145, "text": "\n 154 Lectures \n 11.5 hours \n" }, { "code": null, "e": 15201, "s": 15182, "text": " Arnab Chakraborty" }, { "code": null, "e": 15233, "s": 15201, "text": "\n 14 Lectures \n 57 mins\n" }, { "code": null, "e": 15256, "s": 15233, "text": " Kaushik Roy Chowdhury" }, { "code": null, "e": 15292, "s": 15256, "text": "\n 30 Lectures \n 12.5 hours \n" }, { "code": null, "e": 15309, "s": 15292, "text": " Frahaan Hussain" }, { "code": null, "e": 15344, "s": 15309, "text": "\n 54 Lectures \n 3.5 hours \n" }, { "code": null, "e": 15361, "s": 15344, "text": " Frahaan Hussain" }, { "code": null, "e": 15396, "s": 15361, "text": "\n 77 Lectures \n 5.5 hours \n" }, { "code": null, "e": 15413, "s": 15396, "text": " Frahaan Hussain" }, { "code": null, "e": 15448, "s": 15413, "text": "\n 12 Lectures \n 3.5 hours \n" }, { "code": null, "e": 15465, "s": 15448, "text": " Frahaan Hussain" }, { "code": null, "e": 15472, "s": 15465, "text": " Print" }, { "code": null, "e": 15483, "s": 15472, "text": " Add Notes" } ]
How can we call one constructor from another in the same class in C#?
Make use of this keyword in c# to call one constructor from another constructor To call a constructor which is present in parent class make use of base keyword class Demo{ public Demo(){ System.Console.WriteLine("Parameter less constructor called"); } public Demo(int firstNumber, int secondNumber) : this(){ System.Console.WriteLine($"{firstNumber} {secondNumber}"); } public Demo(int firstNumber, int secondNumber, int thirdNumber) : this(firstNumber, secondNumber){ System.Console.WriteLine($"{firstNumber} {secondNumber} {thirdNumber}"); } } class Program{ static void Main(){ Demo obj = new Demo(1, 2, 3); Console.ReadLine(); } } Parameter less constructor called 1 2 1 2 3 To call a constructor which is present in another class make use of base keyword class DemoBase{ public DemoBase(int firstNumber, int secondNumber, int thirdNumber){ System.Console.WriteLine("Base class Constructor"); System.Console.WriteLine($"{firstNumber} {secondNumber} {thirdNumber}"); } } class Demo : DemoBase{ public Demo(int firstNumber, int secondNumber, int thirdNumber) : base(firstNumber, secondNumber, thirdNumber){ System.Console.WriteLine("Derived class Constructor"); System.Console.WriteLine($"{firstNumber} {secondNumber} {thirdNumber}"); } } class Program{ static void Main(){ Demo obj = new Demo(1, 2, 3); Console.ReadLine(); } } Base class Constructor 1 2 3 Derived class Constructor 1 2 3
[ { "code": null, "e": 1142, "s": 1062, "text": "Make use of this keyword in c# to call one constructor from another constructor" }, { "code": null, "e": 1222, "s": 1142, "text": "To call a constructor which is present in parent class make use of base keyword" }, { "code": null, "e": 1751, "s": 1222, "text": "class Demo{\n public Demo(){\n System.Console.WriteLine(\"Parameter less constructor called\");\n }\n public Demo(int firstNumber, int secondNumber) : this(){\n System.Console.WriteLine($\"{firstNumber} {secondNumber}\");\n }\n public Demo(int firstNumber, int secondNumber, int thirdNumber) : this(firstNumber, secondNumber){\n System.Console.WriteLine($\"{firstNumber} {secondNumber} {thirdNumber}\");\n }\n}\nclass Program{\n static void Main(){\n Demo obj = new Demo(1, 2, 3);\n Console.ReadLine();\n }\n}" }, { "code": null, "e": 1795, "s": 1751, "text": "Parameter less constructor called\n1 2\n1 2 3" }, { "code": null, "e": 1876, "s": 1795, "text": "To call a constructor which is present in another class make use of base keyword" }, { "code": null, "e": 2500, "s": 1876, "text": "class DemoBase{\n public DemoBase(int firstNumber, int secondNumber, int thirdNumber){\n System.Console.WriteLine(\"Base class Constructor\");\n System.Console.WriteLine($\"{firstNumber} {secondNumber} {thirdNumber}\");\n }\n}\nclass Demo : DemoBase{\n public Demo(int firstNumber, int secondNumber, int thirdNumber) : base(firstNumber, secondNumber, thirdNumber){\n System.Console.WriteLine(\"Derived class Constructor\");\n System.Console.WriteLine($\"{firstNumber} {secondNumber} {thirdNumber}\");\n }\n}\nclass Program{\n static void Main(){\n Demo obj = new Demo(1, 2, 3);\n Console.ReadLine();\n }\n}" }, { "code": null, "e": 2561, "s": 2500, "text": "Base class Constructor\n1 2 3\nDerived class Constructor\n1 2 3" } ]
Isoweekday() Method Of Datetime Class In Python - GeeksforGeeks
14 Aug, 2021 Isoweekday() is a method of the DateTime class that tells the day of the given date. It returns an integer that corresponds to a particular day. Syntax: datetime.isoweekday() Parameters: None Return Value: It returns an integer which corresponds to a day as per the table Example 1: Print the day of the current date. Python3 # importing the datetime moduleimport datetime # Creating an dictionary with the return# value as keys and the day as the value# This is used to retrieve the day of the# week using the return value of the# isoweekday() functionweekdays = {1: "Monday", 2: "Tuesday", 3: "Wednesday", 4: "Thursday", 5: "Friday", 6: "Saturday", 7: "Sunday"} # Getting current date using today()# function of the datetime classtodays_date = datetime.date.today()print("Today's date is :", todays_date) # Using the isoweekday() function to# retrieve the day of the given dateday = todays_date.isoweekday()print("The date", todays_date, "falls on", weekdays[day]) Output: Today's date is : 2021-07-27 The date 2021-07-27 falls on Tuesday Example 2: Get the day of the week for today’s date from 2010 to the current year Python3 # importing the datetime moduleimport datetime # Creating an dictionary with the return# value as keys and the day as the value# This is used to retrieve the day of the# week using the return value of the# isoweekday() functionweekdays = {1: "Monday", 2: "Tuesday", 3: "Wednesday", 4: "Thursday", 5: "Friday", 6: "Saturday", 7: "Sunday"} # Getting current year using today() function# of the datetime class and the year attributeToday = datetime.date.today()current_year = Today.year for i in range(2010, current_year+1): # Printing the day of the year # by first creating an datetime object # for the starting day of the year and # then we use isoweekday # to get the value and we use the # weekdays to retrieve the day of the year print("The {}/{} in the year {} has fallen on {}".\ format(Today.month, Today.day, i, weekdays[datetime.date(i, Today.month, Today.day).isoweekday()])) Output: The 7/28 in the year 2010 has fallen on Wednesday The 7/28 in the year 2011 has fallen on Thursday The 7/28 in the year 2012 has fallen on Saturday The 7/28 in the year 2013 has fallen on Sunday The 7/28 in the year 2014 has fallen on Monday The 7/28 in the year 2015 has fallen on Tuesday The 7/28 in the year 2016 has fallen on Thursday The 7/28 in the year 2017 has fallen on Friday The 7/28 in the year 2018 has fallen on Saturday The 7/28 in the year 2019 has fallen on Sunday The 7/28 in the year 2020 has fallen on Tuesday The 7/28 in the year 2021 has fallen on Wednesday anikakapoor as5853535 Picked Python-datetime Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments How to Install PIP on Windows ? Selecting rows in pandas DataFrame based on conditions How to drop one or multiple columns in Pandas Dataframe Python | Get unique values from a list Check if element exists in list in Python How To Convert Python Dictionary To JSON? Defaultdict in Python Python | os.path.join() method Create a directory in Python Bar Plot in Matplotlib
[ { "code": null, "e": 24212, "s": 24184, "text": "\n14 Aug, 2021" }, { "code": null, "e": 24357, "s": 24212, "text": "Isoweekday() is a method of the DateTime class that tells the day of the given date. It returns an integer that corresponds to a particular day." }, { "code": null, "e": 24387, "s": 24357, "text": "Syntax: datetime.isoweekday()" }, { "code": null, "e": 24404, "s": 24387, "text": "Parameters: None" }, { "code": null, "e": 24484, "s": 24404, "text": "Return Value: It returns an integer which corresponds to a day as per the table" }, { "code": null, "e": 24530, "s": 24484, "text": "Example 1: Print the day of the current date." }, { "code": null, "e": 24538, "s": 24530, "text": "Python3" }, { "code": "# importing the datetime moduleimport datetime # Creating an dictionary with the return# value as keys and the day as the value# This is used to retrieve the day of the# week using the return value of the# isoweekday() functionweekdays = {1: \"Monday\", 2: \"Tuesday\", 3: \"Wednesday\", 4: \"Thursday\", 5: \"Friday\", 6: \"Saturday\", 7: \"Sunday\"} # Getting current date using today()# function of the datetime classtodays_date = datetime.date.today()print(\"Today's date is :\", todays_date) # Using the isoweekday() function to# retrieve the day of the given dateday = todays_date.isoweekday()print(\"The date\", todays_date, \"falls on\", weekdays[day])", "e": 25250, "s": 24538, "text": null }, { "code": null, "e": 25258, "s": 25250, "text": "Output:" }, { "code": null, "e": 25324, "s": 25258, "text": "Today's date is : 2021-07-27\nThe date 2021-07-27 falls on Tuesday" }, { "code": null, "e": 25406, "s": 25324, "text": "Example 2: Get the day of the week for today’s date from 2010 to the current year" }, { "code": null, "e": 25414, "s": 25406, "text": "Python3" }, { "code": "# importing the datetime moduleimport datetime # Creating an dictionary with the return# value as keys and the day as the value# This is used to retrieve the day of the# week using the return value of the# isoweekday() functionweekdays = {1: \"Monday\", 2: \"Tuesday\", 3: \"Wednesday\", 4: \"Thursday\", 5: \"Friday\", 6: \"Saturday\", 7: \"Sunday\"} # Getting current year using today() function# of the datetime class and the year attributeToday = datetime.date.today()current_year = Today.year for i in range(2010, current_year+1): # Printing the day of the year # by first creating an datetime object # for the starting day of the year and # then we use isoweekday # to get the value and we use the # weekdays to retrieve the day of the year print(\"The {}/{} in the year {} has fallen on {}\".\\ format(Today.month, Today.day, i, weekdays[datetime.date(i, Today.month, Today.day).isoweekday()]))", "e": 26423, "s": 25414, "text": null }, { "code": null, "e": 26431, "s": 26423, "text": "Output:" }, { "code": null, "e": 26481, "s": 26431, "text": "The 7/28 in the year 2010 has fallen on Wednesday" }, { "code": null, "e": 26530, "s": 26481, "text": "The 7/28 in the year 2011 has fallen on Thursday" }, { "code": null, "e": 26579, "s": 26530, "text": "The 7/28 in the year 2012 has fallen on Saturday" }, { "code": null, "e": 26626, "s": 26579, "text": "The 7/28 in the year 2013 has fallen on Sunday" }, { "code": null, "e": 26673, "s": 26626, "text": "The 7/28 in the year 2014 has fallen on Monday" }, { "code": null, "e": 26721, "s": 26673, "text": "The 7/28 in the year 2015 has fallen on Tuesday" }, { "code": null, "e": 26770, "s": 26721, "text": "The 7/28 in the year 2016 has fallen on Thursday" }, { "code": null, "e": 26817, "s": 26770, "text": "The 7/28 in the year 2017 has fallen on Friday" }, { "code": null, "e": 26866, "s": 26817, "text": "The 7/28 in the year 2018 has fallen on Saturday" }, { "code": null, "e": 26913, "s": 26866, "text": "The 7/28 in the year 2019 has fallen on Sunday" }, { "code": null, "e": 26961, "s": 26913, "text": "The 7/28 in the year 2020 has fallen on Tuesday" }, { "code": null, "e": 27011, "s": 26961, "text": "The 7/28 in the year 2021 has fallen on Wednesday" }, { "code": null, "e": 27023, "s": 27011, "text": "anikakapoor" }, { "code": null, "e": 27033, "s": 27023, "text": "as5853535" }, { "code": null, "e": 27040, "s": 27033, "text": "Picked" }, { "code": null, "e": 27056, "s": 27040, "text": "Python-datetime" }, { "code": null, "e": 27063, "s": 27056, "text": "Python" }, { "code": null, "e": 27161, "s": 27063, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 27170, "s": 27161, "text": "Comments" }, { "code": null, "e": 27183, "s": 27170, "text": "Old Comments" }, { "code": null, "e": 27215, "s": 27183, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 27270, "s": 27215, "text": "Selecting rows in pandas DataFrame based on conditions" }, { "code": null, "e": 27326, "s": 27270, "text": "How to drop one or multiple columns in Pandas Dataframe" }, { "code": null, "e": 27365, "s": 27326, "text": "Python | Get unique values from a list" }, { "code": null, "e": 27407, "s": 27365, "text": "Check if element exists in list in Python" }, { "code": null, "e": 27449, "s": 27407, "text": "How To Convert Python Dictionary To JSON?" }, { "code": null, "e": 27471, "s": 27449, "text": "Defaultdict in Python" }, { "code": null, "e": 27502, "s": 27471, "text": "Python | os.path.join() method" }, { "code": null, "e": 27531, "s": 27502, "text": "Create a directory in Python" } ]
Java String replace() Method
❮ String Methods Return a new string where all "l" characters are replaced with "p" characters: String myStr = "Hello"; System.out.println(myStr.replace('l', 'p')); Try it Yourself » The replace() method searches a string for a specified character, and returns a new string where the specified character(s) are replaced. public String replace(char searchChar, char newChar) We just launchedW3Schools videos Get certifiedby completinga course today! If you want to report an error, or if you want to make a suggestion, do not hesitate to send us an e-mail: help@w3schools.com Your message has been sent to W3Schools.
[ { "code": null, "e": 19, "s": 0, "text": "\n❮ String Methods\n" }, { "code": null, "e": 98, "s": 19, "text": "Return a new string where all \"l\" characters are replaced with \"p\" characters:" }, { "code": null, "e": 167, "s": 98, "text": "String myStr = \"Hello\";\nSystem.out.println(myStr.replace('l', 'p'));" }, { "code": null, "e": 187, "s": 167, "text": "\nTry it Yourself »\n" }, { "code": null, "e": 326, "s": 187, "text": "The replace() method searches a string for a specified \ncharacter, and returns a new string where the specified character(s) are replaced." }, { "code": null, "e": 380, "s": 326, "text": "public String replace(char searchChar, char newChar)\n" }, { "code": null, "e": 413, "s": 380, "text": "We just launchedW3Schools videos" }, { "code": null, "e": 455, "s": 413, "text": "Get certifiedby completinga course today!" }, { "code": null, "e": 562, "s": 455, "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": 581, "s": 562, "text": "help@w3schools.com" } ]
Using FunctionTransformer and Pipeline in SkLearn to Predict Chardonnay Ratings | by Eric Kleppen | Towards Data Science
One of the best things about learning to code is the endless number of rabbit holes to fall into as you discover new concepts. An excercise I worked through on DataCamp exposed me to Pipeline in Scikit-Learn, and it blew my mind! Pipelines allow you to sequentially transform your data and implement fit(). As soon as I was done with the excercise, I started applying what I had learned and crafted a pipeline to clean the wine review dataset and predict the rating of Chardonnay. This is an in-depth review of the process I went through while creating my pipeline and predictive model. I discuss creating features, applying category encoders, constructing a pipeline and generating predictions. The complete code and a link to the github repo can be found at the bottom of the article: The data originates from the Wine Review dataset available on Kaggle. I’ve written several articles covering exploring the dataset and have already stored it in a SQLite database. The data is only partially cleaned, and it needs to be transformed so it can be used in the machine learning model. import numpy as npimport pandas as pdimport sqlite3import category_encoders as ceimport refrom sklearn.feature_selection import chi2, SelectKBestfrom sklearn.model_selection import train_test_splitfrom sklearn.feature_extraction.text import HashingVectorizerfrom sklearn.pipeline import Pipeline, FeatureUnionfrom sklearn.impute import SimpleImputerfrom sklearn import ensemblefrom sklearn.preprocessing import MaxAbsScalerfrom sklearn.preprocessing import FunctionTransformerconn = sqlite3.connect('db/wine_data.sqlite')c = conn.cursor#create Dataframedf = pd.read_sql("select country \ ,description \ ,rating \ ,price \ ,province \ ,title \ ,winery from wine_data where variety = 'Chardonnay'", conn)df.head(2) Notice how many columns contain text data. In order to use them in the machine learning model, text will have to be transformed using encoding. There are several strategies for encoding the categorical data like winery, country, province, and title, and I’ll cover them in the Category Encoders section. Before I encode them, I need to create a few features that might help the predictive model. Feature engineering can be done to extract potentially predictive qualities within the data, and add it to the dataset as a column. I have created a set of funtions that take in a dataframe and output the transformed dataframe. Using Scikit Learn’s Function Transformer, I can use the functions in the pipeline to transform the dataframe. I tried to make the functions dynamic using global variables. One of the features I want to add is the wine’s year found within the title column. The function extract_year takes in a dataframe and returns a dataframe with a year column added. def extract_year(dataframe):#set the column name containing the year using a global variable global year_column years = dataframe[year_column] #years.reset_index(inplace=False) #years.fillna("", inplace=True) l = [] i = 0 #use for loop to extract the year from each title row for year in range(len(dataframe)): temp = re.findall(r'\d+', years[i]) res = list(map(int, temp)) try: if len(str(res[0])) == 4: l.append(res[0]) elif len(str(res[0])) != 4: l.append(0) except: l.append(0) #print(res[0]) i+=1 dataframe['year'] = lreturn dataframe While exploring the dataset, I noticed wines with shorter reviews tended to have lower ratings. Because of that, I’ll add the word count of the description to the model to see if it is a predictor. I use a function that relies on a global variable named word_count_column to indicate which column of the data frame to use. It takes in a data frame and returns a data frame with a word_count column added. def word_count(dataframe): global word_count_column dataframe['word_count'] = dataframe[text].apply(lambda word: len(str(word).split(" "))) return dataframe We can see the two functions work and produce the desired data frame. After adding the two numeric features, it is time to consider encoding the categorical data in columns country, province, title, and winery. Since the machine learning model takes numbers as input, the text must be transformed. The strategy used to encode the data can have a big impact on the accuracy of the model. To easily try a variety of coding strategies, I recommend using the Category Encoder package that works with Scikit Learn. The category encoders available in the package are compatible with Pipeline since they are transformers. pip install category_encodersORconda install -c conda-forge category_encoders There are 15 or so encoders included in the package. I recommend trying these with the model pipeline to see how the different strategies impact the accuracy of the model. James-Stein Encoder Leave One Out M-estimate Ordinal Target Encoder Although they are compatible with Pipeline, I created a function so I could pass in additional logic. I pass in a data frame and two global variables to control which category and target columns are used in the transformation. # encoder = ce.JamesSteinEncoder(cols=[...]) --maybe # encoder = ce.LeaveOneOutEncoder(cols=[...]) --maybe# encoder = ce.MEstimateEncoder(cols=[...]) --maybe# encoder = ce.OrdinalEncoder(cols=[...]) --maybe# encoder = ce.TargetEncoder(cols=[...]) --maybedef category_encode(dataframe): global category_columns global category_target x = dataframe[category_columns] y = dataframe[target] ce_ord = ce.OrdinalEncoder(cols=category_columns) dataframe[category_columns] = ce_ord.fit_transform(x, y) return dataframe Notice the categorical text columns have been transformed into numeric columns. The description column can be used in the model, but it needs to go through a different transformation method. Instead, I’m going to use a function that selects the numeric columns from the data fram and ignores the description column. get_numeric_data = FunctionTransformer(lambda x: x[numeric], validate=False) Pipelines are great because they enforce order during the transformation process making the workflow compact and easy to understand. This also can make the work easier to reproduce. Remember that pipeline uses transformers, so we need to use the FunctionTransformer on our functions to make them compatible. Using FunctionTransformer, it is easy to make the functions used in the feature engineering and column selection process compatible with the pipeline. get_year = FunctionTransformer(extract_year, validate=False)get_word_count = FunctionTransformer(word_count, validate=False)get_encoded_text = FunctionTransformer(category_encode, validate=False)get_numeric_data = FunctionTransformer(lambda x: x[numeric], validate=False) Because some of functions rely on an index value, I need to make a function that resets the index so the pipeline works properly after splitting the data into train and test sets. def reset_index(dataframe): dataframe = dataframe.reset_index(inplace = False) return dataframeget_reset_index = FunctionTransformer(reset_index, validate=False) The functions I created use global variables instead of hard-coded values so they are easier to reuse. Because of this, all of the global variables need to be set: year_column = 'title'word_count_column = 'description'category_columns = ['country','province','title','winery']target = 'price'numeric= ['price', 'year', 'word_count', 'country', 'province', 'title', 'winery'] The pipeline can be used to select the model you want to use. To learn more about setting up a pipeline for model selection, I recommend checking out this Medium article by Rebecca Vickery. I am going to keep things simple and just use the Gradient Boost Regressor in Scikit Learn. #create Gradient Boosting Regressor model model = ensemble.GradientBoostingRegressor( n_estimators = 100, #how many decision trees to build learning_rate = 0.5, #controls rate at which additional decision trees influes overall prediction max_depth = 6, min_samples_split = 21, min_samples_leaf = 19, max_features = 0.9, loss = 'huber') Once the model has been selected, the global variables have been set, and all the functions have been transformed and are compatible with the pipeline, it is time to put the pieces together: pl = Pipeline(memory=None, steps=[ ('reset_index', get_reset_index), ('year', get_year), ('word_count', get_word_count), ('encode', get_encoded_text), ('selector', get_numeric_data), ('model', model) ], verbose=True) Notice I set Verbose = True. Doing this prints the step has been complete. It makes the process more transparent for debugging. To test the pipeline, use the Train Test Split to split the data and run it through the pipline: features = df.drop(['rating'], axis=1)X = featuresy = df['rating']X_train, X_test, y_train, y_test = train_test_split(X, y , test_size = .3 #, stratify=y )pl.fit(X_train, y_train)pl.score(X_test, y_test) import numpy as npimport pandas as pdimport sqlite3import category_encoders as ceimport refrom sklearn.feature_selection import chi2, SelectKBestfrom sklearn.model_selection import train_test_splitfrom sklearn.feature_extraction.text import HashingVectorizerfrom sklearn.pipeline import Pipeline, FeatureUnionfrom sklearn.impute import SimpleImputerfrom sklearn.linear_model import LogisticRegressionfrom sklearn.preprocessing import MaxAbsScalerfrom sklearn.preprocessing import FunctionTransformerconn = sqlite3.connect('db/wine_data.sqlite')c = conn.cursor#create Dataframedf = pd.read_sql("select country \ ,description \ ,rating \ ,price \ ,province \ ,title \ ,winery from wine_data where variety = 'Chardonnay'", conn)#df.head(2)def extract_year(dataframe): global year_column years = dataframe[year_column] #years.reset_index(inplace=False) #years.fillna("", inplace=True) l = [] i = 0 for year in range(len(dataframe)): temp = re.findall(r'\d+', years[i]) res = list(map(int, temp)) try: if len(str(res[0])) == 4: l.append(res[0]) elif len(str(res[0])) != 4: l.append(0) except: l.append(0) #print(res[0]) i+=1 dataframe['year'] = lreturn dataframe#df = extract_year(df)def word_count(dataframe): global word_count_column dataframe['word_count'] = dataframe[word_count_column].apply(lambda word: len(str(word).split(" "))) return dataframe# df = word_count(df)# df.head(3)# encoder = ce.JamesSteinEncoder(cols=[...]) --maybe (best score)# encoder = ce.LeaveOneOutEncoder(cols=[...]) --maybe# encoder = ce.MEstimateEncoder(cols=[...]) --maybe (good)# encoder = ce.OrdinalEncoder(cols=[...]) --maybe# encoder = ce.TargetEncoder(cols=[...]) --maybeyear_column = 'title'word_count_column = 'description'category_columns = ['country','province','title','winery']target = 'price'combine_text = ['country','province','title','winery', 'description']numeric= ['price', 'year', 'word_count','country','province','title','winery']def category_encode(dataframe): global category_columns global category_target x = dataframe[category_columns] y = dataframe[target] ce_ord = ce.OrdinalEncoder(cols=category_columns) dataframe[category_columns] = ce_ord.fit_transform(x, y) return dataframe# df = category_encode(df)# df.head()get_year = FunctionTransformer(extract_year, validate=False)get_word_count = FunctionTransformer(word_count, validate=False)get_encoded_text = FunctionTransformer(category_encode, validate=False)get_numeric_data = FunctionTransformer(lambda x: x[numeric], validate=False)def reset_index(dataframe): dataframe = dataframe.reset_index(inplace = False) return dataframeget_reset_index = FunctionTransformer(reset_index, validate=False)from sklearn import ensemble model = ensemble.GradientBoostingRegressor( n_estimators = 100, #how many decision trees to build learning_rate = 0.5, #controls rate at which additional decision trees influes overall prediction max_depth = 6, min_samples_split = 21, min_samples_leaf = 19, max_features = 0.9, loss = 'huber')pl = Pipeline(memory=None, steps=[ ('reset_index', get_reset_index), ('year', get_year), ('word_count', get_word_count), ('encode', get_encoded_text), ('selector', get_numeric_data), ('model', model) ], verbose=False)features = df.drop(['rating'], axis=1)X = featuresy = df['rating']X_train, X_test, y_train, y_test = train_test_split(X, y , test_size = .3 #, stratify=y )pl.fit(X_train, y_train)pl.score(X_test, y_test) github.com If you enjoyed this, follow me on Medium for more Get FULL ACCESS and help support my content by subscribing Let’s connect on LinkedIn Analyze Data using Python? Check out my website — Eric Kleppen
[ { "code": null, "e": 959, "s": 172, "text": "One of the best things about learning to code is the endless number of rabbit holes to fall into as you discover new concepts. An excercise I worked through on DataCamp exposed me to Pipeline in Scikit-Learn, and it blew my mind! Pipelines allow you to sequentially transform your data and implement fit(). As soon as I was done with the excercise, I started applying what I had learned and crafted a pipeline to clean the wine review dataset and predict the rating of Chardonnay. This is an in-depth review of the process I went through while creating my pipeline and predictive model. I discuss creating features, applying category encoders, constructing a pipeline and generating predictions. The complete code and a link to the github repo can be found at the bottom of the article:" }, { "code": null, "e": 1255, "s": 959, "text": "The data originates from the Wine Review dataset available on Kaggle. I’ve written several articles covering exploring the dataset and have already stored it in a SQLite database. The data is only partially cleaned, and it needs to be transformed so it can be used in the machine learning model." }, { "code": null, "e": 2105, "s": 1255, "text": "import numpy as npimport pandas as pdimport sqlite3import category_encoders as ceimport refrom sklearn.feature_selection import chi2, SelectKBestfrom sklearn.model_selection import train_test_splitfrom sklearn.feature_extraction.text import HashingVectorizerfrom sklearn.pipeline import Pipeline, FeatureUnionfrom sklearn.impute import SimpleImputerfrom sklearn import ensemblefrom sklearn.preprocessing import MaxAbsScalerfrom sklearn.preprocessing import FunctionTransformerconn = sqlite3.connect('db/wine_data.sqlite')c = conn.cursor#create Dataframedf = pd.read_sql(\"select country \\ ,description \\ ,rating \\ ,price \\ ,province \\ ,title \\ ,winery from wine_data where variety = 'Chardonnay'\", conn)df.head(2)" }, { "code": null, "e": 2148, "s": 2105, "text": "Notice how many columns contain text data." }, { "code": null, "e": 2501, "s": 2148, "text": "In order to use them in the machine learning model, text will have to be transformed using encoding. There are several strategies for encoding the categorical data like winery, country, province, and title, and I’ll cover them in the Category Encoders section. Before I encode them, I need to create a few features that might help the predictive model." }, { "code": null, "e": 2902, "s": 2501, "text": "Feature engineering can be done to extract potentially predictive qualities within the data, and add it to the dataset as a column. I have created a set of funtions that take in a dataframe and output the transformed dataframe. Using Scikit Learn’s Function Transformer, I can use the functions in the pipeline to transform the dataframe. I tried to make the functions dynamic using global variables." }, { "code": null, "e": 3083, "s": 2902, "text": "One of the features I want to add is the wine’s year found within the title column. The function extract_year takes in a dataframe and returns a dataframe with a year column added." }, { "code": null, "e": 3755, "s": 3083, "text": "def extract_year(dataframe):#set the column name containing the year using a global variable global year_column years = dataframe[year_column] #years.reset_index(inplace=False) #years.fillna(\"\", inplace=True) l = [] i = 0 #use for loop to extract the year from each title row for year in range(len(dataframe)): temp = re.findall(r'\\d+', years[i]) res = list(map(int, temp)) try: if len(str(res[0])) == 4: l.append(res[0]) elif len(str(res[0])) != 4: l.append(0) except: l.append(0) #print(res[0]) i+=1 dataframe['year'] = lreturn dataframe" }, { "code": null, "e": 4160, "s": 3755, "text": "While exploring the dataset, I noticed wines with shorter reviews tended to have lower ratings. Because of that, I’ll add the word count of the description to the model to see if it is a predictor. I use a function that relies on a global variable named word_count_column to indicate which column of the data frame to use. It takes in a data frame and returns a data frame with a word_count column added." }, { "code": null, "e": 4326, "s": 4160, "text": "def word_count(dataframe): global word_count_column dataframe['word_count'] = dataframe[text].apply(lambda word: len(str(word).split(\" \"))) return dataframe" }, { "code": null, "e": 4396, "s": 4326, "text": "We can see the two functions work and produce the desired data frame." }, { "code": null, "e": 4537, "s": 4396, "text": "After adding the two numeric features, it is time to consider encoding the categorical data in columns country, province, title, and winery." }, { "code": null, "e": 4836, "s": 4537, "text": "Since the machine learning model takes numbers as input, the text must be transformed. The strategy used to encode the data can have a big impact on the accuracy of the model. To easily try a variety of coding strategies, I recommend using the Category Encoder package that works with Scikit Learn." }, { "code": null, "e": 4941, "s": 4836, "text": "The category encoders available in the package are compatible with Pipeline since they are transformers." }, { "code": null, "e": 5019, "s": 4941, "text": "pip install category_encodersORconda install -c conda-forge category_encoders" }, { "code": null, "e": 5191, "s": 5019, "text": "There are 15 or so encoders included in the package. I recommend trying these with the model pipeline to see how the different strategies impact the accuracy of the model." }, { "code": null, "e": 5211, "s": 5191, "text": "James-Stein Encoder" }, { "code": null, "e": 5225, "s": 5211, "text": "Leave One Out" }, { "code": null, "e": 5236, "s": 5225, "text": "M-estimate" }, { "code": null, "e": 5244, "s": 5236, "text": "Ordinal" }, { "code": null, "e": 5259, "s": 5244, "text": "Target Encoder" }, { "code": null, "e": 5486, "s": 5259, "text": "Although they are compatible with Pipeline, I created a function so I could pass in additional logic. I pass in a data frame and two global variables to control which category and target columns are used in the transformation." }, { "code": null, "e": 6018, "s": 5486, "text": "# encoder = ce.JamesSteinEncoder(cols=[...]) --maybe # encoder = ce.LeaveOneOutEncoder(cols=[...]) --maybe# encoder = ce.MEstimateEncoder(cols=[...]) --maybe# encoder = ce.OrdinalEncoder(cols=[...]) --maybe# encoder = ce.TargetEncoder(cols=[...]) --maybedef category_encode(dataframe): global category_columns global category_target x = dataframe[category_columns] y = dataframe[target] ce_ord = ce.OrdinalEncoder(cols=category_columns) dataframe[category_columns] = ce_ord.fit_transform(x, y) return dataframe" }, { "code": null, "e": 6098, "s": 6018, "text": "Notice the categorical text columns have been transformed into numeric columns." }, { "code": null, "e": 6334, "s": 6098, "text": "The description column can be used in the model, but it needs to go through a different transformation method. Instead, I’m going to use a function that selects the numeric columns from the data fram and ignores the description column." }, { "code": null, "e": 6411, "s": 6334, "text": "get_numeric_data = FunctionTransformer(lambda x: x[numeric], validate=False)" }, { "code": null, "e": 6593, "s": 6411, "text": "Pipelines are great because they enforce order during the transformation process making the workflow compact and easy to understand. This also can make the work easier to reproduce." }, { "code": null, "e": 6719, "s": 6593, "text": "Remember that pipeline uses transformers, so we need to use the FunctionTransformer on our functions to make them compatible." }, { "code": null, "e": 6870, "s": 6719, "text": "Using FunctionTransformer, it is easy to make the functions used in the feature engineering and column selection process compatible with the pipeline." }, { "code": null, "e": 7142, "s": 6870, "text": "get_year = FunctionTransformer(extract_year, validate=False)get_word_count = FunctionTransformer(word_count, validate=False)get_encoded_text = FunctionTransformer(category_encode, validate=False)get_numeric_data = FunctionTransformer(lambda x: x[numeric], validate=False)" }, { "code": null, "e": 7322, "s": 7142, "text": "Because some of functions rely on an index value, I need to make a function that resets the index so the pipeline works properly after splitting the data into train and test sets." }, { "code": null, "e": 7490, "s": 7322, "text": "def reset_index(dataframe): dataframe = dataframe.reset_index(inplace = False) return dataframeget_reset_index = FunctionTransformer(reset_index, validate=False)" }, { "code": null, "e": 7654, "s": 7490, "text": "The functions I created use global variables instead of hard-coded values so they are easier to reuse. Because of this, all of the global variables need to be set:" }, { "code": null, "e": 7865, "s": 7654, "text": "year_column = 'title'word_count_column = 'description'category_columns = ['country','province','title','winery']target = 'price'numeric= ['price', 'year', 'word_count', 'country', 'province', 'title', 'winery']" }, { "code": null, "e": 8147, "s": 7865, "text": "The pipeline can be used to select the model you want to use. To learn more about setting up a pipeline for model selection, I recommend checking out this Medium article by Rebecca Vickery. I am going to keep things simple and just use the Gradient Boost Regressor in Scikit Learn." }, { "code": null, "e": 8506, "s": 8147, "text": "#create Gradient Boosting Regressor model model = ensemble.GradientBoostingRegressor( n_estimators = 100, #how many decision trees to build learning_rate = 0.5, #controls rate at which additional decision trees influes overall prediction max_depth = 6, min_samples_split = 21, min_samples_leaf = 19, max_features = 0.9, loss = 'huber')" }, { "code": null, "e": 8697, "s": 8506, "text": "Once the model has been selected, the global variables have been set, and all the functions have been transformed and are compatible with the pipeline, it is time to put the pieces together:" }, { "code": null, "e": 8962, "s": 8697, "text": "pl = Pipeline(memory=None, steps=[ ('reset_index', get_reset_index), ('year', get_year), ('word_count', get_word_count), ('encode', get_encoded_text), ('selector', get_numeric_data), ('model', model) ], verbose=True)" }, { "code": null, "e": 9090, "s": 8962, "text": "Notice I set Verbose = True. Doing this prints the step has been complete. It makes the process more transparent for debugging." }, { "code": null, "e": 9187, "s": 9090, "text": "To test the pipeline, use the Train Test Split to split the data and run it through the pipline:" }, { "code": null, "e": 9541, "s": 9187, "text": "features = df.drop(['rating'], axis=1)X = featuresy = df['rating']X_train, X_test, y_train, y_test = train_test_split(X, y , test_size = .3 #, stratify=y )pl.fit(X_train, y_train)pl.score(X_test, y_test)" }, { "code": null, "e": 13465, "s": 9541, "text": "import numpy as npimport pandas as pdimport sqlite3import category_encoders as ceimport refrom sklearn.feature_selection import chi2, SelectKBestfrom sklearn.model_selection import train_test_splitfrom sklearn.feature_extraction.text import HashingVectorizerfrom sklearn.pipeline import Pipeline, FeatureUnionfrom sklearn.impute import SimpleImputerfrom sklearn.linear_model import LogisticRegressionfrom sklearn.preprocessing import MaxAbsScalerfrom sklearn.preprocessing import FunctionTransformerconn = sqlite3.connect('db/wine_data.sqlite')c = conn.cursor#create Dataframedf = pd.read_sql(\"select country \\ ,description \\ ,rating \\ ,price \\ ,province \\ ,title \\ ,winery from wine_data where variety = 'Chardonnay'\", conn)#df.head(2)def extract_year(dataframe): global year_column years = dataframe[year_column] #years.reset_index(inplace=False) #years.fillna(\"\", inplace=True) l = [] i = 0 for year in range(len(dataframe)): temp = re.findall(r'\\d+', years[i]) res = list(map(int, temp)) try: if len(str(res[0])) == 4: l.append(res[0]) elif len(str(res[0])) != 4: l.append(0) except: l.append(0) #print(res[0]) i+=1 dataframe['year'] = lreturn dataframe#df = extract_year(df)def word_count(dataframe): global word_count_column dataframe['word_count'] = dataframe[word_count_column].apply(lambda word: len(str(word).split(\" \"))) return dataframe# df = word_count(df)# df.head(3)# encoder = ce.JamesSteinEncoder(cols=[...]) --maybe (best score)# encoder = ce.LeaveOneOutEncoder(cols=[...]) --maybe# encoder = ce.MEstimateEncoder(cols=[...]) --maybe (good)# encoder = ce.OrdinalEncoder(cols=[...]) --maybe# encoder = ce.TargetEncoder(cols=[...]) --maybeyear_column = 'title'word_count_column = 'description'category_columns = ['country','province','title','winery']target = 'price'combine_text = ['country','province','title','winery', 'description']numeric= ['price', 'year', 'word_count','country','province','title','winery']def category_encode(dataframe): global category_columns global category_target x = dataframe[category_columns] y = dataframe[target] ce_ord = ce.OrdinalEncoder(cols=category_columns) dataframe[category_columns] = ce_ord.fit_transform(x, y) return dataframe# df = category_encode(df)# df.head()get_year = FunctionTransformer(extract_year, validate=False)get_word_count = FunctionTransformer(word_count, validate=False)get_encoded_text = FunctionTransformer(category_encode, validate=False)get_numeric_data = FunctionTransformer(lambda x: x[numeric], validate=False)def reset_index(dataframe): dataframe = dataframe.reset_index(inplace = False) return dataframeget_reset_index = FunctionTransformer(reset_index, validate=False)from sklearn import ensemble model = ensemble.GradientBoostingRegressor( n_estimators = 100, #how many decision trees to build learning_rate = 0.5, #controls rate at which additional decision trees influes overall prediction max_depth = 6, min_samples_split = 21, min_samples_leaf = 19, max_features = 0.9, loss = 'huber')pl = Pipeline(memory=None, steps=[ ('reset_index', get_reset_index), ('year', get_year), ('word_count', get_word_count), ('encode', get_encoded_text), ('selector', get_numeric_data), ('model', model) ], verbose=False)features = df.drop(['rating'], axis=1)X = featuresy = df['rating']X_train, X_test, y_train, y_test = train_test_split(X, y , test_size = .3 #, stratify=y )pl.fit(X_train, y_train)pl.score(X_test, y_test)" }, { "code": null, "e": 13476, "s": 13465, "text": "github.com" }, { "code": null, "e": 13526, "s": 13476, "text": "If you enjoyed this, follow me on Medium for more" }, { "code": null, "e": 13585, "s": 13526, "text": "Get FULL ACCESS and help support my content by subscribing" }, { "code": null, "e": 13611, "s": 13585, "text": "Let’s connect on LinkedIn" }, { "code": null, "e": 13659, "s": 13611, "text": "Analyze Data using Python? Check out my website" } ]
Java Program to sort integers in unsorted array
Let us first create an unsorted array − int[] arr = { 10, 14, 28, 11, 7, 16, 30, 50, 25, 18}; Now assign the unsorted array to the new array − int[] res = arr; Sorting the integers: Arrays.sort(res); Live Demo import java.util.Arrays; public class Demo { public static void main(String[] args) { int[] arr = { 10, 14, 28, 11, 7, 16, 30, 50, 25, 18}; System.out.println("The unsorted integer array = "+Arrays.toString(arr)); int[] res = arr; Arrays.sort(res); System.out.println("The sorted integer array = "+Arrays.toString(res)); } } The unsorted integer array = [10, 14, 28, 11, 7, 16, 30, 50, 25, 18] The sorted integer array = [7, 10, 11, 14, 16, 18, 25, 28, 30, 50]
[ { "code": null, "e": 1102, "s": 1062, "text": "Let us first create an unsorted array −" }, { "code": null, "e": 1156, "s": 1102, "text": "int[] arr = { 10, 14, 28, 11, 7, 16, 30, 50, 25, 18};" }, { "code": null, "e": 1205, "s": 1156, "text": "Now assign the unsorted array to the new array −" }, { "code": null, "e": 1262, "s": 1205, "text": "int[] res = arr;\nSorting the integers:\nArrays.sort(res);" }, { "code": null, "e": 1273, "s": 1262, "text": " Live Demo" }, { "code": null, "e": 1634, "s": 1273, "text": "import java.util.Arrays;\npublic class Demo {\n public static void main(String[] args) {\n int[] arr = { 10, 14, 28, 11, 7, 16, 30, 50, 25, 18};\n System.out.println(\"The unsorted integer array = \"+Arrays.toString(arr));\n int[] res = arr;\n Arrays.sort(res);\n System.out.println(\"The sorted integer array = \"+Arrays.toString(res));\n }\n}" }, { "code": null, "e": 1770, "s": 1634, "text": "The unsorted integer array = [10, 14, 28, 11, 7, 16, 30, 50, 25, 18]\nThe sorted integer array = [7, 10, 11, 14, 16, 18, 25, 28, 30, 50]" } ]
XSLT <choose>
<xsl:choose> tag specifies a multiple conditional tests against the content of nodes in conjunction with the <xsl:otherwise> and <xsl:when> elements. Following is the syntax declaration of <xsl:choose> element. <xsl:choose > </xsl:choose> Parent elements xsl:attribute, xsl:comment, xsl:copy, xsl:element, xsl:fallback, xsl:for-each, xsl:if, xsl:message, xsl:otherwise, xsl:param, xsl:processing-instruction, xsl:template, xsl:variable, xsl:when, xsl:with-param, output elements Child elements xsl:otherwise, xsl:when This example creates a table of <student> element with its attribute rollno and its child <firstname>, <lastname>, <nickname>, and <marks> by iterating over each student. It checks and then prints the grade details. students.xml <?xml version = "1.0"?> <?xml-stylesheet type = "text/xsl" href = "students.xsl"?> <class> <student rollno = "393"> <firstname>Dinkar</firstname> <lastname>Kad</lastname> <nickname>Dinkar</nickname> <marks>85</marks> </student> <student rollno = "493"> <firstname>Vaneet</firstname> <lastname>Gupta</lastname> <nickname>Vinni</nickname> <marks>95</marks> </student> <student rollno = "593"> <firstname>Jasvir</firstname> <lastname>Singh</lastname> <nickname>Jazz</nickname> <marks>90</marks> </student> </class> students.xsl <?xml version = "1.0" encoding = "UTF-8"?> <xsl:stylesheet version = "1.0" xmlns:xsl = "http://www.w3.org/1999/XSL/Transform"> <xsl:template match = "/"> <html> <body> <h2>Students</h2> <table border = "1"> <tr bgcolor = "#9acd32"> <th>Roll No</th> <th>First Name</th> <th>Last Name</th> <th>Nick Name</th> <th>Marks</th> <th>Grade</th> </tr> <xsl:for-each select = "class/student"> <tr> <td><xsl:value-of select = "@rollno"/></td> <td><xsl:value-of select = "firstname"/></td> <td><xsl:value-of select = "lastname"/></td> <td><xsl:value-of select = "nickname"/></td> <td><xsl:value-of select = "marks"/></td> <td> <xsl:choose> <xsl:when test = "marks > 90"> High </xsl:when> <xsl:when test = "marks > 85"> Medium </xsl:when> <xsl:otherwise> Low </xsl:otherwise> </xsl:choose> </td> </tr> </xsl:for-each> </table> </body> </html> </xsl:template> </xsl:stylesheet> Print Add Notes Bookmark this page
[ { "code": null, "e": 1909, "s": 1759, "text": "<xsl:choose> tag specifies a multiple conditional tests against the content of nodes in conjunction with the <xsl:otherwise> and <xsl:when> elements." }, { "code": null, "e": 1970, "s": 1909, "text": "Following is the syntax declaration of <xsl:choose> element." }, { "code": null, "e": 1999, "s": 1970, "text": "<xsl:choose >\n</xsl:choose>\n" }, { "code": null, "e": 2015, "s": 1999, "text": "Parent elements" }, { "code": null, "e": 2239, "s": 2015, "text": "xsl:attribute, xsl:comment, xsl:copy, xsl:element, xsl:fallback, xsl:for-each, xsl:if, xsl:message, xsl:otherwise, xsl:param, xsl:processing-instruction, xsl:template, xsl:variable, xsl:when, xsl:with-param, output elements" }, { "code": null, "e": 2254, "s": 2239, "text": "Child elements" }, { "code": null, "e": 2278, "s": 2254, "text": "xsl:otherwise, xsl:when" }, { "code": null, "e": 2494, "s": 2278, "text": "This example creates a table of <student> element with its attribute rollno and its child <firstname>, <lastname>, <nickname>, and <marks> by iterating over each student. It checks and then prints the grade details." }, { "code": null, "e": 2507, "s": 2494, "text": "students.xml" }, { "code": null, "e": 3129, "s": 2507, "text": "<?xml version = \"1.0\"?> \n<?xml-stylesheet type = \"text/xsl\" href = \"students.xsl\"?> \n<class> \n <student rollno = \"393\"> \n <firstname>Dinkar</firstname>\n <lastname>Kad</lastname> \n <nickname>Dinkar</nickname> \n <marks>85</marks> \n </student> \n <student rollno = \"493\"> \n <firstname>Vaneet</firstname> \n <lastname>Gupta</lastname> \n <nickname>Vinni</nickname> \n <marks>95</marks> \n </student> \n <student rollno = \"593\"> \n <firstname>Jasvir</firstname> \n <lastname>Singh</lastname> \n <nickname>Jazz</nickname> \n <marks>90</marks> \n </student> \n</class>" }, { "code": null, "e": 3142, "s": 3129, "text": "students.xsl" }, { "code": null, "e": 4817, "s": 3142, "text": "<?xml version = \"1.0\" encoding = \"UTF-8\"?> \n<xsl:stylesheet version = \"1.0\" \n xmlns:xsl = \"http://www.w3.org/1999/XSL/Transform\"> \n <xsl:template match = \"/\"> \n <html> \n <body> \n <h2>Students</h2> \n <table border = \"1\"> \n <tr bgcolor = \"#9acd32\"> \n <th>Roll No</th> \n <th>First Name</th> \n <th>Last Name</th> \n <th>Nick Name</th> \n <th>Marks</th> \n <th>Grade</th> \n </tr> \n\t\t\t\t\t\n <xsl:for-each select = \"class/student\"> \n\t\t\t\t\t\n <tr> \n <td><xsl:value-of select = \"@rollno\"/></td> \n <td><xsl:value-of select = \"firstname\"/></td> \n <td><xsl:value-of select = \"lastname\"/></td> \n <td><xsl:value-of select = \"nickname\"/></td> \n <td><xsl:value-of select = \"marks\"/></td> \n\t\t\t\t\t\t\t\n <td> \n <xsl:choose> \n <xsl:when test = \"marks > 90\"> \n High \n </xsl:when> \n\t\t\t\t\t\t\t\t\t\n <xsl:when test = \"marks > 85\"> \n Medium \n </xsl:when> \n\t\t\t\t\t\t\t\t\t\n <xsl:otherwise> \n Low \n </xsl:otherwise> \n </xsl:choose> \n </td> \n </tr> \n </xsl:for-each> \n </table> \n </body> \n </html> \n </xsl:template> \n</xsl:stylesheet>" }, { "code": null, "e": 4824, "s": 4817, "text": " Print" }, { "code": null, "e": 4835, "s": 4824, "text": " Add Notes" } ]
Interactively analyse 100GB of JSON data with Spark | by Cambridge Spark | Towards Data Science
Do you know what is the heaviest book ever printed? Let’s find out by exploring the Open Library data set using Spark in Python. The purpose of this tutorial is educational, originally posted by Dr. Valentin Dalibard and Dr. Raoul-Gabriel Urma: https://cambridgespark.com/content/tutorials/interactively-analyse-100GB-of-JSON-data-with-Spark/index.html You will get a taster of some of the operations available in Spark and how you can use them to interactively explore a dataset that would be inconvenient (because of size and structure) to work with in simpler tools like Excel. You will also see how MapReduce operations can easily be expressed in Spark. Note that we use Spark to run an ad-hoc analysis in a convenient manner. There are alternatives to analyse this dataset such as using Impala. In this tutorial you will learn: how to get started with Spark, how to use the map, flatMap, filter, and reduce patterns, and how to use the groupByKey and reduceByKey functions. The Open Library is an initiative intended to create “one web page for every book ever published.” You can download their dataset which is about 20GB of compressed data using the following command in your terminal. The --continue flag lets you download the data in several go. wget --continue http://openlibrary.org/data/ol_cdump_latest.txt.gz You can then extract the data — you need about 100GB of free space — using the following command: gunzip -k ol_cdump_latest.txt.gz | cut -f 5 > ol_cdump.json To use the dataset on EC2, upload it to Amazon S3. Use the following command, with your S3 bucket name, the upload the data to an S3. Like the three previous steps, this one takes time to complete. aws s3 cp ol_cdump.json s3://my_bucket Alternatively, if you want to work with a smaller data set to save time, you can download a sample of the data from https://s3-eu-west-1.amazonaws.com/csparkdata/ol_cdump.json The techniques below will work, but the results will differ. If you want to analyse the data locally you can install PySpark on your own machine, ignore the Amazon setup and jump straight to the data analysis. If you would like to get started with Spark on a cluster, a simple option is Amazon Elastic MapReduce (EMR). It gives you a cluster of several machines with Spark pre-configured. This is particularly useful if you quickly need to process a large file which is stored over S3. Here is a youtube video to show you how you can get started: Amazon EMR Spark instances come with Zeppelin notebooks: an alternative to jupyter notebooks which run directly on top of Spark. Open a Zeppelin notebook by clicking on the Zeppelin link on Amazon EMR. Zeppelin allows for multiple languages to be used within the same notebook. Use %pyspark at the top of a cell to run Python commands. %pysparkprint("Hello") Alternatively, you can execute shell instructions: %shecho "World !" The first step is to load the dataset in a Spark RDD: a data structure that abstracts how the data is processed — in distributed mode the data is split among machines — and lets you apply different data processing patterns such as filter, map and reduce. To learn more about RDDs as well as the rest of the topics of this tutorial, check out our big data bootcamp. You can read the file and turn each line into an element of the RDD using the operation textFile. path = "s3://my_bucket/ol_cdump.json"raw_data = sc.textFile(path) Note that if you are working with a local copy of the file, you can just pass a standard file path (e.g., ol_cdump.json) to the function. Each element in the RDD is a single string representing a json value. Thus, the second step turns each of these elements in a Python dictionary so they can be analysed more easily. The json.loadsfunction parses a JSON value into a Python dictionary. And the method .map(f) returns a new RDD where f has been applied to each element in the original RDD. Combine the two to parse all the lines of the RDD. import jsondataset = raw_data.map(json.loads)dataset.persist() Note that the code also calls the method .persist() to cache the RDD in memory so it can be reused directly later. Each element in the RDD dataset is now a dictionary mapping keys to values. You can start by finding out the number of entries: dataset.count() This returns 126,107,177. Not bad, quite a lot of books! You can take a sneak peak at the data using the first operation to return the very first element. Alternatively, take(k) returns a list of the first k elements dataset.take(10) The output is quite long. But you will see that the entries returned contain book attributes such as number_of_pages, title, weight, isbn_10, etc. In order to understand the shape of the data you have, you can extract all the distinct keys available in the dictionaries. You may be tempted to use the map operation again, but you have to use flatMapinstead. Indeed, for each dictionary, you extract a list of keys, so map would produce an RDD of lists of keys. Using flatMap, all the keys are collapsed into a single, flat RDD. One way to think about flatMapis that it lets you apply a one-to-many transformation for each element instead of one-to-one like mapdoes. On this RDD of keys, you can use distinct to remove duplicate keys. Finally, use the collectoperation to extract this RDD of unique keys into a Python list. keys = dataset.flatMap(lambda d: d.keys()).distinct().collect()len(keys) There are 504 unique keys! That is quite a lot of different attributes for a book. In practice not all JSON objects have the same attributes: there are often missing attributes. E.g., the database may mention the number of pages in a book but not necessarily its printed dimensions. That is what you get with real-world data. In the Open Library dataset you find a lot of diversity! To explore that diversity, you could group the number of attributes for each element using groupByKey: groups = dataset.map(lambda e: (len(e.keys()), e)).groupByKey() But hold on! This actually not good practice at all! You could have a most common number of keys with a lot of data associated with that key, say 20GB. In that case, you would create a 20GB Python list which would crash your machine or cause swapping. A better way of computing the same result is by using reduceByKey: count_per_key = ( dataset .map(lambda e: (len(e.keys()), 1)) .reduceByKey(lambda x, y: x + y) .collect() ) The reduceByKey operation adds up the 1s generated for each key, which ends up returning the count per number of attributes. Zeppelin is quite useful here as it lets you visualise the result directly through its interface: print("%table")for e in count_per_key: print("%d\t%d" % (e[0], e[1])) You managed to get some insights about the data. How about something more fun which you can bring up during fancy dinner parties? You are in luck. One of the JSON attribute is the weight of each book. Are you curious to find out what is the heaviest book? Let’s hope it is an interesting book at least. When you explored the dataset you will have noticed that there are different units for the weightattribute: kg, g, ounces, pounds, etc. It is all very messy! You will need a function that can normalise the weights so you can compare each book: def sanitizedWeight(weight_str): w = convertToKilograms(weight_str) if w > 1e6: #books above 1e6 kg are errors return 0.0 else: return wdef convertToKilograms(weight_str): result = weight_str.split() if(len(result)) != 2: return 0 try: number = float(result[0]) except ValueError: return 0 if(result[1] == 'pounds' or result[1] == 'lb' or result[1] == 'lbs'): return number * 453.592 * 1e-3 elif(result[1] == 'ounces' or result[1] == 'oz' or result[1] == 'oz.'): return number * 28.35 * 1e-3 elif(result[1] == 'grams' or result[1] == 'gms' or result[1] == 'g'): return number * 1e-3 elif(result[1] == 'kilograms' or result[1] == 'kilo' or result[1] == 'kg'): return number else: return 0 Note that there are still a few books with weight attributes that are ignored by this function. Some weights appear with no space between the number and the unit, some with unusual capitalisation (GM, KGms), some with typos (“ounds”), some with other oddities. Let’s keep a focus on analysing the dataset — but feel free to improve this parser if you want. To find the heaviest book, you simply need to iterate through the data and reduce it, selecting the heaviest book each time. heaviest_book = ( dataset .filter(lambda e: "weight" in e and "title" in e) .map(lambda e: (e, sanitizedWeight(e["weight"]))) .reduce(lambda x, y: x if x[1]>y[1] else y) ) So what is the answer? Unfortunately it is a bit of a let down, the output is a book of 200,000 pounds(just over 90 metric tons) with a strangle title! ({... u'weight': u'200000 pounds', ..., u'title': u'u fool,stupid', ...}, 90718.40000000001) Clearly someone inserted a dummy entry in the database! This is a bit of let down. How about getting a visualisation of when books were published? You can use the operations you’ve learnt to produce the following query: booksWithDate = ( dataset .filter(lambda e: "publish_date" in e) .map(lambda e: (e["publish_date"], 1)) .reduceByKey(lambda x, y: x + y) .collect() )def is_int(s): try: t = int(s) return True except ValueError: return FalsebooksWithDate = ( dataset .filter(lambda e: "publish_date" in e) .filter(lambda e: len(e["publish_date"]) >=4) .filter(lambda e: is_int(e["publish_date"][-4:])) .map(lambda e: (int(e["publish_date"][-4:]), 1)) .reduceByKey(lambda x, y: x+y) .collect() ) Again, you need to process and clean the data before you can work with real years. You can now use the visualisation feature in Zeppelin to get a nice distribution: print("%table")for r in d: print("%d\t%d" % (r[0], r[1])) If you are interested more about Spark and big data systems, check out our upcoming webinar series: cambridgespark.com And in the meantime you can test your Spark skills trying to find answers to these questions: Which author has written or co-written the most books in the dataset? Which category of books is the most popular in the dataset?
[ { "code": null, "e": 300, "s": 171, "text": "Do you know what is the heaviest book ever printed? Let’s find out by exploring the Open Library data set using Spark in Python." }, { "code": null, "e": 524, "s": 300, "text": "The purpose of this tutorial is educational, originally posted by Dr. Valentin Dalibard and Dr. Raoul-Gabriel Urma: https://cambridgespark.com/content/tutorials/interactively-analyse-100GB-of-JSON-data-with-Spark/index.html" }, { "code": null, "e": 971, "s": 524, "text": "You will get a taster of some of the operations available in Spark and how you can use them to interactively explore a dataset that would be inconvenient (because of size and structure) to work with in simpler tools like Excel. You will also see how MapReduce operations can easily be expressed in Spark. Note that we use Spark to run an ad-hoc analysis in a convenient manner. There are alternatives to analyse this dataset such as using Impala." }, { "code": null, "e": 1004, "s": 971, "text": "In this tutorial you will learn:" }, { "code": null, "e": 1035, "s": 1004, "text": "how to get started with Spark," }, { "code": null, "e": 1097, "s": 1035, "text": "how to use the map, flatMap, filter, and reduce patterns, and" }, { "code": null, "e": 1150, "s": 1097, "text": "how to use the groupByKey and reduceByKey functions." }, { "code": null, "e": 1427, "s": 1150, "text": "The Open Library is an initiative intended to create “one web page for every book ever published.” You can download their dataset which is about 20GB of compressed data using the following command in your terminal. The --continue flag lets you download the data in several go." }, { "code": null, "e": 1494, "s": 1427, "text": "wget --continue http://openlibrary.org/data/ol_cdump_latest.txt.gz" }, { "code": null, "e": 1592, "s": 1494, "text": "You can then extract the data — you need about 100GB of free space — using the following command:" }, { "code": null, "e": 1652, "s": 1592, "text": "gunzip -k ol_cdump_latest.txt.gz | cut -f 5 > ol_cdump.json" }, { "code": null, "e": 1850, "s": 1652, "text": "To use the dataset on EC2, upload it to Amazon S3. Use the following command, with your S3 bucket name, the upload the data to an S3. Like the three previous steps, this one takes time to complete." }, { "code": null, "e": 1889, "s": 1850, "text": "aws s3 cp ol_cdump.json s3://my_bucket" }, { "code": null, "e": 2126, "s": 1889, "text": "Alternatively, if you want to work with a smaller data set to save time, you can download a sample of the data from https://s3-eu-west-1.amazonaws.com/csparkdata/ol_cdump.json The techniques below will work, but the results will differ." }, { "code": null, "e": 2275, "s": 2126, "text": "If you want to analyse the data locally you can install PySpark on your own machine, ignore the Amazon setup and jump straight to the data analysis." }, { "code": null, "e": 2551, "s": 2275, "text": "If you would like to get started with Spark on a cluster, a simple option is Amazon Elastic MapReduce (EMR). It gives you a cluster of several machines with Spark pre-configured. This is particularly useful if you quickly need to process a large file which is stored over S3." }, { "code": null, "e": 2612, "s": 2551, "text": "Here is a youtube video to show you how you can get started:" }, { "code": null, "e": 2814, "s": 2612, "text": "Amazon EMR Spark instances come with Zeppelin notebooks: an alternative to jupyter notebooks which run directly on top of Spark. Open a Zeppelin notebook by clicking on the Zeppelin link on Amazon EMR." }, { "code": null, "e": 2948, "s": 2814, "text": "Zeppelin allows for multiple languages to be used within the same notebook. Use %pyspark at the top of a cell to run Python commands." }, { "code": null, "e": 2971, "s": 2948, "text": "%pysparkprint(\"Hello\")" }, { "code": null, "e": 3022, "s": 2971, "text": "Alternatively, you can execute shell instructions:" }, { "code": null, "e": 3040, "s": 3022, "text": "%shecho \"World !\"" }, { "code": null, "e": 3405, "s": 3040, "text": "The first step is to load the dataset in a Spark RDD: a data structure that abstracts how the data is processed — in distributed mode the data is split among machines — and lets you apply different data processing patterns such as filter, map and reduce. To learn more about RDDs as well as the rest of the topics of this tutorial, check out our big data bootcamp." }, { "code": null, "e": 3503, "s": 3405, "text": "You can read the file and turn each line into an element of the RDD using the operation textFile." }, { "code": null, "e": 3569, "s": 3503, "text": "path = \"s3://my_bucket/ol_cdump.json\"raw_data = sc.textFile(path)" }, { "code": null, "e": 3707, "s": 3569, "text": "Note that if you are working with a local copy of the file, you can just pass a standard file path (e.g., ol_cdump.json) to the function." }, { "code": null, "e": 4111, "s": 3707, "text": "Each element in the RDD is a single string representing a json value. Thus, the second step turns each of these elements in a Python dictionary so they can be analysed more easily. The json.loadsfunction parses a JSON value into a Python dictionary. And the method .map(f) returns a new RDD where f has been applied to each element in the original RDD. Combine the two to parse all the lines of the RDD." }, { "code": null, "e": 4174, "s": 4111, "text": "import jsondataset = raw_data.map(json.loads)dataset.persist()" }, { "code": null, "e": 4289, "s": 4174, "text": "Note that the code also calls the method .persist() to cache the RDD in memory so it can be reused directly later." }, { "code": null, "e": 4365, "s": 4289, "text": "Each element in the RDD dataset is now a dictionary mapping keys to values." }, { "code": null, "e": 4417, "s": 4365, "text": "You can start by finding out the number of entries:" }, { "code": null, "e": 4433, "s": 4417, "text": "dataset.count()" }, { "code": null, "e": 4490, "s": 4433, "text": "This returns 126,107,177. Not bad, quite a lot of books!" }, { "code": null, "e": 4650, "s": 4490, "text": "You can take a sneak peak at the data using the first operation to return the very first element. Alternatively, take(k) returns a list of the first k elements" }, { "code": null, "e": 4667, "s": 4650, "text": "dataset.take(10)" }, { "code": null, "e": 4814, "s": 4667, "text": "The output is quite long. But you will see that the entries returned contain book attributes such as number_of_pages, title, weight, isbn_10, etc." }, { "code": null, "e": 5333, "s": 4814, "text": "In order to understand the shape of the data you have, you can extract all the distinct keys available in the dictionaries. You may be tempted to use the map operation again, but you have to use flatMapinstead. Indeed, for each dictionary, you extract a list of keys, so map would produce an RDD of lists of keys. Using flatMap, all the keys are collapsed into a single, flat RDD. One way to think about flatMapis that it lets you apply a one-to-many transformation for each element instead of one-to-one like mapdoes." }, { "code": null, "e": 5490, "s": 5333, "text": "On this RDD of keys, you can use distinct to remove duplicate keys. Finally, use the collectoperation to extract this RDD of unique keys into a Python list." }, { "code": null, "e": 5563, "s": 5490, "text": "keys = dataset.flatMap(lambda d: d.keys()).distinct().collect()len(keys)" }, { "code": null, "e": 5646, "s": 5563, "text": "There are 504 unique keys! That is quite a lot of different attributes for a book." }, { "code": null, "e": 6049, "s": 5646, "text": "In practice not all JSON objects have the same attributes: there are often missing attributes. E.g., the database may mention the number of pages in a book but not necessarily its printed dimensions. That is what you get with real-world data. In the Open Library dataset you find a lot of diversity! To explore that diversity, you could group the number of attributes for each element using groupByKey:" }, { "code": null, "e": 6113, "s": 6049, "text": "groups = dataset.map(lambda e: (len(e.keys()), e)).groupByKey()" }, { "code": null, "e": 6365, "s": 6113, "text": "But hold on! This actually not good practice at all! You could have a most common number of keys with a lot of data associated with that key, say 20GB. In that case, you would create a 20GB Python list which would crash your machine or cause swapping." }, { "code": null, "e": 6432, "s": 6365, "text": "A better way of computing the same result is by using reduceByKey:" }, { "code": null, "e": 6552, "s": 6432, "text": "count_per_key = ( dataset .map(lambda e: (len(e.keys()), 1)) .reduceByKey(lambda x, y: x + y) .collect() )" }, { "code": null, "e": 6775, "s": 6552, "text": "The reduceByKey operation adds up the 1s generated for each key, which ends up returning the count per number of attributes. Zeppelin is quite useful here as it lets you visualise the result directly through its interface:" }, { "code": null, "e": 6846, "s": 6775, "text": "print(\"%table\")for e in count_per_key: print(\"%d\\t%d\" % (e[0], e[1]))" }, { "code": null, "e": 7393, "s": 6846, "text": "You managed to get some insights about the data. How about something more fun which you can bring up during fancy dinner parties? You are in luck. One of the JSON attribute is the weight of each book. Are you curious to find out what is the heaviest book? Let’s hope it is an interesting book at least. When you explored the dataset you will have noticed that there are different units for the weightattribute: kg, g, ounces, pounds, etc. It is all very messy! You will need a function that can normalise the weights so you can compare each book:" }, { "code": null, "e": 8124, "s": 7393, "text": "def sanitizedWeight(weight_str): w = convertToKilograms(weight_str) if w > 1e6: #books above 1e6 kg are errors return 0.0 else: return wdef convertToKilograms(weight_str): result = weight_str.split() if(len(result)) != 2: return 0 try: number = float(result[0]) except ValueError: return 0 if(result[1] == 'pounds' or result[1] == 'lb' or result[1] == 'lbs'): return number * 453.592 * 1e-3 elif(result[1] == 'ounces' or result[1] == 'oz' or result[1] == 'oz.'): return number * 28.35 * 1e-3 elif(result[1] == 'grams' or result[1] == 'gms' or result[1] == 'g'): return number * 1e-3 elif(result[1] == 'kilograms' or result[1] == 'kilo' or result[1] == 'kg'): return number else: return 0" }, { "code": null, "e": 8481, "s": 8124, "text": "Note that there are still a few books with weight attributes that are ignored by this function. Some weights appear with no space between the number and the unit, some with unusual capitalisation (GM, KGms), some with typos (“ounds”), some with other oddities. Let’s keep a focus on analysing the dataset — but feel free to improve this parser if you want." }, { "code": null, "e": 8606, "s": 8481, "text": "To find the heaviest book, you simply need to iterate through the data and reduce it, selecting the heaviest book each time." }, { "code": null, "e": 8791, "s": 8606, "text": "heaviest_book = ( dataset .filter(lambda e: \"weight\" in e and \"title\" in e) .map(lambda e: (e, sanitizedWeight(e[\"weight\"]))) .reduce(lambda x, y: x if x[1]>y[1] else y) )" }, { "code": null, "e": 8943, "s": 8791, "text": "So what is the answer? Unfortunately it is a bit of a let down, the output is a book of 200,000 pounds(just over 90 metric tons) with a strangle title!" }, { "code": null, "e": 9037, "s": 8943, "text": "({... u'weight': u'200000 pounds', ..., u'title': u'u fool,stupid', ...}, 90718.40000000001)" }, { "code": null, "e": 9120, "s": 9037, "text": "Clearly someone inserted a dummy entry in the database! This is a bit of let down." }, { "code": null, "e": 9257, "s": 9120, "text": "How about getting a visualisation of when books were published? You can use the operations you’ve learnt to produce the following query:" }, { "code": null, "e": 9783, "s": 9257, "text": "booksWithDate = ( dataset .filter(lambda e: \"publish_date\" in e) .map(lambda e: (e[\"publish_date\"], 1)) .reduceByKey(lambda x, y: x + y) .collect() )def is_int(s): try: t = int(s) return True except ValueError: return FalsebooksWithDate = ( dataset .filter(lambda e: \"publish_date\" in e) .filter(lambda e: len(e[\"publish_date\"]) >=4) .filter(lambda e: is_int(e[\"publish_date\"][-4:])) .map(lambda e: (int(e[\"publish_date\"][-4:]), 1)) .reduceByKey(lambda x, y: x+y) .collect() )" }, { "code": null, "e": 9948, "s": 9783, "text": "Again, you need to process and clean the data before you can work with real years. You can now use the visualisation feature in Zeppelin to get a nice distribution:" }, { "code": null, "e": 10007, "s": 9948, "text": "print(\"%table\")for r in d: print(\"%d\\t%d\" % (r[0], r[1]))" }, { "code": null, "e": 10107, "s": 10007, "text": "If you are interested more about Spark and big data systems, check out our upcoming webinar series:" }, { "code": null, "e": 10126, "s": 10107, "text": "cambridgespark.com" }, { "code": null, "e": 10220, "s": 10126, "text": "And in the meantime you can test your Spark skills trying to find answers to these questions:" }, { "code": null, "e": 10290, "s": 10220, "text": "Which author has written or co-written the most books in the dataset?" } ]
Maximum value of long long int in C++ - GeeksforGeeks
18 Dec, 2020 In this article, we will discuss the long long int data type in C++. long long int data type in C++ is used to store 64-bit integers. It is one of the largest data types to store integer values, unlike unsigned long long int both positive as well as negative. Some properties of the long long int data type are: Being a signed data type, it can store positive values as well as negative values. Takes a size of 64 bits where 1 bit is used to store the sign of the integer. A maximum integer value that can be stored in a long long int data type is typically 9, 223, 372, 036, 854, 775, 807 around 263 – 1(but is compiler dependent). The maximum value that can be stored in long long int is stored as a constant in <climits> header file. Whose value can be used as LLONG_MAX. A minimum integer value that can be stored in a long long int data type is typically –9, 223, 372, 036, 854, 775, 808, around –263 (but is compiler dependent). In case of overflow or underflow of data type, the value is wrapped around. For example, if –9, 223, 372, 036, 854, 775, 808 is stored in an long long int data type and 1 is subtracted from it, the value in that variable will become equal to 9, 223, 372, 036, 854, 775, 807. Similarly, in the case of overflow, the value will round back to –9, 223, 372, 036, 854, 775, 808. Below is the program to get the highest value that can be stored in long long int in C++: C++ // C++ program to illustrate the maximum// value that can be stored in long long int#include <climits>#include <iostream>using namespace std; // Driver Codeint main(){ // From the constant of climits // header file long long int valueFromLimits = LLONG_MAX; cout << "Value from climits " << "constant (maximum): "; cout << valueFromLimits << "\n"; valueFromLimits = LLONG_MIN; cout << "Value from climits " << "constant (minimum): "; cout << valueFromLimits << "\n"; return 0;} Value from climits constant (maximum): 9223372036854775807 Value from climits constant (minimum): -9223372036854775808 C Basics C-Data Types C++ C++ Programs CPP Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Iterators in C++ STL Operator Overloading in C++ Friend class and function in C++ Polymorphism in C++ Inline Functions in C++ Header files in C/C++ and its uses How to return multiple values from a function in C or C++? C++ Program for QuickSort C++ program for hashing with chaining delete keyword in C++
[ { "code": null, "e": 24043, "s": 24015, "text": "\n18 Dec, 2020" }, { "code": null, "e": 24303, "s": 24043, "text": "In this article, we will discuss the long long int data type in C++. long long int data type in C++ is used to store 64-bit integers. It is one of the largest data types to store integer values, unlike unsigned long long int both positive as well as negative." }, { "code": null, "e": 24355, "s": 24303, "text": "Some properties of the long long int data type are:" }, { "code": null, "e": 24438, "s": 24355, "text": "Being a signed data type, it can store positive values as well as negative values." }, { "code": null, "e": 24516, "s": 24438, "text": "Takes a size of 64 bits where 1 bit is used to store the sign of the integer." }, { "code": null, "e": 24676, "s": 24516, "text": "A maximum integer value that can be stored in a long long int data type is typically 9, 223, 372, 036, 854, 775, 807 around 263 – 1(but is compiler dependent)." }, { "code": null, "e": 24818, "s": 24676, "text": "The maximum value that can be stored in long long int is stored as a constant in <climits> header file. Whose value can be used as LLONG_MAX." }, { "code": null, "e": 24978, "s": 24818, "text": "A minimum integer value that can be stored in a long long int data type is typically –9, 223, 372, 036, 854, 775, 808, around –263 (but is compiler dependent)." }, { "code": null, "e": 25352, "s": 24978, "text": "In case of overflow or underflow of data type, the value is wrapped around. For example, if –9, 223, 372, 036, 854, 775, 808 is stored in an long long int data type and 1 is subtracted from it, the value in that variable will become equal to 9, 223, 372, 036, 854, 775, 807. Similarly, in the case of overflow, the value will round back to –9, 223, 372, 036, 854, 775, 808." }, { "code": null, "e": 25442, "s": 25352, "text": "Below is the program to get the highest value that can be stored in long long int in C++:" }, { "code": null, "e": 25446, "s": 25442, "text": "C++" }, { "code": "// C++ program to illustrate the maximum// value that can be stored in long long int#include <climits>#include <iostream>using namespace std; // Driver Codeint main(){ // From the constant of climits // header file long long int valueFromLimits = LLONG_MAX; cout << \"Value from climits \" << \"constant (maximum): \"; cout << valueFromLimits << \"\\n\"; valueFromLimits = LLONG_MIN; cout << \"Value from climits \" << \"constant (minimum): \"; cout << valueFromLimits << \"\\n\"; return 0;}", "e": 25988, "s": 25446, "text": null }, { "code": null, "e": 26108, "s": 25988, "text": "Value from climits constant (maximum): 9223372036854775807\nValue from climits constant (minimum): -9223372036854775808\n" }, { "code": null, "e": 26117, "s": 26108, "text": "C Basics" }, { "code": null, "e": 26130, "s": 26117, "text": "C-Data Types" }, { "code": null, "e": 26134, "s": 26130, "text": "C++" }, { "code": null, "e": 26147, "s": 26134, "text": "C++ Programs" }, { "code": null, "e": 26151, "s": 26147, "text": "CPP" }, { "code": null, "e": 26249, "s": 26151, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 26258, "s": 26249, "text": "Comments" }, { "code": null, "e": 26271, "s": 26258, "text": "Old Comments" }, { "code": null, "e": 26292, "s": 26271, "text": "Iterators in C++ STL" }, { "code": null, "e": 26320, "s": 26292, "text": "Operator Overloading in C++" }, { "code": null, "e": 26353, "s": 26320, "text": "Friend class and function in C++" }, { "code": null, "e": 26373, "s": 26353, "text": "Polymorphism in C++" }, { "code": null, "e": 26397, "s": 26373, "text": "Inline Functions in C++" }, { "code": null, "e": 26432, "s": 26397, "text": "Header files in C/C++ and its uses" }, { "code": null, "e": 26491, "s": 26432, "text": "How to return multiple values from a function in C or C++?" }, { "code": null, "e": 26517, "s": 26491, "text": "C++ Program for QuickSort" }, { "code": null, "e": 26555, "s": 26517, "text": "C++ program for hashing with chaining" } ]
Get count of values that only appear once in a MySQL column?
To get number of values that only appear once in a column, use GROUP BY HAVING. Let us first create a table: mysql> create table DemoTable ( Name varchar(20) ); Query OK, 0 rows affected (0.55 sec) Following is the query to insert some records in the table using insert command: mysql> insert into DemoTable values('Larry'); Query OK, 1 row affected (0.13 sec) mysql> insert into DemoTable values('Larry'); Query OK, 1 row affected (0.11 sec) mysql> insert into DemoTable values('Sam'); Query OK, 1 row affected (0.14 sec) mysql> insert into DemoTable values('Chris'); Query OK, 1 row affected (0.14 sec) mysql> insert into DemoTable values('Sam'); Query OK, 1 row affected (0.12 sec) mysql> insert into DemoTable values('Mike'); Query OK, 1 row affected (0.13 sec) mysql> insert into DemoTable values('Sam'); Query OK, 1 row affected (0.11 sec) mysql> insert into DemoTable values('Larry'); Query OK, 1 row affected (0.21 sec) mysql> insert into DemoTable values('Mike'); Query OK, 1 row affected (0.32 sec) mysql> insert into DemoTable values('Mike'); Query OK, 1 row affected (0.16 sec) mysql> insert into DemoTable values('Carol'); Query OK, 1 row affected (0.27 sec) mysql> insert into DemoTable values('Robert'); Query OK, 1 row affected (0.27 sec) Following is the query to display records from the table using select command: mysql> select *from DemoTable; This will produce the following output +--------+ | Name | +--------+ | Larry | | Larry | | Sam | | Chris | | Sam | | Mike | | Sam | | Larry | | Mike | | Mike | | Carol | | Robert | +--------+ 12 rows in set (0.00 sec) Following is the query to count the values that only appear once in a column i.e. the count of the names that appears only once in the “Name” column: mysql> SELECT COUNT(Name) FROM ( SELECT Name FROM DemoTable GROUP BY Name HAVING COUNT(*) = 1 ) AS APPEAR_FIRST_TIME; This will produce the following output +-------------+ | COUNT(Name) | +-------------+ | 3 | +-------------+ 1 row in set (0.00 sec)
[ { "code": null, "e": 1171, "s": 1062, "text": "To get number of values that only appear once in a column, use GROUP BY HAVING. Let us first create a table:" }, { "code": null, "e": 1263, "s": 1171, "text": "mysql> create table DemoTable\n(\n Name varchar(20)\n);\nQuery OK, 0 rows affected (0.55 sec)" }, { "code": null, "e": 1344, "s": 1263, "text": "Following is the query to insert some records in the table using insert command:" }, { "code": null, "e": 2320, "s": 1344, "text": "mysql> insert into DemoTable values('Larry');\nQuery OK, 1 row affected (0.13 sec)\nmysql> insert into DemoTable values('Larry');\nQuery OK, 1 row affected (0.11 sec)\nmysql> insert into DemoTable values('Sam');\nQuery OK, 1 row affected (0.14 sec)\nmysql> insert into DemoTable values('Chris');\nQuery OK, 1 row affected (0.14 sec)\nmysql> insert into DemoTable values('Sam');\nQuery OK, 1 row affected (0.12 sec)\nmysql> insert into DemoTable values('Mike');\nQuery OK, 1 row affected (0.13 sec)\nmysql> insert into DemoTable values('Sam');\nQuery OK, 1 row affected (0.11 sec)\nmysql> insert into DemoTable values('Larry');\nQuery OK, 1 row affected (0.21 sec)\nmysql> insert into DemoTable values('Mike');\nQuery OK, 1 row affected (0.32 sec)\nmysql> insert into DemoTable values('Mike');\nQuery OK, 1 row affected (0.16 sec)\nmysql> insert into DemoTable values('Carol');\nQuery OK, 1 row affected (0.27 sec)\nmysql> insert into DemoTable values('Robert');\nQuery OK, 1 row affected (0.27 sec)" }, { "code": null, "e": 2399, "s": 2320, "text": "Following is the query to display records from the table using select command:" }, { "code": null, "e": 2430, "s": 2399, "text": "mysql> select *from DemoTable;" }, { "code": null, "e": 2469, "s": 2430, "text": "This will produce the following output" }, { "code": null, "e": 2649, "s": 2469, "text": "+--------+\n| Name |\n+--------+\n| Larry |\n| Larry |\n| Sam |\n| Chris |\n| Sam |\n| Mike |\n| Sam |\n| Larry |\n| Mike |\n| Mike |\n| Carol |\n| Robert |\n+--------+\n12 rows in set (0.00 sec)" }, { "code": null, "e": 2799, "s": 2649, "text": "Following is the query to count the values that only appear once in a column i.e. the count of the\nnames that appears only once in the “Name” column:" }, { "code": null, "e": 2929, "s": 2799, "text": "mysql> SELECT COUNT(Name)\nFROM (\n SELECT Name\n FROM DemoTable\n GROUP BY Name\n HAVING COUNT(*) = 1\n) AS APPEAR_FIRST_TIME;" }, { "code": null, "e": 2968, "s": 2929, "text": "This will produce the following output" }, { "code": null, "e": 3072, "s": 2968, "text": "+-------------+\n| COUNT(Name) |\n+-------------+\n| 3 |\n+-------------+\n1 row in set (0.00 sec)" } ]
Geek collects the balls | Practice | GeeksforGeeks
There are two parallel roads, each containing N and M buckets, respectively. Each bucket may contain some balls. The balls in first road are given in an array a and balls in the second road in an array b. The buckets on both roads are kept in such a way that they are sorted according to the number of balls in them. Geek starts from the end of the road which has the bucket with a lower number of balls(i.e. if buckets are sorted in increasing order, then geek will start from the left side of the road). Geek can change the road only at a point of intersection i.e. a point where buckets have the same number of balls on two roads. Help Geek collect the maximum number of balls. Example 1: Input: N = 5, M = 5 a[] = {1, 4, 5, 6, 8} b[] = {2, 3, 4, 6, 9} Output: 29 Explanation: The optimal way to get the maximum number of balls is to start from road 2. Get 2+3. Then switch at intersection point 4. Get 4+5+6. Then switch at intersection point 6. Get 9. Total = 2+3+4+5+6+9 = 29. Example 2: Input: N = 3, M = 3 a[] = {1, 2, 3} b[] = {4, 5, 6} Output: 15 Your Task: You do not need to read input or print anything. Your task is to complete the function maxBalls() which takes N, M, a[] and b[] as input parameters and returns the maximum number of balls that can be collected. Expected Time Complexity: O(N+M) Expected Auxililary Space: O(1) Constraints: 1 ≤ N, M ≤ 103 1 ≤ a[i], b[i] ≤ 106 0 abhisheksinghyadav05052 weeks ago I have written my code in python and I am not able to pass this test case: Possibly your code doesn't work correctly for multiple test-cases (TCs).The first test case where your code failed:Test Cases Passed: 1 / 23Input: 6 6 1 8 8 9 11 12 6 6 8 9 10 14 And Your Code's output is: 53 Its Correct output is: 61 can somebody plzz help me with this.. My Python code's link: https://practice.geeksforgeeks.org/viewSol.php?subId=963fe3930e4108e165d2151383c7c653&pid=705421&user=abhisheksinghyadav0505 0 arghasahu1 month ago My clean Java code with Greedy approach,int maxBalls(int n, int m, int[] a, int[] b) { int i = 0,j = 0, s1 = 0, s2 = 0, c1, c2; while(i < n && j < m) { if (a[i] < b[j]) { s1 += a[i++]; } else if (a[i] > b[j]) { s2 += b[j++]; } else { int x = a[i], oldS1 = s1, oldS2 = s2; for (c1 = 0; i < n && a[i] == x; ++c1, ++i); for (c2 = 0; j < m && b[j] == x; ++c2, ++j); s1 = oldS1 + ((c1 > 1 && c2 > 1)? (c1 + c2 - 2) * x: c1 * x); s1 = Math.max(s1, oldS2 + (c1 + c2 - 1) * x); s2 = oldS2 + ((c1 > 1 && c2 > 1)? (c1 + c2 - 2) * x: c2 * x); s2 = Math.max(s2, oldS1 + (c1 + c2 - 1) * x); } } for (; i < n; ++i) { s1 += a[i]; } for (; j < m; ++j) { s2 += b[j]; } return Math.max(s1, s2); } +1 smartsuman252 months ago My C++ code for greedy approach: int maxBalls(int n, int m, vector<int> a, vector<int> b){ int i=0,j=0; int s1=0,s2=0; sort(a.begin(),a.end()); sort(b.begin(),b.end()); while(i<n || j<m){ if(i<n && j<m){ if(a[i]<b[j]){ s1 += a[i]; i++; } else if(a[i]>b[j]){ s2 += b[j]; j++; } else { int x = a[i]; int c1 = 0,c2 = 0; while(a[i++]==x)c1++; while(b[j++]==x)c2++; i--,j--; if(s1>s2){ s2 = s1 + (c1+c2-1)*x; if(c1>1)s1 += (c1+c2-2)*x; else s1 += x; } else{ s1 = s2 + (c1 + c2 -1)*x; if(c2>1)s2 += (c1+c2-2)*x; else s2 += x; } } } else if(i<n){ s1 += a[i]; i++; } else if(j<m){ s2 += b[j]; j++; } } return max(s1,s2); } -1 shivam1706206 months ago Static int maxBalls(int N, int M, int a[], int b[]) { // code here int n=N; int m=M; long first=0,second=0; int res=0; int i=0,j=0; while(i<n&& j<m) { if(a[i]<b[j]){ first+=a[i++]; } else if(a[i]>b[j]) { second+=b[j++]; } else { res+=Math.max(first,second)+a[i]; first=0; second=0; int temp=a[i]; ++i; temp=b[j]; ++j; while(i<n && a[i]==temp) res+=a[i++]; while(j<m && b[j]==temp) res+=b[j++]; } } while(i<n) { first+=a[i++]; } while(j<m) { second+=b[j++]; } res+=Math.max(first,second); return res; } -2 shivam1706206 months ago int asum=0; int bsum=0; int i=0; int j=0; int ans=0; int m=M; int n=N; while(i<n && j<m) { while((i+1)<n && a[i]==a[i+1]) { asum+=a[i]; i++; } while((j+1)<m && b[j]==b[j+1]) { bsum+=b[j]; j++; } if(a[i]==b[j]) { ans+=max(asum,bsum)+a[i]; i++; j++; asum=0; bsum=0; } else { if(a[i]<b[j]) { asum+=a[i]; i++; } else { bsum+=b[j]; j++; } } } for(;i<n;i++) { asum+=a[i]; } for(;j<m;j++) { bsum+=b[j]; } ans+=max(asum,bsum); return ans; } 0 shivam1706206 months ago whats wrong with the solution int maxBalls(int N, int M, vector<int> a, vector<int> b){ // code here int sum1=0; int sum2=0; int l1=0; int l2=0; int ans=0; while(l1<N && l2<M) { while( (l1+1)<N && a[l1]==a[l1+1] ) { sum1+=a[l1]; l1++; } while( (l2+1)<M && b[l2]==b[l2+1] ) { sum2+=b[l2]; l2++; } if(a[l1]==b[l2]) { ans+=max(sum1,sum2); ans+=a[l1]; l1++; l2++; sum1=0; sum2=0; } else { if(a[l1]<b[l2]) { sum1+=a[l1]; l1++; } else { if(a[l1]>b[l2]) { sum2+=b[l2]; l2++; } } } } while(l1<N) { sum1+=a[l1]; l1++; } while(l2<M) { sum2+=b[l2]; l2++; } ans+=max(sum1,sum2); return ans; } 0 Rishabh saxena8 months ago Rishabh saxena 6 61 8 8 9 11 126 6 8 9 10 14how its correct answer is 61, I think its should be 53. -1 ANAS MALVAT8 months ago ANAS MALVAT int i = 0; int j = 0; int cnt1 = 0; int cnt2 = 0; int ret = 0; while(i < l1 and j < l2) { if(A[i] == B[j]) { int chk = A[i]; while(A[i] == chk and i < l1) { cnt1 += A[i++]; } while(B[j] == chk and j < l2) { cnt2 += B[j++]; } ret += max(cnt1,cnt2); cnt1 = 0; cnt2 = 0; } else if(A[i] < B[j]){ cnt1 += A[i++]; } else if(B[j] < A[i]){ cnt2 += B[j++]; } } while(i < l1) { cnt1 += A[i++]; } while(j < l2) { cnt2 += B[j++]; } return ret + max(cnt1,cnt2); } 0 Swathi Kedarasetty9 months ago Swathi Kedarasetty My AC code in C++. Similar to merge procedure in merge sort. 0 Swathi Kedarasetty This comment was deleted. 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": 907, "s": 226, "text": "There are two parallel roads, each containing N and M buckets, respectively. Each bucket may contain some balls. The balls in first road are given in an array a and balls in the second road in an array b. The buckets on both roads are kept in such a way that they are sorted according to the number of balls in them. Geek starts from the end of the road which has the bucket with a lower number of balls(i.e. if buckets are sorted in increasing order, then geek will start from the left side of the road).\nGeek can change the road only at a point of intersection i.e. a point where buckets have the same number of balls on two roads. Help Geek collect the maximum number of balls." }, { "code": null, "e": 920, "s": 909, "text": "Example 1:" }, { "code": null, "e": 1215, "s": 920, "text": "Input: \nN = 5, M = 5\na[] = {1, 4, 5, 6, 8}\nb[] = {2, 3, 4, 6, 9}\nOutput: 29\nExplanation: The optimal way to get the \nmaximum number of balls is to start from \nroad 2. Get 2+3. Then switch at intersection \npoint 4. Get 4+5+6. Then switch at intersection\npoint 6. Get 9. Total = 2+3+4+5+6+9 = 29." }, { "code": null, "e": 1226, "s": 1215, "text": "Example 2:" }, { "code": null, "e": 1290, "s": 1226, "text": "Input:\nN = 3, M = 3\na[] = {1, 2, 3}\nb[] = {4, 5, 6}\nOutput: 15\n" }, { "code": null, "e": 1515, "s": 1292, "text": "\nYour Task:\nYou do not need to read input or print anything. Your task is to complete the function maxBalls() which takes N, M, a[] and b[] as input parameters and returns the maximum number of balls that can be collected." }, { "code": null, "e": 1582, "s": 1517, "text": "Expected Time Complexity: O(N+M)\nExpected Auxililary Space: O(1)" }, { "code": null, "e": 1635, "s": 1584, "text": "Constraints:\n1 ≤ N, M ≤ 103\n1 ≤ a[i], b[i] ≤ 106 " }, { "code": null, "e": 1637, "s": 1635, "text": "0" }, { "code": null, "e": 1671, "s": 1637, "text": "abhisheksinghyadav05052 weeks ago" }, { "code": null, "e": 1746, "s": 1671, "text": "I have written my code in python and I am not able to pass this test case:" }, { "code": null, "e": 1895, "s": 1746, "text": "Possibly your code doesn't work correctly for multiple test-cases (TCs).The first test case where your code failed:Test Cases Passed: 1 / 23Input: " }, { "code": null, "e": 1900, "s": 1895, "text": "6 6 " }, { "code": null, "e": 1914, "s": 1900, "text": "1 8 8 9 11 12" }, { "code": null, "e": 1929, "s": 1914, "text": " 6 6 8 9 10 14" }, { "code": null, "e": 1957, "s": 1929, "text": "And Your Code's output is: " }, { "code": null, "e": 1960, "s": 1957, "text": "53" }, { "code": null, "e": 1984, "s": 1960, "text": "Its Correct output is: " }, { "code": null, "e": 1987, "s": 1984, "text": "61" }, { "code": null, "e": 2025, "s": 1987, "text": "can somebody plzz help me with this.." }, { "code": null, "e": 2049, "s": 2025, "text": "My Python code's link: " }, { "code": null, "e": 2174, "s": 2049, "text": "https://practice.geeksforgeeks.org/viewSol.php?subId=963fe3930e4108e165d2151383c7c653&pid=705421&user=abhisheksinghyadav0505" }, { "code": null, "e": 2176, "s": 2174, "text": "0" }, { "code": null, "e": 2197, "s": 2176, "text": "arghasahu1 month ago" }, { "code": null, "e": 2691, "s": 2197, "text": "My clean Java code with Greedy approach,int maxBalls(int n, int m, int[] a, int[] b) { int i = 0,j = 0, s1 = 0, s2 = 0, c1, c2; while(i < n && j < m) { if (a[i] < b[j]) { s1 += a[i++]; } else if (a[i] > b[j]) { s2 += b[j++]; } else { int x = a[i], oldS1 = s1, oldS2 = s2; for (c1 = 0; i < n && a[i] == x; ++c1, ++i); for (c2 = 0; j < m && b[j] == x; ++c2, ++j);" }, { "code": null, "e": 3148, "s": 2691, "text": " s1 = oldS1 + ((c1 > 1 && c2 > 1)? (c1 + c2 - 2) * x: c1 * x); s1 = Math.max(s1, oldS2 + (c1 + c2 - 1) * x); s2 = oldS2 + ((c1 > 1 && c2 > 1)? (c1 + c2 - 2) * x: c2 * x); s2 = Math.max(s2, oldS1 + (c1 + c2 - 1) * x); } } for (; i < n; ++i) { s1 += a[i]; } for (; j < m; ++j) { s2 += b[j]; } return Math.max(s1, s2); }" }, { "code": null, "e": 3151, "s": 3148, "text": "+1" }, { "code": null, "e": 3176, "s": 3151, "text": "smartsuman252 months ago" }, { "code": null, "e": 3209, "s": 3176, "text": "My C++ code for greedy approach:" }, { "code": null, "e": 4510, "s": 3211, "text": "int maxBalls(int n, int m, vector<int> a, vector<int> b){\n int i=0,j=0;\n int s1=0,s2=0;\n sort(a.begin(),a.end());\n sort(b.begin(),b.end());\n while(i<n || j<m){\n if(i<n && j<m){\n if(a[i]<b[j]){\n s1 += a[i];\n i++;\n }\n else if(a[i]>b[j]){\n s2 += b[j];\n j++;\n }\n else {\n int x = a[i];\n int c1 = 0,c2 = 0;\n while(a[i++]==x)c1++;\n while(b[j++]==x)c2++;\n i--,j--;\n \n if(s1>s2){\n s2 = s1 + (c1+c2-1)*x;\n if(c1>1)s1 += (c1+c2-2)*x;\n else s1 += x;\n }\n else{\n s1 = s2 + (c1 + c2 -1)*x;\n if(c2>1)s2 += (c1+c2-2)*x;\n else s2 += x;\n }\n }\n }\n else if(i<n){\n s1 += a[i];\n i++;\n }\n else if(j<m){\n s2 += b[j];\n j++;\n }\n }\n return max(s1,s2);\n }" }, { "code": null, "e": 4513, "s": 4510, "text": "-1" }, { "code": null, "e": 4538, "s": 4513, "text": "shivam1706206 months ago" }, { "code": null, "e": 5364, "s": 4538, "text": "Static int maxBalls(int N, int M, int a[], int b[]) { // code here int n=N; int m=M; long first=0,second=0; int res=0; int i=0,j=0; while(i<n&& j<m) { if(a[i]<b[j]){ first+=a[i++]; } else if(a[i]>b[j]) { second+=b[j++]; } else { res+=Math.max(first,second)+a[i]; first=0; second=0; int temp=a[i]; ++i; temp=b[j]; ++j; while(i<n && a[i]==temp) res+=a[i++]; while(j<m && b[j]==temp) res+=b[j++]; } } while(i<n) { first+=a[i++]; } while(j<m) { second+=b[j++]; } res+=Math.max(first,second); return res; }" }, { "code": null, "e": 5367, "s": 5364, "text": "-2" }, { "code": null, "e": 5392, "s": 5367, "text": "shivam1706206 months ago" }, { "code": null, "e": 6385, "s": 5392, "text": " int asum=0; int bsum=0; int i=0; int j=0; int ans=0; int m=M; int n=N; while(i<n && j<m) { while((i+1)<n && a[i]==a[i+1]) { asum+=a[i]; i++; } while((j+1)<m && b[j]==b[j+1]) { bsum+=b[j]; j++; } if(a[i]==b[j]) { ans+=max(asum,bsum)+a[i]; i++; j++; asum=0; bsum=0; } else { if(a[i]<b[j]) { asum+=a[i]; i++; } else { bsum+=b[j]; j++; } } } for(;i<n;i++) { asum+=a[i]; } for(;j<m;j++) { bsum+=b[j]; } ans+=max(asum,bsum); return ans; }" }, { "code": null, "e": 6387, "s": 6385, "text": "0" }, { "code": null, "e": 6412, "s": 6387, "text": "shivam1706206 months ago" }, { "code": null, "e": 6442, "s": 6412, "text": "whats wrong with the solution" }, { "code": null, "e": 7745, "s": 6444, "text": " int maxBalls(int N, int M, vector<int> a, vector<int> b){ // code here int sum1=0; int sum2=0; int l1=0; int l2=0; int ans=0; while(l1<N && l2<M) { while( (l1+1)<N && a[l1]==a[l1+1] ) { sum1+=a[l1]; l1++; } while( (l2+1)<M && b[l2]==b[l2+1] ) { sum2+=b[l2]; l2++; } if(a[l1]==b[l2]) { ans+=max(sum1,sum2); ans+=a[l1]; l1++; l2++; sum1=0; sum2=0; } else { if(a[l1]<b[l2]) { sum1+=a[l1]; l1++; } else { if(a[l1]>b[l2]) { sum2+=b[l2]; l2++; } } } } while(l1<N) { sum1+=a[l1]; l1++; } while(l2<M) { sum2+=b[l2]; l2++; } ans+=max(sum1,sum2); return ans; } " }, { "code": null, "e": 7747, "s": 7745, "text": "0" }, { "code": null, "e": 7774, "s": 7747, "text": "Rishabh saxena8 months ago" }, { "code": null, "e": 7789, "s": 7774, "text": "Rishabh saxena" }, { "code": null, "e": 7874, "s": 7789, "text": "6 61 8 8 9 11 126 6 8 9 10 14how its correct answer is 61, I think its should be 53." }, { "code": null, "e": 7877, "s": 7874, "text": "-1" }, { "code": null, "e": 7901, "s": 7877, "text": "ANAS MALVAT8 months ago" }, { "code": null, "e": 7913, "s": 7901, "text": "ANAS MALVAT" }, { "code": null, "e": 8633, "s": 7913, "text": " int i = 0; int j = 0; int cnt1 = 0; int cnt2 = 0; int ret = 0; while(i < l1 and j < l2) { if(A[i] == B[j]) { int chk = A[i]; while(A[i] == chk and i < l1) { cnt1 += A[i++]; } while(B[j] == chk and j < l2) { cnt2 += B[j++]; } ret += max(cnt1,cnt2); cnt1 = 0; cnt2 = 0; } else if(A[i] < B[j]){ cnt1 += A[i++]; } else if(B[j] < A[i]){ cnt2 += B[j++]; } } while(i < l1) { cnt1 += A[i++]; } while(j < l2) { cnt2 += B[j++]; } return ret + max(cnt1,cnt2); }" }, { "code": null, "e": 8635, "s": 8633, "text": "0" }, { "code": null, "e": 8666, "s": 8635, "text": "Swathi Kedarasetty9 months ago" }, { "code": null, "e": 8685, "s": 8666, "text": "Swathi Kedarasetty" }, { "code": null, "e": 8746, "s": 8685, "text": "My AC code in C++. Similar to merge procedure in merge sort." }, { "code": null, "e": 8748, "s": 8746, "text": "0" }, { "code": null, "e": 8767, "s": 8748, "text": "Swathi Kedarasetty" }, { "code": null, "e": 8793, "s": 8767, "text": "This comment was deleted." }, { "code": null, "e": 8939, "s": 8793, "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": 8975, "s": 8939, "text": " Login to access your submissions. " }, { "code": null, "e": 8985, "s": 8975, "text": "\nProblem\n" }, { "code": null, "e": 8995, "s": 8985, "text": "\nContest\n" }, { "code": null, "e": 9058, "s": 8995, "text": "Reset the IDE using the second button on the top right corner." }, { "code": null, "e": 9206, "s": 9058, "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": 9414, "s": 9206, "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": 9520, "s": 9414, "text": "You can access the hints to get an idea about what is expected of you as well as the final solution code." } ]
HashMap containsValue() Method in Java - GeeksforGeeks
20 Sep, 2019 The java.util.HashMap.containsValue() method is used to check whether a particular value is being mapped by a single or more than one key in the HashMap. It takes the Value as a parameter and returns True if that value is mapped by any of the key in the map. Syntax: Hash_Map.containsValue(Object Value) Parameters: The method takes just one parameter Value of Object type and refers to the value whose mapping is supposed to be checked by any key inside the map. Return Value: The method returns boolean true if the mapping of the value is detected else false. Below programs are used to illustrate the working of java.util.HashMap.containsValue() Method:Program 1: Mapping String Values to Integer Keys. // Java code to illustrate the containsValue() methodimport java.util.*; public class Hash_Map_Demo { public static void main(String[] args) { // Creating an empty HashMap HashMap<Integer, String> hash_map = new HashMap<Integer, String>(); // Mapping string values to int keys hash_map.put(10, "Geeks"); hash_map.put(15, "4"); hash_map.put(20, "Geeks"); hash_map.put(25, "Welcomes"); hash_map.put(30, "You"); // Displaying the HashMap System.out.println("Initial Mappings are: " + hash_map); // Checking for the Value 'Geeks' System.out.println("Is the value 'Geeks' present? " + hash_map.containsValue("Geeks")); // Checking for the Value 'World' System.out.println("Is the value 'World' present? " + hash_map.containsValue("World")); }} Initial Mappings are: {20=Geeks, 25=Welcomes, 10=Geeks, 30=You, 15=4} Is the value 'Geeks' present? true Is the value 'World' present? false Program 2: Mapping Integer Values to String Keys. // Java code to illustrate the containsValue() methodimport java.util.*; public class Hash_Map_Demo { public static void main(String[] args) { // Creating an empty HashMap HashMap<String, Integer> hash_map = new HashMap<String, Integer>(); // Mapping int values to string keys hash_map.put("Geeks", 10); hash_map.put("4", 15); hash_map.put("Geeks", 20); hash_map.put("Welcomes", 25); hash_map.put("You", 30); // Displaying the HashMap System.out.println("Initial Mappings are: " + hash_map); // Checking for the Value '10' System.out.println("Is the value '10' present? " + hash_map.containsValue(10)); // Checking for the Value '30' System.out.println("Is the value '30' present? " + hash_map.containsValue(30)); // Checking for the Value '40' System.out.println("Is the value '40' present? " + hash_map.containsValue(40)); }} Initial Mappings are: {4=15, Geeks=20, You=30, Welcomes=25} Is the value '10' present? false Is the value '30' present? true Is the value '40' present? false Time Complexity : O(n) Note: The same operation can be performed with any type of Mappings with variation and combination of different data types. Java - util package Java-Collections Java-Functions Java-HashMap Java Java Java-Collections Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Interfaces in Java ArrayList in Java Initialize an ArrayList in Java Singleton Class in Java Overriding in Java Collections in Java Multithreading in Java LinkedList in Java Stream In Java Multidimensional Arrays in Java
[ { "code": null, "e": 24275, "s": 24247, "text": "\n20 Sep, 2019" }, { "code": null, "e": 24534, "s": 24275, "text": "The java.util.HashMap.containsValue() method is used to check whether a particular value is being mapped by a single or more than one key in the HashMap. It takes the Value as a parameter and returns True if that value is mapped by any of the key in the map." }, { "code": null, "e": 24542, "s": 24534, "text": "Syntax:" }, { "code": null, "e": 24579, "s": 24542, "text": "Hash_Map.containsValue(Object Value)" }, { "code": null, "e": 24739, "s": 24579, "text": "Parameters: The method takes just one parameter Value of Object type and refers to the value whose mapping is supposed to be checked by any key inside the map." }, { "code": null, "e": 24837, "s": 24739, "text": "Return Value: The method returns boolean true if the mapping of the value is detected else false." }, { "code": null, "e": 24981, "s": 24837, "text": "Below programs are used to illustrate the working of java.util.HashMap.containsValue() Method:Program 1: Mapping String Values to Integer Keys." }, { "code": "// Java code to illustrate the containsValue() methodimport java.util.*; public class Hash_Map_Demo { public static void main(String[] args) { // Creating an empty HashMap HashMap<Integer, String> hash_map = new HashMap<Integer, String>(); // Mapping string values to int keys hash_map.put(10, \"Geeks\"); hash_map.put(15, \"4\"); hash_map.put(20, \"Geeks\"); hash_map.put(25, \"Welcomes\"); hash_map.put(30, \"You\"); // Displaying the HashMap System.out.println(\"Initial Mappings are: \" + hash_map); // Checking for the Value 'Geeks' System.out.println(\"Is the value 'Geeks' present? \" + hash_map.containsValue(\"Geeks\")); // Checking for the Value 'World' System.out.println(\"Is the value 'World' present? \" + hash_map.containsValue(\"World\")); }}", "e": 25854, "s": 24981, "text": null }, { "code": null, "e": 25996, "s": 25854, "text": "Initial Mappings are: {20=Geeks, 25=Welcomes, 10=Geeks, 30=You, 15=4}\nIs the value 'Geeks' present? true\nIs the value 'World' present? false\n" }, { "code": null, "e": 26046, "s": 25996, "text": "Program 2: Mapping Integer Values to String Keys." }, { "code": "// Java code to illustrate the containsValue() methodimport java.util.*; public class Hash_Map_Demo { public static void main(String[] args) { // Creating an empty HashMap HashMap<String, Integer> hash_map = new HashMap<String, Integer>(); // Mapping int values to string keys hash_map.put(\"Geeks\", 10); hash_map.put(\"4\", 15); hash_map.put(\"Geeks\", 20); hash_map.put(\"Welcomes\", 25); hash_map.put(\"You\", 30); // Displaying the HashMap System.out.println(\"Initial Mappings are: \" + hash_map); // Checking for the Value '10' System.out.println(\"Is the value '10' present? \" + hash_map.containsValue(10)); // Checking for the Value '30' System.out.println(\"Is the value '30' present? \" + hash_map.containsValue(30)); // Checking for the Value '40' System.out.println(\"Is the value '40' present? \" + hash_map.containsValue(40)); }}", "e": 27030, "s": 26046, "text": null }, { "code": null, "e": 27189, "s": 27030, "text": "Initial Mappings are: {4=15, Geeks=20, You=30, Welcomes=25}\nIs the value '10' present? false\nIs the value '30' present? true\nIs the value '40' present? false\n" }, { "code": null, "e": 27212, "s": 27189, "text": "Time Complexity : O(n)" }, { "code": null, "e": 27336, "s": 27212, "text": "Note: The same operation can be performed with any type of Mappings with variation and combination of different data types." }, { "code": null, "e": 27356, "s": 27336, "text": "Java - util package" }, { "code": null, "e": 27373, "s": 27356, "text": "Java-Collections" }, { "code": null, "e": 27388, "s": 27373, "text": "Java-Functions" }, { "code": null, "e": 27401, "s": 27388, "text": "Java-HashMap" }, { "code": null, "e": 27406, "s": 27401, "text": "Java" }, { "code": null, "e": 27411, "s": 27406, "text": "Java" }, { "code": null, "e": 27428, "s": 27411, "text": "Java-Collections" }, { "code": null, "e": 27526, "s": 27428, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 27535, "s": 27526, "text": "Comments" }, { "code": null, "e": 27548, "s": 27535, "text": "Old Comments" }, { "code": null, "e": 27567, "s": 27548, "text": "Interfaces in Java" }, { "code": null, "e": 27585, "s": 27567, "text": "ArrayList in Java" }, { "code": null, "e": 27617, "s": 27585, "text": "Initialize an ArrayList in Java" }, { "code": null, "e": 27641, "s": 27617, "text": "Singleton Class in Java" }, { "code": null, "e": 27660, "s": 27641, "text": "Overriding in Java" }, { "code": null, "e": 27680, "s": 27660, "text": "Collections in Java" }, { "code": null, "e": 27703, "s": 27680, "text": "Multithreading in Java" }, { "code": null, "e": 27722, "s": 27703, "text": "LinkedList in Java" }, { "code": null, "e": 27737, "s": 27722, "text": "Stream In Java" } ]
How to install Selenium WebDriver on Mac OS?
We can install Selenium on Mac OS. We shall take the help of Homebrew package manager for installation in Mac OS. Let us follow the step by step process − Install Selenium by running the command − Install Selenium by running the command − pip install selenium Install the Chrome driver with the homebrew by running the command − Install the Chrome driver with the homebrew by running the command − brew cask install chromedriver Verify the version of the Chrome driver, by running the command − Verify the version of the Chrome driver, by running the command − chromedriver −−version Create a test script and try to execute after save. Create a test script and try to execute after save. from selenium import webdriver # driver initialization driver = webdriver.Chrome(executable_path="C:\\chromedriver.exe") # launch URL driver.get("https://www.tutorialspoint.com/index.htm") If the below error is triggered − If the below error is triggered − unknown error: cannot find chrome binary It means the version of the Chrome driver is not compatible with the Chrome browser version we are using. We have to uninstall the Chrome and then downgrade or upgrade the browser as per the driver we have.
[ { "code": null, "e": 1217, "s": 1062, "text": "We can install Selenium on Mac OS. We shall take the help of Homebrew package manager for installation in Mac OS. Let us follow the step by step process −" }, { "code": null, "e": 1259, "s": 1217, "text": "Install Selenium by running the command −" }, { "code": null, "e": 1301, "s": 1259, "text": "Install Selenium by running the command −" }, { "code": null, "e": 1322, "s": 1301, "text": "pip install selenium" }, { "code": null, "e": 1391, "s": 1322, "text": "Install the Chrome driver with the homebrew by running the command −" }, { "code": null, "e": 1460, "s": 1391, "text": "Install the Chrome driver with the homebrew by running the command −" }, { "code": null, "e": 1491, "s": 1460, "text": "brew cask install chromedriver" }, { "code": null, "e": 1557, "s": 1491, "text": "Verify the version of the Chrome driver, by running the command −" }, { "code": null, "e": 1623, "s": 1557, "text": "Verify the version of the Chrome driver, by running the command −" }, { "code": null, "e": 1646, "s": 1623, "text": "chromedriver −−version" }, { "code": null, "e": 1698, "s": 1646, "text": "Create a test script and try to execute after save." }, { "code": null, "e": 1750, "s": 1698, "text": "Create a test script and try to execute after save." }, { "code": null, "e": 1939, "s": 1750, "text": "from selenium import webdriver\n# driver initialization\ndriver = webdriver.Chrome(executable_path=\"C:\\\\chromedriver.exe\")\n# launch URL\ndriver.get(\"https://www.tutorialspoint.com/index.htm\")" }, { "code": null, "e": 1973, "s": 1939, "text": "If the below error is triggered −" }, { "code": null, "e": 2007, "s": 1973, "text": "If the below error is triggered −" }, { "code": null, "e": 2048, "s": 2007, "text": "unknown error: cannot find chrome binary" }, { "code": null, "e": 2255, "s": 2048, "text": "It means the version of the Chrome driver is not compatible with the Chrome browser version we are using. We have to uninstall the Chrome and then downgrade or upgrade the browser as per the driver we have." } ]
C# program to display factors of entered number
Firstly, enter the number for which you want the factors − Console.WriteLine("Enter the Number:"); n = int.Parse(Console.ReadLine()); After that, loop through to find the factors − for (i = 1; i <= n; i++) { if (n % i == 0) { Console.WriteLine(i); } } You can try to run the following code to display factors of a number − using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace Demo { class ApplicationOne { static void Main(string[] args) { int n, i; Console.WriteLine("Enter the Number:"); n = int.Parse(Console.ReadLine()); Console.WriteLine("Factors:"); for (i = 1; i <= n; i++) { if (n % i == 0) { Console.WriteLine(i); } } Console.ReadLine(); } } }
[ { "code": null, "e": 1121, "s": 1062, "text": "Firstly, enter the number for which you want the factors −" }, { "code": null, "e": 1196, "s": 1121, "text": "Console.WriteLine(\"Enter the Number:\");\nn = int.Parse(Console.ReadLine());" }, { "code": null, "e": 1243, "s": 1196, "text": "After that, loop through to find the factors −" }, { "code": null, "e": 1326, "s": 1243, "text": "for (i = 1; i <= n; i++) {\n if (n % i == 0) {\n Console.WriteLine(i);\n }\n}" }, { "code": null, "e": 1397, "s": 1326, "text": "You can try to run the following code to display factors of a number −" }, { "code": null, "e": 1890, "s": 1397, "text": "using System;\nusing System.Collections.Generic;\nusing System.Linq;\nusing System.Text;\nnamespace Demo {\n class ApplicationOne {\n static void Main(string[] args) {\n int n, i;\n Console.WriteLine(\"Enter the Number:\");\n n = int.Parse(Console.ReadLine());\n Console.WriteLine(\"Factors:\");\n for (i = 1; i <= n; i++) {\n if (n % i == 0) {\n Console.WriteLine(i);\n }\n }\n Console.ReadLine();\n }\n }\n}" } ]
Build a DFA to accept Binary strings that starts or ends with "01" - GeeksforGeeks
26 Nov, 2021 Given binary string str, the task is to build a DFA that accepts the string if the string either starts with “01” or ends with “01”. Input: str = “010000” Output: Accepted Explanation: The given string starts with “01”. Input: str = “1100111” Output: Not Accepted Explanation: The given string neither starts with nor ends with “01”. DFA or Deterministic Finite Automata is a finite state machine that accepts a string(under some specific condition) if it reaches a final state, otherwise rejects it.In DFA, there is no concept of memory, therefore we have to check the string character by character, beginning with the 0th character. The input set of characters for the problem is {0, 1}. For a DFA to be valid, there must a transition rule defined for each symbol of the input set at every state to a valid state. Therefore, the following steps are followed to design the DFA: In this case, the strings that start with 01 or end with 01 or both start with 01 and end with 01 should be acceptable. Make an initial state and transit its input alphabets, i.e, 0 and 1 to two different states. Check for acceptance of string after each transition to ignore errors. First, make DfA for minimum length string then go ahead step by step. Define Final State(s) according to the acceptance of string. Step by Step Approach to design a DFA: Step 1: Make an initial state “A”. The minimum possible string is 01 which is acceptable. For this, make the transition of 0 from state “A” to state “B” and then make the transition of 1 from state “B” to state “C” and notice this state “C” as the final state. Step 2: Now, we have designed the DFA that start with 01. To accept all the strings that start with 01 like 011, 010, 010000, 01111, 010101000010001 etc, we need to put a self-loop of 0 and 1 to the state “C”. This self-loop contains all combination of 0 and 1. Step 3: Now, we need to think about the string that ends with “01”. We have done transition of 0 of state “A”, then with input 1 of the state “A”. With this minimum possible string that ends with 01 is 101. For this, do the transition of input 1 of state “A” to state “D” then do the transition of input 0 from the state “D” to state “E” and then do the transition of input 1 from state “E” to state “F” and notice this “F” state as the final state. Step 4: There is one more possibility that any number of 1’s comes in beginning and then end with 01. For this, make a self-loop of 1 on state “D” and any number of zeros can come before 1 that comes in the end. For this, put a self-loop of 0 and state “E”. Step 5: Till now we have done with the strings that start with 1 and end with 01. Now, we need to think about the string that starts with 0 and ends with 01. For this, make a transition of input 0 from state “B” to state “E”. Step 6: Now we are just left with the input alphabets of the state “F”. Transit input 1 from state “F” to state “D” and then make transit input 0 from state “F” to state “E”. Transition table and Transition rules of the above DFA: Below is the implementation of the above approach: C++ Java Python3 C# Javascript // C++ program to check if a string// either starts or ends with 01#include<bits/stdc++.h>using namespace std; void stateA(string);void stateB(string);void stateC(string);void stateD(string);void stateE(string);void stateF(string); // Function for transition// state Avoid checkstateA(string n){ // State transition to // B if the character is // 0 if(n[0] == '0') stateB(n.substr(1)); // State transition to // D if the character is // 1 else stateD(n.substr(1));} // Function for transition// state B void stateB(string n){ // Check if the string has // ended if (n.length() == 0) cout << "string not accepted"; else { // State transition to C // if the character is 1 if(n[0] == '1') stateC(n.substr(1)); // State transition to D // if the character is 0 else stateD(n.substr(1)); } } // Function for transition// state Cvoid stateC(string n){ cout << "String accepted";} // Function for transition// state Dvoid stateD(string n){ if (n.length() == 0) cout << "string not accepted"; else { // State transition to D // if the character is 1 if (n[0] == '1') stateD(n.substr(1)); // State transition to E // if the character is 0 else stateE(n.substr(1)); }} // Function for transition// state Evoid stateE(string n){ if (n.length() == 0) cout << "string not accepted"; else { // State transition to E // if the character is 0 if(n[0] == '0') stateE(n.substr(1)); // State transition to F // if the character is 1 else stateF(n.substr(1)); }} // Function for transition// state Fvoid stateF(string n){ if(n.length() == 0) cout << "string accepred"; else { // State transition to D // if the character is 1 if(n[0] == '1') stateD(n.substr(1)); // State transition to E // if the character is 0 else stateE(n.substr(1)); }} // Driver codeint main(){ string n = "0100101"; checkstateA(n); return 0;} // This code is contributed by chitranayal // Java program to check if a string// either starts or ends with 01import java.util.*; class GFG{ // Function for transition// state Astatic void checkstateA(String n){ // State transition to // B if the character is // 0 if (n.charAt(0) == '0') stateB(n.substring(1)); // State transition to // D if the character is // 1 else stateD(n.substring(1));} // Function for transition// state B static void stateB(String n){ // Check if the string has // ended if (n.length() == 0) System.out.println("string not accepted"); else { // State transition to C // if the character is 1 if (n.charAt(0) == '1') stateC(n.substring(1)); // State transition to D // if the character is 0 else stateD(n.substring(1)); } } // Function for transition// state Cstatic void stateC(String n){ System.out.println("String accepted");} // Function for transition// state Dstatic void stateD(String n){ if (n.length() == 0) System.out.println("string not accepted"); else { // State transition to D // if the character is 1 if (n.charAt(0) == '1') stateD(n.substring(1)); // State transition to E // if the character is 0 else stateE(n.substring(1)); }} // Function for transition// state Estatic void stateE(String n){ if (n.length() == 0) System.out.println("string not accepted"); else { // State transition to E // if the character is 0 if(n.charAt(0) == '0') stateE(n.substring(1)); // State transition to F // if the character is 1 else stateF(n.substring(1)); }} // Function for transition// state Fstatic void stateF(String n){ if (n.length() == 0) System.out.println("string accepred"); else { // State transition to D // if the character is 1 if (n.charAt(0) == '1') stateD(n.substring(1)); // State transition to E // if the character is 0 else stateE(n.substring(1)); }} // Driver Codepublic static void main(String args[]){ String n = "0100101"; checkstateA(n);}} // This code is contributed by jyoti369 # Python3 program to check if# a string either starts or# ends with 01 # Function for transition# state Adef checkstateA(n): # State transition to # B if the character is # 0 if(n[0]=='0'): stateB(n[1:]) # State transition to # D if the character is # 1 else: stateD(n[1:]) # Function for transition# state B def stateB(n): # Check if the string has # ended if (len(n)== 0): print("string not accepted") else: # State transition to C # if the character is 1 if(n[0]=='1'): stateC(n[1:]) # State transition to D # if the character is 0 else: stateD(n[1:]) # Function for transition# state C def stateC(n): print("String accepted") # Function for transition# state Ddef stateD(n): if (len(n)== 0): print("string not accepted") else: # State transition to D # if the character is 1 if (n[0]=='1'): stateD(n[1:]) # State transition to E # if the character is 0 else: stateE(n[1:]) # Function for transition# state Edef stateE(n): if (len(n)== 0): print("string not accepted") else: # State transition to E # if the character is 0 if(n[0]=='0'): stateE(n[1:]) # State transition to F # if the character is 1 else: stateF(n[1:]) # Function for transition# state Fdef stateF(n): if(len(n)== 0): print("string accepred") else: # State transition to D # if the character is 1 if(n[0]=='1'): stateD(n[1:]) # State transition to E # if the character is 0 else: stateE(n[1:]) # Driver codeif __name__ == "__main__": n = "0100101" checkstateA(n) // C# program to check if// a string either starts// or ends with 01using System;using System.Collections;using System.Collections.Generic;class GFG{ // Function for transition// state Astatic void checkstateA(string n){ // State transition to // B if the character is // 0 if(n[0] == '0') stateB(n.Substring(1)); // State transition to // D if the character is // 1 else stateD(n.Substring(1));} // Function for transition// state B static void stateB(string n){ // Check if the string has // ended if (n.Length == 0) { Console.Write("string not accepted"); } else { // State transition to C // if the character is 1 if(n[0] == '1') stateC(n.Substring(1)); // State transition to D // if the character is 0 else stateD(n.Substring(1)); } } // Function for transition// state Cstatic void stateC(string n){ Console.Write("string accepted");} // Function for transition// state Dstatic void stateD(string n){ if (n.Length == 0) Console.Write("string not accepted"); else { // State transition to D // if the character is 1 if (n[0] == '1') stateD(n.Substring(1)); // State transition to E // if the character is 0 else stateE(n.Substring(1)); }} // Function for transition// state Estatic void stateE(string n){ if (n.Length == 0) Console.Write("string not accepted"); else { // State transition to E // if the character is 0 if(n[0] == '0') stateE(n.Substring(1)); // State transition to F // if the character is 1 else stateF(n.Substring(1)); }} // Function for transition// state Fstatic void stateF(string n){ if(n.Length == 0) Console.Write("string accepted"); else { // State transition to D // if the character is 1 if(n[0] == '1') stateD(n.Substring(1)); // State transition to E // if the character is 0 else stateE(n.Substring(1)); }} // Driver codepublic static void Main(string []args){ string n = "0100101"; checkstateA(n);}} // This code is contributed by rutvik_56 <script> // JavaScript program to check if// a string either starts// or ends with 01 // Function for transition// state Afunction checkstateA(n){ // State transition to // B if the character is // 0 if(n[0] == '0') stateB(n.substr(1)); // State transition to // D if the character is // 1 else stateD(n.substr(1));} // Function for transition// state B function stateB(n){ // Check if the string has // ended if (n.length == 0) { document.write("string not accepted"); } else { // State transition to C // if the character is 1 if(n[0] == '1') stateC(n.substr(1)); // State transition to D // if the character is 0 else stateD(n.substr(1)); } } // Function for transition// state Cfunction stateC(n){ document.write("string accepted");} // Function for transition// state Dfunction stateD(n){ if (n.length == 0) Console.Write("string not accepted"); else { // State transition to D // if the character is 1 if (n[0] == '1') stateD(n.substr(1)); // State transition to E // if the character is 0 else stateE(n.substr(1)); }} // Function for transition// state Efunction stateE(n){ if (n.length == 0) document.write("string not accepted"); else { // State transition to E // if the character is 0 if(n[0] == '0') stateE(n.substr(1)); // State transition to F // if the character is 1 else stateF(n.substr(1)); }} // Function for transition// state Ffunction stateF(n){ if(n.length == 0) document.write("string accepted"); else { // State transition to D // if the character is 1 if(n[0] == '1') stateD(n.substr(1)); // State transition to E // if the character is 0 else stateE(n.substr(1)); }} // Driver Code let n = "0100101"; checkstateA(n); </script> String accepted Time Complexity: O(N)Auxiliary Space: O(N) ukasp rutvik_56 jyoti369 splevel62 pankajsharmagfg sumitgumber28 binary-string DFA Algorithms Articles Pattern Searching Strings Theory of Computation & Automata Strings Pattern Searching Algorithms Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments SDE SHEET - A Complete Guide for SDE Preparation DSA Sheet by Love Babbar Introduction to Algorithms Playfair Cipher with Examples How to write a Pseudo Code? Tree Traversals (Inorder, Preorder and Postorder) SQL | Join (Inner, Left, Right and Full Joins) find command in Linux with examples Analysis of Algorithms | Set 1 (Asymptotic Analysis) Mutex vs Semaphore
[ { "code": null, "e": 24820, "s": 24792, "text": "\n26 Nov, 2021" }, { "code": null, "e": 24954, "s": 24820, "text": "Given binary string str, the task is to build a DFA that accepts the string if the string either starts with “01” or ends with “01”. " }, { "code": null, "e": 25041, "s": 24954, "text": "Input: str = “010000” Output: Accepted Explanation: The given string starts with “01”." }, { "code": null, "e": 25156, "s": 25041, "text": "Input: str = “1100111” Output: Not Accepted Explanation: The given string neither starts with nor ends with “01”. " }, { "code": null, "e": 25701, "s": 25156, "text": "DFA or Deterministic Finite Automata is a finite state machine that accepts a string(under some specific condition) if it reaches a final state, otherwise rejects it.In DFA, there is no concept of memory, therefore we have to check the string character by character, beginning with the 0th character. The input set of characters for the problem is {0, 1}. For a DFA to be valid, there must a transition rule defined for each symbol of the input set at every state to a valid state. Therefore, the following steps are followed to design the DFA:" }, { "code": null, "e": 25821, "s": 25701, "text": "In this case, the strings that start with 01 or end with 01 or both start with 01 and end with 01 should be acceptable." }, { "code": null, "e": 25914, "s": 25821, "text": "Make an initial state and transit its input alphabets, i.e, 0 and 1 to two different states." }, { "code": null, "e": 25985, "s": 25914, "text": "Check for acceptance of string after each transition to ignore errors." }, { "code": null, "e": 26055, "s": 25985, "text": "First, make DfA for minimum length string then go ahead step by step." }, { "code": null, "e": 26116, "s": 26055, "text": "Define Final State(s) according to the acceptance of string." }, { "code": null, "e": 26156, "s": 26116, "text": "Step by Step Approach to design a DFA: " }, { "code": null, "e": 26417, "s": 26156, "text": "Step 1: Make an initial state “A”. The minimum possible string is 01 which is acceptable. For this, make the transition of 0 from state “A” to state “B” and then make the transition of 1 from state “B” to state “C” and notice this state “C” as the final state." }, { "code": null, "e": 26679, "s": 26417, "text": "Step 2: Now, we have designed the DFA that start with 01. To accept all the strings that start with 01 like 011, 010, 010000, 01111, 010101000010001 etc, we need to put a self-loop of 0 and 1 to the state “C”. This self-loop contains all combination of 0 and 1." }, { "code": null, "e": 27129, "s": 26679, "text": "Step 3: Now, we need to think about the string that ends with “01”. We have done transition of 0 of state “A”, then with input 1 of the state “A”. With this minimum possible string that ends with 01 is 101. For this, do the transition of input 1 of state “A” to state “D” then do the transition of input 0 from the state “D” to state “E” and then do the transition of input 1 from state “E” to state “F” and notice this “F” state as the final state." }, { "code": null, "e": 27387, "s": 27129, "text": "Step 4: There is one more possibility that any number of 1’s comes in beginning and then end with 01. For this, make a self-loop of 1 on state “D” and any number of zeros can come before 1 that comes in the end. For this, put a self-loop of 0 and state “E”." }, { "code": null, "e": 27613, "s": 27387, "text": "Step 5: Till now we have done with the strings that start with 1 and end with 01. Now, we need to think about the string that starts with 0 and ends with 01. For this, make a transition of input 0 from state “B” to state “E”." }, { "code": null, "e": 27788, "s": 27613, "text": "Step 6: Now we are just left with the input alphabets of the state “F”. Transit input 1 from state “F” to state “D” and then make transit input 0 from state “F” to state “E”." }, { "code": null, "e": 27844, "s": 27788, "text": "Transition table and Transition rules of the above DFA:" }, { "code": null, "e": 27895, "s": 27844, "text": "Below is the implementation of the above approach:" }, { "code": null, "e": 27899, "s": 27895, "text": "C++" }, { "code": null, "e": 27904, "s": 27899, "text": "Java" }, { "code": null, "e": 27912, "s": 27904, "text": "Python3" }, { "code": null, "e": 27915, "s": 27912, "text": "C#" }, { "code": null, "e": 27926, "s": 27915, "text": "Javascript" }, { "code": "// C++ program to check if a string// either starts or ends with 01#include<bits/stdc++.h>using namespace std; void stateA(string);void stateB(string);void stateC(string);void stateD(string);void stateE(string);void stateF(string); // Function for transition// state Avoid checkstateA(string n){ // State transition to // B if the character is // 0 if(n[0] == '0') stateB(n.substr(1)); // State transition to // D if the character is // 1 else stateD(n.substr(1));} // Function for transition// state B void stateB(string n){ // Check if the string has // ended if (n.length() == 0) cout << \"string not accepted\"; else { // State transition to C // if the character is 1 if(n[0] == '1') stateC(n.substr(1)); // State transition to D // if the character is 0 else stateD(n.substr(1)); } } // Function for transition// state Cvoid stateC(string n){ cout << \"String accepted\";} // Function for transition// state Dvoid stateD(string n){ if (n.length() == 0) cout << \"string not accepted\"; else { // State transition to D // if the character is 1 if (n[0] == '1') stateD(n.substr(1)); // State transition to E // if the character is 0 else stateE(n.substr(1)); }} // Function for transition// state Evoid stateE(string n){ if (n.length() == 0) cout << \"string not accepted\"; else { // State transition to E // if the character is 0 if(n[0] == '0') stateE(n.substr(1)); // State transition to F // if the character is 1 else stateF(n.substr(1)); }} // Function for transition// state Fvoid stateF(string n){ if(n.length() == 0) cout << \"string accepred\"; else { // State transition to D // if the character is 1 if(n[0] == '1') stateD(n.substr(1)); // State transition to E // if the character is 0 else stateE(n.substr(1)); }} // Driver codeint main(){ string n = \"0100101\"; checkstateA(n); return 0;} // This code is contributed by chitranayal", "e": 30226, "s": 27926, "text": null }, { "code": "// Java program to check if a string// either starts or ends with 01import java.util.*; class GFG{ // Function for transition// state Astatic void checkstateA(String n){ // State transition to // B if the character is // 0 if (n.charAt(0) == '0') stateB(n.substring(1)); // State transition to // D if the character is // 1 else stateD(n.substring(1));} // Function for transition// state B static void stateB(String n){ // Check if the string has // ended if (n.length() == 0) System.out.println(\"string not accepted\"); else { // State transition to C // if the character is 1 if (n.charAt(0) == '1') stateC(n.substring(1)); // State transition to D // if the character is 0 else stateD(n.substring(1)); } } // Function for transition// state Cstatic void stateC(String n){ System.out.println(\"String accepted\");} // Function for transition// state Dstatic void stateD(String n){ if (n.length() == 0) System.out.println(\"string not accepted\"); else { // State transition to D // if the character is 1 if (n.charAt(0) == '1') stateD(n.substring(1)); // State transition to E // if the character is 0 else stateE(n.substring(1)); }} // Function for transition// state Estatic void stateE(String n){ if (n.length() == 0) System.out.println(\"string not accepted\"); else { // State transition to E // if the character is 0 if(n.charAt(0) == '0') stateE(n.substring(1)); // State transition to F // if the character is 1 else stateF(n.substring(1)); }} // Function for transition// state Fstatic void stateF(String n){ if (n.length() == 0) System.out.println(\"string accepred\"); else { // State transition to D // if the character is 1 if (n.charAt(0) == '1') stateD(n.substring(1)); // State transition to E // if the character is 0 else stateE(n.substring(1)); }} // Driver Codepublic static void main(String args[]){ String n = \"0100101\"; checkstateA(n);}} // This code is contributed by jyoti369", "e": 32580, "s": 30226, "text": null }, { "code": "# Python3 program to check if# a string either starts or# ends with 01 # Function for transition# state Adef checkstateA(n): # State transition to # B if the character is # 0 if(n[0]=='0'): stateB(n[1:]) # State transition to # D if the character is # 1 else: stateD(n[1:]) # Function for transition# state B def stateB(n): # Check if the string has # ended if (len(n)== 0): print(\"string not accepted\") else: # State transition to C # if the character is 1 if(n[0]=='1'): stateC(n[1:]) # State transition to D # if the character is 0 else: stateD(n[1:]) # Function for transition# state C def stateC(n): print(\"String accepted\") # Function for transition# state Ddef stateD(n): if (len(n)== 0): print(\"string not accepted\") else: # State transition to D # if the character is 1 if (n[0]=='1'): stateD(n[1:]) # State transition to E # if the character is 0 else: stateE(n[1:]) # Function for transition# state Edef stateE(n): if (len(n)== 0): print(\"string not accepted\") else: # State transition to E # if the character is 0 if(n[0]=='0'): stateE(n[1:]) # State transition to F # if the character is 1 else: stateF(n[1:]) # Function for transition# state Fdef stateF(n): if(len(n)== 0): print(\"string accepred\") else: # State transition to D # if the character is 1 if(n[0]=='1'): stateD(n[1:]) # State transition to E # if the character is 0 else: stateE(n[1:]) # Driver codeif __name__ == \"__main__\": n = \"0100101\" checkstateA(n)", "e": 34423, "s": 32580, "text": null }, { "code": "// C# program to check if// a string either starts// or ends with 01using System;using System.Collections;using System.Collections.Generic;class GFG{ // Function for transition// state Astatic void checkstateA(string n){ // State transition to // B if the character is // 0 if(n[0] == '0') stateB(n.Substring(1)); // State transition to // D if the character is // 1 else stateD(n.Substring(1));} // Function for transition// state B static void stateB(string n){ // Check if the string has // ended if (n.Length == 0) { Console.Write(\"string not accepted\"); } else { // State transition to C // if the character is 1 if(n[0] == '1') stateC(n.Substring(1)); // State transition to D // if the character is 0 else stateD(n.Substring(1)); } } // Function for transition// state Cstatic void stateC(string n){ Console.Write(\"string accepted\");} // Function for transition// state Dstatic void stateD(string n){ if (n.Length == 0) Console.Write(\"string not accepted\"); else { // State transition to D // if the character is 1 if (n[0] == '1') stateD(n.Substring(1)); // State transition to E // if the character is 0 else stateE(n.Substring(1)); }} // Function for transition// state Estatic void stateE(string n){ if (n.Length == 0) Console.Write(\"string not accepted\"); else { // State transition to E // if the character is 0 if(n[0] == '0') stateE(n.Substring(1)); // State transition to F // if the character is 1 else stateF(n.Substring(1)); }} // Function for transition// state Fstatic void stateF(string n){ if(n.Length == 0) Console.Write(\"string accepted\"); else { // State transition to D // if the character is 1 if(n[0] == '1') stateD(n.Substring(1)); // State transition to E // if the character is 0 else stateE(n.Substring(1)); }} // Driver codepublic static void Main(string []args){ string n = \"0100101\"; checkstateA(n);}} // This code is contributed by rutvik_56", "e": 36492, "s": 34423, "text": null }, { "code": "<script> // JavaScript program to check if// a string either starts// or ends with 01 // Function for transition// state Afunction checkstateA(n){ // State transition to // B if the character is // 0 if(n[0] == '0') stateB(n.substr(1)); // State transition to // D if the character is // 1 else stateD(n.substr(1));} // Function for transition// state B function stateB(n){ // Check if the string has // ended if (n.length == 0) { document.write(\"string not accepted\"); } else { // State transition to C // if the character is 1 if(n[0] == '1') stateC(n.substr(1)); // State transition to D // if the character is 0 else stateD(n.substr(1)); } } // Function for transition// state Cfunction stateC(n){ document.write(\"string accepted\");} // Function for transition// state Dfunction stateD(n){ if (n.length == 0) Console.Write(\"string not accepted\"); else { // State transition to D // if the character is 1 if (n[0] == '1') stateD(n.substr(1)); // State transition to E // if the character is 0 else stateE(n.substr(1)); }} // Function for transition// state Efunction stateE(n){ if (n.length == 0) document.write(\"string not accepted\"); else { // State transition to E // if the character is 0 if(n[0] == '0') stateE(n.substr(1)); // State transition to F // if the character is 1 else stateF(n.substr(1)); }} // Function for transition// state Ffunction stateF(n){ if(n.length == 0) document.write(\"string accepted\"); else { // State transition to D // if the character is 1 if(n[0] == '1') stateD(n.substr(1)); // State transition to E // if the character is 0 else stateE(n.substr(1)); }} // Driver Code let n = \"0100101\"; checkstateA(n); </script>", "e": 38360, "s": 36492, "text": null }, { "code": null, "e": 38376, "s": 38360, "text": "String accepted" }, { "code": null, "e": 38421, "s": 38378, "text": "Time Complexity: O(N)Auxiliary Space: O(N)" }, { "code": null, "e": 38427, "s": 38421, "text": "ukasp" }, { "code": null, "e": 38437, "s": 38427, "text": "rutvik_56" }, { "code": null, "e": 38446, "s": 38437, "text": "jyoti369" }, { "code": null, "e": 38456, "s": 38446, "text": "splevel62" }, { "code": null, "e": 38472, "s": 38456, "text": "pankajsharmagfg" }, { "code": null, "e": 38486, "s": 38472, "text": "sumitgumber28" }, { "code": null, "e": 38500, "s": 38486, "text": "binary-string" }, { "code": null, "e": 38504, "s": 38500, "text": "DFA" }, { "code": null, "e": 38515, "s": 38504, "text": "Algorithms" }, { "code": null, "e": 38524, "s": 38515, "text": "Articles" }, { "code": null, "e": 38542, "s": 38524, "text": "Pattern Searching" }, { "code": null, "e": 38550, "s": 38542, "text": "Strings" }, { "code": null, "e": 38583, "s": 38550, "text": "Theory of Computation & Automata" }, { "code": null, "e": 38591, "s": 38583, "text": "Strings" }, { "code": null, "e": 38609, "s": 38591, "text": "Pattern Searching" }, { "code": null, "e": 38620, "s": 38609, "text": "Algorithms" }, { "code": null, "e": 38718, "s": 38620, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 38727, "s": 38718, "text": "Comments" }, { "code": null, "e": 38740, "s": 38727, "text": "Old Comments" }, { "code": null, "e": 38789, "s": 38740, "text": "SDE SHEET - A Complete Guide for SDE Preparation" }, { "code": null, "e": 38814, "s": 38789, "text": "DSA Sheet by Love Babbar" }, { "code": null, "e": 38841, "s": 38814, "text": "Introduction to Algorithms" }, { "code": null, "e": 38871, "s": 38841, "text": "Playfair Cipher with Examples" }, { "code": null, "e": 38899, "s": 38871, "text": "How to write a Pseudo Code?" }, { "code": null, "e": 38949, "s": 38899, "text": "Tree Traversals (Inorder, Preorder and Postorder)" }, { "code": null, "e": 38996, "s": 38949, "text": "SQL | Join (Inner, Left, Right and Full Joins)" }, { "code": null, "e": 39032, "s": 38996, "text": "find command in Linux with examples" }, { "code": null, "e": 39085, "s": 39032, "text": "Analysis of Algorithms | Set 1 (Asymptotic Analysis)" } ]
How To Change The Column Type in PySpark DataFrames | Towards Data Science
A fairly common operation in PySpark is type casting that is usually required when we need to change the data type of specific columns in DataFrames. For instance, it’s quite common (and a bad practise!) to have datetimes stored as strings, or even integers and doubles stored as StringType. In today’s short guide we will explore how to change the column types of certain DataFrame columns in PySpark. Specifically, we will discuss how to do so using the cast() function the selectExpr() function Spark SQL First, let’s create an example DataFrame that we’ll reference throughout this article in order to demonstrate a few concepts. from pyspark.sql import SparkSession# Create an instance of spark sessionspark_session = SparkSession.builder \ .master('local[1]') \ .appName('Example') \ .getOrCreate()df = spark_session.createDataFrame( [ (1, '10-01-2020', '1.0', '100'), (2, '14-02-2021', '2.0', '200'), (3, '15-06-2019', '3.0', '300'), (4, '12-12-2020', '4.0', '400'), (5, '01-09-2019', '5.0', '500'), ], ['colA', 'colB', 'colC', 'colD'])df.show()+----+----------+----+----+|colA| colB|colC|colD|+----+----------+----+----+| 1|10-01-2020| 1.0| 100|| 2|14-02-2021| 2.0| 200|| 3|15-06-2019| 3.0| 300|| 4|12-12-2020| 4.0| 400|| 5|01-09-2019| 5.0| 500|+----+----------+----+----+df.printSchema()root |-- colA: long (nullable = true) |-- colB: string (nullable = true) |-- colC: string (nullable = true) |-- colD: string (nullable = true) In the following sections, we will showcase how to change the column type of columns colB, colC and colD to DateType, DoubleType and IntegerType respectively. The first option you have when it comes to converting data types is pyspark.sql.Column.cast() function that converts the input column to the specified data type. from datetime import datetimefrom pyspark.sql.functions import col, udffrom pyspark.sql.types import DoubleType, IntegerType, DateType# UDF to process the date columnfunc = udf(lambda x: datetime.strptime(x, '%d-%m-%Y'), DateType())df = df \ .withColumn('colB', func(col('colB'))) \ .withColumn('colC', col('colC').cast(DoubleType())) \ .withColumn('colD', col('colD').cast(IntegerType()))df.show()+----+----------+----+----+|colA| colB|colC|colD|+----+----------+----+----+| 1|2020-01-10| 1.0| 100|| 2|2021-02-14| 2.0| 200|| 3|2019-06-15| 3.0| 300|| 4|2020-12-12| 4.0| 400|| 5|2019-09-01| 5.0| 500|+----+----------+----+----+df.printSchema()root |-- colA: long (nullable = true) |-- colB: date (nullable = true) |-- colC: double (nullable = true) |-- colD: integer (nullable = true) Note that in order to cast the string into DateType we need to specify a UDF in order to process the exact format of the string date. Alternatively, you can use pyspark.sql.DataFrame.selectExpr function by specifying the corresponding SQL expressions that can cast the data type of desired columns, as shown below. df = df.selectExpr( 'colA', 'to_date(colB, \'dd-MM-yyyy\') colB', 'cast(colC as double) colC', 'cast(colD as int) colD',)df.show()+----+----------+----+----+|colA| colB|colC|colD|+----+----------+----+----+| 1|2020-01-10| 1.0| 100|| 2|2021-02-14| 2.0| 200|| 3|2019-06-15| 3.0| 300|| 4|2020-12-12| 4.0| 400|| 5|2019-09-01| 5.0| 500|+----+----------+----+----+df.printSchema()root |-- colA: long (nullable = true) |-- colB: date (nullable = true) |-- colC: double (nullable = true) |-- colD: integer (nullable = true) Lastly, you can even use Spark SQL in order to cast the desired columns in a similar way we have used selectExpr function to do so. # First we need to register the DF as a global temporary viewdf.createGlobalTempView("df")df = spark_session.sql( """ SELECT colA, to_date(colB, 'dd-MM-yyyy') colB, cast(colC as double) colC, cast(colD as int) colD FROM global_temp.df """)df.show()+----+----------+----+----+|colA| colB|colC|colD|+----+----------+----+----+| 1|2020-01-10| 1.0| 100|| 2|2021-02-14| 2.0| 200|| 3|2019-06-15| 3.0| 300|| 4|2020-12-12| 4.0| 400|| 5|2019-09-01| 5.0| 500|+----+----------+----+----+df.printSchema()root |-- colA: long (nullable = true) |-- colB: date (nullable = true) |-- colC: double (nullable = true) |-- colD: integer (nullable = true) In today’s short guide we discussed a few different ways for changing column types of DataFrame columns in PySpark. Specifically, we explored how you can use withColumn() function in combination with cast() as well as using more SQL-like approaches such as selectExpr() or Spark SQL. Become a member and read every story on Medium. Your membership fee directly supports me and other writers you read. You’ll also get full access to every story on Medium. You may also like
[ { "code": null, "e": 464, "s": 172, "text": "A fairly common operation in PySpark is type casting that is usually required when we need to change the data type of specific columns in DataFrames. For instance, it’s quite common (and a bad practise!) to have datetimes stored as strings, or even integers and doubles stored as StringType." }, { "code": null, "e": 624, "s": 464, "text": "In today’s short guide we will explore how to change the column types of certain DataFrame columns in PySpark. Specifically, we will discuss how to do so using" }, { "code": null, "e": 644, "s": 624, "text": "the cast() function" }, { "code": null, "e": 670, "s": 644, "text": "the selectExpr() function" }, { "code": null, "e": 680, "s": 670, "text": "Spark SQL" }, { "code": null, "e": 806, "s": 680, "text": "First, let’s create an example DataFrame that we’ll reference throughout this article in order to demonstrate a few concepts." }, { "code": null, "e": 1679, "s": 806, "text": "from pyspark.sql import SparkSession# Create an instance of spark sessionspark_session = SparkSession.builder \\ .master('local[1]') \\ .appName('Example') \\ .getOrCreate()df = spark_session.createDataFrame( [ (1, '10-01-2020', '1.0', '100'), (2, '14-02-2021', '2.0', '200'), (3, '15-06-2019', '3.0', '300'), (4, '12-12-2020', '4.0', '400'), (5, '01-09-2019', '5.0', '500'), ], ['colA', 'colB', 'colC', 'colD'])df.show()+----+----------+----+----+|colA| colB|colC|colD|+----+----------+----+----+| 1|10-01-2020| 1.0| 100|| 2|14-02-2021| 2.0| 200|| 3|15-06-2019| 3.0| 300|| 4|12-12-2020| 4.0| 400|| 5|01-09-2019| 5.0| 500|+----+----------+----+----+df.printSchema()root |-- colA: long (nullable = true) |-- colB: string (nullable = true) |-- colC: string (nullable = true) |-- colD: string (nullable = true)" }, { "code": null, "e": 1838, "s": 1679, "text": "In the following sections, we will showcase how to change the column type of columns colB, colC and colD to DateType, DoubleType and IntegerType respectively." }, { "code": null, "e": 2000, "s": 1838, "text": "The first option you have when it comes to converting data types is pyspark.sql.Column.cast() function that converts the input column to the specified data type." }, { "code": null, "e": 2808, "s": 2000, "text": "from datetime import datetimefrom pyspark.sql.functions import col, udffrom pyspark.sql.types import DoubleType, IntegerType, DateType# UDF to process the date columnfunc = udf(lambda x: datetime.strptime(x, '%d-%m-%Y'), DateType())df = df \\ .withColumn('colB', func(col('colB'))) \\ .withColumn('colC', col('colC').cast(DoubleType())) \\ .withColumn('colD', col('colD').cast(IntegerType()))df.show()+----+----------+----+----+|colA| colB|colC|colD|+----+----------+----+----+| 1|2020-01-10| 1.0| 100|| 2|2021-02-14| 2.0| 200|| 3|2019-06-15| 3.0| 300|| 4|2020-12-12| 4.0| 400|| 5|2019-09-01| 5.0| 500|+----+----------+----+----+df.printSchema()root |-- colA: long (nullable = true) |-- colB: date (nullable = true) |-- colC: double (nullable = true) |-- colD: integer (nullable = true)" }, { "code": null, "e": 2942, "s": 2808, "text": "Note that in order to cast the string into DateType we need to specify a UDF in order to process the exact format of the string date." }, { "code": null, "e": 3123, "s": 2942, "text": "Alternatively, you can use pyspark.sql.DataFrame.selectExpr function by specifying the corresponding SQL expressions that can cast the data type of desired columns, as shown below." }, { "code": null, "e": 3666, "s": 3123, "text": "df = df.selectExpr( 'colA', 'to_date(colB, \\'dd-MM-yyyy\\') colB', 'cast(colC as double) colC', 'cast(colD as int) colD',)df.show()+----+----------+----+----+|colA| colB|colC|colD|+----+----------+----+----+| 1|2020-01-10| 1.0| 100|| 2|2021-02-14| 2.0| 200|| 3|2019-06-15| 3.0| 300|| 4|2020-12-12| 4.0| 400|| 5|2019-09-01| 5.0| 500|+----+----------+----+----+df.printSchema()root |-- colA: long (nullable = true) |-- colB: date (nullable = true) |-- colC: double (nullable = true) |-- colD: integer (nullable = true)" }, { "code": null, "e": 3798, "s": 3666, "text": "Lastly, you can even use Spark SQL in order to cast the desired columns in a similar way we have used selectExpr function to do so." }, { "code": null, "e": 4488, "s": 3798, "text": "# First we need to register the DF as a global temporary viewdf.createGlobalTempView(\"df\")df = spark_session.sql( \"\"\" SELECT colA, to_date(colB, 'dd-MM-yyyy') colB, cast(colC as double) colC, cast(colD as int) colD FROM global_temp.df \"\"\")df.show()+----+----------+----+----+|colA| colB|colC|colD|+----+----------+----+----+| 1|2020-01-10| 1.0| 100|| 2|2021-02-14| 2.0| 200|| 3|2019-06-15| 3.0| 300|| 4|2020-12-12| 4.0| 400|| 5|2019-09-01| 5.0| 500|+----+----------+----+----+df.printSchema()root |-- colA: long (nullable = true) |-- colB: date (nullable = true) |-- colC: double (nullable = true) |-- colD: integer (nullable = true)" }, { "code": null, "e": 4772, "s": 4488, "text": "In today’s short guide we discussed a few different ways for changing column types of DataFrame columns in PySpark. Specifically, we explored how you can use withColumn() function in combination with cast() as well as using more SQL-like approaches such as selectExpr() or Spark SQL." }, { "code": null, "e": 4943, "s": 4772, "text": "Become a member and read every story on Medium. Your membership fee directly supports me and other writers you read. You’ll also get full access to every story on Medium." } ]
How to learn Pattern printing easily? - GeeksforGeeks
24 Nov, 2021 The task is to print a pattern as shown in the example for a given integer value.The goal is not to print just this one pattern, it is to learn the best approach to solve this kind of problems as these questions are frequently asked in coding exams and in job interviews.Examples: Input: N = 4 Output: 4 4 4 4 4 4 4 4 3 3 3 3 3 4 4 3 2 2 2 3 4 4 3 2 1 2 3 4 4 3 2 2 2 3 4 4 3 3 3 3 3 4 4 4 4 4 4 4 4 Input: N = 7 Output: 7 7 7 7 7 7 7 7 7 7 7 7 7 7 6 6 6 6 6 6 6 6 6 6 6 7 7 6 5 5 5 5 5 5 5 5 5 6 7 7 6 5 4 4 4 4 4 4 4 5 6 7 7 6 5 4 3 3 3 3 3 4 5 6 7 7 6 5 4 3 2 2 2 3 4 5 6 7 7 6 5 4 3 2 1 2 3 4 5 6 7 7 6 5 4 3 2 2 2 3 4 5 6 7 7 6 5 4 3 3 3 3 3 4 5 6 7 7 6 5 4 4 4 4 4 4 4 5 6 7 7 6 5 5 5 5 5 5 5 5 5 6 7 7 6 6 6 6 6 6 6 6 6 6 6 7 7 7 7 7 7 7 7 7 7 7 7 7 7 For the tutorial, an example of N = 4 is used. Step 1: First of all, analyse the pattern for any lines of symmetry. Here our pattern is both vertically and horizontally symmetrical, so draw the lines of symmetry like this, After breaking the pattern in parts, first try to draw only the upper-left part, namely, part A. If there is not any line of symmetry, jump to Step 2. Step 2: Now associate each cell i.e. element with a row and column no.( usually denoted by i and j, respectively) Just like, From now on, a cell is denoted by C(i, j) with its row and column no. Step 3: In this step, try and find a relation between the value of C(i, j) with i and/or j. Usually, the value of C depends on the value of N and values of i and j relative to each other. To elaborate,– In 1st row, every element is same i.e. 4(=N). So it is not of much help. – In 2nd row, C can be seen decreasing from of 4 to 3 for i>=j and then it stays 3 for next i=j and then it stays 2 for next i=j for all values of j, C can be seen decreasing from 4 to 1.So in every row, C starts from N, decreases by 1 until i>=j, and then becomes constant. Here the value of C depends upon the smaller between i and j and the formula could be: C(i, j) = N - min(i, j) + 1 So our approach should be: C++ Java Python3 C# Javascript #include <iostream>using namespace std; int main(){ int N = 4, i, j, min; cout << "Value of N: " << N << endl; for (i = 1; i <= N; i++) { for (j = 1; j <= N; j++) { min = i < j ? i : j; cout << N - min + 1; } cout << endl; } return 0;} // Java program to find triplets // a[i]>a[j]>a[k] and i<j<kimport java.util.*; class GFG{ // Driver codepublic static void main(String[] args){ int N = 4, i, j, min; System.out.println("Value of N: " + N); for (i = 1; i <= N; i++) { for (j = 1; j <= N; j++) { min = i < j ? i : j; System.out.print(N - min + 1); } System.out.println(); }}} // This code is contributed by Princi Singh # Python3 program to find triplets # a[i]>a[j]>a[k] and i<j<kif __name__ == '__main__': N = 4; print("Value of N: ", N); for i in range(1, N + 1): for j in range(1, N + 1): min = i if i < j else j; print(N - min + 1, end = ""); print(); # This code is contributed # by PrinciRaj1992 // C# program to find triplets // a[i]>a[j]>a[k] and i<j<kusing System; class GFG{ // Driver codepublic static void Main(String[] args){ int N = 4, i, j, min; Console.WriteLine("Value of N: " + N); for (i = 1; i <= N; i++) { for (j = 1; j <= N; j++) { min = i < j ? i : j; Console.Write(N - min + 1); } Console.WriteLine(); }}} // This code is contributed by PrinciRaj1992 <script> // JavaScript program to find triplets // a[i]>a[j]>a[k] and i<j<k // Driver code var N = 4, i, j, min; document.write("Value of N: " + N +"<br>"); for (i = 1; i <= N; i++) { for (j = 1; j <= N; j++) { min = i < j ? i : j; document.write(N - min + 1); } document.write("<br>"); } // This code is contributed by shivanisinghss2110 </script> Value of N: 4 4444 4333 4322 4321 If the pattern didn’t have any symmetry and is now completed, the work is done. But for patterns with symmetry, they are still incomplete and it is required to go to step 4. Step 4: Now include part B of the pattern in the picture and associate those elements with column numbers. But don’t assign column numbers serial-wise, instead, assign them the same column number that was assigned to its mirror column in part A. Step 5: Now change the code to append part B. To do that, it is just needed to rerun the inner loop for j = n-1 to j=1. C++ Java Python3 C# Javascript #include <iostream>using namespace std; int main(){ int N = 4, i, j, min; cout << "Value of N: " << N << endl; for (i = 1; i <= N; i++) { for (j = 1; j <= N; j++) { min = i < j ? i : j; cout << N - min + 1; } for (j = N - 1; j >= 1; j--) { min = i < j ? i : j; cout << N - min + 1; } cout << endl; } return 0;} class GFG { public static void main(String[] args) { int N = 4, i, j, min; System.out.println("Value of N: " + N); for (i = 1; i <= N; i++) { for (j = 1; j <= N; j++) { min = i < j ? i : j; System.out.print(N - min + 1); } for (j = N - 1; j >= 1; j--) { min = i < j ? i : j; System.out.print(N - min + 1); } System.out.println(); } }} // This code is contributed by PrinciRaj1992 N = 4;print("Value of N: ", N); for i in range(1, N + 1): for j in range(1, N + 1): min = i if i < j else j; print(N - min + 1, end = ""); for j in range(N - 1, 0, -1): min = i if i < j else j; print(N - min + 1, end = ""); print(); # This code is contributed by Rajput-Ji using System; class GFG { public static void Main(String[] args) { int N = 4, i, j, min; Console.WriteLine("Value of N: " + N); for (i = 1; i <= N; i++) { for (j = 1; j <= N; j++) { min = i < j ? i : j; Console.Write(N - min + 1); } for (j = N - 1; j >= 1; j--) { min = i < j ? i : j; Console.Write(N - min + 1); } Console.WriteLine(); } }} // This code is contributed by Rajput-Ji <script> var N = 4, i, j, min; document.write("Value of N: " + N +"<br>"); for (i = 1; i <= N; i++) { for (j = 1; j <= N; j++) { min = i < j ? i : j; document.write(N - min + 1); } for (j = N - 1; j >= 1; j--) { min = i < j ? i : j; document.write(N - min + 1); } document.write("<br>"); } // this code is contributed by shivanisinghss2110</script> Value of N: 4 4444444 4333334 4322234 4321234 Step 6: Now includes part C and D of the pattern in the picture and associate those elements with row numbers in the same way the column numbers are assigned in step 4. Step 7: Now, In the same way, as done in step 5, change the code to append part C and D. To do that, one just need to rerun the outer loop for i = n-1 to i=1. C++ Java Python3 C# Javascript #include <iostream>using namespace std; int main(){ int N = 4, i, j, min; cout << "Value of N: " << N << endl; for (i = 1; i <= N; i++) { for (j = 1; j <= N; j++) { min = i < j ? i : j; cout << N - min + 1; } for (j = N - 1; j >= 1; j--) { min = i < j ? i : j; cout << N - min + 1; } cout << endl; } for (i = N - 1; i >= 1; i--) { for (j = 1; j <= N; j++) { min = i < j ? i : j; cout << N - min + 1; } for (j = N - 1; j >= 1; j--) { min = i < j ? i : j; cout << N - min + 1; } cout << endl; } return 0;} // Java implementation of the approachclass GFG {public static void main(String[] args) { int N = 4, i, j, min; System.out.println("Value of N: " + N); for (i = 1; i <= N; i++) { for (j = 1; j <= N; j++) { min = i < j ? i : j; System.out.print(N - min + 1); } for (j = N - 1; j >= 1; j--) { min = i < j ? i : j; System.out.print(N - min + 1); } System.out.println(); } for (i = N - 1; i >= 1; i--) { for (j = 1; j <= N; j++) { min = i < j ? i : j; System.out.print(N - min + 1); } for (j = N - 1; j >= 1; j--) { min = i < j ? i : j; System.out.print(N - min + 1); } System.out.println(); } }} // This code is contributed by 29AjayKumar # Python3 implementation of the approachN = 4print("Value of N: ", N) for i in range(1, N + 1): for j in range(1, N + 1): min = i if i < j else j print(N - min + 1, end = " ") for j in range(N - 1, 0, -1): min = i if i < j else j print(N - min + 1, end = " ") print() for i in range(N - 1, 0, -1): for j in range(1, N + 1): min = i if i < j else j print(N - min + 1, end = " ") for j in range(N - 1, 0, -1): min = i if i < j else j print(N - min + 1, end = " ") print() # This code is contributed by sai prakash // C# implementation of the approachusing System; class GFG {public static void Main(String[] args) { int N = 4, i, j, min; Console.WriteLine("Value of N: " + N); for (i = 1; i <= N; i++) { for (j = 1; j <= N; j++) { min = i < j ? i : j; Console.Write(N - min + 1); } for (j = N - 1; j >= 1; j--) { min = i < j ? i : j; Console.Write(N - min + 1); } Console.WriteLine(); } for (i = N - 1; i >= 1; i--) { for (j = 1; j <= N; j++) { min = i < j ? i : j; Console.Write(N - min + 1); } for (j = N - 1; j >= 1; j--) { min = i < j ? i : j; Console.Write(N - min + 1); } Console.WriteLine(); } }} // This code is contributed by Rajput-Ji <script> // JavaScript implementation of the approach var N = 4, i, j, min; document.write("Value of N: " + N +"<br>"); for (i = 1; i <= N; i++) { for (j = 1; j <= N; j++) { min = i < j ? i : j; document.write(N - min + 1 ); } for (j = N - 1; j >= 1; j--) { min = i < j ? i : j; document.write(N - min + 1); } document.write("<br>"); } for (i = N - 1; i >= 1; i--) { for (j = 1; j <= N; j++) { min = i < j ? i : j; document.write(N - min + 1); } for (j = N - 1; j >= 1; j--) { min = i < j ? i : j; document.write(N - min + 1); } document.write("<br>"); } // This code is contributed by shivanisinghss2110</script> Value of N: 4 4444444 4333334 4322234 4321234 4322234 4333334 4444444 My Personal Notes arrow_drop_upSave 29AjayKumar Rajput-Ji princi singh princiraj1992 saiprakash95666 nidhi_biet shivanisinghss2110 pattern-printing Analysis School Programming pattern-printing Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Time Complexity of building a heap Analysis of Algorithms | Big-O analysis NP-Completeness | Set 1 (Introduction) Time Complexity and Space Complexity Proof that Dominant Set of a Graph is NP-Complete Python Dictionary Inheritance in C++ Arrays in C/C++ Reverse a string in Java Overriding in Java
[ { "code": null, "e": 24783, "s": 24755, "text": "\n24 Nov, 2021" }, { "code": null, "e": 25066, "s": 24783, "text": "The task is to print a pattern as shown in the example for a given integer value.The goal is not to print just this one pattern, it is to learn the best approach to solve this kind of problems as these questions are frequently asked in coding exams and in job interviews.Examples: " }, { "code": null, "e": 25545, "s": 25066, "text": "Input: N = 4\nOutput:\n4 4 4 4 4 4 4\n4 3 3 3 3 3 4\n4 3 2 2 2 3 4\n4 3 2 1 2 3 4\n4 3 2 2 2 3 4\n4 3 3 3 3 3 4\n4 4 4 4 4 4 4\n\nInput: N = 7\nOutput:\n7 7 7 7 7 7 7 7 7 7 7 7 7\n7 6 6 6 6 6 6 6 6 6 6 6 7\n7 6 5 5 5 5 5 5 5 5 5 6 7\n7 6 5 4 4 4 4 4 4 4 5 6 7\n7 6 5 4 3 3 3 3 3 4 5 6 7\n7 6 5 4 3 2 2 2 3 4 5 6 7\n7 6 5 4 3 2 1 2 3 4 5 6 7\n7 6 5 4 3 2 2 2 3 4 5 6 7\n7 6 5 4 3 3 3 3 3 4 5 6 7\n7 6 5 4 4 4 4 4 4 4 5 6 7\n7 6 5 5 5 5 5 5 5 5 5 6 7\n7 6 6 6 6 6 6 6 6 6 6 6 7\n7 7 7 7 7 7 7 7 7 7 7 7 7" }, { "code": null, "e": 25594, "s": 25545, "text": "For the tutorial, an example of N = 4 is used. " }, { "code": null, "e": 25771, "s": 25594, "text": "Step 1: First of all, analyse the pattern for any lines of symmetry. Here our pattern is both vertically and horizontally symmetrical, so draw the lines of symmetry like this, " }, { "code": null, "e": 25922, "s": 25771, "text": "After breaking the pattern in parts, first try to draw only the upper-left part, namely, part A. If there is not any line of symmetry, jump to Step 2." }, { "code": null, "e": 26049, "s": 25922, "text": "Step 2: Now associate each cell i.e. element with a row and column no.( usually denoted by i and j, respectively) Just like, " }, { "code": null, "e": 26119, "s": 26049, "text": "From now on, a cell is denoted by C(i, j) with its row and column no." }, { "code": null, "e": 26759, "s": 26119, "text": "Step 3: In this step, try and find a relation between the value of C(i, j) with i and/or j. Usually, the value of C depends on the value of N and values of i and j relative to each other. To elaborate,– In 1st row, every element is same i.e. 4(=N). So it is not of much help. – In 2nd row, C can be seen decreasing from of 4 to 3 for i>=j and then it stays 3 for next i=j and then it stays 2 for next i=j for all values of j, C can be seen decreasing from 4 to 1.So in every row, C starts from N, decreases by 1 until i>=j, and then becomes constant. Here the value of C depends upon the smaller between i and j and the formula could be: " }, { "code": null, "e": 26787, "s": 26759, "text": "C(i, j) = N - min(i, j) + 1" }, { "code": null, "e": 26816, "s": 26787, "text": "So our approach should be: " }, { "code": null, "e": 26820, "s": 26816, "text": "C++" }, { "code": null, "e": 26825, "s": 26820, "text": "Java" }, { "code": null, "e": 26833, "s": 26825, "text": "Python3" }, { "code": null, "e": 26836, "s": 26833, "text": "C#" }, { "code": null, "e": 26847, "s": 26836, "text": "Javascript" }, { "code": "#include <iostream>using namespace std; int main(){ int N = 4, i, j, min; cout << \"Value of N: \" << N << endl; for (i = 1; i <= N; i++) { for (j = 1; j <= N; j++) { min = i < j ? i : j; cout << N - min + 1; } cout << endl; } return 0;}", "e": 27144, "s": 26847, "text": null }, { "code": "// Java program to find triplets // a[i]>a[j]>a[k] and i<j<kimport java.util.*; class GFG{ // Driver codepublic static void main(String[] args){ int N = 4, i, j, min; System.out.println(\"Value of N: \" + N); for (i = 1; i <= N; i++) { for (j = 1; j <= N; j++) { min = i < j ? i : j; System.out.print(N - min + 1); } System.out.println(); }}} // This code is contributed by Princi Singh", "e": 27601, "s": 27144, "text": null }, { "code": "# Python3 program to find triplets # a[i]>a[j]>a[k] and i<j<kif __name__ == '__main__': N = 4; print(\"Value of N: \", N); for i in range(1, N + 1): for j in range(1, N + 1): min = i if i < j else j; print(N - min + 1, end = \"\"); print(); # This code is contributed # by PrinciRaj1992 ", "e": 27939, "s": 27601, "text": null }, { "code": "// C# program to find triplets // a[i]>a[j]>a[k] and i<j<kusing System; class GFG{ // Driver codepublic static void Main(String[] args){ int N = 4, i, j, min; Console.WriteLine(\"Value of N: \" + N); for (i = 1; i <= N; i++) { for (j = 1; j <= N; j++) { min = i < j ? i : j; Console.Write(N - min + 1); } Console.WriteLine(); }}} // This code is contributed by PrinciRaj1992", "e": 28388, "s": 27939, "text": null }, { "code": "<script> // JavaScript program to find triplets // a[i]>a[j]>a[k] and i<j<k // Driver code var N = 4, i, j, min; document.write(\"Value of N: \" + N +\"<br>\"); for (i = 1; i <= N; i++) { for (j = 1; j <= N; j++) { min = i < j ? i : j; document.write(N - min + 1); } document.write(\"<br>\"); } // This code is contributed by shivanisinghss2110 </script>", "e": 28810, "s": 28388, "text": null }, { "code": null, "e": 28846, "s": 28812, "text": "Value of N: 4\n4444\n4333\n4322\n4321" }, { "code": null, "e": 29024, "s": 28848, "text": "If the pattern didn’t have any symmetry and is now completed, the work is done. But for patterns with symmetry, they are still incomplete and it is required to go to step 4. " }, { "code": null, "e": 29271, "s": 29024, "text": "Step 4: Now include part B of the pattern in the picture and associate those elements with column numbers. But don’t assign column numbers serial-wise, instead, assign them the same column number that was assigned to its mirror column in part A. " }, { "code": null, "e": 29395, "s": 29273, "text": "Step 5: Now change the code to append part B. To do that, it is just needed to rerun the inner loop for j = n-1 to j=1. " }, { "code": null, "e": 29399, "s": 29395, "text": "C++" }, { "code": null, "e": 29404, "s": 29399, "text": "Java" }, { "code": null, "e": 29412, "s": 29404, "text": "Python3" }, { "code": null, "e": 29415, "s": 29412, "text": "C#" }, { "code": null, "e": 29426, "s": 29415, "text": "Javascript" }, { "code": "#include <iostream>using namespace std; int main(){ int N = 4, i, j, min; cout << \"Value of N: \" << N << endl; for (i = 1; i <= N; i++) { for (j = 1; j <= N; j++) { min = i < j ? i : j; cout << N - min + 1; } for (j = N - 1; j >= 1; j--) { min = i < j ? i : j; cout << N - min + 1; } cout << endl; } return 0;}", "e": 29834, "s": 29426, "text": null }, { "code": "class GFG { public static void main(String[] args) { int N = 4, i, j, min; System.out.println(\"Value of N: \" + N); for (i = 1; i <= N; i++) { for (j = 1; j <= N; j++) { min = i < j ? i : j; System.out.print(N - min + 1); } for (j = N - 1; j >= 1; j--) { min = i < j ? i : j; System.out.print(N - min + 1); } System.out.println(); } }} // This code is contributed by PrinciRaj1992", "e": 30405, "s": 29834, "text": null }, { "code": "N = 4;print(\"Value of N: \", N); for i in range(1, N + 1): for j in range(1, N + 1): min = i if i < j else j; print(N - min + 1, end = \"\"); for j in range(N - 1, 0, -1): min = i if i < j else j; print(N - min + 1, end = \"\"); print(); # This code is contributed by Rajput-Ji", "e": 30719, "s": 30405, "text": null }, { "code": "using System; class GFG { public static void Main(String[] args) { int N = 4, i, j, min; Console.WriteLine(\"Value of N: \" + N); for (i = 1; i <= N; i++) { for (j = 1; j <= N; j++) { min = i < j ? i : j; Console.Write(N - min + 1); } for (j = N - 1; j >= 1; j--) { min = i < j ? i : j; Console.Write(N - min + 1); } Console.WriteLine(); } }} // This code is contributed by Rajput-Ji", "e": 31293, "s": 30719, "text": null }, { "code": "<script> var N = 4, i, j, min; document.write(\"Value of N: \" + N +\"<br>\"); for (i = 1; i <= N; i++) { for (j = 1; j <= N; j++) { min = i < j ? i : j; document.write(N - min + 1); } for (j = N - 1; j >= 1; j--) { min = i < j ? i : j; document.write(N - min + 1); } document.write(\"<br>\"); } // this code is contributed by shivanisinghss2110</script>", "e": 31818, "s": 31293, "text": null }, { "code": null, "e": 31866, "s": 31820, "text": "Value of N: 4\n4444444\n4333334\n4322234\n4321234" }, { "code": null, "e": 32040, "s": 31870, "text": "Step 6: Now includes part C and D of the pattern in the picture and associate those elements with row numbers in the same way the column numbers are assigned in step 4. " }, { "code": null, "e": 32203, "s": 32042, "text": "Step 7: Now, In the same way, as done in step 5, change the code to append part C and D. To do that, one just need to rerun the outer loop for i = n-1 to i=1. " }, { "code": null, "e": 32207, "s": 32203, "text": "C++" }, { "code": null, "e": 32212, "s": 32207, "text": "Java" }, { "code": null, "e": 32220, "s": 32212, "text": "Python3" }, { "code": null, "e": 32223, "s": 32220, "text": "C#" }, { "code": null, "e": 32234, "s": 32223, "text": "Javascript" }, { "code": "#include <iostream>using namespace std; int main(){ int N = 4, i, j, min; cout << \"Value of N: \" << N << endl; for (i = 1; i <= N; i++) { for (j = 1; j <= N; j++) { min = i < j ? i : j; cout << N - min + 1; } for (j = N - 1; j >= 1; j--) { min = i < j ? i : j; cout << N - min + 1; } cout << endl; } for (i = N - 1; i >= 1; i--) { for (j = 1; j <= N; j++) { min = i < j ? i : j; cout << N - min + 1; } for (j = N - 1; j >= 1; j--) { min = i < j ? i : j; cout << N - min + 1; } cout << endl; } return 0;}", "e": 32920, "s": 32234, "text": null }, { "code": "// Java implementation of the approachclass GFG {public static void main(String[] args) { int N = 4, i, j, min; System.out.println(\"Value of N: \" + N); for (i = 1; i <= N; i++) { for (j = 1; j <= N; j++) { min = i < j ? i : j; System.out.print(N - min + 1); } for (j = N - 1; j >= 1; j--) { min = i < j ? i : j; System.out.print(N - min + 1); } System.out.println(); } for (i = N - 1; i >= 1; i--) { for (j = 1; j <= N; j++) { min = i < j ? i : j; System.out.print(N - min + 1); } for (j = N - 1; j >= 1; j--) { min = i < j ? i : j; System.out.print(N - min + 1); } System.out.println(); } }} // This code is contributed by 29AjayKumar", "e": 33782, "s": 32920, "text": null }, { "code": "# Python3 implementation of the approachN = 4print(\"Value of N: \", N) for i in range(1, N + 1): for j in range(1, N + 1): min = i if i < j else j print(N - min + 1, end = \" \") for j in range(N - 1, 0, -1): min = i if i < j else j print(N - min + 1, end = \" \") print() for i in range(N - 1, 0, -1): for j in range(1, N + 1): min = i if i < j else j print(N - min + 1, end = \" \") for j in range(N - 1, 0, -1): min = i if i < j else j print(N - min + 1, end = \" \") print() # This code is contributed by sai prakash", "e": 34400, "s": 33782, "text": null }, { "code": "// C# implementation of the approachusing System; class GFG {public static void Main(String[] args) { int N = 4, i, j, min; Console.WriteLine(\"Value of N: \" + N); for (i = 1; i <= N; i++) { for (j = 1; j <= N; j++) { min = i < j ? i : j; Console.Write(N - min + 1); } for (j = N - 1; j >= 1; j--) { min = i < j ? i : j; Console.Write(N - min + 1); } Console.WriteLine(); } for (i = N - 1; i >= 1; i--) { for (j = 1; j <= N; j++) { min = i < j ? i : j; Console.Write(N - min + 1); } for (j = N - 1; j >= 1; j--) { min = i < j ? i : j; Console.Write(N - min + 1); } Console.WriteLine(); } }} // This code is contributed by Rajput-Ji", "e": 35258, "s": 34400, "text": null }, { "code": "<script> // JavaScript implementation of the approach var N = 4, i, j, min; document.write(\"Value of N: \" + N +\"<br>\"); for (i = 1; i <= N; i++) { for (j = 1; j <= N; j++) { min = i < j ? i : j; document.write(N - min + 1 ); } for (j = N - 1; j >= 1; j--) { min = i < j ? i : j; document.write(N - min + 1); } document.write(\"<br>\"); } for (i = N - 1; i >= 1; i--) { for (j = 1; j <= N; j++) { min = i < j ? i : j; document.write(N - min + 1); } for (j = N - 1; j >= 1; j--) { min = i < j ? i : j; document.write(N - min + 1); } document.write(\"<br>\"); } // This code is contributed by shivanisinghss2110</script>", "e": 36098, "s": 35258, "text": null }, { "code": null, "e": 36168, "s": 36098, "text": "Value of N: 4\n4444444\n4333334\n4322234\n4321234\n4322234\n4333334\n4444444" }, { "code": null, "e": 36208, "s": 36170, "text": " My Personal Notes\narrow_drop_upSave" }, { "code": null, "e": 36222, "s": 36210, "text": "29AjayKumar" }, { "code": null, "e": 36232, "s": 36222, "text": "Rajput-Ji" }, { "code": null, "e": 36245, "s": 36232, "text": "princi singh" }, { "code": null, "e": 36259, "s": 36245, "text": "princiraj1992" }, { "code": null, "e": 36275, "s": 36259, "text": "saiprakash95666" }, { "code": null, "e": 36286, "s": 36275, "text": "nidhi_biet" }, { "code": null, "e": 36305, "s": 36286, "text": "shivanisinghss2110" }, { "code": null, "e": 36322, "s": 36305, "text": "pattern-printing" }, { "code": null, "e": 36331, "s": 36322, "text": "Analysis" }, { "code": null, "e": 36350, "s": 36331, "text": "School Programming" }, { "code": null, "e": 36367, "s": 36350, "text": "pattern-printing" }, { "code": null, "e": 36465, "s": 36367, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 36474, "s": 36465, "text": "Comments" }, { "code": null, "e": 36487, "s": 36474, "text": "Old Comments" }, { "code": null, "e": 36522, "s": 36487, "text": "Time Complexity of building a heap" }, { "code": null, "e": 36562, "s": 36522, "text": "Analysis of Algorithms | Big-O analysis" }, { "code": null, "e": 36601, "s": 36562, "text": "NP-Completeness | Set 1 (Introduction)" }, { "code": null, "e": 36638, "s": 36601, "text": "Time Complexity and Space Complexity" }, { "code": null, "e": 36688, "s": 36638, "text": "Proof that Dominant Set of a Graph is NP-Complete" }, { "code": null, "e": 36706, "s": 36688, "text": "Python Dictionary" }, { "code": null, "e": 36725, "s": 36706, "text": "Inheritance in C++" }, { "code": null, "e": 36741, "s": 36725, "text": "Arrays in C/C++" }, { "code": null, "e": 36766, "s": 36741, "text": "Reverse a string in Java" } ]
Changing the colour of Tkinter Menu Bar - GeeksforGeeks
07 Apr, 2021 Prerequisites: Tkinter Menus are an important part of any GUI. A common use of menus is to provide convenient access to various operations such as saving or opening a file, quitting a program, or manipulating data. Toplevel menus are displayed just under the title bar of the root or any other toplevel windows. Changing the color of menubar is not available on the Windows. This is because the menubar is not owned by Tkinter itself, but it is outsourced from other third-parties, hence providing the users limited options only. But if are using Linux, then you are all set to go. You can change the color of menubar by setting the background color and foreground color. Just read the article given below to know more in detail. Syntax: menubar = Menu(app, background=’#background color’, fg=’#text color’) Here, the color to be added to the menubar is given as input to the background parameter. Given below is the proper example to do the same. Program: Python # Import the library tkinterfrom tkinter import * # Create a GUI appapp = Tk() # Set the title and geometry to your appapp.title("Geeks For Geeks")app.geometry("800x500") # Create menubar by setting the colormenubar = Menu(app, background='blue', fg='white') # Declare file and edit for showing in menubarfile = Menu(menubar, tearoff=False, background='yellow')edit = Menu(menubar, tearoff=False, background='pink') # Add commands in in file menufile.add_command(label="New")file.add_command(label="Exit", command=app.quit) # Add commands in edit menuedit.add_command(label="Cut")edit.add_command(label="Copy")edit.add_command(label="Paste") # Display the file and edit declared in previous stepmenubar.add_cascade(label="File", menu=file)menubar.add_cascade(label="Edit", menu=edit) # Displaying of menubar in the appapp.config(menu=menubar) # Make infinite loop for displaying app on screenapp.mainloop() Output: Picked Python Tkinter-exercises Python-tkinter Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments How to Install PIP on Windows ? How to drop one or multiple columns in Pandas Dataframe Python OOPs Concepts Python | Get unique values from a list Check if element exists in list in Python Python Classes and Objects Python | os.path.join() method How To Convert Python Dictionary To JSON? Python | Pandas dataframe.groupby() Create a directory in Python
[ { "code": null, "e": 24212, "s": 24184, "text": "\n07 Apr, 2021" }, { "code": null, "e": 24235, "s": 24212, "text": "Prerequisites: Tkinter" }, { "code": null, "e": 24525, "s": 24235, "text": "Menus are an important part of any GUI. A common use of menus is to provide convenient access to various operations such as saving or opening a file, quitting a program, or manipulating data. Toplevel menus are displayed just under the title bar of the root or any other toplevel windows. " }, { "code": null, "e": 24943, "s": 24525, "text": "Changing the color of menubar is not available on the Windows. This is because the menubar is not owned by Tkinter itself, but it is outsourced from other third-parties, hence providing the users limited options only. But if are using Linux, then you are all set to go. You can change the color of menubar by setting the background color and foreground color. Just read the article given below to know more in detail." }, { "code": null, "e": 24951, "s": 24943, "text": "Syntax:" }, { "code": null, "e": 25021, "s": 24951, "text": "menubar = Menu(app, background=’#background color’, fg=’#text color’)" }, { "code": null, "e": 25161, "s": 25021, "text": "Here, the color to be added to the menubar is given as input to the background parameter. Given below is the proper example to do the same." }, { "code": null, "e": 25170, "s": 25161, "text": "Program:" }, { "code": null, "e": 25177, "s": 25170, "text": "Python" }, { "code": "# Import the library tkinterfrom tkinter import * # Create a GUI appapp = Tk() # Set the title and geometry to your appapp.title(\"Geeks For Geeks\")app.geometry(\"800x500\") # Create menubar by setting the colormenubar = Menu(app, background='blue', fg='white') # Declare file and edit for showing in menubarfile = Menu(menubar, tearoff=False, background='yellow')edit = Menu(menubar, tearoff=False, background='pink') # Add commands in in file menufile.add_command(label=\"New\")file.add_command(label=\"Exit\", command=app.quit) # Add commands in edit menuedit.add_command(label=\"Cut\")edit.add_command(label=\"Copy\")edit.add_command(label=\"Paste\") # Display the file and edit declared in previous stepmenubar.add_cascade(label=\"File\", menu=file)menubar.add_cascade(label=\"Edit\", menu=edit) # Displaying of menubar in the appapp.config(menu=menubar) # Make infinite loop for displaying app on screenapp.mainloop()", "e": 26093, "s": 25177, "text": null }, { "code": null, "e": 26101, "s": 26093, "text": "Output:" }, { "code": null, "e": 26108, "s": 26101, "text": "Picked" }, { "code": null, "e": 26133, "s": 26108, "text": "Python Tkinter-exercises" }, { "code": null, "e": 26148, "s": 26133, "text": "Python-tkinter" }, { "code": null, "e": 26155, "s": 26148, "text": "Python" }, { "code": null, "e": 26253, "s": 26155, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 26262, "s": 26253, "text": "Comments" }, { "code": null, "e": 26275, "s": 26262, "text": "Old Comments" }, { "code": null, "e": 26307, "s": 26275, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 26363, "s": 26307, "text": "How to drop one or multiple columns in Pandas Dataframe" }, { "code": null, "e": 26384, "s": 26363, "text": "Python OOPs Concepts" }, { "code": null, "e": 26423, "s": 26384, "text": "Python | Get unique values from a list" }, { "code": null, "e": 26465, "s": 26423, "text": "Check if element exists in list in Python" }, { "code": null, "e": 26492, "s": 26465, "text": "Python Classes and Objects" }, { "code": null, "e": 26523, "s": 26492, "text": "Python | os.path.join() method" }, { "code": null, "e": 26565, "s": 26523, "text": "How To Convert Python Dictionary To JSON?" }, { "code": null, "e": 26601, "s": 26565, "text": "Python | Pandas dataframe.groupby()" } ]
Computer Programming - Arrays
Consider a situation where we need to store five integer numbers. If we use programming's simple variable and data type concepts, then we need five variables of int data type and the program will be as follows − #include <stdio.h> int main() { int number1; int number2; int number3; int number4; int number5; number1 = 10; number2 = 20; number3 = 30; number4 = 40; number5 = 50; printf( "number1: %d\n", number1); printf( "number2: %d\n", number2); printf( "number3: %d\n", number3); printf( "number4: %d\n", number4); printf( "number5: %d\n", number5); } It was simple, because we had to store just five integer numbers. Now let's assume we have to store 5000 integer numbers. Are we going to use 5000 variables? To handle such situations, almost all the programming languages provide a concept called array. An array is a data structure, which can store a fixed-size collection of elements of the same data type. An array is used to store a collection of data, but it is often more useful to think of an array as a collection of variables of the same type. Instead of declaring individual variables, such as number1, number2, ..., number99, you just declare one array variable number of integer type and use number1[0], number1[1], and ..., number1[99] to represent individual variables. Here, 0, 1, 2, .....99 are index associated with var variable and they are being used to represent individual elements available in the array. All arrays consist of contiguous memory locations. The lowest address corresponds to the first element and the highest address to the last element. To create an array variable in C, a programmer specifies the type of the elements and the number of elements to be stored in that array. Given below is a simple syntax to create an array in C programming − type arrayName [ arraySize ]; This is called a single-dimensional array. The arraySize must be an integer constant greater than zero and type can be any valid C data type. For example, now to declare a 10-element array called number of type int, use this statement − int number[10]; Here, number is a variable array, which is sufficient to hold up to 10 integer numbers. You can initialize an array in C either one by one or using a single statement as follows − int number[5] = {10, 20, 30, 40, 50}; The number of values between braces { } cannot be larger than the number of elements that we declare for the array between square brackets [ ]. If you omit the size of the array, an array just big enough to hold the initialization is created. Therefore, if you write − int number[] = {10, 20, 30, 40, 50}; You will create exactly the same array as you did in the previous example. Following is an example to assign a single element of the array − number[4] = 50; The above statement assigns element number 5th in the array with a value of 50. All arrays have 0 as the index of their first element which is also called the base index and the last index of an array will be the total size of the array minus 1. The following image shows the pictorial representation of the array we discussed above − An element is accessed by indexing the array name. This is done by placing the index of the element within square brackets after the name of the array. For example − int var = number[9]; The above statement will take the 10th element from the array and assign the value to var variable. The following example uses all the above-mentioned three concepts viz. creation, assignment, and accessing arrays − #include <stdio.h> int main () { int number[10]; /* number is an array of 10 integers */ int i = 0; /* Initialize elements of array n to 0 */ while( i < 10 ) { /* Set element at location i to i + 100 */ number[ i ] = i + 100; i = i + 1; } /* Output each array element's value */ i = 0; while( i < 10 ) { printf("number[%d] = %d\n", i, number[i] ); i = i + 1; } return 0; } When the above code is compiled and executed, it produces the following result − number[0] = 100 number[1] = 101 number[2] = 102 number[3] = 103 number[4] = 104 number[5] = 105 number[6] = 106 number[7] = 107 number[8] = 108 number[9] = 109 Following is the equivalent program written in Java. Java supports arrays, but there is a little difference in the way they are created in Java using the new operator. You can try to execute the following program to see the output, which must be identical to the result generated by the above C example. public class DemoJava { public static void main(String []args) { int[] number = new int[10]; int i = 0; while( i < 10 ) { number[ i ] = i + 100; i = i + 1; } i = 0; while( i < 10 ) { System.out.format( "number[%d] = %d\n", i, number[i] ); i = i + 1; } } } When the above program is executed, it produces the following result − number[0] = 100 number[1] = 101 number[2] = 102 number[3] = 103 number[4] = 104 number[5] = 105 number[6] = 106 number[7] = 107 number[8] = 108 number[9] = 109 Python does not have a concept of Array, instead Python provides another data structure called list, which provides similar functionality as arrays in any other language. Following is the equivalent program written in Python − # Following defines an empty list. number = [] i = 0 while i < 10: # Appending elements in the list number.append(i + 100) i = i + 1 i = 0 while i < 10: # Accessing elements from the list print "number[", i, "] = ", number[ i ] i = i + 1 When the above program is executed, it produces the following result − number[ 0 ] = 100 number[ 1 ] = 101 number[ 2 ] = 102 number[ 3 ] = 103 number[ 4 ] = 104 number[ 5 ] = 105 number[ 6 ] = 106 number[ 7 ] = 107 number[ 8 ] = 108 number[ 9 ] = 109 107 Lectures 13.5 hours Arnab Chakraborty 106 Lectures 8 hours Arnab Chakraborty 99 Lectures 6 hours Arnab Chakraborty 46 Lectures 2.5 hours Shweta 70 Lectures 9 hours Abhilash Nelson 52 Lectures 7 hours Abhishek And Pukhraj Print Add Notes Bookmark this page
[ { "code": null, "e": 2352, "s": 2140, "text": "Consider a situation where we need to store five integer numbers. If we use programming's simple variable and data type concepts, then we need five variables of int data type and the program will be as follows −" }, { "code": null, "e": 2765, "s": 2352, "text": "#include <stdio.h>\n\nint main() {\n int number1;\n int number2;\n int number3;\n int number4;\n int number5;\n \n number1 = 10; \n number2 = 20; \n number3 = 30; \n number4 = 40; \n number5 = 50; \n\n printf( \"number1: %d\\n\", number1);\n printf( \"number2: %d\\n\", number2);\n printf( \"number3: %d\\n\", number3);\n printf( \"number4: %d\\n\", number4);\n printf( \"number5: %d\\n\", number5);\n}" }, { "code": null, "e": 2923, "s": 2765, "text": "It was simple, because we had to store just five integer numbers. Now let's assume we have to store 5000 integer numbers. Are we going to use 5000 variables?" }, { "code": null, "e": 3268, "s": 2923, "text": "To handle such situations, almost all the programming languages provide a concept called array. An array is a data structure, which can store a fixed-size collection of elements of the same data type. An array is used to store a collection of data, but it is often more useful to think of an array as a collection of variables of the same type." }, { "code": null, "e": 3642, "s": 3268, "text": "Instead of declaring individual variables, such as number1, number2, ..., number99, you just declare one array variable number of integer type and use number1[0], number1[1], and ..., number1[99] to represent individual variables. Here, 0, 1, 2, .....99 are index associated with var variable and they are being used to represent individual elements available in the array." }, { "code": null, "e": 3790, "s": 3642, "text": "All arrays consist of contiguous memory locations. The lowest address corresponds to the first element and the highest address to the last element." }, { "code": null, "e": 3996, "s": 3790, "text": "To create an array variable in C, a programmer specifies the type of the elements and the number of elements to be stored in that array. Given below is a simple syntax to create an array in C programming −" }, { "code": null, "e": 4027, "s": 3996, "text": "type arrayName [ arraySize ];\n" }, { "code": null, "e": 4264, "s": 4027, "text": "This is called a single-dimensional array. The arraySize must be an integer constant greater than zero and type can be any valid C data type. For example, now to declare a 10-element array called number of type int, use this statement −" }, { "code": null, "e": 4281, "s": 4264, "text": "int number[10];\n" }, { "code": null, "e": 4369, "s": 4281, "text": "Here, number is a variable array, which is sufficient to hold up to 10 integer numbers." }, { "code": null, "e": 4461, "s": 4369, "text": "You can initialize an array in C either one by one or using a single statement as follows −" }, { "code": null, "e": 4500, "s": 4461, "text": "int number[5] = {10, 20, 30, 40, 50};\n" }, { "code": null, "e": 4644, "s": 4500, "text": "The number of values between braces { } cannot be larger than the number of elements that we declare for the array between square brackets [ ]." }, { "code": null, "e": 4769, "s": 4644, "text": "If you omit the size of the array, an array just big enough to hold the initialization is created. Therefore, if you write −" }, { "code": null, "e": 4807, "s": 4769, "text": "int number[] = {10, 20, 30, 40, 50};\n" }, { "code": null, "e": 4948, "s": 4807, "text": "You will create exactly the same array as you did in the previous example. Following is an example to assign a single element of the array −" }, { "code": null, "e": 4965, "s": 4948, "text": "number[4] = 50;\n" }, { "code": null, "e": 5300, "s": 4965, "text": "The above statement assigns element number 5th in the array with a value of 50. All arrays have 0 as the index of their first element which is also called the base index and the last index of an array will be the total size of the array minus 1. The following image shows the pictorial representation of the array we discussed above −" }, { "code": null, "e": 5466, "s": 5300, "text": "An element is accessed by indexing the array name. This is done by placing the index of the element within square brackets after the name of the array. For example −" }, { "code": null, "e": 5488, "s": 5466, "text": "int var = number[9];\n" }, { "code": null, "e": 5704, "s": 5488, "text": "The above statement will take the 10th element from the array and assign the value to var variable. The following example uses all the above-mentioned three concepts viz. creation, assignment, and accessing arrays −" }, { "code": null, "e": 6162, "s": 5704, "text": "#include <stdio.h>\n \nint main () {\n int number[10]; /* number is an array of 10 integers */\n int i = 0;\n \n /* Initialize elements of array n to 0 */ \n while( i < 10 ) {\n\t\n /* Set element at location i to i + 100 */\n number[ i ] = i + 100;\n i = i + 1;\n }\n \n /* Output each array element's value */\n i = 0;\n while( i < 10 ) {\n\t\n printf(\"number[%d] = %d\\n\", i, number[i] );\n i = i + 1;\n }\n \n return 0;\n}" }, { "code": null, "e": 6243, "s": 6162, "text": "When the above code is compiled and executed, it produces the following result −" }, { "code": null, "e": 6404, "s": 6243, "text": "number[0] = 100\nnumber[1] = 101\nnumber[2] = 102\nnumber[3] = 103\nnumber[4] = 104\nnumber[5] = 105\nnumber[6] = 106\nnumber[7] = 107\nnumber[8] = 108\nnumber[9] = 109\n" }, { "code": null, "e": 6572, "s": 6404, "text": "Following is the equivalent program written in Java. Java supports arrays, but there is a little difference in the way they are created in Java using the new operator." }, { "code": null, "e": 6708, "s": 6572, "text": "You can try to execute the following program to see the output, which must be identical to the result generated by the above C example." }, { "code": null, "e": 7059, "s": 6708, "text": "public class DemoJava {\n public static void main(String []args) {\n int[] number = new int[10];\n int i = 0;\n \n while( i < 10 ) {\n\t\t\n number[ i ] = i + 100;\n i = i + 1;\n }\n\n i = 0;\n while( i < 10 ) {\n System.out.format( \"number[%d] = %d\\n\", i, number[i] );\n i = i + 1;\n }\n }\n}" }, { "code": null, "e": 7130, "s": 7059, "text": "When the above program is executed, it produces the following result −" }, { "code": null, "e": 7291, "s": 7130, "text": "number[0] = 100\nnumber[1] = 101\nnumber[2] = 102\nnumber[3] = 103\nnumber[4] = 104\nnumber[5] = 105\nnumber[6] = 106\nnumber[7] = 107\nnumber[8] = 108\nnumber[9] = 109\n" }, { "code": null, "e": 7462, "s": 7291, "text": "Python does not have a concept of Array, instead Python provides another data structure called list, which provides similar functionality as arrays in any other language." }, { "code": null, "e": 7518, "s": 7462, "text": "Following is the equivalent program written in Python −" }, { "code": null, "e": 7777, "s": 7518, "text": "# Following defines an empty list.\nnumber = []\ni = 0\n\nwhile i < 10:\n # Appending elements in the list\n number.append(i + 100)\n i = i + 1\n\ni = 0\nwhile i < 10:\n # Accessing elements from the list\n print \"number[\", i, \"] = \", number[ i ]\n i = i + 1" }, { "code": null, "e": 7848, "s": 7777, "text": "When the above program is executed, it produces the following result −" }, { "code": null, "e": 8039, "s": 7848, "text": "number[ 0 ] = 100\nnumber[ 1 ] = 101\nnumber[ 2 ] = 102\nnumber[ 3 ] = 103\nnumber[ 4 ] = 104\nnumber[ 5 ] = 105\nnumber[ 6 ] = 106\nnumber[ 7 ] = 107\nnumber[ 8 ] = 108\nnumber[ 9 ] = 109\n" }, { "code": null, "e": 8076, "s": 8039, "text": "\n 107 Lectures \n 13.5 hours \n" }, { "code": null, "e": 8095, "s": 8076, "text": " Arnab Chakraborty" }, { "code": null, "e": 8129, "s": 8095, "text": "\n 106 Lectures \n 8 hours \n" }, { "code": null, "e": 8148, "s": 8129, "text": " Arnab Chakraborty" }, { "code": null, "e": 8181, "s": 8148, "text": "\n 99 Lectures \n 6 hours \n" }, { "code": null, "e": 8200, "s": 8181, "text": " Arnab Chakraborty" }, { "code": null, "e": 8235, "s": 8200, "text": "\n 46 Lectures \n 2.5 hours \n" }, { "code": null, "e": 8243, "s": 8235, "text": " Shweta" }, { "code": null, "e": 8276, "s": 8243, "text": "\n 70 Lectures \n 9 hours \n" }, { "code": null, "e": 8293, "s": 8276, "text": " Abhilash Nelson" }, { "code": null, "e": 8326, "s": 8293, "text": "\n 52 Lectures \n 7 hours \n" }, { "code": null, "e": 8348, "s": 8326, "text": " Abhishek And Pukhraj" }, { "code": null, "e": 8355, "s": 8348, "text": " Print" }, { "code": null, "e": 8366, "s": 8355, "text": " Add Notes" } ]
Spinning up Jupyter Notebooks as ECS Service in AWS With Terraform | by Stephan Schrijver | Towards Data Science
The data scientists in our team need to run time consuming Python scripts very often. Depending on the repetition of the task, we decide whether to Dockerize it and run it on AWS or not. If a script needs to be run multiple times, we put effort in rewriting/restructuring the code and wrap it into a container, then deploy it to ECR and schedule it as a Fargate task, for example. If it’s a one-off, it turns out that it’s sometimes easier to run the scripts locally, with all additional disadvantages. Running (heavy) scripts locally eats memory and CPU, with the result that you can’t really do other things that demand a lot from your laptop while the script is running. A solution we used for a long time, was to spin up EC2 instances and run the scripts on those instances. In my opinion that doesn’t feel like a maintainable solution, but it was working and we didn’t have any other solution. The team uses Jupyter Notebooks a lot (locally). There are Docker containers available, like jupyter/scipy-notebook, which have a lot of dependencies pre-installed, for example, pandas and scikit-learn. An idea we came up with, was to easily spin up a Docker container on AWS based on that image, which then could be used by a team member. So, we wanted to be able to spin up a Jupyter Notebook in the cloud without too much hassle, if possible even a separate instance for everyone, so dependencies, resources and files are not shared or mixed up. The notebooks should or should not have to interact with other AWS resources. I came across the wiki of the jupyterhub Git repository and there I found a page about Spawners. There is a FargateSpawner, but honestly, I missed the documentation to get it to work properly. Update 9 June 2020: You also might be interested in a new article I posted recently about spinning up Polynote Notebooks, which solves some issues I have encountered with Jupyter. towardsdatascience.com Terraform is a tool for building, changing, and versioning infrastructure safely and efficiently. Terraform can manage existing and popular service providers as well as custom in-house solutions. — Terraform The past few months we have been experimenting with Terraform a lot. We have an ideal situation in mind, where all our resources and infrastructure are set up and maintained as code through Terraform, but that’s still a long way off. Although it gave a new perspective to the problem we were facing. After an hour or two working on Terraform files, I came with a working solution, which is currently being tested within our team! I’ve set up a Git repository to share the scripts I’ve created. You can find that Git repository here and I will explain it along the way. I’ll not be providing the whole Terraform script in a single code snippet in this article, for that, I want to refer to the Git repository. I will split the script in chunks and provide information per snippet. There are some prerequisites to get this to work (referring to the data blocks in the main.tf script). We already have the following services set up in AWS: An ECS cluster An application load balancer An hosted zone and domain within Route53 If you do not have these things in place, you could choose to set them up through Terraform (would definitely suggest doing that elsewhere, in a place where you define and maintain your base architecture). But of course, you can also set these up in the AWS console manually, like we did a while ago. I’ve used variables where possible. This is because we have multiple AWS environments and we want to be able to easily spin up the notebooks on these different environments. We also want to be able to tweak memory and CPU without having to change the terraform scripts. My vars.tfvars and vars.tf look like the following: vars.tfvars (replace everything in capitals and revisit other variable values): vpc_id = "VPC_ID_HERE"region = "REGION_HERE"profile_name ="PROFILE_NAME_HERE"ecs_cluster_name = "ECS_CLUSTER_NAME_HERE"loadbalancer_arn = "LOAD_BALANCER_ARN_HERE"hosted_zone_id = "ROUTE_53_HOSTED_ZONE_HERE"fargate_subnets = [ "SUBNET_1_HERE", "SUBNET_2_HERE", "SUBNET_3_HERE"]jupyter_docker_tag = "latest" #Update July 2021: change this to "dc9744740e12"cpu = 1024memory = 2048domain = "ROUTE_53_DOMAIN_NAME_HERE" vars.tf variable "vpc_id" {}variable "region" {}variable "profile_name" {}variable "ecs_cluster_name" {}variable "loadbalancer_arn" {}variable "hosted_zone_id" {}variable "fargate_subnets" { type = list(string)}variable "token" {}variable "jupyter_docker_tag" {}variable "memory" {}variable "cpu" {}variable "domain" {} First, install Terraform if you didn’t already. After installation, you can run the following command within the folder in which you’ve saved main.tf, vars.tfvars and vars.tf (and after running terraform init): terraform apply -var-file=vars.tfvars It will ask you for a token, which you can use to access the notebook, and will ask you for an approval to make the changes in your AWS cloud environment. After a few seconds, it will output a url you can use to access the environment. It may take a few minutes before the Docker image is really running and accessible, so don’t worry if you don’t get the response you expect right away. You’ll probably receive a HTTP 503 response the first few minutes. When you’re done using the Jupyter environment, simply run the command below. Provide the same token you used while setting up the environment and don’t type ‘yes’ to approve the command. All created resources will be removed. You could choose to save the Jupyter notebook on your local machine first if you want to run it again later. terraform destroy -var-file=vars.tfvars Down here I will further explain what’s in the repository and will be providing extra information per code snippet about what the script actually does. I’ll want to inform you about what the script is doing, assuming you already have some Terraform experience or are willing to look it up yourself. With the data blocks, we’re retrieving information about AWS resources that are already in place. As you can see in the first data block, I want to retrieve information of the ECS cluster that already exists. data "aws_ecs_cluster" "ecs_cluster" { cluster_name = var.ecs_cluster_name} I’m creating a random string, which will be used by several resources later on. This random string is the key element in this script to allow multiple users to spin up notebooks at the same time. resource "random_string" "random_string" { length = 8 special = false} We need to create a task execution role that has policies attached to it which allow us to write to CloudWatch for example. That policy is already provided by AWS (see the data “aws_iam_policy" “amazon_ecs...." block below, but we still need a role which has that policy attached to it. resource "aws_iam_role" "ecs_task_execution_role" { name = "ecsTaskExecutionRole-jupyter-${random_string.random_string.result}" assume_role_policy = <<ASSUME_ROLE_POLICY{"Version": "2012-10-17","Statement": [ { "Sid": "", "Effect": "Allow", "Principal": { "Service": "ecs-tasks.amazonaws.com" }, "Action": "sts:AssumeRole" } ]}ASSUME_ROLE_POLICY}data "aws_iam_policy" "amazon_ecs_task_execution_role_policy" { arn = "arn:aws:iam::aws:policy/service-role/AmazonECSTaskExecutionRolePolicy"}resource "aws_iam_role_policy_attachment" "policy_role_attachment" { role = aws_iam_role.ecs_task_execution_role.name policy_arn = data.aws_iam_policy.amazon_ecs_task_execution_role_policy.arn} For logging purposes, I’m creating a CloudWatch Group, of course, you can set this whatever you want. resource "aws_cloudwatch_log_group" "jupyter_ecs_log_group" { name = "/aws/ecs/jupyter-${random_string.random_string.result}"} Every Fargate or EC2 service/task on ECS needs a task definition that defines what Docker container to use, how many CPU and memory it needs et cetera. You can think of it as a blueprint. As you can see below, I specified the jupyter/data science-notebook as the image. I also changed the entry point, so a custom token can be set, else it will generate a random token which is not very easy to retrieve from the system. resource "aws_ecs_task_definition" "jupyter_task_definition" { family = "jupyter-${random_string.random_string.result}" requires_compatibilities = [ "FARGATE"] network_mode = "awsvpc" cpu = var.cpu memory = var.memory execution_role_arn = data.aws_iam_role.ecs_task_execution_role.arn container_definitions = <<TASK_DEFINITION [ { "entryPoint": ["start-notebook.sh","--NotebookApp.token='${var.token}'"], "essential": true, "image": "registry.hub.docker.com/jupyter/datascience-notebook:${var.jupyter_docker_tag}", "name": "jupyter-${random_string.random_string.result}", "portMappings": [ { "containerPort": 8888, "hostPort": 8888 } ], "logConfiguration": { "logDriver": "awslogs", "options": { "awslogs-region": "${var.region}", "awslogs-group": "${aws_cloudwatch_log_group.jupyter_ecs_log_group.name}", "awslogs-stream-prefix": "${random_string.random_string.result}" } } } ] TASK_DEFINITION} Like I mentioned, we already had a load balancer with a HTTPS listener in place, so we want to retrieve information from it which we can use later on (along with the info of our VPC). You could also be using port 80 of course, but my advice is to use port 443. data "aws_vpc" "vpc" { id = var.vpc_id}data "aws_lb" "lb" { arn = var.loadbalancer_arn}data "aws_lb_listener" "lb_listener" { load_balancer_arn = var.loadbalancer_arn port = 443} This setup also needs a target group, the load balancer listener rule will be pointing to that target group. This target group will be used later on in the aws_ecs_service resource block. resource "aws_lb_target_group" "jupyter_target_group" { name = "jupyter-${random_string.random_string.result}" port = 80 protocol = "HTTP" vpc_id = data.aws_vpc.vpc.id target_type = "ip" health_check { matcher = "200,302" }} We also need to expose port 8888 from our container to our load balancer. I exposed port 8888 to the security groups which are attached to the load balancer. resource "aws_security_group" "jupyter_security_group" { name = "jupyter_${random_string.random_string.result}" vpc_id = data.aws_vpc.vpc.id ingress { description = "Incoming 8888" from_port = 8888 to_port = 8888 protocol = "tcp" security_groups = data.aws_lb.lb.security_groups } egress { from_port = 0 to_port = 0 protocol = "-1" cidr_blocks = [ "0.0.0.0/0"] } tags = { Name = "jupyter_${random_string.random_string.result}" }} With all these resources in place, we can finally define our ECS service. resource "aws_ecs_service" "jupyter_service" { name = "jupyter-${random_string.random_string.result}" cluster = data.aws_ecs_cluster.ecs_cluster.id task_definition = aws_ecs_task_definition.jupyter_task_definition.id desired_count = 1 launch_type = "FARGATE" network_configuration { subnets = var.fargate_subnets security_groups = [ aws_security_group.jupyter_security_group.id] } load_balancer { target_group_arn = aws_lb_target_group.jupyter_target_group.arn container_name = "jupyter-${random_string.random_string.result}" container_port = 8888 } depends_on = [ aws_lb_target_group.jupyter_target_group]} Then, add a forwarding rule in the load balancer. Assume we have the following domain: company.com, and the random string is 123. It will forward to the Jupyter target group if the host-header is jupyter-123.company.com. Update July 2021: field = "host-header" only works until version 2.41.0 of the AWS provider, pin the AWS provider using required_providers or update the condition block so it works with the latest version. resource "aws_lb_listener_rule" "jupyter_lb_listener_rule" { listener_arn = data.aws_lb_listener.lb_listener.arn priority = null action { type = "forward" target_group_arn = aws_lb_target_group.jupyter_target_group.arn } condition { field = "host-header" values = [ "jupyter-${random_string.random_string.result}.${var.domain}"] } depends_on = [ aws_lb_target_group.jupyter_target_group]} Then add that CNAME in Route53 which points to the load balancer. To continue on the previous example, the CNAME will be jupyter-123.company.com which will be pointing to our load balancer url. resource "aws_route53_record" "jupyter_cname" { zone_id = var.hosted_zone_id name = "jupyter-${random_string.random_string.result}.${var.domain}" type = "CNAME" records = [ data.aws_lb.lb.dns_name] ttl = 300} Everything is in place now, and we, of course, want to know how to access the notebook, because some strings are randomly generated and we have set a token in the beginning. We can do this by an output variable. output "url" { value = "${aws_route53_record.jupyter_cname.name}?token=${var.token}"} Currently, the Jupyter Notebook cannot access other AWS resources. Therefore you have to provide a task role within the task definition. Also, when you want to access databases within your VPC, you have to add an inbound/ingress rule in the security group of your database, which allows incoming traffic from the security group attached to the ECS service. The state is set to local for now, so people that spin up the notebooks with this script, are also responsible for destroying them. If you have any questions or feedback regarding this article, don’t hesitate to contact me or leave a comment. Since the version of the Jupyter docker image was not pinned to a specific version in this article at the moment of publishing, I added a comment in vars.tfvars. The image tag in the comments is the image which was the latest version of the docker image at the moment of writing this article. When you want to use the latest version of the the docker image: GitHub user mvtango created a pull request in my repository. From my understanding, the latest images are using Jupyter Lab by default.
[ { "code": null, "e": 674, "s": 171, "text": "The data scientists in our team need to run time consuming Python scripts very often. Depending on the repetition of the task, we decide whether to Dockerize it and run it on AWS or not. If a script needs to be run multiple times, we put effort in rewriting/restructuring the code and wrap it into a container, then deploy it to ECR and schedule it as a Fargate task, for example. If it’s a one-off, it turns out that it’s sometimes easier to run the scripts locally, with all additional disadvantages." }, { "code": null, "e": 1070, "s": 674, "text": "Running (heavy) scripts locally eats memory and CPU, with the result that you can’t really do other things that demand a lot from your laptop while the script is running. A solution we used for a long time, was to spin up EC2 instances and run the scripts on those instances. In my opinion that doesn’t feel like a maintainable solution, but it was working and we didn’t have any other solution." }, { "code": null, "e": 1410, "s": 1070, "text": "The team uses Jupyter Notebooks a lot (locally). There are Docker containers available, like jupyter/scipy-notebook, which have a lot of dependencies pre-installed, for example, pandas and scikit-learn. An idea we came up with, was to easily spin up a Docker container on AWS based on that image, which then could be used by a team member." }, { "code": null, "e": 1697, "s": 1410, "text": "So, we wanted to be able to spin up a Jupyter Notebook in the cloud without too much hassle, if possible even a separate instance for everyone, so dependencies, resources and files are not shared or mixed up. The notebooks should or should not have to interact with other AWS resources." }, { "code": null, "e": 1890, "s": 1697, "text": "I came across the wiki of the jupyterhub Git repository and there I found a page about Spawners. There is a FargateSpawner, but honestly, I missed the documentation to get it to work properly." }, { "code": null, "e": 2070, "s": 1890, "text": "Update 9 June 2020: You also might be interested in a new article I posted recently about spinning up Polynote Notebooks, which solves some issues I have encountered with Jupyter." }, { "code": null, "e": 2093, "s": 2070, "text": "towardsdatascience.com" }, { "code": null, "e": 2289, "s": 2093, "text": "Terraform is a tool for building, changing, and versioning infrastructure safely and efficiently. Terraform can manage existing and popular service providers as well as custom in-house solutions." }, { "code": null, "e": 2301, "s": 2289, "text": "— Terraform" }, { "code": null, "e": 2731, "s": 2301, "text": "The past few months we have been experimenting with Terraform a lot. We have an ideal situation in mind, where all our resources and infrastructure are set up and maintained as code through Terraform, but that’s still a long way off. Although it gave a new perspective to the problem we were facing. After an hour or two working on Terraform files, I came with a working solution, which is currently being tested within our team!" }, { "code": null, "e": 3081, "s": 2731, "text": "I’ve set up a Git repository to share the scripts I’ve created. You can find that Git repository here and I will explain it along the way. I’ll not be providing the whole Terraform script in a single code snippet in this article, for that, I want to refer to the Git repository. I will split the script in chunks and provide information per snippet." }, { "code": null, "e": 3238, "s": 3081, "text": "There are some prerequisites to get this to work (referring to the data blocks in the main.tf script). We already have the following services set up in AWS:" }, { "code": null, "e": 3253, "s": 3238, "text": "An ECS cluster" }, { "code": null, "e": 3282, "s": 3253, "text": "An application load balancer" }, { "code": null, "e": 3323, "s": 3282, "text": "An hosted zone and domain within Route53" }, { "code": null, "e": 3624, "s": 3323, "text": "If you do not have these things in place, you could choose to set them up through Terraform (would definitely suggest doing that elsewhere, in a place where you define and maintain your base architecture). But of course, you can also set these up in the AWS console manually, like we did a while ago." }, { "code": null, "e": 3946, "s": 3624, "text": "I’ve used variables where possible. This is because we have multiple AWS environments and we want to be able to easily spin up the notebooks on these different environments. We also want to be able to tweak memory and CPU without having to change the terraform scripts. My vars.tfvars and vars.tf look like the following:" }, { "code": null, "e": 4026, "s": 3946, "text": "vars.tfvars (replace everything in capitals and revisit other variable values):" }, { "code": null, "e": 4443, "s": 4026, "text": "vpc_id = \"VPC_ID_HERE\"region = \"REGION_HERE\"profile_name =\"PROFILE_NAME_HERE\"ecs_cluster_name = \"ECS_CLUSTER_NAME_HERE\"loadbalancer_arn = \"LOAD_BALANCER_ARN_HERE\"hosted_zone_id = \"ROUTE_53_HOSTED_ZONE_HERE\"fargate_subnets = [ \"SUBNET_1_HERE\", \"SUBNET_2_HERE\", \"SUBNET_3_HERE\"]jupyter_docker_tag = \"latest\" #Update July 2021: change this to \"dc9744740e12\"cpu = 1024memory = 2048domain = \"ROUTE_53_DOMAIN_NAME_HERE\"" }, { "code": null, "e": 4451, "s": 4443, "text": "vars.tf" }, { "code": null, "e": 4764, "s": 4451, "text": "variable \"vpc_id\" {}variable \"region\" {}variable \"profile_name\" {}variable \"ecs_cluster_name\" {}variable \"loadbalancer_arn\" {}variable \"hosted_zone_id\" {}variable \"fargate_subnets\" { type = list(string)}variable \"token\" {}variable \"jupyter_docker_tag\" {}variable \"memory\" {}variable \"cpu\" {}variable \"domain\" {}" }, { "code": null, "e": 4975, "s": 4764, "text": "First, install Terraform if you didn’t already. After installation, you can run the following command within the folder in which you’ve saved main.tf, vars.tfvars and vars.tf (and after running terraform init):" }, { "code": null, "e": 5013, "s": 4975, "text": "terraform apply -var-file=vars.tfvars" }, { "code": null, "e": 5468, "s": 5013, "text": "It will ask you for a token, which you can use to access the notebook, and will ask you for an approval to make the changes in your AWS cloud environment. After a few seconds, it will output a url you can use to access the environment. It may take a few minutes before the Docker image is really running and accessible, so don’t worry if you don’t get the response you expect right away. You’ll probably receive a HTTP 503 response the first few minutes." }, { "code": null, "e": 5804, "s": 5468, "text": "When you’re done using the Jupyter environment, simply run the command below. Provide the same token you used while setting up the environment and don’t type ‘yes’ to approve the command. All created resources will be removed. You could choose to save the Jupyter notebook on your local machine first if you want to run it again later." }, { "code": null, "e": 5844, "s": 5804, "text": "terraform destroy -var-file=vars.tfvars" }, { "code": null, "e": 5996, "s": 5844, "text": "Down here I will further explain what’s in the repository and will be providing extra information per code snippet about what the script actually does." }, { "code": null, "e": 6352, "s": 5996, "text": "I’ll want to inform you about what the script is doing, assuming you already have some Terraform experience or are willing to look it up yourself. With the data blocks, we’re retrieving information about AWS resources that are already in place. As you can see in the first data block, I want to retrieve information of the ECS cluster that already exists." }, { "code": null, "e": 6429, "s": 6352, "text": "data \"aws_ecs_cluster\" \"ecs_cluster\" { cluster_name = var.ecs_cluster_name}" }, { "code": null, "e": 6625, "s": 6429, "text": "I’m creating a random string, which will be used by several resources later on. This random string is the key element in this script to allow multiple users to spin up notebooks at the same time." }, { "code": null, "e": 6698, "s": 6625, "text": "resource \"random_string\" \"random_string\" { length = 8 special = false}" }, { "code": null, "e": 6985, "s": 6698, "text": "We need to create a task execution role that has policies attached to it which allow us to write to CloudWatch for example. That policy is already provided by AWS (see the data “aws_iam_policy\" “amazon_ecs....\" block below, but we still need a role which has that policy attached to it." }, { "code": null, "e": 7711, "s": 6985, "text": "resource \"aws_iam_role\" \"ecs_task_execution_role\" { name = \"ecsTaskExecutionRole-jupyter-${random_string.random_string.result}\" assume_role_policy = <<ASSUME_ROLE_POLICY{\"Version\": \"2012-10-17\",\"Statement\": [ { \"Sid\": \"\", \"Effect\": \"Allow\", \"Principal\": { \"Service\": \"ecs-tasks.amazonaws.com\" }, \"Action\": \"sts:AssumeRole\" } ]}ASSUME_ROLE_POLICY}data \"aws_iam_policy\" \"amazon_ecs_task_execution_role_policy\" { arn = \"arn:aws:iam::aws:policy/service-role/AmazonECSTaskExecutionRolePolicy\"}resource \"aws_iam_role_policy_attachment\" \"policy_role_attachment\" { role = aws_iam_role.ecs_task_execution_role.name policy_arn = data.aws_iam_policy.amazon_ecs_task_execution_role_policy.arn}" }, { "code": null, "e": 7813, "s": 7711, "text": "For logging purposes, I’m creating a CloudWatch Group, of course, you can set this whatever you want." }, { "code": null, "e": 7941, "s": 7813, "text": "resource \"aws_cloudwatch_log_group\" \"jupyter_ecs_log_group\" { name = \"/aws/ecs/jupyter-${random_string.random_string.result}\"}" }, { "code": null, "e": 8362, "s": 7941, "text": "Every Fargate or EC2 service/task on ECS needs a task definition that defines what Docker container to use, how many CPU and memory it needs et cetera. You can think of it as a blueprint. As you can see below, I specified the jupyter/data science-notebook as the image. I also changed the entry point, so a custom token can be set, else it will generate a random token which is not very easy to retrieve from the system." }, { "code": null, "e": 9477, "s": 8362, "text": "resource \"aws_ecs_task_definition\" \"jupyter_task_definition\" { family = \"jupyter-${random_string.random_string.result}\" requires_compatibilities = [ \"FARGATE\"] network_mode = \"awsvpc\" cpu = var.cpu memory = var.memory execution_role_arn = data.aws_iam_role.ecs_task_execution_role.arn container_definitions = <<TASK_DEFINITION [ { \"entryPoint\": [\"start-notebook.sh\",\"--NotebookApp.token='${var.token}'\"], \"essential\": true, \"image\": \"registry.hub.docker.com/jupyter/datascience-notebook:${var.jupyter_docker_tag}\", \"name\": \"jupyter-${random_string.random_string.result}\", \"portMappings\": [ { \"containerPort\": 8888, \"hostPort\": 8888 } ], \"logConfiguration\": { \"logDriver\": \"awslogs\", \"options\": { \"awslogs-region\": \"${var.region}\", \"awslogs-group\": \"${aws_cloudwatch_log_group.jupyter_ecs_log_group.name}\", \"awslogs-stream-prefix\": \"${random_string.random_string.result}\" } } } ] TASK_DEFINITION}" }, { "code": null, "e": 9738, "s": 9477, "text": "Like I mentioned, we already had a load balancer with a HTTPS listener in place, so we want to retrieve information from it which we can use later on (along with the info of our VPC). You could also be using port 80 of course, but my advice is to use port 443." }, { "code": null, "e": 9921, "s": 9738, "text": "data \"aws_vpc\" \"vpc\" { id = var.vpc_id}data \"aws_lb\" \"lb\" { arn = var.loadbalancer_arn}data \"aws_lb_listener\" \"lb_listener\" { load_balancer_arn = var.loadbalancer_arn port = 443}" }, { "code": null, "e": 10109, "s": 9921, "text": "This setup also needs a target group, the load balancer listener rule will be pointing to that target group. This target group will be used later on in the aws_ecs_service resource block." }, { "code": null, "e": 10344, "s": 10109, "text": "resource \"aws_lb_target_group\" \"jupyter_target_group\" { name = \"jupyter-${random_string.random_string.result}\" port = 80 protocol = \"HTTP\" vpc_id = data.aws_vpc.vpc.id target_type = \"ip\" health_check { matcher = \"200,302\" }}" }, { "code": null, "e": 10502, "s": 10344, "text": "We also need to expose port 8888 from our container to our load balancer. I exposed port 8888 to the security groups which are attached to the load balancer." }, { "code": null, "e": 10975, "s": 10502, "text": "resource \"aws_security_group\" \"jupyter_security_group\" { name = \"jupyter_${random_string.random_string.result}\" vpc_id = data.aws_vpc.vpc.id ingress { description = \"Incoming 8888\" from_port = 8888 to_port = 8888 protocol = \"tcp\" security_groups = data.aws_lb.lb.security_groups } egress { from_port = 0 to_port = 0 protocol = \"-1\" cidr_blocks = [ \"0.0.0.0/0\"] } tags = { Name = \"jupyter_${random_string.random_string.result}\" }}" }, { "code": null, "e": 11049, "s": 10975, "text": "With all these resources in place, we can finally define our ECS service." }, { "code": null, "e": 11690, "s": 11049, "text": "resource \"aws_ecs_service\" \"jupyter_service\" { name = \"jupyter-${random_string.random_string.result}\" cluster = data.aws_ecs_cluster.ecs_cluster.id task_definition = aws_ecs_task_definition.jupyter_task_definition.id desired_count = 1 launch_type = \"FARGATE\" network_configuration { subnets = var.fargate_subnets security_groups = [ aws_security_group.jupyter_security_group.id] } load_balancer { target_group_arn = aws_lb_target_group.jupyter_target_group.arn container_name = \"jupyter-${random_string.random_string.result}\" container_port = 8888 } depends_on = [ aws_lb_target_group.jupyter_target_group]}" }, { "code": null, "e": 12117, "s": 11690, "text": "Then, add a forwarding rule in the load balancer. Assume we have the following domain: company.com, and the random string is 123. It will forward to the Jupyter target group if the host-header is jupyter-123.company.com. Update July 2021: field = \"host-header\" only works until version 2.41.0 of the AWS provider, pin the AWS provider using required_providers or update the condition block so it works with the latest version." }, { "code": null, "e": 12533, "s": 12117, "text": "resource \"aws_lb_listener_rule\" \"jupyter_lb_listener_rule\" { listener_arn = data.aws_lb_listener.lb_listener.arn priority = null action { type = \"forward\" target_group_arn = aws_lb_target_group.jupyter_target_group.arn } condition { field = \"host-header\" values = [ \"jupyter-${random_string.random_string.result}.${var.domain}\"] } depends_on = [ aws_lb_target_group.jupyter_target_group]}" }, { "code": null, "e": 12727, "s": 12533, "text": "Then add that CNAME in Route53 which points to the load balancer. To continue on the previous example, the CNAME will be jupyter-123.company.com which will be pointing to our load balancer url." }, { "code": null, "e": 12944, "s": 12727, "text": "resource \"aws_route53_record\" \"jupyter_cname\" { zone_id = var.hosted_zone_id name = \"jupyter-${random_string.random_string.result}.${var.domain}\" type = \"CNAME\" records = [ data.aws_lb.lb.dns_name] ttl = 300}" }, { "code": null, "e": 13156, "s": 12944, "text": "Everything is in place now, and we, of course, want to know how to access the notebook, because some strings are randomly generated and we have set a token in the beginning. We can do this by an output variable." }, { "code": null, "e": 13243, "s": 13156, "text": "output \"url\" { value = \"${aws_route53_record.jupyter_cname.name}?token=${var.token}\"}" }, { "code": null, "e": 13732, "s": 13243, "text": "Currently, the Jupyter Notebook cannot access other AWS resources. Therefore you have to provide a task role within the task definition. Also, when you want to access databases within your VPC, you have to add an inbound/ingress rule in the security group of your database, which allows incoming traffic from the security group attached to the ECS service. The state is set to local for now, so people that spin up the notebooks with this script, are also responsible for destroying them." }, { "code": null, "e": 13843, "s": 13732, "text": "If you have any questions or feedback regarding this article, don’t hesitate to contact me or leave a comment." } ]
Program to print the pattern "GFG" - GeeksforGeeks
13 Oct, 2021 In this article, given the value of n(length of the alphabet) and k(width of the alphabet) we will learn how to print the pattern “GFG” using stars and white-spaces. Examples: INPUT: n=7, k=5 OUTPUT: ***** ***** ***** * * * * * * * ** ***** * *** * * * * * * * * * * ***** * ***** INPUT: n=11, k=7 OUTPUT: ******* ******* ******* * * * * * * * * * * * * * ***** ******* * ***** * * * * * * * * * * * * * * * * * * * * ******* * ******* C++ Java Python3 C# PHP Javascript #include <iostream> using namespace std; // Function to print the pattern "GFG" void print1(int n, int k) { int i, j; for (i = 0; i < n; i++) { cout << "\n"; for (j = 0; j < (3 * k + 2); j++) { if ((i == 0 && j != k && /*For printing the upper portion of the pattern "GFG"*/ j != 2 * k + 1) || ((i == n / 2) && (j > 1) && (j != k) && (j != 2 * k + 1) && /* for printing the middle portion of the pattern "GFG" */ (j != 2 * k + 3)) || ((i == n - 1) && (j != k) && /* for printing the lower portion of the pattern "GFG" */ ((j <= k) || (j > 2 * k + 1))) || (j == 0) || (j == k + 1) || (j == (2 * k + 2)) || ((j == k - 1 || j == 3 * k + 1) && (i > n / 2))) cout << "*"; // printing * wherever required else cout << " "; // printing space wherever required } } } // Driver code int main() { int n = 7; // the length of the pattern "GFG" int k = 5; // the width of the pattern "GFG" print1(n, k); } import java.util.Scanner; public class PatternGFG // create a Class named PatternGFG { // Function to print the pattern "GFG" private static void print(int n, int k) { for (int i = 0; i < n; i++) { System.out.println(); for (int j = 0; j < (3 * k + 2); j++) { // For printing the upper portion of // the pattern "GFG" if ((i == 0 && j != k && j != 2 * k + 1) || ((i == n / 2) && (j > 1) && (j != k) && // for printing the middle portion of // the pattern "GFG" (j != 2 * k + 1) && (j != 2 * k + 3)) || ((i == n - 1) && (j != k) && // for printing the lower portion of // the pattern "GFG" ((j <= k) || (j > 2 * k + 1))) || (j == 0) || (j == k + 1) || (j == (2 * k + 2)) || ((j == k - 1 || j == 3 * k + 1) && (i > n / 2))) // printing * wherever required System.out.print("*"); else System.out.print(" "); // printing space wherever required } } } // Driver code public static void main(String[] args) { int n = 7, k = 5; // length and width of the pattern print(n, k); } } # Python Program to print # the pattern “GFG” import math # Function to print the # pattern "GFG" def print1(n, k) : for i in range(0, n) : print ("\n") for j in range(0, (3 * k + 2)) : if ((i == 0 and j != k and # For printing the # upper portion of # the pattern "GFG" j != 2 * k + 1) or ((i == math.floor(n / 2)) and (j > 1) and (j != k) and (j != 2 * k + 1) and # for printing the # middle portion of # the pattern "GFG" (j != 2 * k + 3)) or ((i == n - 1) and (j != k) and # for printing the # lower portion of # the pattern "GFG" ((j <= k) or (j > 2 * k + 1))) or (j == 0) or (j == k + 1) or (j == (2 * k + 2)) or ((j ==k - 1 or j == 3 * k + 1) and (i > math.floor(n / 2)))) : # printing * where # ever required print ("*", end = "") else : # printing space # wherever required print (" ", end = "") # Driver code # the length of the # pattern "GFG" n = 7 # the width of the # pattern "GFG" k = 5 print1(n, k) # This code is contributed # by Manish Shaw(manishshaw1) // C# code for printing pattern. using System; public class GFG { // Function to print the pattern "GFG" private static void print(int n, int k) { for (int i = 0; i < n; i++) { Console.WriteLine(); for (int j = 0; j < (3 * k + 2); j++) { // For printing the upper portion of // the pattern "GFG" if ((i == 0 && j != k && j != 2 * k + 1) || ((i == n / 2) && (j > 1) && (j != k) && // for printing the middle portion of // the pattern "GFG" (j != 2 * k + 1) && (j != 2 * k + 3)) || ((i == n - 1) && (j != k) && // for printing the lower portion of // the pattern "GFG" ((j <= k) || (j > 2 * k + 1))) || (j == 0) || (j == k + 1) || (j == (2 * k + 2)) || ((j == k - 1 || j == 3 * k + 1) && (i > n / 2))) // printing * wherever required Console.Write("*"); else Console.Write(" "); } } } // Driver code public static void Main() { // length and width of the pattern int n = 7, k = 5; print(n, k); } } // This code is contributed by vt_m. <?php // PHP Program to print // the pattern “GFG” // Function to print the // pattern "GFG" function print1($n, $k) { for ($i = 0; $i < $n; $i++) { echo "\n"; for ($j = 0; $j < (3 * $k + 2); $j++) { if (($i == 0 && $j != $k && // For printing the upper portion // of the pattern "GFG" $j != 2 * $k + 1) || (($i == floor($n / 2)) && ($j > 1) && ($j != $k) && ($j != 2 * $k + 1) && /* for printing the middle portion of the pattern "GFG" */ ($j != 2 * $k + 3)) || (($i == $n - 1) && ($j != $k) && /* for printing the lower portion of the pattern "GFG" */ (($j <= $k) || ($j > 2 * $k + 1))) || ($j == 0) || ($j == $k + 1) || ($j == (2 * $k + 2)) || (($j ==$k - 1 || $j == 3 * $k + 1) && ($i > floor($n / 2)))) // printing * wherever required echo "*"; else // printing space wherever required echo " "; } } } // Driver code // the length of the pattern "GFG" $n = 7; // the width of the pattern "GFG" $k = 5; print1($n, $k); // This code is contributed by Sam007 ?> <script> // Javascript implementation for the above approach // Function to print the pattern "GFG" function print1(n, k) { var i, j; for (i = 0; i < n; i++) { document.write("<br>"); for (j = 0; j < (3 * k + 2); j++) { if ((i == 0 && j != k && /*For printing the upper portion of the pattern "GFG"*/ j != 2 * k + 1) || ((i == n / 2) && (j > 1) && (j != k) && (j != 2 * k + 1) && /* for printing the middle portion of the pattern "GFG" */ (j != 2 * k + 3)) || ((i == n - 1) && (j != k) && /* for printing the lower portion of the pattern "GFG" */ ((j <= k) || (j > 2 * k + 1))) || (j == 0) || (j == k + 1) || (j == (2 * k + 2)) || ((j == k - 1 || j == 3 * k + 1) && (i > n / 2))) document.write("*"); // printing * wherever required else document.write(" "," "); // printing space wherever required } } } // Driver code var n = 7; // the length of the pattern "GFG" var k = 5; // the width of the pattern "GFG" print1(n, k); // This code is contributed by Shubham Singh </script> Output : ***** ***** ***** * * * * * * * ** ***** * *** * * * * * * * * * * ***** * ***** Sam007 manishshaw1 SHUBHAMSINGH10 saurabh1990aror pattern-printing School Programming Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Constructors in Java Exceptions in Java Ternary Operator in Python Inline Functions in C++ Difference between Abstract Class and Interface in Java Exception Handling in C++ Destructors in C++ Python Exception Handling 'this' pointer in C++ Python program to add two numbers
[ { "code": null, "e": 24198, "s": 24167, "text": " \n13 Oct, 2021\n" }, { "code": null, "e": 24376, "s": 24198, "text": "In this article, given the value of n(length of the alphabet) and k(width of the alphabet) we will learn how to print the pattern “GFG” using stars and white-spaces. Examples: " }, { "code": null, "e": 24795, "s": 24376, "text": "INPUT: n=7, k=5\nOUTPUT:\n***** ***** *****\n* * *\n* * *\n* ** ***** * ***\n* * * * *\n* * * * *\n***** * *****\n\nINPUT: n=11, k=7\nOUTPUT:\n******* ******* *******\n* * *\n* * *\n* * *\n* * *\n* ***** ******* * *****\n* * * * *\n* * * * *\n* * * * *\n* * * * *\n******* * *******" }, { "code": null, "e": 24801, "s": 24797, "text": "C++" }, { "code": null, "e": 24806, "s": 24801, "text": "Java" }, { "code": null, "e": 24814, "s": 24806, "text": "Python3" }, { "code": null, "e": 24817, "s": 24814, "text": "C#" }, { "code": null, "e": 24821, "s": 24817, "text": "PHP" }, { "code": null, "e": 24832, "s": 24821, "text": "Javascript" }, { "code": "\n\n\n\n\n\n\n#include <iostream>\n \nusing namespace std;\n \n// Function to print the pattern \"GFG\"\nvoid print1(int n, int k) {\n int i, j;\n for (i = 0; i < n; i++) {\n cout << \"\\n\";\n for (j = 0; j < (3 * k + 2); j++) {\n if ((i == 0 && j != k &&\n \n /*For printing the upper portion \n of the pattern \"GFG\"*/\n j != 2 * k + 1) || \n ((i == n / 2) && (j > 1) && (j != k) && \n (j != 2 * k + 1) &&\n \n /* for printing the middle portion\n of the pattern \"GFG\" */\n (j != 2 * k + 3)) || \n ((i == n - 1) && (j != k) &&\n \n /* for printing the lower portion of\n the pattern \"GFG\" */\n ((j <= k) || (j > 2 * k + 1))) \n || (j == 0) || (j == k + 1) || (j == (2 * k + 2)) ||\n ((j == k - 1 || j == 3 * k + 1) && (i > n / 2)))\n \n cout << \"*\"; // printing * wherever required\n \n else\n cout << \" \"; // printing space wherever required\n }\n }\n}\n \n// Driver code\nint main() {\n int n = 7; // the length of the pattern \"GFG\"\n int k = 5; // the width of the pattern \"GFG\"\n print1(n, k);\n}\n\n\n\n\n\n", "e": 26001, "s": 24842, "text": null }, { "code": "\n\n\n\n\n\n\nimport java.util.Scanner;\n \npublic class PatternGFG // create a Class named PatternGFG\n{\n \n // Function to print the pattern \"GFG\"\n private static void print(int n, int k) {\n for (int i = 0; i < n; i++) {\n System.out.println();\n for (int j = 0; j < (3 * k + 2); j++) {\n \n // For printing the upper portion of \n // the pattern \"GFG\"\n if ((i == 0 && j != k && j != 2 * k + 1) ||\n ((i == n / 2) && (j > 1) && (j != k) && \n \n // for printing the middle portion of\n // the pattern \"GFG\"\n (j != 2 * k + 1) && (j != 2 * k + 3)) ||\n ((i == n - 1) && (j != k) &&\n \n // for printing the lower portion of\n // the pattern \"GFG\" \n ((j <= k) || (j > 2 * k + 1))) \n \n || (j == 0) || (j == k + 1) || (j == (2 * k + 2)) ||\n ((j == k - 1 || j == 3 * k + 1) && (i > n / 2)))\n \n // printing * wherever required\n System.out.print(\"*\"); \n \n else\n System.out.print(\" \"); // printing space wherever required\n }\n }\n }\n \n // Driver code\n public static void main(String[] args) {\n int n = 7, k = 5; // length and width of the pattern\n print(n, k);\n }\n}\n\n\n\n\n\n", "e": 27258, "s": 26011, "text": null }, { "code": "\n\n\n\n\n\n\n# Python Program to print \n# the pattern “GFG”\nimport math\n \n# Function to print the\n# pattern \"GFG\"\ndef print1(n, k) :\n \n for i in range(0, n) :\n print (\"\\n\")\n for j in range(0, (3 * k + 2)) :\n if ((i == 0 and j != k and\n \n # For printing the \n # upper portion of\n # the pattern \"GFG\"\n j != 2 * k + 1) or\n ((i == math.floor(n / 2)) and\n (j > 1) and (j != k) and\n (j != 2 * k + 1) and\n \n # for printing the\n # middle portion of\n # the pattern \"GFG\" \n (j != 2 * k + 3)) or\n ((i == n - 1) and (j != k) and\n \n # for printing the\n # lower portion of\n # the pattern \"GFG\"\n ((j <= k) or (j > 2 *\n k + 1))) or\n (j == 0) or (j == k + 1) or\n (j == (2 * k + 2)) or\n ((j ==k - 1 or j == 3 *\n k + 1) and\n (i > math.floor(n / 2)))) :\n \n # printing * where\n # ever required\n print (\"*\", end = \"\")\n \n else :\n \n # printing space \n # wherever required\n print (\" \", end = \"\")\n \n# Driver code\n \n# the length of the\n# pattern \"GFG\"\nn = 7\n \n# the width of the\n# pattern \"GFG\"\nk = 5\n \nprint1(n, k) \n \n# This code is contributed \n# by Manish Shaw(manishshaw1)\n\n\n\n\n\n", "e": 28814, "s": 27268, "text": null }, { "code": "\n\n\n\n\n\n\n// C# code for printing pattern.\nusing System;\n \npublic class GFG {\n \n // Function to print the pattern \"GFG\"\n private static void print(int n, int k) {\n \n for (int i = 0; i < n; i++) {\n \n Console.WriteLine();\n \n for (int j = 0; j < (3 * k + 2); j++) {\n \n // For printing the upper portion of \n // the pattern \"GFG\"\n if ((i == 0 && j != k && j != 2 * k + 1) ||\n ((i == n / 2) && (j > 1) && (j != k) && \n \n // for printing the middle portion of\n // the pattern \"GFG\"\n (j != 2 * k + 1) && (j != 2 * k + 3)) ||\n ((i == n - 1) && (j != k) &&\n \n // for printing the lower portion of\n // the pattern \"GFG\" \n ((j <= k) || (j > 2 * k + 1))) \n \n || (j == 0) || (j == k + 1) || \n (j == (2 * k + 2)) || ((j == k - 1 || \n j == 3 * k + 1) && (i > n / 2)))\n \n // printing * wherever required\n Console.Write(\"*\"); \n \n else\n Console.Write(\" \"); \n }\n }\n }\n \n // Driver code\n public static void Main() {\n \n // length and width of the pattern\n int n = 7, k = 5; \n \n print(n, k);\n }\n}\n \n// This code is contributed by vt_m.\n\n\n\n\n\n", "e": 30370, "s": 28824, "text": null }, { "code": "\n\n\n\n\n\n\n<?php\n// PHP Program to print \n// the pattern “GFG”\n \n// Function to print the\n// pattern \"GFG\"\nfunction print1($n, $k) {\n \nfor ($i = 0; $i < $n; $i++) {\n echo \"\\n\";\n for ($j = 0; $j < (3 * $k + 2); $j++) {\n if (($i == 0 && $j != $k &&\n \n // For printing the upper portion \n // of the pattern \"GFG\"\n $j != 2 * $k + 1) || \n (($i == floor($n / 2)) && \n ($j > 1) && ($j != $k) && \n ($j != 2 * $k + 1) &&\n \n /* for printing the middle portion\n of the pattern \"GFG\" */\n ($j != 2 * $k + 3)) || \n (($i == $n - 1) && ($j != $k) &&\n \n /* for printing the lower portion of\n the pattern \"GFG\" */\n (($j <= $k) || ($j > 2 * $k + 1))) ||\n ($j == 0) || ($j == $k + 1) || \n ($j == (2 * $k + 2)) ||\n (($j ==$k - 1 || $j == 3 * $k + 1) && \n ($i > floor($n / 2))))\n \n // printing * wherever required\n echo \"*\"; \n \n else\n \n // printing space wherever required\n echo \" \"; \n \n }\n}\n}\n \n// Driver code\n// the length of the pattern \"GFG\"\n$n = 7; \n \n// the width of the pattern \"GFG\"\n$k = 5; \n \nprint1($n, $k); \n \n// This code is contributed by Sam007\n?>\n\n\n\n\n\n", "e": 31613, "s": 30380, "text": null }, { "code": "\n\n\n\n\n\n\n<script>\n// Javascript implementation for the above approach \n \n// Function to print the pattern \"GFG\"\nfunction print1(n, k) {\n var i, j;\n for (i = 0; i < n; i++) {\n document.write(\"<br>\");\n for (j = 0; j < (3 * k + 2); j++) {\n if ((i == 0 && j != k &&\n \n /*For printing the upper portion \n of the pattern \"GFG\"*/\n j != 2 * k + 1) || \n ((i == n / 2) && (j > 1) && (j != k) && \n (j != 2 * k + 1) &&\n \n /* for printing the middle portion\n of the pattern \"GFG\" */\n (j != 2 * k + 3)) || \n ((i == n - 1) && (j != k) &&\n \n /* for printing the lower portion of\n the pattern \"GFG\" */\n ((j <= k) || (j > 2 * k + 1))) \n || (j == 0) || (j == k + 1) || (j == (2 * k + 2)) ||\n ((j == k - 1 || j == 3 * k + 1) && (i > n / 2)))\n \n document.write(\"*\"); // printing * wherever required\n \n else\n document.write(\" \",\" \"); // printing space wherever required\n }\n }\n}\n \n// Driver code\nvar n = 7; // the length of the pattern \"GFG\"\nvar k = 5; // the width of the pattern \"GFG\"\nprint1(n, k);\n \n// This code is contributed by Shubham Singh\n</script>\n\n\n\n\n\n", "e": 32863, "s": 31623, "text": null }, { "code": null, "e": 32874, "s": 32863, "text": "Output : " }, { "code": null, "e": 32992, "s": 32874, "text": "***** ***** *****\n* * *\n* * *\n* ** ***** * ***\n* * * * *\n* * * * *\n***** * *****" }, { "code": null, "e": 33001, "s": 32994, "text": "Sam007" }, { "code": null, "e": 33013, "s": 33001, "text": "manishshaw1" }, { "code": null, "e": 33028, "s": 33013, "text": "SHUBHAMSINGH10" }, { "code": null, "e": 33044, "s": 33028, "text": "saurabh1990aror" }, { "code": null, "e": 33063, "s": 33044, "text": "\npattern-printing\n" }, { "code": null, "e": 33084, "s": 33063, "text": "\nSchool Programming\n" }, { "code": null, "e": 33289, "s": 33084, "text": "Writing code in comment? \n Please use ide.geeksforgeeks.org, \n generate link and share the link here.\n " }, { "code": null, "e": 33310, "s": 33289, "text": "Constructors in Java" }, { "code": null, "e": 33329, "s": 33310, "text": "Exceptions in Java" }, { "code": null, "e": 33356, "s": 33329, "text": "Ternary Operator in Python" }, { "code": null, "e": 33380, "s": 33356, "text": "Inline Functions in C++" }, { "code": null, "e": 33436, "s": 33380, "text": "Difference between Abstract Class and Interface in Java" }, { "code": null, "e": 33462, "s": 33436, "text": "Exception Handling in C++" }, { "code": null, "e": 33481, "s": 33462, "text": "Destructors in C++" }, { "code": null, "e": 33507, "s": 33481, "text": "Python Exception Handling" }, { "code": null, "e": 33529, "s": 33507, "text": "'this' pointer in C++" } ]
TypeORM - Entity Listener and Logging
Entity listener is used in entities which supports custom method and listen specific events. We can define any entity custom method using decorators. Let’s understand decorators in brief. @AfterLoad − When the entity is loaded using QueryBuilder or repository/manager, this method will be called. @BeforeInsert − This method will call before the entity is inserted using repository/manager. @AfterInsert − This method will call after the entity is inserted using repository/manager. @BeforeUpdate − This method will call it before an existing entity is updated using repository/manager. @AfterUpdate − It will call after an entity is updated. @BeforeRemove − It will call before an entity is removed. @AfterRemove − It will call after an entity is removed. Subscriber is used to listen specific entity events. It is implemented from EntitySubscriberInterface. Let’s understand a simple example for how to use entity listener in subscriber. Consider the Student entity is shown below − import {Entity, PrimaryGeneratedColumn, Column} from "typeorm"; @Entity() export class Student { @PrimaryGeneratedColumn() id: number; @Column() Name: string; @Column() age: number; } Subscriber is created using the below command − typeorm subscriber:create -n StudentSubscriber The above command creates a subscriber directory inside your project src. Then, StudentSubscriber.ts file is created inside your subscriber. You could see the following response, Subscriber /Users/workspace/TypeORM/FirstProject/src/subscriber/StudentSubscriber.ts has been created successfully. Now move to file, you could see the below coding − import {EventSubscriber, EntitySubscriberInterface} from "typeorm"; @EventSubscriber() export class StudentSubscriber implements EntitySubscriberInterface<any> { } Now, add the following changes in the file, import {EventSubscriber, EntitySubscriberInterface,InsertEvent} from "typeorm"; import {Student} from "../entity/Student"; @EventSubscriber() export class StudentSubscriber implements EntitySubscriberInterface<any> { listenTo() { return Student; } afterInsert(event: InsertEvent<Student>) { console.log(event); } } Here, We have used afterInsert() method to call the entity event. Similarly, you can use other events as well. We have already configured ormconfig.json file. Now, add the below changes in index.ts file as follows − import "reflect-metadata"; import {createConnection} from "typeorm"; import {Student} from "./entity/Student"; createConnection().then(async connection => { console.log('connection established'); }).catch(error => console.log(error)); After executing the application, you could see the below output on your screen, Database logging is an important part of your highly available database solution design because database logs make it possible to recover from a failure, and they make it possible to synchronize primary and secondary databases. All databases have logs associated with them. These logs keep records of database changes. If a database needs to be restored to a point beyond the last full, off-line backup, logs are required to roll the data forward to the point of failure. Logging is enabled by adding {logging: true} in database connection. Logging options are classified into different types. They are as follows − query − return all log queries. It is defined as given below − { host: "localhost", ... logging: ["query"] } error − return logs for all failed queries and errors. It is defined below − { host: "localhost", ... logging: ["error"] } schema − return logs for the schema. warn − return internal ORM warnings. info − return logs internal ORM informative messages. log − return internal ORM log messages. Custom logging is simple and highly customizable logging option. We can create our own logger class using the below code − import {Logger} from "typeorm"; export class MyCustomLogger implements Logger { // implement all methods from logger class } Connection option is specified in ormconfig.json as follows − name: "mysql", type: "mysql", host: "localhost", port: 3306, username: "root", password: "root", database: "test", logger: new MyCustomLogger() 19 Lectures 50 mins James Coonce Print Add Notes Bookmark this page
[ { "code": null, "e": 2239, "s": 2051, "text": "Entity listener is used in entities which supports custom method and listen specific events. We can define any entity custom method using decorators. Let’s understand decorators in brief." }, { "code": null, "e": 2348, "s": 2239, "text": "@AfterLoad − When the entity is loaded using QueryBuilder or repository/manager, this method will be called." }, { "code": null, "e": 2442, "s": 2348, "text": "@BeforeInsert − This method will call before the entity is inserted using repository/manager." }, { "code": null, "e": 2534, "s": 2442, "text": "@AfterInsert − This method will call after the entity is inserted using repository/manager." }, { "code": null, "e": 2638, "s": 2534, "text": "@BeforeUpdate − This method will call it before an existing entity is updated using repository/manager." }, { "code": null, "e": 2694, "s": 2638, "text": "@AfterUpdate − It will call after an entity is updated." }, { "code": null, "e": 2752, "s": 2694, "text": "@BeforeRemove − It will call before an entity is removed." }, { "code": null, "e": 2808, "s": 2752, "text": "@AfterRemove − It will call after an entity is removed." }, { "code": null, "e": 3036, "s": 2808, "text": "Subscriber is used to listen specific entity events. It is implemented from EntitySubscriberInterface. Let’s understand a simple example for how to use entity listener in subscriber. Consider the Student entity is shown below −" }, { "code": null, "e": 3261, "s": 3036, "text": "import {Entity, PrimaryGeneratedColumn, Column} from \"typeorm\"; \n\n@Entity() \nexport class Student { \n\n @PrimaryGeneratedColumn() \n id: number; \n \n @Column() \n Name: string; \n \n @Column() \n age: number; \n}" }, { "code": null, "e": 3309, "s": 3261, "text": "Subscriber is created using the below command −" }, { "code": null, "e": 3357, "s": 3309, "text": "typeorm subscriber:create -n StudentSubscriber\n" }, { "code": null, "e": 3536, "s": 3357, "text": "The above command creates a subscriber directory inside your project src. Then, StudentSubscriber.ts file is created inside your subscriber. You could see the following response," }, { "code": null, "e": 3653, "s": 3536, "text": "Subscriber /Users/workspace/TypeORM/FirstProject/src/subscriber/StudentSubscriber.ts has been created successfully.\n" }, { "code": null, "e": 3704, "s": 3653, "text": "Now move to file, you could see the below coding −" }, { "code": null, "e": 3873, "s": 3704, "text": "import {EventSubscriber, EntitySubscriberInterface} from \"typeorm\"; \n\n@EventSubscriber() \nexport class StudentSubscriber implements EntitySubscriberInterface<any> { \n}\n" }, { "code": null, "e": 3917, "s": 3873, "text": "Now, add the following changes in the file," }, { "code": null, "e": 4276, "s": 3917, "text": "import {EventSubscriber, EntitySubscriberInterface,InsertEvent} from \"typeorm\"; \nimport {Student} from \"../entity/Student\"; \n\n@EventSubscriber() \nexport class StudentSubscriber implements EntitySubscriberInterface<any> { \n listenTo() \n { \n return Student; \n } \n \n afterInsert(event: InsertEvent<Student>) { \n console.log(event); \n } \n}\n" }, { "code": null, "e": 4282, "s": 4276, "text": "Here," }, { "code": null, "e": 4492, "s": 4282, "text": "We have used afterInsert() method to call the entity event. Similarly, you can use other events as well. We have already configured ormconfig.json file. Now, add the below changes in index.ts file as follows −" }, { "code": null, "e": 4734, "s": 4492, "text": "import \"reflect-metadata\"; import {createConnection} from \"typeorm\"; import {Student} from \"./entity/Student\"; \n\ncreateConnection().then(async connection => {\n\n console.log('connection established'); \n}).catch(error => console.log(error));" }, { "code": null, "e": 4814, "s": 4734, "text": "After executing the application, you could see the below output on your screen," }, { "code": null, "e": 5042, "s": 4814, "text": "Database logging is an important part of your highly available database solution design because database logs make it possible to recover from a failure, and they make it possible to synchronize primary and secondary databases." }, { "code": null, "e": 5286, "s": 5042, "text": "All databases have logs associated with them. These logs keep records of database changes. If a database needs to be restored to a point beyond the last full, off-line backup, logs are required to roll the data forward to the point of failure." }, { "code": null, "e": 5430, "s": 5286, "text": "Logging is enabled by adding {logging: true} in database connection. Logging options are classified into different types. They are as follows −" }, { "code": null, "e": 5493, "s": 5430, "text": "query − return all log queries. It is defined as given below −" }, { "code": null, "e": 5552, "s": 5493, "text": "{ \n host: \"localhost\",\n ... \n logging: [\"query\"] \n}\n" }, { "code": null, "e": 5629, "s": 5552, "text": "error − return logs for all failed queries and errors. It is defined below −" }, { "code": null, "e": 5688, "s": 5629, "text": "{ \n host: \"localhost\",\n ... \n logging: [\"error\"] \n}\n" }, { "code": null, "e": 5725, "s": 5688, "text": "schema − return logs for the schema." }, { "code": null, "e": 5762, "s": 5725, "text": "warn − return internal ORM warnings." }, { "code": null, "e": 5816, "s": 5762, "text": "info − return logs internal ORM informative messages." }, { "code": null, "e": 5856, "s": 5816, "text": "log − return internal ORM log messages." }, { "code": null, "e": 5979, "s": 5856, "text": "Custom logging is simple and highly customizable logging option. We can create our own logger class using the below code −" }, { "code": null, "e": 6116, "s": 5979, "text": "import {Logger} from \"typeorm\"; \n\nexport class MyCustomLogger implements Logger { \n \n // implement all methods from logger class \n}\n" }, { "code": null, "e": 6178, "s": 6116, "text": "Connection option is specified in ormconfig.json as follows −" }, { "code": null, "e": 6329, "s": 6178, "text": "name: \"mysql\", \ntype: \"mysql\", \nhost: \"localhost\", \nport: 3306, \nusername: \"root\", \npassword: \"root\", \ndatabase: \"test\", \nlogger: new MyCustomLogger()" }, { "code": null, "e": 6361, "s": 6329, "text": "\n 19 Lectures \n 50 mins\n" }, { "code": null, "e": 6375, "s": 6361, "text": " James Coonce" }, { "code": null, "e": 6382, "s": 6375, "text": " Print" }, { "code": null, "e": 6393, "s": 6382, "text": " Add Notes" } ]
C# | Properties - GeeksforGeeks
14 Sep, 2021 Before going on properties lets have a look at why the concept of properties came into C#? The is because of two reasons: If the members of a class are private then how another class in C# will be able to read, write, or compute the value of that field. If the members of the class are public then another class may misuse that member. Example: C# // C# program to illustrate the problems// with public and private membersusing System; // public classpublic class C1{ // public data members public int rn; public string name; // private field // private int marks = 35; } // another public classpublic class C2{ // Main Methodpublic static void Main(string[] args){ // Creating object of C1 class C1 obj = new C1(); // setting values to public // data members of class C1 obj.rn = 10000; obj.name = null; // setting values to private // data members of class C1 // obj.mark = 0; // display result Console.WriteLine("Name: {0} \nRoll No: {1}", obj.name, obj.rn); }} Output: Name: Roll No: 10000 Explanation: In above you can see that public members of class C1 can be accessed by class C2 and using the object “obj” of C1 it can provide the values to the members like Name is given value null but we don’t want this to be null. C2 cannot provide the value to the member “marks” because it is private in C1. To test the private member access remove the comments and try to run and you can see the compiler will give an error. The Programming languages which do not have properties, use getter and setter methods to provide such access mechanism. Using Properties Properties are the special type of class members that provides a flexible mechanism to read, write, or compute the value of a private field. Properties can be used as if they are public data members, but they are actually special methods called accessors. This enables data to be accessed easily and helps to promote the flexibility and safety of methods. Encapsulation and hiding of information can also be achieved using properties. It uses pre-defined methods which are “get” and “set” methods which help to access and modify the properties.Accessors: The block of “set” and “get” is known as “Accessors”. It is very essential to restrict the accessibility of property. There are two type of accessors i.e. get accessors and set accessors. There are different types of properties based on the “get” and “set” accessors: Read and Write Properties: When property contains both get and set methods. Read-Only Properties: When property contains only get method. Write Only Properties: When property contains only set method. Auto Implemented Properties: When there is no additional logic in the property accessors and it introduce in C# 3.0. The syntax for Defining Properties: <access_modifier> <return_type> <property_name> { get { // body } set { // body } } Where, <access_modifier> can be public, private, protected or internal. <return_type> can be any valid C# type. <property_name> can be user-defined. Properties can be different access modifiers like public, private, protected, internal. Access modifiers define how users of the class can access the property. The get and set accessors for the same property may have different access modifiers. A property may be declared as a static property by using the static keyword or may be marked as a virtual property by using the virtual keyword. Get Accessor: It specifies that the value of a field can access publicly. It returns a single value and it specifies the read-only property.Example: class Geeks { // Declare roll_no field private int roll_no; // Declare roll_no property public int Roll_no { get { return roll_no; } } } Set Accessor: It will specify the assignment of a value to a private field in a property. It returns a single value and it specifies the write-only property. Example: class Geeks { // Declare roll_no field private int roll_no; // Declare roll_no property public int Roll_no { get { return roll_no; } set { roll_no = value; } } } Accessor Accessibility we can’t use accessor modifiers on an interface or an explicit interface member implementation. we can use accessor modifiers only if the property has both set and get accessors. If the property is an override modifier, the accessor modifier must match the accessor of the overridden accessor. The accessibility level on the accessor must be more restrictive than the accessibility level on the property. Below are the programs to demonstrate different types of properties:Program 1: To demonstrate the Read-Only property using “get” accessor. C# // C# program to illustrate the// read-only propertyusing System; public class Student { // Declare counter field as cnt private static int cnt; // to define constructor public Student() { // increment the counter // using constructor cnt++; } // Declare counter property public static int Counter { // read-only property get { return cnt; } }} class StudentTest { // Main Method public static void Main(string[] args) { // create three instances of // Student class it call constructor // three times which increase the counter Student s1 = new Student(); Student s2 = new Student(); Student s3 = new Student(); // s1.Counter = 10; // Compile Time Error: Can't set value of // Counter because it is read only. Console.WriteLine("Total No of Student: " + Student.Counter); // Program Give Warning // The variable `s1' is assigned but its value is never used }} Output: Total No of Student: 3 Program 2: To demonstrate the both read & write property using “get” and “set” accessors. C# // C# program to illustrate the// read and write propertyusing System; public class Student { // Declare name field private string name = "GeeksforGeeks"; // Declare name property public string Name { get { return name; } set { name = value; } }} class TestStudent { // Main Method public static void Main(string[] args) { Student s = new Student(); // calls set accessor of the property Name, // and pass "GFG" as value of the // standard field 'value'. s.Name = "GFG"; // displays GFG, Calls the get accessor // of the property Name. Console.WriteLine("Name: " + s.Name); }} Output: Name: GFG skajlep abhishek0719kadiyan CSharp-Indexers & Properties CSharp-OOP C# Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Difference between Abstract Class and Interface in C# C# | IsNullOrEmpty() Method C# | Delegates C# | Arrays of Strings Partial Classes in C# Difference between Ref and Out keywords in C# String.Split() Method in C# with Examples C# | How to check whether a List contains a specified element Extension Method in C# Top 50 C# Interview Questions & Answers
[ { "code": null, "e": 25224, "s": 25196, "text": "\n14 Sep, 2021" }, { "code": null, "e": 25347, "s": 25224, "text": "Before going on properties lets have a look at why the concept of properties came into C#? The is because of two reasons: " }, { "code": null, "e": 25479, "s": 25347, "text": "If the members of a class are private then how another class in C# will be able to read, write, or compute the value of that field." }, { "code": null, "e": 25561, "s": 25479, "text": "If the members of the class are public then another class may misuse that member." }, { "code": null, "e": 25571, "s": 25561, "text": "Example: " }, { "code": null, "e": 25574, "s": 25571, "text": "C#" }, { "code": "// C# program to illustrate the problems// with public and private membersusing System; // public classpublic class C1{ // public data members public int rn; public string name; // private field // private int marks = 35; } // another public classpublic class C2{ // Main Methodpublic static void Main(string[] args){ // Creating object of C1 class C1 obj = new C1(); // setting values to public // data members of class C1 obj.rn = 10000; obj.name = null; // setting values to private // data members of class C1 // obj.mark = 0; // display result Console.WriteLine(\"Name: {0} \\nRoll No: {1}\", obj.name, obj.rn); }}", "e": 26278, "s": 25574, "text": null }, { "code": null, "e": 26288, "s": 26278, "text": "Output: " }, { "code": null, "e": 26312, "s": 26288, "text": "Name: \nRoll No: 10000" }, { "code": null, "e": 26863, "s": 26312, "text": "Explanation: In above you can see that public members of class C1 can be accessed by class C2 and using the object “obj” of C1 it can provide the values to the members like Name is given value null but we don’t want this to be null. C2 cannot provide the value to the member “marks” because it is private in C1. To test the private member access remove the comments and try to run and you can see the compiler will give an error. The Programming languages which do not have properties, use getter and setter methods to provide such access mechanism. " }, { "code": null, "e": 26880, "s": 26863, "text": "Using Properties" }, { "code": null, "e": 27704, "s": 26880, "text": "Properties are the special type of class members that provides a flexible mechanism to read, write, or compute the value of a private field. Properties can be used as if they are public data members, but they are actually special methods called accessors. This enables data to be accessed easily and helps to promote the flexibility and safety of methods. Encapsulation and hiding of information can also be achieved using properties. It uses pre-defined methods which are “get” and “set” methods which help to access and modify the properties.Accessors: The block of “set” and “get” is known as “Accessors”. It is very essential to restrict the accessibility of property. There are two type of accessors i.e. get accessors and set accessors. There are different types of properties based on the “get” and “set” accessors: " }, { "code": null, "e": 27780, "s": 27704, "text": "Read and Write Properties: When property contains both get and set methods." }, { "code": null, "e": 27842, "s": 27780, "text": "Read-Only Properties: When property contains only get method." }, { "code": null, "e": 27905, "s": 27842, "text": "Write Only Properties: When property contains only set method." }, { "code": null, "e": 28022, "s": 27905, "text": "Auto Implemented Properties: When there is no additional logic in the property accessors and it introduce in C# 3.0." }, { "code": null, "e": 28059, "s": 28022, "text": "The syntax for Defining Properties: " }, { "code": null, "e": 28159, "s": 28059, "text": "<access_modifier> <return_type> <property_name>\n{\n get { // body }\n set { // body }\n}" }, { "code": null, "e": 28700, "s": 28159, "text": "Where, <access_modifier> can be public, private, protected or internal. <return_type> can be any valid C# type. <property_name> can be user-defined. Properties can be different access modifiers like public, private, protected, internal. Access modifiers define how users of the class can access the property. The get and set accessors for the same property may have different access modifiers. A property may be declared as a static property by using the static keyword or may be marked as a virtual property by using the virtual keyword. " }, { "code": null, "e": 28850, "s": 28700, "text": "Get Accessor: It specifies that the value of a field can access publicly. It returns a single value and it specifies the read-only property.Example: " }, { "code": null, "e": 29012, "s": 28850, "text": "class Geeks {\n// Declare roll_no field\nprivate int roll_no;\n\n// Declare roll_no property\npublic int Roll_no \n{ \n\n get \n {\n return roll_no;\n }\n\n}\n}" }, { "code": null, "e": 29180, "s": 29012, "text": "Set Accessor: It will specify the assignment of a value to a private field in a property. It returns a single value and it specifies the write-only property. Example: " }, { "code": null, "e": 29396, "s": 29180, "text": "class Geeks {\n\n// Declare roll_no field\nprivate int roll_no;\n\n// Declare roll_no property\npublic int Roll_no\n { \n\n get \n {\n return roll_no;\n }\n\n set \n {\n roll_no = value;\n }\n}\n}" }, { "code": null, "e": 29421, "s": 29396, "text": "Accessor Accessibility " }, { "code": null, "e": 29517, "s": 29421, "text": "we can’t use accessor modifiers on an interface or an explicit interface member implementation." }, { "code": null, "e": 29600, "s": 29517, "text": "we can use accessor modifiers only if the property has both set and get accessors." }, { "code": null, "e": 29715, "s": 29600, "text": "If the property is an override modifier, the accessor modifier must match the accessor of the overridden accessor." }, { "code": null, "e": 29826, "s": 29715, "text": "The accessibility level on the accessor must be more restrictive than the accessibility level on the property." }, { "code": null, "e": 29966, "s": 29826, "text": "Below are the programs to demonstrate different types of properties:Program 1: To demonstrate the Read-Only property using “get” accessor. " }, { "code": null, "e": 29969, "s": 29966, "text": "C#" }, { "code": "// C# program to illustrate the// read-only propertyusing System; public class Student { // Declare counter field as cnt private static int cnt; // to define constructor public Student() { // increment the counter // using constructor cnt++; } // Declare counter property public static int Counter { // read-only property get { return cnt; } }} class StudentTest { // Main Method public static void Main(string[] args) { // create three instances of // Student class it call constructor // three times which increase the counter Student s1 = new Student(); Student s2 = new Student(); Student s3 = new Student(); // s1.Counter = 10; // Compile Time Error: Can't set value of // Counter because it is read only. Console.WriteLine(\"Total No of Student: \" + Student.Counter); // Program Give Warning // The variable `s1' is assigned but its value is never used }}", "e": 31031, "s": 29969, "text": null }, { "code": null, "e": 31041, "s": 31031, "text": "Output: " }, { "code": null, "e": 31064, "s": 31041, "text": "Total No of Student: 3" }, { "code": null, "e": 31155, "s": 31064, "text": "Program 2: To demonstrate the both read & write property using “get” and “set” accessors. " }, { "code": null, "e": 31158, "s": 31155, "text": "C#" }, { "code": "// C# program to illustrate the// read and write propertyusing System; public class Student { // Declare name field private string name = \"GeeksforGeeks\"; // Declare name property public string Name { get { return name; } set { name = value; } }} class TestStudent { // Main Method public static void Main(string[] args) { Student s = new Student(); // calls set accessor of the property Name, // and pass \"GFG\" as value of the // standard field 'value'. s.Name = \"GFG\"; // displays GFG, Calls the get accessor // of the property Name. Console.WriteLine(\"Name: \" + s.Name); }}", "e": 31894, "s": 31158, "text": null }, { "code": null, "e": 31904, "s": 31894, "text": "Output: " }, { "code": null, "e": 31914, "s": 31904, "text": "Name: GFG" }, { "code": null, "e": 31924, "s": 31916, "text": "skajlep" }, { "code": null, "e": 31944, "s": 31924, "text": "abhishek0719kadiyan" }, { "code": null, "e": 31973, "s": 31944, "text": "CSharp-Indexers & Properties" }, { "code": null, "e": 31984, "s": 31973, "text": "CSharp-OOP" }, { "code": null, "e": 31987, "s": 31984, "text": "C#" }, { "code": null, "e": 32085, "s": 31987, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 32094, "s": 32085, "text": "Comments" }, { "code": null, "e": 32107, "s": 32094, "text": "Old Comments" }, { "code": null, "e": 32161, "s": 32107, "text": "Difference between Abstract Class and Interface in C#" }, { "code": null, "e": 32189, "s": 32161, "text": "C# | IsNullOrEmpty() Method" }, { "code": null, "e": 32204, "s": 32189, "text": "C# | Delegates" }, { "code": null, "e": 32227, "s": 32204, "text": "C# | Arrays of Strings" }, { "code": null, "e": 32249, "s": 32227, "text": "Partial Classes in C#" }, { "code": null, "e": 32295, "s": 32249, "text": "Difference between Ref and Out keywords in C#" }, { "code": null, "e": 32337, "s": 32295, "text": "String.Split() Method in C# with Examples" }, { "code": null, "e": 32399, "s": 32337, "text": "C# | How to check whether a List contains a specified element" }, { "code": null, "e": 32422, "s": 32399, "text": "Extension Method in C#" } ]
Explain Inheritance vs Instantiation for Python classes.
Being an Object Oriented language, Python supports inheritance, it even supports multiple inheritance. Classes can inherit from other classes. A class can inherit attributes and behaviour methods from another class, called the superclass. A class which inherits from a superclass is called a subclass, also called heir class or child class. In other words inheritance refers to defining a new class with little or no modification to an existing class. class A: # define your class A pass class B: # define your class B pass class C(A, B): # subclass of A and B Instantiating a class is creating a copy of the class which inherits all class variables and methods. Instantiating a class in Python is simple. To instantiate a class, we simply call the class as if it were a function, passing the arguments that the __init__ method defines. The return value will be the newly created object. class Foo(): def __init__(self,x,y): print x+y f = Foo(3,4) 7
[ { "code": null, "e": 1514, "s": 1062, "text": "Being an Object Oriented language, Python supports inheritance, it even supports multiple inheritance. Classes can inherit from other classes. A class can inherit attributes and behaviour methods from another class, called the superclass. A class which inherits from a superclass is called a subclass, also called heir class or child class. In other words inheritance refers to defining a new class with little or no modification to an existing class." }, { "code": null, "e": 1640, "s": 1514, "text": "class A: # define your class A\npass\nclass B: # define your class B\npass\nclass C(A, B): # subclass of A and B" }, { "code": null, "e": 1967, "s": 1640, "text": "Instantiating a class is creating a copy of the class which inherits all class variables and methods. Instantiating a class in Python is simple. To instantiate a class, we simply call the class as if it were a function, passing the arguments that the __init__ method defines. The return value will be the newly created object." }, { "code": null, "e": 2047, "s": 1967, "text": "class Foo():\n def __init__(self,x,y):\n print x+y\nf = Foo(3,4)" }, { "code": null, "e": 2049, "s": 2047, "text": "7" } ]
Program to Print the Trapezium Pattern
22 Jun, 2022 Given ‘num’ which indicates number of lines.The task is to print a trapezium pattern in num lines.Examples: Input : 4 Output : 1*2*3*4*17*18*19*20 5*6*7*14*15*16 8*9*12*13 10*11 Input : 2 Output : 1*2*5*6 3*4 Algorithm : step 1. To read num which indicates the number of lines. step 2.We are diving the pattern into 2 halves that is LHS part and the RHS part. Ex : When num = 2 LHS – 1*2* 3*RHS – 5*6 4 step 3.Combining LHS and RHS we get the complete pattern. C++ Java Python 3 C# PHP Javascript // CPP program to print Trapezium Pattern#include <iostream> using namespace std; int main(){ int num = 3; int space; int i, j, lterm, rterm; // The terms on the LHS of the pattern lterm = 1; // The terms on the RHS of the pattern rterm = num * num + 1; for (i = num; i > 0; i--) { // To print number of spaces for (space = num; space > i; space--) cout << " "; for (j = 1; j <= i; j++) { cout << lterm; cout << "*"; lterm++; } for (j = 1; j <= i; j++) { cout << rterm; if (j < i) printf("*"); rterm++; } // To get the next term on RHS of the Pattern rterm = rterm - (i - 1) * 2 - 1; cout << endl; }} // Java program to print Trapezium Patternpublic class HelloWorld { public static void trapeziumPattern(int num) { int firsthalf = 1; int secondhalf = (num * num) + 1; int numOfSpaces = 0; // numOfLines is the line number for (int numOfLines = num; numOfLines >= 1; numOfLines--) { // Prints the spaces for each line for (int numOfSpacesCounter = numOfSpaces; numOfSpacesCounter >= 1; numOfSpacesCounter--) { System.out.print(" "); } // Prints the first half of the trapezium for (int firstHalfCounter = 1; firstHalfCounter <= numOfLines; firstHalfCounter++) { // If it is the last number for a line then // we don't print '*' if (firstHalfCounter == numOfLines) System.out.print((firsthalf++)); else System.out.print((firsthalf++) + "*"); } // Prints the second half of the trapezium for (int secondHalfCounter = 1; secondHalfCounter <= numOfLines; secondHalfCounter++) { System.out.print("*" + (secondhalf++)); } System.out.println(); // Calculates the number of Spaces for the next // line numOfSpaces += 2; // Calculates the first number of the // second half for the next iteration/line secondhalf = (secondhalf - 1) - ((numOfLines - 1) * 2); } } public static void main(String[] args) { trapeziumPattern( 4); // Passing the integer as the argument to // print trapezium pattern }} # Python 3 program to print# Trapezium Pattern if __name__ == "__main__": num = 3 # The terms on the LHS # of the pattern lterm = 1 # The terms on the RHS # of the pattern rterm = num * num + 1 for i in range(num, -1, -1): # To print number of spaces for space in range(num, i-1, -1): print(" ", end ="") for j in range(1, i + 1): print(str(lterm)+"*", end ="") lterm += 1 for j in range(1, i + 1): print(rterm, end ="") if j < i: print("*", end ="") rterm += 1 # To get the next term on RHS of the Pattern rterm = rterm - (i - 1) * 2 - 1 print() # This code is contributed by ChitraNayal // C# program to print Trapezium Patternusing System; public class HelloWorld { public static void Main(String[] args) { // Scanner scn = new Scanner(System.in); int num = 3; int space; // System.out.println("Enter number of lines : "); // num = scn.nextInt(); int i, j, lterm, rterm; lterm = 1; // The terms on the LHS of the pattern // The terms on the RHS of the pattern rterm = num * num + 1; for (i = num; i > 0; i--) { // To print number of spaces for (space = num; space > i; space--) Console.Write(" "); for (j = 1; j <= i; j++) { Console.Write(lterm); Console.Write("*"); lterm++; } for (j = 1; j <= i; j++) { Console.Write(rterm); if (j < i) Console.Write("*"); rterm++; } // To get the next term on RHS of the Pattern rterm = rterm - (i - 1) * 2 - 1; Console.WriteLine(); } }} // This code is contributed by ankita_saini <?php// PHP program to print// Trapezium Pattern$num = 3;$space; $i; $j; $lterm; $rterm; // The terms on the LHS// of the pattern$lterm = 1; // The terms on the// RHS of the pattern$rterm = $num * $num + 1; for ($i = $num; $i > 0; $i--){ // To print number of spaces for ($space = $num; $space > $i; $space--) echo " "; for ($j = 1; $j <= $i; $j++) { echo $lterm; echo "*"; $lterm++; } for ($j = 1; $j <= $i; $j++) { echo $rterm; if ($j < $i) echo "*"; $rterm++; } // To get the next term // on RHS of the Pattern $rterm = $rterm - ($i - 1) * 2 - 1; echo "\n";} // This code is contributed// by Akanksha Rai(Abby_akku)?> <script> // JavaScript program to print Trapezium Pattern var num = 3; var space; var i, j, lterm, rterm; // The terms on the LHS of the pattern lterm = 1; // The terms on the RHS of the pattern rterm = num * num + 1; for (i = num; i > 0; i--) { // To print number of spaces for (space = num; space > i; space--) document.write(" "); for (j = 1; j <= i; j++) { document.write(lterm); document.write("*"); lterm++; } for (j = 1; j <= i; j++) { document.write(rterm); if (j < i) document.write("*"); rterm++; } // To get the next term on RHS of the Pattern rterm = rterm - (i - 1) * 2 - 1; document.write("<br>"); } </script> Output: Enter number of lines : 3 1*2*3*10*11*12 4*5*8*9 6*7 Time complexity: O(n2) space complexity: O(1) ankita_saini Akanksha_Rai ukasp farhan150 rdtank sabarirjsr hasani pattern-printing C++ Programs Java Programs School Programming pattern-printing Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Shallow Copy and Deep Copy in C++ C++ Program to check if a given String is Palindrome or not How to find the minimum and maximum element of a Vector using STL in C++? Passing a function as a parameter in C++ cin in C++ Initializing a List in Java Java Programming Examples Convert a String to Character Array in Java Convert Double to Integer in Java Implementing a Linked List in Java using Class
[ { "code": null, "e": 28, "s": 0, "text": "\n22 Jun, 2022" }, { "code": null, "e": 138, "s": 28, "text": "Given ‘num’ which indicates number of lines.The task is to print a trapezium pattern in num lines.Examples: " }, { "code": null, "e": 257, "s": 138, "text": "Input : 4 \nOutput :\n1*2*3*4*17*18*19*20\n 5*6*7*14*15*16\n 8*9*12*13\n 10*11\n\n\nInput : 2\nOutput :\n1*2*5*6\n 3*4" }, { "code": null, "e": 510, "s": 257, "text": "Algorithm : step 1. To read num which indicates the number of lines. step 2.We are diving the pattern into 2 halves that is LHS part and the RHS part. Ex : When num = 2 LHS – 1*2* 3*RHS – 5*6 4 step 3.Combining LHS and RHS we get the complete pattern. " }, { "code": null, "e": 514, "s": 510, "text": "C++" }, { "code": null, "e": 519, "s": 514, "text": "Java" }, { "code": null, "e": 528, "s": 519, "text": "Python 3" }, { "code": null, "e": 531, "s": 528, "text": "C#" }, { "code": null, "e": 535, "s": 531, "text": "PHP" }, { "code": null, "e": 546, "s": 535, "text": "Javascript" }, { "code": "// CPP program to print Trapezium Pattern#include <iostream> using namespace std; int main(){ int num = 3; int space; int i, j, lterm, rterm; // The terms on the LHS of the pattern lterm = 1; // The terms on the RHS of the pattern rterm = num * num + 1; for (i = num; i > 0; i--) { // To print number of spaces for (space = num; space > i; space--) cout << \" \"; for (j = 1; j <= i; j++) { cout << lterm; cout << \"*\"; lterm++; } for (j = 1; j <= i; j++) { cout << rterm; if (j < i) printf(\"*\"); rterm++; } // To get the next term on RHS of the Pattern rterm = rterm - (i - 1) * 2 - 1; cout << endl; }}", "e": 1337, "s": 546, "text": null }, { "code": "// Java program to print Trapezium Patternpublic class HelloWorld { public static void trapeziumPattern(int num) { int firsthalf = 1; int secondhalf = (num * num) + 1; int numOfSpaces = 0; // numOfLines is the line number for (int numOfLines = num; numOfLines >= 1; numOfLines--) { // Prints the spaces for each line for (int numOfSpacesCounter = numOfSpaces; numOfSpacesCounter >= 1; numOfSpacesCounter--) { System.out.print(\" \"); } // Prints the first half of the trapezium for (int firstHalfCounter = 1; firstHalfCounter <= numOfLines; firstHalfCounter++) { // If it is the last number for a line then // we don't print '*' if (firstHalfCounter == numOfLines) System.out.print((firsthalf++)); else System.out.print((firsthalf++) + \"*\"); } // Prints the second half of the trapezium for (int secondHalfCounter = 1; secondHalfCounter <= numOfLines; secondHalfCounter++) { System.out.print(\"*\" + (secondhalf++)); } System.out.println(); // Calculates the number of Spaces for the next // line numOfSpaces += 2; // Calculates the first number of the // second half for the next iteration/line secondhalf = (secondhalf - 1) - ((numOfLines - 1) * 2); } } public static void main(String[] args) { trapeziumPattern( 4); // Passing the integer as the argument to // print trapezium pattern }}", "e": 3156, "s": 1337, "text": null }, { "code": "# Python 3 program to print# Trapezium Pattern if __name__ == \"__main__\": num = 3 # The terms on the LHS # of the pattern lterm = 1 # The terms on the RHS # of the pattern rterm = num * num + 1 for i in range(num, -1, -1): # To print number of spaces for space in range(num, i-1, -1): print(\" \", end =\"\") for j in range(1, i + 1): print(str(lterm)+\"*\", end =\"\") lterm += 1 for j in range(1, i + 1): print(rterm, end =\"\") if j < i: print(\"*\", end =\"\") rterm += 1 # To get the next term on RHS of the Pattern rterm = rterm - (i - 1) * 2 - 1 print() # This code is contributed by ChitraNayal", "e": 3913, "s": 3156, "text": null }, { "code": "// C# program to print Trapezium Patternusing System; public class HelloWorld { public static void Main(String[] args) { // Scanner scn = new Scanner(System.in); int num = 3; int space; // System.out.println(\"Enter number of lines : \"); // num = scn.nextInt(); int i, j, lterm, rterm; lterm = 1; // The terms on the LHS of the pattern // The terms on the RHS of the pattern rterm = num * num + 1; for (i = num; i > 0; i--) { // To print number of spaces for (space = num; space > i; space--) Console.Write(\" \"); for (j = 1; j <= i; j++) { Console.Write(lterm); Console.Write(\"*\"); lterm++; } for (j = 1; j <= i; j++) { Console.Write(rterm); if (j < i) Console.Write(\"*\"); rterm++; } // To get the next term on RHS of the Pattern rterm = rterm - (i - 1) * 2 - 1; Console.WriteLine(); } }} // This code is contributed by ankita_saini", "e": 5063, "s": 3913, "text": null }, { "code": "<?php// PHP program to print// Trapezium Pattern$num = 3;$space; $i; $j; $lterm; $rterm; // The terms on the LHS// of the pattern$lterm = 1; // The terms on the// RHS of the pattern$rterm = $num * $num + 1; for ($i = $num; $i > 0; $i--){ // To print number of spaces for ($space = $num; $space > $i; $space--) echo \" \"; for ($j = 1; $j <= $i; $j++) { echo $lterm; echo \"*\"; $lterm++; } for ($j = 1; $j <= $i; $j++) { echo $rterm; if ($j < $i) echo \"*\"; $rterm++; } // To get the next term // on RHS of the Pattern $rterm = $rterm - ($i - 1) * 2 - 1; echo \"\\n\";} // This code is contributed// by Akanksha Rai(Abby_akku)?>", "e": 5791, "s": 5063, "text": null }, { "code": "<script> // JavaScript program to print Trapezium Pattern var num = 3; var space; var i, j, lterm, rterm; // The terms on the LHS of the pattern lterm = 1; // The terms on the RHS of the pattern rterm = num * num + 1; for (i = num; i > 0; i--) { // To print number of spaces for (space = num; space > i; space--) document.write(\" \"); for (j = 1; j <= i; j++) { document.write(lterm); document.write(\"*\"); lterm++; } for (j = 1; j <= i; j++) { document.write(rterm); if (j < i) document.write(\"*\"); rterm++; } // To get the next term on RHS of the Pattern rterm = rterm - (i - 1) * 2 - 1; document.write(\"<br>\"); } </script>", "e": 6603, "s": 5791, "text": null }, { "code": null, "e": 6612, "s": 6603, "text": "Output: " }, { "code": null, "e": 6671, "s": 6612, "text": "Enter number of lines : 3\n1*2*3*10*11*12\n 4*5*8*9\n 6*7" }, { "code": null, "e": 6694, "s": 6671, "text": "Time complexity: O(n2)" }, { "code": null, "e": 6718, "s": 6694, "text": "space complexity: O(1) " }, { "code": null, "e": 6731, "s": 6718, "text": "ankita_saini" }, { "code": null, "e": 6744, "s": 6731, "text": "Akanksha_Rai" }, { "code": null, "e": 6750, "s": 6744, "text": "ukasp" }, { "code": null, "e": 6760, "s": 6750, "text": "farhan150" }, { "code": null, "e": 6767, "s": 6760, "text": "rdtank" }, { "code": null, "e": 6778, "s": 6767, "text": "sabarirjsr" }, { "code": null, "e": 6785, "s": 6778, "text": "hasani" }, { "code": null, "e": 6802, "s": 6785, "text": "pattern-printing" }, { "code": null, "e": 6815, "s": 6802, "text": "C++ Programs" }, { "code": null, "e": 6829, "s": 6815, "text": "Java Programs" }, { "code": null, "e": 6848, "s": 6829, "text": "School Programming" }, { "code": null, "e": 6865, "s": 6848, "text": "pattern-printing" }, { "code": null, "e": 6963, "s": 6865, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 6997, "s": 6963, "text": "Shallow Copy and Deep Copy in C++" }, { "code": null, "e": 7057, "s": 6997, "text": "C++ Program to check if a given String is Palindrome or not" }, { "code": null, "e": 7131, "s": 7057, "text": "How to find the minimum and maximum element of a Vector using STL in C++?" }, { "code": null, "e": 7172, "s": 7131, "text": "Passing a function as a parameter in C++" }, { "code": null, "e": 7183, "s": 7172, "text": "cin in C++" }, { "code": null, "e": 7211, "s": 7183, "text": "Initializing a List in Java" }, { "code": null, "e": 7237, "s": 7211, "text": "Java Programming Examples" }, { "code": null, "e": 7281, "s": 7237, "text": "Convert a String to Character Array in Java" }, { "code": null, "e": 7315, "s": 7281, "text": "Convert Double to Integer in Java" } ]
Python – Check if String Contain Only Defined Characters using Regex
29 Dec, 2020 In this article, we are going to see how to check whether the given string contains only certain set of characters in Python. These defined characters will be represented using sets. Examples: Input: ‘657’ let us say regular expression contain following characters-(‘78653’)Output: Valid Explanation: The Input string only consist of characters present in the given string Input: ‘7606’ let us say regular expression contain following characters-(‘102’) Output: Invalid Approach: Method or approach is simple we will define the character set using a regular expression. The regular expression is a special pattern or sequence of characters that will allow us to match and find other sets of characters or strings. Functions Used: compile(): Regular expressions are compiled into pattern objects, which have methods for various operations such as searching for pattern matches or performing string substitutions. search(): re.search() method either returns None (if the pattern doesn’t match), or a re.MatchObject that contains information about the matching part of the string. This method stops after the first match, so this is best suited for testing a regular expression more than extracting data. Below is the implementation. Python3 # _importing moduleimport re def check(str, pattern): # _matching the strings if re.search(pattern, str): print("Valid String") else: print("Invalid String") # _driver codepattern = re.compile('^[1234]+$')check('2134', pattern)check('349', pattern) Output: Valid String Invalid String Python Regex-programs python-regex Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Python Dictionary Different ways to create Pandas Dataframe Enumerate() in Python Read a file line by line in Python Python String | replace() How to Install PIP on Windows ? *args and **kwargs in Python Iterate over a list in Python Python Classes and Objects Convert integer to string in Python
[ { "code": null, "e": 54, "s": 26, "text": "\n29 Dec, 2020" }, { "code": null, "e": 237, "s": 54, "text": "In this article, we are going to see how to check whether the given string contains only certain set of characters in Python. These defined characters will be represented using sets." }, { "code": null, "e": 247, "s": 237, "text": "Examples:" }, { "code": null, "e": 427, "s": 247, "text": "Input: ‘657’ let us say regular expression contain following characters-(‘78653’)Output: Valid Explanation: The Input string only consist of characters present in the given string" }, { "code": null, "e": 524, "s": 427, "text": "Input: ‘7606’ let us say regular expression contain following characters-(‘102’) Output: Invalid" }, { "code": null, "e": 534, "s": 524, "text": "Approach:" }, { "code": null, "e": 769, "s": 534, "text": "Method or approach is simple we will define the character set using a regular expression. The regular expression is a special pattern or sequence of characters that will allow us to match and find other sets of characters or strings. " }, { "code": null, "e": 785, "s": 769, "text": "Functions Used:" }, { "code": null, "e": 967, "s": 785, "text": "compile(): Regular expressions are compiled into pattern objects, which have methods for various operations such as searching for pattern matches or performing string substitutions." }, { "code": null, "e": 1257, "s": 967, "text": "search(): re.search() method either returns None (if the pattern doesn’t match), or a re.MatchObject that contains information about the matching part of the string. This method stops after the first match, so this is best suited for testing a regular expression more than extracting data." }, { "code": null, "e": 1286, "s": 1257, "text": "Below is the implementation." }, { "code": null, "e": 1294, "s": 1286, "text": "Python3" }, { "code": "# _importing moduleimport re def check(str, pattern): # _matching the strings if re.search(pattern, str): print(\"Valid String\") else: print(\"Invalid String\") # _driver codepattern = re.compile('^[1234]+$')check('2134', pattern)check('349', pattern)", "e": 1574, "s": 1294, "text": null }, { "code": null, "e": 1582, "s": 1574, "text": "Output:" }, { "code": null, "e": 1611, "s": 1582, "text": "Valid String\nInvalid String\n" }, { "code": null, "e": 1633, "s": 1611, "text": "Python Regex-programs" }, { "code": null, "e": 1646, "s": 1633, "text": "python-regex" }, { "code": null, "e": 1653, "s": 1646, "text": "Python" }, { "code": null, "e": 1751, "s": 1653, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 1769, "s": 1751, "text": "Python Dictionary" }, { "code": null, "e": 1811, "s": 1769, "text": "Different ways to create Pandas Dataframe" }, { "code": null, "e": 1833, "s": 1811, "text": "Enumerate() in Python" }, { "code": null, "e": 1868, "s": 1833, "text": "Read a file line by line in Python" }, { "code": null, "e": 1894, "s": 1868, "text": "Python String | replace()" }, { "code": null, "e": 1926, "s": 1894, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 1955, "s": 1926, "text": "*args and **kwargs in Python" }, { "code": null, "e": 1985, "s": 1955, "text": "Iterate over a list in Python" }, { "code": null, "e": 2012, "s": 1985, "text": "Python Classes and Objects" } ]
jQuery | Introduction
18 May, 2021 jQuery is an open source JavaScript library that simplifies the interactions between an HTML/CSS document, or more precisely the Document Object Model (DOM), and JavaScript.Elaborating the terms, jQuery simplifies HTML document traversing and manipulation, browser event handling, DOM animations, Ajax interactions, and cross-browser JavaScript development.Note: The only library available today that meets the needs of both designer types and programmer types is jQuery. jQuery is widely famous with its philosophy of “Write less, do more.” This philosophy can be further elaborated as three concepts: Finding some elements (via CSS selectors) and doing something with them (via jQuery methods) i.e. locate a set of elements in the DOM, and then do something with that set of elements. Chaining multiple jQuery methods on a set of elements Using the jQuery wrapper and implicit iteration Using jQuery (JS) library on HTML pageThere are several ways to start using jQuery on your web site. Use the Google-hosted/ Microsoft-hosted content delivery network (CDN) to include a version of jQuery.Download own version of jQuery from jQuery.com and host it on own server or local filesystem. Use the Google-hosted/ Microsoft-hosted content delivery network (CDN) to include a version of jQuery. Download own version of jQuery from jQuery.com and host it on own server or local filesystem. Note: All jQuery methods are inside a document-ready event to prevent any jQuery code from running before the document is finished loading (is ready). Basic syntax for any jQuery function is: $(selector).action() A $ sign is to define/access jQuery A (selector) is to “query (or find)” HTML elements in html page A jQuery action() is the action to be performed on the selected element(s) Example: <!DOCTYPE html><html> <head> <script src= "https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"> </script> <script> $(document).ready(function () { $("h2").click(function () { $(this).hover(); }); }); </script> </head> <body> <center> <h2 style="color: green;"> GeeksforGeeks </h2> </center> </body></html> Output: Why jQuery?Some of the key points which support the answer for why to use jQuery: It is incredibly popular, which is to say it has a large community of users and a healthy amount of contributors who participate as developers and evangelists. It normalizes the differences between web browsers so that you don’t have to. It is intentionally a lightweight footprint with a simple yet clever plugin architecture. Its repository of plugins is vast and has seen steady growth since jQuery’s release. Its API is fully documented, including inline code examples, which in the world of JavaScript libraries is a luxury. Heck, any documentation at all was a luxury for years. It is friendly, which is to say it provides helpful ways to avoid conflicts with other JavaScript libraries. Advantages: Wide range of plug-ins. jQuery allows developers to create plug-ins on top of the JavaScript library. Large development community It has a good and comprehensive documentation It is a lot more easy to use compared to standard javascript and other javascript libraries. JQuery lets users develop Ajax templates with ease, Ajax enables a sleeker interface where actions can be performed on pages without requiring the entire page to be reloaded. Being Light weight and a powerful chaining capabilities makes jQuery more strong. Disadvantages: While JQuery has an impressive library in terms of quantity, depending on how much customization you require on your website, the functionality may be limited thus using raw javascript may be inevitable in some cases. The JQuery javascript file is required to run JQuery commands, while the size of this file is relatively small (25-100KB depending on the server), it is still a strain on the client computer and maybe your web server as well if you intend to host the JQuery script on your own web server. jQuery-Basics JavaScript JQuery Web Technologies Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Difference between var, let and const keywords in JavaScript Differences between Functional Components and Class Components in React Remove elements from a JavaScript Array Hide or show elements in HTML using display property Difference Between PUT and PATCH Request JQuery | Set the value of an input text field How to change selected value of a drop-down list using jQuery? Form validation using jQuery How to add options to a select element using jQuery? How to Dynamically Add/Remove Table Rows using jQuery ?
[ { "code": null, "e": 52, "s": 24, "text": "\n18 May, 2021" }, { "code": null, "e": 524, "s": 52, "text": "jQuery is an open source JavaScript library that simplifies the interactions between an HTML/CSS document, or more precisely the Document Object Model (DOM), and JavaScript.Elaborating the terms, jQuery simplifies HTML document traversing and manipulation, browser event handling, DOM animations, Ajax interactions, and cross-browser JavaScript development.Note: The only library available today that meets the needs of both designer types and programmer types is jQuery." }, { "code": null, "e": 655, "s": 524, "text": "jQuery is widely famous with its philosophy of “Write less, do more.” This philosophy can be further elaborated as three concepts:" }, { "code": null, "e": 839, "s": 655, "text": "Finding some elements (via CSS selectors) and doing something with them (via jQuery methods) i.e. locate a set of elements in the DOM, and then do something with that set of elements." }, { "code": null, "e": 893, "s": 839, "text": "Chaining multiple jQuery methods on a set of elements" }, { "code": null, "e": 941, "s": 893, "text": "Using the jQuery wrapper and implicit iteration" }, { "code": null, "e": 1042, "s": 941, "text": "Using jQuery (JS) library on HTML pageThere are several ways to start using jQuery on your web site." }, { "code": null, "e": 1238, "s": 1042, "text": "Use the Google-hosted/ Microsoft-hosted content delivery network (CDN) to include a version of jQuery.Download own version of jQuery from jQuery.com and host it on own server or local filesystem." }, { "code": null, "e": 1341, "s": 1238, "text": "Use the Google-hosted/ Microsoft-hosted content delivery network (CDN) to include a version of jQuery." }, { "code": null, "e": 1435, "s": 1341, "text": "Download own version of jQuery from jQuery.com and host it on own server or local filesystem." }, { "code": null, "e": 1586, "s": 1435, "text": "Note: All jQuery methods are inside a document-ready event to prevent any jQuery code from running before the document is finished loading (is ready)." }, { "code": null, "e": 1627, "s": 1586, "text": "Basic syntax for any jQuery function is:" }, { "code": null, "e": 1648, "s": 1627, "text": "$(selector).action()" }, { "code": null, "e": 1684, "s": 1648, "text": "A $ sign is to define/access jQuery" }, { "code": null, "e": 1748, "s": 1684, "text": "A (selector) is to “query (or find)” HTML elements in html page" }, { "code": null, "e": 1823, "s": 1748, "text": "A jQuery action() is the action to be performed on the selected element(s)" }, { "code": null, "e": 1832, "s": 1823, "text": "Example:" }, { "code": "<!DOCTYPE html><html> <head> <script src= \"https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js\"> </script> <script> $(document).ready(function () { $(\"h2\").click(function () { $(this).hover(); }); }); </script> </head> <body> <center> <h2 style=\"color: green;\"> GeeksforGeeks </h2> </center> </body></html>", "e": 2323, "s": 1832, "text": null }, { "code": null, "e": 2331, "s": 2323, "text": "Output:" }, { "code": null, "e": 2413, "s": 2331, "text": "Why jQuery?Some of the key points which support the answer for why to use jQuery:" }, { "code": null, "e": 2573, "s": 2413, "text": "It is incredibly popular, which is to say it has a large community of users and a healthy amount of contributors who participate as developers and evangelists." }, { "code": null, "e": 2651, "s": 2573, "text": "It normalizes the differences between web browsers so that you don’t have to." }, { "code": null, "e": 2741, "s": 2651, "text": "It is intentionally a lightweight footprint with a simple yet clever plugin architecture." }, { "code": null, "e": 2826, "s": 2741, "text": "Its repository of plugins is vast and has seen steady growth since jQuery’s release." }, { "code": null, "e": 2998, "s": 2826, "text": "Its API is fully documented, including inline code examples, which in the world of JavaScript libraries is a luxury. Heck, any documentation at all was a luxury for years." }, { "code": null, "e": 3107, "s": 2998, "text": "It is friendly, which is to say it provides helpful ways to avoid conflicts with other JavaScript libraries." }, { "code": null, "e": 3119, "s": 3107, "text": "Advantages:" }, { "code": null, "e": 3221, "s": 3119, "text": "Wide range of plug-ins. jQuery allows developers to create plug-ins on top of the JavaScript library." }, { "code": null, "e": 3249, "s": 3221, "text": "Large development community" }, { "code": null, "e": 3295, "s": 3249, "text": "It has a good and comprehensive documentation" }, { "code": null, "e": 3388, "s": 3295, "text": "It is a lot more easy to use compared to standard javascript and other javascript libraries." }, { "code": null, "e": 3563, "s": 3388, "text": "JQuery lets users develop Ajax templates with ease, Ajax enables a sleeker interface where actions can be performed on pages without requiring the entire page to be reloaded." }, { "code": null, "e": 3645, "s": 3563, "text": "Being Light weight and a powerful chaining capabilities makes jQuery more strong." }, { "code": null, "e": 3660, "s": 3645, "text": "Disadvantages:" }, { "code": null, "e": 3878, "s": 3660, "text": "While JQuery has an impressive library in terms of quantity, depending on how much customization you require on your website, the functionality may be limited thus using raw javascript may be inevitable in some cases." }, { "code": null, "e": 4167, "s": 3878, "text": "The JQuery javascript file is required to run JQuery commands, while the size of this file is relatively small (25-100KB depending on the server), it is still a strain on the client computer and maybe your web server as well if you intend to host the JQuery script on your own web server." }, { "code": null, "e": 4181, "s": 4167, "text": "jQuery-Basics" }, { "code": null, "e": 4192, "s": 4181, "text": "JavaScript" }, { "code": null, "e": 4199, "s": 4192, "text": "JQuery" }, { "code": null, "e": 4216, "s": 4199, "text": "Web Technologies" }, { "code": null, "e": 4314, "s": 4216, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 4375, "s": 4314, "text": "Difference between var, let and const keywords in JavaScript" }, { "code": null, "e": 4447, "s": 4375, "text": "Differences between Functional Components and Class Components in React" }, { "code": null, "e": 4487, "s": 4447, "text": "Remove elements from a JavaScript Array" }, { "code": null, "e": 4540, "s": 4487, "text": "Hide or show elements in HTML using display property" }, { "code": null, "e": 4581, "s": 4540, "text": "Difference Between PUT and PATCH Request" }, { "code": null, "e": 4627, "s": 4581, "text": "JQuery | Set the value of an input text field" }, { "code": null, "e": 4690, "s": 4627, "text": "How to change selected value of a drop-down list using jQuery?" }, { "code": null, "e": 4719, "s": 4690, "text": "Form validation using jQuery" }, { "code": null, "e": 4772, "s": 4719, "text": "How to add options to a select element using jQuery?" } ]
C# | Remove the specified element from a HashSet
01 Feb, 2019 A HashSet is an unordered collection of the unique elements. It comes under System.Collections.Generic namespace. It is used in a situation where we want to prevent duplicates from being inserted in the collection. As far as performance is concerned, it is better in comparison to the list. HashSet<T>.Remove(T) method is used to removes the specified element from a HashSet<T> object. Syntax: public bool Remove (T item); Here, item is the element which is to be remove. Return Value: The method returns True if the element is successfully found and removed and returns False if item is not found in the HashSet<T> object. Below examples illustrate the use of HashSet.Remove(T) Method: Example 1: // C# code to remove the specified // element from a HashSetusing System;using System.Collections.Generic; class GFG { // Driver code public static void Main() { // Creating a HashSet of integers HashSet<int> mySet = new HashSet<int>(); // Inserting even numbers less than // equal to 20 in HashSet mySet for (int i = 0; i < 10; i++) { mySet.Add(i * 2); } Console.WriteLine("The elements in HashSet are : "); // Displaying the elements in HashSet foreach(int i in mySet) { Console.WriteLine(i); } // Displaying the number of elements in HashSet Console.WriteLine("Number of elements are : " + mySet.Count); // Removing the element 10 if present if (mySet.Contains(10)) { mySet.Remove(10); } Console.WriteLine("The elements in HashSet are : "); // Displaying the elements in HashSet foreach(int i in mySet) { Console.WriteLine(i); } // Displaying the number of elements in HashSet Console.WriteLine("Number of elements are : " + mySet.Count); }} The elements in HashSet are : 0 2 4 6 8 10 12 14 16 18 Number of elements are : 10 The elements in HashSet are : 0 2 4 6 8 12 14 16 18 Number of elements are : 9 Example 2: // C# code to remove the specified// element from a HashSetusing System;using System.Collections.Generic; class GFG { // Driver code public static void Main() { // Creating a HashSet of strings HashSet<string> mySet = new HashSet<string>(); // Inserting elements into HashSet mySet.Add("Data Structures"); mySet.Add("Algorithms"); mySet.Add("Java"); mySet.Add("Puzzles"); mySet.Add("Coding"); Console.WriteLine("The elements in HashSet are : "); // Displaying the elements in HashSet foreach(string i in mySet) { Console.WriteLine(i); } // Displaying the number of elements in HashSet Console.WriteLine("Number of elements are : " + mySet.Count); // Removing the element "JavaScript" if present if (mySet.Contains("JavaScript")) { mySet.Remove("JavaScript"); } Console.WriteLine("The elements in HashSet are : "); // Displaying the elements in HashSet foreach(string i in mySet) { Console.WriteLine(i); } // Displaying the number of elements in HashSet Console.WriteLine("Number of elements are : " + mySet.Count); }} The elements in HashSet are : Data Structures Algorithms Java Puzzles Coding Number of elements are : 5 The elements in HashSet are : Data Structures Algorithms Java Puzzles Coding Number of elements are : 5 Reference: https://docs.microsoft.com/en-us/dotnet/api/system.collections.generic.hashset-1.remove?view=netframework-4.7.2 CSharp-Generic-HashSet CSharp-Generic-Namespace CSharp-method C# Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n01 Feb, 2019" }, { "code": null, "e": 414, "s": 28, "text": "A HashSet is an unordered collection of the unique elements. It comes under System.Collections.Generic namespace. It is used in a situation where we want to prevent duplicates from being inserted in the collection. As far as performance is concerned, it is better in comparison to the list. HashSet<T>.Remove(T) method is used to removes the specified element from a HashSet<T> object." }, { "code": null, "e": 422, "s": 414, "text": "Syntax:" }, { "code": null, "e": 452, "s": 422, "text": "public bool Remove (T item);\n" }, { "code": null, "e": 501, "s": 452, "text": "Here, item is the element which is to be remove." }, { "code": null, "e": 653, "s": 501, "text": "Return Value: The method returns True if the element is successfully found and removed and returns False if item is not found in the HashSet<T> object." }, { "code": null, "e": 716, "s": 653, "text": "Below examples illustrate the use of HashSet.Remove(T) Method:" }, { "code": null, "e": 727, "s": 716, "text": "Example 1:" }, { "code": "// C# code to remove the specified // element from a HashSetusing System;using System.Collections.Generic; class GFG { // Driver code public static void Main() { // Creating a HashSet of integers HashSet<int> mySet = new HashSet<int>(); // Inserting even numbers less than // equal to 20 in HashSet mySet for (int i = 0; i < 10; i++) { mySet.Add(i * 2); } Console.WriteLine(\"The elements in HashSet are : \"); // Displaying the elements in HashSet foreach(int i in mySet) { Console.WriteLine(i); } // Displaying the number of elements in HashSet Console.WriteLine(\"Number of elements are : \" + mySet.Count); // Removing the element 10 if present if (mySet.Contains(10)) { mySet.Remove(10); } Console.WriteLine(\"The elements in HashSet are : \"); // Displaying the elements in HashSet foreach(int i in mySet) { Console.WriteLine(i); } // Displaying the number of elements in HashSet Console.WriteLine(\"Number of elements are : \" + mySet.Count); }}", "e": 1910, "s": 727, "text": null }, { "code": null, "e": 2075, "s": 1910, "text": "The elements in HashSet are : \n0\n2\n4\n6\n8\n10\n12\n14\n16\n18\nNumber of elements are : 10\nThe elements in HashSet are : \n0\n2\n4\n6\n8\n12\n14\n16\n18\nNumber of elements are : 9\n" }, { "code": null, "e": 2086, "s": 2075, "text": "Example 2:" }, { "code": "// C# code to remove the specified// element from a HashSetusing System;using System.Collections.Generic; class GFG { // Driver code public static void Main() { // Creating a HashSet of strings HashSet<string> mySet = new HashSet<string>(); // Inserting elements into HashSet mySet.Add(\"Data Structures\"); mySet.Add(\"Algorithms\"); mySet.Add(\"Java\"); mySet.Add(\"Puzzles\"); mySet.Add(\"Coding\"); Console.WriteLine(\"The elements in HashSet are : \"); // Displaying the elements in HashSet foreach(string i in mySet) { Console.WriteLine(i); } // Displaying the number of elements in HashSet Console.WriteLine(\"Number of elements are : \" + mySet.Count); // Removing the element \"JavaScript\" if present if (mySet.Contains(\"JavaScript\")) { mySet.Remove(\"JavaScript\"); } Console.WriteLine(\"The elements in HashSet are : \"); // Displaying the elements in HashSet foreach(string i in mySet) { Console.WriteLine(i); } // Displaying the number of elements in HashSet Console.WriteLine(\"Number of elements are : \" + mySet.Count); }}", "e": 3346, "s": 2086, "text": null }, { "code": null, "e": 3557, "s": 3346, "text": "The elements in HashSet are : \nData Structures\nAlgorithms\nJava\nPuzzles\nCoding\nNumber of elements are : 5\nThe elements in HashSet are : \nData Structures\nAlgorithms\nJava\nPuzzles\nCoding\nNumber of elements are : 5\n" }, { "code": null, "e": 3568, "s": 3557, "text": "Reference:" }, { "code": null, "e": 3680, "s": 3568, "text": "https://docs.microsoft.com/en-us/dotnet/api/system.collections.generic.hashset-1.remove?view=netframework-4.7.2" }, { "code": null, "e": 3703, "s": 3680, "text": "CSharp-Generic-HashSet" }, { "code": null, "e": 3728, "s": 3703, "text": "CSharp-Generic-Namespace" }, { "code": null, "e": 3742, "s": 3728, "text": "CSharp-method" }, { "code": null, "e": 3745, "s": 3742, "text": "C#" } ]
z-score Standardization in R
24 Feb, 2021 In statistics, the task is to standardize variables which are called valvulating z-scores. Comparing two standardizing variables is the function of standardizing vector. By subtracting the vector by its mean and dividing the result by the vector’s standard deviation we can standardize a vector. Formula: Z= (x – mean)/standard deviation Approach: Declare a vector Calculate its mean and standard deviation by the functions mean() and sd(). To create a standardized vector:Subtract mean from the vectorNow divide the above result with standard deviation Subtract mean from the vector Now divide the above result with standard deviation R a <- c(7, 8, 3, 2, 2, 10, 9) # Finding Meanm<-mean(a) # Finding Standard Deviations<-sd(a) #standardized vectora.z<-(a-m)/s a.z Output: [1] 0.3325644 0.6235582 -0.8314110 -1.1224048 -1.1224048 1.2055459 0.9145521 Now we can also check whether the vector has been correctly standardized or not by checking if its mean is zero and the standard deviation is one. The answer of mean is not coming exactly zero but almost zero. Which is acceptable since it is the result of computer laws. Program: R a <- c(7, 8, 3, 2, 2, 10, 9) # Finding Meanm<-mean(a) # Finding Standard Deviations<-sd(a) #standardized vectora.z<-(a-m)/s mean(a.z) sd(a.z) Output: [1] 1.427197e-16 [1] 1 Example 2: R a <- c(10, 6, 3, 5, 4)b <- c(150, 200, 500, 600, 850) a.z <- (a - mean(a)) / sd(a) b.z <- (b - mean(b)) / sd(b) average.z <- (a.z + (b.z)) / 2round(average.z, 1) Output: [1] 0.3 -0.4 -0.4 0.1 0.4 Picked R-Statistics R Language Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Change Color of Bars in Barchart using ggplot2 in R How to Split Column Into Multiple Columns in R DataFrame? Group by function in R using Dplyr How to Change Axis Scales in R Plots? How to filter R DataFrame by values in a column? R - if statement Logistic Regression in R Programming Replace Specific Characters in String in R How to import an Excel File into R ? Joining of Dataframes in R Programming
[ { "code": null, "e": 28, "s": 0, "text": "\n24 Feb, 2021" }, { "code": null, "e": 324, "s": 28, "text": "In statistics, the task is to standardize variables which are called valvulating z-scores. Comparing two standardizing variables is the function of standardizing vector. By subtracting the vector by its mean and dividing the result by the vector’s standard deviation we can standardize a vector." }, { "code": null, "e": 333, "s": 324, "text": "Formula:" }, { "code": null, "e": 366, "s": 333, "text": "Z= (x – mean)/standard deviation" }, { "code": null, "e": 376, "s": 366, "text": "Approach:" }, { "code": null, "e": 393, "s": 376, "text": "Declare a vector" }, { "code": null, "e": 469, "s": 393, "text": "Calculate its mean and standard deviation by the functions mean() and sd()." }, { "code": null, "e": 582, "s": 469, "text": "To create a standardized vector:Subtract mean from the vectorNow divide the above result with standard deviation" }, { "code": null, "e": 612, "s": 582, "text": "Subtract mean from the vector" }, { "code": null, "e": 664, "s": 612, "text": "Now divide the above result with standard deviation" }, { "code": null, "e": 666, "s": 664, "text": "R" }, { "code": "a <- c(7, 8, 3, 2, 2, 10, 9) # Finding Meanm<-mean(a) # Finding Standard Deviations<-sd(a) #standardized vectora.z<-(a-m)/s a.z", "e": 798, "s": 666, "text": null }, { "code": null, "e": 806, "s": 798, "text": "Output:" }, { "code": null, "e": 887, "s": 806, "text": "[1] 0.3325644 0.6235582 -0.8314110 -1.1224048 -1.1224048 1.2055459 0.9145521" }, { "code": null, "e": 1158, "s": 887, "text": "Now we can also check whether the vector has been correctly standardized or not by checking if its mean is zero and the standard deviation is one. The answer of mean is not coming exactly zero but almost zero. Which is acceptable since it is the result of computer laws." }, { "code": null, "e": 1167, "s": 1158, "text": "Program:" }, { "code": null, "e": 1169, "s": 1167, "text": "R" }, { "code": "a <- c(7, 8, 3, 2, 2, 10, 9) # Finding Meanm<-mean(a) # Finding Standard Deviations<-sd(a) #standardized vectora.z<-(a-m)/s mean(a.z) sd(a.z)", "e": 1316, "s": 1169, "text": null }, { "code": null, "e": 1324, "s": 1316, "text": "Output:" }, { "code": null, "e": 1341, "s": 1324, "text": "[1] 1.427197e-16" }, { "code": null, "e": 1347, "s": 1341, "text": "[1] 1" }, { "code": null, "e": 1359, "s": 1347, "text": "Example 2: " }, { "code": null, "e": 1361, "s": 1359, "text": "R" }, { "code": "a <- c(10, 6, 3, 5, 4)b <- c(150, 200, 500, 600, 850) a.z <- (a - mean(a)) / sd(a) b.z <- (b - mean(b)) / sd(b) average.z <- (a.z + (b.z)) / 2round(average.z, 1)", "e": 1526, "s": 1361, "text": null }, { "code": null, "e": 1534, "s": 1526, "text": "Output:" }, { "code": null, "e": 1563, "s": 1534, "text": "[1] 0.3 -0.4 -0.4 0.1 0.4" }, { "code": null, "e": 1570, "s": 1563, "text": "Picked" }, { "code": null, "e": 1583, "s": 1570, "text": "R-Statistics" }, { "code": null, "e": 1594, "s": 1583, "text": "R Language" }, { "code": null, "e": 1692, "s": 1594, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 1744, "s": 1692, "text": "Change Color of Bars in Barchart using ggplot2 in R" }, { "code": null, "e": 1802, "s": 1744, "text": "How to Split Column Into Multiple Columns in R DataFrame?" }, { "code": null, "e": 1837, "s": 1802, "text": "Group by function in R using Dplyr" }, { "code": null, "e": 1875, "s": 1837, "text": "How to Change Axis Scales in R Plots?" }, { "code": null, "e": 1924, "s": 1875, "text": "How to filter R DataFrame by values in a column?" }, { "code": null, "e": 1941, "s": 1924, "text": "R - if statement" }, { "code": null, "e": 1978, "s": 1941, "text": "Logistic Regression in R Programming" }, { "code": null, "e": 2021, "s": 1978, "text": "Replace Specific Characters in String in R" }, { "code": null, "e": 2058, "s": 2021, "text": "How to import an Excel File into R ?" } ]
sys.maxsize() in Python
23 Jun, 2021 maxsize attribute of the sys module fetches the largest value a variable of data type Py_ssize_t can store. It is the Python platform’s pointer that dictates the maximum size of lists and strings in Python. The size value returned by maxsize depends on the platform architecture: 32-bit: the value will be 2^31 – 1, i.e. 2147483647 64-bit: the value will be 2^63 – 1, i.e. 9223372036854775807 Syntax: sys.maxsize Returns: maximum value of Py_ssize_t depending upon the architecture Example 1: Let us fetch the maximum Py_ssize_t value on a 64-bit system. Python3 # importing the moduleimport sys # fetching the maximum valuemax_val = sys.maxsizeprint(max_val) Output: 9223372036854775807 Example 2: Creating a list with the maximum size. Python3 # importing the moduleimport sys # fetching the maximum valuemax_val = sys.maxsize # creating list with max sizelist = range(max_val) # displaying the length of the listprint(len(list)) print("List successfully created") 9223372036854775807 List successfully created Output: 9223372036854775807 List successfully created Example 3: Trying to create a list with a size greater than the maximum size. Python3 # importing the moduleimport sys # fetching the maximum valuemax_val = sys.maxsize try: # creating list with max size + 1 list = range(max_val + 1) # displaying the length of the list print(len(list)) print("List successfully created") except Exception as e: # displaying the exception print(e) print("List creation unsuccessful") Python int too large to convert to C ssize_t List creation unsuccessful Output: Python int too large to convert to C ssize_t List creation unsuccessful ruhelaa48 Python-sys Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n23 Jun, 2021" }, { "code": null, "e": 308, "s": 28, "text": "maxsize attribute of the sys module fetches the largest value a variable of data type Py_ssize_t can store. It is the Python platform’s pointer that dictates the maximum size of lists and strings in Python. The size value returned by maxsize depends on the platform architecture:" }, { "code": null, "e": 360, "s": 308, "text": "32-bit: the value will be 2^31 – 1, i.e. 2147483647" }, { "code": null, "e": 421, "s": 360, "text": "64-bit: the value will be 2^63 – 1, i.e. 9223372036854775807" }, { "code": null, "e": 441, "s": 421, "text": "Syntax: sys.maxsize" }, { "code": null, "e": 510, "s": 441, "text": "Returns: maximum value of Py_ssize_t depending upon the architecture" }, { "code": null, "e": 583, "s": 510, "text": "Example 1: Let us fetch the maximum Py_ssize_t value on a 64-bit system." }, { "code": null, "e": 591, "s": 583, "text": "Python3" }, { "code": "# importing the moduleimport sys # fetching the maximum valuemax_val = sys.maxsizeprint(max_val)", "e": 694, "s": 591, "text": null }, { "code": null, "e": 702, "s": 694, "text": "Output:" }, { "code": null, "e": 722, "s": 702, "text": "9223372036854775807" }, { "code": null, "e": 772, "s": 722, "text": "Example 2: Creating a list with the maximum size." }, { "code": null, "e": 780, "s": 772, "text": "Python3" }, { "code": "# importing the moduleimport sys # fetching the maximum valuemax_val = sys.maxsize # creating list with max sizelist = range(max_val) # displaying the length of the listprint(len(list)) print(\"List successfully created\")", "e": 1007, "s": 780, "text": null }, { "code": null, "e": 1054, "s": 1007, "text": "9223372036854775807\nList successfully created\n" }, { "code": null, "e": 1062, "s": 1054, "text": "Output:" }, { "code": null, "e": 1108, "s": 1062, "text": "9223372036854775807\nList successfully created" }, { "code": null, "e": 1186, "s": 1108, "text": "Example 3: Trying to create a list with a size greater than the maximum size." }, { "code": null, "e": 1194, "s": 1186, "text": "Python3" }, { "code": "# importing the moduleimport sys # fetching the maximum valuemax_val = sys.maxsize try: # creating list with max size + 1 list = range(max_val + 1) # displaying the length of the list print(len(list)) print(\"List successfully created\") except Exception as e: # displaying the exception print(e) print(\"List creation unsuccessful\")", "e": 1562, "s": 1194, "text": null }, { "code": null, "e": 1635, "s": 1562, "text": "Python int too large to convert to C ssize_t\nList creation unsuccessful\n" }, { "code": null, "e": 1643, "s": 1635, "text": "Output:" }, { "code": null, "e": 1715, "s": 1643, "text": "Python int too large to convert to C ssize_t\nList creation unsuccessful" }, { "code": null, "e": 1725, "s": 1715, "text": "ruhelaa48" }, { "code": null, "e": 1736, "s": 1725, "text": "Python-sys" }, { "code": null, "e": 1743, "s": 1736, "text": "Python" } ]
Segmented Sieve
13 Jun, 2022 Given a number n, print all primes smaller than n. For example, if the given number is 10, output 2, 3, 5, 7. A Naive approach is to run a loop from 0 to n-1 and check each number for primeness. A Better Approach is to use Simple Sieve of Eratosthenes. C C++ Java Python3 C# Javascript // This functions finds all primes smaller than 'limit'// using simple sieve of eratosthenes.void simpleSieve(int limit){ // Create a boolean array "mark[0..limit-1]" and // initialize all entries of it as true. A value // in mark[p] will finally be false if 'p' is Not // a prime, else true. bool mark[limit]; for(int i = 0; i<limit; i++) { mark[i] = true; } // One by one traverse all numbers so that their // multiples can be marked as composite. for (int p=2; p*p<limit; p++) { // If p is not changed, then it is a prime if (mark[p] == true) { // Update all multiples of p for (int i=p*p; i<limit; i+=p) mark[i] = false; } } // Print all prime numbers and store them in prime for (int p=2; p<limit; p++) if (mark[p] == true) cout << p << " ";} // C++ code to implement the approach#include <bits/stdc++.h>using namespace std; void simpleSieve(int limit){ // Create a boolean array "mark[0..limit-1]" and // initialize all entries of it as true. A value // in mark[p] will finally be false if 'p' is Not // a prime, else true. bool mark[limit]; for(int i = 0; i<limit; i++) { mark[i] = true; } // One by one traverse all numbers so that their // multiples can be marked as composite. for (int p=2; p*p<limit; p++) { // If p is not changed, then it is a prime if (mark[p] == true) { // Update all multiples of p for (int i=p*p; i<limit; i+=p) mark[i] = false; } } // Print all prime numbers and store them in prime for (int p=2; p<limit; p++) if (mark[p] == true) cout << p << " ";} // This code is contributed by sanjoy_62. // This functions finds all primes smaller than 'limit'// using simple sieve of eratosthenes.static void simpleSieve(int limit){ // Create a boolean array "mark[0..limit-1]" and // initialize all entries of it as true. A value // in mark[p] will finally be false if 'p' is Not // a prime, else true. boolean []mark = new boolean[limit]; Arrays.fill(mark, true); // One by one traverse all numbers so that their // multiples can be marked as composite. for (int p = 2; p * p < limit; p++) { // If p is not changed, then it is a prime if (mark[p] == true) { // Update all multiples of p for (int i = p * p; i < limit; i += p) mark[i] = false; } } // Print all prime numbers and store them in prime for (int p = 2; p < limit; p++) if (mark[p] == true) System.out.print(p + " ");} // This code is contributed by rutvik_56. # This functions finds all primes smaller than 'limit'# using simple sieve of eratosthenes.def simpleSieve(limit): # Create a boolean array "mark[0..limit-1]" and # initialize all entries of it as true. A value # in mark[p] will finally be false if 'p' is Not # a prime, else true. mark = [True for i in range(limit)] # One by one traverse all numbers so that their # multiples can be marked as composite. for p in range(p * p, limit - 1, 1): # If p is not changed, then it is a prime if (mark[p] == True): # Update all multiples of p for i in range(p * p, limit - 1, p): mark[i] = False # Print all prime numbers and store them in prime for p in range(2, limit - 1, 1): if (mark[p] == True): print(p, end=" ") # This code is contributed by Dharanendra L V. // This functions finds all primes smaller than 'limit'// using simple sieve of eratosthenes.static void simpleSieve(int limit){ // Create a boolean array "mark[0..limit-1]" and // initialize all entries of it as true. A value // in mark[p] will finally be false if 'p' is Not // a prime, else true. bool []mark = new bool[limit]; Array.Fill(mark, true); // One by one traverse all numbers so that their // multiples can be marked as composite. for (int p = 2; p * p < limit; p++) { // If p is not changed, then it is a prime if (mark[p] == true) { // Update all multiples of p for (int i = p * p; i < limit; i += p) mark[i] = false; } } // Print all prime numbers and store them in prime for (int p = 2; p < limit; p++) if (mark[p] == true) Console.Write(p + " ");} // This code is contributed by pratham76. <script> // This functions finds all primes smaller than 'limit'// using simple sieve of eratosthenes.function simpleSieve(limit){ // Create a boolean array "mark[0..limit-1]" and // initialize all entries of it as true. A value // in mark[p] will finally be false if 'p' is Not // a prime, else true. var mark = Array(limit).fill(true); // One by one traverse all numbers so that their // multiples can be marked as composite. for (p = 2; p * p < limit; p++) { // If p is not changed, then it is a prime if (mark[p] == true) { // Update all multiples of p for (i = p * p; i < limit; i += p) mark[i] = false; } } // Print all prime numbers and store them in prime for (p = 2; p < limit; p++) if (mark[p] == true) document.write(p + " ");} // This code is contributed by todaysgaurav </script> Problems with Simple Sieve:The Sieve of Eratosthenes looks good, but consider the situation when n is large, the Simple Sieve faces the following issues. An array of size Θ(n) may not fit in memory The simple Sieve is not cached friendly even for slightly bigger n. The algorithm traverses the array without locality of reference Segmented SieveThe idea of a segmented sieve is to divide the range [0..n-1] in different segments and compute primes in all segments one by one. This algorithm first uses Simple Sieve to find primes smaller than or equal to √(n). Below are steps used in Segmented Sieve. Use Simple Sieve to find all primes up to the square root of ‘n’ and store these primes in an array “prime[]”. Store the found primes in an array ‘prime[]’.We need all primes in the range [0..n-1]. We divide this range into different segments such that the size of every segment is at-most √nDo following for every segment [low..high] Create an array mark[high-low+1]. Here we need only O(x) space where x is a number of elements in a given range.Iterate through all primes found in step 1. For every prime, mark its multiples in the given range [low..high]. Use Simple Sieve to find all primes up to the square root of ‘n’ and store these primes in an array “prime[]”. Store the found primes in an array ‘prime[]’. We need all primes in the range [0..n-1]. We divide this range into different segments such that the size of every segment is at-most √n Do following for every segment [low..high] Create an array mark[high-low+1]. Here we need only O(x) space where x is a number of elements in a given range.Iterate through all primes found in step 1. For every prime, mark its multiples in the given range [low..high]. Create an array mark[high-low+1]. Here we need only O(x) space where x is a number of elements in a given range. Iterate through all primes found in step 1. For every prime, mark its multiples in the given range [low..high]. In Simple Sieve, we needed O(n) space which may not be feasible for large n. Here we need O(√n) space and we process smaller ranges at a time (locality of reference) Below is the implementation of the above idea. C++ Java Python3 C# Javascript // C++ program to print all primes smaller than// n using segmented sieve#include <bits/stdc++.h>using namespace std; // This functions finds all primes smaller than 'limit'// using simple sieve of eratosthenes. It also stores// found primes in vector prime[]void simpleSieve(int limit, vector<int> &prime){ // Create a boolean array "mark[0..n-1]" and initialize // all entries of it as true. A value in mark[p] will // finally be false if 'p' is Not a prime, else true. vector<bool> mark(limit + 1, true); for (int p=2; p*p<limit; p++) { // If p is not changed, then it is a prime if (mark[p] == true) { // Update all multiples of p for (int i=p*p; i<limit; i+=p) mark[i] = false; } } // Print all prime numbers and store them in prime for (int p=2; p<limit; p++) { if (mark[p] == true) { prime.push_back(p); cout << p << " "; } }} // Prints all prime numbers smaller than 'n'void segmentedSieve(int n){ // Compute all primes smaller than or equal // to square root of n using simple sieve int limit = floor(sqrt(n))+1; vector<int> prime; prime.reserve(limit); simpleSieve(limit, prime); // Divide the range [0..n-1] in different segments // We have chosen segment size as sqrt(n). int low = limit; int high = 2*limit; // While all segments of range [0..n-1] are not processed, // process one segment at a time while (low < n) { if (high >= n) high = n; // To mark primes in current range. A value in mark[i] // will finally be false if 'i-low' is Not a prime, // else true. bool mark[limit+1]; memset(mark, true, sizeof(mark)); // Use the found primes by simpleSieve() to find // primes in current range for (int i = 0; i < prime.size(); i++) { // Find the minimum number in [low..high] that is // a multiple of prime[i] (divisible by prime[i]) // For example, if low is 31 and prime[i] is 3, // we start with 33. int loLim = floor(low/prime[i]) * prime[i]; if (loLim < low) loLim += prime[i]; /* Mark multiples of prime[i] in [low..high]: We are marking j - low for j, i.e. each number in range [low, high] is mapped to [0, high-low] so if range is [50, 100] marking 50 corresponds to marking 0, marking 51 corresponds to 1 and so on. In this way we need to allocate space only for range */ for (int j=loLim; j<high; j+=prime[i]) mark[j-low] = false; } // Numbers which are not marked as false are prime for (int i = low; i<high; i++) if (mark[i - low] == true) cout << i << " "; // Update low and high for next segment low = low + limit; high = high + limit; }} // Driver program to test above functionint main(){ int n = 100000; cout << "Primes smaller than " << n << ":n"; segmentedSieve(n); return 0;} // Java program to print all primes smaller than// n using segmented sieve import java.util.Vector;import static java.lang.Math.sqrt;import static java.lang.Math.floor; class Test{ // This method finds all primes smaller than 'limit' // using simple sieve of eratosthenes. It also stores // found primes in vector prime[] static void simpleSieve(int limit, Vector<Integer> prime) { // Create a boolean array "mark[0..n-1]" and initialize // all entries of it as true. A value in mark[p] will // finally be false if 'p' is Not a prime, else true. boolean mark[] = new boolean[limit+1]; for (int i = 0; i < mark.length; i++) mark[i] = true; for (int p=2; p*p<limit; p++) { // If p is not changed, then it is a prime if (mark[p] == true) { // Update all multiples of p for (int i=p*p; i<limit; i+=p) mark[i] = false; } } // Print all prime numbers and store them in prime for (int p=2; p<limit; p++) { if (mark[p] == true) { prime.add(p); System.out.print(p + " "); } } } // Prints all prime numbers smaller than 'n' static void segmentedSieve(int n) { // Compute all primes smaller than or equal // to square root of n using simple sieve int limit = (int) (floor(sqrt(n))+1); Vector<Integer> prime = new Vector<>(); simpleSieve(limit, prime); // Divide the range [0..n-1] in different segments // We have chosen segment size as sqrt(n). int low = limit; int high = 2*limit; // While all segments of range [0..n-1] are not processed, // process one segment at a time while (low < n) { if (high >= n) high = n; // To mark primes in current range. A value in mark[i] // will finally be false if 'i-low' is Not a prime, // else true. boolean mark[] = new boolean[limit+1]; for (int i = 0; i < mark.length; i++) mark[i] = true; // Use the found primes by simpleSieve() to find // primes in current range for (int i = 0; i < prime.size(); i++) { // Find the minimum number in [low..high] that is // a multiple of prime.get(i) (divisible by prime.get(i)) // For example, if low is 31 and prime.get(i) is 3, // we start with 33. int loLim = (int) (floor(low/prime.get(i)) * prime.get(i)); if (loLim < low) loLim += prime.get(i); /* Mark multiples of prime.get(i) in [low..high]: We are marking j - low for j, i.e. each number in range [low, high] is mapped to [0, high-low] so if range is [50, 100] marking 50 corresponds to marking 0, marking 51 corresponds to 1 and so on. In this way we need to allocate space only for range */ for (int j=loLim; j<high; j+=prime.get(i)) mark[j-low] = false; } // Numbers which are not marked as false are prime for (int i = low; i<high; i++) if (mark[i - low] == true) System.out.print(i + " "); // Update low and high for next segment low = low + limit; high = high + limit; } } // Driver method public static void main(String args[]) { int n = 100; System.out.println("Primes smaller than " + n + ":"); segmentedSieve(n); }} # Python3 program to print all primes# smaller than n, using segmented sieveimport mathprime = [] # This method finds all primes# smaller than 'limit' using# simple sieve of eratosthenes.# It also stores found primes in list primedef simpleSieve(limit): # Create a boolean list "mark[0..n-1]" and # initialize all entries of it as True. # A value in mark[p] will finally be False # if 'p' is Not a prime, else True. mark = [True for i in range(limit + 1)] p = 2 while (p * p <= limit): # If p is not changed, then it is a prime if (mark[p] == True): # Update all multiples of p for i in range(p * p, limit + 1, p): mark[i] = False p += 1 # Print all prime numbers # and store them in prime for p in range(2, limit): if mark[p]: prime.append(p) print(p,end = " ") # Prints all prime numbers smaller than 'n'def segmentedSieve(n): # Compute all primes smaller than or equal # to square root of n using simple sieve limit = int(math.floor(math.sqrt(n)) + 1) simpleSieve(limit) # Divide the range [0..n-1] in different segments # We have chosen segment size as sqrt(n). low = limit high = limit * 2 # While all segments of range [0..n-1] are not processed, # process one segment at a time while low < n: if high >= n: high = n # To mark primes in current range. A value in mark[i] # will finally be False if 'i-low' is Not a prime, # else True. mark = [True for i in range(limit + 1)] # Use the found primes by simpleSieve() # to find primes in current range for i in range(len(prime)): # Find the minimum number in [low..high] # that is a multiple of prime[i] # (divisible by prime[i]) # For example, if low is 31 and prime[i] is 3, # we start with 33. loLim = int(math.floor(low / prime[i]) * prime[i]) if loLim < low: loLim += prime[i] # Mark multiples of prime[i] in [low..high]: # We are marking j - low for j, i.e. each number # in range [low, high] is mapped to [0, high-low] # so if range is [50, 100] marking 50 corresponds # to marking 0, marking 51 corresponds to 1 and # so on. In this way we need to allocate space # only for range for j in range(loLim, high, prime[i]): mark[j - low] = False # Numbers which are not marked as False are prime for i in range(low, high): if mark[i - low]: print(i, end = " ") # Update low and high for next segment low = low + limit high = high + limit # Driver Coden = 100print("Primes smaller than", n, ":")segmentedSieve(100) # This code is contributed by bhavyadeep // C# program to print// all primes smaller than// n using segmented sieveusing System;using System.Collections; class GFG{ // This method finds all primes // smaller than 'limit' using simple // sieve of eratosthenes. It also stores // found primes in vector prime[] static void simpleSieve(int limit, ArrayList prime) { // Create a boolean array "mark[0..n-1]" // and initialize all entries of it as // true. A value in mark[p] will finally be // false if 'p' is Not a prime, else true. bool[] mark = new bool[limit + 1]; for (int i = 0; i < mark.Length; i++) mark[i] = true; for (int p = 2; p * p < limit; p++) { // If p is not changed, then it is a prime if (mark[p] == true) { // Update all multiples of p for (int i = p * p; i < limit; i += p) mark[i] = false; } } // Print all prime numbers and store them in prime for (int p = 2; p < limit; p++) { if (mark[p] == true) { prime.Add(p); Console.Write(p + " "); } } } // Prints all prime numbers smaller than 'n' static void segmentedSieve(int n) { // Compute all primes smaller than or equal // to square root of n using simple sieve int limit = (int) (Math.Floor(Math.Sqrt(n)) + 1); ArrayList prime = new ArrayList(); simpleSieve(limit, prime); // Divide the range [0..n-1] in // different segments We have chosen // segment size as sqrt(n). int low = limit; int high = 2*limit; // While all segments of range // [0..n-1] are not processed, // process one segment at a time while (low < n) { if (high >= n) high = n; // To mark primes in current range. // A value in mark[i] will finally // be false if 'i-low' is Not a prime, // else true. bool[] mark = new bool[limit + 1]; for (int i = 0; i < mark.Length; i++) mark[i] = true; // Use the found primes by // simpleSieve() to find // primes in current range for (int i = 0; i < prime.Count; i++) { // Find the minimum number in // [low..high] that is a multiple // of prime.get(i) (divisible by // prime.get(i)) For example, // if low is 31 and prime.get(i) // is 3, we start with 33. int loLim = ((int)Math.Floor((double)(low / (int)prime[i])) * (int)prime[i]); if (loLim < low) loLim += (int)prime[i]; /* Mark multiples of prime.get(i) in [low..high]: We are marking j - low for j, i.e. each number in range [low, high] is mapped to [0, high-low] so if range is [50, 100] marking 50 corresponds to marking 0, marking 51 corresponds to 1 and so on. In this way we need to allocate space only for range */ for (int j = loLim; j < high; j += (int)prime[i]) mark[j-low] = false; } // Numbers which are not marked as false are prime for (int i = low; i < high; i++) if (mark[i - low] == true) Console.Write(i + " "); // Update low and high for next segment low = low + limit; high = high + limit; } } // Driver code static void Main() { int n = 100; Console.WriteLine("Primes smaller than " + n + ":"); segmentedSieve(n); }} // This code is contributed by mits // JavaSCript program to print all primes smaller than// n using segmented sieve // This functions finds all primes smaller than 'limit'// using simple sieve of eratosthenes. It also stores// found primes in vector prime[] let res = ""; function simpleSieve(limit, prime){ // Create a boolean array "mark[0..n-1]" and initialize // all entries of it as true. A value in mark[p] will // finally be false if 'p' is Not a prime, else true. let mark = new Array(limit+1).fill(true); for (let p=2; p*p<limit; p++) { // If p is not changed, then it is a prime if (mark[p] === true) { // Update all multiples of p for (let i=p*p; i<limit; i+=p){ mark[i] = false; } } } // Print all prime numbers and store them in prime for (let p=2; p<limit; p++) { if (mark[p] === true) { prime.push(p); res = res + p + " "; } }} // Prints all prime numbers smaller than 'n'function segmentedSieve(n){ // Compute all primes smaller than or equal // to square root of n using simple sieve let limit = Math.floor(Math.sqrt(n))+1; let prime = new Array(limit); simpleSieve(limit, prime); // Divide the range [0..n-1] in different segments // We have chosen segment size as sqrt(n). let low = limit; let high = 2*limit; // While all segments of range [0..n-1] are not processed, // process one segment at a time while (low < n) { if (high >= n){ high = n; } // To mark primes in current range. A value in mark[i] // will finally be false if 'i-low' is Not a prime, // else true. let mark = new Array(limit+1).fill(true); // Use the found primes by simpleSieve() to find // primes in current range for (let i = 0; i < prime.length; i++) { // Find the minimum number in [low..high] that is // a multiple of prime[i] (divisible by prime[i]) // For example, if low is 31 and prime[i] is 3, // we start with 33. let loLim = Math.floor(low/prime[i]) * prime[i]; if (loLim < low){ loLim += prime[i]; } /* Mark multiples of prime[i] in [low..high]: We are marking j - low for j, i.e. each number in range [low, high] is mapped to [0, high-low] so if range is [50, 100] marking 50 corresponds to marking 0, marking 51 corresponds to 1 and so on. In this way we need to allocate space only for range */ for (let j=loLim; j<high; j+=prime[i]){ mark[j-low] = false; } } // Numbers which are not marked as false are prime for (let i = low; i<high; i++){ if (mark[i - low] == true){ res = res + i + " "; } } // Update low and high for next segment low = low + limit; high = high + limit; } console.log(res);} // Driver program to test above functionlet n = 100;console.log("Primes smaller than", n);segmentedSieve(n); // The code is contributed by Gautam goel (gautamgoel962) Output: Primes smaller than 100: 2 3 5 7 11 13 17 19 23 29 31 37 41 43 47 53 59 61 67 71 73 79 83 89 97 Time Complexity : O(sqrt(n)) Auxiliary Space: O(1) Note that time complexity (or a number of operations) by Segmented Sieve is the same as Simple Sieve. It has advantages for large ‘n’ as it has better locality of reference thus allowing better caching by the CPU and also requires less memory space.This article is contributed by Utkarsh Trivedi. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above Mithun Kumar BhavyadeepPurswani aerosayan kumarayush151 rutvik_56 pratham76 dharanendralv23 scisaif todaysgaurav sweetyty sanjoy_62 rishavnitro gautamgoel962 sumitgumber28 Prime Number sieve Mathematical Mathematical Prime Number sieve Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. 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 Coin Change | DP-7 Operators in C / C++ Prime Numbers Program to find GCD or HCF of two numbers Find minimum number of coins that make a given value
[ { "code": null, "e": 52, "s": 24, "text": "\n13 Jun, 2022" }, { "code": null, "e": 162, "s": 52, "text": "Given a number n, print all primes smaller than n. For example, if the given number is 10, output 2, 3, 5, 7." }, { "code": null, "e": 305, "s": 162, "text": "A Naive approach is to run a loop from 0 to n-1 and check each number for primeness. A Better Approach is to use Simple Sieve of Eratosthenes." }, { "code": null, "e": 307, "s": 305, "text": "C" }, { "code": null, "e": 311, "s": 307, "text": "C++" }, { "code": null, "e": 316, "s": 311, "text": "Java" }, { "code": null, "e": 324, "s": 316, "text": "Python3" }, { "code": null, "e": 327, "s": 324, "text": "C#" }, { "code": null, "e": 338, "s": 327, "text": "Javascript" }, { "code": "// This functions finds all primes smaller than 'limit'// using simple sieve of eratosthenes.void simpleSieve(int limit){ // Create a boolean array \"mark[0..limit-1]\" and // initialize all entries of it as true. A value // in mark[p] will finally be false if 'p' is Not // a prime, else true. bool mark[limit]; for(int i = 0; i<limit; i++) { mark[i] = true; } // One by one traverse all numbers so that their // multiples can be marked as composite. for (int p=2; p*p<limit; p++) { // If p is not changed, then it is a prime if (mark[p] == true) { // Update all multiples of p for (int i=p*p; i<limit; i+=p) mark[i] = false; } } // Print all prime numbers and store them in prime for (int p=2; p<limit; p++) if (mark[p] == true) cout << p << \" \";}", "e": 1221, "s": 338, "text": null }, { "code": "// C++ code to implement the approach#include <bits/stdc++.h>using namespace std; void simpleSieve(int limit){ // Create a boolean array \"mark[0..limit-1]\" and // initialize all entries of it as true. A value // in mark[p] will finally be false if 'p' is Not // a prime, else true. bool mark[limit]; for(int i = 0; i<limit; i++) { mark[i] = true; } // One by one traverse all numbers so that their // multiples can be marked as composite. for (int p=2; p*p<limit; p++) { // If p is not changed, then it is a prime if (mark[p] == true) { // Update all multiples of p for (int i=p*p; i<limit; i+=p) mark[i] = false; } } // Print all prime numbers and store them in prime for (int p=2; p<limit; p++) if (mark[p] == true) cout << p << \" \";} // This code is contributed by sanjoy_62.", "e": 2137, "s": 1221, "text": null }, { "code": "// This functions finds all primes smaller than 'limit'// using simple sieve of eratosthenes.static void simpleSieve(int limit){ // Create a boolean array \"mark[0..limit-1]\" and // initialize all entries of it as true. A value // in mark[p] will finally be false if 'p' is Not // a prime, else true. boolean []mark = new boolean[limit]; Arrays.fill(mark, true); // One by one traverse all numbers so that their // multiples can be marked as composite. for (int p = 2; p * p < limit; p++) { // If p is not changed, then it is a prime if (mark[p] == true) { // Update all multiples of p for (int i = p * p; i < limit; i += p) mark[i] = false; } } // Print all prime numbers and store them in prime for (int p = 2; p < limit; p++) if (mark[p] == true) System.out.print(p + \" \");} // This code is contributed by rutvik_56.", "e": 3085, "s": 2137, "text": null }, { "code": "# This functions finds all primes smaller than 'limit'# using simple sieve of eratosthenes.def simpleSieve(limit): # Create a boolean array \"mark[0..limit-1]\" and # initialize all entries of it as true. A value # in mark[p] will finally be false if 'p' is Not # a prime, else true. mark = [True for i in range(limit)] # One by one traverse all numbers so that their # multiples can be marked as composite. for p in range(p * p, limit - 1, 1): # If p is not changed, then it is a prime if (mark[p] == True): # Update all multiples of p for i in range(p * p, limit - 1, p): mark[i] = False # Print all prime numbers and store them in prime for p in range(2, limit - 1, 1): if (mark[p] == True): print(p, end=\" \") # This code is contributed by Dharanendra L V.", "e": 3947, "s": 3085, "text": null }, { "code": "// This functions finds all primes smaller than 'limit'// using simple sieve of eratosthenes.static void simpleSieve(int limit){ // Create a boolean array \"mark[0..limit-1]\" and // initialize all entries of it as true. A value // in mark[p] will finally be false if 'p' is Not // a prime, else true. bool []mark = new bool[limit]; Array.Fill(mark, true); // One by one traverse all numbers so that their // multiples can be marked as composite. for (int p = 2; p * p < limit; p++) { // If p is not changed, then it is a prime if (mark[p] == true) { // Update all multiples of p for (int i = p * p; i < limit; i += p) mark[i] = false; } } // Print all prime numbers and store them in prime for (int p = 2; p < limit; p++) if (mark[p] == true) Console.Write(p + \" \");} // This code is contributed by pratham76.", "e": 4903, "s": 3947, "text": null }, { "code": "<script> // This functions finds all primes smaller than 'limit'// using simple sieve of eratosthenes.function simpleSieve(limit){ // Create a boolean array \"mark[0..limit-1]\" and // initialize all entries of it as true. A value // in mark[p] will finally be false if 'p' is Not // a prime, else true. var mark = Array(limit).fill(true); // One by one traverse all numbers so that their // multiples can be marked as composite. for (p = 2; p * p < limit; p++) { // If p is not changed, then it is a prime if (mark[p] == true) { // Update all multiples of p for (i = p * p; i < limit; i += p) mark[i] = false; } } // Print all prime numbers and store them in prime for (p = 2; p < limit; p++) if (mark[p] == true) document.write(p + \" \");} // This code is contributed by todaysgaurav </script>", "e": 5823, "s": 4903, "text": null }, { "code": null, "e": 5977, "s": 5823, "text": "Problems with Simple Sieve:The Sieve of Eratosthenes looks good, but consider the situation when n is large, the Simple Sieve faces the following issues." }, { "code": null, "e": 6021, "s": 5977, "text": "An array of size Θ(n) may not fit in memory" }, { "code": null, "e": 6153, "s": 6021, "text": "The simple Sieve is not cached friendly even for slightly bigger n. The algorithm traverses the array without locality of reference" }, { "code": null, "e": 6425, "s": 6153, "text": "Segmented SieveThe idea of a segmented sieve is to divide the range [0..n-1] in different segments and compute primes in all segments one by one. This algorithm first uses Simple Sieve to find primes smaller than or equal to √(n). Below are steps used in Segmented Sieve." }, { "code": null, "e": 6984, "s": 6425, "text": "Use Simple Sieve to find all primes up to the square root of ‘n’ and store these primes in an array “prime[]”. Store the found primes in an array ‘prime[]’.We need all primes in the range [0..n-1]. We divide this range into different segments such that the size of every segment is at-most √nDo following for every segment [low..high] Create an array mark[high-low+1]. Here we need only O(x) space where x is a number of elements in a given range.Iterate through all primes found in step 1. For every prime, mark its multiples in the given range [low..high]." }, { "code": null, "e": 7141, "s": 6984, "text": "Use Simple Sieve to find all primes up to the square root of ‘n’ and store these primes in an array “prime[]”. Store the found primes in an array ‘prime[]’." }, { "code": null, "e": 7278, "s": 7141, "text": "We need all primes in the range [0..n-1]. We divide this range into different segments such that the size of every segment is at-most √n" }, { "code": null, "e": 7545, "s": 7278, "text": "Do following for every segment [low..high] Create an array mark[high-low+1]. Here we need only O(x) space where x is a number of elements in a given range.Iterate through all primes found in step 1. For every prime, mark its multiples in the given range [low..high]." }, { "code": null, "e": 7658, "s": 7545, "text": "Create an array mark[high-low+1]. Here we need only O(x) space where x is a number of elements in a given range." }, { "code": null, "e": 7770, "s": 7658, "text": "Iterate through all primes found in step 1. For every prime, mark its multiples in the given range [low..high]." }, { "code": null, "e": 7936, "s": 7770, "text": "In Simple Sieve, we needed O(n) space which may not be feasible for large n. Here we need O(√n) space and we process smaller ranges at a time (locality of reference)" }, { "code": null, "e": 7983, "s": 7936, "text": "Below is the implementation of the above idea." }, { "code": null, "e": 7987, "s": 7983, "text": "C++" }, { "code": null, "e": 7992, "s": 7987, "text": "Java" }, { "code": null, "e": 8000, "s": 7992, "text": "Python3" }, { "code": null, "e": 8003, "s": 8000, "text": "C#" }, { "code": null, "e": 8014, "s": 8003, "text": "Javascript" }, { "code": "// C++ program to print all primes smaller than// n using segmented sieve#include <bits/stdc++.h>using namespace std; // This functions finds all primes smaller than 'limit'// using simple sieve of eratosthenes. It also stores// found primes in vector prime[]void simpleSieve(int limit, vector<int> &prime){ // Create a boolean array \"mark[0..n-1]\" and initialize // all entries of it as true. A value in mark[p] will // finally be false if 'p' is Not a prime, else true. vector<bool> mark(limit + 1, true); for (int p=2; p*p<limit; p++) { // If p is not changed, then it is a prime if (mark[p] == true) { // Update all multiples of p for (int i=p*p; i<limit; i+=p) mark[i] = false; } } // Print all prime numbers and store them in prime for (int p=2; p<limit; p++) { if (mark[p] == true) { prime.push_back(p); cout << p << \" \"; } }} // Prints all prime numbers smaller than 'n'void segmentedSieve(int n){ // Compute all primes smaller than or equal // to square root of n using simple sieve int limit = floor(sqrt(n))+1; vector<int> prime; prime.reserve(limit); simpleSieve(limit, prime); // Divide the range [0..n-1] in different segments // We have chosen segment size as sqrt(n). int low = limit; int high = 2*limit; // While all segments of range [0..n-1] are not processed, // process one segment at a time while (low < n) { if (high >= n) high = n; // To mark primes in current range. A value in mark[i] // will finally be false if 'i-low' is Not a prime, // else true. bool mark[limit+1]; memset(mark, true, sizeof(mark)); // Use the found primes by simpleSieve() to find // primes in current range for (int i = 0; i < prime.size(); i++) { // Find the minimum number in [low..high] that is // a multiple of prime[i] (divisible by prime[i]) // For example, if low is 31 and prime[i] is 3, // we start with 33. int loLim = floor(low/prime[i]) * prime[i]; if (loLim < low) loLim += prime[i]; /* Mark multiples of prime[i] in [low..high]: We are marking j - low for j, i.e. each number in range [low, high] is mapped to [0, high-low] so if range is [50, 100] marking 50 corresponds to marking 0, marking 51 corresponds to 1 and so on. In this way we need to allocate space only for range */ for (int j=loLim; j<high; j+=prime[i]) mark[j-low] = false; } // Numbers which are not marked as false are prime for (int i = low; i<high; i++) if (mark[i - low] == true) cout << i << \" \"; // Update low and high for next segment low = low + limit; high = high + limit; }} // Driver program to test above functionint main(){ int n = 100000; cout << \"Primes smaller than \" << n << \":n\"; segmentedSieve(n); return 0;}", "e": 11196, "s": 8014, "text": null }, { "code": "// Java program to print all primes smaller than// n using segmented sieve import java.util.Vector;import static java.lang.Math.sqrt;import static java.lang.Math.floor; class Test{ // This method finds all primes smaller than 'limit' // using simple sieve of eratosthenes. It also stores // found primes in vector prime[] static void simpleSieve(int limit, Vector<Integer> prime) { // Create a boolean array \"mark[0..n-1]\" and initialize // all entries of it as true. A value in mark[p] will // finally be false if 'p' is Not a prime, else true. boolean mark[] = new boolean[limit+1]; for (int i = 0; i < mark.length; i++) mark[i] = true; for (int p=2; p*p<limit; p++) { // If p is not changed, then it is a prime if (mark[p] == true) { // Update all multiples of p for (int i=p*p; i<limit; i+=p) mark[i] = false; } } // Print all prime numbers and store them in prime for (int p=2; p<limit; p++) { if (mark[p] == true) { prime.add(p); System.out.print(p + \" \"); } } } // Prints all prime numbers smaller than 'n' static void segmentedSieve(int n) { // Compute all primes smaller than or equal // to square root of n using simple sieve int limit = (int) (floor(sqrt(n))+1); Vector<Integer> prime = new Vector<>(); simpleSieve(limit, prime); // Divide the range [0..n-1] in different segments // We have chosen segment size as sqrt(n). int low = limit; int high = 2*limit; // While all segments of range [0..n-1] are not processed, // process one segment at a time while (low < n) { if (high >= n) high = n; // To mark primes in current range. A value in mark[i] // will finally be false if 'i-low' is Not a prime, // else true. boolean mark[] = new boolean[limit+1]; for (int i = 0; i < mark.length; i++) mark[i] = true; // Use the found primes by simpleSieve() to find // primes in current range for (int i = 0; i < prime.size(); i++) { // Find the minimum number in [low..high] that is // a multiple of prime.get(i) (divisible by prime.get(i)) // For example, if low is 31 and prime.get(i) is 3, // we start with 33. int loLim = (int) (floor(low/prime.get(i)) * prime.get(i)); if (loLim < low) loLim += prime.get(i); /* Mark multiples of prime.get(i) in [low..high]: We are marking j - low for j, i.e. each number in range [low, high] is mapped to [0, high-low] so if range is [50, 100] marking 50 corresponds to marking 0, marking 51 corresponds to 1 and so on. In this way we need to allocate space only for range */ for (int j=loLim; j<high; j+=prime.get(i)) mark[j-low] = false; } // Numbers which are not marked as false are prime for (int i = low; i<high; i++) if (mark[i - low] == true) System.out.print(i + \" \"); // Update low and high for next segment low = low + limit; high = high + limit; } } // Driver method public static void main(String args[]) { int n = 100; System.out.println(\"Primes smaller than \" + n + \":\"); segmentedSieve(n); }}", "e": 15065, "s": 11196, "text": null }, { "code": "# Python3 program to print all primes# smaller than n, using segmented sieveimport mathprime = [] # This method finds all primes# smaller than 'limit' using# simple sieve of eratosthenes.# It also stores found primes in list primedef simpleSieve(limit): # Create a boolean list \"mark[0..n-1]\" and # initialize all entries of it as True. # A value in mark[p] will finally be False # if 'p' is Not a prime, else True. mark = [True for i in range(limit + 1)] p = 2 while (p * p <= limit): # If p is not changed, then it is a prime if (mark[p] == True): # Update all multiples of p for i in range(p * p, limit + 1, p): mark[i] = False p += 1 # Print all prime numbers # and store them in prime for p in range(2, limit): if mark[p]: prime.append(p) print(p,end = \" \") # Prints all prime numbers smaller than 'n'def segmentedSieve(n): # Compute all primes smaller than or equal # to square root of n using simple sieve limit = int(math.floor(math.sqrt(n)) + 1) simpleSieve(limit) # Divide the range [0..n-1] in different segments # We have chosen segment size as sqrt(n). low = limit high = limit * 2 # While all segments of range [0..n-1] are not processed, # process one segment at a time while low < n: if high >= n: high = n # To mark primes in current range. A value in mark[i] # will finally be False if 'i-low' is Not a prime, # else True. mark = [True for i in range(limit + 1)] # Use the found primes by simpleSieve() # to find primes in current range for i in range(len(prime)): # Find the minimum number in [low..high] # that is a multiple of prime[i] # (divisible by prime[i]) # For example, if low is 31 and prime[i] is 3, # we start with 33. loLim = int(math.floor(low / prime[i]) * prime[i]) if loLim < low: loLim += prime[i] # Mark multiples of prime[i] in [low..high]: # We are marking j - low for j, i.e. each number # in range [low, high] is mapped to [0, high-low] # so if range is [50, 100] marking 50 corresponds # to marking 0, marking 51 corresponds to 1 and # so on. In this way we need to allocate space # only for range for j in range(loLim, high, prime[i]): mark[j - low] = False # Numbers which are not marked as False are prime for i in range(low, high): if mark[i - low]: print(i, end = \" \") # Update low and high for next segment low = low + limit high = high + limit # Driver Coden = 100print(\"Primes smaller than\", n, \":\")segmentedSieve(100) # This code is contributed by bhavyadeep", "e": 18140, "s": 15065, "text": null }, { "code": "// C# program to print// all primes smaller than// n using segmented sieveusing System;using System.Collections; class GFG{ // This method finds all primes // smaller than 'limit' using simple // sieve of eratosthenes. It also stores // found primes in vector prime[] static void simpleSieve(int limit, ArrayList prime) { // Create a boolean array \"mark[0..n-1]\" // and initialize all entries of it as // true. A value in mark[p] will finally be // false if 'p' is Not a prime, else true. bool[] mark = new bool[limit + 1]; for (int i = 0; i < mark.Length; i++) mark[i] = true; for (int p = 2; p * p < limit; p++) { // If p is not changed, then it is a prime if (mark[p] == true) { // Update all multiples of p for (int i = p * p; i < limit; i += p) mark[i] = false; } } // Print all prime numbers and store them in prime for (int p = 2; p < limit; p++) { if (mark[p] == true) { prime.Add(p); Console.Write(p + \" \"); } } } // Prints all prime numbers smaller than 'n' static void segmentedSieve(int n) { // Compute all primes smaller than or equal // to square root of n using simple sieve int limit = (int) (Math.Floor(Math.Sqrt(n)) + 1); ArrayList prime = new ArrayList(); simpleSieve(limit, prime); // Divide the range [0..n-1] in // different segments We have chosen // segment size as sqrt(n). int low = limit; int high = 2*limit; // While all segments of range // [0..n-1] are not processed, // process one segment at a time while (low < n) { if (high >= n) high = n; // To mark primes in current range. // A value in mark[i] will finally // be false if 'i-low' is Not a prime, // else true. bool[] mark = new bool[limit + 1]; for (int i = 0; i < mark.Length; i++) mark[i] = true; // Use the found primes by // simpleSieve() to find // primes in current range for (int i = 0; i < prime.Count; i++) { // Find the minimum number in // [low..high] that is a multiple // of prime.get(i) (divisible by // prime.get(i)) For example, // if low is 31 and prime.get(i) // is 3, we start with 33. int loLim = ((int)Math.Floor((double)(low / (int)prime[i])) * (int)prime[i]); if (loLim < low) loLim += (int)prime[i]; /* Mark multiples of prime.get(i) in [low..high]: We are marking j - low for j, i.e. each number in range [low, high] is mapped to [0, high-low] so if range is [50, 100] marking 50 corresponds to marking 0, marking 51 corresponds to 1 and so on. In this way we need to allocate space only for range */ for (int j = loLim; j < high; j += (int)prime[i]) mark[j-low] = false; } // Numbers which are not marked as false are prime for (int i = low; i < high; i++) if (mark[i - low] == true) Console.Write(i + \" \"); // Update low and high for next segment low = low + limit; high = high + limit; } } // Driver code static void Main() { int n = 100; Console.WriteLine(\"Primes smaller than \" + n + \":\"); segmentedSieve(n); }} // This code is contributed by mits", "e": 22134, "s": 18140, "text": null }, { "code": "// JavaSCript program to print all primes smaller than// n using segmented sieve // This functions finds all primes smaller than 'limit'// using simple sieve of eratosthenes. It also stores// found primes in vector prime[] let res = \"\"; function simpleSieve(limit, prime){ // Create a boolean array \"mark[0..n-1]\" and initialize // all entries of it as true. A value in mark[p] will // finally be false if 'p' is Not a prime, else true. let mark = new Array(limit+1).fill(true); for (let p=2; p*p<limit; p++) { // If p is not changed, then it is a prime if (mark[p] === true) { // Update all multiples of p for (let i=p*p; i<limit; i+=p){ mark[i] = false; } } } // Print all prime numbers and store them in prime for (let p=2; p<limit; p++) { if (mark[p] === true) { prime.push(p); res = res + p + \" \"; } }} // Prints all prime numbers smaller than 'n'function segmentedSieve(n){ // Compute all primes smaller than or equal // to square root of n using simple sieve let limit = Math.floor(Math.sqrt(n))+1; let prime = new Array(limit); simpleSieve(limit, prime); // Divide the range [0..n-1] in different segments // We have chosen segment size as sqrt(n). let low = limit; let high = 2*limit; // While all segments of range [0..n-1] are not processed, // process one segment at a time while (low < n) { if (high >= n){ high = n; } // To mark primes in current range. A value in mark[i] // will finally be false if 'i-low' is Not a prime, // else true. let mark = new Array(limit+1).fill(true); // Use the found primes by simpleSieve() to find // primes in current range for (let i = 0; i < prime.length; i++) { // Find the minimum number in [low..high] that is // a multiple of prime[i] (divisible by prime[i]) // For example, if low is 31 and prime[i] is 3, // we start with 33. let loLim = Math.floor(low/prime[i]) * prime[i]; if (loLim < low){ loLim += prime[i]; } /* Mark multiples of prime[i] in [low..high]: We are marking j - low for j, i.e. each number in range [low, high] is mapped to [0, high-low] so if range is [50, 100] marking 50 corresponds to marking 0, marking 51 corresponds to 1 and so on. In this way we need to allocate space only for range */ for (let j=loLim; j<high; j+=prime[i]){ mark[j-low] = false; } } // Numbers which are not marked as false are prime for (let i = low; i<high; i++){ if (mark[i - low] == true){ res = res + i + \" \"; } } // Update low and high for next segment low = low + limit; high = high + limit; } console.log(res);} // Driver program to test above functionlet n = 100;console.log(\"Primes smaller than\", n);segmentedSieve(n); // The code is contributed by Gautam goel (gautamgoel962)", "e": 25423, "s": 22134, "text": null }, { "code": null, "e": 25432, "s": 25423, "text": "Output: " }, { "code": null, "e": 25530, "s": 25432, "text": "Primes smaller than 100:\n2 3 5 7 11 13 17 19 23 29 31 37 41\n43 47 53 59 61 67 71 73 79 83 89 97 " }, { "code": null, "e": 25559, "s": 25530, "text": "Time Complexity : O(sqrt(n))" }, { "code": null, "e": 25581, "s": 25559, "text": "Auxiliary Space: O(1)" }, { "code": null, "e": 26003, "s": 25581, "text": "Note that time complexity (or a number of operations) by Segmented Sieve is the same as Simple Sieve. It has advantages for large ‘n’ as it has better locality of reference thus allowing better caching by the CPU and also requires less memory space.This article is contributed by Utkarsh Trivedi. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above " }, { "code": null, "e": 26016, "s": 26003, "text": "Mithun Kumar" }, { "code": null, "e": 26035, "s": 26016, "text": "BhavyadeepPurswani" }, { "code": null, "e": 26045, "s": 26035, "text": "aerosayan" }, { "code": null, "e": 26059, "s": 26045, "text": "kumarayush151" }, { "code": null, "e": 26069, "s": 26059, "text": "rutvik_56" }, { "code": null, "e": 26079, "s": 26069, "text": "pratham76" }, { "code": null, "e": 26095, "s": 26079, "text": "dharanendralv23" }, { "code": null, "e": 26103, "s": 26095, "text": "scisaif" }, { "code": null, "e": 26116, "s": 26103, "text": "todaysgaurav" }, { "code": null, "e": 26125, "s": 26116, "text": "sweetyty" }, { "code": null, "e": 26135, "s": 26125, "text": "sanjoy_62" }, { "code": null, "e": 26147, "s": 26135, "text": "rishavnitro" }, { "code": null, "e": 26161, "s": 26147, "text": "gautamgoel962" }, { "code": null, "e": 26175, "s": 26161, "text": "sumitgumber28" }, { "code": null, "e": 26188, "s": 26175, "text": "Prime Number" }, { "code": null, "e": 26194, "s": 26188, "text": "sieve" }, { "code": null, "e": 26207, "s": 26194, "text": "Mathematical" }, { "code": null, "e": 26220, "s": 26207, "text": "Mathematical" }, { "code": null, "e": 26233, "s": 26220, "text": "Prime Number" }, { "code": null, "e": 26239, "s": 26233, "text": "sieve" }, { "code": null, "e": 26337, "s": 26239, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 26367, "s": 26337, "text": "Program for Fibonacci numbers" }, { "code": null, "e": 26410, "s": 26367, "text": "Set in C++ Standard Template Library (STL)" }, { "code": null, "e": 26470, "s": 26410, "text": "Write a program to print all permutations of a given string" }, { "code": null, "e": 26485, "s": 26470, "text": "C++ Data Types" }, { "code": null, "e": 26509, "s": 26485, "text": "Merge two sorted arrays" }, { "code": null, "e": 26528, "s": 26509, "text": "Coin Change | DP-7" }, { "code": null, "e": 26549, "s": 26528, "text": "Operators in C / C++" }, { "code": null, "e": 26563, "s": 26549, "text": "Prime Numbers" }, { "code": null, "e": 26605, "s": 26563, "text": "Program to find GCD or HCF of two numbers" } ]
Interfaces and Inheritance in C#
An interface is defined as a syntactical contract that all the classes inheriting the interface should follow. The interface defines the 'what' part of the syntactical contract and the deriving classes define the 'how' part of the syntactical contract. Let us see an example of Interfaces in C#. Live Demo using System.Collections.Generic; using System.Linq; using System.Text; using System; namespace InterfaceApplication { public interface ITransactions { // interface members void showTransaction(); double getAmount(); } public class Transaction : ITransactions { private string tCode; private string date; private double amount; public Transaction() { tCode = " "; date = " "; amount = 0.0; } public Transaction(string c, string d, double a) { tCode = c; date = d; amount = a; } public double getAmount() { return amount; } public void showTransaction() { Console.WriteLine("Transaction: {0}", tCode); Console.WriteLine("Date: {0}", date); Console.WriteLine("Amount: {0}", getAmount()); } } class Tester { static void Main(string[] args) { Transaction t1 = new Transaction("001", "8/10/2012", 78900.00); Transaction t2 = new Transaction("002", "9/10/2012", 451900.00); t1.showTransaction(); t2.showTransaction(); Console.ReadKey(); } } } Transaction: 001 Date: 8/10/2012 Amount: 78900 Transaction: 002 Date: 9/10/2012 Amount: 451900 Inheritance allows us to define a class in terms of another class, which makes it easier to create and maintain an application. This also provides an opportunity to reuse the code functionality and speeds up implementation time. The idea of inheritance implements the IS-A relationship. For example, mammal IS A animal, dog IS-A mammal hence dog IS-A animal as well, and so on. The following is an example showing how to work with Inheritance in C#. Live Demo using System; namespace InheritanceApplication { class Shape { public void setWidth(int w) { width = w; } public void setHeight(int h) { height = h; } protected int width; protected int height; } // Derived class class Rectangle: Shape { public int getArea() { return (width * height); } } class RectangleTester { static void Main(string[] args) { Rectangle Rect = new Rectangle(); Rect.setWidth(5); Rect.setHeight(7); // Print the area of the object. Console.WriteLine("Total area: {0}", Rect.getArea()); Console.ReadKey(); } } } Total area: 35
[ { "code": null, "e": 1440, "s": 1187, "text": "An interface is defined as a syntactical contract that all the classes inheriting the interface should follow. The interface defines the 'what' part of the syntactical contract and the deriving classes define the 'how' part of the syntactical contract." }, { "code": null, "e": 1483, "s": 1440, "text": "Let us see an example of Interfaces in C#." }, { "code": null, "e": 1494, "s": 1483, "text": " Live Demo" }, { "code": null, "e": 2690, "s": 1494, "text": "using System.Collections.Generic;\nusing System.Linq;\nusing System.Text;\nusing System;\n\nnamespace InterfaceApplication {\n\n public interface ITransactions {\n // interface members\n void showTransaction();\n double getAmount();\n }\n\n public class Transaction : ITransactions {\n private string tCode;\n private string date;\n private double amount;\n\n public Transaction() {\n tCode = \" \";\n date = \" \";\n amount = 0.0;\n }\n\n public Transaction(string c, string d, double a) {\n tCode = c;\n date = d;\n amount = a;\n }\n\n public double getAmount() {\n return amount;\n }\n\n public void showTransaction() {\n Console.WriteLine(\"Transaction: {0}\", tCode);\n Console.WriteLine(\"Date: {0}\", date);\n Console.WriteLine(\"Amount: {0}\", getAmount());\n }\n }\n\n class Tester {\n\n static void Main(string[] args) {\n Transaction t1 = new Transaction(\"001\", \"8/10/2012\", 78900.00);\n Transaction t2 = new Transaction(\"002\", \"9/10/2012\", 451900.00);\n\n t1.showTransaction();\n t2.showTransaction();\n Console.ReadKey();\n }\n }\n}" }, { "code": null, "e": 2785, "s": 2690, "text": "Transaction: 001\nDate: 8/10/2012\nAmount: 78900\nTransaction: 002\nDate: 9/10/2012\nAmount: 451900" }, { "code": null, "e": 3014, "s": 2785, "text": "Inheritance allows us to define a class in terms of another class, which makes it easier to create and maintain an application. This also provides an opportunity to reuse the code functionality and speeds up implementation time." }, { "code": null, "e": 3163, "s": 3014, "text": "The idea of inheritance implements the IS-A relationship. For example, mammal IS A animal, dog IS-A mammal hence dog IS-A animal as well, and so on." }, { "code": null, "e": 3235, "s": 3163, "text": "The following is an example showing how to work with Inheritance in C#." }, { "code": null, "e": 3246, "s": 3235, "text": " Live Demo" }, { "code": null, "e": 3949, "s": 3246, "text": "using System;\n\nnamespace InheritanceApplication {\n class Shape {\n public void setWidth(int w) {\n width = w;\n }\n\n public void setHeight(int h) {\n height = h;\n }\n\n protected int width;\n protected int height;\n }\n\n // Derived class\n class Rectangle: Shape {\n public int getArea() {\n return (width * height);\n }\n }\n\n class RectangleTester {\n static void Main(string[] args) {\n Rectangle Rect = new Rectangle();\n \n Rect.setWidth(5);\n Rect.setHeight(7);\n\n // Print the area of the object.\n Console.WriteLine(\"Total area: {0}\", Rect.getArea());\n Console.ReadKey();\n }\n }\n}" }, { "code": null, "e": 3964, "s": 3949, "text": "Total area: 35" } ]
How to subset rows that do not contain NA and blank in one of the columns in an R data frame?
It is possible that we get data sets where a column contains NA as well as blank, therefore, it becomes necessary to deal with these values. One of the ways to deal with these values is selecting the rows where we do not have them. This can be done by subsetting through single square brackets. Consider the below data frame − > set.seed(1) > x1<-sample(1:50,20) > x2<-rep(c(1,"",3,4),times=5) > x3<-rep(c(5,NA,10,"",20),each=4) > df<-data.frame(x1,x2,x3) > df x1 x2 x3 1 4 1 5 2 39 5 3 1 3 5 4 34 4 5 5 23 1 <NA> 6 43 <NA> 7 14 3 <NA> 8 18 4 <NA> 9 33 1 10 10 21 10 11 41 3 10 12 10 4 10 13 7 1 14 9 15 15 3 16 40 4 17 25 1 20 18 47 20 19 12 3 20 20 36 4 20 Subsetting rows where x3 is neither NA nor blank − > df[!(is.na(df$x3) | df$x3==""), ] x1 x2 x3 1 4 1 5 2 39 5 3 1 3 5 4 34 4 5 9 33 1 10 10 21 10 11 41 3 10 12 10 4 10 17 25 1 20 18 47 20 19 12 3 20 20 36 4 20 Subsetting rows where x2 is not blank − > df[!(df$x2==""), ] x1 x2 x3 1 4 1 5 3 1 3 5 4 34 4 5 5 23 1 <NA> 7 14 3 <NA> 8 18 4 <NA> 9 33 1 10 11 41 3 10 12 10 4 10 13 7 1 15 15 3 16 40 4 17 25 1 20 19 12 3 20 20 36 4 20
[ { "code": null, "e": 1482, "s": 1187, "text": "It is possible that we get data sets where a column contains NA as well as blank, therefore, it becomes necessary to deal with these values. One of the ways to deal with these values is selecting the rows where we do not have them. This can be done by subsetting through single square brackets." }, { "code": null, "e": 1514, "s": 1482, "text": "Consider the below data frame −" }, { "code": null, "e": 1848, "s": 1514, "text": "> set.seed(1)\n> x1<-sample(1:50,20)\n> x2<-rep(c(1,\"\",3,4),times=5)\n> x3<-rep(c(5,NA,10,\"\",20),each=4)\n> df<-data.frame(x1,x2,x3)\n> df\n x1 x2 x3\n1 4 1 5\n2 39 5\n3 1 3 5\n4 34 4 5\n5 23 1 <NA>\n6 43 <NA>\n7 14 3 <NA>\n8 18 4 <NA>\n9 33 1 10\n10 21 10\n11 41 3 10\n12 10 4 10\n13 7 1\n14 9\n15 15 3\n16 40 4\n17 25 1 20\n18 47 20\n19 12 3 20\n20 36 4 20" }, { "code": null, "e": 1899, "s": 1848, "text": "Subsetting rows where x3 is neither NA nor blank −" }, { "code": null, "e": 2059, "s": 1899, "text": "> df[!(is.na(df$x3) | df$x3==\"\"), ]\nx1 x2 x3\n1 4 1 5\n2 39 5\n3 1 3 5\n4 34 4 5\n9 33 1 10\n10 21 10\n11 41 3 10\n12 10 4 10\n17 25 1 20\n18 47 20\n19 12 3 20\n20 36 4 20" }, { "code": null, "e": 2099, "s": 2059, "text": "Subsetting rows where x2 is not blank −" }, { "code": null, "e": 2278, "s": 2099, "text": "> df[!(df$x2==\"\"), ]\nx1 x2 x3\n1 4 1 5\n3 1 3 5\n4 34 4 5\n5 23 1 <NA>\n7 14 3 <NA>\n8 18 4 <NA>\n9 33 1 10\n11 41 3 10\n12 10 4 10\n13 7 1\n15 15 3\n16 40 4\n17 25 1 20\n19 12 3 20\n20 36 4 20" } ]
Mongoose mongoose.model() Function
05 Feb, 2021 The mongoose.model() function of the mongoose module is used to create a collection of a particular database of MongoDB. The name of the collection created by the model function is always in plural format mean GFG to gfss and the created collection imposed a definite structure. Syntax: mongoose.model(<Collectionname>, <CollectionSchema>) Parameters: This function accepts the following two parameters: Collection name: It is the name of the collection. Collection Schema: It is the schema of the collection. Return type: This function returns the Mongoose object. Installing Module: Install the mongoose module using the following command: npm install mongoose Project Structure: Our project structure will look like this: Running the server on Local IP: Data is the directory where MongoDB server is present. mongod --dbpath=data --bind_ip 127.0.0.1 Filename- index.js: Javascript // Importing mongoose moduleconst mongoose = require("mongoose") // Database Addressconst url = "mongodb://localhost:27017/GFG" // Connecting to databasemongoose.connect(url).then((ans) => { console.log("ConnectedSuccessful")}).catch((err) => { console.log("Error in the Connection")}) // Calling Schema classconst Schema = mongoose.Schema; // Creating Structure of the collectionconst collection_structure = new Schema({ name: { type: String, require: true } , marks: { type: Number, default: 0 }}) // Creating collectionconst collections = mongoose.model("GFG", collection_structure) // Inserting one documentcollections.create({ name: "aayush", marks: 10}).then((ans) => { console.log("Document inserted")}).catch((err) => { console.log(err.Message);}) Run index.js file using below command: node index.js Output: MongoDB Database: Our database after executing the above command will look like this: Mongoose Technical Scripter 2020 MongoDB 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": "\n05 Feb, 2021" }, { "code": null, "e": 331, "s": 52, "text": "The mongoose.model() function of the mongoose module is used to create a collection of a particular database of MongoDB. The name of the collection created by the model function is always in plural format mean GFG to gfss and the created collection imposed a definite structure." }, { "code": null, "e": 339, "s": 331, "text": "Syntax:" }, { "code": null, "e": 392, "s": 339, "text": "mongoose.model(<Collectionname>, <CollectionSchema>)" }, { "code": null, "e": 456, "s": 392, "text": "Parameters: This function accepts the following two parameters:" }, { "code": null, "e": 507, "s": 456, "text": "Collection name: It is the name of the collection." }, { "code": null, "e": 562, "s": 507, "text": "Collection Schema: It is the schema of the collection." }, { "code": null, "e": 618, "s": 562, "text": "Return type: This function returns the Mongoose object." }, { "code": null, "e": 694, "s": 618, "text": "Installing Module: Install the mongoose module using the following command:" }, { "code": null, "e": 715, "s": 694, "text": "npm install mongoose" }, { "code": null, "e": 777, "s": 715, "text": "Project Structure: Our project structure will look like this:" }, { "code": null, "e": 864, "s": 777, "text": "Running the server on Local IP: Data is the directory where MongoDB server is present." }, { "code": null, "e": 905, "s": 864, "text": "mongod --dbpath=data --bind_ip 127.0.0.1" }, { "code": null, "e": 925, "s": 905, "text": "Filename- index.js:" }, { "code": null, "e": 936, "s": 925, "text": "Javascript" }, { "code": "// Importing mongoose moduleconst mongoose = require(\"mongoose\") // Database Addressconst url = \"mongodb://localhost:27017/GFG\" // Connecting to databasemongoose.connect(url).then((ans) => { console.log(\"ConnectedSuccessful\")}).catch((err) => { console.log(\"Error in the Connection\")}) // Calling Schema classconst Schema = mongoose.Schema; // Creating Structure of the collectionconst collection_structure = new Schema({ name: { type: String, require: true } , marks: { type: Number, default: 0 }}) // Creating collectionconst collections = mongoose.model(\"GFG\", collection_structure) // Inserting one documentcollections.create({ name: \"aayush\", marks: 10}).then((ans) => { console.log(\"Document inserted\")}).catch((err) => { console.log(err.Message);})", "e": 1721, "s": 936, "text": null }, { "code": null, "e": 1760, "s": 1721, "text": "Run index.js file using below command:" }, { "code": null, "e": 1774, "s": 1760, "text": "node index.js" }, { "code": null, "e": 1782, "s": 1774, "text": "Output:" }, { "code": null, "e": 1868, "s": 1782, "text": "MongoDB Database: Our database after executing the above command will look like this:" }, { "code": null, "e": 1877, "s": 1868, "text": "Mongoose" }, { "code": null, "e": 1901, "s": 1877, "text": "Technical Scripter 2020" }, { "code": null, "e": 1909, "s": 1901, "text": "MongoDB" }, { "code": null, "e": 1928, "s": 1909, "text": "Technical Scripter" } ]
Difference Between indexOf and findIndex function of array
18 Jul, 2019 The task is differentiate between the indexOf() and findIndex() function of JavaScript. we’re going to discuss both approaches. indexOf() function:This function is used to find the index of the first occurrence of the element provided for search as the argument to the function.Syntax:arr.indexOf(element[, index]) Arguments:element:This parameter specifies the element to be searched.index:This parameter specifies the from which index search to be start. Syntax: arr.indexOf(element[, index]) Arguments: element:This parameter specifies the element to be searched. index:This parameter specifies the from which index search to be start. findIndex() function:This function returns index of the first element of the given array which satisfies the testing function.Syntax:array.findIndex(fun(curValue, index, arr), thisValue) Arguments:fun: This parameter specifies a function to be run for every element of the array.curValue: This parameter specifies the value of the current element.index: This parameter specifies the array index of the current element.arr: This parameter specifies the array object with current element belongs to.thisValue: This parameter specifies a value to be passed to the function to be used as its “this” value.If this is empty, the value “undefined” will be used. Syntax: array.findIndex(fun(curValue, index, arr), thisValue) Arguments: fun: This parameter specifies a function to be run for every element of the array. curValue: This parameter specifies the value of the current element. index: This parameter specifies the array index of the current element. arr: This parameter specifies the array object with current element belongs to. thisValue: This parameter specifies a value to be passed to the function to be used as its “this” value.If this is empty, the value “undefined” will be used. Example 1: In this example, indexOf() function is used. <!DOCTYPE HTML><html> <head> <title> JavaScript | Difference Between indexOf and findIndex function of array. </title></head> <body style="text-align:center;" id="body"> <h1 style="color:green;"> GeeksForGeeks </h1> <p id="GFG_UP" style="font-size: 19px; font-weight: bold;"> </p> <button onclick="GFG_Fun()"> click here </button> <p id="GFG_DOWN" style="color: green; font-size: 24px; font-weight: bold;"> </p> <script> var el_up = document.getElementById("GFG_UP"); var el_down = document.getElementById("GFG_DOWN"); var array = ["Geeks", "GFG", "geeks", "Geeks"]; el_up.innerHTML = "ARRAY - [" + array + "]"; function GFG_Fun() { el_down.innerHTML = "First index of 'Geeks' is " + array.indexOf('Geeks'); } </script></body> </html> Output: Before clicking on the button: After clicking on the button: Example 2: In this example, findIndex() function is used. <!DOCTYPE HTML><html> <head> <title> JavaScript | Difference Between indexOf and findIndex function of array. </title></head> <body style="text-align:center;" id="body"> <h1 style="color:green;"> GeeksForGeeks </h1> <p id="GFG_UP" style="font-size: 19px; font-weight: bold;"> </p> <button onclick="GFG_Fun()"> click here </button> <p id="GFG_DOWN" style="color: green; font-size: 24px; font-weight: bold;"> </p> <script> var el_up = document.getElementById("GFG_UP"); var el_down = document.getElementById("GFG_DOWN"); var array = [1, 3, 4, 5, 6, 7, 8, 9]; el_up.innerHTML = "ARRAY - [" + array + "]"; function getEven(n) { if (n % 2 == 0) { return 1; } return 0; } function GFG_Fun() { el_down.innerHTML = "First even number in array is at index " + array.findIndex(getEven); } </script></body> </html> Output: Before clicking on the button: After clicking on the button: JavaScript-Misc JavaScript Web Technologies Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n18 Jul, 2019" }, { "code": null, "e": 156, "s": 28, "text": "The task is differentiate between the indexOf() and findIndex() function of JavaScript. we’re going to discuss both approaches." }, { "code": null, "e": 485, "s": 156, "text": "indexOf() function:This function is used to find the index of the first occurrence of the element provided for search as the argument to the function.Syntax:arr.indexOf(element[, index])\nArguments:element:This parameter specifies the element to be searched.index:This parameter specifies the from which index search to be start." }, { "code": null, "e": 493, "s": 485, "text": "Syntax:" }, { "code": null, "e": 524, "s": 493, "text": "arr.indexOf(element[, index])\n" }, { "code": null, "e": 535, "s": 524, "text": "Arguments:" }, { "code": null, "e": 596, "s": 535, "text": "element:This parameter specifies the element to be searched." }, { "code": null, "e": 668, "s": 596, "text": "index:This parameter specifies the from which index search to be start." }, { "code": null, "e": 1323, "s": 668, "text": "findIndex() function:This function returns index of the first element of the given array which satisfies the testing function.Syntax:array.findIndex(fun(curValue, index, arr), thisValue)\nArguments:fun: This parameter specifies a function to be run for every element of the array.curValue: This parameter specifies the value of the current element.index: This parameter specifies the array index of the current element.arr: This parameter specifies the array object with current element belongs to.thisValue: This parameter specifies a value to be passed to the function to be used as its “this” value.If this is empty, the value “undefined” will be used." }, { "code": null, "e": 1331, "s": 1323, "text": "Syntax:" }, { "code": null, "e": 1386, "s": 1331, "text": "array.findIndex(fun(curValue, index, arr), thisValue)\n" }, { "code": null, "e": 1397, "s": 1386, "text": "Arguments:" }, { "code": null, "e": 1480, "s": 1397, "text": "fun: This parameter specifies a function to be run for every element of the array." }, { "code": null, "e": 1549, "s": 1480, "text": "curValue: This parameter specifies the value of the current element." }, { "code": null, "e": 1621, "s": 1549, "text": "index: This parameter specifies the array index of the current element." }, { "code": null, "e": 1701, "s": 1621, "text": "arr: This parameter specifies the array object with current element belongs to." }, { "code": null, "e": 1859, "s": 1701, "text": "thisValue: This parameter specifies a value to be passed to the function to be used as its “this” value.If this is empty, the value “undefined” will be used." }, { "code": null, "e": 1915, "s": 1859, "text": "Example 1: In this example, indexOf() function is used." }, { "code": "<!DOCTYPE HTML><html> <head> <title> JavaScript | Difference Between indexOf and findIndex function of array. </title></head> <body style=\"text-align:center;\" id=\"body\"> <h1 style=\"color:green;\"> GeeksForGeeks </h1> <p id=\"GFG_UP\" style=\"font-size: 19px; font-weight: bold;\"> </p> <button onclick=\"GFG_Fun()\"> click here </button> <p id=\"GFG_DOWN\" style=\"color: green; font-size: 24px; font-weight: bold;\"> </p> <script> var el_up = document.getElementById(\"GFG_UP\"); var el_down = document.getElementById(\"GFG_DOWN\"); var array = [\"Geeks\", \"GFG\", \"geeks\", \"Geeks\"]; el_up.innerHTML = \"ARRAY - [\" + array + \"]\"; function GFG_Fun() { el_down.innerHTML = \"First index of 'Geeks' is \" + array.indexOf('Geeks'); } </script></body> </html>", "e": 2879, "s": 1915, "text": null }, { "code": null, "e": 2887, "s": 2879, "text": "Output:" }, { "code": null, "e": 2918, "s": 2887, "text": "Before clicking on the button:" }, { "code": null, "e": 2948, "s": 2918, "text": "After clicking on the button:" }, { "code": null, "e": 3006, "s": 2948, "text": "Example 2: In this example, findIndex() function is used." }, { "code": "<!DOCTYPE HTML><html> <head> <title> JavaScript | Difference Between indexOf and findIndex function of array. </title></head> <body style=\"text-align:center;\" id=\"body\"> <h1 style=\"color:green;\"> GeeksForGeeks </h1> <p id=\"GFG_UP\" style=\"font-size: 19px; font-weight: bold;\"> </p> <button onclick=\"GFG_Fun()\"> click here </button> <p id=\"GFG_DOWN\" style=\"color: green; font-size: 24px; font-weight: bold;\"> </p> <script> var el_up = document.getElementById(\"GFG_UP\"); var el_down = document.getElementById(\"GFG_DOWN\"); var array = [1, 3, 4, 5, 6, 7, 8, 9]; el_up.innerHTML = \"ARRAY - [\" + array + \"]\"; function getEven(n) { if (n % 2 == 0) { return 1; } return 0; } function GFG_Fun() { el_down.innerHTML = \"First even number in array is at index \" + array.findIndex(getEven); } </script></body> </html>", "e": 4116, "s": 3006, "text": null }, { "code": null, "e": 4124, "s": 4116, "text": "Output:" }, { "code": null, "e": 4155, "s": 4124, "text": "Before clicking on the button:" }, { "code": null, "e": 4185, "s": 4155, "text": "After clicking on the button:" }, { "code": null, "e": 4201, "s": 4185, "text": "JavaScript-Misc" }, { "code": null, "e": 4212, "s": 4201, "text": "JavaScript" }, { "code": null, "e": 4229, "s": 4212, "text": "Web Technologies" } ]
Scala Stack reverse() method with example
03 Nov, 2019 In Scala Stack class, the reverse() method is utilized to return a stack with the reverse order. Method Definition: def reverse: Stack[A] Return Type: It returns a stack with the reverse order. Example #1: // Scala program of reverse() // method // Import Stack import scala.collection.mutable._ // Creating object object GfG { // Main method def main(args:Array[String]) { // Creating stack val s1 = Stack(1, 2, 3, 4, 5, 6) // Print the stack println(s1) // Applying reverse method val result = s1.reverse // Display output print("Reversed stack: " + result) } } Stack(1, 2, 3, 4, 5, 6) Reversed stack: Stack(6, 5, 4, 3, 2, 1) Example #2: // Scala program of reverse() // method // Import Stack import scala.collection.mutable._ // Creating object object GfG { // Main method def main(args:Array[String]) { // Creating stack val s1 = Stack(5, 2, 13, 7, 1, 3) // Print the stack println(s1) // Applying reverse method val result = s1.reverse // Display output print("Reversed stack: " + result) } } Stack(5, 2, 13, 7, 1, 3) Reversed stack: Stack(3, 1, 7, 13, 2, 5) Scala scala-collection Scala-Method Scala Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n03 Nov, 2019" }, { "code": null, "e": 125, "s": 28, "text": "In Scala Stack class, the reverse() method is utilized to return a stack with the reverse order." }, { "code": null, "e": 166, "s": 125, "text": "Method Definition: def reverse: Stack[A]" }, { "code": null, "e": 222, "s": 166, "text": "Return Type: It returns a stack with the reverse order." }, { "code": null, "e": 234, "s": 222, "text": "Example #1:" }, { "code": "// Scala program of reverse() // method // Import Stack import scala.collection.mutable._ // Creating object object GfG { // Main method def main(args:Array[String]) { // Creating stack val s1 = Stack(1, 2, 3, 4, 5, 6) // Print the stack println(s1) // Applying reverse method val result = s1.reverse // Display output print(\"Reversed stack: \" + result) } } ", "e": 725, "s": 234, "text": null }, { "code": null, "e": 790, "s": 725, "text": "Stack(1, 2, 3, 4, 5, 6)\nReversed stack: Stack(6, 5, 4, 3, 2, 1)\n" }, { "code": null, "e": 802, "s": 790, "text": "Example #2:" }, { "code": "// Scala program of reverse() // method // Import Stack import scala.collection.mutable._ // Creating object object GfG { // Main method def main(args:Array[String]) { // Creating stack val s1 = Stack(5, 2, 13, 7, 1, 3) // Print the stack println(s1) // Applying reverse method val result = s1.reverse // Display output print(\"Reversed stack: \" + result) } } ", "e": 1294, "s": 802, "text": null }, { "code": null, "e": 1361, "s": 1294, "text": "Stack(5, 2, 13, 7, 1, 3)\nReversed stack: Stack(3, 1, 7, 13, 2, 5)\n" }, { "code": null, "e": 1367, "s": 1361, "text": "Scala" }, { "code": null, "e": 1384, "s": 1367, "text": "scala-collection" }, { "code": null, "e": 1397, "s": 1384, "text": "Scala-Method" }, { "code": null, "e": 1403, "s": 1397, "text": "Scala" } ]
PostgreSQL – Insert Multiple Values in Various Rows
01 Feb, 2021 PostgreSQL is a type of relational database (RDBMS) similar to MySQL. Relational Database stores data in the form of a table in which each row is a record and each column is one attribute. In this article, we will look into the process of inserting multiple rows in a PostgreSQL database. In general, we use the INSERT statement to insert values in a database. Just an improvised version of the same statement can be used to insert multiple values in various rows of a database as shown in the syntax below: Syntax : ##When specifying Column Names Insert into tableName (col1, col2) values (value,value),(value,value),(value,value); ## when not specifying Column Names Insert into tableName values (value,value),(value,value),(value,value); Approach : Our database name is geeksforgeeks and the table name is gfg at the beginning there is no data inside the table. For selecting the database we will use query \c databaseName. For checking the data inside the table we will use query select *from tableName. Now for inserting values, we will use the table name and the column names and the records to be inserted will be separated by comma(“‘”). The query will be Insert into tableName (col1, col2) values (value,value),(value,value),(value,value). If you want to insert without the column names then the query will be a different one than the above query. Insert into tableName values (value,value),(value,value),(value,value) . But one thing should be remembered here that in this case, the order of the values being inserted should be the same as that of in the database and all the mandatory columns must be inserted. Now again we will check for records inside the table using select*from tableName. Example 1 : In this example, we first selected the database using the \c geeksforgeeks command, and then we looked into the database table records then we inserted the multiples record inside the table then again look inside the database tables. The steps followed are to select the database and then look into the table records then insert multiple values and then again look into the table records. Example 2 : Here in this example, we will insert the rows without using the column names but one thing to note about this approach is if you are not giving the column names the order of values being inserted will be the same as that of in the table and all the mandatory columns must be filled in the table otherwise there will be an exception. After inserting the data we will again look into the database table. Picked postgreSQL-managing-table PostgreSQL Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. PostgreSQL - Psql commands PostgreSQL - Change Column Type PostgreSQL - For Loops PostgreSQL - LIMIT with OFFSET clause PostgreSQL - Function Returning A Table PostgreSQL - ARRAY_AGG() Function PostgreSQL - Copy Table PostgreSQL - DROP INDEX How to use PostgreSQL Database in Django? PostgreSQL - Identity Column
[ { "code": null, "e": 28, "s": 0, "text": "\n01 Feb, 2021" }, { "code": null, "e": 536, "s": 28, "text": "PostgreSQL is a type of relational database (RDBMS) similar to MySQL. Relational Database stores data in the form of a table in which each row is a record and each column is one attribute. In this article, we will look into the process of inserting multiple rows in a PostgreSQL database. In general, we use the INSERT statement to insert values in a database. Just an improvised version of the same statement can be used to insert multiple values in various rows of a database as shown in the syntax below:" }, { "code": null, "e": 545, "s": 536, "text": "Syntax :" }, { "code": null, "e": 771, "s": 545, "text": "##When specifying Column Names\nInsert into tableName (col1, col2) values (value,value),(value,value),(value,value);\n\n## when not specifying Column Names\nInsert into tableName values (value,value),(value,value),(value,value);" }, { "code": null, "e": 782, "s": 771, "text": "Approach :" }, { "code": null, "e": 958, "s": 782, "text": "Our database name is geeksforgeeks and the table name is gfg at the beginning there is no data inside the table. For selecting the database we will use query \\c databaseName." }, { "code": null, "e": 1039, "s": 958, "text": "For checking the data inside the table we will use query select *from tableName." }, { "code": null, "e": 1177, "s": 1039, "text": "Now for inserting values, we will use the table name and the column names and the records to be inserted will be separated by comma(“‘”)." }, { "code": null, "e": 1280, "s": 1177, "text": "The query will be Insert into tableName (col1, col2) values (value,value),(value,value),(value,value)." }, { "code": null, "e": 1388, "s": 1280, "text": "If you want to insert without the column names then the query will be a different one than the above query." }, { "code": null, "e": 1654, "s": 1388, "text": "Insert into tableName values (value,value),(value,value),(value,value) . But one thing should be remembered here that in this case, the order of the values being inserted should be the same as that of in the database and all the mandatory columns must be inserted." }, { "code": null, "e": 1736, "s": 1654, "text": "Now again we will check for records inside the table using select*from tableName." }, { "code": null, "e": 1748, "s": 1736, "text": "Example 1 :" }, { "code": null, "e": 2137, "s": 1748, "text": "In this example, we first selected the database using the \\c geeksforgeeks command, and then we looked into the database table records then we inserted the multiples record inside the table then again look inside the database tables. The steps followed are to select the database and then look into the table records then insert multiple values and then again look into the table records." }, { "code": null, "e": 2149, "s": 2137, "text": "Example 2 :" }, { "code": null, "e": 2551, "s": 2149, "text": "Here in this example, we will insert the rows without using the column names but one thing to note about this approach is if you are not giving the column names the order of values being inserted will be the same as that of in the table and all the mandatory columns must be filled in the table otherwise there will be an exception. After inserting the data we will again look into the database table." }, { "code": null, "e": 2558, "s": 2551, "text": "Picked" }, { "code": null, "e": 2584, "s": 2558, "text": "postgreSQL-managing-table" }, { "code": null, "e": 2595, "s": 2584, "text": "PostgreSQL" }, { "code": null, "e": 2693, "s": 2595, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 2720, "s": 2693, "text": "PostgreSQL - Psql commands" }, { "code": null, "e": 2752, "s": 2720, "text": "PostgreSQL - Change Column Type" }, { "code": null, "e": 2775, "s": 2752, "text": "PostgreSQL - For Loops" }, { "code": null, "e": 2813, "s": 2775, "text": "PostgreSQL - LIMIT with OFFSET clause" }, { "code": null, "e": 2853, "s": 2813, "text": "PostgreSQL - Function Returning A Table" }, { "code": null, "e": 2887, "s": 2853, "text": "PostgreSQL - ARRAY_AGG() Function" }, { "code": null, "e": 2911, "s": 2887, "text": "PostgreSQL - Copy Table" }, { "code": null, "e": 2935, "s": 2911, "text": "PostgreSQL - DROP INDEX" }, { "code": null, "e": 2977, "s": 2935, "text": "How to use PostgreSQL Database in Django?" } ]
Use of nonlocal vs use of global keyword in Python
15 Jun, 2021 Prerequisites: Global and Local Variables in PythonBefore moving to nonlocal and global in Python. Let us consider some basic scenarios in nested functions. Python3 def fun(): var1 = 10 def gun(): print(var1) var2 = var1 + 1 print(var2) gun()fun() 10 11 The variable var1 has scope across entire fun(). It will be accessible from nested function of fun() Python3 def fun(): var1 = 10 def gun(): # gun() initializes a new variable var1. var1 = 20 print(var1, id(var1)) print(var1, id(var1)) gun()fun() 10 10853920 20 10854240 In this case gun() initialized new variable var1 in the scope of gun. var1 with value 10 and var1 with value 20 are two different and unique variables. var1 holding value 20 will be by default accessed in gun(). Considering the previous example, we know that guns will initialize a new variable var1 in its own scope. But when it is going to do so, it cannot find the value of var1 yet, to perform the arithmetic operation as no value has been assigned to var1 previously in gun(). Python3 def fun(): var1 = 10 def gun(): # tell python explicitly that it # has to access var1 initialized # in fun on line 2 # using the keyword nonlocal nonlocal var1 var1 = var1 + 10 print(var1) gun()fun() 20 In this example, before initializing var1 in gun(). We have explicitly told Python that, do not initialize a new variable, instead access var1 present already on line 2. using the keyword nonlocal So when the interpreter performs addition, it access the value 10(already present) and error is avoided. Let us move on to global keyword now. Consider the examples given below Python3 var1 = 10def fun(): # global variable var1 will# be read or accessed in fun() print('var1 is', var1) fun() var1 is 10 Global variable var1 will be simply read or accessed inside function fun() Python3 var1 = 10def fun(): # new local variable var1 # will be initialized in fun() var1 = 20 print('var1 is', var1) print('var1 is at', id(var1)) fun()print('var1 is', var1)print('var1 is at', id(var1)) var1 is 20 var1 is at 10854240 var1 is 10 var1 is at 10853920 A new variable var1 will be initialized in fun(). Global variable var1 will be different from local variable var1 of fun(). By default in fun(), the local variables will be accessed. Considering previous example, we know that fun() will initialize a new variable var1 in its own scope. But when it is going to do so, it cannot find the value of var1 yet, to perform arithmetic operation as no value has been assigned to var1 previously in fun() Python3 var1 = 10def fun(): # tell python explicitly do not # initialise a new variable # instead access var1 which # has global scope global var1 var1 = var1 + 20 print('var1 is', var1) fun() var1 is 30 In this example, before initializing var1 in fun(). We have explicitly told python that, do not initialize a new variable, instead access var1 present already on line 1. using the keyword global So when interpreter performs addition, it access the value 10(already present), and error is avoided. anikaseth98 python-basics Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 54, "s": 26, "text": "\n15 Jun, 2021" }, { "code": null, "e": 211, "s": 54, "text": "Prerequisites: Global and Local Variables in PythonBefore moving to nonlocal and global in Python. Let us consider some basic scenarios in nested functions." }, { "code": null, "e": 219, "s": 211, "text": "Python3" }, { "code": "def fun(): var1 = 10 def gun(): print(var1) var2 = var1 + 1 print(var2) gun()fun()", "e": 334, "s": 219, "text": null }, { "code": null, "e": 340, "s": 334, "text": "10\n11" }, { "code": null, "e": 443, "s": 342, "text": "The variable var1 has scope across entire fun(). It will be accessible from nested function of fun()" }, { "code": null, "e": 451, "s": 443, "text": "Python3" }, { "code": "def fun(): var1 = 10 def gun(): # gun() initializes a new variable var1. var1 = 20 print(var1, id(var1)) print(var1, id(var1)) gun()fun()", "e": 624, "s": 451, "text": null }, { "code": null, "e": 648, "s": 624, "text": "10 10853920\n20 10854240" }, { "code": null, "e": 862, "s": 650, "text": "In this case gun() initialized new variable var1 in the scope of gun. var1 with value 10 and var1 with value 20 are two different and unique variables. var1 holding value 20 will be by default accessed in gun()." }, { "code": null, "e": 1133, "s": 862, "text": "Considering the previous example, we know that guns will initialize a new variable var1 in its own scope. But when it is going to do so, it cannot find the value of var1 yet, to perform the arithmetic operation as no value has been assigned to var1 previously in gun(). " }, { "code": null, "e": 1141, "s": 1133, "text": "Python3" }, { "code": "def fun(): var1 = 10 def gun(): # tell python explicitly that it # has to access var1 initialized # in fun on line 2 # using the keyword nonlocal nonlocal var1 var1 = var1 + 10 print(var1) gun()fun()", "e": 1401, "s": 1141, "text": null }, { "code": null, "e": 1404, "s": 1401, "text": "20" }, { "code": null, "e": 1708, "s": 1406, "text": "In this example, before initializing var1 in gun(). We have explicitly told Python that, do not initialize a new variable, instead access var1 present already on line 2. using the keyword nonlocal So when the interpreter performs addition, it access the value 10(already present) and error is avoided." }, { "code": null, "e": 1781, "s": 1708, "text": "Let us move on to global keyword now. Consider the examples given below " }, { "code": null, "e": 1789, "s": 1781, "text": "Python3" }, { "code": "var1 = 10def fun(): # global variable var1 will# be read or accessed in fun() print('var1 is', var1) fun()", "e": 1902, "s": 1789, "text": null }, { "code": null, "e": 1913, "s": 1902, "text": "var1 is 10" }, { "code": null, "e": 1990, "s": 1915, "text": "Global variable var1 will be simply read or accessed inside function fun()" }, { "code": null, "e": 1998, "s": 1990, "text": "Python3" }, { "code": "var1 = 10def fun(): # new local variable var1 # will be initialized in fun() var1 = 20 print('var1 is', var1) print('var1 is at', id(var1)) fun()print('var1 is', var1)print('var1 is at', id(var1))", "e": 2210, "s": 1998, "text": null }, { "code": null, "e": 2272, "s": 2210, "text": "var1 is 20\nvar1 is at 10854240\nvar1 is 10\nvar1 is at 10853920" }, { "code": null, "e": 2457, "s": 2274, "text": "A new variable var1 will be initialized in fun(). Global variable var1 will be different from local variable var1 of fun(). By default in fun(), the local variables will be accessed." }, { "code": null, "e": 2719, "s": 2457, "text": "Considering previous example, we know that fun() will initialize a new variable var1 in its own scope. But when it is going to do so, it cannot find the value of var1 yet, to perform arithmetic operation as no value has been assigned to var1 previously in fun()" }, { "code": null, "e": 2727, "s": 2719, "text": "Python3" }, { "code": "var1 = 10def fun(): # tell python explicitly do not # initialise a new variable # instead access var1 which # has global scope global var1 var1 = var1 + 20 print('var1 is', var1) fun()", "e": 2933, "s": 2727, "text": null }, { "code": null, "e": 2944, "s": 2933, "text": "var1 is 30" }, { "code": null, "e": 3244, "s": 2946, "text": "In this example, before initializing var1 in fun(). We have explicitly told python that, do not initialize a new variable, instead access var1 present already on line 1. using the keyword global So when interpreter performs addition, it access the value 10(already present), and error is avoided. " }, { "code": null, "e": 3256, "s": 3244, "text": "anikaseth98" }, { "code": null, "e": 3270, "s": 3256, "text": "python-basics" }, { "code": null, "e": 3277, "s": 3270, "text": "Python" } ]
Dart – Basic Syntax
27 Jun, 2021 Dart is a static programming language developed by Google. According to the GitHub popularity index, it became the most popular programming language as it actually supports the flutter toolkit. Flutter is a framework that uses dart’s native compilation ability to generate fast cross-platform apps. Dart supports two types of compilation that are, Just in time and Ahead of time. Its syntax has basically a blend of CPP, Python, Java, and JavaScript. In this blog, We will look at the basic syntax in Dart and how to represent the language that the computer understands. We will see the basic structure of Dart programming. The syntax is a basic dart program that consists of various elements such as a keyword, an identifier, a constant, a string literal, data types, and symbols. Eg: to represent numbers words and even decimals we can call the type of data. Each line is dart must end with the semicolon. Dart void main() { // declare and initialized a variable int A = 2; int B = 3; // displaying the output print( A + B );} To represent this we can tell the type of the data, in the above example as an integer type. Similarly, To represent a word or string we can call the data type a string. All these are called Variables. Now the integers, strings, and even decimal values are temporarily held by a word or character like ‘A’ and ‘B’. All these are called variables because the data inside can keep changing. The word to the left of the ‘=’ is the variable while the one in the right is the actual value. A comment is a code snippet that is not readable by the compiler. Comments help to write a code efficiently and make it easier to understand the code. Comments in dart can be obtained using one of the following: ' // ' is used to comment on a single line. '/*.....*/ is used to comment on multiple lines. Dart void main() { // Displaying the output print('Hello, Geeks!'); /* print('Dart is a programming language'); print('Dart is a programming language'); */ print('Hello, Geeks!');} Keywords are the words that are used a dart to represent the basics syntax that the compiler will understand. The basic keywords that are used in dart programs are listed below: Apart from this, there are other keywords that can be used as the syntax, but they are rarely used. Identifiers are the name given to variables that can be read by the compiler. There are certain rules to write the identifiers: No special symbol can be used except _ and $. It can not be the reserved keywords. There should not be any space between the variable name. They are case sensitives. Variables are the name given to a memory location declaring by writing variable-type _ name and then initialized and declared by ” variable-type name = value; “. The dart language supports the following built-in types : String A Dart string is a collection of characters and letters. You can use either single or double quotes to create a string. For multi-line string, we can use ‘....’ or “.....”. We can give the value of a character inside a string by doing $ {expression}. Dart var name = 'John'; Here a variable is called a name and the string is assigned a value “John”. Note: If a variable is not initialized then the default value is null Numbers Both int and double are can be used for the representation of numbers. These data types are used to represent any number and even a decimal. The num type operates with basic algebraic operators. Dart void main() { // declare and initialized a variable int A = 20; double B = 30.0; // displaying the output print( A + B );} Booleans In order to use the Boolean data types, dart uses the keyword named bool. These data types have two values that are True and False. Dart void main() { bool isIttrue1 = true; print('$isIttrue1');} Collection [List, Set, Maps] Collections in Dart is basically a collection of similar and different data types. These are used as data structures in dart. Each element can be accessed sequentially. Dart void main() { var list = [10, 20, 30]; var names = ['Jack','Jill', 10, 1];} Operators representation is really simple. The basic addition of numbers is possible by inserting the + operator. Similarly, we can insert any operators including BIT operation simply calling the operator on two values and assign it to another value. Let see some basics operators used in dart programming. Algebraic Operators These operators can be used between two values and assign to the third one. The operators are listed below: Addition -> “+” OperatorSubtraction -> “-” OperatorMultiplication -> “*” OperatorDivision -> “/” OperatorModular -> “%” Operator Addition -> “+” Operator Subtraction -> “-” Operator Multiplication -> “*” Operator Division -> “/” Operator Modular -> “%” Operator Relational Operators The below-listed operators are used to establish a relationship between two objects: Equal -> “==” OperatorNot Equal -> “!=” OperatorGreater than -> “>” OperatorLess than -> “<“ OperatorGreater than or equal to -> “>=” OperatorLess than or Equal to -> “<=” Operator Equal -> “==” Operator Not Equal -> “!=” Operator Greater than -> “>” Operator Less than -> “<“ Operator Greater than or equal to -> “>=” Operator Less than or Equal to -> “<=” Operator Logical Operators These operators are used to establish logic among objects or values. These operators are listed below: Logical AND -> “&&” OperatorLogical OR -> “||” OperatorNot -> “!” operator Logical AND -> “&&” Operator Logical OR -> “||” Operator Not -> “!” operator Assignment Operators The operators are used to assign values. These are listed below: Assignment -> “=” OperatorIncrement -> “+=” OperatorDecrement -> “-=” OperatorProduct -> “*=” OperatorDivision -> “/=” Operator Assignment -> “=” Operator Increment -> “+=” Operator Decrement -> “-=” Operator Product -> “*=” Operator Division -> “/=” Operator =, +=, -=, *=, /= , etc called as assignment operators. Null Aware Operators These operators are used to add Null aware objects. They are listed below: ?????= ? ?? ??= simranarora5sos Dart-basics Picked Technical Scripter 2020 Dart 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": "\n27 Jun, 2021" }, { "code": null, "e": 677, "s": 52, "text": "Dart is a static programming language developed by Google. According to the GitHub popularity index, it became the most popular programming language as it actually supports the flutter toolkit. Flutter is a framework that uses dart’s native compilation ability to generate fast cross-platform apps. Dart supports two types of compilation that are, Just in time and Ahead of time. Its syntax has basically a blend of CPP, Python, Java, and JavaScript. In this blog, We will look at the basic syntax in Dart and how to represent the language that the computer understands. We will see the basic structure of Dart programming. " }, { "code": null, "e": 961, "s": 677, "text": "The syntax is a basic dart program that consists of various elements such as a keyword, an identifier, a constant, a string literal, data types, and symbols. Eg: to represent numbers words and even decimals we can call the type of data. Each line is dart must end with the semicolon." }, { "code": null, "e": 966, "s": 961, "text": "Dart" }, { "code": "void main() { // declare and initialized a variable int A = 2; int B = 3; // displaying the output print( A + B );}", "e": 1093, "s": 966, "text": null }, { "code": null, "e": 1581, "s": 1096, "text": "To represent this we can tell the type of the data, in the above example as an integer type. Similarly, To represent a word or string we can call the data type a string. All these are called Variables. Now the integers, strings, and even decimal values are temporarily held by a word or character like ‘A’ and ‘B’. All these are called variables because the data inside can keep changing. The word to the left of the ‘=’ is the variable while the one in the right is the actual value." }, { "code": null, "e": 1795, "s": 1583, "text": "A comment is a code snippet that is not readable by the compiler. Comments help to write a code efficiently and make it easier to understand the code. Comments in dart can be obtained using one of the following:" }, { "code": null, "e": 1891, "s": 1797, "text": "' // ' is used to comment on a single line.\n\n'/*.....*/ is used to comment on multiple lines." }, { "code": null, "e": 1898, "s": 1893, "text": "Dart" }, { "code": "void main() { // Displaying the output print('Hello, Geeks!'); /* print('Dart is a programming language'); print('Dart is a programming language'); */ print('Hello, Geeks!');}", "e": 2085, "s": 1898, "text": null }, { "code": null, "e": 2268, "s": 2090, "text": "Keywords are the words that are used a dart to represent the basics syntax that the compiler will understand. The basic keywords that are used in dart programs are listed below:" }, { "code": null, "e": 2370, "s": 2270, "text": "Apart from this, there are other keywords that can be used as the syntax, but they are rarely used." }, { "code": null, "e": 2500, "s": 2372, "text": "Identifiers are the name given to variables that can be read by the compiler. There are certain rules to write the identifiers:" }, { "code": null, "e": 2548, "s": 2502, "text": "No special symbol can be used except _ and $." }, { "code": null, "e": 2585, "s": 2548, "text": "It can not be the reserved keywords." }, { "code": null, "e": 2642, "s": 2585, "text": "There should not be any space between the variable name." }, { "code": null, "e": 2668, "s": 2642, "text": "They are case sensitives." }, { "code": null, "e": 2830, "s": 2668, "text": "Variables are the name given to a memory location declaring by writing variable-type _ name and then initialized and declared by ” variable-type name = value; “." }, { "code": null, "e": 2890, "s": 2832, "text": "The dart language supports the following built-in types :" }, { "code": null, "e": 2899, "s": 2892, "text": "String" }, { "code": null, "e": 3153, "s": 2901, "text": "A Dart string is a collection of characters and letters. You can use either single or double quotes to create a string. For multi-line string, we can use ‘....’ or “.....”. We can give the value of a character inside a string by doing $ {expression}. " }, { "code": null, "e": 3160, "s": 3155, "text": "Dart" }, { "code": "var name = 'John';", "e": 3179, "s": 3160, "text": null }, { "code": null, "e": 3258, "s": 3182, "text": "Here a variable is called a name and the string is assigned a value “John”." }, { "code": null, "e": 3331, "s": 3260, "text": "Note: If a variable is not initialized then the default value is null " }, { "code": null, "e": 3340, "s": 3331, "text": "Numbers " }, { "code": null, "e": 3537, "s": 3342, "text": "Both int and double are can be used for the representation of numbers. These data types are used to represent any number and even a decimal. The num type operates with basic algebraic operators." }, { "code": null, "e": 3544, "s": 3539, "text": "Dart" }, { "code": "void main() { // declare and initialized a variable int A = 20; double B = 30.0; // displaying the output print( A + B );}", "e": 3678, "s": 3544, "text": null }, { "code": null, "e": 3690, "s": 3681, "text": "Booleans" }, { "code": null, "e": 3824, "s": 3692, "text": "In order to use the Boolean data types, dart uses the keyword named bool. These data types have two values that are True and False." }, { "code": null, "e": 3831, "s": 3826, "text": "Dart" }, { "code": "void main() { bool isIttrue1 = true; print('$isIttrue1');}", "e": 3890, "s": 3831, "text": null }, { "code": null, "e": 3919, "s": 3890, "text": "Collection [List, Set, Maps]" }, { "code": null, "e": 4088, "s": 3919, "text": "Collections in Dart is basically a collection of similar and different data types. These are used as data structures in dart. Each element can be accessed sequentially." }, { "code": null, "e": 4093, "s": 4088, "text": "Dart" }, { "code": "void main() { var list = [10, 20, 30]; var names = ['Jack','Jill', 10, 1];}", "e": 4171, "s": 4093, "text": null }, { "code": null, "e": 4478, "s": 4171, "text": "Operators representation is really simple. The basic addition of numbers is possible by inserting the + operator. Similarly, we can insert any operators including BIT operation simply calling the operator on two values and assign it to another value. Let see some basics operators used in dart programming." }, { "code": null, "e": 4498, "s": 4478, "text": "Algebraic Operators" }, { "code": null, "e": 4606, "s": 4498, "text": "These operators can be used between two values and assign to the third one. The operators are listed below:" }, { "code": null, "e": 4735, "s": 4606, "text": "Addition -> “+” OperatorSubtraction -> “-” OperatorMultiplication -> “*” OperatorDivision -> “/” OperatorModular -> “%” Operator" }, { "code": null, "e": 4760, "s": 4735, "text": "Addition -> “+” Operator" }, { "code": null, "e": 4788, "s": 4760, "text": "Subtraction -> “-” Operator" }, { "code": null, "e": 4819, "s": 4788, "text": "Multiplication -> “*” Operator" }, { "code": null, "e": 4844, "s": 4819, "text": "Division -> “/” Operator" }, { "code": null, "e": 4868, "s": 4844, "text": "Modular -> “%” Operator" }, { "code": null, "e": 4889, "s": 4868, "text": "Relational Operators" }, { "code": null, "e": 4974, "s": 4889, "text": "The below-listed operators are used to establish a relationship between two objects:" }, { "code": null, "e": 5155, "s": 4974, "text": "Equal -> “==” OperatorNot Equal -> “!=” OperatorGreater than -> “>” OperatorLess than -> “<“ OperatorGreater than or equal to -> “>=” OperatorLess than or Equal to -> “<=” Operator" }, { "code": null, "e": 5178, "s": 5155, "text": "Equal -> “==” Operator" }, { "code": null, "e": 5205, "s": 5178, "text": "Not Equal -> “!=” Operator" }, { "code": null, "e": 5234, "s": 5205, "text": "Greater than -> “>” Operator" }, { "code": null, "e": 5260, "s": 5234, "text": "Less than -> “<“ Operator" }, { "code": null, "e": 5302, "s": 5260, "text": "Greater than or equal to -> “>=” Operator" }, { "code": null, "e": 5341, "s": 5302, "text": "Less than or Equal to -> “<=” Operator" }, { "code": null, "e": 5360, "s": 5341, "text": "Logical Operators " }, { "code": null, "e": 5463, "s": 5360, "text": "These operators are used to establish logic among objects or values. These operators are listed below:" }, { "code": null, "e": 5538, "s": 5463, "text": "Logical AND -> “&&” OperatorLogical OR -> “||” OperatorNot -> “!” operator" }, { "code": null, "e": 5567, "s": 5538, "text": "Logical AND -> “&&” Operator" }, { "code": null, "e": 5595, "s": 5567, "text": "Logical OR -> “||” Operator" }, { "code": null, "e": 5615, "s": 5595, "text": "Not -> “!” operator" }, { "code": null, "e": 5636, "s": 5615, "text": "Assignment Operators" }, { "code": null, "e": 5701, "s": 5636, "text": "The operators are used to assign values. These are listed below:" }, { "code": null, "e": 5829, "s": 5701, "text": "Assignment -> “=” OperatorIncrement -> “+=” OperatorDecrement -> “-=” OperatorProduct -> “*=” OperatorDivision -> “/=” Operator" }, { "code": null, "e": 5856, "s": 5829, "text": "Assignment -> “=” Operator" }, { "code": null, "e": 5883, "s": 5856, "text": "Increment -> “+=” Operator" }, { "code": null, "e": 5910, "s": 5883, "text": "Decrement -> “-=” Operator" }, { "code": null, "e": 5935, "s": 5910, "text": "Product -> “*=” Operator" }, { "code": null, "e": 5961, "s": 5935, "text": "Division -> “/=” Operator" }, { "code": null, "e": 6018, "s": 5961, "text": "=, +=, -=, *=, /= , etc called as assignment operators." }, { "code": null, "e": 6039, "s": 6018, "text": "Null Aware Operators" }, { "code": null, "e": 6114, "s": 6039, "text": "These operators are used to add Null aware objects. They are listed below:" }, { "code": null, "e": 6122, "s": 6114, "text": " ?????=" }, { "code": null, "e": 6125, "s": 6122, "text": " ?" }, { "code": null, "e": 6128, "s": 6125, "text": "??" }, { "code": null, "e": 6132, "s": 6128, "text": "??=" }, { "code": null, "e": 6148, "s": 6132, "text": "simranarora5sos" }, { "code": null, "e": 6160, "s": 6148, "text": "Dart-basics" }, { "code": null, "e": 6167, "s": 6160, "text": "Picked" }, { "code": null, "e": 6191, "s": 6167, "text": "Technical Scripter 2020" }, { "code": null, "e": 6196, "s": 6191, "text": "Dart" }, { "code": null, "e": 6215, "s": 6196, "text": "Technical Scripter" } ]
isupper() and islower() and their application in C++
16 Jun, 2022 In C++, isupper() and islower() are predefined functions used for string and character handling. cstring.h is the header file required for string functions and cctype.h is the headerfile required for character functions. isupper() Function This function is used to check if the argument contains any uppercase letters such as A, B, C, D, ..., Z. Syntax int isupper(int x) C++ // Program to check if a character is in// uppercase using isupper()#include <iostream>#include <cctype>using namespace std;int main(){ char x; cin >> x; if (isupper(x)) cout << "Uppercase"; else cout << "Not uppercase."; return 0;} Input : A Output : Uppercase Input : a Output : Not uppercase islower() Function This function is used to check if the argument contains lowercase letters such as a, b, c, d, ..., z. Syntax int islower(int x) C++ // Program to check if a character is in// lowercase using islower()#include <iostream>#include <cctype>using namespace std;int main(){ char x; cin >> x; if (islower(x)) cout << "Lowercase"; else cout << "Not Lowercase."; return 0;} Input:A Output : Not Lowercase Input : a Output : Lowercase Application of islower(), isupper(), tolower(), toupper() function. Given a string, task is to convert the characters in the string into opposite case, i.e. if a character is in lowercase, we need to convert it into uppercase and vice versa. Syntax of tolower(): int tolower(int ch); Syntax of toupper(): int toupper(int ch); Examples: Input : GeekS Output :gEEKs Input :Test Case Output :tEST cASE 1. Traverse the given string character by character upto its length, check if character is in lowercase or uppercase using predefined function. 3. If lowercase, convert it to uppercase using toupper() function, if uppercase, convert it to lowercase using tolower() function. 4. Print the final string. C++ // C++ program to toggle cases of a given// string.#include <iostream>#include <cstring>using namespace std; // function to toggle cases of a stringvoid toggle(string& str){ int length = str.length(); for (int i = 0; i < length; i++) { int c = str[i]; if (islower(c)) str[i] = toupper(c); else if (isupper(c)) str[i] = tolower(c); }} // Driver Codeint main(){ string str = "GeekS"; toggle(str); cout << str; return 0;} Output: gEEKs Time complexity : O(n) Auxiliary Space : O(1) This article is contributed by Ayush Saxena. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to review-team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. tk315 ManasChhabra2 code_29 likitarai1 youmailmahibagi cpp-string STL Strings Strings STL Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 52, "s": 24, "text": "\n16 Jun, 2022" }, { "code": null, "e": 273, "s": 52, "text": "In C++, isupper() and islower() are predefined functions used for string and character handling. cstring.h is the header file required for string functions and cctype.h is the headerfile required for character functions." }, { "code": null, "e": 399, "s": 273, "text": "isupper() Function This function is used to check if the argument contains any uppercase letters such as A, B, C, D, ..., Z. " }, { "code": null, "e": 425, "s": 399, "text": "Syntax\nint isupper(int x)" }, { "code": null, "e": 429, "s": 425, "text": "C++" }, { "code": "// Program to check if a character is in// uppercase using isupper()#include <iostream>#include <cctype>using namespace std;int main(){ char x; cin >> x; if (isupper(x)) cout << \"Uppercase\"; else cout << \"Not uppercase.\"; return 0;}", "e": 694, "s": 429, "text": null }, { "code": null, "e": 723, "s": 694, "text": "Input : A\nOutput : Uppercase" }, { "code": null, "e": 756, "s": 723, "text": "Input : a\nOutput : Not uppercase" }, { "code": null, "e": 878, "s": 756, "text": "islower() Function This function is used to check if the argument contains lowercase letters such as a, b, c, d, ..., z. " }, { "code": null, "e": 906, "s": 878, "text": "Syntax\nint islower(int x)\n " }, { "code": null, "e": 910, "s": 906, "text": "C++" }, { "code": "// Program to check if a character is in// lowercase using islower()#include <iostream>#include <cctype>using namespace std;int main(){ char x; cin >> x; if (islower(x)) cout << \"Lowercase\"; else cout << \"Not Lowercase.\"; return 0;}", "e": 1176, "s": 910, "text": null }, { "code": null, "e": 1207, "s": 1176, "text": "Input:A\nOutput : Not Lowercase" }, { "code": null, "e": 1236, "s": 1207, "text": "Input : a\nOutput : Lowercase" }, { "code": null, "e": 1478, "s": 1236, "text": "Application of islower(), isupper(), tolower(), toupper() function. Given a string, task is to convert the characters in the string into opposite case, i.e. if a character is in lowercase, we need to convert it into uppercase and vice versa." }, { "code": null, "e": 1521, "s": 1478, "text": "Syntax of tolower():\n\nint tolower(int ch);" }, { "code": null, "e": 1564, "s": 1521, "text": "Syntax of toupper():\n\nint toupper(int ch);" }, { "code": null, "e": 1575, "s": 1564, "text": "Examples: " }, { "code": null, "e": 1639, "s": 1575, "text": "Input : GeekS\nOutput :gEEKs\n\nInput :Test Case\nOutput :tEST cASE" }, { "code": null, "e": 1941, "s": 1639, "text": "1. Traverse the given string character by character upto its length, check if character is in lowercase or uppercase using predefined function. 3. If lowercase, convert it to uppercase using toupper() function, if uppercase, convert it to lowercase using tolower() function. 4. Print the final string." }, { "code": null, "e": 1945, "s": 1941, "text": "C++" }, { "code": "// C++ program to toggle cases of a given// string.#include <iostream>#include <cstring>using namespace std; // function to toggle cases of a stringvoid toggle(string& str){ int length = str.length(); for (int i = 0; i < length; i++) { int c = str[i]; if (islower(c)) str[i] = toupper(c); else if (isupper(c)) str[i] = tolower(c); }} // Driver Codeint main(){ string str = \"GeekS\"; toggle(str); cout << str; return 0;}", "e": 2435, "s": 1945, "text": null }, { "code": null, "e": 2444, "s": 2435, "text": "Output: " }, { "code": null, "e": 2450, "s": 2444, "text": "gEEKs" }, { "code": null, "e": 2496, "s": 2450, "text": "Time complexity : O(n) Auxiliary Space : O(1)" }, { "code": null, "e": 2917, "s": 2496, "text": "This article is contributed by Ayush Saxena. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to review-team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. " }, { "code": null, "e": 2923, "s": 2917, "text": "tk315" }, { "code": null, "e": 2937, "s": 2923, "text": "ManasChhabra2" }, { "code": null, "e": 2945, "s": 2937, "text": "code_29" }, { "code": null, "e": 2956, "s": 2945, "text": "likitarai1" }, { "code": null, "e": 2972, "s": 2956, "text": "youmailmahibagi" }, { "code": null, "e": 2983, "s": 2972, "text": "cpp-string" }, { "code": null, "e": 2987, "s": 2983, "text": "STL" }, { "code": null, "e": 2995, "s": 2987, "text": "Strings" }, { "code": null, "e": 3003, "s": 2995, "text": "Strings" }, { "code": null, "e": 3007, "s": 3003, "text": "STL" } ]
How to Retrieve an Entire Row or Column of an Array in Python?
12 Nov, 2020 Arrays are a set of similar elements grouped together to form a single entity, that is, it is basically a collection of integers, floating-point numbers, characters etc. The indexing of the rows and columns start from 0. Uni-dimensional arrays form a vector of similar data-type belonging elements. It contains a single row of elements, each of them falling into different columns. The dimensions of the uni-dimensional array are [1 x c], where c is the number of columns. It is possible to access any column from the array using its corresponding index. Since, this array contains a single row, printing the array is equivalent to printing the first row. array - retrieves the column at cth index (c+1 row) The following Python code illustrates the process of retrieving either an entire column in a 1-D array: Python # importing the required packageimport numpy as np # creating a numpy character arrayarr1 = np.array(["Ram", "Shyam" , "Sita"]) print("First row - ")print(arr1) # printing first column referred by first indexprint ("First Column")print (arr1[0]) # computing length of array length = len(arr1)print("Last Column")print (arr1[length-1]) Output: Original Array - ['Ram' 'Shyam' 'Sita'] First Column Ram Last Column Sita It is also possible to retrieve a range of columns from the uni-dimensional array by specifying the start and the last index. If we do not specify the last index, the array is printed till the end of the array. array[start : end] – retrieves the array columns from start index to end-1 index. The following python code is used to retrieve a range of columns in a 1-D array: Python3 # importing the required packageimport numpy as np # creating a numpy integer arrayarr1 = np.array([1, 2, 3, 4, 5, 6, 7, 8]) print("First two columns")print(arr1[0:2]) # printing columns in a rangeprint("Columns in a range")print(arr1[4:7]) # computing length of arraylength = len(arr1) print("Last 3 Columns")print(arr1[length-3:length]) print("Array till the end")print(arr1[3:]) Output: First two columns [1 2] Columns in a range [5 6 7] Last 3 Columns [6 7 8] Array till the end [4 5 6 7 8] Multi-Dimensional Array is a sequence of rows stacked together to form a matrix. The matrix contains similar elements, belonging to either integers, characters and double numbers. It is referred by the dimensions [r x c] , where r is the number of rows and c is the number of columns. matrix [r] - prints row at r index matrix[ : , c] - prints column at c index The following Python code illustrates the process of retrieving either an entire row or a column : Python3 # importing the required packageimport numpy as np # creating a numpy integer arraymat1 = np.array([[1, 2, 3], [4, 5, 6]]) print("Original matrix ")print(mat1) print("Row at 0th index")print(mat1[0]) # 1st columnsprint("Column at 1st index")print(mat1[:, 1]) # computing length of arrayprint("Column at 2nd index")print(mat1[:, 2]) Output: Original matrix [[1 2 3] [4 5 6]] Row at 0th index [1 2 3] Column at 1st index [2 5] Column at 2nd index [3 6] It is also possible to prints rows or columns belonging to a range in the matrix. We specify the beginning and ending indexes of the rows and columns of the matrix. If we leave the end index blank, it prints the columns or rows till the length of the matrix. Python3 # importing the required packageimport numpy as np # creating a numpy integer arraymat1 = np.array([[1, 2, 3, 4], [4, 5, 6, 8], [7, 6, 8, 9]])print("Original matrix ")print(mat1) print("Row from 1st to 2nd index")print(mat1[1:3]) # 1st columnsprint("Last three columns") # prints all the columns till the endprint(mat1[:, 1:]) # printing a subset of matrixprint("Matrix subset")# row index 1 and 2 inclusive and col_index 2 and 3 inclusiveprint(mat1[1:3, 2:4]) Output: Original matrix [[1 2 3 4] [4 5 6 8] [7 6 8 9]] Row from 1st to 2nd index [[4 5 6 8] [7 6 8 9]] Last three columns [[2 3 4] [5 6 8] [6 8 9]] Matrix subset [[6 8] [8 9]] Python-numpy Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n12 Nov, 2020" }, { "code": null, "e": 249, "s": 28, "text": "Arrays are a set of similar elements grouped together to form a single entity, that is, it is basically a collection of integers, floating-point numbers, characters etc. The indexing of the rows and columns start from 0." }, { "code": null, "e": 685, "s": 249, "text": "Uni-dimensional arrays form a vector of similar data-type belonging elements. It contains a single row of elements, each of them falling into different columns. The dimensions of the uni-dimensional array are [1 x c], where c is the number of columns. It is possible to access any column from the array using its corresponding index. Since, this array contains a single row, printing the array is equivalent to printing the first row. " }, { "code": null, "e": 738, "s": 685, "text": "array - retrieves the column at cth index (c+1 row)\n" }, { "code": null, "e": 842, "s": 738, "text": "The following Python code illustrates the process of retrieving either an entire column in a 1-D array:" }, { "code": null, "e": 849, "s": 842, "text": "Python" }, { "code": "# importing the required packageimport numpy as np # creating a numpy character arrayarr1 = np.array([\"Ram\", \"Shyam\" , \"Sita\"]) print(\"First row - \")print(arr1) # printing first column referred by first indexprint (\"First Column\")print (arr1[0]) # computing length of array length = len(arr1)print(\"Last Column\")print (arr1[length-1])", "e": 1188, "s": 849, "text": null }, { "code": null, "e": 1196, "s": 1188, "text": "Output:" }, { "code": null, "e": 1273, "s": 1196, "text": "Original Array - \n['Ram' 'Shyam' 'Sita']\nFirst Column\nRam\nLast Column\nSita\n" }, { "code": null, "e": 1484, "s": 1273, "text": "It is also possible to retrieve a range of columns from the uni-dimensional array by specifying the start and the last index. If we do not specify the last index, the array is printed till the end of the array." }, { "code": null, "e": 1566, "s": 1484, "text": "array[start : end] – retrieves the array columns from start index to end-1 index." }, { "code": null, "e": 1647, "s": 1566, "text": "The following python code is used to retrieve a range of columns in a 1-D array:" }, { "code": null, "e": 1655, "s": 1647, "text": "Python3" }, { "code": "# importing the required packageimport numpy as np # creating a numpy integer arrayarr1 = np.array([1, 2, 3, 4, 5, 6, 7, 8]) print(\"First two columns\")print(arr1[0:2]) # printing columns in a rangeprint(\"Columns in a range\")print(arr1[4:7]) # computing length of arraylength = len(arr1) print(\"Last 3 Columns\")print(arr1[length-3:length]) print(\"Array till the end\")print(arr1[3:])", "e": 2043, "s": 1655, "text": null }, { "code": null, "e": 2051, "s": 2043, "text": "Output:" }, { "code": null, "e": 2157, "s": 2051, "text": "First two columns\n[1 2]\nColumns in a range\n[5 6 7]\nLast 3 Columns\n[6 7 8]\nArray till the end\n[4 5 6 7 8]\n" }, { "code": null, "e": 2443, "s": 2157, "text": "Multi-Dimensional Array is a sequence of rows stacked together to form a matrix. The matrix contains similar elements, belonging to either integers, characters and double numbers. It is referred by the dimensions [r x c] , where r is the number of rows and c is the number of columns. " }, { "code": null, "e": 2521, "s": 2443, "text": "matrix [r] - prints row at r index\nmatrix[ : , c] - prints column at c index\n" }, { "code": null, "e": 2620, "s": 2521, "text": "The following Python code illustrates the process of retrieving either an entire row or a column :" }, { "code": null, "e": 2628, "s": 2620, "text": "Python3" }, { "code": "# importing the required packageimport numpy as np # creating a numpy integer arraymat1 = np.array([[1, 2, 3], [4, 5, 6]]) print(\"Original matrix \")print(mat1) print(\"Row at 0th index\")print(mat1[0]) # 1st columnsprint(\"Column at 1st index\")print(mat1[:, 1]) # computing length of arrayprint(\"Column at 2nd index\")print(mat1[:, 2])", "e": 2965, "s": 2628, "text": null }, { "code": null, "e": 2973, "s": 2965, "text": "Output:" }, { "code": null, "e": 3087, "s": 2973, "text": "Original matrix \n[[1 2 3]\n [4 5 6]]\nRow at 0th index\n[1 2 3]\nColumn at 1st index\n[2 5]\nColumn at 2nd index\n[3 6]\n" }, { "code": null, "e": 3347, "s": 3087, "text": "It is also possible to prints rows or columns belonging to a range in the matrix. We specify the beginning and ending indexes of the rows and columns of the matrix. If we leave the end index blank, it prints the columns or rows till the length of the matrix. " }, { "code": null, "e": 3355, "s": 3347, "text": "Python3" }, { "code": "# importing the required packageimport numpy as np # creating a numpy integer arraymat1 = np.array([[1, 2, 3, 4], [4, 5, 6, 8], [7, 6, 8, 9]])print(\"Original matrix \")print(mat1) print(\"Row from 1st to 2nd index\")print(mat1[1:3]) # 1st columnsprint(\"Last three columns\") # prints all the columns till the endprint(mat1[:, 1:]) # printing a subset of matrixprint(\"Matrix subset\")# row index 1 and 2 inclusive and col_index 2 and 3 inclusiveprint(mat1[1:3, 2:4])", "e": 3821, "s": 3355, "text": null }, { "code": null, "e": 3830, "s": 3821, "text": "Output: " }, { "code": null, "e": 4007, "s": 3830, "text": "Original matrix \n[[1 2 3 4]\n [4 5 6 8]\n [7 6 8 9]]\nRow from 1st to 2nd index\n[[4 5 6 8]\n [7 6 8 9]]\nLast three columns\n[[2 3 4]\n [5 6 8]\n [6 8 9]]\nMatrix subset\n[[6 8]\n [8 9]]\n" }, { "code": null, "e": 4020, "s": 4007, "text": "Python-numpy" }, { "code": null, "e": 4027, "s": 4020, "text": "Python" } ]
How to Send Image File from One Activity to Another Activity?
30 Apr, 2021 In this article, we are going to send an image from one activity to another. We will be using putExtra to send image and we will be using bundle to get the data sent from the previous activity and then we will be showing the received image. Step 1: Create a New Project To create a new project in Android Studio please refer to How to Create/Start a New Project in Android Studio. Note that select Java as the programming language. Step 2: Working with the activity_main.xml file Navigate to the app > res > layout > activity_main.xml and add the below code to that file. Below is the code for the activity_main.xml file. XML <?xml version="1.0" encoding="utf-8"?><LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" android:gravity="center" android:orientation="vertical" tools:context=".MainActivity"> <Button android:id="@+id/sendimagei" android:layout_width="wrap_content" android:layout_height="wrap_content" android:padding="16dp" android:text="Send Image" android:textColor="#000" android:textSize="32sp" /> </LinearLayout> Step 3: Working with the MainActivity.java file Go to the MainActivity.java file and refer to the following code. Below is the code for the MainActivity.java file. Comments are added inside the code to understand the code in more detail. Java import android.content.Intent;import android.os.Bundle;import android.view.View;import android.widget.Button; import androidx.appcompat.app.AppCompatActivity; public class MainActivity extends AppCompatActivity { Button sendimage; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); // initialise the layout sendimage = findViewById(R.id.sendimagei); sendimage.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { // add the image in putExtra // and send the data in next activity Intent sendimage = new Intent(MainActivity.this, SecondActivity.class); sendimage.putExtra("image", R.drawable.circle); startActivity(sendimage); } }); }} Step 4: Create another new Activity Refer to this article and name the activity as SecondActivity. Go to the activity_second.xml file and refer to the following code. Below is the code for the activity_second.xml file. XML <?xml version="1.0" encoding="utf-8"?><LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" android:gravity="center" android:orientation="vertical" tools:context=".SecondActivity"> <ImageView android:id="@+id/images" android:layout_width="250dp" android:layout_height="250dp" /> </LinearLayout> Step 5: Working with the SecondActivity.java file Go to the SecondActivity.java file and refer to the following code. Below is the code for the SecondActivity.java file. Comments are added inside the code to understand the code in more detail. Java import android.os.Bundle;import android.widget.ImageView; import androidx.appcompat.app.AppCompatActivity; public class SecondActivity extends AppCompatActivity { ImageView imageView; int imagevalue; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_second); // initialise the layout imageView = findViewById(R.id.images); // check if any value sent from previous activity Bundle bundle = getIntent().getExtras(); // if bundle is not null then get the image value if (bundle != null) { imagevalue = bundle.getInt("image"); } imageView.setImageResource(imagevalue); }} Output: Android Java Java Android Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 53, "s": 25, "text": "\n30 Apr, 2021" }, { "code": null, "e": 294, "s": 53, "text": "In this article, we are going to send an image from one activity to another. We will be using putExtra to send image and we will be using bundle to get the data sent from the previous activity and then we will be showing the received image." }, { "code": null, "e": 323, "s": 294, "text": "Step 1: Create a New Project" }, { "code": null, "e": 485, "s": 323, "text": "To create a new project in Android Studio please refer to How to Create/Start a New Project in Android Studio. Note that select Java as the programming language." }, { "code": null, "e": 533, "s": 485, "text": "Step 2: Working with the activity_main.xml file" }, { "code": null, "e": 676, "s": 533, "text": "Navigate to the app > res > layout > activity_main.xml and add the below code to that file. Below is the code for the activity_main.xml file. " }, { "code": null, "e": 680, "s": 676, "text": "XML" }, { "code": "<?xml version=\"1.0\" encoding=\"utf-8\"?><LinearLayout xmlns:android=\"http://schemas.android.com/apk/res/android\" xmlns:tools=\"http://schemas.android.com/tools\" android:layout_width=\"match_parent\" android:layout_height=\"match_parent\" android:gravity=\"center\" android:orientation=\"vertical\" tools:context=\".MainActivity\"> <Button android:id=\"@+id/sendimagei\" android:layout_width=\"wrap_content\" android:layout_height=\"wrap_content\" android:padding=\"16dp\" android:text=\"Send Image\" android:textColor=\"#000\" android:textSize=\"32sp\" /> </LinearLayout>", "e": 1306, "s": 680, "text": null }, { "code": null, "e": 1354, "s": 1306, "text": "Step 3: Working with the MainActivity.java file" }, { "code": null, "e": 1544, "s": 1354, "text": "Go to the MainActivity.java file and refer to the following code. Below is the code for the MainActivity.java file. Comments are added inside the code to understand the code in more detail." }, { "code": null, "e": 1549, "s": 1544, "text": "Java" }, { "code": "import android.content.Intent;import android.os.Bundle;import android.view.View;import android.widget.Button; import androidx.appcompat.app.AppCompatActivity; public class MainActivity extends AppCompatActivity { Button sendimage; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); // initialise the layout sendimage = findViewById(R.id.sendimagei); sendimage.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { // add the image in putExtra // and send the data in next activity Intent sendimage = new Intent(MainActivity.this, SecondActivity.class); sendimage.putExtra(\"image\", R.drawable.circle); startActivity(sendimage); } }); }}", "e": 2485, "s": 1549, "text": null }, { "code": null, "e": 2521, "s": 2485, "text": "Step 4: Create another new Activity" }, { "code": null, "e": 2704, "s": 2521, "text": "Refer to this article and name the activity as SecondActivity. Go to the activity_second.xml file and refer to the following code. Below is the code for the activity_second.xml file." }, { "code": null, "e": 2708, "s": 2704, "text": "XML" }, { "code": "<?xml version=\"1.0\" encoding=\"utf-8\"?><LinearLayout xmlns:android=\"http://schemas.android.com/apk/res/android\" xmlns:tools=\"http://schemas.android.com/tools\" android:layout_width=\"match_parent\" android:layout_height=\"match_parent\" android:gravity=\"center\" android:orientation=\"vertical\" tools:context=\".SecondActivity\"> <ImageView android:id=\"@+id/images\" android:layout_width=\"250dp\" android:layout_height=\"250dp\" /> </LinearLayout>", "e": 3191, "s": 2708, "text": null }, { "code": null, "e": 3241, "s": 3191, "text": "Step 5: Working with the SecondActivity.java file" }, { "code": null, "e": 3435, "s": 3241, "text": "Go to the SecondActivity.java file and refer to the following code. Below is the code for the SecondActivity.java file. Comments are added inside the code to understand the code in more detail." }, { "code": null, "e": 3440, "s": 3435, "text": "Java" }, { "code": "import android.os.Bundle;import android.widget.ImageView; import androidx.appcompat.app.AppCompatActivity; public class SecondActivity extends AppCompatActivity { ImageView imageView; int imagevalue; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_second); // initialise the layout imageView = findViewById(R.id.images); // check if any value sent from previous activity Bundle bundle = getIntent().getExtras(); // if bundle is not null then get the image value if (bundle != null) { imagevalue = bundle.getInt(\"image\"); } imageView.setImageResource(imagevalue); }}", "e": 4222, "s": 3440, "text": null }, { "code": null, "e": 4230, "s": 4222, "text": "Output:" }, { "code": null, "e": 4238, "s": 4230, "text": "Android" }, { "code": null, "e": 4243, "s": 4238, "text": "Java" }, { "code": null, "e": 4248, "s": 4243, "text": "Java" }, { "code": null, "e": 4256, "s": 4248, "text": "Android" } ]
Comparison of a float with a value in C
17 Nov, 2020 Predict the output of the following C program. C #include<stdio.h>int main(){ float x = 0.1; if (x == 0.1) printf("IF"); else if (x == 0.1f) printf("ELSE IF"); else printf("ELSE");} The output of above program is “ELSE IF” which means the expression “x == 0.1” returns false and expression “x == 0.1f” returns true. Let consider the following program to understand the reason behind the above output. C #include<stdio.h>int main(){ float x = 0.1; printf("%d %d %d", sizeof(x), sizeof(0.1), sizeof(0.1f)); return 0;} The output of above program is "4 8 4" on a typical C compiler. It actually prints size of float, size of double and size of float. The values used in an expression are considered as double (double precision floating point format) unless a ‘f’ is specified at the end. So the expression “x==0.1” has a double on right side and float which are stored in a single precision floating point format on left side. In such situations, float is promoted to double (see this). The double precision format uses more bits for precision than single precision format. The binary equivalent of 0.110 can be written as (0.00011001100110011...)2 which goes up to infinity(See this article to know more about conversion). Since the precision of float is less than the double therefore after a certain point(23 in float and 52 in double) it would truncate the result. Hence, after promotion of float into double(at the time of comparison) compiler will pad the remaining bits with zeroes. Hence, we get the different result in which decimal equivalent of both would be different. For instance, In float => (0.1)10 = (0.00011001100110011001100)2 In double after promotion of float ...(1) => (0.1)10 = (0.00011001100110011001100000000000000000...)2 ^ padding zeroes here In double without promotion ... (2) => (0.1)10 = (0.0001100110011001100110011001100110011001100110011001)2 Hence we can see the result of both equations are different. Therefore 'if' statement can never be executed. Note that the promotion of float to double can only cause mismatch when a value (like 0.1) uses more precision bits than the bits of single precision. For example, the following C program prints “IF”. C #include<stdio.h>int main(){ float x = 0.5; if (x == 0.5) printf("IF"); else if (x == 0.5f) printf("ELSE IF"); else printf("ELSE");} Output: IF Here binary equivalent of 0.510 is (0.100000...)2 (No precision will be lost in both float and double type). Therefore if compiler pad the extra zeroes at the time of promotion then we would get the same result in the decimal equivalent of both left and right side in comparison(x == 0.5). You can refer Floating Point Representation – Basics for the representation of floating-point numbers. This article is contributed by Abhay Rathi and improved by SHUBHAM BANSAL. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above hilalkaldanekaldane937 C-Data Types cpp-data-types C Language Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 54, "s": 26, "text": "\n17 Nov, 2020" }, { "code": null, "e": 102, "s": 54, "text": "Predict the output of the following C program. " }, { "code": null, "e": 104, "s": 102, "text": "C" }, { "code": "#include<stdio.h>int main(){ float x = 0.1; if (x == 0.1) printf(\"IF\"); else if (x == 0.1f) printf(\"ELSE IF\"); else printf(\"ELSE\");}", "e": 270, "s": 104, "text": null }, { "code": null, "e": 405, "s": 270, "text": "The output of above program is “ELSE IF” which means the expression “x == 0.1” returns false and expression “x == 0.1f” returns true. " }, { "code": null, "e": 492, "s": 405, "text": "Let consider the following program to understand the reason behind the above output. " }, { "code": null, "e": 494, "s": 492, "text": "C" }, { "code": "#include<stdio.h>int main(){ float x = 0.1; printf(\"%d %d %d\", sizeof(x), sizeof(0.1), sizeof(0.1f)); return 0;}", "e": 613, "s": 494, "text": null }, { "code": null, "e": 747, "s": 613, "text": "The output of above program is \"4 8 4\" on a typical C compiler.\nIt actually prints size of float, size of double and size of float.\n\n" }, { "code": null, "e": 1171, "s": 747, "text": "The values used in an expression are considered as double (double precision floating point format) unless a ‘f’ is specified at the end. So the expression “x==0.1” has a double on right side and float which are stored in a single precision floating point format on left side. In such situations, float is promoted to double (see this). The double precision format uses more bits for precision than single precision format. " }, { "code": null, "e": 1693, "s": 1171, "text": "The binary equivalent of 0.110 can be written as (0.00011001100110011...)2 which goes up to infinity(See this article to know more about conversion). Since the precision of float is less than the double therefore after a certain point(23 in float and 52 in double) it would truncate the result. Hence, after promotion of float into double(at the time of comparison) compiler will pad the remaining bits with zeroes. Hence, we get the different result in which decimal equivalent of both would be different. For instance, " }, { "code": null, "e": 2126, "s": 1693, "text": "In float \n=> (0.1)10 = (0.00011001100110011001100)2\nIn double after promotion of float ...(1)\n=> (0.1)10 = (0.00011001100110011001100000000000000000...)2\n ^ padding zeroes here\nIn double without promotion ... (2)\n=> (0.1)10 = (0.0001100110011001100110011001100110011001100110011001)2\n\nHence we can see the result of both equations are different.\nTherefore 'if' statement can never be executed.\n\n" }, { "code": null, "e": 2327, "s": 2126, "text": "Note that the promotion of float to double can only cause mismatch when a value (like 0.1) uses more precision bits than the bits of single precision. For example, the following C program prints “IF”." }, { "code": null, "e": 2329, "s": 2327, "text": "C" }, { "code": "#include<stdio.h>int main(){ float x = 0.5; if (x == 0.5) printf(\"IF\"); else if (x == 0.5f) printf(\"ELSE IF\"); else printf(\"ELSE\");}", "e": 2495, "s": 2329, "text": null }, { "code": null, "e": 2504, "s": 2495, "text": "Output: " }, { "code": null, "e": 2509, "s": 2504, "text": "IF\n\n" }, { "code": null, "e": 2560, "s": 2509, "text": "Here binary equivalent of 0.510 is (0.100000...)2 " }, { "code": null, "e": 2801, "s": 2560, "text": "(No precision will be lost in both float and double type). Therefore if compiler pad the extra zeroes at the time of promotion then we would get the same result in the decimal equivalent of both left and right side in comparison(x == 0.5). " }, { "code": null, "e": 2904, "s": 2801, "text": "You can refer Floating Point Representation – Basics for the representation of floating-point numbers." }, { "code": null, "e": 3104, "s": 2904, "text": "This article is contributed by Abhay Rathi and improved by SHUBHAM BANSAL. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above " }, { "code": null, "e": 3127, "s": 3104, "text": "hilalkaldanekaldane937" }, { "code": null, "e": 3140, "s": 3127, "text": "C-Data Types" }, { "code": null, "e": 3155, "s": 3140, "text": "cpp-data-types" }, { "code": null, "e": 3166, "s": 3155, "text": "C Language" } ]