title
stringlengths 3
221
| text
stringlengths 17
477k
| parsed
listlengths 0
3.17k
|
---|---|---|
Double Base Palindrome
|
04 May, 2022
Double base Palindrome as the name suggest is a number which is Palindrome in 2 bases. One of the base is 10 i.e. decimal and another base is k.(which can be 2 or others). Note : The palindromic number, in either base, may not include leading zeros. Example : The decimal number, 585 = 10010010012 (binary), is palindromic in both bases.
A Palindrome is a word, phrase, number, or other sequence of characters which reads the same backward as forward, such as madam or 12321.
Find the sum of all numbers less than n which are palindromic in base 10 and base k.
Examples:
Input : 10 2
Output : 25
Explanation : (here n = 10 and k = 2)
1 3 5 7 9 (they are all palindrome
in base 10 and 2) so sum is :
1 + 3 + 5 + 7 + 9 = 25
Input : 100 2
Output : 157
Explanation : 1 + 3 + 5 + 7 + 9 + 33 + 99 = 157
Method 1 : This method is simple. For every number less than n :
Check if it is a palindrome in base 10
If yes, then convert it into base k
Check if it is palindrome in base k
If yes, then add it in sum.
This method is quite lengthy as it checks for every number whether it is a palindrome or not. So, for number as large as 1000000, it checks for every number. If k = 2, then a palindrome in base 2 can only be odd number, which might reduce the comparisons to 1000000 / 2 = 500000 (which is still large).
Below is the implementation of the above approach :
C++
Java
Python3
C#
PHP
Javascript
// CPP Program for Checking double base// Palindrome.#include <bits/stdc++.h>using namespace std; // converts number to base k by changing// it into string.string integer_to_string(int n, int base){ string str; while (n > 0) { int digit = n % base; n /= base; str.push_back(digit + '0'); } return str;} // function to check for palindromeint isPalindrome(int i, int k){ int temp = i; // m stores reverse of a number int m = 0; while (temp > 0) { m = temp % 10 + m * 10; temp /= 10; } // if reverse is equal to number if (m == i) { // converting to base k string str = integer_to_string(m, k); string str1 = str; // reversing number in base k reverse(str.begin(), str.end()); // checking palindrome in base k if (str == str1) { return i; } } return 0;} // function to find sum of palindromesvoid sumPalindrome(int n, int k){ int sum = 0; for (int i = 1; i < n; i++) { sum += isPalindrome(i, k); } cout << "Total sum is " << sum;} // driver functionint main(){ int n = 100; int k = 2; sumPalindrome(n, k); return 0;}
// Java Program for Checking double base// Palindrome.import java.util.*; class GFG{// converts number to base k by changing// it into string.static String integer_to_string(int n, int base){ String str=""; while (n > 0) { int digit = n % base; n /= base; str+=(char)(digit+'0'); } return str;} // function to check for palindromestatic int isPalindrome(int i, int k){ int temp = i; // m stores reverse of a number int m = 0; while (temp > 0) { m = temp % 10 + m * 10; temp /= 10; } // if reverse is equal to number if (m == i) { // converting to base k String str = integer_to_string(m, k); StringBuilder sb = new StringBuilder(str); String str1=sb.reverse().toString(); if (str.equals(str1)) { return i; } } return 0;} // function to find sum of palindromesstatic void sumPalindrome(int n, int k){ int sum = 0; for (int i = 1; i < n; i++) { sum += isPalindrome(i, k); } System.out.println("Total sum is "+sum);} // driver functionpublic static void main(String[] args){ int n = 100; int k = 2; sumPalindrome(n, k);}}// This code is contributed by mits
# Python3 Program for Checking# double base Palindrome. # converts number to base# k by changing it into string.def integer_to_string(n, base): str = ""; while (n > 0): digit = n % base; n = int(n / base); str = chr(digit + ord('0')) + str; return str; # function to check for palindromedef isPalindrome(i, k): temp = i; # m stores reverse of a number m = 0; while (temp > 0): m = (temp % 10) + (m * 10); temp = int(temp / 10); # if reverse is equal to number if (m == i): # converting to base k str = integer_to_string(m, k); str1 = str; # reversing number in base k # str=str[::-1]; # checking palindrome # in base k if (str[::-1] == str1): return i; return 0; # function to find sum of palindromesdef sumPalindrome(n, k): sum = 0; for i in range(n): sum += isPalindrome(i, k); print("Total sum is", sum); # Driver coden = 100;k = 2; sumPalindrome(n, k); # This code is contributed# by mits
// C# Program for Checking double base// Palindrome.using System; class GFG{// converts number to base k by changing// it into string.static string integer_to_string(int n, int base1){ string str=""; while (n > 0) { int digit = n % base1; n /= base1; str+=(char)(digit+'0'); } return str;} // function to check for palindromestatic int isPalindrome(int i, int k){ int temp = i; // m stores reverse of a number int m = 0; while (temp > 0) { m = temp % 10 + m * 10; temp /= 10; } // if reverse is equal to number if (m == i) { // converting to base k string str = integer_to_string(m, k); char[] ch = str.ToCharArray(); Array.Reverse(ch); string str1=new String(ch);; if (str.Equals(str1)) { return i; } } return 0;} // function to find sum of palindromesstatic void sumPalindrome(int n, int k){ int sum = 0; for (int i = 1; i < n; i++) { sum += isPalindrome(i, k); } Console.WriteLine("Total sum is "+sum);} // driver function static void Main(){ int n = 100; int k = 2; sumPalindrome(n, k);}}// This code is contributed by mits
<?php// PHP Program for Checking// double base Palindrome. // converts number to base// k by changing it into string.function integer_to_string($n, $base){ $str = ""; while ($n > 0) { $digit = $n % $base; $n = (int)($n / $base); $str = ($digit + '0') . $str; } return $str;} // function to check// for palindromefunction isPalindrome($i, $k){ $temp = $i; // m stores reverse // of a number $m = 0; while ($temp > 0) { $m = ($temp % 10) + ($m * 10); $temp = (int)($temp / 10); } // if reverse is // equal to number if ($m == $i) { // converting to base k $str = integer_to_string($m, $k); $str1 = $str; // reversing number in base k // $str=strrev($str); // checking palindrome // in base k if (strcmp(strrev($str), $str1) == 0) { return $i; } } return 0;} // function to find// sum of palindromesfunction sumPalindrome($n, $k){ $sum = 0; for ($i = 0; $i < $n; $i++) { $sum += isPalindrome($i, $k); } echo "Total sum is " . $sum;} // Driver code$n = 100;$k = 2; sumPalindrome($n, $k); // This code is contributed// by mits?>
<script> // Javascript program for checking// double base Palindrome. // Converts number to base k by changing// it into string.function integer_to_string(n, base1){ let str=""; while (n > 0) { let digit = n % base1; n = parseInt(n / base1, 10); str += String.fromCharCode(digit + '0'.charCodeAt()); } return str;} // Function to check for palindromefunction isPalindrome(i, k){ let temp = i; // m stores reverse of a number let m = 0; while (temp > 0) { m = temp % 10 + m * 10; temp = parseInt(temp / 10, 10); } // If reverse is equal to number if (m == i) { // Converting to base k let str = integer_to_string(m, k); let ch = str.split(''); ch.reverse(); let str1 = ch.join(""); if (str == str1) { return i; } } return 0;} // Function to find sum of palindromesfunction sumPalindrome(n, k){ let sum = 0; for(let i = 1; i < n; i++) { sum += isPalindrome(i, k); } document.write("Total sum is " + sum + "</br>");} // Driver codelet n = 100;let k = 2; sumPalindrome(n, k); // This code is contributed by decode2207 </script>
Output:
Total sum is 157
Method 2 : This method is a little complex to understand but more advance than method 1. Rather than checking palindrome for two bases. This method generates palindrome in given range. Suppose we have a palindrome of the form 123321 in base k, then the first 3 digits define the palindrome. However, the 3 digits 123 also define the palindrome 12321. So the 3-digit number 123 defines a 5-digit palindrome and a 6 digit palindrome. From which follows that every positive number less than kn generates two palindromes less than k2n . This holds for every base k. Example : let’s say k = 10 that is decimal. Then for n = 1, all numbers less than 10n have 2 palindrome, 1 even length and 1 odd length in 102n. These are 1, 11 or 2, 22 or 3, 33 and so on. So, for 1000000 we generate around 2000 and for 108 we generate around 20000 palindromes.
Start from i=1 and generate odd palindrome of it.
Check if this generated odd palindrome is also palindrome in base k
If yes, then add this number to sum.
Repeat the above three steps by changing i=i+1 until the last generated odd palindrome has crossed limit.
Now, again start from i=1 and generate even palindrome of it.
Check if this generated even palindrome is also palindrome in base k
If yes, then add this number to sum.
Repeat the above three steps by changing i=i+1 until the last generated even palindrome has crossed limit.
Below is the implementation of the above approach :
C++
Java
Python3
C#
PHP
Javascript
// CPP Program for Checking double// base Palindrome.#include <bits/stdc++.h>using namespace std; // generates even and odd palindromesint makePalindrome(int n, bool odd){ int res = n; if (odd) n = n / 10; while (n > 0) { res = 10 * res + n % 10; n /= 10; } return res;} // Check if a number is palindrome// in base kbool isPalindrome(int n, int base){ int reversed = 0; int temp = n; while (temp > 0) { reversed = reversed * base + temp % base; temp /= base; } return reversed == n;} // function to print sum of Palindromesvoid sumPalindrome(int n, int k){ int sum = 0, i = 1; int p = makePalindrome(i, true); // loop for odd generation of // odd palindromes while (p < n) { if (isPalindrome(p, k)) sum += p; i++; // cout << p << " "; p = makePalindrome(i, true); } i = 1; // loop for generation of // even palindromes p = makePalindrome(i, false); while (p < n) { if (isPalindrome(p, k)) sum += p; i++; p = makePalindrome(i, false); } // result of all palindromes in // both bases. cout << "Total sum is " << sum << endl;} // driver codeint main(){ int n = 1000000, k = 2; sumPalindrome(n ,k); return 0;}
// Java Program for Checking double// base Palindrome. public class GFG { // generates even and odd palindromes static int makePalindrome(int n, boolean odd) { int res = n; if (odd) { n = n / 10; } while (n > 0) { res = 10 * res + n % 10; n /= 10; } return res; } // Check if a number is palindrome// in base k static boolean isPalindrome(int n, int base) { int reversed = 0; int temp = n; while (temp > 0) { reversed = reversed * base + temp % base; temp /= base; } return reversed == n; } // function to print sum of Palindromes static void sumPalindrome(int n, int k) { int sum = 0, i = 1; int p = makePalindrome(i, true); // loop for odd generation of // odd palindromes while (p < n) { if (isPalindrome(p, k)) { sum += p; } i++; // cout << p << " "; p = makePalindrome(i, true); } i = 1; // loop for generation of // even palindromes p = makePalindrome(i, false); while (p < n) { if (isPalindrome(p, k)) { sum += p; } i++; p = makePalindrome(i, false); } // result of all palindromes in // both bases. System.out.println("Total sum is " + sum); } // driver code public static void main(String[] args) { int n = 1000000, k = 2; sumPalindrome(n, k); }}
# Python3 Program for Checking double# base Palindrome. # Function generates even and# odd palindromesdef makePalindrome(n, odd): res = n; if (odd): n = int(n / 10); while (n > 0): res = 10 * res + n % 10; n = int(n / 10); return res; # Check if a number is palindrome# in base kdef isPalindrome(n, base): reversed = 0; temp = n; while (temp > 0): reversed = reversed * base + temp % base; temp = int(temp / base); return reversed == n; # function to print sum of Palindromesdef sumPalindrome(n, k): sum = 0; i = 1; p = makePalindrome(i, True); # loop for odd generation of # odd palindromes while (p < n): if (isPalindrome(p, k)): sum += p; i += 1; p = makePalindrome(i, True); i = 1; # loop for generation of # even palindromes p = makePalindrome(i, False); while (p < n): if (isPalindrome(p, k)): sum += p; i += 1; p = makePalindrome(i, False); # result of all palindromes in # both bases. print("Total sum is", sum); # Driver coden = 1000000;k = 2;sumPalindrome(n, k); # This code is contributed by mits
// C# Program for Checking double// base1 Palindrome. public class GFG { // generates even and odd palindromes static int makePalindrome(int n, bool odd) { int res = n; if (odd) { n = n / 10; } while (n > 0) { res = 10 * res + n % 10; n /= 10; } return res; } // Check if a number is palindrome// in base1 k static bool isPalindrome(int n, int base1) { int reversed = 0; int temp = n; while (temp > 0) { reversed = reversed * base1 + temp % base1; temp /= base1; } return reversed == n; } // function to print sum of Palindromes static void sumPalindrome(int n, int k) { int sum = 0, i = 1; int p = makePalindrome(i, true); // loop for odd generation of // odd palindromes while (p < n) { if (isPalindrome(p, k)) { sum += p; } i++; p = makePalindrome(i, true); } i = 1; // loop for generation of // even palindromes p = makePalindrome(i, false); while (p < n) { if (isPalindrome(p, k)) { sum += p; } i++; p = makePalindrome(i, false); } // result of all palindromes in // both base1s. System.Console.WriteLine("Total sum is " + sum); } // driver code public static void Main() { int n = 1000000, k = 2; sumPalindrome(n, k); }} // This code is contributed by mits
<?php// PHP Program for Checking double// base Palindrome. // Function generates even and// odd palindromesfunction makePalindrome($n, $odd){ $res = $n; if ($odd) { $n = (int)($n / 10); } while ($n > 0) { $res = 10 * $res + $n % 10; $n = (int)($n / 10); } return $res;} // Check if a number is palindrome// in base kfunction isPalindrome($n, $base){ $reversed = 0; $temp = $n; while ($temp > 0) { $reversed = $reversed * $base + $temp % $base; $temp = (int)($temp / $base); } return $reversed == $n;} // function to print sum of Palindromesfunction sumPalindrome($n, $k){ $sum = 0; $i = 1; $p = makePalindrome($i, true); // loop for odd generation of // odd palindromes while ($p < $n) { if (isPalindrome($p, $k)) { $sum += $p; } $i++; $p = makePalindrome($i, true); } $i = 1; // loop for generation of // even palindromes $p = makePalindrome($i, false); while ($p < $n) { if (isPalindrome($p, $k)) { $sum += $p; } $i++; $p = makePalindrome($i, false); } // result of all palindromes in // both bases. echo("Total sum is " . $sum);} // Driver code$n = 1000000; $k = 2;sumPalindrome($n, $k); // This code is contributed// by Mukul Singh.?>
<script>// javascript Program for Checking var// base Palindrome. // generates even and odd palindromes function makePalindrome(n, odd) { var res = n; if (odd) { n = parseInt(n / 10); } while (n > 0) { res = 10 * res + n % 10; n = parseInt(n / 10); } return res; } // Check if a number is palindrome// in base k function isPalindrome(n , base) { var reversed = 0; var temp = n; while (temp > 0) { reversed = reversed * base + temp % base; temp = parseInt(temp/base); } return reversed == n; } // function to print sum of Palindromes function sumPalindrome(n , k) { var sum = 0, i = 1; var p = makePalindrome(i, true); // loop for odd generation of // odd palindromes while (p < n) { if (isPalindrome(p, k)) { sum += p; } i++; // cout << p << " "; p = makePalindrome(i, true); } i = 1; // loop for generation of // even palindromes p = makePalindrome(i, false); while (p < n) { if (isPalindrome(p, k)) { sum += p; } i++; p = makePalindrome(i, false); } // result of all palindromes in // both bases. document.write("Total sum is " + sum); } // driver codevar n = 1000000, k = 2;sumPalindrome(n, k); // This code contributed by Princi Singh</script>
Output:
Total sum is 872187
This article is contributed by Shubham Rana. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
Mithun Kumar
29AjayKumar
Code_Mech
princi singh
decode2207
arorakashish0911
surinderdawra388
base-conversion
palindrome
Mathematical
Mathematical
palindrome
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
|
[
{
"code": null,
"e": 54,
"s": 26,
"text": "\n04 May, 2022"
},
{
"code": null,
"e": 393,
"s": 54,
"text": "Double base Palindrome as the name suggest is a number which is Palindrome in 2 bases. One of the base is 10 i.e. decimal and another base is k.(which can be 2 or others). Note : The palindromic number, in either base, may not include leading zeros. Example : The decimal number, 585 = 10010010012 (binary), is palindromic in both bases. "
},
{
"code": null,
"e": 531,
"s": 393,
"text": "A Palindrome is a word, phrase, number, or other sequence of characters which reads the same backward as forward, such as madam or 12321."
},
{
"code": null,
"e": 616,
"s": 531,
"text": "Find the sum of all numbers less than n which are palindromic in base 10 and base k."
},
{
"code": null,
"e": 627,
"s": 616,
"text": "Examples: "
},
{
"code": null,
"e": 899,
"s": 627,
"text": "Input : 10 2\nOutput : 25\nExplanation : (here n = 10 and k = 2)\n 1 3 5 7 9 (they are all palindrome \n in base 10 and 2) so sum is :\n 1 + 3 + 5 + 7 + 9 = 25\n\nInput : 100 2\nOutput : 157\nExplanation : 1 + 3 + 5 + 7 + 9 + 33 + 99 = 157"
},
{
"code": null,
"e": 965,
"s": 899,
"text": "Method 1 : This method is simple. For every number less than n : "
},
{
"code": null,
"e": 1004,
"s": 965,
"text": "Check if it is a palindrome in base 10"
},
{
"code": null,
"e": 1040,
"s": 1004,
"text": "If yes, then convert it into base k"
},
{
"code": null,
"e": 1076,
"s": 1040,
"text": "Check if it is palindrome in base k"
},
{
"code": null,
"e": 1104,
"s": 1076,
"text": "If yes, then add it in sum."
},
{
"code": null,
"e": 1407,
"s": 1104,
"text": "This method is quite lengthy as it checks for every number whether it is a palindrome or not. So, for number as large as 1000000, it checks for every number. If k = 2, then a palindrome in base 2 can only be odd number, which might reduce the comparisons to 1000000 / 2 = 500000 (which is still large)."
},
{
"code": null,
"e": 1461,
"s": 1407,
"text": "Below is the implementation of the above approach : "
},
{
"code": null,
"e": 1465,
"s": 1461,
"text": "C++"
},
{
"code": null,
"e": 1470,
"s": 1465,
"text": "Java"
},
{
"code": null,
"e": 1478,
"s": 1470,
"text": "Python3"
},
{
"code": null,
"e": 1481,
"s": 1478,
"text": "C#"
},
{
"code": null,
"e": 1485,
"s": 1481,
"text": "PHP"
},
{
"code": null,
"e": 1496,
"s": 1485,
"text": "Javascript"
},
{
"code": "// CPP Program for Checking double base// Palindrome.#include <bits/stdc++.h>using namespace std; // converts number to base k by changing// it into string.string integer_to_string(int n, int base){ string str; while (n > 0) { int digit = n % base; n /= base; str.push_back(digit + '0'); } return str;} // function to check for palindromeint isPalindrome(int i, int k){ int temp = i; // m stores reverse of a number int m = 0; while (temp > 0) { m = temp % 10 + m * 10; temp /= 10; } // if reverse is equal to number if (m == i) { // converting to base k string str = integer_to_string(m, k); string str1 = str; // reversing number in base k reverse(str.begin(), str.end()); // checking palindrome in base k if (str == str1) { return i; } } return 0;} // function to find sum of palindromesvoid sumPalindrome(int n, int k){ int sum = 0; for (int i = 1; i < n; i++) { sum += isPalindrome(i, k); } cout << \"Total sum is \" << sum;} // driver functionint main(){ int n = 100; int k = 2; sumPalindrome(n, k); return 0;}",
"e": 2714,
"s": 1496,
"text": null
},
{
"code": "// Java Program for Checking double base// Palindrome.import java.util.*; class GFG{// converts number to base k by changing// it into string.static String integer_to_string(int n, int base){ String str=\"\"; while (n > 0) { int digit = n % base; n /= base; str+=(char)(digit+'0'); } return str;} // function to check for palindromestatic int isPalindrome(int i, int k){ int temp = i; // m stores reverse of a number int m = 0; while (temp > 0) { m = temp % 10 + m * 10; temp /= 10; } // if reverse is equal to number if (m == i) { // converting to base k String str = integer_to_string(m, k); StringBuilder sb = new StringBuilder(str); String str1=sb.reverse().toString(); if (str.equals(str1)) { return i; } } return 0;} // function to find sum of palindromesstatic void sumPalindrome(int n, int k){ int sum = 0; for (int i = 1; i < n; i++) { sum += isPalindrome(i, k); } System.out.println(\"Total sum is \"+sum);} // driver functionpublic static void main(String[] args){ int n = 100; int k = 2; sumPalindrome(n, k);}}// This code is contributed by mits",
"e": 3944,
"s": 2714,
"text": null
},
{
"code": "# Python3 Program for Checking# double base Palindrome. # converts number to base# k by changing it into string.def integer_to_string(n, base): str = \"\"; while (n > 0): digit = n % base; n = int(n / base); str = chr(digit + ord('0')) + str; return str; # function to check for palindromedef isPalindrome(i, k): temp = i; # m stores reverse of a number m = 0; while (temp > 0): m = (temp % 10) + (m * 10); temp = int(temp / 10); # if reverse is equal to number if (m == i): # converting to base k str = integer_to_string(m, k); str1 = str; # reversing number in base k # str=str[::-1]; # checking palindrome # in base k if (str[::-1] == str1): return i; return 0; # function to find sum of palindromesdef sumPalindrome(n, k): sum = 0; for i in range(n): sum += isPalindrome(i, k); print(\"Total sum is\", sum); # Driver coden = 100;k = 2; sumPalindrome(n, k); # This code is contributed# by mits",
"e": 5016,
"s": 3944,
"text": null
},
{
"code": "// C# Program for Checking double base// Palindrome.using System; class GFG{// converts number to base k by changing// it into string.static string integer_to_string(int n, int base1){ string str=\"\"; while (n > 0) { int digit = n % base1; n /= base1; str+=(char)(digit+'0'); } return str;} // function to check for palindromestatic int isPalindrome(int i, int k){ int temp = i; // m stores reverse of a number int m = 0; while (temp > 0) { m = temp % 10 + m * 10; temp /= 10; } // if reverse is equal to number if (m == i) { // converting to base k string str = integer_to_string(m, k); char[] ch = str.ToCharArray(); Array.Reverse(ch); string str1=new String(ch);; if (str.Equals(str1)) { return i; } } return 0;} // function to find sum of palindromesstatic void sumPalindrome(int n, int k){ int sum = 0; for (int i = 1; i < n; i++) { sum += isPalindrome(i, k); } Console.WriteLine(\"Total sum is \"+sum);} // driver function static void Main(){ int n = 100; int k = 2; sumPalindrome(n, k);}}// This code is contributed by mits",
"e": 6227,
"s": 5016,
"text": null
},
{
"code": "<?php// PHP Program for Checking// double base Palindrome. // converts number to base// k by changing it into string.function integer_to_string($n, $base){ $str = \"\"; while ($n > 0) { $digit = $n % $base; $n = (int)($n / $base); $str = ($digit + '0') . $str; } return $str;} // function to check// for palindromefunction isPalindrome($i, $k){ $temp = $i; // m stores reverse // of a number $m = 0; while ($temp > 0) { $m = ($temp % 10) + ($m * 10); $temp = (int)($temp / 10); } // if reverse is // equal to number if ($m == $i) { // converting to base k $str = integer_to_string($m, $k); $str1 = $str; // reversing number in base k // $str=strrev($str); // checking palindrome // in base k if (strcmp(strrev($str), $str1) == 0) { return $i; } } return 0;} // function to find// sum of palindromesfunction sumPalindrome($n, $k){ $sum = 0; for ($i = 0; $i < $n; $i++) { $sum += isPalindrome($i, $k); } echo \"Total sum is \" . $sum;} // Driver code$n = 100;$k = 2; sumPalindrome($n, $k); // This code is contributed// by mits?>",
"e": 7473,
"s": 6227,
"text": null
},
{
"code": "<script> // Javascript program for checking// double base Palindrome. // Converts number to base k by changing// it into string.function integer_to_string(n, base1){ let str=\"\"; while (n > 0) { let digit = n % base1; n = parseInt(n / base1, 10); str += String.fromCharCode(digit + '0'.charCodeAt()); } return str;} // Function to check for palindromefunction isPalindrome(i, k){ let temp = i; // m stores reverse of a number let m = 0; while (temp > 0) { m = temp % 10 + m * 10; temp = parseInt(temp / 10, 10); } // If reverse is equal to number if (m == i) { // Converting to base k let str = integer_to_string(m, k); let ch = str.split(''); ch.reverse(); let str1 = ch.join(\"\"); if (str == str1) { return i; } } return 0;} // Function to find sum of palindromesfunction sumPalindrome(n, k){ let sum = 0; for(let i = 1; i < n; i++) { sum += isPalindrome(i, k); } document.write(\"Total sum is \" + sum + \"</br>\");} // Driver codelet n = 100;let k = 2; sumPalindrome(n, k); // This code is contributed by decode2207 </script>",
"e": 8723,
"s": 7473,
"text": null
},
{
"code": null,
"e": 8732,
"s": 8723,
"text": "Output: "
},
{
"code": null,
"e": 8749,
"s": 8732,
"text": "Total sum is 157"
},
{
"code": null,
"e": 9592,
"s": 8749,
"text": "Method 2 : This method is a little complex to understand but more advance than method 1. Rather than checking palindrome for two bases. This method generates palindrome in given range. Suppose we have a palindrome of the form 123321 in base k, then the first 3 digits define the palindrome. However, the 3 digits 123 also define the palindrome 12321. So the 3-digit number 123 defines a 5-digit palindrome and a 6 digit palindrome. From which follows that every positive number less than kn generates two palindromes less than k2n . This holds for every base k. Example : let’s say k = 10 that is decimal. Then for n = 1, all numbers less than 10n have 2 palindrome, 1 even length and 1 odd length in 102n. These are 1, 11 or 2, 22 or 3, 33 and so on. So, for 1000000 we generate around 2000 and for 108 we generate around 20000 palindromes. "
},
{
"code": null,
"e": 9642,
"s": 9592,
"text": "Start from i=1 and generate odd palindrome of it."
},
{
"code": null,
"e": 9710,
"s": 9642,
"text": "Check if this generated odd palindrome is also palindrome in base k"
},
{
"code": null,
"e": 9747,
"s": 9710,
"text": "If yes, then add this number to sum."
},
{
"code": null,
"e": 9853,
"s": 9747,
"text": "Repeat the above three steps by changing i=i+1 until the last generated odd palindrome has crossed limit."
},
{
"code": null,
"e": 9915,
"s": 9853,
"text": "Now, again start from i=1 and generate even palindrome of it."
},
{
"code": null,
"e": 9984,
"s": 9915,
"text": "Check if this generated even palindrome is also palindrome in base k"
},
{
"code": null,
"e": 10021,
"s": 9984,
"text": "If yes, then add this number to sum."
},
{
"code": null,
"e": 10128,
"s": 10021,
"text": "Repeat the above three steps by changing i=i+1 until the last generated even palindrome has crossed limit."
},
{
"code": null,
"e": 10182,
"s": 10128,
"text": "Below is the implementation of the above approach : "
},
{
"code": null,
"e": 10186,
"s": 10182,
"text": "C++"
},
{
"code": null,
"e": 10191,
"s": 10186,
"text": "Java"
},
{
"code": null,
"e": 10199,
"s": 10191,
"text": "Python3"
},
{
"code": null,
"e": 10202,
"s": 10199,
"text": "C#"
},
{
"code": null,
"e": 10206,
"s": 10202,
"text": "PHP"
},
{
"code": null,
"e": 10217,
"s": 10206,
"text": "Javascript"
},
{
"code": "// CPP Program for Checking double// base Palindrome.#include <bits/stdc++.h>using namespace std; // generates even and odd palindromesint makePalindrome(int n, bool odd){ int res = n; if (odd) n = n / 10; while (n > 0) { res = 10 * res + n % 10; n /= 10; } return res;} // Check if a number is palindrome// in base kbool isPalindrome(int n, int base){ int reversed = 0; int temp = n; while (temp > 0) { reversed = reversed * base + temp % base; temp /= base; } return reversed == n;} // function to print sum of Palindromesvoid sumPalindrome(int n, int k){ int sum = 0, i = 1; int p = makePalindrome(i, true); // loop for odd generation of // odd palindromes while (p < n) { if (isPalindrome(p, k)) sum += p; i++; // cout << p << \" \"; p = makePalindrome(i, true); } i = 1; // loop for generation of // even palindromes p = makePalindrome(i, false); while (p < n) { if (isPalindrome(p, k)) sum += p; i++; p = makePalindrome(i, false); } // result of all palindromes in // both bases. cout << \"Total sum is \" << sum << endl;} // driver codeint main(){ int n = 1000000, k = 2; sumPalindrome(n ,k); return 0;}",
"e": 11571,
"s": 10217,
"text": null
},
{
"code": "// Java Program for Checking double// base Palindrome. public class GFG { // generates even and odd palindromes static int makePalindrome(int n, boolean odd) { int res = n; if (odd) { n = n / 10; } while (n > 0) { res = 10 * res + n % 10; n /= 10; } return res; } // Check if a number is palindrome// in base k static boolean isPalindrome(int n, int base) { int reversed = 0; int temp = n; while (temp > 0) { reversed = reversed * base + temp % base; temp /= base; } return reversed == n; } // function to print sum of Palindromes static void sumPalindrome(int n, int k) { int sum = 0, i = 1; int p = makePalindrome(i, true); // loop for odd generation of // odd palindromes while (p < n) { if (isPalindrome(p, k)) { sum += p; } i++; // cout << p << \" \"; p = makePalindrome(i, true); } i = 1; // loop for generation of // even palindromes p = makePalindrome(i, false); while (p < n) { if (isPalindrome(p, k)) { sum += p; } i++; p = makePalindrome(i, false); } // result of all palindromes in // both bases. System.out.println(\"Total sum is \" + sum); } // driver code public static void main(String[] args) { int n = 1000000, k = 2; sumPalindrome(n, k); }}",
"e": 13158,
"s": 11571,
"text": null
},
{
"code": "# Python3 Program for Checking double# base Palindrome. # Function generates even and# odd palindromesdef makePalindrome(n, odd): res = n; if (odd): n = int(n / 10); while (n > 0): res = 10 * res + n % 10; n = int(n / 10); return res; # Check if a number is palindrome# in base kdef isPalindrome(n, base): reversed = 0; temp = n; while (temp > 0): reversed = reversed * base + temp % base; temp = int(temp / base); return reversed == n; # function to print sum of Palindromesdef sumPalindrome(n, k): sum = 0; i = 1; p = makePalindrome(i, True); # loop for odd generation of # odd palindromes while (p < n): if (isPalindrome(p, k)): sum += p; i += 1; p = makePalindrome(i, True); i = 1; # loop for generation of # even palindromes p = makePalindrome(i, False); while (p < n): if (isPalindrome(p, k)): sum += p; i += 1; p = makePalindrome(i, False); # result of all palindromes in # both bases. print(\"Total sum is\", sum); # Driver coden = 1000000;k = 2;sumPalindrome(n, k); # This code is contributed by mits",
"e": 14344,
"s": 13158,
"text": null
},
{
"code": "// C# Program for Checking double// base1 Palindrome. public class GFG { // generates even and odd palindromes static int makePalindrome(int n, bool odd) { int res = n; if (odd) { n = n / 10; } while (n > 0) { res = 10 * res + n % 10; n /= 10; } return res; } // Check if a number is palindrome// in base1 k static bool isPalindrome(int n, int base1) { int reversed = 0; int temp = n; while (temp > 0) { reversed = reversed * base1 + temp % base1; temp /= base1; } return reversed == n; } // function to print sum of Palindromes static void sumPalindrome(int n, int k) { int sum = 0, i = 1; int p = makePalindrome(i, true); // loop for odd generation of // odd palindromes while (p < n) { if (isPalindrome(p, k)) { sum += p; } i++; p = makePalindrome(i, true); } i = 1; // loop for generation of // even palindromes p = makePalindrome(i, false); while (p < n) { if (isPalindrome(p, k)) { sum += p; } i++; p = makePalindrome(i, false); } // result of all palindromes in // both base1s. System.Console.WriteLine(\"Total sum is \" + sum); } // driver code public static void Main() { int n = 1000000, k = 2; sumPalindrome(n, k); }} // This code is contributed by mits",
"e": 15908,
"s": 14344,
"text": null
},
{
"code": "<?php// PHP Program for Checking double// base Palindrome. // Function generates even and// odd palindromesfunction makePalindrome($n, $odd){ $res = $n; if ($odd) { $n = (int)($n / 10); } while ($n > 0) { $res = 10 * $res + $n % 10; $n = (int)($n / 10); } return $res;} // Check if a number is palindrome// in base kfunction isPalindrome($n, $base){ $reversed = 0; $temp = $n; while ($temp > 0) { $reversed = $reversed * $base + $temp % $base; $temp = (int)($temp / $base); } return $reversed == $n;} // function to print sum of Palindromesfunction sumPalindrome($n, $k){ $sum = 0; $i = 1; $p = makePalindrome($i, true); // loop for odd generation of // odd palindromes while ($p < $n) { if (isPalindrome($p, $k)) { $sum += $p; } $i++; $p = makePalindrome($i, true); } $i = 1; // loop for generation of // even palindromes $p = makePalindrome($i, false); while ($p < $n) { if (isPalindrome($p, $k)) { $sum += $p; } $i++; $p = makePalindrome($i, false); } // result of all palindromes in // both bases. echo(\"Total sum is \" . $sum);} // Driver code$n = 1000000; $k = 2;sumPalindrome($n, $k); // This code is contributed// by Mukul Singh.?>",
"e": 17296,
"s": 15908,
"text": null
},
{
"code": "<script>// javascript Program for Checking var// base Palindrome. // generates even and odd palindromes function makePalindrome(n, odd) { var res = n; if (odd) { n = parseInt(n / 10); } while (n > 0) { res = 10 * res + n % 10; n = parseInt(n / 10); } return res; } // Check if a number is palindrome// in base k function isPalindrome(n , base) { var reversed = 0; var temp = n; while (temp > 0) { reversed = reversed * base + temp % base; temp = parseInt(temp/base); } return reversed == n; } // function to print sum of Palindromes function sumPalindrome(n , k) { var sum = 0, i = 1; var p = makePalindrome(i, true); // loop for odd generation of // odd palindromes while (p < n) { if (isPalindrome(p, k)) { sum += p; } i++; // cout << p << \" \"; p = makePalindrome(i, true); } i = 1; // loop for generation of // even palindromes p = makePalindrome(i, false); while (p < n) { if (isPalindrome(p, k)) { sum += p; } i++; p = makePalindrome(i, false); } // result of all palindromes in // both bases. document.write(\"Total sum is \" + sum); } // driver codevar n = 1000000, k = 2;sumPalindrome(n, k); // This code contributed by Princi Singh</script>",
"e": 18854,
"s": 17296,
"text": null
},
{
"code": null,
"e": 18863,
"s": 18854,
"text": "Output: "
},
{
"code": null,
"e": 18884,
"s": 18863,
"text": "Total sum is 872187 "
},
{
"code": null,
"e": 19305,
"s": 18884,
"text": "This article is contributed by Shubham Rana. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. "
},
{
"code": null,
"e": 19318,
"s": 19305,
"text": "Mithun Kumar"
},
{
"code": null,
"e": 19330,
"s": 19318,
"text": "29AjayKumar"
},
{
"code": null,
"e": 19340,
"s": 19330,
"text": "Code_Mech"
},
{
"code": null,
"e": 19353,
"s": 19340,
"text": "princi singh"
},
{
"code": null,
"e": 19364,
"s": 19353,
"text": "decode2207"
},
{
"code": null,
"e": 19381,
"s": 19364,
"text": "arorakashish0911"
},
{
"code": null,
"e": 19398,
"s": 19381,
"text": "surinderdawra388"
},
{
"code": null,
"e": 19414,
"s": 19398,
"text": "base-conversion"
},
{
"code": null,
"e": 19425,
"s": 19414,
"text": "palindrome"
},
{
"code": null,
"e": 19438,
"s": 19425,
"text": "Mathematical"
},
{
"code": null,
"e": 19451,
"s": 19438,
"text": "Mathematical"
},
{
"code": null,
"e": 19462,
"s": 19451,
"text": "palindrome"
}
] |
Program to find the Depreciation of Value
|
28 May, 2022
The value of any article or item subject to wear and tear, decreases with time. This decrease is called its Depreciation. Given three variable V1, R and T where V1 is the initial value, R is the rate of depreciation and T is the time in years. The task is to find the value of the item after T years.Examples:
Input: V1 = 200, R = 10, T = 2 Output: 162Input: V1 = 560, R = 5, T = 3 Output: 480.13
Approach: As in Compound Interest, interest is regularly added to the principal at the end of the agreed intervals of time to generate a new and fresh principal. Similarly, Depreciated value is the decreased value from the amount at the end of agreed intervals of time to generate a new Value.Thus if V1 is the value at a certain time and R% per annum is the rate (the rate can not be more than 100%) of depreciation per year, then the value V2 at the end of T years is:
Below is the implementation of the above approach :
C++
Java
Python3
C#
Javascript
// CPP program to find depreciation of the value// initial value, rate and time are given#include <bits/stdc++.h>using namespace std; // Function to return the depreciation of valuefloat Depreciation(float v, float r, float t){ float D = v * pow((1 - r / 100), t); return D;} // Driver Codeint main(){ float V1 = 200, R = 10, T = 2; cout << Depreciation(V1, R, T); return 0;}
// Java program to find depreciation of the value// initial value, rate and time are givenimport java.io.*; class GFG{ // Function to return the depreciation of valuestatic float Depreciation(float v, float r, float t){ float D = (float)(v * Math.pow((1 - r / 100), t)); return D;} // Driver codepublic static void main(String[] args){ float V1 = 200, R = 10, T = 2; System.out.print(Depreciation(V1, R, T));}} // This code is contributed by anuj_67..
# Python 3 program to find depreciation of the value# initial value, rate and time are givenfrom math import pow # Function to return the depreciation of valuedef Depreciation(v, r, t): D = v * pow((1 - r / 100), t) return D # Driver Codeif __name__ == '__main__': V1 = 200 R = 10 T = 2 print(int(Depreciation(V1, R, T))) # This code is contributed by# Surendra_Gangwar
// C# program to find depreciation of the value// initial value, rate and time are givenusing System; class GFG{ // Function to return the depreciation of valuestatic float Depreciation(float v, float r, float t){ float D = (float) (v * Math.Pow((1 - r / 100), t)); return D;} // Driver codepublic static void Main(){ float V1 = 200, R = 10, T = 2; Console.WriteLine(Depreciation(V1, R, T));}} // This code is contributed by nidhiva
// javascript program to find depreciation of the value// initial value, rate and time are given // Function to return the depreciation of value function Depreciation( v, r, t){ var D = v * Math.pow((1 - r / 100), t) return D;} // Driver code var V1 = 200, R = 10, T = 2; document.write(Depreciation(V1, R, T)); // This code is contributed by bunnyram19.
162
Time Complexity: O(1)
Auxiliary Space: O(1)
nidhiva
vt_m
SURENDRA_GANGWAR
bunnyram19
subhammahato348
Compound Interest
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.
Segment Tree | Set 1 (Sum of given range)
Check if a number is Palindrome
Count ways to reach the n'th stair
Fizz Buzz Implementation
Median of two sorted arrays of same size
Sum of the series (1*2) + (2*3) + (3*4) + ...... upto n terms
Product of Array except itself
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n28 May, 2022"
},
{
"code": null,
"e": 340,
"s": 28,
"text": "The value of any article or item subject to wear and tear, decreases with time. This decrease is called its Depreciation. Given three variable V1, R and T where V1 is the initial value, R is the rate of depreciation and T is the time in years. The task is to find the value of the item after T years.Examples: "
},
{
"code": null,
"e": 429,
"s": 340,
"text": "Input: V1 = 200, R = 10, T = 2 Output: 162Input: V1 = 560, R = 5, T = 3 Output: 480.13 "
},
{
"code": null,
"e": 904,
"s": 431,
"text": "Approach: As in Compound Interest, interest is regularly added to the principal at the end of the agreed intervals of time to generate a new and fresh principal. Similarly, Depreciated value is the decreased value from the amount at the end of agreed intervals of time to generate a new Value.Thus if V1 is the value at a certain time and R% per annum is the rate (the rate can not be more than 100%) of depreciation per year, then the value V2 at the end of T years is: "
},
{
"code": null,
"e": 958,
"s": 904,
"text": "Below is the implementation of the above approach : "
},
{
"code": null,
"e": 962,
"s": 958,
"text": "C++"
},
{
"code": null,
"e": 967,
"s": 962,
"text": "Java"
},
{
"code": null,
"e": 975,
"s": 967,
"text": "Python3"
},
{
"code": null,
"e": 978,
"s": 975,
"text": "C#"
},
{
"code": null,
"e": 989,
"s": 978,
"text": "Javascript"
},
{
"code": "// CPP program to find depreciation of the value// initial value, rate and time are given#include <bits/stdc++.h>using namespace std; // Function to return the depreciation of valuefloat Depreciation(float v, float r, float t){ float D = v * pow((1 - r / 100), t); return D;} // Driver Codeint main(){ float V1 = 200, R = 10, T = 2; cout << Depreciation(V1, R, T); return 0;}",
"e": 1384,
"s": 989,
"text": null
},
{
"code": "// Java program to find depreciation of the value// initial value, rate and time are givenimport java.io.*; class GFG{ // Function to return the depreciation of valuestatic float Depreciation(float v, float r, float t){ float D = (float)(v * Math.pow((1 - r / 100), t)); return D;} // Driver codepublic static void main(String[] args){ float V1 = 200, R = 10, T = 2; System.out.print(Depreciation(V1, R, T));}} // This code is contributed by anuj_67..",
"e": 1879,
"s": 1384,
"text": null
},
{
"code": "# Python 3 program to find depreciation of the value# initial value, rate and time are givenfrom math import pow # Function to return the depreciation of valuedef Depreciation(v, r, t): D = v * pow((1 - r / 100), t) return D # Driver Codeif __name__ == '__main__': V1 = 200 R = 10 T = 2 print(int(Depreciation(V1, R, T))) # This code is contributed by# Surendra_Gangwar",
"e": 2269,
"s": 1879,
"text": null
},
{
"code": "// C# program to find depreciation of the value// initial value, rate and time are givenusing System; class GFG{ // Function to return the depreciation of valuestatic float Depreciation(float v, float r, float t){ float D = (float) (v * Math.Pow((1 - r / 100), t)); return D;} // Driver codepublic static void Main(){ float V1 = 200, R = 10, T = 2; Console.WriteLine(Depreciation(V1, R, T));}} // This code is contributed by nidhiva",
"e": 2721,
"s": 2269,
"text": null
},
{
"code": "// javascript program to find depreciation of the value// initial value, rate and time are given // Function to return the depreciation of value function Depreciation( v, r, t){ var D = v * Math.pow((1 - r / 100), t) return D;} // Driver code var V1 = 200, R = 10, T = 2; document.write(Depreciation(V1, R, T)); // This code is contributed by bunnyram19. ",
"e": 3099,
"s": 2721,
"text": null
},
{
"code": null,
"e": 3103,
"s": 3099,
"text": "162"
},
{
"code": null,
"e": 3127,
"s": 3105,
"text": "Time Complexity: O(1)"
},
{
"code": null,
"e": 3149,
"s": 3127,
"text": "Auxiliary Space: O(1)"
},
{
"code": null,
"e": 3157,
"s": 3149,
"text": "nidhiva"
},
{
"code": null,
"e": 3162,
"s": 3157,
"text": "vt_m"
},
{
"code": null,
"e": 3179,
"s": 3162,
"text": "SURENDRA_GANGWAR"
},
{
"code": null,
"e": 3190,
"s": 3179,
"text": "bunnyram19"
},
{
"code": null,
"e": 3206,
"s": 3190,
"text": "subhammahato348"
},
{
"code": null,
"e": 3224,
"s": 3206,
"text": "Compound Interest"
},
{
"code": null,
"e": 3237,
"s": 3224,
"text": "Mathematical"
},
{
"code": null,
"e": 3250,
"s": 3237,
"text": "Mathematical"
},
{
"code": null,
"e": 3348,
"s": 3250,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 3380,
"s": 3348,
"text": "Algorithm to solve Rubik's Cube"
},
{
"code": null,
"e": 3426,
"s": 3380,
"text": "Merge two sorted arrays with O(1) extra space"
},
{
"code": null,
"e": 3470,
"s": 3426,
"text": "Program to print prime numbers from 1 to N."
},
{
"code": null,
"e": 3512,
"s": 3470,
"text": "Segment Tree | Set 1 (Sum of given range)"
},
{
"code": null,
"e": 3544,
"s": 3512,
"text": "Check if a number is Palindrome"
},
{
"code": null,
"e": 3579,
"s": 3544,
"text": "Count ways to reach the n'th stair"
},
{
"code": null,
"e": 3604,
"s": 3579,
"text": "Fizz Buzz Implementation"
},
{
"code": null,
"e": 3645,
"s": 3604,
"text": "Median of two sorted arrays of same size"
},
{
"code": null,
"e": 3707,
"s": 3645,
"text": "Sum of the series (1*2) + (2*3) + (3*4) + ...... upto n terms"
}
] |
Custom Field Validations in Django Forms
|
16 Mar, 2021
This article revolves around how to add custom validation to a particular field. For example to add validation of an email to a CharField by specifying a particular format. There can be multiple ways on how to achieve custom validation. In this article, we are going to show it from the form itself so that you need not manipulate it elsewhere.
A validator is a callable that takes a value and raises a ValidationError if it doesn’t meet criteria. Validators can be useful for re-using validation logic between different types of fields.
Django Custom Field Validation Explanation for Django Forms
Illustration of validators 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 ?
To use built-in Validators in your forms field, import validators in forms.py like this.
Python3
from django import formsfrom django.core import validators class StuForm(forms.Form): name = forms.CharField( validators =[validators.MaxLengthValidator(10)])
call built-in MaxLengthValidators from validators, it raises validation error if the length of the value is greater than limit_value.
How to create our custom validators in django ?
So we are going to create our own custom validators.
Example 1 :-
We will create a validator, if name is not start with s it will raise a an error.
forms.py
Python3
from django import forms def start_with_s(value): if value[0]!='s': raise forms.ValidationError("Name should start with s") class StuForm(forms.Form): name = forms.CharField( validators =[start_with_s])
Pass the function in validators.
We write a logic if a name doesn’t start with ‘s’ it raise an error and wrap in function.
Example 2 :-
We will create a validator for a mobile number field
Python3
from django import forms def mobile_no(value): mobile = str(value) if len(mobile) != 10: raise forms.ValidationError("Mobile Number Should 10 digit") class StuForm(forms.Form): mob = forms.IntegerField( validators =[mobile_no])
We write a logic of mobile number validator it raise an error and wrap in function
Django-forms
Python Django
Python Framework
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
Python | os.path.join() method
How to drop one or multiple columns in Pandas Dataframe
How To Convert Python Dictionary To JSON?
Check if element exists in list in Python
Python | Get unique values from a list
Python | datetime.timedelta() function
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n16 Mar, 2021"
},
{
"code": null,
"e": 373,
"s": 28,
"text": "This article revolves around how to add custom validation to a particular field. For example to add validation of an email to a CharField by specifying a particular format. There can be multiple ways on how to achieve custom validation. In this article, we are going to show it from the form itself so that you need not manipulate it elsewhere."
},
{
"code": null,
"e": 566,
"s": 373,
"text": "A validator is a callable that takes a value and raises a ValidationError if it doesn’t meet criteria. Validators can be useful for re-using validation logic between different types of fields."
},
{
"code": null,
"e": 626,
"s": 566,
"text": "Django Custom Field Validation Explanation for Django Forms"
},
{
"code": null,
"e": 737,
"s": 626,
"text": "Illustration of validators using an Example. Consider a project named geeksforgeeks having an app named geeks."
},
{
"code": null,
"e": 824,
"s": 737,
"text": "Refer to the following articles to check how to create a project and an app in Django."
},
{
"code": null,
"e": 875,
"s": 824,
"text": "How to Create a Basic Project using MVT in Django?"
},
{
"code": null,
"e": 908,
"s": 875,
"text": "How to Create an App in Django ?"
},
{
"code": null,
"e": 997,
"s": 908,
"text": "To use built-in Validators in your forms field, import validators in forms.py like this."
},
{
"code": null,
"e": 1005,
"s": 997,
"text": "Python3"
},
{
"code": "from django import formsfrom django.core import validators class StuForm(forms.Form): name = forms.CharField( validators =[validators.MaxLengthValidator(10)])",
"e": 1169,
"s": 1005,
"text": null
},
{
"code": null,
"e": 1303,
"s": 1169,
"text": "call built-in MaxLengthValidators from validators, it raises validation error if the length of the value is greater than limit_value."
},
{
"code": null,
"e": 1351,
"s": 1303,
"text": "How to create our custom validators in django ?"
},
{
"code": null,
"e": 1404,
"s": 1351,
"text": "So we are going to create our own custom validators."
},
{
"code": null,
"e": 1417,
"s": 1404,
"text": "Example 1 :-"
},
{
"code": null,
"e": 1499,
"s": 1417,
"text": "We will create a validator, if name is not start with s it will raise a an error."
},
{
"code": null,
"e": 1508,
"s": 1499,
"text": "forms.py"
},
{
"code": null,
"e": 1516,
"s": 1508,
"text": "Python3"
},
{
"code": "from django import forms def start_with_s(value): if value[0]!='s': raise forms.ValidationError(\"Name should start with s\") class StuForm(forms.Form): name = forms.CharField( validators =[start_with_s])",
"e": 1731,
"s": 1516,
"text": null
},
{
"code": null,
"e": 1764,
"s": 1731,
"text": "Pass the function in validators."
},
{
"code": null,
"e": 1854,
"s": 1764,
"text": "We write a logic if a name doesn’t start with ‘s’ it raise an error and wrap in function."
},
{
"code": null,
"e": 1867,
"s": 1854,
"text": "Example 2 :-"
},
{
"code": null,
"e": 1920,
"s": 1867,
"text": "We will create a validator for a mobile number field"
},
{
"code": null,
"e": 1928,
"s": 1920,
"text": "Python3"
},
{
"code": "from django import forms def mobile_no(value): mobile = str(value) if len(mobile) != 10: raise forms.ValidationError(\"Mobile Number Should 10 digit\") class StuForm(forms.Form): mob = forms.IntegerField( validators =[mobile_no])",
"e": 2169,
"s": 1928,
"text": null
},
{
"code": null,
"e": 2252,
"s": 2169,
"text": "We write a logic of mobile number validator it raise an error and wrap in function"
},
{
"code": null,
"e": 2265,
"s": 2252,
"text": "Django-forms"
},
{
"code": null,
"e": 2279,
"s": 2265,
"text": "Python Django"
},
{
"code": null,
"e": 2296,
"s": 2279,
"text": "Python Framework"
},
{
"code": null,
"e": 2303,
"s": 2296,
"text": "Python"
},
{
"code": null,
"e": 2401,
"s": 2303,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 2433,
"s": 2401,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 2460,
"s": 2433,
"text": "Python Classes and Objects"
},
{
"code": null,
"e": 2481,
"s": 2460,
"text": "Python OOPs Concepts"
},
{
"code": null,
"e": 2504,
"s": 2481,
"text": "Introduction To PYTHON"
},
{
"code": null,
"e": 2535,
"s": 2504,
"text": "Python | os.path.join() method"
},
{
"code": null,
"e": 2591,
"s": 2535,
"text": "How to drop one or multiple columns in Pandas Dataframe"
},
{
"code": null,
"e": 2633,
"s": 2591,
"text": "How To Convert Python Dictionary To JSON?"
},
{
"code": null,
"e": 2675,
"s": 2633,
"text": "Check if element exists in list in Python"
},
{
"code": null,
"e": 2714,
"s": 2675,
"text": "Python | Get unique values from a list"
}
] |
NLP | Word Collocations
|
28 Jan, 2019
Collocations are two or more words that tend to appear frequently together, for example – United States. There are many other words that can come after United, such as the United Kingdom and United Airlines. As with many aspects of natural language processing, context is very important. And for collocations, context is everything.In the case of collocations, the context will be a document in the form of a list of words. Discovering collocations in this list of words means to find common phrases that occur frequently throughout the text.
Link to DATA – Monty Python and the Holy Grail script
Code #1 : Loading Libraries
from nltk.corpus import webtext # use to find bigrams, which are pairs of wordsfrom nltk.collocations import BigramCollocationFinderfrom nltk.metrics import BigramAssocMeasures
Code #2 : Let’s find the collocations
# Loading the data words = [w.lower() for w in webtext.words( 'C:\\Geeksforgeeks\\python_and_grail.txt')] biagram_collocation = BigramCollocationFinder.from_words(words)biagram_collocation.nbest(BigramAssocMeasures.likelihood_ratio, 15)
Output :
[("'", 's'),
('arthur', ':'),
('#', '1'),
("'", 't'),
('villager', '#'),
('#', '2'),
(']', '['),
('1', ':'),
('oh', ', '),
('black', 'knight'),
('ha', 'ha'),
(':', 'oh'),
("'", 're'),
('galahad', ':'),
('well', ', ')]
As we can see in the code above finding colocations in this way is not very useful. So, the code below is a refined version by adding a word filter to remove punctuation and stopwords. Code #3 :
from nltk.corpus import stopwords stopset = set(stopwords.words('english'))filter_stops = lambda w: len(w) < 3 or w in stopset biagram_collocation.apply_word_filter(filter_stops)biagram_collocation.nbest(BigramAssocMeasures.likelihood_ratio, 15)
Output :
[('black', 'knight'),
('clop', 'clop'),
('head', 'knight'),
('mumble', 'mumble'),
('squeak', 'squeak'),
('saw', 'saw'),
('holy', 'grail'),
('run', 'away'),
('french', 'guard'),
('cartoon', 'character'),
('iesu', 'domine'),
('pie', 'iesu'),
('round', 'table'),
('sir', 'robin'),
('clap', 'clap')]
How it works in the code?
BigramCollocationFinder constructs two frequency distributions:one for each wordanother for bigrams.
one for each word
another for bigrams.
A frequency distribution is basically an enhanced Python dictionary where the keys are what’s being counted, and the values are the counts.
Any filtering functions reduces the size by eliminating any words that don’t pass the filter
Using a filtering function to eliminate all words that are one or two characters, and all English stopwords, results in a much cleaner result.
After filtering, the collocation finder is ready for finding collocations.
Code #4 : Working on triplets instead of pairs.
# Loading Librariesfrom nltk.collocations import TrigramCollocationFinderfrom nltk.metrics import TrigramAssocMeasures # Loading data - text filewords = [w.lower() for w in webtext.words( 'C:\Geeksforgeeks\\python_and_grail.txt')] trigram_collocation = TrigramCollocationFinder.from_words(words)trigram_collocation.apply_word_filter(filter_stops)trigram_collocation.apply_freq_filter(3) trigram_collocation.nbest(TrigramAssocMeasures.likelihood_ratio, 15)
Output :
[('clop', 'clop', 'clop'),
('mumble', 'mumble', 'mumble'),
('squeak', 'squeak', 'squeak'),
('saw', 'saw', 'saw'),
('pie', 'iesu', 'domine'),
('clap', 'clap', 'clap'),
('dona', 'eis', 'requiem'),
('brave', 'sir', 'robin'),
('heh', 'heh', 'heh'),
('king', 'arthur', 'music'),
('hee', 'hee', 'hee'),
('holy', 'hand', 'grenade'),
('boom', 'boom', 'boom'),
('...', 'dona', 'eis'),
('already', 'got', 'one')]
Natural-language-processing
Python-nltk
Machine Learning
Python
Machine Learning
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
ML | Linear Regression
ML | Monte Carlo Tree Search (MCTS)
Introduction to Recurrent Neural Network
Getting started with Machine Learning
Markov Decision Process
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": 28,
"s": 0,
"text": "\n28 Jan, 2019"
},
{
"code": null,
"e": 571,
"s": 28,
"text": "Collocations are two or more words that tend to appear frequently together, for example – United States. There are many other words that can come after United, such as the United Kingdom and United Airlines. As with many aspects of natural language processing, context is very important. And for collocations, context is everything.In the case of collocations, the context will be a document in the form of a list of words. Discovering collocations in this list of words means to find common phrases that occur frequently throughout the text."
},
{
"code": null,
"e": 625,
"s": 571,
"text": "Link to DATA – Monty Python and the Holy Grail script"
},
{
"code": null,
"e": 653,
"s": 625,
"text": "Code #1 : Loading Libraries"
},
{
"code": "from nltk.corpus import webtext # use to find bigrams, which are pairs of wordsfrom nltk.collocations import BigramCollocationFinderfrom nltk.metrics import BigramAssocMeasures",
"e": 831,
"s": 653,
"text": null
},
{
"code": null,
"e": 870,
"s": 831,
"text": " Code #2 : Let’s find the collocations"
},
{
"code": "# Loading the data words = [w.lower() for w in webtext.words( 'C:\\\\Geeksforgeeks\\\\python_and_grail.txt')] biagram_collocation = BigramCollocationFinder.from_words(words)biagram_collocation.nbest(BigramAssocMeasures.likelihood_ratio, 15)",
"e": 1111,
"s": 870,
"text": null
},
{
"code": null,
"e": 1120,
"s": 1111,
"text": "Output :"
},
{
"code": null,
"e": 1353,
"s": 1120,
"text": "[(\"'\", 's'),\n ('arthur', ':'),\n ('#', '1'),\n (\"'\", 't'),\n ('villager', '#'),\n ('#', '2'),\n (']', '['),\n ('1', ':'),\n ('oh', ', '),\n ('black', 'knight'),\n ('ha', 'ha'),\n (':', 'oh'),\n (\"'\", 're'),\n ('galahad', ':'),\n ('well', ', ')]\n"
},
{
"code": null,
"e": 1548,
"s": 1353,
"text": "As we can see in the code above finding colocations in this way is not very useful. So, the code below is a refined version by adding a word filter to remove punctuation and stopwords. Code #3 :"
},
{
"code": "from nltk.corpus import stopwords stopset = set(stopwords.words('english'))filter_stops = lambda w: len(w) < 3 or w in stopset biagram_collocation.apply_word_filter(filter_stops)biagram_collocation.nbest(BigramAssocMeasures.likelihood_ratio, 15)",
"e": 1796,
"s": 1548,
"text": null
},
{
"code": null,
"e": 1805,
"s": 1796,
"text": "Output :"
},
{
"code": null,
"e": 2116,
"s": 1805,
"text": "[('black', 'knight'),\n ('clop', 'clop'),\n ('head', 'knight'),\n ('mumble', 'mumble'),\n ('squeak', 'squeak'),\n ('saw', 'saw'),\n ('holy', 'grail'),\n ('run', 'away'),\n ('french', 'guard'),\n ('cartoon', 'character'),\n ('iesu', 'domine'),\n ('pie', 'iesu'),\n ('round', 'table'),\n ('sir', 'robin'),\n ('clap', 'clap')]\n"
},
{
"code": null,
"e": 2142,
"s": 2116,
"text": "How it works in the code?"
},
{
"code": null,
"e": 2243,
"s": 2142,
"text": "BigramCollocationFinder constructs two frequency distributions:one for each wordanother for bigrams."
},
{
"code": null,
"e": 2261,
"s": 2243,
"text": "one for each word"
},
{
"code": null,
"e": 2282,
"s": 2261,
"text": "another for bigrams."
},
{
"code": null,
"e": 2422,
"s": 2282,
"text": "A frequency distribution is basically an enhanced Python dictionary where the keys are what’s being counted, and the values are the counts."
},
{
"code": null,
"e": 2515,
"s": 2422,
"text": "Any filtering functions reduces the size by eliminating any words that don’t pass the filter"
},
{
"code": null,
"e": 2658,
"s": 2515,
"text": "Using a filtering function to eliminate all words that are one or two characters, and all English stopwords, results in a much cleaner result."
},
{
"code": null,
"e": 2733,
"s": 2658,
"text": "After filtering, the collocation finder is ready for finding collocations."
},
{
"code": null,
"e": 2781,
"s": 2733,
"text": "Code #4 : Working on triplets instead of pairs."
},
{
"code": "# Loading Librariesfrom nltk.collocations import TrigramCollocationFinderfrom nltk.metrics import TrigramAssocMeasures # Loading data - text filewords = [w.lower() for w in webtext.words( 'C:\\Geeksforgeeks\\\\python_and_grail.txt')] trigram_collocation = TrigramCollocationFinder.from_words(words)trigram_collocation.apply_word_filter(filter_stops)trigram_collocation.apply_freq_filter(3) trigram_collocation.nbest(TrigramAssocMeasures.likelihood_ratio, 15)",
"e": 3243,
"s": 2781,
"text": null
},
{
"code": null,
"e": 3252,
"s": 3243,
"text": "Output :"
},
{
"code": null,
"e": 3671,
"s": 3252,
"text": "[('clop', 'clop', 'clop'),\n ('mumble', 'mumble', 'mumble'),\n ('squeak', 'squeak', 'squeak'),\n ('saw', 'saw', 'saw'),\n ('pie', 'iesu', 'domine'),\n ('clap', 'clap', 'clap'),\n ('dona', 'eis', 'requiem'),\n ('brave', 'sir', 'robin'),\n ('heh', 'heh', 'heh'),\n ('king', 'arthur', 'music'),\n ('hee', 'hee', 'hee'),\n ('holy', 'hand', 'grenade'),\n ('boom', 'boom', 'boom'),\n ('...', 'dona', 'eis'),\n ('already', 'got', 'one')]\n\n"
},
{
"code": null,
"e": 3699,
"s": 3671,
"text": "Natural-language-processing"
},
{
"code": null,
"e": 3711,
"s": 3699,
"text": "Python-nltk"
},
{
"code": null,
"e": 3728,
"s": 3711,
"text": "Machine Learning"
},
{
"code": null,
"e": 3735,
"s": 3728,
"text": "Python"
},
{
"code": null,
"e": 3752,
"s": 3735,
"text": "Machine Learning"
},
{
"code": null,
"e": 3850,
"s": 3752,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 3873,
"s": 3850,
"text": "ML | Linear Regression"
},
{
"code": null,
"e": 3909,
"s": 3873,
"text": "ML | Monte Carlo Tree Search (MCTS)"
},
{
"code": null,
"e": 3950,
"s": 3909,
"text": "Introduction to Recurrent Neural Network"
},
{
"code": null,
"e": 3988,
"s": 3950,
"text": "Getting started with Machine Learning"
},
{
"code": null,
"e": 4012,
"s": 3988,
"text": "Markov Decision Process"
},
{
"code": null,
"e": 4040,
"s": 4012,
"text": "Read JSON file using Python"
},
{
"code": null,
"e": 4090,
"s": 4040,
"text": "Adding new column to existing DataFrame in Pandas"
},
{
"code": null,
"e": 4112,
"s": 4090,
"text": "Python map() function"
}
] |
PHP get_browser() Function
|
03 Dec, 2021
In this article, we will know to check whether the user’s browser capability using the get_browser() function in PHP, along with understanding its implementation through the example. The get_browser() function in PHP is an inbuilt function that is used to tell the user about the browser’s capabilities. This function looks up the user’s browscap.ini file and returns the capabilities of the user’s browser. The user_agent and the return_array are passed as parameters to the get_browser() function and it returns an object or an array with information about the user’s browser on success, or FALSE on failure.
Syntax:
get_browser(user_agent, return_array)
Parameters Used: The get_browser() function in PHP accepts two parameters:
user_agent: It is an optional parameter that specifies the name of an HTTP user agent. Default is the value of $HTTP_USER_AGENT.
return_array: It is an optional parameter that returns an array instead of an object if it is set to True.
Return Value: It returns an object or an array with information about the user’s browser on success, or FALSE on failure.
Exceptions:
The user_agent parameter can be bypassed with a NULL value.
The cookies value simply means that the browser itself is capable of accepting cookies and does not mean the user has enabled the browser to accept cookies or not.
In order for this function to work the browscap configuration setting in php.ini must point to the correct location of the browscap.ini file on your system.
Approach: For checking the browser capability of the users’ system & acknowledging them accordingly, we will be using the get_browser() function that contains the 2 parameters namely, user_agent that will be utilized to specify the name of an HTTP user agent, & the second parameter is return_array that will return an array instead of an object if the value is set to true.
Example 1: The below example illustrate the get_browser() function that will display the user’s browser capability.
PHP
<?php echo $_SERVER['HTTP_USER_AGENT']; // Using get_browser() to display // capabilities of the user browser $mybrowser = get_browser(); print_r($mybrowser);?>
Output:
[parent] => IE 6.0
[platform] => WinXP
[netclr] => 1
[browser] => IE
[version] => 6
[majorver] => 6
[minorver] => 0
=> 2
[frames] => 1
[iframes] => 1
Example 2: The below example illustrate the get_browser() function with the return array that is set to true.
PHP
<?php echo $_SERVER['HTTP_USER_AGENT']; // Using get_browser() with return_array set to TRUE $mybrowser = get_browser(null, true); print_r($mybrowser);?>
Output:
Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.7) Gecko/20040803 Firefox/0.9.3
Array
(
[browser_name_regex] => ^mozilla/5\.0 (windows; .;
windows nt 5\.1; .*rv:.*) gecko/.* firefox/0\.9.*$
[browser_name_pattern] => Mozilla/5.0 (Windows; ?;
Windows NT 5.1; *rv:*) Gecko/* Firefox/0.9*
[parent] => Firefox 0.9
[platform] => WinXP
[browser] => Firefox
[version] => 0.9
[majorver] => 0
[minorver] => 9
[cssversion] => 2
[frames] => 1
[iframes] => 1
[tables] => 1
[cookies] => 1
=> 1
[javaapplets] => 1
[activexcontrols] =>
[beta] => 1
)
Reference: http://php.net/manual/en/function.get-browser.php
bhaskargeeksforgeeks
PHP-function
PHP
Web Technologies
PHP
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Insert Form Data into Database using PHP ?
How to convert array to string in PHP ?
How to check whether an array is empty using PHP?
PHP | Converting string to Date and DateTime
Comparing two dates in PHP
Top 10 Projects For Beginners To Practice HTML and CSS Skills
Installation of Node.js on Linux
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": "\n03 Dec, 2021"
},
{
"code": null,
"e": 639,
"s": 28,
"text": "In this article, we will know to check whether the user’s browser capability using the get_browser() function in PHP, along with understanding its implementation through the example. The get_browser() function in PHP is an inbuilt function that is used to tell the user about the browser’s capabilities. This function looks up the user’s browscap.ini file and returns the capabilities of the user’s browser. The user_agent and the return_array are passed as parameters to the get_browser() function and it returns an object or an array with information about the user’s browser on success, or FALSE on failure."
},
{
"code": null,
"e": 647,
"s": 639,
"text": "Syntax:"
},
{
"code": null,
"e": 685,
"s": 647,
"text": "get_browser(user_agent, return_array)"
},
{
"code": null,
"e": 760,
"s": 685,
"text": "Parameters Used: The get_browser() function in PHP accepts two parameters:"
},
{
"code": null,
"e": 889,
"s": 760,
"text": "user_agent: It is an optional parameter that specifies the name of an HTTP user agent. Default is the value of $HTTP_USER_AGENT."
},
{
"code": null,
"e": 996,
"s": 889,
"text": "return_array: It is an optional parameter that returns an array instead of an object if it is set to True."
},
{
"code": null,
"e": 1118,
"s": 996,
"text": "Return Value: It returns an object or an array with information about the user’s browser on success, or FALSE on failure."
},
{
"code": null,
"e": 1130,
"s": 1118,
"text": "Exceptions:"
},
{
"code": null,
"e": 1190,
"s": 1130,
"text": "The user_agent parameter can be bypassed with a NULL value."
},
{
"code": null,
"e": 1354,
"s": 1190,
"text": "The cookies value simply means that the browser itself is capable of accepting cookies and does not mean the user has enabled the browser to accept cookies or not."
},
{
"code": null,
"e": 1511,
"s": 1354,
"text": "In order for this function to work the browscap configuration setting in php.ini must point to the correct location of the browscap.ini file on your system."
},
{
"code": null,
"e": 1887,
"s": 1511,
"text": "Approach: For checking the browser capability of the users’ system & acknowledging them accordingly, we will be using the get_browser() function that contains the 2 parameters namely, user_agent that will be utilized to specify the name of an HTTP user agent, & the second parameter is return_array that will return an array instead of an object if the value is set to true."
},
{
"code": null,
"e": 2003,
"s": 1887,
"text": "Example 1: The below example illustrate the get_browser() function that will display the user’s browser capability."
},
{
"code": null,
"e": 2007,
"s": 2003,
"text": "PHP"
},
{
"code": "<?php echo $_SERVER['HTTP_USER_AGENT']; // Using get_browser() to display // capabilities of the user browser $mybrowser = get_browser(); print_r($mybrowser);?>",
"e": 2174,
"s": 2007,
"text": null
},
{
"code": null,
"e": 2182,
"s": 2174,
"text": "Output:"
},
{
"code": null,
"e": 2333,
"s": 2182,
"text": "[parent] => IE 6.0\n[platform] => WinXP\n[netclr] => 1\n[browser] => IE\n[version] => 6\n[majorver] => 6\n[minorver] => 0\n => 2\n[frames] => 1\n[iframes] => 1"
},
{
"code": null,
"e": 2443,
"s": 2333,
"text": "Example 2: The below example illustrate the get_browser() function with the return array that is set to true."
},
{
"code": null,
"e": 2447,
"s": 2443,
"text": "PHP"
},
{
"code": "<?php echo $_SERVER['HTTP_USER_AGENT']; // Using get_browser() with return_array set to TRUE $mybrowser = get_browser(null, true); print_r($mybrowser);?>",
"e": 2614,
"s": 2447,
"text": null
},
{
"code": null,
"e": 2622,
"s": 2614,
"text": "Output:"
},
{
"code": null,
"e": 3256,
"s": 2622,
"text": "Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.7) Gecko/20040803 Firefox/0.9.3\n\nArray\n(\n [browser_name_regex] => ^mozilla/5\\.0 (windows; .;\n windows nt 5\\.1; .*rv:.*) gecko/.* firefox/0\\.9.*$\n [browser_name_pattern] => Mozilla/5.0 (Windows; ?;\n Windows NT 5.1; *rv:*) Gecko/* Firefox/0.9*\n [parent] => Firefox 0.9\n [platform] => WinXP\n [browser] => Firefox\n [version] => 0.9\n [majorver] => 0\n [minorver] => 9\n [cssversion] => 2\n [frames] => 1\n [iframes] => 1\n [tables] => 1\n [cookies] => 1\n => 1\n [javaapplets] => 1\n [activexcontrols] =>\n [beta] => 1\n) "
},
{
"code": null,
"e": 3317,
"s": 3256,
"text": "Reference: http://php.net/manual/en/function.get-browser.php"
},
{
"code": null,
"e": 3338,
"s": 3317,
"text": "bhaskargeeksforgeeks"
},
{
"code": null,
"e": 3351,
"s": 3338,
"text": "PHP-function"
},
{
"code": null,
"e": 3355,
"s": 3351,
"text": "PHP"
},
{
"code": null,
"e": 3372,
"s": 3355,
"text": "Web Technologies"
},
{
"code": null,
"e": 3376,
"s": 3372,
"text": "PHP"
},
{
"code": null,
"e": 3474,
"s": 3376,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 3524,
"s": 3474,
"text": "How to Insert Form Data into Database using PHP ?"
},
{
"code": null,
"e": 3564,
"s": 3524,
"text": "How to convert array to string in PHP ?"
},
{
"code": null,
"e": 3614,
"s": 3564,
"text": "How to check whether an array is empty using PHP?"
},
{
"code": null,
"e": 3659,
"s": 3614,
"text": "PHP | Converting string to Date and DateTime"
},
{
"code": null,
"e": 3686,
"s": 3659,
"text": "Comparing two dates in PHP"
},
{
"code": null,
"e": 3748,
"s": 3686,
"text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills"
},
{
"code": null,
"e": 3781,
"s": 3748,
"text": "Installation of Node.js on Linux"
},
{
"code": null,
"e": 3842,
"s": 3781,
"text": "Difference between var, let and const keywords in JavaScript"
},
{
"code": null,
"e": 3892,
"s": 3842,
"text": "How to insert spaces/tabs in text using HTML/CSS?"
}
] |
Find the coordinates of the fourth vertex of a rectangle with given 3 vertices
|
31 May, 2022
Given an N * M grid. It contains exactly three ‘*’ and every other cell is a ‘.’ where ‘*’ denotes a vertex of a rectangle. The task is to find the coordinates of the fourth (missing) vertex (1-based indexing).Examples:
Input: grid[][] = {“*.*”, “*..”, “...”} Output: 2 3 (1, 1), (1, 3) and (2, 1) are the given coordinates of the rectangle where (2, 3) is the missing coordinate.Input: grid[][] = {“*.*”, “..*”} Output: 2 1
Approach: Find the coordinates of the 3 vertices by iterating through the given grid. Since a rectangle consists of 2 X-coordinates and 2 Y-coordinates and 4 vertices, every X-coordinate and Y-coordinate should occur exactly twice. We can count how many times each X and Y coordinate occurs in the 3 given vertices and the 4th one will have coordinates that occur only once.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 that return the coordinates// of the fourth vertex of the rectanglepair<int, int> findFourthVertex(int n, int m, string s[]){ unordered_map<int, int> row, col; for (int i = 0; i < n; i++) for (int j = 0; j < m; j++) // Save the coordinates of the given // vertices of the rectangle if (s[i][j] == '*') { row[i]++; col[j]++; } int x, y; for (auto tm : row) if (tm.second == 1) x = tm.first; for (auto tm : col) if (tm.second == 1) y = tm.first; // 1-based indexing return make_pair(x + 1, y + 1);} // Driver codeint main(){ string s[] = { "*.*", "*..", "..." }; int n = sizeof(s) / sizeof(s[0]); int m = s[0].length(); auto rs = findFourthVertex(n, m, s); cout << rs.first << " " << rs.second;}
// Java implementation of the approachimport java.util.HashMap;import java.util.Map; class GfG{ // Function that return the coordinates // of the fourth vertex of the rectangle static Pair<Integer, Integer> findFourthVertex(int n, int m, String s[]) { HashMap<Integer, Integer> row = new HashMap<>(); HashMap<Integer, Integer> col = new HashMap<>(); for (int i = 0; i < n; i++) { for (int j = 0; j < m; j++) { // Save the coordinates of the given // vertices of the rectangle if (s[i].charAt(j) == '*') { if (row.containsKey(i)) { row.put(i, row.get(i) + 1); } else { row.put(i, 1); } if (col.containsKey(j)) { col.put(j, col.get(j) + 1); } else { col.put(j, 1); } } } } int x = 0, y = 0; for (Map.Entry<Integer, Integer> entry : row.entrySet()) { if (entry.getValue() == 1) x = entry.getKey(); } for (Map.Entry<Integer, Integer> entry : col.entrySet()) { if (entry.getValue() == 1) y = entry.getKey(); } // 1-based indexing Pair<Integer, Integer> ans = new Pair<>(x + 1, y + 1); return ans; } // Driver Code public static void main(String []args) { String s[] = { "*.*", "*..", "..." }; int n = s.length; int m = s[0].length(); Pair<Integer, Integer> rs = findFourthVertex(n, m, s); System.out.println(rs.first + " " + rs.second); }} class Pair<A, B>{ A first; B second; public Pair(A first, B second) { this.first = first; this.second = second; }} // This code is contributed by Rituraj Jain
# Python3 implementation of the approach # Function that return the coordinates# of the fourth vertex of the rectangledef findFourthVertex(n, m, s) : row = dict.fromkeys(range(n), 0) col = dict.fromkeys(range(m), 0) for i in range(n) : for j in range(m) : # Save the coordinates of the given # vertices of the rectangle if (s[i][j] == '*') : row[i] += 1; col[j] += 1; for keys,values in row.items() : if (values == 1) : x = keys; for keys,values in col.items() : if (values == 1) : y = keys; # 1-based indexing return (x + 1, y + 1) ; # Driver codeif __name__ == "__main__" : s = [ "*.*", "*..", "..." ] n = len(s); m = len(s[0]); rs = findFourthVertex(n, m, s); print(rs[0], rs[1]) # This code is contributed by Ryuga
// C# implementation of the approachusing System;using System.Collections.Generic; class GfG{ // Function that return the coordinates // of the fourth vertex of the rectangle static Pair<int, int> findFourthVertex(int n, int m, String []s) { Dictionary<int, int> row = new Dictionary<int, int>(); Dictionary<int, int> col = new Dictionary<int, int>(); for (int i = 0; i < n; i++) { for (int j = 0; j < m; j++) { // Save the coordinates of the given // vertices of the rectangle if (s[i][j] == '*') { if (row.ContainsKey(i)) { row[i] = row[i] + 1; } else { row.Add(i, 1); } if (col.ContainsKey(j)) { col[j] = col[j] + 1; } else { col.Add(j, 1); } } } } int x = 0, y = 0; foreach(KeyValuePair<int, int> entry in row) { if (entry.Value == 1) x = entry.Key; } foreach(KeyValuePair<int, int> entry in col) { if (entry.Value == 1) y = entry.Key; } // 1-based indexing Pair<int, int> ans = new Pair<int, int>(x + 1, y + 1); return ans; } // Driver Code public static void Main(String []args) { String []s = { "*.*", "*..", "..." }; int n = s.Length; int m = s[0].Length; Pair<int, int> rs = findFourthVertex(n, m, s); Console.WriteLine(rs.first + " " + rs.second); }} class Pair<A, B>{ public A first; public B second; public Pair(A first, B second) { this.first = first; this.second = second; }} // This code is contributed by 29AjayKumar
<script> // Javascript implementation of the approach // Function that return the coordinates// of the fourth vertex of the rectanglefunction findFourthVertex(n, m, s){ var row = new Map(), col = new Map(); for (var i = 0; i < n; i++) for (var j = 0; j < m; j++) // Save the coordinates of the given // vertices of the rectangle if (s[i][j] == '*') { if(row.has(i)) row.set(i, row.get(i)+1) else row.set(i, 1) if(col.has(j)) col.set(j, col.get(j)+1) else col.set(j, 1) } var x, y; row.forEach((value, key) => { if (value == 1) x = key; }); col.forEach((value, key) => { if (value == 1) y = key; }); // 1-based indexing return [x + 1, y + 1];} // Driver codevar s = ["*.*", "*..", "..." ];var n = s.length;var m = s[0].length;var rs = findFourthVertex(n, m, s);document.write( rs[0] + " " + rs[1]); // This code is contributed by famously.</script>
2 3
Time Complexity: O(N*M), as we are using a loop to traverse N*M times. Auxiliary Space: O(N + M), as we are using extra space for map.
ankthon
rituraj_jain
29AjayKumar
famously
sumitgumber28
pankajsharmagfg
ashutoshsinghgeeksforgeeks
rohitkumarsinghcna
square-rectangle
Algorithms
Geometric
Mathematical
Mathematical
Geometric
Algorithms
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
Understanding Time Complexity with Simple Examples
Find if there is a path between two vertices in an undirected graph
Closest Pair of Points using Divide and Conquer algorithm
How to check if a given point lies inside or outside a polygon?
How to check if two given line segments intersect?
Optimum location of point to minimize total distance
Find if two rectangles overlap
|
[
{
"code": null,
"e": 53,
"s": 25,
"text": "\n31 May, 2022"
},
{
"code": null,
"e": 275,
"s": 53,
"text": "Given an N * M grid. It contains exactly three ‘*’ and every other cell is a ‘.’ where ‘*’ denotes a vertex of a rectangle. The task is to find the coordinates of the fourth (missing) vertex (1-based indexing).Examples: "
},
{
"code": null,
"e": 482,
"s": 275,
"text": "Input: grid[][] = {“*.*”, “*..”, “...”} Output: 2 3 (1, 1), (1, 3) and (2, 1) are the given coordinates of the rectangle where (2, 3) is the missing coordinate.Input: grid[][] = {“*.*”, “..*”} Output: 2 1 "
},
{
"code": null,
"e": 911,
"s": 484,
"text": "Approach: Find the coordinates of the 3 vertices by iterating through the given grid. Since a rectangle consists of 2 X-coordinates and 2 Y-coordinates and 4 vertices, every X-coordinate and Y-coordinate should occur exactly twice. We can count how many times each X and Y coordinate occurs in the 3 given vertices and the 4th one will have coordinates that occur only once.Below is the implementation of the above approach: "
},
{
"code": null,
"e": 915,
"s": 911,
"text": "C++"
},
{
"code": null,
"e": 920,
"s": 915,
"text": "Java"
},
{
"code": null,
"e": 928,
"s": 920,
"text": "Python3"
},
{
"code": null,
"e": 931,
"s": 928,
"text": "C#"
},
{
"code": null,
"e": 942,
"s": 931,
"text": "Javascript"
},
{
"code": "// C++ implementation of the approach#include <bits/stdc++.h>using namespace std; // Function that return the coordinates// of the fourth vertex of the rectanglepair<int, int> findFourthVertex(int n, int m, string s[]){ unordered_map<int, int> row, col; for (int i = 0; i < n; i++) for (int j = 0; j < m; j++) // Save the coordinates of the given // vertices of the rectangle if (s[i][j] == '*') { row[i]++; col[j]++; } int x, y; for (auto tm : row) if (tm.second == 1) x = tm.first; for (auto tm : col) if (tm.second == 1) y = tm.first; // 1-based indexing return make_pair(x + 1, y + 1);} // Driver codeint main(){ string s[] = { \"*.*\", \"*..\", \"...\" }; int n = sizeof(s) / sizeof(s[0]); int m = s[0].length(); auto rs = findFourthVertex(n, m, s); cout << rs.first << \" \" << rs.second;}",
"e": 1886,
"s": 942,
"text": null
},
{
"code": "// Java implementation of the approachimport java.util.HashMap;import java.util.Map; class GfG{ // Function that return the coordinates // of the fourth vertex of the rectangle static Pair<Integer, Integer> findFourthVertex(int n, int m, String s[]) { HashMap<Integer, Integer> row = new HashMap<>(); HashMap<Integer, Integer> col = new HashMap<>(); for (int i = 0; i < n; i++) { for (int j = 0; j < m; j++) { // Save the coordinates of the given // vertices of the rectangle if (s[i].charAt(j) == '*') { if (row.containsKey(i)) { row.put(i, row.get(i) + 1); } else { row.put(i, 1); } if (col.containsKey(j)) { col.put(j, col.get(j) + 1); } else { col.put(j, 1); } } } } int x = 0, y = 0; for (Map.Entry<Integer, Integer> entry : row.entrySet()) { if (entry.getValue() == 1) x = entry.getKey(); } for (Map.Entry<Integer, Integer> entry : col.entrySet()) { if (entry.getValue() == 1) y = entry.getKey(); } // 1-based indexing Pair<Integer, Integer> ans = new Pair<>(x + 1, y + 1); return ans; } // Driver Code public static void main(String []args) { String s[] = { \"*.*\", \"*..\", \"...\" }; int n = s.length; int m = s[0].length(); Pair<Integer, Integer> rs = findFourthVertex(n, m, s); System.out.println(rs.first + \" \" + rs.second); }} class Pair<A, B>{ A first; B second; public Pair(A first, B second) { this.first = first; this.second = second; }} // This code is contributed by Rituraj Jain",
"e": 4111,
"s": 1886,
"text": null
},
{
"code": "# Python3 implementation of the approach # Function that return the coordinates# of the fourth vertex of the rectangledef findFourthVertex(n, m, s) : row = dict.fromkeys(range(n), 0) col = dict.fromkeys(range(m), 0) for i in range(n) : for j in range(m) : # Save the coordinates of the given # vertices of the rectangle if (s[i][j] == '*') : row[i] += 1; col[j] += 1; for keys,values in row.items() : if (values == 1) : x = keys; for keys,values in col.items() : if (values == 1) : y = keys; # 1-based indexing return (x + 1, y + 1) ; # Driver codeif __name__ == \"__main__\" : s = [ \"*.*\", \"*..\", \"...\" ] n = len(s); m = len(s[0]); rs = findFourthVertex(n, m, s); print(rs[0], rs[1]) # This code is contributed by Ryuga",
"e": 5004,
"s": 4111,
"text": null
},
{
"code": "// C# implementation of the approachusing System;using System.Collections.Generic; class GfG{ // Function that return the coordinates // of the fourth vertex of the rectangle static Pair<int, int> findFourthVertex(int n, int m, String []s) { Dictionary<int, int> row = new Dictionary<int, int>(); Dictionary<int, int> col = new Dictionary<int, int>(); for (int i = 0; i < n; i++) { for (int j = 0; j < m; j++) { // Save the coordinates of the given // vertices of the rectangle if (s[i][j] == '*') { if (row.ContainsKey(i)) { row[i] = row[i] + 1; } else { row.Add(i, 1); } if (col.ContainsKey(j)) { col[j] = col[j] + 1; } else { col.Add(j, 1); } } } } int x = 0, y = 0; foreach(KeyValuePair<int, int> entry in row) { if (entry.Value == 1) x = entry.Key; } foreach(KeyValuePair<int, int> entry in col) { if (entry.Value == 1) y = entry.Key; } // 1-based indexing Pair<int, int> ans = new Pair<int, int>(x + 1, y + 1); return ans; } // Driver Code public static void Main(String []args) { String []s = { \"*.*\", \"*..\", \"...\" }; int n = s.Length; int m = s[0].Length; Pair<int, int> rs = findFourthVertex(n, m, s); Console.WriteLine(rs.first + \" \" + rs.second); }} class Pair<A, B>{ public A first; public B second; public Pair(A first, B second) { this.first = first; this.second = second; }} // This code is contributed by 29AjayKumar",
"e": 7164,
"s": 5004,
"text": null
},
{
"code": "<script> // Javascript implementation of the approach // Function that return the coordinates// of the fourth vertex of the rectanglefunction findFourthVertex(n, m, s){ var row = new Map(), col = new Map(); for (var i = 0; i < n; i++) for (var j = 0; j < m; j++) // Save the coordinates of the given // vertices of the rectangle if (s[i][j] == '*') { if(row.has(i)) row.set(i, row.get(i)+1) else row.set(i, 1) if(col.has(j)) col.set(j, col.get(j)+1) else col.set(j, 1) } var x, y; row.forEach((value, key) => { if (value == 1) x = key; }); col.forEach((value, key) => { if (value == 1) y = key; }); // 1-based indexing return [x + 1, y + 1];} // Driver codevar s = [\"*.*\", \"*..\", \"...\" ];var n = s.length;var m = s[0].length;var rs = findFourthVertex(n, m, s);document.write( rs[0] + \" \" + rs[1]); // This code is contributed by famously.</script>",
"e": 8271,
"s": 7164,
"text": null
},
{
"code": null,
"e": 8275,
"s": 8271,
"text": "2 3"
},
{
"code": null,
"e": 8412,
"s": 8277,
"text": "Time Complexity: O(N*M), as we are using a loop to traverse N*M times. Auxiliary Space: O(N + M), as we are using extra space for map."
},
{
"code": null,
"e": 8420,
"s": 8412,
"text": "ankthon"
},
{
"code": null,
"e": 8433,
"s": 8420,
"text": "rituraj_jain"
},
{
"code": null,
"e": 8445,
"s": 8433,
"text": "29AjayKumar"
},
{
"code": null,
"e": 8454,
"s": 8445,
"text": "famously"
},
{
"code": null,
"e": 8468,
"s": 8454,
"text": "sumitgumber28"
},
{
"code": null,
"e": 8484,
"s": 8468,
"text": "pankajsharmagfg"
},
{
"code": null,
"e": 8511,
"s": 8484,
"text": "ashutoshsinghgeeksforgeeks"
},
{
"code": null,
"e": 8530,
"s": 8511,
"text": "rohitkumarsinghcna"
},
{
"code": null,
"e": 8547,
"s": 8530,
"text": "square-rectangle"
},
{
"code": null,
"e": 8558,
"s": 8547,
"text": "Algorithms"
},
{
"code": null,
"e": 8568,
"s": 8558,
"text": "Geometric"
},
{
"code": null,
"e": 8581,
"s": 8568,
"text": "Mathematical"
},
{
"code": null,
"e": 8594,
"s": 8581,
"text": "Mathematical"
},
{
"code": null,
"e": 8604,
"s": 8594,
"text": "Geometric"
},
{
"code": null,
"e": 8615,
"s": 8604,
"text": "Algorithms"
},
{
"code": null,
"e": 8713,
"s": 8615,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 8738,
"s": 8713,
"text": "DSA Sheet by Love Babbar"
},
{
"code": null,
"e": 8787,
"s": 8738,
"text": "SDE SHEET - A Complete Guide for SDE Preparation"
},
{
"code": null,
"e": 8825,
"s": 8787,
"text": "What is Hashing | A Complete Tutorial"
},
{
"code": null,
"e": 8876,
"s": 8825,
"text": "Understanding Time Complexity with Simple Examples"
},
{
"code": null,
"e": 8944,
"s": 8876,
"text": "Find if there is a path between two vertices in an undirected graph"
},
{
"code": null,
"e": 9002,
"s": 8944,
"text": "Closest Pair of Points using Divide and Conquer algorithm"
},
{
"code": null,
"e": 9066,
"s": 9002,
"text": "How to check if a given point lies inside or outside a polygon?"
},
{
"code": null,
"e": 9117,
"s": 9066,
"text": "How to check if two given line segments intersect?"
},
{
"code": null,
"e": 9170,
"s": 9117,
"text": "Optimum location of point to minimize total distance"
}
] |
D3.js geoMercator() Function - GeeksforGeeks
|
01 Oct, 2020
D3.js is a JavaScript library for producing dynamic, interactive data visualizations in web browsers. It makes use of Scalable Vector Graphics, HTML5, and Cascading Style Sheets standards. The geoMercator() function in d3.js is used to draw The spherical Mercator projection.
Syntax:
d3.geoMercator()
Parameters: This method does not accept any parameters.
Returns: This method creates the Mercator projection from given json data.
Example #1: The following example draws Mercator projection of world with center at (0, 0) and 0 rotation.
<!DOCTYPE html><html lang="en"> <head> <meta charset="UTF-8" /> <meta name="viewport" content="width=device-width, initial-scale=1.0" /> </head> <body> <div style="width: 700px; height: 500px;"> <center> <h3 style="color: black;"></h3> </center> <svg width="600" height="450"></svg> </div> <script src="https://d3js.org/d3.v4.js"></script> <script src= "https://d3js.org/d3-geo-projection.v2.min.js"> </script> <script> var svg = d3.select("svg"), width = +svg.attr("width"), height = +svg.attr("height"); // Mercator projection // Center(0, 0) with 0 rotation var gfg = d3 .geoMercator() .scale(width / 2.5 / Math.PI) .rotate([0, 0]) .center([0, 0]) .translate([width / 2, height / 2]); // Loading the json data // Used json file stored at/*https://raw.githubusercontent.com/janasayantan /datageojson/master/world.json*/ d3.json("https://raw.githubusercontent.com/janasayantan/datageojson/master/world.json", function (data) { // Drawing the map svg.append("g").selectAll( "path").data(data.features).enter().append( "path").attr("fill", "black").attr( "d", d3.geoPath().projection(gfg)).style( "stroke", "#ffff"); }); </script> </body></html>
Output:
Mercator projection of World with no rotation and centered at (0, 0)
Example #2: The following example draws Mercator projection of world after altering the center and rotation.
<!DOCTYPE html><html lang="en"> <head> <meta charset="UTF-8" /> <meta name="viewport" content="width=device-width, initial-scale=1.0" /> </head> <body> <div style="width: 700px; height: 600px;"> <center> <h3 style="color: black;"></h3> </center> <svg width="500" height="450"></svg> </div> <script src="https://d3js.org/d3.v4.js"></script> <script src= "https://d3js.org/d3-geo-projection.v2.min.js"> </script> <script> var svg = d3.select("svg"), width = +svg.attr("width"), height = +svg.attr("height"); // Mercator projection // Center(20, 20) and 90 degree rotation w.r.t Y axis var gfg = d3 .geoMercator() .scale(width / 2.5 / Math.PI) .rotate([90, 0]) .center([20, 20]) .translate([width / 2, height / 2]); // Loading the json data // Used json file stored at /*https://raw.githubusercontent.com/janasayantan /datageojson/master/world.json*/ d3.json("https://raw.githubusercontent.com/janasayantan/datageojson/master/world.json", function (data) { // Draw the map svg.append("g").selectAll( "path").data(data.features).enter().append( "path").attr("fill", "Turquoise").attr( "d", d3.geoPath().projection(gfg)).style( "stroke", "#ffff"); }); </script> </body></html>
Output:
Mercator projection with 90 degree rotation w.r.t Y axis and centered at (20, 20)
D3.js
JavaScript
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Remove elements from a JavaScript Array
Convert a string to an integer in JavaScript
Difference between var, let and const keywords in JavaScript
Differences between Functional Components and Class Components in React
How to append HTML code to a div using JavaScript ?
Remove elements from a JavaScript Array
Installation of Node.js on Linux
Convert a string to an integer in JavaScript
How to fetch data from an API in ReactJS ?
How to insert spaces/tabs in text using HTML/CSS?
|
[
{
"code": null,
"e": 25873,
"s": 25845,
"text": "\n01 Oct, 2020"
},
{
"code": null,
"e": 26149,
"s": 25873,
"text": "D3.js is a JavaScript library for producing dynamic, interactive data visualizations in web browsers. It makes use of Scalable Vector Graphics, HTML5, and Cascading Style Sheets standards. The geoMercator() function in d3.js is used to draw The spherical Mercator projection."
},
{
"code": null,
"e": 26157,
"s": 26149,
"text": "Syntax:"
},
{
"code": null,
"e": 26174,
"s": 26157,
"text": "d3.geoMercator()"
},
{
"code": null,
"e": 26230,
"s": 26174,
"text": "Parameters: This method does not accept any parameters."
},
{
"code": null,
"e": 26305,
"s": 26230,
"text": "Returns: This method creates the Mercator projection from given json data."
},
{
"code": null,
"e": 26412,
"s": 26305,
"text": "Example #1: The following example draws Mercator projection of world with center at (0, 0) and 0 rotation."
},
{
"code": "<!DOCTYPE html><html lang=\"en\"> <head> <meta charset=\"UTF-8\" /> <meta name=\"viewport\" content=\"width=device-width, initial-scale=1.0\" /> </head> <body> <div style=\"width: 700px; height: 500px;\"> <center> <h3 style=\"color: black;\"></h3> </center> <svg width=\"600\" height=\"450\"></svg> </div> <script src=\"https://d3js.org/d3.v4.js\"></script> <script src= \"https://d3js.org/d3-geo-projection.v2.min.js\"> </script> <script> var svg = d3.select(\"svg\"), width = +svg.attr(\"width\"), height = +svg.attr(\"height\"); // Mercator projection // Center(0, 0) with 0 rotation var gfg = d3 .geoMercator() .scale(width / 2.5 / Math.PI) .rotate([0, 0]) .center([0, 0]) .translate([width / 2, height / 2]); // Loading the json data // Used json file stored at/*https://raw.githubusercontent.com/janasayantan /datageojson/master/world.json*/ d3.json(\"https://raw.githubusercontent.com/janasayantan/datageojson/master/world.json\", function (data) { // Drawing the map svg.append(\"g\").selectAll( \"path\").data(data.features).enter().append( \"path\").attr(\"fill\", \"black\").attr( \"d\", d3.geoPath().projection(gfg)).style( \"stroke\", \"#ffff\"); }); </script> </body></html>",
"e": 28080,
"s": 26412,
"text": null
},
{
"code": null,
"e": 28088,
"s": 28080,
"text": "Output:"
},
{
"code": null,
"e": 28158,
"s": 28088,
"text": "Mercator projection of World with no rotation and centered at (0, 0)"
},
{
"code": null,
"e": 28267,
"s": 28158,
"text": "Example #2: The following example draws Mercator projection of world after altering the center and rotation."
},
{
"code": "<!DOCTYPE html><html lang=\"en\"> <head> <meta charset=\"UTF-8\" /> <meta name=\"viewport\" content=\"width=device-width, initial-scale=1.0\" /> </head> <body> <div style=\"width: 700px; height: 600px;\"> <center> <h3 style=\"color: black;\"></h3> </center> <svg width=\"500\" height=\"450\"></svg> </div> <script src=\"https://d3js.org/d3.v4.js\"></script> <script src= \"https://d3js.org/d3-geo-projection.v2.min.js\"> </script> <script> var svg = d3.select(\"svg\"), width = +svg.attr(\"width\"), height = +svg.attr(\"height\"); // Mercator projection // Center(20, 20) and 90 degree rotation w.r.t Y axis var gfg = d3 .geoMercator() .scale(width / 2.5 / Math.PI) .rotate([90, 0]) .center([20, 20]) .translate([width / 2, height / 2]); // Loading the json data // Used json file stored at /*https://raw.githubusercontent.com/janasayantan /datageojson/master/world.json*/ d3.json(\"https://raw.githubusercontent.com/janasayantan/datageojson/master/world.json\", function (data) { // Draw the map svg.append(\"g\").selectAll( \"path\").data(data.features).enter().append( \"path\").attr(\"fill\", \"Turquoise\").attr( \"d\", d3.geoPath().projection(gfg)).style( \"stroke\", \"#ffff\"); }); </script> </body></html>",
"e": 29930,
"s": 28267,
"text": null
},
{
"code": null,
"e": 29938,
"s": 29930,
"text": "Output:"
},
{
"code": null,
"e": 30022,
"s": 29938,
"text": "Mercator projection with 90 degree rotation w.r.t Y axis and centered at (20, 20)"
},
{
"code": null,
"e": 30028,
"s": 30022,
"text": "D3.js"
},
{
"code": null,
"e": 30039,
"s": 30028,
"text": "JavaScript"
},
{
"code": null,
"e": 30056,
"s": 30039,
"text": "Web Technologies"
},
{
"code": null,
"e": 30154,
"s": 30056,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 30194,
"s": 30154,
"text": "Remove elements from a JavaScript Array"
},
{
"code": null,
"e": 30239,
"s": 30194,
"text": "Convert a string to an integer in JavaScript"
},
{
"code": null,
"e": 30300,
"s": 30239,
"text": "Difference between var, let and const keywords in JavaScript"
},
{
"code": null,
"e": 30372,
"s": 30300,
"text": "Differences between Functional Components and Class Components in React"
},
{
"code": null,
"e": 30424,
"s": 30372,
"text": "How to append HTML code to a div using JavaScript ?"
},
{
"code": null,
"e": 30464,
"s": 30424,
"text": "Remove elements from a JavaScript Array"
},
{
"code": null,
"e": 30497,
"s": 30464,
"text": "Installation of Node.js on Linux"
},
{
"code": null,
"e": 30542,
"s": 30497,
"text": "Convert a string to an integer in JavaScript"
},
{
"code": null,
"e": 30585,
"s": 30542,
"text": "How to fetch data from an API in ReactJS ?"
}
] |
HTTP headers | Content-Location - GeeksforGeeks
|
07 Nov, 2019
The HTTP Content-Location header is an entity-header that gives another location for the data that is returned and also tells how to access the resource by indicating the direct URL. Its usage is often confused with another HTTP Header which is Location. The main difference between them is that Location gives the URL of the resource where the redirection of the page happens while HTTP Content-Location is used to indicate the URL of a transmitted resource.
Syntax:
Content-Location: <url>
Directives: This header accepts a single directive mentioned above and described below:
<url>:This directive holds the relative or absolute URL that gives access to a resource.
Examples:
In this example, index.html is the URL which indicated the location of the content.Content-Location: /index.html
Content-Location: /index.html
In this example, teddy.xml is the URL which indicates the location of the content.Content-Location: /teddy.xmlTo check this Content-Location in action go to Inspect Element -> Network check the response header for Content-Location like below.Supported Browsers: The browsers are compatible with the HTTP Content-Location header are listed below:Google ChromeInternet ExplorerOperaFirefoxSafariMy Personal Notes
arrow_drop_upSave
Content-Location: /teddy.xml
To check this Content-Location in action go to Inspect Element -> Network check the response header for Content-Location like below.
Supported Browsers: The browsers are compatible with the HTTP Content-Location header are listed below:
Google Chrome
Internet Explorer
Opera
Firefox
Safari
HTTP-headers
Picked
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Remove elements from a JavaScript Array
Convert a string to an integer in JavaScript
How to fetch data from an API in ReactJS ?
Difference between var, let and const keywords in JavaScript
Differences between Functional Components and Class Components in React
How to create footer to stay at the bottom of a Web page?
Node.js fs.readFileSync() Method
How to set the default value for an HTML <select> element ?
File uploading in React.js
How to apply style to parent if it has child with CSS?
|
[
{
"code": null,
"e": 25803,
"s": 25775,
"text": "\n07 Nov, 2019"
},
{
"code": null,
"e": 26263,
"s": 25803,
"text": "The HTTP Content-Location header is an entity-header that gives another location for the data that is returned and also tells how to access the resource by indicating the direct URL. Its usage is often confused with another HTTP Header which is Location. The main difference between them is that Location gives the URL of the resource where the redirection of the page happens while HTTP Content-Location is used to indicate the URL of a transmitted resource."
},
{
"code": null,
"e": 26271,
"s": 26263,
"text": "Syntax:"
},
{
"code": null,
"e": 26295,
"s": 26271,
"text": "Content-Location: <url>"
},
{
"code": null,
"e": 26383,
"s": 26295,
"text": "Directives: This header accepts a single directive mentioned above and described below:"
},
{
"code": null,
"e": 26472,
"s": 26383,
"text": "<url>:This directive holds the relative or absolute URL that gives access to a resource."
},
{
"code": null,
"e": 26482,
"s": 26472,
"text": "Examples:"
},
{
"code": null,
"e": 26595,
"s": 26482,
"text": "In this example, index.html is the URL which indicated the location of the content.Content-Location: /index.html"
},
{
"code": null,
"e": 26625,
"s": 26595,
"text": "Content-Location: /index.html"
},
{
"code": null,
"e": 27054,
"s": 26625,
"text": "In this example, teddy.xml is the URL which indicates the location of the content.Content-Location: /teddy.xmlTo check this Content-Location in action go to Inspect Element -> Network check the response header for Content-Location like below.Supported Browsers: The browsers are compatible with the HTTP Content-Location header are listed below:Google ChromeInternet ExplorerOperaFirefoxSafariMy Personal Notes\narrow_drop_upSave"
},
{
"code": null,
"e": 27083,
"s": 27054,
"text": "Content-Location: /teddy.xml"
},
{
"code": null,
"e": 27216,
"s": 27083,
"text": "To check this Content-Location in action go to Inspect Element -> Network check the response header for Content-Location like below."
},
{
"code": null,
"e": 27320,
"s": 27216,
"text": "Supported Browsers: The browsers are compatible with the HTTP Content-Location header are listed below:"
},
{
"code": null,
"e": 27334,
"s": 27320,
"text": "Google Chrome"
},
{
"code": null,
"e": 27352,
"s": 27334,
"text": "Internet Explorer"
},
{
"code": null,
"e": 27358,
"s": 27352,
"text": "Opera"
},
{
"code": null,
"e": 27366,
"s": 27358,
"text": "Firefox"
},
{
"code": null,
"e": 27373,
"s": 27366,
"text": "Safari"
},
{
"code": null,
"e": 27386,
"s": 27373,
"text": "HTTP-headers"
},
{
"code": null,
"e": 27393,
"s": 27386,
"text": "Picked"
},
{
"code": null,
"e": 27410,
"s": 27393,
"text": "Web Technologies"
},
{
"code": null,
"e": 27508,
"s": 27410,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 27548,
"s": 27508,
"text": "Remove elements from a JavaScript Array"
},
{
"code": null,
"e": 27593,
"s": 27548,
"text": "Convert a string to an integer in JavaScript"
},
{
"code": null,
"e": 27636,
"s": 27593,
"text": "How to fetch data from an API in ReactJS ?"
},
{
"code": null,
"e": 27697,
"s": 27636,
"text": "Difference between var, let and const keywords in JavaScript"
},
{
"code": null,
"e": 27769,
"s": 27697,
"text": "Differences between Functional Components and Class Components in React"
},
{
"code": null,
"e": 27827,
"s": 27769,
"text": "How to create footer to stay at the bottom of a Web page?"
},
{
"code": null,
"e": 27860,
"s": 27827,
"text": "Node.js fs.readFileSync() Method"
},
{
"code": null,
"e": 27920,
"s": 27860,
"text": "How to set the default value for an HTML <select> element ?"
},
{
"code": null,
"e": 27947,
"s": 27920,
"text": "File uploading in React.js"
}
] |
Entity Framework - Table-Valued Function
|
In this chapter, let us learn how to map Table-valued Functions (TVFs) using the Entity Framework Designer and how to call a TVF from a LINQ query.
TVFs are currently only supported in the Database First workflow.
TVFs are currently only supported in the Database First workflow.
It was first introduced in Entity Framework version 5.
It was first introduced in Entity Framework version 5.
To use the TVFs you must target .NET Framework 4.5 or above.
To use the TVFs you must target .NET Framework 4.5 or above.
It is very similar to stored procedures but with one key difference, i.e., the result of a TVF is composable. This means the results from a TVF can be used in a LINQ query while the results of a stored procedure cannot.
It is very similar to stored procedures but with one key difference, i.e., the result of a TVF is composable. This means the results from a TVF can be used in a LINQ query while the results of a stored procedure cannot.
Let’s take a look at the following example of creating a new project from File → New → Project.
Step 1 − Select the Console Application from the middle pane and enter TableValuedFunctionDemo in the name field.
Step 2 − In Server explorer right-click on your database.
Step 3 − Select New Query and enter the following code in T-SQL editor to add a new table in your database.
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id =
OBJECT_ID(N'[dbo].[StudentGrade]') AND type in (N'U'))
BEGIN
CREATE TABLE [dbo].[StudentGrade](
[EnrollmentID] [int] IDENTITY(1,1) NOT NULL,
[CourseID] [int] NOT NULL,
[StudentID] [int] NOT NULL,
[Grade] [decimal](3, 2) NULL,
CONSTRAINT [PK_StudentGrade] PRIMARY KEY CLUSTERED ([EnrollmentID] ASC)
WITH (IGNORE_DUP_KEY = OFF) ON [PRIMARY]
) ON [PRIMARY]
END
GO
Step 4 − Right-click on the editor and select Execute.
Step 5 − Right-click on your database and click refresh. You will see the newly added table in your database.
Step 6 − Now create a function that will return student grades for course. Enter the following code in T-SQL editor.
CREATE FUNCTION [dbo].[GetStudentGradesForCourse]
(@CourseID INT)
RETURNS TABLE
RETURN
SELECT [EnrollmentID],
[CourseID],
[StudentID],
[Grade]
FROM [dbo].[StudentGrade]
WHERE CourseID = @CourseID
Step 7 − Right-click on the editor and select Execute.
Now you can see that the function is created.
Step 8 − Right click on the project name in Solution Explorer and select Add → New Item.
Step 9 − Then select ADO.NET Entity Data Model in the Templates pane.
Step 10 − Enter TVFModel as name, and then click Add.
Step 11 − In the Choose Model Contents dialog box, select EF designer from database, and then click Next.
Step 12 − Select your database and click Next.
Step 13 − In the Choose Your Database Objects dialog box select tables, views.
Step 14 − Select the GetStudentGradesForCourse function located under the Stored Procedures and Functions node and click Finish.
Step 15 − Select View → Other Windows → Entity Data Model Browser and right-click GetStudentGradesForCourse under Function Imports and select Edit.
You will see the following dialog.
Step 16 − Click on Entities radio button and select Enrollment from the combobox as return type of this Function and click Ok.
Let’s take a look at the following C# code in which all the students grade will be retrieved who are enrolled in Course ID = 4022 in database.
class Program {
static void Main(string[] args) {
using (var context = new UniContextEntities()) {
var CourseID = 4022;
// Return all the best students in the Microeconomics class.
var students = context.GetStudentGradesForCourse(CourseID);
foreach (var result in students) {
Console.WriteLine("Student ID: {0}, Grade: {1}",
result.StudentID, result.Grade);
}
Console.ReadKey();
}
}
}
When the above code is compiled and executed you will receive the following output −
Student ID: 1, Grade: 2
Student ID: 4, Grade: 4
Student ID: 9, Grade: 3.5
We recommend that you execute the above example in a step-by-step manner for better understanding.
19 Lectures
5 hours
Trevoir Williams
33 Lectures
3.5 hours
Nilay Mehta
21 Lectures
2.5 hours
TELCOMA Global
89 Lectures
7.5 hours
Mustafa Radaideh
Print
Add Notes
Bookmark this page
|
[
{
"code": null,
"e": 3180,
"s": 3032,
"text": "In this chapter, let us learn how to map Table-valued Functions (TVFs) using the Entity Framework Designer and how to call a TVF from a LINQ query."
},
{
"code": null,
"e": 3246,
"s": 3180,
"text": "TVFs are currently only supported in the Database First workflow."
},
{
"code": null,
"e": 3312,
"s": 3246,
"text": "TVFs are currently only supported in the Database First workflow."
},
{
"code": null,
"e": 3367,
"s": 3312,
"text": "It was first introduced in Entity Framework version 5."
},
{
"code": null,
"e": 3422,
"s": 3367,
"text": "It was first introduced in Entity Framework version 5."
},
{
"code": null,
"e": 3483,
"s": 3422,
"text": "To use the TVFs you must target .NET Framework 4.5 or above."
},
{
"code": null,
"e": 3544,
"s": 3483,
"text": "To use the TVFs you must target .NET Framework 4.5 or above."
},
{
"code": null,
"e": 3764,
"s": 3544,
"text": "It is very similar to stored procedures but with one key difference, i.e., the result of a TVF is composable. This means the results from a TVF can be used in a LINQ query while the results of a stored procedure cannot."
},
{
"code": null,
"e": 3984,
"s": 3764,
"text": "It is very similar to stored procedures but with one key difference, i.e., the result of a TVF is composable. This means the results from a TVF can be used in a LINQ query while the results of a stored procedure cannot."
},
{
"code": null,
"e": 4080,
"s": 3984,
"text": "Let’s take a look at the following example of creating a new project from File → New → Project."
},
{
"code": null,
"e": 4194,
"s": 4080,
"text": "Step 1 − Select the Console Application from the middle pane and enter TableValuedFunctionDemo in the name field."
},
{
"code": null,
"e": 4252,
"s": 4194,
"text": "Step 2 − In Server explorer right-click on your database."
},
{
"code": null,
"e": 4360,
"s": 4252,
"text": "Step 3 − Select New Query and enter the following code in T-SQL editor to add a new table in your database."
},
{
"code": null,
"e": 4832,
"s": 4360,
"text": "IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id =\n OBJECT_ID(N'[dbo].[StudentGrade]') AND type in (N'U'))\n\nBEGIN\n\n CREATE TABLE [dbo].[StudentGrade](\n\n [EnrollmentID] [int] IDENTITY(1,1) NOT NULL,\n [CourseID] [int] NOT NULL,\n [StudentID] [int] NOT NULL,\n [Grade] [decimal](3, 2) NULL,\n\n CONSTRAINT [PK_StudentGrade] PRIMARY KEY CLUSTERED ([EnrollmentID] ASC)\n\n WITH (IGNORE_DUP_KEY = OFF) ON [PRIMARY]\n\n ) ON [PRIMARY]\n\nEND\nGO"
},
{
"code": null,
"e": 4887,
"s": 4832,
"text": "Step 4 − Right-click on the editor and select Execute."
},
{
"code": null,
"e": 4997,
"s": 4887,
"text": "Step 5 − Right-click on your database and click refresh. You will see the newly added table in your database."
},
{
"code": null,
"e": 5114,
"s": 4997,
"text": "Step 6 − Now create a function that will return student grades for course. Enter the following code in T-SQL editor."
},
{
"code": null,
"e": 5344,
"s": 5114,
"text": "CREATE FUNCTION [dbo].[GetStudentGradesForCourse]\n\n(@CourseID INT)\n\nRETURNS TABLE\n\nRETURN\n SELECT [EnrollmentID],\n [CourseID],\n [StudentID],\n [Grade]\n FROM [dbo].[StudentGrade]\n WHERE CourseID = @CourseID "
},
{
"code": null,
"e": 5399,
"s": 5344,
"text": "Step 7 − Right-click on the editor and select Execute."
},
{
"code": null,
"e": 5445,
"s": 5399,
"text": "Now you can see that the function is created."
},
{
"code": null,
"e": 5535,
"s": 5445,
"text": "Step 8 − Right click on the project name in Solution Explorer and select Add → New Item."
},
{
"code": null,
"e": 5605,
"s": 5535,
"text": "Step 9 − Then select ADO.NET Entity Data Model in the Templates pane."
},
{
"code": null,
"e": 5659,
"s": 5605,
"text": "Step 10 − Enter TVFModel as name, and then click Add."
},
{
"code": null,
"e": 5765,
"s": 5659,
"text": "Step 11 − In the Choose Model Contents dialog box, select EF designer from database, and then click Next."
},
{
"code": null,
"e": 5812,
"s": 5765,
"text": "Step 12 − Select your database and click Next."
},
{
"code": null,
"e": 5891,
"s": 5812,
"text": "Step 13 − In the Choose Your Database Objects dialog box select tables, views."
},
{
"code": null,
"e": 6020,
"s": 5891,
"text": "Step 14 − Select the GetStudentGradesForCourse function located under the Stored Procedures and Functions node and click Finish."
},
{
"code": null,
"e": 6168,
"s": 6020,
"text": "Step 15 − Select View → Other Windows → Entity Data Model Browser and right-click GetStudentGradesForCourse under Function Imports and select Edit."
},
{
"code": null,
"e": 6203,
"s": 6168,
"text": "You will see the following dialog."
},
{
"code": null,
"e": 6330,
"s": 6203,
"text": "Step 16 − Click on Entities radio button and select Enrollment from the combobox as return type of this Function and click Ok."
},
{
"code": null,
"e": 6473,
"s": 6330,
"text": "Let’s take a look at the following C# code in which all the students grade will be retrieved who are enrolled in Course ID = 4022 in database."
},
{
"code": null,
"e": 6964,
"s": 6473,
"text": "class Program {\n\n static void Main(string[] args) {\n\n using (var context = new UniContextEntities()) {\n\n var CourseID = 4022;\n\n // Return all the best students in the Microeconomics class.\n var students = context.GetStudentGradesForCourse(CourseID);\n\n foreach (var result in students) {\n Console.WriteLine(\"Student ID: {0}, Grade: {1}\",\n result.StudentID, result.Grade);\n }\n\n Console.ReadKey();\n }\n }\n}"
},
{
"code": null,
"e": 7049,
"s": 6964,
"text": "When the above code is compiled and executed you will receive the following output −"
},
{
"code": null,
"e": 7124,
"s": 7049,
"text": "Student ID: 1, Grade: 2\nStudent ID: 4, Grade: 4\nStudent ID: 9, Grade: 3.5\n"
},
{
"code": null,
"e": 7223,
"s": 7124,
"text": "We recommend that you execute the above example in a step-by-step manner for better understanding."
},
{
"code": null,
"e": 7256,
"s": 7223,
"text": "\n 19 Lectures \n 5 hours \n"
},
{
"code": null,
"e": 7274,
"s": 7256,
"text": " Trevoir Williams"
},
{
"code": null,
"e": 7309,
"s": 7274,
"text": "\n 33 Lectures \n 3.5 hours \n"
},
{
"code": null,
"e": 7322,
"s": 7309,
"text": " Nilay Mehta"
},
{
"code": null,
"e": 7357,
"s": 7322,
"text": "\n 21 Lectures \n 2.5 hours \n"
},
{
"code": null,
"e": 7373,
"s": 7357,
"text": " TELCOMA Global"
},
{
"code": null,
"e": 7408,
"s": 7373,
"text": "\n 89 Lectures \n 7.5 hours \n"
},
{
"code": null,
"e": 7426,
"s": 7408,
"text": " Mustafa Radaideh"
},
{
"code": null,
"e": 7433,
"s": 7426,
"text": " Print"
},
{
"code": null,
"e": 7444,
"s": 7433,
"text": " Add Notes"
}
] |
AWK - Workflow
|
To become an expert AWK programmer, you need to know its internals. AWK follows a simple workflow − Read, Execute, and Repeat. The following diagram depicts the workflow of AWK −
AWK reads a line from the input stream (file, pipe, or stdin) and stores it in memory.
All AWK commands are applied sequentially on the input. By default AWK execute commands on every line. We can restrict this by providing patterns.
This process repeats until the file reaches its end.
Let us now understand the program structure of AWK.
The syntax of the BEGIN block is as follows −
Syntax
BEGIN {awk-commands}
The BEGIN block gets executed at program start-up. It executes only once. This is good place to initialize variables. BEGIN is an AWK keyword and hence it must be in upper-case. Please note that this block is optional.
The syntax of the body block is as follows −
Syntax
/pattern/ {awk-commands}
The body block applies AWK commands on every input line. By default, AWK executes commands on every line. We can restrict this by providing patterns. Note that there are no keywords for the Body block.
The syntax of the END block is as follows −
Syntax
END {awk-commands}
The END block executes at the end of the program. END is an AWK keyword and hence it must be in upper-case. Please note that this block is optional.
Let us create a file marks.txt which contains the serial number, name of the student, subject name, and number of marks obtained.
1) Amit Physics 80
2) Rahul Maths 90
3) Shyam Biology 87
4) Kedar English 85
5) Hari History 89
Let us now display the file contents with header by using AWK script.
Example
[jerry]$ awk 'BEGIN{printf "Sr No\tName\tSub\tMarks\n"} {print}' marks.txt
When this code is executed, it produces the following result −
Output
Sr No Name Sub Marks
1) Amit Physics 80
2) Rahul Maths 90
3) Shyam Biology 87
4) Kedar English 85
5) Hari History 89
At the start, AWK prints the header from the BEGIN block. Then in the body block, it reads a line from a file and executes AWK's print command which just prints the contents on the standard output stream. This process repeats until file reaches the end.
Print
Add Notes
Bookmark this page
|
[
{
"code": null,
"e": 2036,
"s": 1857,
"text": "To become an expert AWK programmer, you need to know its internals. AWK follows a simple workflow − Read, Execute, and Repeat. The following diagram depicts the workflow of AWK −"
},
{
"code": null,
"e": 2123,
"s": 2036,
"text": "AWK reads a line from the input stream (file, pipe, or stdin) and stores it in memory."
},
{
"code": null,
"e": 2270,
"s": 2123,
"text": "All AWK commands are applied sequentially on the input. By default AWK execute commands on every line. We can restrict this by providing patterns."
},
{
"code": null,
"e": 2323,
"s": 2270,
"text": "This process repeats until the file reaches its end."
},
{
"code": null,
"e": 2375,
"s": 2323,
"text": "Let us now understand the program structure of AWK."
},
{
"code": null,
"e": 2421,
"s": 2375,
"text": "The syntax of the BEGIN block is as follows −"
},
{
"code": null,
"e": 2428,
"s": 2421,
"text": "Syntax"
},
{
"code": null,
"e": 2450,
"s": 2428,
"text": "BEGIN {awk-commands}\n"
},
{
"code": null,
"e": 2669,
"s": 2450,
"text": "The BEGIN block gets executed at program start-up. It executes only once. This is good place to initialize variables. BEGIN is an AWK keyword and hence it must be in upper-case. Please note that this block is optional."
},
{
"code": null,
"e": 2714,
"s": 2669,
"text": "The syntax of the body block is as follows −"
},
{
"code": null,
"e": 2721,
"s": 2714,
"text": "Syntax"
},
{
"code": null,
"e": 2747,
"s": 2721,
"text": "/pattern/ {awk-commands}\n"
},
{
"code": null,
"e": 2949,
"s": 2747,
"text": "The body block applies AWK commands on every input line. By default, AWK executes commands on every line. We can restrict this by providing patterns. Note that there are no keywords for the Body block."
},
{
"code": null,
"e": 2993,
"s": 2949,
"text": "The syntax of the END block is as follows −"
},
{
"code": null,
"e": 3000,
"s": 2993,
"text": "Syntax"
},
{
"code": null,
"e": 3020,
"s": 3000,
"text": "END {awk-commands}\n"
},
{
"code": null,
"e": 3169,
"s": 3020,
"text": "The END block executes at the end of the program. END is an AWK keyword and hence it must be in upper-case. Please note that this block is optional."
},
{
"code": null,
"e": 3299,
"s": 3169,
"text": "Let us create a file marks.txt which contains the serial number, name of the student, subject name, and number of marks obtained."
},
{
"code": null,
"e": 3420,
"s": 3299,
"text": "1) Amit Physics 80\n2) Rahul Maths 90\n3) Shyam Biology 87\n4) Kedar English 85\n5) Hari History 89\n"
},
{
"code": null,
"e": 3490,
"s": 3420,
"text": "Let us now display the file contents with header by using AWK script."
},
{
"code": null,
"e": 3498,
"s": 3490,
"text": "Example"
},
{
"code": null,
"e": 3573,
"s": 3498,
"text": "[jerry]$ awk 'BEGIN{printf \"Sr No\\tName\\tSub\\tMarks\\n\"} {print}' marks.txt"
},
{
"code": null,
"e": 3636,
"s": 3573,
"text": "When this code is executed, it produces the following result −"
},
{
"code": null,
"e": 3643,
"s": 3636,
"text": "Output"
},
{
"code": null,
"e": 3761,
"s": 3643,
"text": "Sr No Name Sub Marks\n1) Amit Physics 80\n2) Rahul Maths 90\n3) Shyam Biology 87\n4) Kedar English 85\n5) Hari History 89\n"
},
{
"code": null,
"e": 4015,
"s": 3761,
"text": "At the start, AWK prints the header from the BEGIN block. Then in the body block, it reads a line from a file and executes AWK's print command which just prints the contents on the standard output stream. This process repeats until file reaches the end."
},
{
"code": null,
"e": 4022,
"s": 4015,
"text": " Print"
},
{
"code": null,
"e": 4033,
"s": 4022,
"text": " Add Notes"
}
] |
Design and Analysis Max Cliques
|
In an undirected graph, a clique is a complete sub-graph of the given graph. Complete sub-graph means, all the vertices of this sub-graph is connected to all other vertices of this sub-graph.
The Max-Clique problem is the computational problem of finding maximum clique of the graph. Max clique is used in many real-world problems.
Let us consider a social networking application, where vertices represent people’s profile and the edges represent mutual acquaintance in a graph. In this graph, a clique represents a subset of people who all know each other.
To find a maximum clique, one can systematically inspect all subsets, but this sort of brute-force search is too time-consuming for networks comprising more than a few dozen vertices.
Algorithm: Max-Clique (G, n, k)
S := Φ
for i = 1 to k do
t := choice (1...n)
if t Є S then
return failure
S := S ∪ t
for all pairs (i, j) such that i Є S and j Є S and i ≠ j do
if (i, j) is not a edge of the graph then
return failure
return success
Max-Clique problem is a non-deterministic algorithm. In this algorithm, first we try to determine a set of k distinct vertices and then we try to test whether these vertices form a complete graph.
There is no polynomial time deterministic algorithm to solve this problem. This problem is NP-Complete.
Take a look at the following graph. Here, the sub-graph containing vertices 2, 3, 4 and 6 forms a complete graph. Hence, this sub-graph is a clique. As this is the maximum complete sub-graph of the provided graph, it’s a 4-Clique.
102 Lectures
10 hours
Arnab Chakraborty
30 Lectures
3 hours
Arnab Chakraborty
31 Lectures
4 hours
Arnab Chakraborty
43 Lectures
1.5 hours
Manoj Kumar
7 Lectures
1 hours
Zach Miller
54 Lectures
4 hours
Sasha Miller
Print
Add Notes
Bookmark this page
|
[
{
"code": null,
"e": 2791,
"s": 2599,
"text": "In an undirected graph, a clique is a complete sub-graph of the given graph. Complete sub-graph means, all the vertices of this sub-graph is connected to all other vertices of this sub-graph."
},
{
"code": null,
"e": 2931,
"s": 2791,
"text": "The Max-Clique problem is the computational problem of finding maximum clique of the graph. Max clique is used in many real-world problems."
},
{
"code": null,
"e": 3157,
"s": 2931,
"text": "Let us consider a social networking application, where vertices represent people’s profile and the edges represent mutual acquaintance in a graph. In this graph, a clique represents a subset of people who all know each other."
},
{
"code": null,
"e": 3341,
"s": 3157,
"text": "To find a maximum clique, one can systematically inspect all subsets, but this sort of brute-force search is too time-consuming for networks comprising more than a few dozen vertices."
},
{
"code": null,
"e": 3630,
"s": 3341,
"text": "Algorithm: Max-Clique (G, n, k) \nS := Φ \nfor i = 1 to k do \n t := choice (1...n) \n if t Є S then \n return failure \n S := S ∪ t \nfor all pairs (i, j) such that i Є S and j Є S and i ≠ j do \n if (i, j) is not a edge of the graph then \n return failure \nreturn success \n"
},
{
"code": null,
"e": 3827,
"s": 3630,
"text": "Max-Clique problem is a non-deterministic algorithm. In this algorithm, first we try to determine a set of k distinct vertices and then we try to test whether these vertices form a complete graph."
},
{
"code": null,
"e": 3931,
"s": 3827,
"text": "There is no polynomial time deterministic algorithm to solve this problem. This problem is NP-Complete."
},
{
"code": null,
"e": 4162,
"s": 3931,
"text": "Take a look at the following graph. Here, the sub-graph containing vertices 2, 3, 4 and 6 forms a complete graph. Hence, this sub-graph is a clique. As this is the maximum complete sub-graph of the provided graph, it’s a 4-Clique."
},
{
"code": null,
"e": 4197,
"s": 4162,
"text": "\n 102 Lectures \n 10 hours \n"
},
{
"code": null,
"e": 4216,
"s": 4197,
"text": " Arnab Chakraborty"
},
{
"code": null,
"e": 4249,
"s": 4216,
"text": "\n 30 Lectures \n 3 hours \n"
},
{
"code": null,
"e": 4268,
"s": 4249,
"text": " Arnab Chakraborty"
},
{
"code": null,
"e": 4301,
"s": 4268,
"text": "\n 31 Lectures \n 4 hours \n"
},
{
"code": null,
"e": 4320,
"s": 4301,
"text": " Arnab Chakraborty"
},
{
"code": null,
"e": 4355,
"s": 4320,
"text": "\n 43 Lectures \n 1.5 hours \n"
},
{
"code": null,
"e": 4368,
"s": 4355,
"text": " Manoj Kumar"
},
{
"code": null,
"e": 4400,
"s": 4368,
"text": "\n 7 Lectures \n 1 hours \n"
},
{
"code": null,
"e": 4413,
"s": 4400,
"text": " Zach Miller"
},
{
"code": null,
"e": 4446,
"s": 4413,
"text": "\n 54 Lectures \n 4 hours \n"
},
{
"code": null,
"e": 4460,
"s": 4446,
"text": " Sasha Miller"
},
{
"code": null,
"e": 4467,
"s": 4460,
"text": " Print"
},
{
"code": null,
"e": 4478,
"s": 4467,
"text": " Add Notes"
}
] |
Bootstrap - Button Plugin
|
Buttons were explained in chapter Bootstrap Buttons. With this plugin you can add in some interaction such as control button states or create groups of buttons for more components like toolbars.
To add a loading state to a button, simply add the data-loading-text = "Loading..." as an attribute to the button element as shown in the following example −
<button id = "fat-btn" class = "btn btn-primary" data-loading-text = "Loading..." type = "button">
Loading state
</button>
<script>
$(function() {
$(".btn").click(function(){
$(this).button('loading').delay(1000).queue(function() {
// $(this).button('reset');
});
});
});
</script>
When you click on the button the output would be as seen in the following image −
To activate toggling (i.e. change the normal state of a button to a push state and vice versa) on a single button, add the data-toggle = "button" as an attribute to the button element as shown in the following example −
<button type = "button" class = "btn btn-primary" data-toggle = "button">
Single toggle
</button>
You can create group of checkboxes and add toggling to it by simply adding the data attribute data-toggle = "buttons" to the btn-group.
<div class = "btn-group" data-toggle = "buttons">
<label class = "btn btn-primary">
<input type = "checkbox"> Option 1
</label>
<label class = "btn btn-primary">
<input type = "checkbox"> Option 2
</label>
<label class = "btn btn-primary">
<input type = "checkbox"> Option 3
</label>
</div>
Similarly you can create a group of radio inputs and add toggling to it by simply adding the data attribute data-toggle = "buttons" to the btn-group.
<div class = "btn-group" data-toggle = "buttons">
<label class = "btn btn-primary">
<input type = "radio" name =" options" id = "option1"> Option 1
</label>
<label class = "btn btn-primary">
<input type = "radio" name = "options" id = "option2"> Option 2
</label>
<label class = "btn btn-primary">
<input type = "radio" name = "options" id = "option3"> Option 3
</label>
</div>
You can enable buttons plugin via JavaScript as shown below −
$('.btn').button()
There are no options.
Given below are some of the useful methods for buttons plugin −
button('toggle')
Toggles push state. Gives the button the appearance that it has been activated. You can also enable auto toggling of a button by using the data-toggle attribute.
$().button('toggle')
.button('loading')
When loading, the button is disabled and the text is changed to the option from the data-loading-text attribute of button element
$().button('loading')
.button('reset')
Resets button state, bringing the original content back to the text. This method is useful when you need to return the button back to the primary state
$().button('reset')
.button(string)
String in this method is referring to any string declared by the user. To reset the button state and bring in new content use this method.
$().button(string)
The following example demonstrates the use of the above methods −
<h2>Click on each of the buttons to see the effects of methods</h2>
<h4>Example to demonstrate .button('toggle') method</h4>
<div id = "myButtons1" class = "bs-example">
<button type = "button" class = "btn btn-primary">Primary</button>
</div>
<h4>Example to demonstrate .button('loading') method</h4>
<div id = "myButtons2" class = "bs-example">
<button type = "button" class = "btn btn-primary" data-loading-text = "Loading...">
Primary
</button>
</div>
<h4>Example to demonstrate .button('reset') method</h4>
<div id = "myButtons3" class = "bs-example">
<button type = "button" class = "btn btn-primary" data-loading-text = "Loading...">
Primary
</button>
</div>
<h4>Example to demonstrate .button(string) method</h4>
<button type = "button" class = "btn btn-primary" id = "myButton4"
data-complete-text = "Loading finished">
Click Me
</button>
<script type = "text/javascript">
$(function () {
$("#myButtons1 .btn").click(function(){
$(this).button('toggle');
});
});
$(function() {
$("#myButtons2 .btn").click(function(){
$(this).button('loading').delay(1000).queue(function() {
});
});
});
$(function() {
$("#myButtons3 .btn").click(function(){
$(this).button('loading').delay(1000).queue(function() {
$(this).button('reset');
});
});
});
$(function() {
$("#myButton4").click(function(){
$(this).button('loading').delay(1000).queue(function() {
$(this).button('complete');
});
});
});
</script>
26 Lectures
2 hours
Anadi Sharma
54 Lectures
4.5 hours
Frahaan Hussain
161 Lectures
14.5 hours
Eduonix Learning Solutions
20 Lectures
4 hours
Azaz Patel
15 Lectures
1.5 hours
Muhammad Ismail
62 Lectures
8 hours
Yossef Ayman Zedan
Print
Add Notes
Bookmark this page
|
[
{
"code": null,
"e": 3526,
"s": 3331,
"text": "Buttons were explained in chapter Bootstrap Buttons. With this plugin you can add in some interaction such as control button states or create groups of buttons for more components like toolbars."
},
{
"code": null,
"e": 3684,
"s": 3526,
"text": "To add a loading state to a button, simply add the data-loading-text = \"Loading...\" as an attribute to the button element as shown in the following example −"
},
{
"code": null,
"e": 4032,
"s": 3684,
"text": "\n<button id = \"fat-btn\" class = \"btn btn-primary\" data-loading-text = \"Loading...\" type = \"button\"> \n Loading state \n</button>\n\n<script>\n $(function() { \n $(\".btn\").click(function(){\n $(this).button('loading').delay(1000).queue(function() {\n // $(this).button('reset');\n }); \n });\n }); \n</script>"
},
{
"code": null,
"e": 4114,
"s": 4032,
"text": "When you click on the button the output would be as seen in the following image −"
},
{
"code": null,
"e": 4334,
"s": 4114,
"text": "To activate toggling (i.e. change the normal state of a button to a push state and vice versa) on a single button, add the data-toggle = \"button\" as an attribute to the button element as shown in the following example −"
},
{
"code": null,
"e": 4436,
"s": 4334,
"text": "\n<button type = \"button\" class = \"btn btn-primary\" data-toggle = \"button\">\n Single toggle\n</button>"
},
{
"code": null,
"e": 4572,
"s": 4436,
"text": "You can create group of checkboxes and add toggling to it by simply adding the data attribute data-toggle = \"buttons\" to the btn-group."
},
{
"code": null,
"e": 4907,
"s": 4572,
"text": "<div class = \"btn-group\" data-toggle = \"buttons\">\n <label class = \"btn btn-primary\">\n <input type = \"checkbox\"> Option 1\n </label>\n \n <label class = \"btn btn-primary\">\n <input type = \"checkbox\"> Option 2\n </label>\n \n <label class = \"btn btn-primary\">\n <input type = \"checkbox\"> Option 3\n </label>\n</div>"
},
{
"code": null,
"e": 5057,
"s": 4907,
"text": "Similarly you can create a group of radio inputs and add toggling to it by simply adding the data attribute data-toggle = \"buttons\" to the btn-group."
},
{
"code": null,
"e": 5480,
"s": 5057,
"text": "<div class = \"btn-group\" data-toggle = \"buttons\">\n <label class = \"btn btn-primary\">\n <input type = \"radio\" name =\" options\" id = \"option1\"> Option 1\n </label>\n \n <label class = \"btn btn-primary\">\n <input type = \"radio\" name = \"options\" id = \"option2\"> Option 2\n </label>\n \n <label class = \"btn btn-primary\">\n <input type = \"radio\" name = \"options\" id = \"option3\"> Option 3\n </label>\n</div>\t"
},
{
"code": null,
"e": 5542,
"s": 5480,
"text": "You can enable buttons plugin via JavaScript as shown below −"
},
{
"code": null,
"e": 5562,
"s": 5542,
"text": "$('.btn').button()\n"
},
{
"code": null,
"e": 5584,
"s": 5562,
"text": "There are no options."
},
{
"code": null,
"e": 5648,
"s": 5584,
"text": "Given below are some of the useful methods for buttons plugin −"
},
{
"code": null,
"e": 5665,
"s": 5648,
"text": "button('toggle')"
},
{
"code": null,
"e": 5827,
"s": 5665,
"text": "Toggles push state. Gives the button the appearance that it has been activated. You can also enable auto toggling of a button by using the data-toggle attribute."
},
{
"code": null,
"e": 5849,
"s": 5827,
"text": "$().button('toggle')\n"
},
{
"code": null,
"e": 5868,
"s": 5849,
"text": ".button('loading')"
},
{
"code": null,
"e": 5998,
"s": 5868,
"text": "When loading, the button is disabled and the text is changed to the option from the data-loading-text attribute of button element"
},
{
"code": null,
"e": 6021,
"s": 5998,
"text": "$().button('loading')\n"
},
{
"code": null,
"e": 6038,
"s": 6021,
"text": ".button('reset')"
},
{
"code": null,
"e": 6190,
"s": 6038,
"text": "Resets button state, bringing the original content back to the text. This method is useful when you need to return the button back to the primary state"
},
{
"code": null,
"e": 6211,
"s": 6190,
"text": "$().button('reset')\n"
},
{
"code": null,
"e": 6227,
"s": 6211,
"text": ".button(string)"
},
{
"code": null,
"e": 6366,
"s": 6227,
"text": "String in this method is referring to any string declared by the user. To reset the button state and bring in new content use this method."
},
{
"code": null,
"e": 6386,
"s": 6366,
"text": "$().button(string)\n"
},
{
"code": null,
"e": 6452,
"s": 6386,
"text": "The following example demonstrates the use of the above methods −"
},
{
"code": null,
"e": 8102,
"s": 6452,
"text": "<h2>Click on each of the buttons to see the effects of methods</h2>\n<h4>Example to demonstrate .button('toggle') method</h4>\n\n<div id = \"myButtons1\" class = \"bs-example\">\n <button type = \"button\" class = \"btn btn-primary\">Primary</button>\n</div>\n\n<h4>Example to demonstrate .button('loading') method</h4>\n\n<div id = \"myButtons2\" class = \"bs-example\">\n <button type = \"button\" class = \"btn btn-primary\" data-loading-text = \"Loading...\">\n Primary\n </button>\n</div>\n\n<h4>Example to demonstrate .button('reset') method</h4>\n\n<div id = \"myButtons3\" class = \"bs-example\">\n <button type = \"button\" class = \"btn btn-primary\" data-loading-text = \"Loading...\">\n Primary\n </button>\n</div>\n\n<h4>Example to demonstrate .button(string) method</h4>\n\n<button type = \"button\" class = \"btn btn-primary\" id = \"myButton4\" \n data-complete-text = \"Loading finished\">\n Click Me\n</button>\n\n<script type = \"text/javascript\">\n $(function () {\n $(\"#myButtons1 .btn\").click(function(){\n $(this).button('toggle');\n });\n });\n \n $(function() { \n $(\"#myButtons2 .btn\").click(function(){\n $(this).button('loading').delay(1000).queue(function() {\n }); \n });\n }); \n \n $(function() { \n $(\"#myButtons3 .btn\").click(function(){\n $(this).button('loading').delay(1000).queue(function() {\n $(this).button('reset');\n }); \n });\n }); \n \n $(function() { \n $(\"#myButton4\").click(function(){\n $(this).button('loading').delay(1000).queue(function() {\n $(this).button('complete');\n }); \n });\n }); \n</script> "
},
{
"code": null,
"e": 8135,
"s": 8102,
"text": "\n 26 Lectures \n 2 hours \n"
},
{
"code": null,
"e": 8149,
"s": 8135,
"text": " Anadi Sharma"
},
{
"code": null,
"e": 8184,
"s": 8149,
"text": "\n 54 Lectures \n 4.5 hours \n"
},
{
"code": null,
"e": 8201,
"s": 8184,
"text": " Frahaan Hussain"
},
{
"code": null,
"e": 8238,
"s": 8201,
"text": "\n 161 Lectures \n 14.5 hours \n"
},
{
"code": null,
"e": 8266,
"s": 8238,
"text": " Eduonix Learning Solutions"
},
{
"code": null,
"e": 8299,
"s": 8266,
"text": "\n 20 Lectures \n 4 hours \n"
},
{
"code": null,
"e": 8311,
"s": 8299,
"text": " Azaz Patel"
},
{
"code": null,
"e": 8346,
"s": 8311,
"text": "\n 15 Lectures \n 1.5 hours \n"
},
{
"code": null,
"e": 8363,
"s": 8346,
"text": " Muhammad Ismail"
},
{
"code": null,
"e": 8396,
"s": 8363,
"text": "\n 62 Lectures \n 8 hours \n"
},
{
"code": null,
"e": 8416,
"s": 8396,
"text": " Yossef Ayman Zedan"
},
{
"code": null,
"e": 8423,
"s": 8416,
"text": " Print"
},
{
"code": null,
"e": 8434,
"s": 8423,
"text": " Add Notes"
}
] |
How do we use runOnUiThread in Android?
|
Before getting into example, we should know what is runOnUiThread() in android. Sometimes Main thread performs some heavy operations. if user wants to add some extra operations on UI, it will get load and provides ANR. Using runOnUiThread going to do back ground operations on worker thread and update the result on main thread.
This example demonstrate about How do we use runOnUiThread in Android.
Step 1 − Create a new project in Android Studio, go to File ⇒ New Project and fill all required details to create a new project.
Step 2 − Add the following code to res/layout/activity_main.xml.
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/parent"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity"
android:gravity="center"
android:orientation="vertical">
<Button
android:id="@+id/runOn"
android:text="Run"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
<TextView
android:id="@+id/text"
android:textSize="20sp"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
</LinearLayout>
In the above code, we have taken one button and text view, when you click on button , it will update text view.
Step 3 − Add the following code to src/MainActivity.java
package com.example.andy.myapplication;
import android.os.Build;
import android.os.Bundle;
import android.support.annotation.RequiresApi;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
public class MainActivity extends AppCompatActivity {
int i = 0;
@RequiresApi(api = Build.VERSION_CODES.JELLY_BEAN)
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final TextView textView = findViewById(R.id.text);
final Button runOn = findViewById(R.id.runOn);
runOn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
new Thread() {
public void run() {
while (i++ < 1000) {
try {
runOnUiThread(new Runnable() {
@Override
public void run() {
textView.setText("#" + i);
}
});
Thread.sleep(300);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}.start();
}
});
}
}
In the above code, when user click on button. It will update text view using runOnUiThread() as shown below -
new Thread() {
public void run() {
while (i++ < 1000) {
try {
runOnUiThread(new Runnable() {
@Override
public void run() {
textView.setText("#" + i);
}
});
Thread.sleep(300);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}.start();
Let's try to run your application. I assume you have connected your actual Android Mobile device with your computer. To run the app from android studio, open one of your project's activity files and click Run icon from the toolbar. Select your mobile device as an option and then check your mobile device which will display your default screen −
In the above result, it shown initial screen. when user click on run button it will update text view as shown below -
Click here to download the project code
|
[
{
"code": null,
"e": 1391,
"s": 1062,
"text": "Before getting into example, we should know what is runOnUiThread() in android. Sometimes Main thread performs some heavy operations. if user wants to add some extra operations on UI, it will get load and provides ANR. Using runOnUiThread going to do back ground operations on worker thread and update the result on main thread."
},
{
"code": null,
"e": 1462,
"s": 1391,
"text": "This example demonstrate about How do we use runOnUiThread in Android."
},
{
"code": null,
"e": 1591,
"s": 1462,
"text": "Step 1 − Create a new project in Android Studio, go to File ⇒ New Project and fill all required details to create a new project."
},
{
"code": null,
"e": 1656,
"s": 1591,
"text": "Step 2 − Add the following code to res/layout/activity_main.xml."
},
{
"code": null,
"e": 2351,
"s": 1656,
"text": "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<LinearLayout xmlns:android=\"http://schemas.android.com/apk/res/android\"\n android:id=\"@+id/parent\"\n xmlns:tools=\"http://schemas.android.com/tools\"\n android:layout_width=\"match_parent\"\n android:layout_height=\"match_parent\"\n tools:context=\".MainActivity\"\n android:gravity=\"center\"\n android:orientation=\"vertical\">\n <Button\n android:id=\"@+id/runOn\"\n android:text=\"Run\"\n android:layout_width=\"wrap_content\"\n android:layout_height=\"wrap_content\" />\n <TextView\n android:id=\"@+id/text\"\n android:textSize=\"20sp\"\n android:layout_width=\"wrap_content\"\n android:layout_height=\"wrap_content\" />\n</LinearLayout>"
},
{
"code": null,
"e": 2463,
"s": 2351,
"text": "In the above code, we have taken one button and text view, when you click on button , it will update text view."
},
{
"code": null,
"e": 2520,
"s": 2463,
"text": "Step 3 − Add the following code to src/MainActivity.java"
},
{
"code": null,
"e": 3939,
"s": 2520,
"text": "package com.example.andy.myapplication;\nimport android.os.Build;\nimport android.os.Bundle;\nimport android.support.annotation.RequiresApi;\nimport android.support.v7.app.AppCompatActivity;\nimport android.view.View;\nimport android.widget.Button;\nimport android.widget.TextView;\n\npublic class MainActivity extends AppCompatActivity {\n int i = 0;\n @RequiresApi(api = Build.VERSION_CODES.JELLY_BEAN)\n @Override\n protected void onCreate(Bundle savedInstanceState) {\n super.onCreate(savedInstanceState);\n setContentView(R.layout.activity_main);\n final TextView textView = findViewById(R.id.text);\n final Button runOn = findViewById(R.id.runOn);\n runOn.setOnClickListener(new View.OnClickListener() {\n @Override\n public void onClick(View v) {\n new Thread() {\n public void run() {\n while (i++ < 1000) {\n try {\n runOnUiThread(new Runnable() {\n @Override\n public void run() {\n textView.setText(\"#\" + i);\n }\n });\n Thread.sleep(300);\n } catch (InterruptedException e) {\n e.printStackTrace();\n }\n }\n }\n }.start();\n }\n });\n }\n}"
},
{
"code": null,
"e": 4049,
"s": 3939,
"text": "In the above code, when user click on button. It will update text view using runOnUiThread() as shown below -"
},
{
"code": null,
"e": 4453,
"s": 4049,
"text": "new Thread() {\n public void run() {\n while (i++ < 1000) {\n try {\n runOnUiThread(new Runnable() {\n @Override\n public void run() {\n textView.setText(\"#\" + i);\n }\n });\n Thread.sleep(300);\n } catch (InterruptedException e) {\n e.printStackTrace();\n }\n }\n }\n}.start();"
},
{
"code": null,
"e": 4800,
"s": 4453,
"text": "Let's try to run your application. I assume you have connected your actual Android Mobile device with your computer. To run the app from android studio, open one of your project's activity files and click Run icon from the toolbar. Select your mobile device as an option and then check your mobile device which will display your default screen −"
},
{
"code": null,
"e": 4918,
"s": 4800,
"text": "In the above result, it shown initial screen. when user click on run button it will update text view as shown below -"
},
{
"code": null,
"e": 4958,
"s": 4918,
"text": "Click here to download the project code"
}
] |
Handling Browser Authentication using Selenium
|
We can handle browser authentication with Selenium webdriver. We have to pass the credentials appended with the URL. The username and password must be added with the format: https://username:password@URL. Let us make an attempt to handle the below browser authentication.
Once the User Name and Password are entered correctly and the OK button is clicked, we are navigated to the actual page with the text Congratulations! You must have the proper credentials.
https://username:password@URL
https://admin:admin@the−internet.herokuapp.com/basic_auth
Here, the username and password value is admin.
URL is www.the−internet.herokuapp.com/basic_auth
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
public class BrwAuthnPopup{
public static void main(String[] args) {
System.setProperty("webdriver.chrome.driver",
"C:\\Users\\ghs6kor\\Desktop\\Java\\chromedriver.exe");
WebDriver driver = new ChromeDriver();
String a = "admin";
// appending username, password with URL
String s = "https://" + a + ":" + a + "@" +
"the-internet.herokuapp.com/basic_auth";
driver.get(s);
// identify text
String m = driver.findElement(By.cssSelector("p")).getText();
System.out.println("Text is: " + m);
driver.close();
}
}
|
[
{
"code": null,
"e": 1334,
"s": 1062,
"text": "We can handle browser authentication with Selenium webdriver. We have to pass the credentials appended with the URL. The username and password must be added with the format: https://username:password@URL. Let us make an attempt to handle the below browser authentication."
},
{
"code": null,
"e": 1523,
"s": 1334,
"text": "Once the User Name and Password are entered correctly and the OK button is clicked, we are navigated to the actual page with the text Congratulations! You must have the proper credentials."
},
{
"code": null,
"e": 1611,
"s": 1523,
"text": "https://username:password@URL\nhttps://admin:admin@the−internet.herokuapp.com/basic_auth"
},
{
"code": null,
"e": 1659,
"s": 1611,
"text": "Here, the username and password value is admin."
},
{
"code": null,
"e": 1708,
"s": 1659,
"text": "URL is www.the−internet.herokuapp.com/basic_auth"
},
{
"code": null,
"e": 2449,
"s": 1708,
"text": "import org.openqa.selenium.By;\nimport org.openqa.selenium.WebDriver;\nimport org.openqa.selenium.WebElement;\nimport org.openqa.selenium.chrome.ChromeDriver;\npublic class BrwAuthnPopup{\n public static void main(String[] args) {\n System.setProperty(\"webdriver.chrome.driver\",\n \"C:\\\\Users\\\\ghs6kor\\\\Desktop\\\\Java\\\\chromedriver.exe\");\n WebDriver driver = new ChromeDriver();\n String a = \"admin\";\n // appending username, password with URL\n String s = \"https://\" + a + \":\" + a + \"@\" +\n \"the-internet.herokuapp.com/basic_auth\";\n driver.get(s);\n // identify text\n String m = driver.findElement(By.cssSelector(\"p\")).getText();\n System.out.println(\"Text is: \" + m);\n driver.close();\n }\n}"
}
] |
C++ interview questions on virtual function and abstract class - GeeksforGeeks
|
01 Sep, 2018
1. What is a pure virtual function?
Ans. A pure virtual function (or abstract function) in C++ is a virtual function for which we don’t have implementation, we only declare it. A pure virtual function is declared by assigning 0 in declaration. See the following example.
// An abstract classclass Test { // Data members of classpublic: // Pure Virtual Function virtual void show() = 0; /* Other members */};
2. What is abstract class?Ans. A class which contains atleast one pure virtual function, is known as abstract class. see the following example
// An abstract classclass Test { // Data members of classpublic: // Pure Virtual Function virtual void show() = 0; /* Other members */};
in above example, Test is an abstract class because it has a pure virtual function.
Some interesting facts about abstract class1) We can’t create an object of abstract class.
// pure virtual functions make a class abstract#include <iostream>using namespace std; class Test { int x; public: virtual void show() = 0; int getX() { return x; }}; int main(void){ Test t; return 0;}
Output :
Compiler Error: cannot declare variable 't' to be of abstract
type 'Test' because the following virtual functions are pure
within 'Test': note: virtual void Test::show()
2.We can have pointers and references of abstract class type.For example the following program works fine.
#include <iostream>using namespace std; class Base {public: virtual void show() = 0;}; class Derived : public Base {public: void show() { cout << "In Derived \n"; }}; int main(void){ Base* bp = new Derived(); bp->show(); return 0;}
Output:
In Derived
3. If we do not override the pure virtual function in derived class, then derived class also becomes abstract class.The following example demonstrates the same.
#include <iostream>using namespace std;class Base {public: virtual void show() = 0;}; class Derived : public Base {}; int main(void){ Derived d; return 0;}
output:
Compiler Error: cannot declare variable 'd' to be of abstract type
'Derived' because the following virtual functions are pure within
'Derived': virtual void Base::show()
3. What is the output of this program?
#include <iostream>using namespace std;class Test {protected: int width, height; public: void set_values(int a, int b) { width = a; height = b; } virtual int area(void) = 0;};class r : public Test {public: int area(void) { return (width * height); }};class t : public Test {public: int area(void) { return (width * height / 2); }};int main(){ r rect; t trgl; Test* ppoly1 = ▭ Test* ppoly2 = &trgl; ppoly1->set_values(4, 5); ppoly2->set_values(4, 5); cout << ppoly1->area(); cout << ppoly2->area(); return 0;}
output:
2010
Explanation: In this program, we are calculating the area of rectangle andtriangle by using abstract class.
4. What is the output of this program?
#include <iostream>using namespace std;class Base {public: virtual void print() const = 0;};class DerivedOne : virtual public Base {public: void print() const { cout << "1"; }};class DerivedTwo : virtual public Base {public: void print() const { cout << "2"; }};class Multiple : public DerivedOne, DerivedTwo {public: void print() const { DerivedTwo::print(); }};int main(){ Multiple both; DerivedOne one; DerivedTwo two; Base* array[3]; array[0] = &both; array[1] = &one; array[2] = &two; for (int i = 0; i < 3; i++) array[i]->print(); return 0;}
output
212
Explanation: In this program, We are executing these based on the condition given in array. So it is printing as 212.
5. What is the output of this program?
#include <iostream>using namespace std;class sample {public: virtual void example() = 0;};class Ex1 : public sample {public: void example() { cout << "GeeksForGeeks"; }};class Ex2 : public sample {public: void example() { cout << " is awesome"; }};int main(){ sample* arra[2]; Ex1 e1; Ex2 e2; arra[0] = &e1; arra[1] = &e2; arra[0]->example(); arra[1]->example();}
Output:
GeeksForGeeks is awesome
Explanation: In this program, We are combining the two statements from two classes and printing it by using abstract class.
cpp-inheritance
cpp-virtual
C++
CS - Placements
CPP
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Operator Overloading in C++
Polymorphism in C++
Friend class and function in C++
Sorting a vector in C++
std::string class in C++
Applications of linked list data structure
Most asked Computer Science Subjects Interview Questions in Amazon, Microsoft, Flipkart
TCS Interview Questions
Count of substrings of length K with exactly K distinct characters
Hotel Management System
|
[
{
"code": null,
"e": 25367,
"s": 25339,
"text": "\n01 Sep, 2018"
},
{
"code": null,
"e": 25403,
"s": 25367,
"text": "1. What is a pure virtual function?"
},
{
"code": null,
"e": 25638,
"s": 25403,
"text": "Ans. A pure virtual function (or abstract function) in C++ is a virtual function for which we don’t have implementation, we only declare it. A pure virtual function is declared by assigning 0 in declaration. See the following example."
},
{
"code": "// An abstract classclass Test { // Data members of classpublic: // Pure Virtual Function virtual void show() = 0; /* Other members */};",
"e": 25789,
"s": 25638,
"text": null
},
{
"code": null,
"e": 25932,
"s": 25789,
"text": "2. What is abstract class?Ans. A class which contains atleast one pure virtual function, is known as abstract class. see the following example"
},
{
"code": "// An abstract classclass Test { // Data members of classpublic: // Pure Virtual Function virtual void show() = 0; /* Other members */};",
"e": 26083,
"s": 25932,
"text": null
},
{
"code": null,
"e": 26167,
"s": 26083,
"text": "in above example, Test is an abstract class because it has a pure virtual function."
},
{
"code": null,
"e": 26258,
"s": 26167,
"text": "Some interesting facts about abstract class1) We can’t create an object of abstract class."
},
{
"code": "// pure virtual functions make a class abstract#include <iostream>using namespace std; class Test { int x; public: virtual void show() = 0; int getX() { return x; }}; int main(void){ Test t; return 0;}",
"e": 26478,
"s": 26258,
"text": null
},
{
"code": null,
"e": 26487,
"s": 26478,
"text": "Output :"
},
{
"code": null,
"e": 26665,
"s": 26487,
"text": "Compiler Error: cannot declare variable 't' to be of abstract\n type 'Test' because the following virtual functions are pure \nwithin 'Test': note: virtual void Test::show() \n"
},
{
"code": null,
"e": 26772,
"s": 26665,
"text": "2.We can have pointers and references of abstract class type.For example the following program works fine."
},
{
"code": "#include <iostream>using namespace std; class Base {public: virtual void show() = 0;}; class Derived : public Base {public: void show() { cout << \"In Derived \\n\"; }}; int main(void){ Base* bp = new Derived(); bp->show(); return 0;}",
"e": 27022,
"s": 26772,
"text": null
},
{
"code": null,
"e": 27030,
"s": 27022,
"text": "Output:"
},
{
"code": null,
"e": 27043,
"s": 27030,
"text": " In Derived "
},
{
"code": null,
"e": 27204,
"s": 27043,
"text": "3. If we do not override the pure virtual function in derived class, then derived class also becomes abstract class.The following example demonstrates the same."
},
{
"code": "#include <iostream>using namespace std;class Base {public: virtual void show() = 0;}; class Derived : public Base {}; int main(void){ Derived d; return 0;}",
"e": 27371,
"s": 27204,
"text": null
},
{
"code": null,
"e": 27379,
"s": 27371,
"text": "output:"
},
{
"code": null,
"e": 27553,
"s": 27379,
"text": "Compiler Error: cannot declare variable 'd' to be of abstract type \n'Derived' because the following virtual functions are pure within\n'Derived': virtual void Base::show() \n"
},
{
"code": null,
"e": 27592,
"s": 27553,
"text": "3. What is the output of this program?"
},
{
"code": "#include <iostream>using namespace std;class Test {protected: int width, height; public: void set_values(int a, int b) { width = a; height = b; } virtual int area(void) = 0;};class r : public Test {public: int area(void) { return (width * height); }};class t : public Test {public: int area(void) { return (width * height / 2); }};int main(){ r rect; t trgl; Test* ppoly1 = ▭ Test* ppoly2 = &trgl; ppoly1->set_values(4, 5); ppoly2->set_values(4, 5); cout << ppoly1->area(); cout << ppoly2->area(); return 0;}",
"e": 28190,
"s": 27592,
"text": null
},
{
"code": null,
"e": 28198,
"s": 28190,
"text": "output:"
},
{
"code": null,
"e": 28203,
"s": 28198,
"text": "2010"
},
{
"code": null,
"e": 28311,
"s": 28203,
"text": "Explanation: In this program, we are calculating the area of rectangle andtriangle by using abstract class."
},
{
"code": null,
"e": 28350,
"s": 28311,
"text": "4. What is the output of this program?"
},
{
"code": "#include <iostream>using namespace std;class Base {public: virtual void print() const = 0;};class DerivedOne : virtual public Base {public: void print() const { cout << \"1\"; }};class DerivedTwo : virtual public Base {public: void print() const { cout << \"2\"; }};class Multiple : public DerivedOne, DerivedTwo {public: void print() const { DerivedTwo::print(); }};int main(){ Multiple both; DerivedOne one; DerivedTwo two; Base* array[3]; array[0] = &both; array[1] = &one; array[2] = &two; for (int i = 0; i < 3; i++) array[i]->print(); return 0;}",
"e": 28983,
"s": 28350,
"text": null
},
{
"code": null,
"e": 28990,
"s": 28983,
"text": "output"
},
{
"code": null,
"e": 28994,
"s": 28990,
"text": "212"
},
{
"code": null,
"e": 29112,
"s": 28994,
"text": "Explanation: In this program, We are executing these based on the condition given in array. So it is printing as 212."
},
{
"code": null,
"e": 29151,
"s": 29112,
"text": "5. What is the output of this program?"
},
{
"code": "#include <iostream>using namespace std;class sample {public: virtual void example() = 0;};class Ex1 : public sample {public: void example() { cout << \"GeeksForGeeks\"; }};class Ex2 : public sample {public: void example() { cout << \" is awesome\"; }};int main(){ sample* arra[2]; Ex1 e1; Ex2 e2; arra[0] = &e1; arra[1] = &e2; arra[0]->example(); arra[1]->example();}",
"e": 29571,
"s": 29151,
"text": null
},
{
"code": null,
"e": 29579,
"s": 29571,
"text": "Output:"
},
{
"code": null,
"e": 29605,
"s": 29579,
"text": " GeeksForGeeks is awesome"
},
{
"code": null,
"e": 29729,
"s": 29605,
"text": "Explanation: In this program, We are combining the two statements from two classes and printing it by using abstract class."
},
{
"code": null,
"e": 29745,
"s": 29729,
"text": "cpp-inheritance"
},
{
"code": null,
"e": 29757,
"s": 29745,
"text": "cpp-virtual"
},
{
"code": null,
"e": 29761,
"s": 29757,
"text": "C++"
},
{
"code": null,
"e": 29777,
"s": 29761,
"text": "CS - Placements"
},
{
"code": null,
"e": 29781,
"s": 29777,
"text": "CPP"
},
{
"code": null,
"e": 29879,
"s": 29781,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 29907,
"s": 29879,
"text": "Operator Overloading in C++"
},
{
"code": null,
"e": 29927,
"s": 29907,
"text": "Polymorphism in C++"
},
{
"code": null,
"e": 29960,
"s": 29927,
"text": "Friend class and function in C++"
},
{
"code": null,
"e": 29984,
"s": 29960,
"text": "Sorting a vector in C++"
},
{
"code": null,
"e": 30009,
"s": 29984,
"text": "std::string class in C++"
},
{
"code": null,
"e": 30052,
"s": 30009,
"text": "Applications of linked list data structure"
},
{
"code": null,
"e": 30140,
"s": 30052,
"text": "Most asked Computer Science Subjects Interview Questions in Amazon, Microsoft, Flipkart"
},
{
"code": null,
"e": 30164,
"s": 30140,
"text": "TCS Interview Questions"
},
{
"code": null,
"e": 30231,
"s": 30164,
"text": "Count of substrings of length K with exactly K distinct characters"
}
] |
Mathematics | Independent Sets, Covering and Matching - GeeksforGeeks
|
13 Dec, 2019
1. Independent Sets –
A set of vertices I is called independent set if no two vertices in set I are adjacent to each other or in other words the set of non-adjacent vertices is called independent set.
It is also called a stable set.
The parameter α0(G) = max { |I|: I is an independent set in G } is called independence number of G i.e the maximum number of non-adjacent vertices.
Any independent set I with |I| = α0(G) is called a maximum independent set.For above given graph G, Independent sets are:I1 = {1}, I2 = {2}, I3 = {3}, I4 = {4}
I5 = {1, 3} and I6 = {2, 4} Therefore, maximum number of non-adjacent vertices i.e Independence number α0(G) = 2.
For above given graph G, Independent sets are:
I1 = {1}, I2 = {2}, I3 = {3}, I4 = {4}
I5 = {1, 3} and I6 = {2, 4}
Therefore, maximum number of non-adjacent vertices i.e Independence number α0(G) = 2.
2. Vertex Covering –
A set of vertices K which can cover all the edges of graph G is called a vertex cover of G i.e. if every edge of G is covered by a vertex in set K.
The parameter β0(G) = min { |K|: K is a vertex cover of G } is called vertex covering number of G i.e the minimum number of vertices which can cover all the edges.
Any vertex cover K with |K| = β0(G) is called a minimum vertex cover.For above given graph G, Vertex cover is:V1 = {1, 3}, V2 = {2, 4},
V3 = {1, 2, 3}, V4 = {1, 2, 3, 4}, etc. Therefore, minimum number of vertices which can cover all edges, i.e., Vertex covering number β0(G) = 2.
For above given graph G, Vertex cover is:
V1 = {1, 3}, V2 = {2, 4},
V3 = {1, 2, 3}, V4 = {1, 2, 3, 4}, etc.
Therefore, minimum number of vertices which can cover all edges, i.e., Vertex covering number β0(G) = 2.
Notes –
I is an independent set in G iff V(G) – I is vertex cover of G.
For any graph G, α0(G) + β0(G) = n, where n is number of vertices in G.
Edge Covering –
A set of edges F which can cover all the vertices of graph G is called a edge cover of G i.e. if every vertex in G is incident with a edge in F.
The parameter β1(G) = min { |F|: F is an edge cover of G } is called edge covering number of G i.e sum of minimum number of edges which can cover all the vertices and number of isolated vertices(if exist).
Any edge cover F with |F| = β1(G) is called a minimum edge cover.
For above given graph G, Edge cover is:
E1 = {a, b, c, d},
E2 = {a, d} and E3 = {b, c}.
Therefore, minimum number of edges which can cover all vertices, i.e., Edge covering number β1(G) = 2.
Note – For any graph G, α1(G) + β1(G) = n, where n is number of vertices in G.
3. Matching –
The set of non-adjacent edges is called matching i.e independent set of edges in G such that no two edges are adjacent in the set.
he parameter α1(G) = max { |M|: M is a matching in G } is called matching number of G i.e the maximum number of non-adjacent edges.
Any matching M with |M| = α1(G) is called a maximum matching.
For above given graph G, Matching are:
M1 = {a}, M2 = {b}, M3 = {c}, M4 = {d}
M5 = {a, d} and M6 = {b, c}
Therefore, maximum number of non-adjacent edges i.e matching number α1(G) = 2.
Complete Matching:A matching of a graph G is complete if it contains all of G’svertices. Sometimes this is also called a perfect matching.HALL’S MARRIAGE THEOREM: The bipartite graph G =(V, E) with bipartition (V1, V2) has a complete matching from V1 to V2 if and only if |N (A)| > |A| for all subsets A of V1. (This is both necessary and sufficient condition for complete matching.)
RahulWankhede
AkhilYalal
VaibhavRai3
Discrete Mathematics
Engineering Mathematics
GATE CS
Technical Scripter
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Inequalities in LaTeX
Activation Functions
Arrow Symbols in LaTeX
Newton's Divided Difference Interpolation Formula
Set Notations in LaTeX
Layers of OSI Model
ACID Properties in DBMS
TCP/IP Model
Types of Operating Systems
Normal Forms in DBMS
|
[
{
"code": null,
"e": 31277,
"s": 31249,
"text": "\n13 Dec, 2019"
},
{
"code": null,
"e": 31299,
"s": 31277,
"text": "1. Independent Sets –"
},
{
"code": null,
"e": 31478,
"s": 31299,
"text": "A set of vertices I is called independent set if no two vertices in set I are adjacent to each other or in other words the set of non-adjacent vertices is called independent set."
},
{
"code": null,
"e": 31510,
"s": 31478,
"text": "It is also called a stable set."
},
{
"code": null,
"e": 31658,
"s": 31510,
"text": "The parameter α0(G) = max { |I|: I is an independent set in G } is called independence number of G i.e the maximum number of non-adjacent vertices."
},
{
"code": null,
"e": 31932,
"s": 31658,
"text": "Any independent set I with |I| = α0(G) is called a maximum independent set.For above given graph G, Independent sets are:I1 = {1}, I2 = {2}, I3 = {3}, I4 = {4}\nI5 = {1, 3} and I6 = {2, 4} Therefore, maximum number of non-adjacent vertices i.e Independence number α0(G) = 2."
},
{
"code": null,
"e": 31979,
"s": 31932,
"text": "For above given graph G, Independent sets are:"
},
{
"code": null,
"e": 32047,
"s": 31979,
"text": "I1 = {1}, I2 = {2}, I3 = {3}, I4 = {4}\nI5 = {1, 3} and I6 = {2, 4} "
},
{
"code": null,
"e": 32133,
"s": 32047,
"text": "Therefore, maximum number of non-adjacent vertices i.e Independence number α0(G) = 2."
},
{
"code": null,
"e": 32154,
"s": 32133,
"text": "2. Vertex Covering –"
},
{
"code": null,
"e": 32302,
"s": 32154,
"text": "A set of vertices K which can cover all the edges of graph G is called a vertex cover of G i.e. if every edge of G is covered by a vertex in set K."
},
{
"code": null,
"e": 32466,
"s": 32302,
"text": "The parameter β0(G) = min { |K|: K is a vertex cover of G } is called vertex covering number of G i.e the minimum number of vertices which can cover all the edges."
},
{
"code": null,
"e": 32749,
"s": 32466,
"text": "Any vertex cover K with |K| = β0(G) is called a minimum vertex cover.For above given graph G, Vertex cover is:V1 = {1, 3}, V2 = {2, 4}, \nV3 = {1, 2, 3}, V4 = {1, 2, 3, 4}, etc. Therefore, minimum number of vertices which can cover all edges, i.e., Vertex covering number β0(G) = 2."
},
{
"code": null,
"e": 32791,
"s": 32749,
"text": "For above given graph G, Vertex cover is:"
},
{
"code": null,
"e": 32860,
"s": 32791,
"text": "V1 = {1, 3}, V2 = {2, 4}, \nV3 = {1, 2, 3}, V4 = {1, 2, 3, 4}, etc. "
},
{
"code": null,
"e": 32965,
"s": 32860,
"text": "Therefore, minimum number of vertices which can cover all edges, i.e., Vertex covering number β0(G) = 2."
},
{
"code": null,
"e": 32973,
"s": 32965,
"text": "Notes –"
},
{
"code": null,
"e": 33037,
"s": 32973,
"text": "I is an independent set in G iff V(G) – I is vertex cover of G."
},
{
"code": null,
"e": 33109,
"s": 33037,
"text": "For any graph G, α0(G) + β0(G) = n, where n is number of vertices in G."
},
{
"code": null,
"e": 33125,
"s": 33109,
"text": "Edge Covering –"
},
{
"code": null,
"e": 33270,
"s": 33125,
"text": "A set of edges F which can cover all the vertices of graph G is called a edge cover of G i.e. if every vertex in G is incident with a edge in F."
},
{
"code": null,
"e": 33476,
"s": 33270,
"text": "The parameter β1(G) = min { |F|: F is an edge cover of G } is called edge covering number of G i.e sum of minimum number of edges which can cover all the vertices and number of isolated vertices(if exist)."
},
{
"code": null,
"e": 33542,
"s": 33476,
"text": "Any edge cover F with |F| = β1(G) is called a minimum edge cover."
},
{
"code": null,
"e": 33582,
"s": 33542,
"text": "For above given graph G, Edge cover is:"
},
{
"code": null,
"e": 33633,
"s": 33582,
"text": "E1 = {a, b, c, d}, \nE2 = {a, d} and E3 = {b, c}. "
},
{
"code": null,
"e": 33736,
"s": 33633,
"text": "Therefore, minimum number of edges which can cover all vertices, i.e., Edge covering number β1(G) = 2."
},
{
"code": null,
"e": 33815,
"s": 33736,
"text": "Note – For any graph G, α1(G) + β1(G) = n, where n is number of vertices in G."
},
{
"code": null,
"e": 33829,
"s": 33815,
"text": "3. Matching –"
},
{
"code": null,
"e": 33960,
"s": 33829,
"text": "The set of non-adjacent edges is called matching i.e independent set of edges in G such that no two edges are adjacent in the set."
},
{
"code": null,
"e": 34092,
"s": 33960,
"text": "he parameter α1(G) = max { |M|: M is a matching in G } is called matching number of G i.e the maximum number of non-adjacent edges."
},
{
"code": null,
"e": 34154,
"s": 34092,
"text": "Any matching M with |M| = α1(G) is called a maximum matching."
},
{
"code": null,
"e": 34193,
"s": 34154,
"text": "For above given graph G, Matching are:"
},
{
"code": null,
"e": 34261,
"s": 34193,
"text": "M1 = {a}, M2 = {b}, M3 = {c}, M4 = {d}\nM5 = {a, d} and M6 = {b, c} "
},
{
"code": null,
"e": 34340,
"s": 34261,
"text": "Therefore, maximum number of non-adjacent edges i.e matching number α1(G) = 2."
},
{
"code": null,
"e": 34724,
"s": 34340,
"text": "Complete Matching:A matching of a graph G is complete if it contains all of G’svertices. Sometimes this is also called a perfect matching.HALL’S MARRIAGE THEOREM: The bipartite graph G =(V, E) with bipartition (V1, V2) has a complete matching from V1 to V2 if and only if |N (A)| > |A| for all subsets A of V1. (This is both necessary and sufficient condition for complete matching.)"
},
{
"code": null,
"e": 34738,
"s": 34724,
"text": "RahulWankhede"
},
{
"code": null,
"e": 34749,
"s": 34738,
"text": "AkhilYalal"
},
{
"code": null,
"e": 34761,
"s": 34749,
"text": "VaibhavRai3"
},
{
"code": null,
"e": 34782,
"s": 34761,
"text": "Discrete Mathematics"
},
{
"code": null,
"e": 34806,
"s": 34782,
"text": "Engineering Mathematics"
},
{
"code": null,
"e": 34814,
"s": 34806,
"text": "GATE CS"
},
{
"code": null,
"e": 34833,
"s": 34814,
"text": "Technical Scripter"
},
{
"code": null,
"e": 34931,
"s": 34833,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 34953,
"s": 34931,
"text": "Inequalities in LaTeX"
},
{
"code": null,
"e": 34974,
"s": 34953,
"text": "Activation Functions"
},
{
"code": null,
"e": 34997,
"s": 34974,
"text": "Arrow Symbols in LaTeX"
},
{
"code": null,
"e": 35047,
"s": 34997,
"text": "Newton's Divided Difference Interpolation Formula"
},
{
"code": null,
"e": 35070,
"s": 35047,
"text": "Set Notations in LaTeX"
},
{
"code": null,
"e": 35090,
"s": 35070,
"text": "Layers of OSI Model"
},
{
"code": null,
"e": 35114,
"s": 35090,
"text": "ACID Properties in DBMS"
},
{
"code": null,
"e": 35127,
"s": 35114,
"text": "TCP/IP Model"
},
{
"code": null,
"e": 35154,
"s": 35127,
"text": "Types of Operating Systems"
}
] |
Hello World in TypeScript - GeeksforGeeks
|
15 Jul, 2021
TypeScript is an open-source programming language. It is developed and maintained by Microsoft. TypeScript follows javascript syntactically but adds more features to it. It is a superset of javascript. The diagram below depicts the relationship:
Typescript is purely object-oriented with features like classes, objects and interfaces just like Java. Previously for javascript variables and objects, we need not mention their data types, which makes overall logic difficult to understand because we didn’t know what type of data are we dealing with. Typescript fixes this problem and provides developers with a way to state the data types for variables and objects.Some of the built-in types that typescript provides are:
number : 64-bit double precision numbers for both integers and fractions.string : a sequence of characters or string type data.void : used for functions that return nothing.null : represents no value or null valueboolean : represents a boolean value either true or false
number : 64-bit double precision numbers for both integers and fractions.
string : a sequence of characters or string type data.
void : used for functions that return nothing.
null : represents no value or null value
boolean : represents a boolean value either true or false
Syntax to define variables:
var variable_name : type;
Example :
javascript
// declares a string type variable called name.var name: string; // declares a number type variable called amount.var amount: number; // declares a boolean type variable called check;var checked: boolean; // declares a string type variable called first_name and// initializes with some value.var first_name: string = "geeksforgeeks"; // declares an array of numbers called digits.var digits: number[];
Syntax to define classes, objects and functions:
class Class_Name{
// instance variables
// constructor
// Typescript allows only one constructor per class
constructor(parameters){
}
// methods
}
var object_name:class_name;
function_name(): returntype{
// function_body
}
Examples:
javascript
class Name { first_name: string; last_name: string; constructor(fname: string, lname: string) { first_name = fname; last_name = lname; } getName(): string { var fullname: string = first_name + last_name; return fullname; }} var author_name: Name;
Running a Typescript code
Browsers natively does not understand typescript, but they understand javascript. So in order to run typescript codes, first it is transpiled to javascript. tsc : is a typescript compiler(transpiler) that converts typescript code into javascript.You can install tsc by running following command:
npm install -g typescript
Creating a basic typescript code that will print “Greetings from Geeks For Geeks” :
javascript
var greet: string = "Greetings";var geeks: string = "Geeks For Geeks";console.log(greet + " from " + geeks);// save the file as hello.ts
To compile typescript code we can run the following command on the command line.tsc hello.tsThis command will generate a javascript file with name hello.jsRun the javascript file using the following command on command line:node hello.js
To compile typescript code we can run the following command on the command line.tsc hello.tsThis command will generate a javascript file with name hello.js
tsc hello.ts
This command will generate a javascript file with name hello.js
Run the javascript file using the following command on command line:node hello.js
node hello.js
You should see an output as below on your command line:
Greetings from Geeks For Geeks
Applications of TypeScript Language :
Angular 2+ versions are written is typescript and uses typescript, which proves it’s efficiency in industrial uses.
Typescript makes compile time error diagnosis easy.
Typescript is scalable and well supports large applications.
References 1. http://www.typescriptlang.org/ 2. http://www.typescriptlang.org/docs/index.html
saurabh1990aror
JavaScript-Misc
TypeScript
JavaScript
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Remove elements from a JavaScript Array
Convert a string to an integer in JavaScript
Difference between var, let and const keywords in JavaScript
Differences between Functional Components and Class Components in React
How to append HTML code to a div using JavaScript ?
Remove elements from a JavaScript Array
Installation of Node.js on Linux
Convert a string to an integer in JavaScript
How to fetch data from an API in ReactJS ?
How to insert spaces/tabs in text using HTML/CSS?
|
[
{
"code": null,
"e": 25703,
"s": 25675,
"text": "\n15 Jul, 2021"
},
{
"code": null,
"e": 25951,
"s": 25703,
"text": "TypeScript is an open-source programming language. It is developed and maintained by Microsoft. TypeScript follows javascript syntactically but adds more features to it. It is a superset of javascript. The diagram below depicts the relationship: "
},
{
"code": null,
"e": 26428,
"s": 25951,
"text": "Typescript is purely object-oriented with features like classes, objects and interfaces just like Java. Previously for javascript variables and objects, we need not mention their data types, which makes overall logic difficult to understand because we didn’t know what type of data are we dealing with. Typescript fixes this problem and provides developers with a way to state the data types for variables and objects.Some of the built-in types that typescript provides are: "
},
{
"code": null,
"e": 26699,
"s": 26428,
"text": "number : 64-bit double precision numbers for both integers and fractions.string : a sequence of characters or string type data.void : used for functions that return nothing.null : represents no value or null valueboolean : represents a boolean value either true or false"
},
{
"code": null,
"e": 26773,
"s": 26699,
"text": "number : 64-bit double precision numbers for both integers and fractions."
},
{
"code": null,
"e": 26828,
"s": 26773,
"text": "string : a sequence of characters or string type data."
},
{
"code": null,
"e": 26875,
"s": 26828,
"text": "void : used for functions that return nothing."
},
{
"code": null,
"e": 26916,
"s": 26875,
"text": "null : represents no value or null value"
},
{
"code": null,
"e": 26974,
"s": 26916,
"text": "boolean : represents a boolean value either true or false"
},
{
"code": null,
"e": 27004,
"s": 26974,
"text": "Syntax to define variables: "
},
{
"code": null,
"e": 27030,
"s": 27004,
"text": "var variable_name : type;"
},
{
"code": null,
"e": 27042,
"s": 27030,
"text": "Example : "
},
{
"code": null,
"e": 27053,
"s": 27042,
"text": "javascript"
},
{
"code": "// declares a string type variable called name.var name: string; // declares a number type variable called amount.var amount: number; // declares a boolean type variable called check;var checked: boolean; // declares a string type variable called first_name and// initializes with some value.var first_name: string = \"geeksforgeeks\"; // declares an array of numbers called digits.var digits: number[];",
"e": 27459,
"s": 27053,
"text": null
},
{
"code": null,
"e": 27510,
"s": 27459,
"text": "Syntax to define classes, objects and functions: "
},
{
"code": null,
"e": 27744,
"s": 27510,
"text": "class Class_Name{\n // instance variables\n \n // constructor\n // Typescript allows only one constructor per class\n constructor(parameters){\n }\n\n // methods\n}\n\nvar object_name:class_name;\n\nfunction_name(): returntype{\n// function_body\n}"
},
{
"code": null,
"e": 27756,
"s": 27744,
"text": "Examples: "
},
{
"code": null,
"e": 27767,
"s": 27756,
"text": "javascript"
},
{
"code": "class Name { first_name: string; last_name: string; constructor(fname: string, lname: string) { first_name = fname; last_name = lname; } getName(): string { var fullname: string = first_name + last_name; return fullname; }} var author_name: Name;",
"e": 28069,
"s": 27767,
"text": null
},
{
"code": null,
"e": 28095,
"s": 28069,
"text": "Running a Typescript code"
},
{
"code": null,
"e": 28393,
"s": 28095,
"text": "Browsers natively does not understand typescript, but they understand javascript. So in order to run typescript codes, first it is transpiled to javascript. tsc : is a typescript compiler(transpiler) that converts typescript code into javascript.You can install tsc by running following command: "
},
{
"code": null,
"e": 28419,
"s": 28393,
"text": "npm install -g typescript"
},
{
"code": null,
"e": 28505,
"s": 28419,
"text": "Creating a basic typescript code that will print “Greetings from Geeks For Geeks” : "
},
{
"code": null,
"e": 28516,
"s": 28505,
"text": "javascript"
},
{
"code": "var greet: string = \"Greetings\";var geeks: string = \"Geeks For Geeks\";console.log(greet + \" from \" + geeks);// save the file as hello.ts",
"e": 28653,
"s": 28516,
"text": null
},
{
"code": null,
"e": 28890,
"s": 28653,
"text": "To compile typescript code we can run the following command on the command line.tsc hello.tsThis command will generate a javascript file with name hello.jsRun the javascript file using the following command on command line:node hello.js"
},
{
"code": null,
"e": 29046,
"s": 28890,
"text": "To compile typescript code we can run the following command on the command line.tsc hello.tsThis command will generate a javascript file with name hello.js"
},
{
"code": null,
"e": 29059,
"s": 29046,
"text": "tsc hello.ts"
},
{
"code": null,
"e": 29123,
"s": 29059,
"text": "This command will generate a javascript file with name hello.js"
},
{
"code": null,
"e": 29205,
"s": 29123,
"text": "Run the javascript file using the following command on command line:node hello.js"
},
{
"code": null,
"e": 29219,
"s": 29205,
"text": "node hello.js"
},
{
"code": null,
"e": 29275,
"s": 29219,
"text": "You should see an output as below on your command line:"
},
{
"code": null,
"e": 29306,
"s": 29275,
"text": "Greetings from Geeks For Geeks"
},
{
"code": null,
"e": 29346,
"s": 29306,
"text": "Applications of TypeScript Language : "
},
{
"code": null,
"e": 29462,
"s": 29346,
"text": "Angular 2+ versions are written is typescript and uses typescript, which proves it’s efficiency in industrial uses."
},
{
"code": null,
"e": 29514,
"s": 29462,
"text": "Typescript makes compile time error diagnosis easy."
},
{
"code": null,
"e": 29575,
"s": 29514,
"text": "Typescript is scalable and well supports large applications."
},
{
"code": null,
"e": 29670,
"s": 29575,
"text": "References 1. http://www.typescriptlang.org/ 2. http://www.typescriptlang.org/docs/index.html "
},
{
"code": null,
"e": 29686,
"s": 29670,
"text": "saurabh1990aror"
},
{
"code": null,
"e": 29702,
"s": 29686,
"text": "JavaScript-Misc"
},
{
"code": null,
"e": 29713,
"s": 29702,
"text": "TypeScript"
},
{
"code": null,
"e": 29724,
"s": 29713,
"text": "JavaScript"
},
{
"code": null,
"e": 29741,
"s": 29724,
"text": "Web Technologies"
},
{
"code": null,
"e": 29839,
"s": 29741,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 29879,
"s": 29839,
"text": "Remove elements from a JavaScript Array"
},
{
"code": null,
"e": 29924,
"s": 29879,
"text": "Convert a string to an integer in JavaScript"
},
{
"code": null,
"e": 29985,
"s": 29924,
"text": "Difference between var, let and const keywords in JavaScript"
},
{
"code": null,
"e": 30057,
"s": 29985,
"text": "Differences between Functional Components and Class Components in React"
},
{
"code": null,
"e": 30109,
"s": 30057,
"text": "How to append HTML code to a div using JavaScript ?"
},
{
"code": null,
"e": 30149,
"s": 30109,
"text": "Remove elements from a JavaScript Array"
},
{
"code": null,
"e": 30182,
"s": 30149,
"text": "Installation of Node.js on Linux"
},
{
"code": null,
"e": 30227,
"s": 30182,
"text": "Convert a string to an integer in JavaScript"
},
{
"code": null,
"e": 30270,
"s": 30227,
"text": "How to fetch data from an API in ReactJS ?"
}
] |
Connect Flask to a Database with Flask-SQLAlchemy - GeeksforGeeks
|
28 Dec, 2021
Flask is a micro web framework written in python. Micro-framework is normally a framework with little to no dependencies on external libraries. Though being a micro framework almost everything can be implemented using python libraries and other dependencies when and as required.
In this article, we will be building a Flask application that takes data in a form from the user and then displays it on another page on the website. We can also delete the data. We won’t focus on the front-end part rather we will be just coding the backend for the web application.
In any directory where you feel comfortable create a folder and open the command line in the directory. Create a python virtual environment using the command below.
python -m venv <name>
Once the command is done running activate the virtual environment using the command below.
<name>\scripts\activate
Now, install Flask using pip(package installer for python). Simply run the command below.
pip install Flask
Once the installation is done create a file name app.py and open it in your favorite editor. To check whether Flask has been properly installed you can run the following code.
Python
from flask import Flaskapp = Flask(__name__) '''If everything works fine you will get amessage that Flask is working on the firstpage of the application''' @app.route('/')def check(): return 'Flask is working' if __name__ == '__main__': app.run()
Output:
Now, let’s move on to creating a database for our application. For the purpose of this article, we will be using SQLAlchemy a database toolkit, and an ORM(Object Relational Mapper). We will be using pip again to install SQLAlchemy. The command is as follows,
pip install flask-sqlalchemy
In your app.py file import SQLAlchemy as shown in the below code. We also need to add a configuration setting to our application so that we can use SQLite database in our application. We also need to create an SQLAlchemy database instance which is as simple as creating an object.
Python
from flask import Flaskfrom flask_sqlalchemy import SQLAlchemy app = Flask(__name__)app.debug = True # adding configuration for using a sqlite databaseapp.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///site.db' # Creating an SQLAlchemy instancedb = SQLAlchemy(app) if __name__ == '__main__': app.run()
In sqlalchemy we use classes to create our database structure. In our application, we will create a Profile table that will be responsible for holding the user’s id, first name, last name, and age.
Python
from flask import Flask, request, redirectfrom flask.templating import render_templatefrom flask_sqlalchemy import SQLAlchemy app = Flask(__name__)app.debug = True # adding configuration for using a sqlite databaseapp.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///site.db' # Creating an SQLAlchemy instancedb = SQLAlchemy(app) # Modelsclass Profile(db.Model): # Id : Field which stores unique id for every row in # database table. # first_name: Used to store the first name if the user # last_name: Used to store last name of the user # Age: Used to store the age of the user id = db.Column(db.Integer, primary_key=True) first_name = db.Column(db.String(20), unique=False, nullable=False) last_name = db.Column(db.String(20), unique=False, nullable=False) age = db.Column(db.Integer, nullable=False) # repr method represents how one object of this datatable # will look like def __repr__(self): return f"Name : {self.first_name}, Age: {self.age}" if __name__ == '__main__': app.run()
The table below explains some of the keywords used in the model class.
In the command line which is navigated to the project directory and virtual environment running, we need to run the following commands.
python
The above command will initiate a python bash in your command line where you can use further lines of code to create your data table according to your model class in your database.
from app import db
db.create_all()
After the commands, the response would look like something in the picture and in your project directory you will notice a new file named ‘site.db’.
Install Flask-Migrate using pip
pip install Flask-Migrate
Now, in your app.py add two lines, the code being as follows,
Python
# Import for Migrationsfrom flask_migrate import Migrate, migrate # Settings for migrationsmigrate = Migrate(app, db)
Now to create migrations we run the following commands one after the other.
flask db init
flask db init
flask db migrate -m "Initial migration"
flask db migrate -m “Initial migration”
flask db upgrade
flask db upgrade
Now we have successfully created the data table in our database.
Before moving forward and building our form let’s create an index page for our website. The HTML file is always stored inside a folder in the parent directory of the application named ‘templates’. Inside the templates folder create a file named index.html and paste the below code for now. We will go back to adding more code into our index file as we move on.
HTML
<html> <head> <title>Index Page</title> </head> <body> <h3>Profiles</h3> </body></html>
In the app.py add a small function that will render an HTML page at a specific route specified in app.route.
Python
from flask import Flask, request, redirectfrom flask.templating import render_templatefrom flask_sqlalchemy import SQLAlchemy app = Flask(__name__)app.debug = True # adding configuration for using a sqlite databaseapp.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///site.db' # Creating an SQLAlchemy instancedb = SQLAlchemy(app) # Modelsclass Profile(db.Model): id = db.Column(db.Integer, primary_key=True) first_name = db.Column(db.String(20), unique=False, nullable=False) last_name = db.Column(db.String(20), unique=False, nullable=False) age = db.Column(db.Integer, nullable=False) def __repr__(self): return f"Name : {self.first_name}, Age: {self.age}" # function to render index [email protected]('/')def index(): return render_template('index.html') if __name__ == '__main__': app.run()
To test whether everything is working fine you can run your application using the command
python app.py
The command will set up a local server at http://localhost:5000.
Output:
We will be creating an HTML page in which our form will be rendered. Create an HTML file named add_profile in your templates folder. The HTML code is as follows. The important points in the code will be highlighted as you read on.
HTML
<!DOCTYPE html><html> <head> <title>Add Profile</title> </head> <body> <h3>Profile form</h3> <form action="/add" method="POST"> <label>First Name</label> <input type="text" name="first_name" placeholder="first name..."> <label>Last Name</label> <input type="text" name= "last_name" placeholder="last name..."> <label>Age</label> <input type="number" name="age" placeholder="age.."> <button type="submit">Add</button> </form> </body></html>
Adding a function in our application to render the form page
In our app.py file, we will add the following function. At route or site path ‘http://localhost:5000/add_data’ the page will be rendered.
Python
@app.route('/add_data')def add_data(): return render_template('add_profile.html')
To check whether the code is working fine or not, you can run the following command to start the local server.
python app.py
Now, visit http://localhost:5000/add_data and you will be able to see the form.
Output:
To add data to the database we will be using the “POST” method. POST is used to send data to a server to create/update a resource. In flask where we specify our route that is app.route we can also specify the HTTP methods there. Then inside the function, we create variables to store data and use request objects to procure data from the form.
Note: The name used in the input tags in the HTML file has to be the same one that is being been used in this function,
For example,
<input type="number" name="age" placeholder="age..">
“age” should also be used in the python function as,
age = request.form.get("age")
Then we move on to create an object of the Profile class and store it in our database using database sessions.
Python
# function to add [email protected]('/add', methods=["POST"])def profile(): # In this function we will input data from the # form page and store it in our database. # Remember that inside the get the name should # exactly be the same as that in the html # input fields first_name = request.form.get("first_name") last_name = request.form.get("last_name") age = request.form.get("age") # create an object of the Profile class of models # and store data as a row in our datatable if first_name != '' and last_name != '' and age is not None: p = Profile(first_name=first_name, last_name=last_name, age=age) db.session.add(p) db.session.commit() return redirect('/') else: return redirect('/')
Once the function is executed it redirects us back to the index page of the application.
On our index page now, we will be displaying all the data that has been stored in our data table. We will be using ‘Profile.query.all()‘ to query all the objects of the Profile class and then use Jinja templating language to display it dynamically on our index HTML file.
Update your index file as follows. The delete function will be written later on in this article. For now, we will query all the data from the data table and display it on our home page.
HTML
<!DOCTYPE html><html> <head> <title>Index Page</title> </head> <body> <h3>Profiles</h3> <a href="/add_data">ADD</a> <br> <table> <thead> <th>Id</th> <th>First Name</th> <th>Last Name</th> <th>Age</th> <th>#</th> </thead> {% for data in profiles %} <tbody> <td>{{data.id}}</td> <td>{{data.first_name}}</td> <td>{{data.last_name}}</td> <td>{{data.age}}</td> <td><a href="/delete/{{data.id}}" type="button">Delete</a></td> </tbody> {% endfor%} </table> </body></html>
We loop through every object in profiles that we pass down to our template in our index function and print all its data in a tabular form. The index function in our app.py is updated as follows.
Python
@app.route('/')def index(): # Query all data and then pass it to the template profiles = Profile.query.all() return render_template('index.html', profiles=profiles)
To delete data we have already used an anchor tag in our table and now we will just be associating a function with it.
Python
@app.route('/delete/<int:id>')def erase(id): # Deletes the data on the basis of unique id and # redirects to home page data = Profile.query.get(id) db.session.delete(data) db.session.commit() return redirect('/')
The function queries data on the basis of id and then deletes it from our database.
Complete Code
The entire code for app.py, index.html, and add-profile.html has been given.
app.py
Python
from flask import Flask, request, redirectfrom flask.templating import render_templatefrom flask_sqlalchemy import SQLAlchemyfrom flask_migrate import Migrate, migrate app = Flask(__name__)app.debug = True # adding configuration for using a sqlite databaseapp.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///site.db' # Creating an SQLAlchemy instancedb = SQLAlchemy(app) # Settings for migrationsmigrate = Migrate(app, db) # Modelsclass Profile(db.Model): # Id : Field which stores unique id for every row in # database table. # first_name: Used to store the first name if the user # last_name: Used to store last name of the user # Age: Used to store the age of the user id = db.Column(db.Integer, primary_key=True) first_name = db.Column(db.String(20), unique=False, nullable=False) last_name = db.Column(db.String(20), unique=False, nullable=False) age = db.Column(db.Integer, nullable=False) # repr method represents how one object of this datatable # will look like def __repr__(self): return f"Name : {self.first_name}, Age: {self.age}" # function to render index [email protected]('/')def index(): profiles = Profile.query.all() return render_template('index.html', profiles=profiles) @app.route('/add_data')def add_data(): return render_template('add_profile.html') # function to add [email protected]('/add', methods=["POST"])def profile(): # In this function we will input data from the # form page and store it in our database. Remember # that inside the get the name should exactly be the same # as that in the html input fields first_name = request.form.get("first_name") last_name = request.form.get("last_name") age = request.form.get("age") # create an object of the Profile class of models and # store data as a row in our datatable if first_name != '' and last_name != '' and age is not None: p = Profile(first_name=first_name, last_name=last_name, age=age) db.session.add(p) db.session.commit() return redirect('/') else: return redirect('/') @app.route('/delete/<int:id>')def erase(id): # deletes the data on the basis of unique id and # directs to home page data = Profile.query.get(id) db.session.delete(data) db.session.commit() return redirect('/') if __name__ == '__main__': app.run()
index.html
HTML
<!DOCTYPE html><html> <head> <title>Index Page</title> </head> <body> <h3>Profiles</h3> <a href="/add_data">ADD</a> <br> <table> <thead> <th>Id</th> <th>First Name</th> <th>Last Name</th> <th>Age</th> <th>#</th> </thead> {% for data in profiles %} <tbody> <td>{{data.id}}</td> <td>{{data.first_name}}</td> <td>{{data.last_name}}</td> <td>{{data.age}}</td> <td><a href="/delete/{{data.id}}" type="button">Delete</a></td> </tbody> {% endfor%} </table> </body></html>
add_profile.html
HTML
<!DOCTYPE html><html> <head> <title>Add Profile</title> </head> <body> <h3>Profile form</h3> <form action="/add" method="POST"> <label>First Name</label> <input type="text" name="first_name" placeholder="first name..."> <label>Last Name</label> <input type="text" name= "last_name" placeholder="last name..."> <label>Age</label> <input type="number" name="age" placeholder="age.."> <button type="submit">Add</button> </form> </body></html>
Output:
varshagumber28
anikakapoor
sagar0719kumar
sumitgumber28
rkbhola5
Picked
Python Flask
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python Dictionary
Read a file line by line in Python
How to Install PIP on Windows ?
Different ways to create Pandas Dataframe
Python String | replace()
*args and **kwargs in Python
Reading and Writing to text files in Python
Create a Pandas DataFrame from Lists
Convert integer to string in Python
Check if element exists in list in Python
|
[
{
"code": null,
"e": 25689,
"s": 25661,
"text": "\n28 Dec, 2021"
},
{
"code": null,
"e": 25969,
"s": 25689,
"text": "Flask is a micro web framework written in python. Micro-framework is normally a framework with little to no dependencies on external libraries. Though being a micro framework almost everything can be implemented using python libraries and other dependencies when and as required."
},
{
"code": null,
"e": 26252,
"s": 25969,
"text": "In this article, we will be building a Flask application that takes data in a form from the user and then displays it on another page on the website. We can also delete the data. We won’t focus on the front-end part rather we will be just coding the backend for the web application."
},
{
"code": null,
"e": 26417,
"s": 26252,
"text": "In any directory where you feel comfortable create a folder and open the command line in the directory. Create a python virtual environment using the command below."
},
{
"code": null,
"e": 26439,
"s": 26417,
"text": "python -m venv <name>"
},
{
"code": null,
"e": 26530,
"s": 26439,
"text": "Once the command is done running activate the virtual environment using the command below."
},
{
"code": null,
"e": 26554,
"s": 26530,
"text": "<name>\\scripts\\activate"
},
{
"code": null,
"e": 26644,
"s": 26554,
"text": "Now, install Flask using pip(package installer for python). Simply run the command below."
},
{
"code": null,
"e": 26662,
"s": 26644,
"text": "pip install Flask"
},
{
"code": null,
"e": 26838,
"s": 26662,
"text": "Once the installation is done create a file name app.py and open it in your favorite editor. To check whether Flask has been properly installed you can run the following code."
},
{
"code": null,
"e": 26845,
"s": 26838,
"text": "Python"
},
{
"code": "from flask import Flaskapp = Flask(__name__) '''If everything works fine you will get amessage that Flask is working on the firstpage of the application''' @app.route('/')def check(): return 'Flask is working' if __name__ == '__main__': app.run()",
"e": 27100,
"s": 26845,
"text": null
},
{
"code": null,
"e": 27108,
"s": 27100,
"text": "Output:"
},
{
"code": null,
"e": 27367,
"s": 27108,
"text": "Now, let’s move on to creating a database for our application. For the purpose of this article, we will be using SQLAlchemy a database toolkit, and an ORM(Object Relational Mapper). We will be using pip again to install SQLAlchemy. The command is as follows,"
},
{
"code": null,
"e": 27396,
"s": 27367,
"text": "pip install flask-sqlalchemy"
},
{
"code": null,
"e": 27677,
"s": 27396,
"text": "In your app.py file import SQLAlchemy as shown in the below code. We also need to add a configuration setting to our application so that we can use SQLite database in our application. We also need to create an SQLAlchemy database instance which is as simple as creating an object."
},
{
"code": null,
"e": 27684,
"s": 27677,
"text": "Python"
},
{
"code": "from flask import Flaskfrom flask_sqlalchemy import SQLAlchemy app = Flask(__name__)app.debug = True # adding configuration for using a sqlite databaseapp.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///site.db' # Creating an SQLAlchemy instancedb = SQLAlchemy(app) if __name__ == '__main__': app.run()",
"e": 27989,
"s": 27684,
"text": null
},
{
"code": null,
"e": 28187,
"s": 27989,
"text": "In sqlalchemy we use classes to create our database structure. In our application, we will create a Profile table that will be responsible for holding the user’s id, first name, last name, and age."
},
{
"code": null,
"e": 28194,
"s": 28187,
"text": "Python"
},
{
"code": "from flask import Flask, request, redirectfrom flask.templating import render_templatefrom flask_sqlalchemy import SQLAlchemy app = Flask(__name__)app.debug = True # adding configuration for using a sqlite databaseapp.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///site.db' # Creating an SQLAlchemy instancedb = SQLAlchemy(app) # Modelsclass Profile(db.Model): # Id : Field which stores unique id for every row in # database table. # first_name: Used to store the first name if the user # last_name: Used to store last name of the user # Age: Used to store the age of the user id = db.Column(db.Integer, primary_key=True) first_name = db.Column(db.String(20), unique=False, nullable=False) last_name = db.Column(db.String(20), unique=False, nullable=False) age = db.Column(db.Integer, nullable=False) # repr method represents how one object of this datatable # will look like def __repr__(self): return f\"Name : {self.first_name}, Age: {self.age}\" if __name__ == '__main__': app.run()",
"e": 29226,
"s": 28194,
"text": null
},
{
"code": null,
"e": 29298,
"s": 29226,
"text": "The table below explains some of the keywords used in the model class. "
},
{
"code": null,
"e": 29435,
"s": 29298,
"text": "In the command line which is navigated to the project directory and virtual environment running, we need to run the following commands. "
},
{
"code": null,
"e": 29442,
"s": 29435,
"text": "python"
},
{
"code": null,
"e": 29624,
"s": 29442,
"text": "The above command will initiate a python bash in your command line where you can use further lines of code to create your data table according to your model class in your database. "
},
{
"code": null,
"e": 29659,
"s": 29624,
"text": "from app import db\ndb.create_all()"
},
{
"code": null,
"e": 29808,
"s": 29659,
"text": "After the commands, the response would look like something in the picture and in your project directory you will notice a new file named ‘site.db’. "
},
{
"code": null,
"e": 29841,
"s": 29808,
"text": "Install Flask-Migrate using pip "
},
{
"code": null,
"e": 29867,
"s": 29841,
"text": "pip install Flask-Migrate"
},
{
"code": null,
"e": 29930,
"s": 29867,
"text": "Now, in your app.py add two lines, the code being as follows, "
},
{
"code": null,
"e": 29937,
"s": 29930,
"text": "Python"
},
{
"code": "# Import for Migrationsfrom flask_migrate import Migrate, migrate # Settings for migrationsmigrate = Migrate(app, db)",
"e": 30055,
"s": 29937,
"text": null
},
{
"code": null,
"e": 30131,
"s": 30055,
"text": "Now to create migrations we run the following commands one after the other."
},
{
"code": null,
"e": 30145,
"s": 30131,
"text": "flask db init"
},
{
"code": null,
"e": 30159,
"s": 30145,
"text": "flask db init"
},
{
"code": null,
"e": 30199,
"s": 30159,
"text": "flask db migrate -m \"Initial migration\""
},
{
"code": null,
"e": 30239,
"s": 30199,
"text": "flask db migrate -m “Initial migration”"
},
{
"code": null,
"e": 30256,
"s": 30239,
"text": "flask db upgrade"
},
{
"code": null,
"e": 30273,
"s": 30256,
"text": "flask db upgrade"
},
{
"code": null,
"e": 30338,
"s": 30273,
"text": "Now we have successfully created the data table in our database."
},
{
"code": null,
"e": 30699,
"s": 30338,
"text": "Before moving forward and building our form let’s create an index page for our website. The HTML file is always stored inside a folder in the parent directory of the application named ‘templates’. Inside the templates folder create a file named index.html and paste the below code for now. We will go back to adding more code into our index file as we move on."
},
{
"code": null,
"e": 30704,
"s": 30699,
"text": "HTML"
},
{
"code": "<html> <head> <title>Index Page</title> </head> <body> <h3>Profiles</h3> </body></html>",
"e": 30810,
"s": 30704,
"text": null
},
{
"code": null,
"e": 30921,
"s": 30810,
"text": " In the app.py add a small function that will render an HTML page at a specific route specified in app.route. "
},
{
"code": null,
"e": 30928,
"s": 30921,
"text": "Python"
},
{
"code": "from flask import Flask, request, redirectfrom flask.templating import render_templatefrom flask_sqlalchemy import SQLAlchemy app = Flask(__name__)app.debug = True # adding configuration for using a sqlite databaseapp.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///site.db' # Creating an SQLAlchemy instancedb = SQLAlchemy(app) # Modelsclass Profile(db.Model): id = db.Column(db.Integer, primary_key=True) first_name = db.Column(db.String(20), unique=False, nullable=False) last_name = db.Column(db.String(20), unique=False, nullable=False) age = db.Column(db.Integer, nullable=False) def __repr__(self): return f\"Name : {self.first_name}, Age: {self.age}\" # function to render index [email protected]('/')def index(): return render_template('index.html') if __name__ == '__main__': app.run()",
"e": 31748,
"s": 30928,
"text": null
},
{
"code": null,
"e": 31839,
"s": 31748,
"text": "To test whether everything is working fine you can run your application using the command "
},
{
"code": null,
"e": 31853,
"s": 31839,
"text": "python app.py"
},
{
"code": null,
"e": 31918,
"s": 31853,
"text": "The command will set up a local server at http://localhost:5000."
},
{
"code": null,
"e": 31926,
"s": 31918,
"text": "Output:"
},
{
"code": null,
"e": 32157,
"s": 31926,
"text": "We will be creating an HTML page in which our form will be rendered. Create an HTML file named add_profile in your templates folder. The HTML code is as follows. The important points in the code will be highlighted as you read on."
},
{
"code": null,
"e": 32162,
"s": 32157,
"text": "HTML"
},
{
"code": "<!DOCTYPE html><html> <head> <title>Add Profile</title> </head> <body> <h3>Profile form</h3> <form action=\"/add\" method=\"POST\"> <label>First Name</label> <input type=\"text\" name=\"first_name\" placeholder=\"first name...\"> <label>Last Name</label> <input type=\"text\" name= \"last_name\" placeholder=\"last name...\"> <label>Age</label> <input type=\"number\" name=\"age\" placeholder=\"age..\"> <button type=\"submit\">Add</button> </form> </body></html>",
"e": 32686,
"s": 32162,
"text": null
},
{
"code": null,
"e": 32747,
"s": 32686,
"text": "Adding a function in our application to render the form page"
},
{
"code": null,
"e": 32886,
"s": 32747,
"text": "In our app.py file, we will add the following function. At route or site path ‘http://localhost:5000/add_data’ the page will be rendered. "
},
{
"code": null,
"e": 32893,
"s": 32886,
"text": "Python"
},
{
"code": "@app.route('/add_data')def add_data(): return render_template('add_profile.html')",
"e": 32978,
"s": 32893,
"text": null
},
{
"code": null,
"e": 33091,
"s": 32978,
"text": " To check whether the code is working fine or not, you can run the following command to start the local server. "
},
{
"code": null,
"e": 33105,
"s": 33091,
"text": "python app.py"
},
{
"code": null,
"e": 33185,
"s": 33105,
"text": "Now, visit http://localhost:5000/add_data and you will be able to see the form."
},
{
"code": null,
"e": 33194,
"s": 33185,
"text": "Output: "
},
{
"code": null,
"e": 33539,
"s": 33194,
"text": "To add data to the database we will be using the “POST” method. POST is used to send data to a server to create/update a resource. In flask where we specify our route that is app.route we can also specify the HTTP methods there. Then inside the function, we create variables to store data and use request objects to procure data from the form. "
},
{
"code": null,
"e": 33659,
"s": 33539,
"text": "Note: The name used in the input tags in the HTML file has to be the same one that is being been used in this function,"
},
{
"code": null,
"e": 33674,
"s": 33659,
"text": "For example, "
},
{
"code": null,
"e": 33727,
"s": 33674,
"text": "<input type=\"number\" name=\"age\" placeholder=\"age..\">"
},
{
"code": null,
"e": 33781,
"s": 33727,
"text": "“age” should also be used in the python function as, "
},
{
"code": null,
"e": 33811,
"s": 33781,
"text": "age = request.form.get(\"age\")"
},
{
"code": null,
"e": 33923,
"s": 33811,
"text": "Then we move on to create an object of the Profile class and store it in our database using database sessions. "
},
{
"code": null,
"e": 33930,
"s": 33923,
"text": "Python"
},
{
"code": "# function to add [email protected]('/add', methods=[\"POST\"])def profile(): # In this function we will input data from the # form page and store it in our database. # Remember that inside the get the name should # exactly be the same as that in the html # input fields first_name = request.form.get(\"first_name\") last_name = request.form.get(\"last_name\") age = request.form.get(\"age\") # create an object of the Profile class of models # and store data as a row in our datatable if first_name != '' and last_name != '' and age is not None: p = Profile(first_name=first_name, last_name=last_name, age=age) db.session.add(p) db.session.commit() return redirect('/') else: return redirect('/')",
"e": 34698,
"s": 33930,
"text": null
},
{
"code": null,
"e": 34787,
"s": 34698,
"text": "Once the function is executed it redirects us back to the index page of the application."
},
{
"code": null,
"e": 35059,
"s": 34787,
"text": "On our index page now, we will be displaying all the data that has been stored in our data table. We will be using ‘Profile.query.all()‘ to query all the objects of the Profile class and then use Jinja templating language to display it dynamically on our index HTML file."
},
{
"code": null,
"e": 35245,
"s": 35059,
"text": "Update your index file as follows. The delete function will be written later on in this article. For now, we will query all the data from the data table and display it on our home page."
},
{
"code": null,
"e": 35250,
"s": 35245,
"text": "HTML"
},
{
"code": "<!DOCTYPE html><html> <head> <title>Index Page</title> </head> <body> <h3>Profiles</h3> <a href=\"/add_data\">ADD</a> <br> <table> <thead> <th>Id</th> <th>First Name</th> <th>Last Name</th> <th>Age</th> <th>#</th> </thead> {% for data in profiles %} <tbody> <td>{{data.id}}</td> <td>{{data.first_name}}</td> <td>{{data.last_name}}</td> <td>{{data.age}}</td> <td><a href=\"/delete/{{data.id}}\" type=\"button\">Delete</a></td> </tbody> {% endfor%} </table> </body></html>",
"e": 35911,
"s": 35250,
"text": null
},
{
"code": null,
"e": 36108,
"s": 35911,
"text": " We loop through every object in profiles that we pass down to our template in our index function and print all its data in a tabular form. The index function in our app.py is updated as follows. "
},
{
"code": null,
"e": 36115,
"s": 36108,
"text": "Python"
},
{
"code": "@app.route('/')def index(): # Query all data and then pass it to the template profiles = Profile.query.all() return render_template('index.html', profiles=profiles)",
"e": 36291,
"s": 36115,
"text": null
},
{
"code": null,
"e": 36410,
"s": 36291,
"text": "To delete data we have already used an anchor tag in our table and now we will just be associating a function with it."
},
{
"code": null,
"e": 36417,
"s": 36410,
"text": "Python"
},
{
"code": "@app.route('/delete/<int:id>')def erase(id): # Deletes the data on the basis of unique id and # redirects to home page data = Profile.query.get(id) db.session.delete(data) db.session.commit() return redirect('/')",
"e": 36648,
"s": 36417,
"text": null
},
{
"code": null,
"e": 36732,
"s": 36648,
"text": "The function queries data on the basis of id and then deletes it from our database."
},
{
"code": null,
"e": 36746,
"s": 36732,
"text": "Complete Code"
},
{
"code": null,
"e": 36824,
"s": 36746,
"text": "The entire code for app.py, index.html, and add-profile.html has been given. "
},
{
"code": null,
"e": 36831,
"s": 36824,
"text": "app.py"
},
{
"code": null,
"e": 36838,
"s": 36831,
"text": "Python"
},
{
"code": "from flask import Flask, request, redirectfrom flask.templating import render_templatefrom flask_sqlalchemy import SQLAlchemyfrom flask_migrate import Migrate, migrate app = Flask(__name__)app.debug = True # adding configuration for using a sqlite databaseapp.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///site.db' # Creating an SQLAlchemy instancedb = SQLAlchemy(app) # Settings for migrationsmigrate = Migrate(app, db) # Modelsclass Profile(db.Model): # Id : Field which stores unique id for every row in # database table. # first_name: Used to store the first name if the user # last_name: Used to store last name of the user # Age: Used to store the age of the user id = db.Column(db.Integer, primary_key=True) first_name = db.Column(db.String(20), unique=False, nullable=False) last_name = db.Column(db.String(20), unique=False, nullable=False) age = db.Column(db.Integer, nullable=False) # repr method represents how one object of this datatable # will look like def __repr__(self): return f\"Name : {self.first_name}, Age: {self.age}\" # function to render index [email protected]('/')def index(): profiles = Profile.query.all() return render_template('index.html', profiles=profiles) @app.route('/add_data')def add_data(): return render_template('add_profile.html') # function to add [email protected]('/add', methods=[\"POST\"])def profile(): # In this function we will input data from the # form page and store it in our database. Remember # that inside the get the name should exactly be the same # as that in the html input fields first_name = request.form.get(\"first_name\") last_name = request.form.get(\"last_name\") age = request.form.get(\"age\") # create an object of the Profile class of models and # store data as a row in our datatable if first_name != '' and last_name != '' and age is not None: p = Profile(first_name=first_name, last_name=last_name, age=age) db.session.add(p) db.session.commit() return redirect('/') else: return redirect('/') @app.route('/delete/<int:id>')def erase(id): # deletes the data on the basis of unique id and # directs to home page data = Profile.query.get(id) db.session.delete(data) db.session.commit() return redirect('/') if __name__ == '__main__': app.run()",
"e": 39193,
"s": 36838,
"text": null
},
{
"code": null,
"e": 39205,
"s": 39193,
"text": "index.html "
},
{
"code": null,
"e": 39210,
"s": 39205,
"text": "HTML"
},
{
"code": "<!DOCTYPE html><html> <head> <title>Index Page</title> </head> <body> <h3>Profiles</h3> <a href=\"/add_data\">ADD</a> <br> <table> <thead> <th>Id</th> <th>First Name</th> <th>Last Name</th> <th>Age</th> <th>#</th> </thead> {% for data in profiles %} <tbody> <td>{{data.id}}</td> <td>{{data.first_name}}</td> <td>{{data.last_name}}</td> <td>{{data.age}}</td> <td><a href=\"/delete/{{data.id}}\" type=\"button\">Delete</a></td> </tbody> {% endfor%} </table> </body></html>",
"e": 39871,
"s": 39210,
"text": null
},
{
"code": null,
"e": 39889,
"s": 39871,
"text": "add_profile.html "
},
{
"code": null,
"e": 39894,
"s": 39889,
"text": "HTML"
},
{
"code": "<!DOCTYPE html><html> <head> <title>Add Profile</title> </head> <body> <h3>Profile form</h3> <form action=\"/add\" method=\"POST\"> <label>First Name</label> <input type=\"text\" name=\"first_name\" placeholder=\"first name...\"> <label>Last Name</label> <input type=\"text\" name= \"last_name\" placeholder=\"last name...\"> <label>Age</label> <input type=\"number\" name=\"age\" placeholder=\"age..\"> <button type=\"submit\">Add</button> </form> </body></html>",
"e": 40418,
"s": 39894,
"text": null
},
{
"code": null,
"e": 40426,
"s": 40418,
"text": "Output:"
},
{
"code": null,
"e": 40443,
"s": 40428,
"text": "varshagumber28"
},
{
"code": null,
"e": 40455,
"s": 40443,
"text": "anikakapoor"
},
{
"code": null,
"e": 40470,
"s": 40455,
"text": "sagar0719kumar"
},
{
"code": null,
"e": 40484,
"s": 40470,
"text": "sumitgumber28"
},
{
"code": null,
"e": 40493,
"s": 40484,
"text": "rkbhola5"
},
{
"code": null,
"e": 40500,
"s": 40493,
"text": "Picked"
},
{
"code": null,
"e": 40513,
"s": 40500,
"text": "Python Flask"
},
{
"code": null,
"e": 40520,
"s": 40513,
"text": "Python"
},
{
"code": null,
"e": 40618,
"s": 40520,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 40636,
"s": 40618,
"text": "Python Dictionary"
},
{
"code": null,
"e": 40671,
"s": 40636,
"text": "Read a file line by line in Python"
},
{
"code": null,
"e": 40703,
"s": 40671,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 40745,
"s": 40703,
"text": "Different ways to create Pandas Dataframe"
},
{
"code": null,
"e": 40771,
"s": 40745,
"text": "Python String | replace()"
},
{
"code": null,
"e": 40800,
"s": 40771,
"text": "*args and **kwargs in Python"
},
{
"code": null,
"e": 40844,
"s": 40800,
"text": "Reading and Writing to text files in Python"
},
{
"code": null,
"e": 40881,
"s": 40844,
"text": "Create a Pandas DataFrame from Lists"
},
{
"code": null,
"e": 40917,
"s": 40881,
"text": "Convert integer to string in Python"
}
] |
Reverse words in a given string | Set 2 - GeeksforGeeks
|
26 Sep, 2021
Given string str, the task is to reverse the string by considering each word of the string, str as a single unit.
Examples:
Input: str = “geeks quiz practice code”Output: code practice quiz geeks Explanation: The words in the given string are [“geeks”, “quiz”, “practice”, “code”]. Therefore, after reversing the order of the words, the required output is“code practice quiz geeks”.
Input: str = “getting good at coding needs a lot of practice”Output: practice of lot a needs coding at good getting
In-place Reversal Approach: Refer to the article Reverse words in a given string for the in-place reversal of words followed by a reversal of the entire string.
Time Complexity: O(N) Auxiliary Space: O(1)
Stack-based Approach: In this article, the approach to solving the problem using Stack is going to be discussed. The idea here is to push all the words of str into the Stack and then print all the elements of the Stack. Follow the steps below to solve the problem:
Create a Stack to store each word of the string str.Iterate over string str, and separate each word of str by a space delimiter.Push all the words of str into the stack.Print all the elements of the stack one by one.
Create a Stack to store each word of the string str.
Iterate over string str, and separate each word of str by a space delimiter.
Push all the words of str into the stack.
Print all the elements of the stack one by one.
Below is the implementation of the above approach:
C++
Java
Python3
C#
Javascript
// C++ Program to implement// the above approach #include <bits/stdc++.h>using namespace std; // Function to reverse the words// of a given stringvoid printRev(string str){ // Stack to store each // word of the string stack<string> st; // Store the whole string // in string stream stringstream ss(str); string temp; while (getline(ss, temp, ' ')) { // Push each word of the // string into the stack st.push(temp); } // Print the string in reverse // order of the words while (!st.empty()) { cout << st.top() << " "; st.pop(); }} // Driver Codeint main(){ string str; str = "geeks quiz practice code"; printRev(str); return 0;}
// Java Program to implement// the above approachimport java.util.*;class GFG{ // Function to reverse the words // of a given String static void printRev(String str) { // Stack to store each // word of the String Stack<String> st = new Stack<String>(); // Store the whole String // in String stream String[] ss = str.split(" "); for (String temp : ss) { // Push each word of the // String into the stack st.add(temp); } // Print the String in reverse // order of the words while (!st.isEmpty()) { System.out.print(st.peek() + " "); st.pop(); } } // Driver Code public static void main(String[] args) { String str; str = "geeks quiz practice code"; printRev(str); }} // This code is contributed by Rajput-Ji
# Python3 program to implement# the above approach # Function to reverse the words# of a given stringdef printRev(strr): # Stack to store each # word of the string strr = strr.split(" ") st = [] # Store the whole string # in stream for i in strr: # Push each word of the # into the stack st.append(i) # Print the in reverse # order of the words while len(st) > 0: print(st[-1], end = " ") del st[-1] # Driver Codeif __name__ == '__main__': strr = "geeks quiz practice code" printRev(strr) # This code is contributed by mohit kumar 29
// C# program to implement// the above approachusing System;using System.Collections; class GFG{ // Function to reverse the words// of a given Stringstatic void printRev(string str){ // Stack to store each // word of the String Stack st = new Stack(); String[] separator = {" "}; // Store the whole String // in String stream string[] ss = str.Split(separator, int.MaxValue, StringSplitOptions.RemoveEmptyEntries); foreach(string temp in ss) { // Push each word of the // String into the stack st.Push(temp); } // Print the String in reverse // order of the words while (st.Count > 0) { Console.Write(st.Peek() + " "); st.Pop(); }} // Driver Codepublic static void Main(string[] args){ string str; str = "geeks quiz practice code"; printRev(str);}} // This code is contributed by rutvik_56
<script>// Javascript Program to implement// the above approach // Function to reverse the words// of a given Stringfunction printRev(str){ // Stack to store each // word of the String let st = []; // Store the whole String // in String stream let ss = str.split(" "); for (let temp=0;temp< ss.length;temp++) { // Push each word of the // String into the stack st.push(ss[temp]); } // Print the String in reverse // order of the words while (st.length!=0) { document.write(st.pop() + " "); }} // Driver Codelet str;str = "geeks quiz practice code";printRev(str); // This code is contributed by unknown2108</script>
code practice quiz geeks
Time Complexity: O(N), where N denotes the length of the string.Auxiliary Space: O(N)
As all the words in a sentence are separated by spaces.
We have to split the sentence by spaces using split().
We split all the words by spaces and store them in a list.
Reverse this list and print it.
C++
Java
Python3
C#
Javascript
// C++ program to implement// the above approach#include <bits/stdc++.h>using namespace std; // Function to reverse the words// of a given stringvoid printRev(string lis[]){ // reverse the list reverse(lis, lis + 4); for(int i = 0; i < 4; i++) { cout << lis[i] << " "; }} int main(){ string strr[] = {"geeks", "quiz", "practice", "code"}; printRev(strr); return 0;} // This code is contributed by divyeshrabadiya07.
// Java program to implement// the above approachimport java.util.*; class GFG{ // Function to reverse the words// of a given stringstatic void printRev(String string){ // Split by space and converting // string to list String[] lis = string.split(" ", 0); // Reverse the list Collections.reverse(Arrays.asList(lis)); // Printing the list for(String li : lis) { System.out.print(li + " "); }} // Driver codepublic static void main(String[] args){ String strr = "geeks quiz practice code"; printRev(strr);}} // This code is contributed by decode2207
# Python3 program to implement# the above approach # Function to reverse the words# of a given string def printRev(string): # split by space and converting # string to list lis = list(string.split()) # reverse the list lis.reverse() # printing the list print(*lis) # Driver Codeif __name__ == '__main__': strr = "geeks quiz practice code" printRev(strr) # This code is contributed by vikkycirus
// C# program to implement// the above approachusing System;class GFG { // Function to reverse the words // of a given string static void printRev(string String) { // split by space and converting // string to list string[] lis = String.Split(' '); // reverse the list Array.Reverse(lis); // printing the list foreach(string li in lis) { Console.Write(li + " "); } } static void Main() { string strr = "geeks quiz practice code"; printRev(strr); }} // This code is contributed by rameshtravel07.
<script> // javascript program to implement// the above approach // Function to reverse the words// of a given string function printRev(string){ // split by space and converting // string to list var lis = string.split(' '); console.log(lis); // reverse the list lis.reverse(); console.log(lis); // printing the list document.write(lis.join(' '));} // Driver Code var strr = "geeks quiz practice code" printRev(strr) </script>
code practice quiz geeks
mohit kumar 29
Rajput-Ji
rutvik_56
vikkycirus
adnanirshad158
bunnyram19
unknown2108
ruhelaa48
saurabh1990aror
rameshtravel07
decode2207
divyeshrabadiya07
anikaseth98
Reverse
substring
Stack
Strings
Strings
Stack
Reverse
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Real-time application of Data Structures
ZigZag Tree Traversal
Reverse individual words
Evaluation of Prefix Expressions
Sort a stack using a temporary stack
Write a program to reverse an array or string
Reverse a string in Java
Write a program to print all permutations of a given string
C++ Data Types
Longest Common Subsequence | DP-4
|
[
{
"code": null,
"e": 25933,
"s": 25905,
"text": "\n26 Sep, 2021"
},
{
"code": null,
"e": 26047,
"s": 25933,
"text": "Given string str, the task is to reverse the string by considering each word of the string, str as a single unit."
},
{
"code": null,
"e": 26057,
"s": 26047,
"text": "Examples:"
},
{
"code": null,
"e": 26317,
"s": 26057,
"text": "Input: str = “geeks quiz practice code”Output: code practice quiz geeks Explanation: The words in the given string are [“geeks”, “quiz”, “practice”, “code”]. Therefore, after reversing the order of the words, the required output is“code practice quiz geeks”."
},
{
"code": null,
"e": 26433,
"s": 26317,
"text": "Input: str = “getting good at coding needs a lot of practice”Output: practice of lot a needs coding at good getting"
},
{
"code": null,
"e": 26595,
"s": 26433,
"text": "In-place Reversal Approach: Refer to the article Reverse words in a given string for the in-place reversal of words followed by a reversal of the entire string. "
},
{
"code": null,
"e": 26639,
"s": 26595,
"text": "Time Complexity: O(N) Auxiliary Space: O(1)"
},
{
"code": null,
"e": 26904,
"s": 26639,
"text": "Stack-based Approach: In this article, the approach to solving the problem using Stack is going to be discussed. The idea here is to push all the words of str into the Stack and then print all the elements of the Stack. Follow the steps below to solve the problem:"
},
{
"code": null,
"e": 27121,
"s": 26904,
"text": "Create a Stack to store each word of the string str.Iterate over string str, and separate each word of str by a space delimiter.Push all the words of str into the stack.Print all the elements of the stack one by one."
},
{
"code": null,
"e": 27174,
"s": 27121,
"text": "Create a Stack to store each word of the string str."
},
{
"code": null,
"e": 27251,
"s": 27174,
"text": "Iterate over string str, and separate each word of str by a space delimiter."
},
{
"code": null,
"e": 27293,
"s": 27251,
"text": "Push all the words of str into the stack."
},
{
"code": null,
"e": 27341,
"s": 27293,
"text": "Print all the elements of the stack one by one."
},
{
"code": null,
"e": 27392,
"s": 27341,
"text": "Below is the implementation of the above approach:"
},
{
"code": null,
"e": 27396,
"s": 27392,
"text": "C++"
},
{
"code": null,
"e": 27401,
"s": 27396,
"text": "Java"
},
{
"code": null,
"e": 27409,
"s": 27401,
"text": "Python3"
},
{
"code": null,
"e": 27412,
"s": 27409,
"text": "C#"
},
{
"code": null,
"e": 27423,
"s": 27412,
"text": "Javascript"
},
{
"code": "// C++ Program to implement// the above approach #include <bits/stdc++.h>using namespace std; // Function to reverse the words// of a given stringvoid printRev(string str){ // Stack to store each // word of the string stack<string> st; // Store the whole string // in string stream stringstream ss(str); string temp; while (getline(ss, temp, ' ')) { // Push each word of the // string into the stack st.push(temp); } // Print the string in reverse // order of the words while (!st.empty()) { cout << st.top() << \" \"; st.pop(); }} // Driver Codeint main(){ string str; str = \"geeks quiz practice code\"; printRev(str); return 0;}",
"e": 28142,
"s": 27423,
"text": null
},
{
"code": "// Java Program to implement// the above approachimport java.util.*;class GFG{ // Function to reverse the words // of a given String static void printRev(String str) { // Stack to store each // word of the String Stack<String> st = new Stack<String>(); // Store the whole String // in String stream String[] ss = str.split(\" \"); for (String temp : ss) { // Push each word of the // String into the stack st.add(temp); } // Print the String in reverse // order of the words while (!st.isEmpty()) { System.out.print(st.peek() + \" \"); st.pop(); } } // Driver Code public static void main(String[] args) { String str; str = \"geeks quiz practice code\"; printRev(str); }} // This code is contributed by Rajput-Ji",
"e": 29056,
"s": 28142,
"text": null
},
{
"code": "# Python3 program to implement# the above approach # Function to reverse the words# of a given stringdef printRev(strr): # Stack to store each # word of the string strr = strr.split(\" \") st = [] # Store the whole string # in stream for i in strr: # Push each word of the # into the stack st.append(i) # Print the in reverse # order of the words while len(st) > 0: print(st[-1], end = \" \") del st[-1] # Driver Codeif __name__ == '__main__': strr = \"geeks quiz practice code\" printRev(strr) # This code is contributed by mohit kumar 29",
"e": 29679,
"s": 29056,
"text": null
},
{
"code": "// C# program to implement// the above approachusing System;using System.Collections; class GFG{ // Function to reverse the words// of a given Stringstatic void printRev(string str){ // Stack to store each // word of the String Stack st = new Stack(); String[] separator = {\" \"}; // Store the whole String // in String stream string[] ss = str.Split(separator, int.MaxValue, StringSplitOptions.RemoveEmptyEntries); foreach(string temp in ss) { // Push each word of the // String into the stack st.Push(temp); } // Print the String in reverse // order of the words while (st.Count > 0) { Console.Write(st.Peek() + \" \"); st.Pop(); }} // Driver Codepublic static void Main(string[] args){ string str; str = \"geeks quiz practice code\"; printRev(str);}} // This code is contributed by rutvik_56",
"e": 30616,
"s": 29679,
"text": null
},
{
"code": "<script>// Javascript Program to implement// the above approach // Function to reverse the words// of a given Stringfunction printRev(str){ // Stack to store each // word of the String let st = []; // Store the whole String // in String stream let ss = str.split(\" \"); for (let temp=0;temp< ss.length;temp++) { // Push each word of the // String into the stack st.push(ss[temp]); } // Print the String in reverse // order of the words while (st.length!=0) { document.write(st.pop() + \" \"); }} // Driver Codelet str;str = \"geeks quiz practice code\";printRev(str); // This code is contributed by unknown2108</script>",
"e": 31395,
"s": 30616,
"text": null
},
{
"code": null,
"e": 31421,
"s": 31395,
"text": "code practice quiz geeks "
},
{
"code": null,
"e": 31507,
"s": 31421,
"text": "Time Complexity: O(N), where N denotes the length of the string.Auxiliary Space: O(N)"
},
{
"code": null,
"e": 31563,
"s": 31507,
"text": "As all the words in a sentence are separated by spaces."
},
{
"code": null,
"e": 31618,
"s": 31563,
"text": "We have to split the sentence by spaces using split()."
},
{
"code": null,
"e": 31677,
"s": 31618,
"text": "We split all the words by spaces and store them in a list."
},
{
"code": null,
"e": 31709,
"s": 31677,
"text": "Reverse this list and print it."
},
{
"code": null,
"e": 31713,
"s": 31709,
"text": "C++"
},
{
"code": null,
"e": 31718,
"s": 31713,
"text": "Java"
},
{
"code": null,
"e": 31726,
"s": 31718,
"text": "Python3"
},
{
"code": null,
"e": 31729,
"s": 31726,
"text": "C#"
},
{
"code": null,
"e": 31740,
"s": 31729,
"text": "Javascript"
},
{
"code": "// C++ program to implement// the above approach#include <bits/stdc++.h>using namespace std; // Function to reverse the words// of a given stringvoid printRev(string lis[]){ // reverse the list reverse(lis, lis + 4); for(int i = 0; i < 4; i++) { cout << lis[i] << \" \"; }} int main(){ string strr[] = {\"geeks\", \"quiz\", \"practice\", \"code\"}; printRev(strr); return 0;} // This code is contributed by divyeshrabadiya07.",
"e": 32204,
"s": 31740,
"text": null
},
{
"code": "// Java program to implement// the above approachimport java.util.*; class GFG{ // Function to reverse the words// of a given stringstatic void printRev(String string){ // Split by space and converting // string to list String[] lis = string.split(\" \", 0); // Reverse the list Collections.reverse(Arrays.asList(lis)); // Printing the list for(String li : lis) { System.out.print(li + \" \"); }} // Driver codepublic static void main(String[] args){ String strr = \"geeks quiz practice code\"; printRev(strr);}} // This code is contributed by decode2207",
"e": 32815,
"s": 32204,
"text": null
},
{
"code": "# Python3 program to implement# the above approach # Function to reverse the words# of a given string def printRev(string): # split by space and converting # string to list lis = list(string.split()) # reverse the list lis.reverse() # printing the list print(*lis) # Driver Codeif __name__ == '__main__': strr = \"geeks quiz practice code\" printRev(strr) # This code is contributed by vikkycirus",
"e": 33241,
"s": 32815,
"text": null
},
{
"code": "// C# program to implement// the above approachusing System;class GFG { // Function to reverse the words // of a given string static void printRev(string String) { // split by space and converting // string to list string[] lis = String.Split(' '); // reverse the list Array.Reverse(lis); // printing the list foreach(string li in lis) { Console.Write(li + \" \"); } } static void Main() { string strr = \"geeks quiz practice code\"; printRev(strr); }} // This code is contributed by rameshtravel07.",
"e": 33860,
"s": 33241,
"text": null
},
{
"code": "<script> // javascript program to implement// the above approach // Function to reverse the words// of a given string function printRev(string){ // split by space and converting // string to list var lis = string.split(' '); console.log(lis); // reverse the list lis.reverse(); console.log(lis); // printing the list document.write(lis.join(' '));} // Driver Code var strr = \"geeks quiz practice code\" printRev(strr) </script>",
"e": 34330,
"s": 33860,
"text": null
},
{
"code": null,
"e": 34355,
"s": 34330,
"text": "code practice quiz geeks"
},
{
"code": null,
"e": 34370,
"s": 34355,
"text": "mohit kumar 29"
},
{
"code": null,
"e": 34380,
"s": 34370,
"text": "Rajput-Ji"
},
{
"code": null,
"e": 34390,
"s": 34380,
"text": "rutvik_56"
},
{
"code": null,
"e": 34401,
"s": 34390,
"text": "vikkycirus"
},
{
"code": null,
"e": 34416,
"s": 34401,
"text": "adnanirshad158"
},
{
"code": null,
"e": 34427,
"s": 34416,
"text": "bunnyram19"
},
{
"code": null,
"e": 34439,
"s": 34427,
"text": "unknown2108"
},
{
"code": null,
"e": 34449,
"s": 34439,
"text": "ruhelaa48"
},
{
"code": null,
"e": 34465,
"s": 34449,
"text": "saurabh1990aror"
},
{
"code": null,
"e": 34480,
"s": 34465,
"text": "rameshtravel07"
},
{
"code": null,
"e": 34491,
"s": 34480,
"text": "decode2207"
},
{
"code": null,
"e": 34509,
"s": 34491,
"text": "divyeshrabadiya07"
},
{
"code": null,
"e": 34521,
"s": 34509,
"text": "anikaseth98"
},
{
"code": null,
"e": 34529,
"s": 34521,
"text": "Reverse"
},
{
"code": null,
"e": 34539,
"s": 34529,
"text": "substring"
},
{
"code": null,
"e": 34545,
"s": 34539,
"text": "Stack"
},
{
"code": null,
"e": 34553,
"s": 34545,
"text": "Strings"
},
{
"code": null,
"e": 34561,
"s": 34553,
"text": "Strings"
},
{
"code": null,
"e": 34567,
"s": 34561,
"text": "Stack"
},
{
"code": null,
"e": 34575,
"s": 34567,
"text": "Reverse"
},
{
"code": null,
"e": 34673,
"s": 34575,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 34714,
"s": 34673,
"text": "Real-time application of Data Structures"
},
{
"code": null,
"e": 34736,
"s": 34714,
"text": "ZigZag Tree Traversal"
},
{
"code": null,
"e": 34761,
"s": 34736,
"text": "Reverse individual words"
},
{
"code": null,
"e": 34794,
"s": 34761,
"text": "Evaluation of Prefix Expressions"
},
{
"code": null,
"e": 34831,
"s": 34794,
"text": "Sort a stack using a temporary stack"
},
{
"code": null,
"e": 34877,
"s": 34831,
"text": "Write a program to reverse an array or string"
},
{
"code": null,
"e": 34902,
"s": 34877,
"text": "Reverse a string in Java"
},
{
"code": null,
"e": 34962,
"s": 34902,
"text": "Write a program to print all permutations of a given string"
},
{
"code": null,
"e": 34977,
"s": 34962,
"text": "C++ Data Types"
}
] |
Contour Plots using Plotly in Python - GeeksforGeeks
|
12 Feb, 2021
A Plotly is a Python library that is used to design graphs, especially interactive graphs. It can plot various graphs and charts like histogram, barplot, boxplot, spreadplot, and many more. It is mainly used in data analysis as well as financial analysis. plotly is an interactive visualization library.
A contour plot has a function of two variables of curves along which the function has constant values so that these curves join the points with equal values. In contour plot, a 2d contour plot presents contour lines of a 2D numerical array z, i.e. interpolated lines of iso values of z.
Syntax: plotly.graph_objects.Contour(arg=None,colorbar=None, hoverinfo=None, x=None,y=None,**kwargs)
Parameters:
arg: dict of properties compatible with this constructor or an instance of plotly.graph_objects.Contour
colorbar: plotly.graph_objects.contour.ColorBar instance or dict with compatible properties
x: Sets the x coordinates.
y: Sets the y coordinates.
z: Sets the z coordinates.
hoverinfo: Determines which trace information appear on hover. If none or skip are set, no information is displayed upon hovering. But, if none is set, click and hover events are still fired.
Example 1: Creating a simple contour plot
Python3
import plotly.graph_objects as goimport numpy as np data = [[1,2,3,4,5], [3,4,5,6,7], [7,8,9,6,4], [3,7,2,4,2]] fig = go.Figure(data = go.Contour(z = data)) fig.show()
Output:
Example 2: Creating contour plot with X and Y coordinates.
Python3
import plotly.graph_objects as go feature_x = np.arange(0, 50, 2)feature_y = np.arange(0, 50, 3) # Creating 2-D grid of features[X, Y] = np.meshgrid(feature_x, feature_y) Z = np.cos(X / 2) + np.sin(Y / 4) fig = go.Figure(data = go.Contour(x = feature_x, y = feature_y, z = Z)) fig.show()
Output:
In plotly, the colorscale for the contour plot is used to add different colors and can be set using the colorscale parameter.
Example:
Python3
import plotly.graph_objects as go feature_x = np.arange(0, 50, 2)feature_y = np.arange(0, 50, 3) # Creating 2-D grid of features[X, Y] = np.meshgrid(feature_x, feature_y) Z = np.cos(X / 2) + np.sin(Y / 4) fig = go.Figure(data = go.Contour(x = feature_x, y = feature_y, z = Z, colorscale='rainbow' )) fig.show()
Output:
Here we can customize our contour plot using colorscale. A list of colors that will be spaced evenly to create the colorscale. Many predefined colorscale lists are included in the sequential, diverging.
The following color set is available on colorscale.
‘aggrnyl’, ‘agsunset’, ‘algae’, ‘amp’, ‘armyrose’, ‘balance’, ‘blackbody’, ‘bluered’, ‘blues’, ‘blugrn’, ‘bluyl’, ‘brbg’,’brwnyl’, ‘bugn’, ‘bupu’, ‘burg’, ‘burgyl’, ‘cividis’, ‘curl’, ‘darkmint’, ‘deep’, ‘delta’, ‘dense’, ‘earth’, ‘edge’, ‘electric’, ’emrld’, ‘fall’, ‘geyser’, ‘gnbu’, ‘gray’, ‘greens’, ‘greys’,’haline’, ‘hot’, ‘hsv’, ‘ice’, ‘icefire’, ‘inferno’, ‘jet’, ‘magenta’, ‘magma’, ‘matter’, ‘mint’, ‘mrybm’, ‘mygbm’, ‘oranges’, ‘orrd’, ‘oryel’, ‘oxy’, ‘peach’, ‘phase’, ‘picnic’, ‘pinkyl’, ‘piyg’, ‘plasma’, ‘plotly3’, ‘portland’, ‘prgn’, ‘pubu’, ‘pubugn’,’puor’, ‘purd’, ‘purp’, ‘purples’, ‘purpor’, ‘rainbow’, ‘rdbu’, ‘rdgy’, ‘rdpu’, ‘rdylbu’, ‘rdylgn’, ‘redor’, ‘reds’, ‘solar’, ‘spectral’, ‘speed’, ‘sunset’, ‘sunsetdark’, ‘teal’, ‘tealgrn’, ‘tealrose’, ‘tempo’, ‘temps’, ‘thermal’, ‘tropic’, ‘turbid’, ‘turbo’, ‘twilight’, ‘viridis’, ‘ylgn’, ‘ylgnbu’, ‘ylorbr’, ‘ylorrd’].
Example:
Python3
import plotly.graph_objects as go feature_x = np.arange(0, 50, 2)feature_y = np.arange(0, 50, 3) colorscale = colorscale = [[0, 'green'], [0.5, 'red'], [1.0, 'rgb(0, 0, 255)']] # Creating 2-D grid of features[X, Y] = np.meshgrid(feature_x, feature_y) Z = np.cos(X / 2) + np.sin(Y / 4) fig = go.Figure(data = go.Contour(x = feature_x, y = feature_y, z = Z, colorscale = colorscale)) fig.show()
Output:
We can customize size and range of our contour plot using contours attributes. contours accept dict object that contains the range and size of the coordinates.
Python3
import plotly.graph_objects as go feature_x = np.arange(0, 50, 2)feature_y = np.arange(0, 50, 3) # Creating 2-D grid of features[X, Y] = np.meshgrid(feature_x, feature_y) Z = np.cos(X / 2) + np.sin(Y / 4) fig = go.Figure(data = go.Contour(x = feature_x, y = feature_y, z = Z, contours=dict( start=1, end=5, size=.2) ) ) fig.show()
Output:
Labels can be added using the contours parameter that has a property called showlabels. It determines whether to label the contour lines with their values.
Example:
Python3
import plotly.graph_objects as go feature_x = np.arange(0, 50, 2)feature_y = np.arange(0, 50, 3) # Creating 2-D grid of features[X, Y] = np.meshgrid(feature_x, feature_y) Z = np.cos(X / 2) + np.sin(Y / 4) fig = go.Figure(data=go.Contour( x=feature_x, y=feature_y, z=Z, contours=dict( coloring='lines', showlabels=True,))) fig.show()
Output:
kumar_satyam
Python-Plotly
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
Taking input in Python
Read a file line by line in Python
How to Install PIP on Windows ?
Enumerate() in Python
Different ways to create Pandas Dataframe
|
[
{
"code": null,
"e": 25313,
"s": 25285,
"text": "\n12 Feb, 2021"
},
{
"code": null,
"e": 25617,
"s": 25313,
"text": "A Plotly is a Python library that is used to design graphs, especially interactive graphs. It can plot various graphs and charts like histogram, barplot, boxplot, spreadplot, and many more. It is mainly used in data analysis as well as financial analysis. plotly is an interactive visualization library."
},
{
"code": null,
"e": 25904,
"s": 25617,
"text": "A contour plot has a function of two variables of curves along which the function has constant values so that these curves join the points with equal values. In contour plot, a 2d contour plot presents contour lines of a 2D numerical array z, i.e. interpolated lines of iso values of z."
},
{
"code": null,
"e": 26005,
"s": 25904,
"text": "Syntax: plotly.graph_objects.Contour(arg=None,colorbar=None, hoverinfo=None, x=None,y=None,**kwargs)"
},
{
"code": null,
"e": 26017,
"s": 26005,
"text": "Parameters:"
},
{
"code": null,
"e": 26121,
"s": 26017,
"text": "arg: dict of properties compatible with this constructor or an instance of plotly.graph_objects.Contour"
},
{
"code": null,
"e": 26214,
"s": 26121,
"text": "colorbar: plotly.graph_objects.contour.ColorBar instance or dict with compatible properties"
},
{
"code": null,
"e": 26241,
"s": 26214,
"text": "x: Sets the x coordinates."
},
{
"code": null,
"e": 26268,
"s": 26241,
"text": "y: Sets the y coordinates."
},
{
"code": null,
"e": 26295,
"s": 26268,
"text": "z: Sets the z coordinates."
},
{
"code": null,
"e": 26487,
"s": 26295,
"text": "hoverinfo: Determines which trace information appear on hover. If none or skip are set, no information is displayed upon hovering. But, if none is set, click and hover events are still fired."
},
{
"code": null,
"e": 26529,
"s": 26487,
"text": "Example 1: Creating a simple contour plot"
},
{
"code": null,
"e": 26537,
"s": 26529,
"text": "Python3"
},
{
"code": "import plotly.graph_objects as goimport numpy as np data = [[1,2,3,4,5], [3,4,5,6,7], [7,8,9,6,4], [3,7,2,4,2]] fig = go.Figure(data = go.Contour(z = data)) fig.show()",
"e": 26721,
"s": 26537,
"text": null
},
{
"code": null,
"e": 26729,
"s": 26721,
"text": "Output:"
},
{
"code": null,
"e": 26788,
"s": 26729,
"text": "Example 2: Creating contour plot with X and Y coordinates."
},
{
"code": null,
"e": 26796,
"s": 26788,
"text": "Python3"
},
{
"code": "import plotly.graph_objects as go feature_x = np.arange(0, 50, 2)feature_y = np.arange(0, 50, 3) # Creating 2-D grid of features[X, Y] = np.meshgrid(feature_x, feature_y) Z = np.cos(X / 2) + np.sin(Y / 4) fig = go.Figure(data = go.Contour(x = feature_x, y = feature_y, z = Z)) fig.show()",
"e": 27088,
"s": 26796,
"text": null
},
{
"code": null,
"e": 27096,
"s": 27088,
"text": "Output:"
},
{
"code": null,
"e": 27222,
"s": 27096,
"text": "In plotly, the colorscale for the contour plot is used to add different colors and can be set using the colorscale parameter."
},
{
"code": null,
"e": 27231,
"s": 27222,
"text": "Example:"
},
{
"code": null,
"e": 27239,
"s": 27231,
"text": "Python3"
},
{
"code": "import plotly.graph_objects as go feature_x = np.arange(0, 50, 2)feature_y = np.arange(0, 50, 3) # Creating 2-D grid of features[X, Y] = np.meshgrid(feature_x, feature_y) Z = np.cos(X / 2) + np.sin(Y / 4) fig = go.Figure(data = go.Contour(x = feature_x, y = feature_y, z = Z, colorscale='rainbow' )) fig.show()",
"e": 27582,
"s": 27239,
"text": null
},
{
"code": null,
"e": 27590,
"s": 27582,
"text": "Output:"
},
{
"code": null,
"e": 27794,
"s": 27590,
"text": "Here we can customize our contour plot using colorscale. A list of colors that will be spaced evenly to create the colorscale. Many predefined colorscale lists are included in the sequential, diverging. "
},
{
"code": null,
"e": 27846,
"s": 27794,
"text": "The following color set is available on colorscale."
},
{
"code": null,
"e": 28735,
"s": 27846,
"text": "‘aggrnyl’, ‘agsunset’, ‘algae’, ‘amp’, ‘armyrose’, ‘balance’, ‘blackbody’, ‘bluered’, ‘blues’, ‘blugrn’, ‘bluyl’, ‘brbg’,’brwnyl’, ‘bugn’, ‘bupu’, ‘burg’, ‘burgyl’, ‘cividis’, ‘curl’, ‘darkmint’, ‘deep’, ‘delta’, ‘dense’, ‘earth’, ‘edge’, ‘electric’, ’emrld’, ‘fall’, ‘geyser’, ‘gnbu’, ‘gray’, ‘greens’, ‘greys’,’haline’, ‘hot’, ‘hsv’, ‘ice’, ‘icefire’, ‘inferno’, ‘jet’, ‘magenta’, ‘magma’, ‘matter’, ‘mint’, ‘mrybm’, ‘mygbm’, ‘oranges’, ‘orrd’, ‘oryel’, ‘oxy’, ‘peach’, ‘phase’, ‘picnic’, ‘pinkyl’, ‘piyg’, ‘plasma’, ‘plotly3’, ‘portland’, ‘prgn’, ‘pubu’, ‘pubugn’,’puor’, ‘purd’, ‘purp’, ‘purples’, ‘purpor’, ‘rainbow’, ‘rdbu’, ‘rdgy’, ‘rdpu’, ‘rdylbu’, ‘rdylgn’, ‘redor’, ‘reds’, ‘solar’, ‘spectral’, ‘speed’, ‘sunset’, ‘sunsetdark’, ‘teal’, ‘tealgrn’, ‘tealrose’, ‘tempo’, ‘temps’, ‘thermal’, ‘tropic’, ‘turbid’, ‘turbo’, ‘twilight’, ‘viridis’, ‘ylgn’, ‘ylgnbu’, ‘ylorbr’, ‘ylorrd’]."
},
{
"code": null,
"e": 28744,
"s": 28735,
"text": "Example:"
},
{
"code": null,
"e": 28752,
"s": 28744,
"text": "Python3"
},
{
"code": "import plotly.graph_objects as go feature_x = np.arange(0, 50, 2)feature_y = np.arange(0, 50, 3) colorscale = colorscale = [[0, 'green'], [0.5, 'red'], [1.0, 'rgb(0, 0, 255)']] # Creating 2-D grid of features[X, Y] = np.meshgrid(feature_x, feature_y) Z = np.cos(X / 2) + np.sin(Y / 4) fig = go.Figure(data = go.Contour(x = feature_x, y = feature_y, z = Z, colorscale = colorscale)) fig.show()",
"e": 29189,
"s": 28752,
"text": null
},
{
"code": null,
"e": 29197,
"s": 29189,
"text": "Output:"
},
{
"code": null,
"e": 29357,
"s": 29197,
"text": "We can customize size and range of our contour plot using contours attributes. contours accept dict object that contains the range and size of the coordinates."
},
{
"code": null,
"e": 29365,
"s": 29357,
"text": "Python3"
},
{
"code": "import plotly.graph_objects as go feature_x = np.arange(0, 50, 2)feature_y = np.arange(0, 50, 3) # Creating 2-D grid of features[X, Y] = np.meshgrid(feature_x, feature_y) Z = np.cos(X / 2) + np.sin(Y / 4) fig = go.Figure(data = go.Contour(x = feature_x, y = feature_y, z = Z, contours=dict( start=1, end=5, size=.2) ) ) fig.show()",
"e": 29815,
"s": 29365,
"text": null
},
{
"code": null,
"e": 29823,
"s": 29815,
"text": "Output:"
},
{
"code": null,
"e": 29979,
"s": 29823,
"text": "Labels can be added using the contours parameter that has a property called showlabels. It determines whether to label the contour lines with their values."
},
{
"code": null,
"e": 29988,
"s": 29979,
"text": "Example:"
},
{
"code": null,
"e": 29996,
"s": 29988,
"text": "Python3"
},
{
"code": "import plotly.graph_objects as go feature_x = np.arange(0, 50, 2)feature_y = np.arange(0, 50, 3) # Creating 2-D grid of features[X, Y] = np.meshgrid(feature_x, feature_y) Z = np.cos(X / 2) + np.sin(Y / 4) fig = go.Figure(data=go.Contour( x=feature_x, y=feature_y, z=Z, contours=dict( coloring='lines', showlabels=True,))) fig.show()",
"e": 30349,
"s": 29996,
"text": null
},
{
"code": null,
"e": 30357,
"s": 30349,
"text": "Output:"
},
{
"code": null,
"e": 30370,
"s": 30357,
"text": "kumar_satyam"
},
{
"code": null,
"e": 30384,
"s": 30370,
"text": "Python-Plotly"
},
{
"code": null,
"e": 30391,
"s": 30384,
"text": "Python"
},
{
"code": null,
"e": 30489,
"s": 30391,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 30517,
"s": 30489,
"text": "Read JSON file using Python"
},
{
"code": null,
"e": 30567,
"s": 30517,
"text": "Adding new column to existing DataFrame in Pandas"
},
{
"code": null,
"e": 30589,
"s": 30567,
"text": "Python map() function"
},
{
"code": null,
"e": 30633,
"s": 30589,
"text": "How to get column names in Pandas dataframe"
},
{
"code": null,
"e": 30651,
"s": 30633,
"text": "Python Dictionary"
},
{
"code": null,
"e": 30674,
"s": 30651,
"text": "Taking input in Python"
},
{
"code": null,
"e": 30709,
"s": 30674,
"text": "Read a file line by line in Python"
},
{
"code": null,
"e": 30741,
"s": 30709,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 30763,
"s": 30741,
"text": "Enumerate() in Python"
}
] |
numpy.asanyarray() in Python - GeeksforGeeks
|
28 May, 2019
numpy.asanyarray()function is used when we want to convert input to an array but it pass ndarray subclasses through. Input can be scalars, lists, lists of tuples, tuples, tuples of tuples, tuples of lists and ndarrays.
Syntax : numpy.asanyarray(arr, dtype=None, order=None)
Parameters :arr : [array_like] Input data, in any form that can be converted to an array. This includes scalars, lists, lists of tuples, tuples, tuples of tuples, tuples of lists, and ndarrays.dtype : [data-type, optional] By default, the data-type is inferred from the input data.order : Whether to use row-major (C-style) or column-major (Fortran-style) memory representation. Defaults to ‘C’.
Return : [ndarray or an ndarray subclass] Array interpretation of arr. If arr is ndarray or a subclass of ndarray, it is returned as-is and no copy is performed.
Code #1 : List to array
# Python program explaining# numpy.asanyarray() function import numpy as geekmy_list = [1, 3, 5, 7, 9] print ("Input list : ", my_list) out_arr = geek.asanyarray(my_list)print ("output array from input list : ", out_arr)
Output :
Input list : [1, 3, 5, 7, 9]
output array from input list : [1 3 5 7 9]
Code #2 : Tuple to array
# Python program explaining# numpy.asanyarray() function import numpy as geek my_tuple = ([1, 3, 9], [8, 2, 6]) print ("Input tuple : ", my_tuple) out_arr = geek.asanyarray(my_tuple) print ("output array from input tuple : ", out_arr)
Output :
Input tuple : ([1, 3, 9], [8, 2, 6])
output array from input tuple : [[1 3 9]
[8 2 6]]
Code #3 : Scalar to array
# Python program explaining# numpy.asanyarray() function import numpy as geek my_scalar = 12 print ("Input scalar : ", my_scalar) out_arr = geek.asanyarray(my_scalar) print ("output array from input scalar : ", out_arr) print(type(out_arr))
Output :
Input scalar : 12
output array from input scalar : 12
class 'numpy.ndarray'
SujithSagar
Python numpy-arrayCreation
Python-numpy
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Install PIP on Windows ?
Check if element exists in list in Python
How To Convert Python Dictionary To JSON?
How to drop one or multiple columns in Pandas Dataframe
Python Classes and Objects
Python | os.path.join() method
Python | Get unique values from a list
Create a directory in Python
Defaultdict in Python
Python | Pandas dataframe.groupby()
|
[
{
"code": null,
"e": 25562,
"s": 25534,
"text": "\n28 May, 2019"
},
{
"code": null,
"e": 25781,
"s": 25562,
"text": "numpy.asanyarray()function is used when we want to convert input to an array but it pass ndarray subclasses through. Input can be scalars, lists, lists of tuples, tuples, tuples of tuples, tuples of lists and ndarrays."
},
{
"code": null,
"e": 25836,
"s": 25781,
"text": "Syntax : numpy.asanyarray(arr, dtype=None, order=None)"
},
{
"code": null,
"e": 26232,
"s": 25836,
"text": "Parameters :arr : [array_like] Input data, in any form that can be converted to an array. This includes scalars, lists, lists of tuples, tuples, tuples of tuples, tuples of lists, and ndarrays.dtype : [data-type, optional] By default, the data-type is inferred from the input data.order : Whether to use row-major (C-style) or column-major (Fortran-style) memory representation. Defaults to ‘C’."
},
{
"code": null,
"e": 26394,
"s": 26232,
"text": "Return : [ndarray or an ndarray subclass] Array interpretation of arr. If arr is ndarray or a subclass of ndarray, it is returned as-is and no copy is performed."
},
{
"code": null,
"e": 26418,
"s": 26394,
"text": "Code #1 : List to array"
},
{
"code": "# Python program explaining# numpy.asanyarray() function import numpy as geekmy_list = [1, 3, 5, 7, 9] print (\"Input list : \", my_list) out_arr = geek.asanyarray(my_list)print (\"output array from input list : \", out_arr) ",
"e": 26649,
"s": 26418,
"text": null
},
{
"code": null,
"e": 26658,
"s": 26649,
"text": "Output :"
},
{
"code": null,
"e": 26734,
"s": 26658,
"text": "Input list : [1, 3, 5, 7, 9]\noutput array from input list : [1 3 5 7 9]\n"
},
{
"code": null,
"e": 26760,
"s": 26734,
"text": " Code #2 : Tuple to array"
},
{
"code": "# Python program explaining# numpy.asanyarray() function import numpy as geek my_tuple = ([1, 3, 9], [8, 2, 6]) print (\"Input tuple : \", my_tuple) out_arr = geek.asanyarray(my_tuple) print (\"output array from input tuple : \", out_arr) ",
"e": 27004,
"s": 26760,
"text": null
},
{
"code": null,
"e": 27013,
"s": 27004,
"text": "Output :"
},
{
"code": null,
"e": 27105,
"s": 27013,
"text": "Input tuple : ([1, 3, 9], [8, 2, 6])\noutput array from input tuple : [[1 3 9]\n [8 2 6]]\n"
},
{
"code": null,
"e": 27132,
"s": 27105,
"text": " Code #3 : Scalar to array"
},
{
"code": "# Python program explaining# numpy.asanyarray() function import numpy as geek my_scalar = 12 print (\"Input scalar : \", my_scalar) out_arr = geek.asanyarray(my_scalar) print (\"output array from input scalar : \", out_arr) print(type(out_arr))",
"e": 27381,
"s": 27132,
"text": null
},
{
"code": null,
"e": 27390,
"s": 27381,
"text": "Output :"
},
{
"code": null,
"e": 27470,
"s": 27390,
"text": "Input scalar : 12\noutput array from input scalar : 12\nclass 'numpy.ndarray'\n"
},
{
"code": null,
"e": 27482,
"s": 27470,
"text": "SujithSagar"
},
{
"code": null,
"e": 27509,
"s": 27482,
"text": "Python numpy-arrayCreation"
},
{
"code": null,
"e": 27522,
"s": 27509,
"text": "Python-numpy"
},
{
"code": null,
"e": 27529,
"s": 27522,
"text": "Python"
},
{
"code": null,
"e": 27627,
"s": 27529,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 27659,
"s": 27627,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 27701,
"s": 27659,
"text": "Check if element exists in list in Python"
},
{
"code": null,
"e": 27743,
"s": 27701,
"text": "How To Convert Python Dictionary To JSON?"
},
{
"code": null,
"e": 27799,
"s": 27743,
"text": "How to drop one or multiple columns in Pandas Dataframe"
},
{
"code": null,
"e": 27826,
"s": 27799,
"text": "Python Classes and Objects"
},
{
"code": null,
"e": 27857,
"s": 27826,
"text": "Python | os.path.join() method"
},
{
"code": null,
"e": 27896,
"s": 27857,
"text": "Python | Get unique values from a list"
},
{
"code": null,
"e": 27925,
"s": 27896,
"text": "Create a directory in Python"
},
{
"code": null,
"e": 27947,
"s": 27925,
"text": "Defaultdict in Python"
}
] |
Implementing a Superellipse - GeeksforGeeks
|
29 Nov, 2017
What is a superellipseA superellipse, also known as a Lamé curve after Gabriel Lamé, is a closed curve resembling the ellipse, retaining the geometric features of semi-major axis and semi-minor axis, and symmetry about them, but a different overall shape.In the Cartesian coordinate system, the set of all points (x, y) on the curve satisfy the equation
where n, a and b are positive numbers, and the vertical bars | | around a number indicate the absolute value of the number.
a = 1 and b = 0.75
There are many number of specific cases of superellipse like given in the image down below:These can be achieved by varying the value of n in the equation. So now we try to implement this in python and to do that we are require some libraries.
Modules Required:
matplotlib: To plot the curve of the equation. Its an 3rd party library in python and if you want to install it click here.
math : Its an built in library of python which have almost all the mathematical tools.
# Python program to implement # Superellipse # importing the required librariesimport matplotlib.pyplot as pltfrom math import sin, cos, pi def sgn(x): return ((x>0)-(x<0))*1 # parameter for marking the shape a, b, n = 200, 200, 2.5na = 2 / n# defining the accuracystep = 100 piece =(pi * 2)/stepxp =[];yp =[] t = 0for t1 in range(step + 1): # because sin ^ n(x) is mathematically the same as (sin(x))^n... x =(abs((cos(t)))**na)*a * sgn(cos(t)) y =(abs((sin(t)))**na)*b * sgn(sin(t)) xp.append(x);yp.append(y) t+= piece plt.plot(xp, yp) # plotting all point from array xp, ypplt.title("Superellipse with parameter "+str(n))plt.show()
Output:
when n = 2.5
Now let’s see what happens when we changes the value of n to 0.5
# Python program to implement # Superellipse# importing the required librariesimport matplotlib.pyplot as pltfrom math import sin, cos, pi def sgn(x): return ((x>0)-(x<0))*1 # parameter for marking the shape a, b, n = 200, 200, 0.5na = 2 / n# defining the accuracystep = 100 piece =(pi * 2)/stepxp =[];yp =[] t = 0for t1 in range(step + 1): # because sin ^ n(x) is mathematically the same as (sin(x))^n... x =(abs((cos(t)))**na)*a * sgn(cos(t)) y =(abs((sin(t)))**na)*b * sgn(sin(t)) xp.append(x);yp.append(y) t+= piece plt.plot(xp, yp) # plotting all point from array xp, ypplt.title("Superellipse with parameter "+str(n))plt.show()
Output:
Source Code of the program in Java.
// Java program to implement// Superellipseimport java.awt.*;import java.awt.geom.Path2D;import static java.lang.Math.pow;import java.util.Hashtable;import javax.swing.*;import javax.swing.event.*; public class SuperEllipse extends JPanel implements ChangeListener { private double exp = 2.5; public SuperEllipse() { setPreferredSize(new Dimension(650, 650)); setBackground(Color.white); setFont(new Font("Serif", Font.PLAIN, 18)); } void drawGrid(Graphics2D g) { g.setStroke(new BasicStroke(2)); g.setColor(new Color(0xEEEEEE)); int w = getWidth(); int h = getHeight(); int spacing = 25; for (int i = 0; i < w / spacing; i++) { g.drawLine(0, i * spacing, w, i * spacing); g.drawLine(i * spacing, 0, i * spacing, w); } g.drawLine(0, h - 1, w, h - 1); g.setColor(new Color(0xAAAAAA)); g.drawLine(0, w / 2, w, w / 2); g.drawLine(w / 2, 0, w / 2, w); } void drawLegend(Graphics2D g) { g.setColor(Color.black); g.setFont(getFont()); g.drawString("n = " + String.valueOf(exp), getWidth() - 150, 45); g.drawString("a = b = 200", getWidth() - 150, 75); } void drawEllipse(Graphics2D g) { final int a = 200; // a = b double[] points = new double[a + 1]; Path2D p = new Path2D.Double(); p.moveTo(a, 0); // calculate first quadrant for (int x = a; x >= 0; x--) { points[x] = pow(pow(a, exp) - pow(x, exp), 1 / exp); // solve for y p.lineTo(x, -points[x]); } // mirror to others for (int x = 0; x <= a; x++) p.lineTo(x, points[x]); for (int x = a; x >= 0; x--) p.lineTo(-x, points[x]); for (int x = 0; x <= a; x++) p.lineTo(-x, -points[x]); g.translate(getWidth() / 2, getHeight() / 2); g.setStroke(new BasicStroke(2)); g.setColor(new Color(0x25B0C4DE, true)); g.fill(p); g.setColor(new Color(0xB0C4DE)); // LightSteelBlue g.draw(p); } @Override public void paintComponent(Graphics gg) { super.paintComponent(gg); Graphics2D g = (Graphics2D)gg; g.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON); g.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_ON); drawGrid(g); drawLegend(g); drawEllipse(g); } @Override public void stateChanged(ChangeEvent e) { JSlider source = (JSlider)e.getSource(); exp = source.getValue() / 2.0; repaint(); } public static void main(String[] args) { SwingUtilities.invokeLater(() -> { JFrame f = new JFrame(); f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); f.setTitle("Super Ellipse"); f.setResizable(false); SuperEllipse panel = new SuperEllipse(); f.add(panel, BorderLayout.CENTER); JSlider exponent = new JSlider(JSlider.HORIZONTAL, 1, 9, 5); exponent.addChangeListener(panel); exponent.setMajorTickSpacing(1); exponent.setPaintLabels(true); exponent.setBackground(Color.white); exponent.setBorder(BorderFactory.createEmptyBorder(20, 20, 20, 20)); Hashtable<Integer, JLabel> labelTable = new Hashtable<>(); for (int i = 1; i < 10; i++) labelTable.put(i, new JLabel(String.valueOf(i * 0.5))); exponent.setLabelTable(labelTable); f.add(exponent, BorderLayout.SOUTH); f.pack(); f.setLocationRelativeTo(null); f.setVisible(true); }); }}
Output:
Reference Links:
1. Wikipedia – Superellipse2. WolframMathWorld – Superellipse
This article is contributed by Subhajit Saha. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
GBlog
Mathematical
Technical Scripter
Mathematical
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
DSA Sheet by Love Babbar
GET and POST requests using Python
Top 10 Projects For Beginners To Practice HTML and CSS Skills
Types of Software Testing
Working with csv files in Python
Program for Fibonacci numbers
Write a program to print all permutations of a given string
C++ Data Types
Set in C++ Standard Template Library (STL)
Coin Change | DP-7
|
[
{
"code": null,
"e": 26365,
"s": 26337,
"text": "\n29 Nov, 2017"
},
{
"code": null,
"e": 26721,
"s": 26365,
"text": "What is a superellipseA superellipse, also known as a Lamé curve after Gabriel Lamé, is a closed curve resembling the ellipse, retaining the geometric features of semi-major axis and semi-minor axis, and symmetry about them, but a different overall shape.In the Cartesian coordinate system, the set of all points (x, y) on the curve satisfy the equation"
},
{
"code": null,
"e": 26845,
"s": 26721,
"text": "where n, a and b are positive numbers, and the vertical bars | | around a number indicate the absolute value of the number."
},
{
"code": null,
"e": 26864,
"s": 26845,
"text": "a = 1 and b = 0.75"
},
{
"code": null,
"e": 27108,
"s": 26864,
"text": "There are many number of specific cases of superellipse like given in the image down below:These can be achieved by varying the value of n in the equation. So now we try to implement this in python and to do that we are require some libraries."
},
{
"code": null,
"e": 27126,
"s": 27108,
"text": "Modules Required:"
},
{
"code": null,
"e": 27250,
"s": 27126,
"text": "matplotlib: To plot the curve of the equation. Its an 3rd party library in python and if you want to install it click here."
},
{
"code": null,
"e": 27337,
"s": 27250,
"text": "math : Its an built in library of python which have almost all the mathematical tools."
},
{
"code": "# Python program to implement # Superellipse # importing the required librariesimport matplotlib.pyplot as pltfrom math import sin, cos, pi def sgn(x): return ((x>0)-(x<0))*1 # parameter for marking the shape a, b, n = 200, 200, 2.5na = 2 / n# defining the accuracystep = 100 piece =(pi * 2)/stepxp =[];yp =[] t = 0for t1 in range(step + 1): # because sin ^ n(x) is mathematically the same as (sin(x))^n... x =(abs((cos(t)))**na)*a * sgn(cos(t)) y =(abs((sin(t)))**na)*b * sgn(sin(t)) xp.append(x);yp.append(y) t+= piece plt.plot(xp, yp) # plotting all point from array xp, ypplt.title(\"Superellipse with parameter \"+str(n))plt.show()",
"e": 27999,
"s": 27337,
"text": null
},
{
"code": null,
"e": 28007,
"s": 27999,
"text": "Output:"
},
{
"code": null,
"e": 28020,
"s": 28007,
"text": "when n = 2.5"
},
{
"code": null,
"e": 28085,
"s": 28020,
"text": "Now let’s see what happens when we changes the value of n to 0.5"
},
{
"code": "# Python program to implement # Superellipse# importing the required librariesimport matplotlib.pyplot as pltfrom math import sin, cos, pi def sgn(x): return ((x>0)-(x<0))*1 # parameter for marking the shape a, b, n = 200, 200, 0.5na = 2 / n# defining the accuracystep = 100 piece =(pi * 2)/stepxp =[];yp =[] t = 0for t1 in range(step + 1): # because sin ^ n(x) is mathematically the same as (sin(x))^n... x =(abs((cos(t)))**na)*a * sgn(cos(t)) y =(abs((sin(t)))**na)*b * sgn(sin(t)) xp.append(x);yp.append(y) t+= piece plt.plot(xp, yp) # plotting all point from array xp, ypplt.title(\"Superellipse with parameter \"+str(n))plt.show()",
"e": 28745,
"s": 28085,
"text": null
},
{
"code": null,
"e": 28753,
"s": 28745,
"text": "Output:"
},
{
"code": null,
"e": 28789,
"s": 28753,
"text": "Source Code of the program in Java."
},
{
"code": "// Java program to implement// Superellipseimport java.awt.*;import java.awt.geom.Path2D;import static java.lang.Math.pow;import java.util.Hashtable;import javax.swing.*;import javax.swing.event.*; public class SuperEllipse extends JPanel implements ChangeListener { private double exp = 2.5; public SuperEllipse() { setPreferredSize(new Dimension(650, 650)); setBackground(Color.white); setFont(new Font(\"Serif\", Font.PLAIN, 18)); } void drawGrid(Graphics2D g) { g.setStroke(new BasicStroke(2)); g.setColor(new Color(0xEEEEEE)); int w = getWidth(); int h = getHeight(); int spacing = 25; for (int i = 0; i < w / spacing; i++) { g.drawLine(0, i * spacing, w, i * spacing); g.drawLine(i * spacing, 0, i * spacing, w); } g.drawLine(0, h - 1, w, h - 1); g.setColor(new Color(0xAAAAAA)); g.drawLine(0, w / 2, w, w / 2); g.drawLine(w / 2, 0, w / 2, w); } void drawLegend(Graphics2D g) { g.setColor(Color.black); g.setFont(getFont()); g.drawString(\"n = \" + String.valueOf(exp), getWidth() - 150, 45); g.drawString(\"a = b = 200\", getWidth() - 150, 75); } void drawEllipse(Graphics2D g) { final int a = 200; // a = b double[] points = new double[a + 1]; Path2D p = new Path2D.Double(); p.moveTo(a, 0); // calculate first quadrant for (int x = a; x >= 0; x--) { points[x] = pow(pow(a, exp) - pow(x, exp), 1 / exp); // solve for y p.lineTo(x, -points[x]); } // mirror to others for (int x = 0; x <= a; x++) p.lineTo(x, points[x]); for (int x = a; x >= 0; x--) p.lineTo(-x, points[x]); for (int x = 0; x <= a; x++) p.lineTo(-x, -points[x]); g.translate(getWidth() / 2, getHeight() / 2); g.setStroke(new BasicStroke(2)); g.setColor(new Color(0x25B0C4DE, true)); g.fill(p); g.setColor(new Color(0xB0C4DE)); // LightSteelBlue g.draw(p); } @Override public void paintComponent(Graphics gg) { super.paintComponent(gg); Graphics2D g = (Graphics2D)gg; g.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON); g.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_ON); drawGrid(g); drawLegend(g); drawEllipse(g); } @Override public void stateChanged(ChangeEvent e) { JSlider source = (JSlider)e.getSource(); exp = source.getValue() / 2.0; repaint(); } public static void main(String[] args) { SwingUtilities.invokeLater(() -> { JFrame f = new JFrame(); f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); f.setTitle(\"Super Ellipse\"); f.setResizable(false); SuperEllipse panel = new SuperEllipse(); f.add(panel, BorderLayout.CENTER); JSlider exponent = new JSlider(JSlider.HORIZONTAL, 1, 9, 5); exponent.addChangeListener(panel); exponent.setMajorTickSpacing(1); exponent.setPaintLabels(true); exponent.setBackground(Color.white); exponent.setBorder(BorderFactory.createEmptyBorder(20, 20, 20, 20)); Hashtable<Integer, JLabel> labelTable = new Hashtable<>(); for (int i = 1; i < 10; i++) labelTable.put(i, new JLabel(String.valueOf(i * 0.5))); exponent.setLabelTable(labelTable); f.add(exponent, BorderLayout.SOUTH); f.pack(); f.setLocationRelativeTo(null); f.setVisible(true); }); }}",
"e": 32625,
"s": 28789,
"text": null
},
{
"code": null,
"e": 32633,
"s": 32625,
"text": "Output:"
},
{
"code": null,
"e": 32650,
"s": 32633,
"text": "Reference Links:"
},
{
"code": null,
"e": 32712,
"s": 32650,
"text": "1. Wikipedia – Superellipse2. WolframMathWorld – Superellipse"
},
{
"code": null,
"e": 33013,
"s": 32712,
"text": "This article is contributed by Subhajit Saha. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks."
},
{
"code": null,
"e": 33138,
"s": 33013,
"text": "Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above."
},
{
"code": null,
"e": 33144,
"s": 33138,
"text": "GBlog"
},
{
"code": null,
"e": 33157,
"s": 33144,
"text": "Mathematical"
},
{
"code": null,
"e": 33176,
"s": 33157,
"text": "Technical Scripter"
},
{
"code": null,
"e": 33189,
"s": 33176,
"text": "Mathematical"
},
{
"code": null,
"e": 33287,
"s": 33189,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 33312,
"s": 33287,
"text": "DSA Sheet by Love Babbar"
},
{
"code": null,
"e": 33347,
"s": 33312,
"text": "GET and POST requests using Python"
},
{
"code": null,
"e": 33409,
"s": 33347,
"text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills"
},
{
"code": null,
"e": 33435,
"s": 33409,
"text": "Types of Software Testing"
},
{
"code": null,
"e": 33468,
"s": 33435,
"text": "Working with csv files in Python"
},
{
"code": null,
"e": 33498,
"s": 33468,
"text": "Program for Fibonacci numbers"
},
{
"code": null,
"e": 33558,
"s": 33498,
"text": "Write a program to print all permutations of a given string"
},
{
"code": null,
"e": 33573,
"s": 33558,
"text": "C++ Data Types"
},
{
"code": null,
"e": 33616,
"s": 33573,
"text": "Set in C++ Standard Template Library (STL)"
}
] |
Implementing Sparse Vector in Java - GeeksforGeeks
|
02 Dec, 2020
A vector or arraylist is a one-dimensional array of elements. The elements of a Sparse Vector have mostly zero values. It is inefficient to use a one-dimensional array to store a sparse vector. It is also inefficient to add elements whose values are zero in forming sums of sparse vectors. We convert the one-dimensional vector to a vector of (index, value) pairs.
Examples
Input:
Enter size of Sparse Vectors :
100
Enter number of entries for Vector A :
5
Enter 5 (int, double) pairs
2 20.0
5 12.2
19 23.1
4 66.0
11 100.0
Enter number of entries for vector B :
5
Enter 5 (int, double) pairs
9 21.0
10 44.5
6 13.22
71 30.0
63 99.0
Output:
Vector A = (2, 20.0) (4, 66.0) (5, 12.2) (11, 100.0) (19, 23.1)
Vector B = (6, 13.22) (9, 21.0) (10, 44.5) (63, 99.0) (71, 30.0)
A dot B = 0.0
A + B = (2, 20.0) (4, 66.0) (5, 12.2) (6, 13.22) (9, 21.0) (10, 44.5) (11, 100.0) (19, 23.1) (63, 99.0) (71, 30.0)
Approach
To store the Sparse Vector efficiently we only store the non-zero values of the vector along with the index. The First element of pair will be the index of sparse vector element(which is non-zero) and the second element will be the actual element.
We are using TreeMap as the vector for the index-value pairs. The advantage of using TreeMap is, the map is sorted according to the natural ordering of its keys. This proves to be an efficient way of sorting and storing the key-value pairs.
Implementation
Java
// importing generic packagesimport java.util.Scanner;import java.util.TreeMap;import java.util.Map; public class SparseVector { // TreeMap is used to maintain sorted order private TreeMap<Integer, Double> st; private int size; // Constructor public SparseVector(int size) { this.size = size; // assigning empty TreeMap st = new TreeMap<Integer, Double>(); } // Function to insert a (index, value) pair public void put(int i, double value) { // checking if index(i) is out of bounds if (i < 0 || i >= size) throw new RuntimeException( "\nError : Out of Bounds\n"); // if value is zero, don't add to that index & // remove any previously held value if (value == 0.0) st.remove(i); // if value is non-zero add index-value pair to // TreeMap else st.put(i, value); } // Function to get value for an index public double get(int i) { // checking if index(i) is out of bounds if (i < 0 || i >= size) throw new RuntimeException( "\nError : Out of Bounds\n"); // if index is valid, return value at index if (st.containsKey(i)) return st.get(i); // if index not found, it means the value is zero as // only non-zero entries are added to the Map else return 0.0; } // Function to get size of the vector public int size() { return size; } // Function to get dot product of two vectors public double dot(SparseVector b) { SparseVector a = this; // Dot product of Sparse Vectors whose lengths are // different is not possible if (a.size != b.size) throw new RuntimeException( "Error : Vector lengths are not same"); double sum = 0.0; // Traversing each sorted vector and getting // product of consequent entries of the vectors if (a.st.size() <= b.st.size()) { for (Map.Entry<Integer, Double> entry : a.st.entrySet()) if (b.st.containsKey(entry.getKey())) sum += a.get(entry.getKey()) * b.get(entry.getKey()); } // Traversing each sorted vector and getting // product of consequent entries of the vectors else { for (Map.Entry<Integer, Double> entry : b.st.entrySet()) if (a.st.containsKey(entry.getKey())) sum += a.get(entry.getKey()) * b.get(entry.getKey()); } return sum; } // Function to get sum of two vectors public SparseVector plus(SparseVector b) { SparseVector a = this; // Addition of Sparse Vectors whose lengths are // different is not possible if (a.size != b.size) throw new RuntimeException( "Error : Vector lengths are not same"); // creating new empty Sparse Vector object SparseVector c = new SparseVector(size); // Traversing and adding the two vectors a & b and // constructing resultant Sparse Vector c for (Map.Entry<Integer, Double> entry : a.st.entrySet()) c.put(entry.getKey(), a.get(entry.getKey())); for (Map.Entry<Integer, Double> entry : b.st.entrySet()) c.put(entry.getKey(), b.get(entry.getKey()) + c.get(entry.getKey())); return c; } // Function toString() for printing vector public String toString() { String s = ""; for (Map.Entry<Integer, Double> entry : st.entrySet()) s += "(" + entry.getKey() + ", " + st.get(entry.getKey()) + ") "; return s; } public static void main(String[] args) { Scanner scan = new Scanner(System.in); System.out.println( "Enter size of Sparse Vectors : "); // Size of the two Sparse Vector int n = scan.nextInt(); // sparse vector a and b SparseVector A = new SparseVector(n); SparseVector B = new SparseVector(n); // store key, value pairs System.out.println( "Enter number of entries for Vector A :"); int n1 = scan.nextInt(); System.out.println("Enter " + n1 + " (int, double) pairs :"); for (int i = 0; i < n1; i++) A.put(scan.nextInt(), scan.nextDouble()); System.out.println( "Enter number of entries for vector B :"); int n2 = scan.nextInt(); System.out.println("Enter " + n2 + " (int, double) pairs :"); for (int i = 0; i < n2; i++) B.put(scan.nextInt(), scan.nextDouble()); System.out.println("\nVector A = " + A); System.out.println("Vector B = " + B); System.out.println("\nA dot B = " + A.dot(B)); System.out.println("A + B = " + A.plus(B)); }}
Output
Picked
Java
Java Programs
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Stream In Java
Constructors in Java
Exceptions in Java
Functional Interfaces in Java
Different ways of Reading a text file in Java
Java Programming Examples
Convert Double to Integer in Java
Implementing a Linked List in Java using Class
How to Iterate HashMap in Java?
Program to print ASCII Value of a character
|
[
{
"code": null,
"e": 25249,
"s": 25221,
"text": "\n02 Dec, 2020"
},
{
"code": null,
"e": 25614,
"s": 25249,
"text": "A vector or arraylist is a one-dimensional array of elements. The elements of a Sparse Vector have mostly zero values. It is inefficient to use a one-dimensional array to store a sparse vector. It is also inefficient to add elements whose values are zero in forming sums of sparse vectors. We convert the one-dimensional vector to a vector of (index, value) pairs."
},
{
"code": null,
"e": 25623,
"s": 25614,
"text": "Examples"
},
{
"code": null,
"e": 26153,
"s": 25623,
"text": "Input: \nEnter size of Sparse Vectors : \n100\nEnter number of entries for Vector A :\n5\nEnter 5 (int, double) pairs\n2 20.0\n5 12.2\n19 23.1\n4 66.0\n11 100.0\nEnter number of entries for vector B :\n5\nEnter 5 (int, double) pairs\n9 21.0\n10 44.5\n6 13.22\n71 30.0\n63 99.0\n\nOutput:\nVector A = (2, 20.0) (4, 66.0) (5, 12.2) (11, 100.0) (19, 23.1)\nVector B = (6, 13.22) (9, 21.0) (10, 44.5) (63, 99.0) (71, 30.0)\nA dot B = 0.0\nA + B = (2, 20.0) (4, 66.0) (5, 12.2) (6, 13.22) (9, 21.0) (10, 44.5) (11, 100.0) (19, 23.1) (63, 99.0) (71, 30.0)"
},
{
"code": null,
"e": 26162,
"s": 26153,
"text": "Approach"
},
{
"code": null,
"e": 26410,
"s": 26162,
"text": "To store the Sparse Vector efficiently we only store the non-zero values of the vector along with the index. The First element of pair will be the index of sparse vector element(which is non-zero) and the second element will be the actual element."
},
{
"code": null,
"e": 26652,
"s": 26410,
"text": "We are using TreeMap as the vector for the index-value pairs. The advantage of using TreeMap is, the map is sorted according to the natural ordering of its keys. This proves to be an efficient way of sorting and storing the key-value pairs. "
},
{
"code": null,
"e": 26667,
"s": 26652,
"text": "Implementation"
},
{
"code": null,
"e": 26672,
"s": 26667,
"text": "Java"
},
{
"code": "// importing generic packagesimport java.util.Scanner;import java.util.TreeMap;import java.util.Map; public class SparseVector { // TreeMap is used to maintain sorted order private TreeMap<Integer, Double> st; private int size; // Constructor public SparseVector(int size) { this.size = size; // assigning empty TreeMap st = new TreeMap<Integer, Double>(); } // Function to insert a (index, value) pair public void put(int i, double value) { // checking if index(i) is out of bounds if (i < 0 || i >= size) throw new RuntimeException( \"\\nError : Out of Bounds\\n\"); // if value is zero, don't add to that index & // remove any previously held value if (value == 0.0) st.remove(i); // if value is non-zero add index-value pair to // TreeMap else st.put(i, value); } // Function to get value for an index public double get(int i) { // checking if index(i) is out of bounds if (i < 0 || i >= size) throw new RuntimeException( \"\\nError : Out of Bounds\\n\"); // if index is valid, return value at index if (st.containsKey(i)) return st.get(i); // if index not found, it means the value is zero as // only non-zero entries are added to the Map else return 0.0; } // Function to get size of the vector public int size() { return size; } // Function to get dot product of two vectors public double dot(SparseVector b) { SparseVector a = this; // Dot product of Sparse Vectors whose lengths are // different is not possible if (a.size != b.size) throw new RuntimeException( \"Error : Vector lengths are not same\"); double sum = 0.0; // Traversing each sorted vector and getting // product of consequent entries of the vectors if (a.st.size() <= b.st.size()) { for (Map.Entry<Integer, Double> entry : a.st.entrySet()) if (b.st.containsKey(entry.getKey())) sum += a.get(entry.getKey()) * b.get(entry.getKey()); } // Traversing each sorted vector and getting // product of consequent entries of the vectors else { for (Map.Entry<Integer, Double> entry : b.st.entrySet()) if (a.st.containsKey(entry.getKey())) sum += a.get(entry.getKey()) * b.get(entry.getKey()); } return sum; } // Function to get sum of two vectors public SparseVector plus(SparseVector b) { SparseVector a = this; // Addition of Sparse Vectors whose lengths are // different is not possible if (a.size != b.size) throw new RuntimeException( \"Error : Vector lengths are not same\"); // creating new empty Sparse Vector object SparseVector c = new SparseVector(size); // Traversing and adding the two vectors a & b and // constructing resultant Sparse Vector c for (Map.Entry<Integer, Double> entry : a.st.entrySet()) c.put(entry.getKey(), a.get(entry.getKey())); for (Map.Entry<Integer, Double> entry : b.st.entrySet()) c.put(entry.getKey(), b.get(entry.getKey()) + c.get(entry.getKey())); return c; } // Function toString() for printing vector public String toString() { String s = \"\"; for (Map.Entry<Integer, Double> entry : st.entrySet()) s += \"(\" + entry.getKey() + \", \" + st.get(entry.getKey()) + \") \"; return s; } public static void main(String[] args) { Scanner scan = new Scanner(System.in); System.out.println( \"Enter size of Sparse Vectors : \"); // Size of the two Sparse Vector int n = scan.nextInt(); // sparse vector a and b SparseVector A = new SparseVector(n); SparseVector B = new SparseVector(n); // store key, value pairs System.out.println( \"Enter number of entries for Vector A :\"); int n1 = scan.nextInt(); System.out.println(\"Enter \" + n1 + \" (int, double) pairs :\"); for (int i = 0; i < n1; i++) A.put(scan.nextInt(), scan.nextDouble()); System.out.println( \"Enter number of entries for vector B :\"); int n2 = scan.nextInt(); System.out.println(\"Enter \" + n2 + \" (int, double) pairs :\"); for (int i = 0; i < n2; i++) B.put(scan.nextInt(), scan.nextDouble()); System.out.println(\"\\nVector A = \" + A); System.out.println(\"Vector B = \" + B); System.out.println(\"\\nA dot B = \" + A.dot(B)); System.out.println(\"A + B = \" + A.plus(B)); }}",
"e": 31755,
"s": 26672,
"text": null
},
{
"code": null,
"e": 31762,
"s": 31755,
"text": "Output"
},
{
"code": null,
"e": 31769,
"s": 31762,
"text": "Picked"
},
{
"code": null,
"e": 31774,
"s": 31769,
"text": "Java"
},
{
"code": null,
"e": 31788,
"s": 31774,
"text": "Java Programs"
},
{
"code": null,
"e": 31793,
"s": 31788,
"text": "Java"
},
{
"code": null,
"e": 31891,
"s": 31793,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 31906,
"s": 31891,
"text": "Stream In Java"
},
{
"code": null,
"e": 31927,
"s": 31906,
"text": "Constructors in Java"
},
{
"code": null,
"e": 31946,
"s": 31927,
"text": "Exceptions in Java"
},
{
"code": null,
"e": 31976,
"s": 31946,
"text": "Functional Interfaces in Java"
},
{
"code": null,
"e": 32022,
"s": 31976,
"text": "Different ways of Reading a text file in Java"
},
{
"code": null,
"e": 32048,
"s": 32022,
"text": "Java Programming Examples"
},
{
"code": null,
"e": 32082,
"s": 32048,
"text": "Convert Double to Integer in Java"
},
{
"code": null,
"e": 32129,
"s": 32082,
"text": "Implementing a Linked List in Java using Class"
},
{
"code": null,
"e": 32161,
"s": 32129,
"text": "How to Iterate HashMap in Java?"
}
] |
PHP | ArrayObject count() Function - GeeksforGeeks
|
27 Sep, 2019
The ArrayObject::count() function is an inbuilt function in PHP which is used to get the number of public properties in the ArrayObject.
Syntax:
int ArrayObject::count( void )
Parameters: This function does not accept any parameters.
Return Value: This function returns the number of public properties in the ArrayObject.
Below programs illustrate the ArrayObject::count() function in PHP:
Program 1:
<?php // PHP program to illustrate the // ArrayObject::count() function // Declare an array and convert it// into array object$arrObject = new ArrayObject( array('Geeks', 'for', 'Geeks')); // Use ArrayObject::count() function// to count the number of public// properties in the ArrayObject$count = $arrObject->count(); print_r($count); ?>
3
Program 2:
<?php // PHP program to illustrate the // ArrayObject::count() function // Declare an associative array$arr = array( "a" => "Welcome", "b" => "to", "c" => "GeeksforGeeks"); // Create into array object $arrObject = new ArrayObject($arr); // Use ArrayObject::count() function// to count the number of public// properties in the ArrayObject$count = $arrObject->count(); print_r($count); ?>
3
Reference: https://www.php.net/manual/en/arrayobject.count.php
PHP-ArrayObject
PHP-function
PHP
Web Technologies
PHP
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to fetch data from localserver database and display on HTML table using PHP ?
How to create admin login page using PHP?
PHP str_replace() Function
How to pass form variables from one page to other page in PHP ?
Create a drop-down list that options fetched from a MySQL database in PHP
Remove elements from a JavaScript Array
Installation of Node.js on Linux
Convert a string to an integer in JavaScript
How to fetch data from an API in ReactJS ?
Top 10 Projects For Beginners To Practice HTML and CSS Skills
|
[
{
"code": null,
"e": 26217,
"s": 26189,
"text": "\n27 Sep, 2019"
},
{
"code": null,
"e": 26354,
"s": 26217,
"text": "The ArrayObject::count() function is an inbuilt function in PHP which is used to get the number of public properties in the ArrayObject."
},
{
"code": null,
"e": 26362,
"s": 26354,
"text": "Syntax:"
},
{
"code": null,
"e": 26393,
"s": 26362,
"text": "int ArrayObject::count( void )"
},
{
"code": null,
"e": 26451,
"s": 26393,
"text": "Parameters: This function does not accept any parameters."
},
{
"code": null,
"e": 26539,
"s": 26451,
"text": "Return Value: This function returns the number of public properties in the ArrayObject."
},
{
"code": null,
"e": 26607,
"s": 26539,
"text": "Below programs illustrate the ArrayObject::count() function in PHP:"
},
{
"code": null,
"e": 26618,
"s": 26607,
"text": "Program 1:"
},
{
"code": "<?php // PHP program to illustrate the // ArrayObject::count() function // Declare an array and convert it// into array object$arrObject = new ArrayObject( array('Geeks', 'for', 'Geeks')); // Use ArrayObject::count() function// to count the number of public// properties in the ArrayObject$count = $arrObject->count(); print_r($count); ?> ",
"e": 26969,
"s": 26618,
"text": null
},
{
"code": null,
"e": 26972,
"s": 26969,
"text": "3\n"
},
{
"code": null,
"e": 26983,
"s": 26972,
"text": "Program 2:"
},
{
"code": "<?php // PHP program to illustrate the // ArrayObject::count() function // Declare an associative array$arr = array( \"a\" => \"Welcome\", \"b\" => \"to\", \"c\" => \"GeeksforGeeks\"); // Create into array object $arrObject = new ArrayObject($arr); // Use ArrayObject::count() function// to count the number of public// properties in the ArrayObject$count = $arrObject->count(); print_r($count); ?> ",
"e": 27391,
"s": 26983,
"text": null
},
{
"code": null,
"e": 27394,
"s": 27391,
"text": "3\n"
},
{
"code": null,
"e": 27457,
"s": 27394,
"text": "Reference: https://www.php.net/manual/en/arrayobject.count.php"
},
{
"code": null,
"e": 27473,
"s": 27457,
"text": "PHP-ArrayObject"
},
{
"code": null,
"e": 27486,
"s": 27473,
"text": "PHP-function"
},
{
"code": null,
"e": 27490,
"s": 27486,
"text": "PHP"
},
{
"code": null,
"e": 27507,
"s": 27490,
"text": "Web Technologies"
},
{
"code": null,
"e": 27511,
"s": 27507,
"text": "PHP"
},
{
"code": null,
"e": 27609,
"s": 27511,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 27691,
"s": 27609,
"text": "How to fetch data from localserver database and display on HTML table using PHP ?"
},
{
"code": null,
"e": 27733,
"s": 27691,
"text": "How to create admin login page using PHP?"
},
{
"code": null,
"e": 27760,
"s": 27733,
"text": "PHP str_replace() Function"
},
{
"code": null,
"e": 27824,
"s": 27760,
"text": "How to pass form variables from one page to other page in PHP ?"
},
{
"code": null,
"e": 27898,
"s": 27824,
"text": "Create a drop-down list that options fetched from a MySQL database in PHP"
},
{
"code": null,
"e": 27938,
"s": 27898,
"text": "Remove elements from a JavaScript Array"
},
{
"code": null,
"e": 27971,
"s": 27938,
"text": "Installation of Node.js on Linux"
},
{
"code": null,
"e": 28016,
"s": 27971,
"text": "Convert a string to an integer in JavaScript"
},
{
"code": null,
"e": 28059,
"s": 28016,
"text": "How to fetch data from an API in ReactJS ?"
}
] |
Root-Mean-Square Error in R Programming - GeeksforGeeks
|
22 Jul, 2020
Root mean squared error (RMSE) is the square root of the mean of the square of all of the error. RMSE is considered an excellent general-purpose error metric for numerical predictions. RMSE is a good measure of accuracy, but only to compare prediction errors of different models or model configurations for a particular variable and not between variables, as it is scale-dependent. It is the measure of how well a regression line fits the data points. The formula for calculating RMSE is:
where,predictedi = The predicted value for the ith observation.actuali = The observed(actual) value for the ith observationN = Total number of observations.
Note: The difference between the actual values and the predicted values is known as residuals.
The rmse() function available in Metrics package in R is used to calculate root mean square error between actual values and predicted values.
Syntax:rmse(actual, predicted)
Parameters:actual: The ground truth numeric vector.predicted: The predicted numeric vector, where each element in the vector is a prediction for the corresponding element in actual.
Example 1:Let’s define two vectors actual vector with ground truth numeric values and predicted vector with predicted numeric values where each element in the vector is a prediction for the corresponding element in actual.
# R program to illustrate RMSE # Importing the required packagelibrary(Metrics) # Taking two vectorsactual = c(1.5, 1.0, 2.0, 7.4, 5.8, 6.6) predicted = c(1.0, 1.1, 2.5, 7.3, 6.0, 6.2) # Calculating RMSE using rmse() result = rmse(actual, predicted) # Printing the valueprint(result)
Output:
[1] 0.3464102
Example 2:In this example let’s take the trees data in the datasets library which represents the data from a study conducted on black cherry trees.
# Importing required packageslibrary(datasets)library(tidyr)library(dplyr) # Access the data from R’s datasets packagedata(trees) # Display the data in the trees dataset trees
Output:
Girth Height Volume
1 8.3 70 10.3
2 8.6 65 10.3
3 8.8 63 10.2
4 10.5 72 16.4
5 10.7 81 18.8
6 10.8 83 19.7
7 11.0 66 15.6
8 11.0 75 18.2
9 11.1 80 22.6
10 11.2 75 19.9
11 11.3 79 24.2
12 11.4 76 21.0
13 11.4 76 21.4
14 11.7 69 21.3
15 12.0 75 19.1
16 12.9 74 22.2
17 12.9 85 33.8
18 13.3 86 27.4
19 13.7 71 25.7
20 13.8 64 24.9
21 14.0 78 34.5
22 14.2 80 31.7
23 14.5 74 36.3
24 16.0 72 38.3
25 16.3 77 42.6
26 17.3 81 55.4
27 17.5 82 55.7
28 17.9 80 58.3
29 18.0 80 51.5
30 18.0 80 51.0
31 20.6 87 77.0
# Look at the structure# Of the variablesstr(trees)
Output:
'data.frame': 31 obs. of 3 variables:
$ Girth : num 8.3 8.6 8.8 10.5 10.7 10.8 11 11 11.1 11.2 ...
$ Height: num 70 65 63 72 81 83 66 75 80 75 ...
$ Volume: num 10.3 10.3 10.2 16.4 18.8 19.7 15.6 18.2 22.6 19.9 ...
This data set consists of 31 observations of 3 numeric variables describing black cherry trees with trunk girth, height and volume as variables.Now, try to fit a linear regression model to predict Volume of the trunks on the basis of given trunk girth. The Simple Liner Regression Model in R will help in this case. Let’s dive right in and build a linear model relating tree volume to girth. R makes this straightforward with the base function lm(). How well will the model do at predicting that tree’s volume from its girth? Use the predict() function, a generic R function for making predictions of model-fitting functions. predict() takes as arguments, the linear regression model and the values of the predictor variable that we want response variable values for.
# Building a linear model # Relating tree volume to girthfit_1 <- lm(Volume ~ Girth, data = trees) trees.Girth = trees %>% select(Girth) # Use predict function to predict volumedata.predicted = c(predict(fit_1, data.frame(Girth = trees.Girth))) data.predicted
Output:
1 2 3 4 5 6 7 8 9
5.103149 6.622906 7.636077 16.248033 17.261205 17.767790 18.780962 18.780962 19.287547
10 11 12 13 14 15 16 17 18
19.794133 20.300718 20.807304 20.807304 22.327061 23.846818 28.406089 28.406089 30.432431
19 20 21 22 23 24 25 26 27
32.458774 32.965360 33.978531 34.991702 36.511459 44.110244 45.630001 50.695857 51.709028
28 29 30 31
53.735371 54.241956 54.241956 67.413183
Now we have the actual volume of cherry tree trunks and the predicted one as driven by the linear regression models. Finally use rmse() function to get the relative error between the actual and the predicted values.
# Load the Metrics package library(Metrics) # Applying rmse() function rmse(trees$Volume, predict(fit_1, data.frame(Girth = trees.Girth)))
Output:
[1] 4.11254
As the error value is 4.11254 which is a good score for a linear model. But it can be reduced further by adding more predictors(Multiple Regression Model). So, in summary, it can be said that it is very easy to find the root mean square error using R. One can perform this task using rmse() function in R.
Picked
R Machine-Learning
R Language
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Change Color of Bars in Barchart using ggplot2 in R
Group by function in R using Dplyr
How to Change Axis Scales in R Plots?
How to Split Column Into Multiple Columns in R DataFrame?
Replace Specific Characters in String in R
How to filter R DataFrame by values in a column?
How to import an Excel File into R ?
R - if statement
Time Series Analysis in R
How to filter R dataframe by multiple conditions?
|
[
{
"code": null,
"e": 26407,
"s": 26379,
"text": "\n22 Jul, 2020"
},
{
"code": null,
"e": 26896,
"s": 26407,
"text": "Root mean squared error (RMSE) is the square root of the mean of the square of all of the error. RMSE is considered an excellent general-purpose error metric for numerical predictions. RMSE is a good measure of accuracy, but only to compare prediction errors of different models or model configurations for a particular variable and not between variables, as it is scale-dependent. It is the measure of how well a regression line fits the data points. The formula for calculating RMSE is:"
},
{
"code": null,
"e": 27053,
"s": 26896,
"text": "where,predictedi = The predicted value for the ith observation.actuali = The observed(actual) value for the ith observationN = Total number of observations."
},
{
"code": null,
"e": 27148,
"s": 27053,
"text": "Note: The difference between the actual values and the predicted values is known as residuals."
},
{
"code": null,
"e": 27290,
"s": 27148,
"text": "The rmse() function available in Metrics package in R is used to calculate root mean square error between actual values and predicted values."
},
{
"code": null,
"e": 27321,
"s": 27290,
"text": "Syntax:rmse(actual, predicted)"
},
{
"code": null,
"e": 27503,
"s": 27321,
"text": "Parameters:actual: The ground truth numeric vector.predicted: The predicted numeric vector, where each element in the vector is a prediction for the corresponding element in actual."
},
{
"code": null,
"e": 27726,
"s": 27503,
"text": "Example 1:Let’s define two vectors actual vector with ground truth numeric values and predicted vector with predicted numeric values where each element in the vector is a prediction for the corresponding element in actual."
},
{
"code": "# R program to illustrate RMSE # Importing the required packagelibrary(Metrics) # Taking two vectorsactual = c(1.5, 1.0, 2.0, 7.4, 5.8, 6.6) predicted = c(1.0, 1.1, 2.5, 7.3, 6.0, 6.2) # Calculating RMSE using rmse() result = rmse(actual, predicted) # Printing the valueprint(result) ",
"e": 28043,
"s": 27726,
"text": null
},
{
"code": null,
"e": 28051,
"s": 28043,
"text": "Output:"
},
{
"code": null,
"e": 28066,
"s": 28051,
"text": "[1] 0.3464102\n"
},
{
"code": null,
"e": 28214,
"s": 28066,
"text": "Example 2:In this example let’s take the trees data in the datasets library which represents the data from a study conducted on black cherry trees."
},
{
"code": "# Importing required packageslibrary(datasets)library(tidyr)library(dplyr) # Access the data from R’s datasets packagedata(trees) # Display the data in the trees dataset trees ",
"e": 28406,
"s": 28214,
"text": null
},
{
"code": null,
"e": 28414,
"s": 28406,
"text": "Output:"
},
{
"code": null,
"e": 29152,
"s": 28414,
"text": " Girth Height Volume\n1 8.3 70 10.3\n2 8.6 65 10.3\n3 8.8 63 10.2\n4 10.5 72 16.4\n5 10.7 81 18.8\n6 10.8 83 19.7\n7 11.0 66 15.6\n8 11.0 75 18.2\n9 11.1 80 22.6\n10 11.2 75 19.9\n11 11.3 79 24.2\n12 11.4 76 21.0\n13 11.4 76 21.4\n14 11.7 69 21.3\n15 12.0 75 19.1\n16 12.9 74 22.2\n17 12.9 85 33.8\n18 13.3 86 27.4\n19 13.7 71 25.7\n20 13.8 64 24.9\n21 14.0 78 34.5\n22 14.2 80 31.7\n23 14.5 74 36.3\n24 16.0 72 38.3\n25 16.3 77 42.6\n26 17.3 81 55.4\n27 17.5 82 55.7\n28 17.9 80 58.3\n29 18.0 80 51.5\n30 18.0 80 51.0\n31 20.6 87 77.0\n"
},
{
"code": "# Look at the structure# Of the variablesstr(trees) ",
"e": 29209,
"s": 29152,
"text": null
},
{
"code": null,
"e": 29217,
"s": 29209,
"text": "Output:"
},
{
"code": null,
"e": 29442,
"s": 29217,
"text": "'data.frame': 31 obs. of 3 variables:\n $ Girth : num 8.3 8.6 8.8 10.5 10.7 10.8 11 11 11.1 11.2 ...\n $ Height: num 70 65 63 72 81 83 66 75 80 75 ...\n $ Volume: num 10.3 10.3 10.2 16.4 18.8 19.7 15.6 18.2 22.6 19.9 ...\n"
},
{
"code": null,
"e": 30210,
"s": 29442,
"text": "This data set consists of 31 observations of 3 numeric variables describing black cherry trees with trunk girth, height and volume as variables.Now, try to fit a linear regression model to predict Volume of the trunks on the basis of given trunk girth. The Simple Liner Regression Model in R will help in this case. Let’s dive right in and build a linear model relating tree volume to girth. R makes this straightforward with the base function lm(). How well will the model do at predicting that tree’s volume from its girth? Use the predict() function, a generic R function for making predictions of model-fitting functions. predict() takes as arguments, the linear regression model and the values of the predictor variable that we want response variable values for."
},
{
"code": "# Building a linear model # Relating tree volume to girthfit_1 <- lm(Volume ~ Girth, data = trees) trees.Girth = trees %>% select(Girth) # Use predict function to predict volumedata.predicted = c(predict(fit_1, data.frame(Girth = trees.Girth))) data.predicted",
"e": 30502,
"s": 30210,
"text": null
},
{
"code": null,
"e": 30510,
"s": 30502,
"text": "Output:"
},
{
"code": null,
"e": 31139,
"s": 30510,
"text": " 1 2 3 4 5 6 7 8 9 \n 5.103149 6.622906 7.636077 16.248033 17.261205 17.767790 18.780962 18.780962 19.287547 \n 10 11 12 13 14 15 16 17 18 \n19.794133 20.300718 20.807304 20.807304 22.327061 23.846818 28.406089 28.406089 30.432431 \n 19 20 21 22 23 24 25 26 27 \n32.458774 32.965360 33.978531 34.991702 36.511459 44.110244 45.630001 50.695857 51.709028 \n 28 29 30 31 \n53.735371 54.241956 54.241956 67.413183 \n"
},
{
"code": null,
"e": 31355,
"s": 31139,
"text": "Now we have the actual volume of cherry tree trunks and the predicted one as driven by the linear regression models. Finally use rmse() function to get the relative error between the actual and the predicted values."
},
{
"code": "# Load the Metrics package library(Metrics) # Applying rmse() function rmse(trees$Volume, predict(fit_1, data.frame(Girth = trees.Girth)))",
"e": 31495,
"s": 31355,
"text": null
},
{
"code": null,
"e": 31503,
"s": 31495,
"text": "Output:"
},
{
"code": null,
"e": 31516,
"s": 31503,
"text": "[1] 4.11254\n"
},
{
"code": null,
"e": 31822,
"s": 31516,
"text": "As the error value is 4.11254 which is a good score for a linear model. But it can be reduced further by adding more predictors(Multiple Regression Model). So, in summary, it can be said that it is very easy to find the root mean square error using R. One can perform this task using rmse() function in R."
},
{
"code": null,
"e": 31829,
"s": 31822,
"text": "Picked"
},
{
"code": null,
"e": 31848,
"s": 31829,
"text": "R Machine-Learning"
},
{
"code": null,
"e": 31859,
"s": 31848,
"text": "R Language"
},
{
"code": null,
"e": 31957,
"s": 31859,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 32009,
"s": 31957,
"text": "Change Color of Bars in Barchart using ggplot2 in R"
},
{
"code": null,
"e": 32044,
"s": 32009,
"text": "Group by function in R using Dplyr"
},
{
"code": null,
"e": 32082,
"s": 32044,
"text": "How to Change Axis Scales in R Plots?"
},
{
"code": null,
"e": 32140,
"s": 32082,
"text": "How to Split Column Into Multiple Columns in R DataFrame?"
},
{
"code": null,
"e": 32183,
"s": 32140,
"text": "Replace Specific Characters in String in R"
},
{
"code": null,
"e": 32232,
"s": 32183,
"text": "How to filter R DataFrame by values in a column?"
},
{
"code": null,
"e": 32269,
"s": 32232,
"text": "How to import an Excel File into R ?"
},
{
"code": null,
"e": 32286,
"s": 32269,
"text": "R - if statement"
},
{
"code": null,
"e": 32312,
"s": 32286,
"text": "Time Series Analysis in R"
}
] |
Product of 2 Numbers using Recursion - GeeksforGeeks
|
07 Apr, 2021
Given two number x and y find product using recursion.Examples :
Input : x = 5, y = 2
Output : 10
Input : x = 100, y = 5
Output : 500
Method 1) If x is less than y, swap the two variables value 2) Recursively find y times the sum of x 3) If any of them become zero, return 0
C++
Java
Python3
C#
PHP
Javascript
// C++ Program to find Product// of 2 Numbers using Recursion#include <bits/stdc++.h>using namespace std; // recursive function to calculate// multiplication of two numbersint product(int x, int y){ // if x is less than // y swap the numbers if (x < y) return product(y, x); // iteratively calculate // y times sum of x else if (y != 0) return (x + product(x, y - 1)); // if any of the two numbers is // zero return zero else return 0;} // Driver Codeint main(){ int x = 5, y = 2; cout << product(x, y); return 0;}
// Java Program to find Product// of 2 Numbers using Recursionimport java.io.*;import java.util.*; class GFG{ // recursive function to calculate // multiplication of two numbers static int product(int x, int y) { // if x is less than // y swap the numbers if (x < y) return product(y, x); // iteratively calculate // y times sum of x else if (y != 0) return (x + product(x, y - 1)); // if any of the two numbers is // zero return zero else return 0; } // Driver Code public static void main (String[] args) { int x = 5, y = 2; System.out.println(product(x, y)); }} // This code is contributed by Gitanjali.
# Python3 to find Product of# 2 Numbers using Recursion # recursive function to calculate# multiplication of two numbersdef product( x , y ): # if x is less than y swap # the numbers if x < y: return product(y, x) # iteratively calculate y # times sum of x elif y != 0: return (x + product(x, y - 1)) # if any of the two numbers is # zero return zero else: return 0 # Driver codex = 5y = 2print( product(x, y)) # This code is contributed# by Abhishek Sharma44.
// C# Program to find Product// of 2 Numbers using Recursionusing System; class GFG{ // recursive function to calculate // multiplication of two numbers static int product(int x, int y) { // if x is less than // y swap the numbers if (x < y) return product(y, x); // iteratively calculate // y times sum of x else if (y != 0) return (x + product(x, y - 1)); // if any of the two numbers is // zero return zero else return 0; } // Driver code public static void Main () { int x = 5, y = 2; Console.WriteLine(product(x, y)); }} // This code is contributed by vt_m.
<?php// PHP Program to find Product// of 2 Numbers using Recursion // recursive function to calculate// multiplication of two numbersfunction product($x, $y){ // if x is less than // y swap thenumbers if ($x < $y) return product($y, $x); // iteratively calculate // y times sum of x else if ($y != 0) return ($x + product($x, $y - 1)); // if any of the two numbers is // zero return zero else return 0;} // Driver Code$x = 5; $y = 2;echo(product($x, $y)); // This code is contributed by Ajit.?>
<script>// JavaScript program to find Product// of 2 Numbers using Recursion // recursive function to calculate// multiplication of two numbersfunction product(x, y){ // if x is less than // y swap thenumbers if (x < y) return product(y, x); // iteratively calculate // y times sum of x else if (y != 0) return (x + product(x, y - 1)); // if any of the two numbers is // zero return zero else return 0;} // Driver Codelet x = 5;let y = 2;document.write(product(x, y)); // This code is contributed by mohan. </script>
Output :
10
jit_t
pulamolusaimohan
Recursion
School Programming
Recursion
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Backtracking | Introduction
Print all possible combinations of r elements in a given array of size n
Recursive Practice Problems with Solutions
Write a program to reverse digits of a number
Print all subsequences of a string
Python Dictionary
Arrays in C/C++
Inheritance in C++
Reverse a string in Java
C++ Classes and Objects
|
[
{
"code": null,
"e": 26361,
"s": 26333,
"text": "\n07 Apr, 2021"
},
{
"code": null,
"e": 26428,
"s": 26361,
"text": "Given two number x and y find product using recursion.Examples : "
},
{
"code": null,
"e": 26498,
"s": 26428,
"text": "Input : x = 5, y = 2\nOutput : 10\n\nInput : x = 100, y = 5\nOutput : 500"
},
{
"code": null,
"e": 26643,
"s": 26500,
"text": "Method 1) If x is less than y, swap the two variables value 2) Recursively find y times the sum of x 3) If any of them become zero, return 0 "
},
{
"code": null,
"e": 26647,
"s": 26643,
"text": "C++"
},
{
"code": null,
"e": 26652,
"s": 26647,
"text": "Java"
},
{
"code": null,
"e": 26660,
"s": 26652,
"text": "Python3"
},
{
"code": null,
"e": 26663,
"s": 26660,
"text": "C#"
},
{
"code": null,
"e": 26667,
"s": 26663,
"text": "PHP"
},
{
"code": null,
"e": 26678,
"s": 26667,
"text": "Javascript"
},
{
"code": "// C++ Program to find Product// of 2 Numbers using Recursion#include <bits/stdc++.h>using namespace std; // recursive function to calculate// multiplication of two numbersint product(int x, int y){ // if x is less than // y swap the numbers if (x < y) return product(y, x); // iteratively calculate // y times sum of x else if (y != 0) return (x + product(x, y - 1)); // if any of the two numbers is // zero return zero else return 0;} // Driver Codeint main(){ int x = 5, y = 2; cout << product(x, y); return 0;}",
"e": 27252,
"s": 26678,
"text": null
},
{
"code": "// Java Program to find Product// of 2 Numbers using Recursionimport java.io.*;import java.util.*; class GFG{ // recursive function to calculate // multiplication of two numbers static int product(int x, int y) { // if x is less than // y swap the numbers if (x < y) return product(y, x); // iteratively calculate // y times sum of x else if (y != 0) return (x + product(x, y - 1)); // if any of the two numbers is // zero return zero else return 0; } // Driver Code public static void main (String[] args) { int x = 5, y = 2; System.out.println(product(x, y)); }} // This code is contributed by Gitanjali.",
"e": 28016,
"s": 27252,
"text": null
},
{
"code": "# Python3 to find Product of# 2 Numbers using Recursion # recursive function to calculate# multiplication of two numbersdef product( x , y ): # if x is less than y swap # the numbers if x < y: return product(y, x) # iteratively calculate y # times sum of x elif y != 0: return (x + product(x, y - 1)) # if any of the two numbers is # zero return zero else: return 0 # Driver codex = 5y = 2print( product(x, y)) # This code is contributed# by Abhishek Sharma44.",
"e": 28535,
"s": 28016,
"text": null
},
{
"code": "// C# Program to find Product// of 2 Numbers using Recursionusing System; class GFG{ // recursive function to calculate // multiplication of two numbers static int product(int x, int y) { // if x is less than // y swap the numbers if (x < y) return product(y, x); // iteratively calculate // y times sum of x else if (y != 0) return (x + product(x, y - 1)); // if any of the two numbers is // zero return zero else return 0; } // Driver code public static void Main () { int x = 5, y = 2; Console.WriteLine(product(x, y)); }} // This code is contributed by vt_m.",
"e": 29255,
"s": 28535,
"text": null
},
{
"code": "<?php// PHP Program to find Product// of 2 Numbers using Recursion // recursive function to calculate// multiplication of two numbersfunction product($x, $y){ // if x is less than // y swap thenumbers if ($x < $y) return product($y, $x); // iteratively calculate // y times sum of x else if ($y != 0) return ($x + product($x, $y - 1)); // if any of the two numbers is // zero return zero else return 0;} // Driver Code$x = 5; $y = 2;echo(product($x, $y)); // This code is contributed by Ajit.?>",
"e": 29801,
"s": 29255,
"text": null
},
{
"code": "<script>// JavaScript program to find Product// of 2 Numbers using Recursion // recursive function to calculate// multiplication of two numbersfunction product(x, y){ // if x is less than // y swap thenumbers if (x < y) return product(y, x); // iteratively calculate // y times sum of x else if (y != 0) return (x + product(x, y - 1)); // if any of the two numbers is // zero return zero else return 0;} // Driver Codelet x = 5;let y = 2;document.write(product(x, y)); // This code is contributed by mohan. </script>",
"e": 30369,
"s": 29801,
"text": null
},
{
"code": null,
"e": 30379,
"s": 30369,
"text": "Output : "
},
{
"code": null,
"e": 30382,
"s": 30379,
"text": "10"
},
{
"code": null,
"e": 30390,
"s": 30384,
"text": "jit_t"
},
{
"code": null,
"e": 30407,
"s": 30390,
"text": "pulamolusaimohan"
},
{
"code": null,
"e": 30417,
"s": 30407,
"text": "Recursion"
},
{
"code": null,
"e": 30436,
"s": 30417,
"text": "School Programming"
},
{
"code": null,
"e": 30446,
"s": 30436,
"text": "Recursion"
},
{
"code": null,
"e": 30544,
"s": 30446,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 30572,
"s": 30544,
"text": "Backtracking | Introduction"
},
{
"code": null,
"e": 30645,
"s": 30572,
"text": "Print all possible combinations of r elements in a given array of size n"
},
{
"code": null,
"e": 30688,
"s": 30645,
"text": "Recursive Practice Problems with Solutions"
},
{
"code": null,
"e": 30734,
"s": 30688,
"text": "Write a program to reverse digits of a number"
},
{
"code": null,
"e": 30769,
"s": 30734,
"text": "Print all subsequences of a string"
},
{
"code": null,
"e": 30787,
"s": 30769,
"text": "Python Dictionary"
},
{
"code": null,
"e": 30803,
"s": 30787,
"text": "Arrays in C/C++"
},
{
"code": null,
"e": 30822,
"s": 30803,
"text": "Inheritance in C++"
},
{
"code": null,
"e": 30847,
"s": 30822,
"text": "Reverse a string in Java"
}
] |
Plot Multiple lines in Matplotlib - GeeksforGeeks
|
25 Nov, 2020
In this article, we will learn how to plot multiple lines using matplotlib in Python. Let’s discuss some concepts:
Matplotlib: Matplotlib is an amazing visualization library in Python for 2D plots of arrays. Matplotlib is a multi-platform data visualization library built on NumPy arrays and designed to work with the broader SciPy stack. It was introduced by John Hunter in the year 2002.
Line plot: Line plots can be created in Python with Matplotlib’s pyplot library. To build a line plot, first import Matplotlib. It is a standard convention to import Matplotlib’s pyplot library as plt. The plt alias will be familiar to other Python programmers.
Here we will discuss some examples to draw a line or multiple lines with different features. To do such work we must follow the steps given below:
Import libraries.
Create Data.
Plot the lines over data.
In this example, we will learn how to draw a horizontal line with the help of matplotlib. Here we will use two lists as data for two dimensions (x and y) and at last plot the line. For making a horizontal line we have to change the value of the x-axis continuously by taking the y-axis as constant.
Python3
# importing packageimport matplotlib.pyplot as plt # create datax = [10,20,30,40,50]y = [30,30,30,30,30] # plot lineplt.plot(x, y)plt.show()
Output:
In this example, we will learn how to draw a vertical line with the help of matplotlib. Here we will use two lists as data with two dimensions (x and y) and at last plot the line. For making a vertical line we have to change the value of the y-axis continuously by taking the x-axis as constant. So we change the axes to get a vertical line.
Python3
# importing packageimport matplotlib.pyplot as plt # create datax = [10,20,30,40,50]y = [30,30,30,30,30] # plot lineplt.plot(y,x)plt.show()
Output:
In this example, we will learn how to draw a horizontal line and a vertical line both in one graph with the help of matplotlib. Here we will use two list as data with two dimensions (x and y) and at last plot the line with respect to the dimensions. So, in this example we merge the above both graphs to make both lines together in a graph.
Python3
# importing packageimport matplotlib.pyplot as plt # create datax = [10,20,30,40,50]y = [30,30,30,30,30] # plot linesplt.plot(x, y, label = "line 1")plt.plot(y, x, label = "line 2")plt.legend()plt.show()
Output:
In this example, we will learn how to draw multiple lines with the help of matplotlib. Here we will use two lists as data with two dimensions (x and y) and at last plot the lines as different dimensions and functions over the same data.
To draw multiple lines we will use different functions which are as follows:
y = x
x = y
y = sin(x)
y = cos(x)
Python3
# importing packageimport matplotlib.pyplot as pltimport numpy as np # create datax = [1,2,3,4,5]y = [3,3,3,3,3] # plot linesplt.plot(x, y, label = "line 1")plt.plot(y, x, label = "line 2")plt.plot(x, np.sin(x), label = "curve 1")plt.plot(x, np.cos(x), label = "curve 2")plt.legend()plt.show()
Output:
This example is similar to the above example and the enhancement is the different line styles. This can help in the modification of better visualization.
Here we will use different line styles which are as follows:
– : dashed
— : double dashed
-. : dashed-dotted
: : dotted
Python3
# importing packageimport matplotlib.pyplot as pltimport numpy as np # create datax = [1,2,3,4,5]y = [3,3,3,3,3] # plot linesplt.plot(x, y, label = "line 1", linestyle="-")plt.plot(y, x, label = "line 2", linestyle="--")plt.plot(x, np.sin(x), label = "curve 1", linestyle="-.")plt.plot(x, np.cos(x), label = "curve 2", linestyle=":")plt.legend()plt.show()
Output:
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
Taking input in Python
Read a file line by line in Python
How to Install PIP on Windows ?
Enumerate() in Python
Different ways to create Pandas Dataframe
|
[
{
"code": null,
"e": 31547,
"s": 31519,
"text": "\n25 Nov, 2020"
},
{
"code": null,
"e": 31662,
"s": 31547,
"text": "In this article, we will learn how to plot multiple lines using matplotlib in Python. Let’s discuss some concepts:"
},
{
"code": null,
"e": 31937,
"s": 31662,
"text": "Matplotlib: Matplotlib is an amazing visualization library in Python for 2D plots of arrays. Matplotlib is a multi-platform data visualization library built on NumPy arrays and designed to work with the broader SciPy stack. It was introduced by John Hunter in the year 2002."
},
{
"code": null,
"e": 32199,
"s": 31937,
"text": "Line plot: Line plots can be created in Python with Matplotlib’s pyplot library. To build a line plot, first import Matplotlib. It is a standard convention to import Matplotlib’s pyplot library as plt. The plt alias will be familiar to other Python programmers."
},
{
"code": null,
"e": 32346,
"s": 32199,
"text": "Here we will discuss some examples to draw a line or multiple lines with different features. To do such work we must follow the steps given below:"
},
{
"code": null,
"e": 32364,
"s": 32346,
"text": "Import libraries."
},
{
"code": null,
"e": 32377,
"s": 32364,
"text": "Create Data."
},
{
"code": null,
"e": 32403,
"s": 32377,
"text": "Plot the lines over data."
},
{
"code": null,
"e": 32702,
"s": 32403,
"text": "In this example, we will learn how to draw a horizontal line with the help of matplotlib. Here we will use two lists as data for two dimensions (x and y) and at last plot the line. For making a horizontal line we have to change the value of the x-axis continuously by taking the y-axis as constant."
},
{
"code": null,
"e": 32710,
"s": 32702,
"text": "Python3"
},
{
"code": "# importing packageimport matplotlib.pyplot as plt # create datax = [10,20,30,40,50]y = [30,30,30,30,30] # plot lineplt.plot(x, y)plt.show()",
"e": 32853,
"s": 32710,
"text": null
},
{
"code": null,
"e": 32861,
"s": 32853,
"text": "Output:"
},
{
"code": null,
"e": 33203,
"s": 32861,
"text": "In this example, we will learn how to draw a vertical line with the help of matplotlib. Here we will use two lists as data with two dimensions (x and y) and at last plot the line. For making a vertical line we have to change the value of the y-axis continuously by taking the x-axis as constant. So we change the axes to get a vertical line."
},
{
"code": null,
"e": 33211,
"s": 33203,
"text": "Python3"
},
{
"code": "# importing packageimport matplotlib.pyplot as plt # create datax = [10,20,30,40,50]y = [30,30,30,30,30] # plot lineplt.plot(y,x)plt.show()",
"e": 33353,
"s": 33211,
"text": null
},
{
"code": null,
"e": 33361,
"s": 33353,
"text": "Output:"
},
{
"code": null,
"e": 33702,
"s": 33361,
"text": "In this example, we will learn how to draw a horizontal line and a vertical line both in one graph with the help of matplotlib. Here we will use two list as data with two dimensions (x and y) and at last plot the line with respect to the dimensions. So, in this example we merge the above both graphs to make both lines together in a graph."
},
{
"code": null,
"e": 33710,
"s": 33702,
"text": "Python3"
},
{
"code": "# importing packageimport matplotlib.pyplot as plt # create datax = [10,20,30,40,50]y = [30,30,30,30,30] # plot linesplt.plot(x, y, label = \"line 1\")plt.plot(y, x, label = \"line 2\")plt.legend()plt.show()",
"e": 33916,
"s": 33710,
"text": null
},
{
"code": null,
"e": 33924,
"s": 33916,
"text": "Output:"
},
{
"code": null,
"e": 34161,
"s": 33924,
"text": "In this example, we will learn how to draw multiple lines with the help of matplotlib. Here we will use two lists as data with two dimensions (x and y) and at last plot the lines as different dimensions and functions over the same data."
},
{
"code": null,
"e": 34238,
"s": 34161,
"text": "To draw multiple lines we will use different functions which are as follows:"
},
{
"code": null,
"e": 34244,
"s": 34238,
"text": "y = x"
},
{
"code": null,
"e": 34250,
"s": 34244,
"text": "x = y"
},
{
"code": null,
"e": 34261,
"s": 34250,
"text": "y = sin(x)"
},
{
"code": null,
"e": 34272,
"s": 34261,
"text": "y = cos(x)"
},
{
"code": null,
"e": 34280,
"s": 34272,
"text": "Python3"
},
{
"code": "# importing packageimport matplotlib.pyplot as pltimport numpy as np # create datax = [1,2,3,4,5]y = [3,3,3,3,3] # plot linesplt.plot(x, y, label = \"line 1\")plt.plot(y, x, label = \"line 2\")plt.plot(x, np.sin(x), label = \"curve 1\")plt.plot(x, np.cos(x), label = \"curve 2\")plt.legend()plt.show()",
"e": 34576,
"s": 34280,
"text": null
},
{
"code": null,
"e": 34584,
"s": 34576,
"text": "Output:"
},
{
"code": null,
"e": 34739,
"s": 34584,
"text": "This example is similar to the above example and the enhancement is the different line styles. This can help in the modification of better visualization. "
},
{
"code": null,
"e": 34800,
"s": 34739,
"text": "Here we will use different line styles which are as follows:"
},
{
"code": null,
"e": 34818,
"s": 34800,
"text": "– : dashed"
},
{
"code": null,
"e": 34841,
"s": 34818,
"text": "— : double dashed"
},
{
"code": null,
"e": 34866,
"s": 34841,
"text": "-. : dashed-dotted"
},
{
"code": null,
"e": 34884,
"s": 34866,
"text": ": : dotted"
},
{
"code": null,
"e": 34892,
"s": 34884,
"text": "Python3"
},
{
"code": "# importing packageimport matplotlib.pyplot as pltimport numpy as np # create datax = [1,2,3,4,5]y = [3,3,3,3,3] # plot linesplt.plot(x, y, label = \"line 1\", linestyle=\"-\")plt.plot(y, x, label = \"line 2\", linestyle=\"--\")plt.plot(x, np.sin(x), label = \"curve 1\", linestyle=\"-.\")plt.plot(x, np.cos(x), label = \"curve 2\", linestyle=\":\")plt.legend()plt.show()",
"e": 35250,
"s": 34892,
"text": null
},
{
"code": null,
"e": 35258,
"s": 35250,
"text": "Output:"
},
{
"code": null,
"e": 35276,
"s": 35258,
"text": "Python-matplotlib"
},
{
"code": null,
"e": 35283,
"s": 35276,
"text": "Python"
},
{
"code": null,
"e": 35381,
"s": 35283,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 35409,
"s": 35381,
"text": "Read JSON file using Python"
},
{
"code": null,
"e": 35459,
"s": 35409,
"text": "Adding new column to existing DataFrame in Pandas"
},
{
"code": null,
"e": 35481,
"s": 35459,
"text": "Python map() function"
},
{
"code": null,
"e": 35525,
"s": 35481,
"text": "How to get column names in Pandas dataframe"
},
{
"code": null,
"e": 35543,
"s": 35525,
"text": "Python Dictionary"
},
{
"code": null,
"e": 35566,
"s": 35543,
"text": "Taking input in Python"
},
{
"code": null,
"e": 35601,
"s": 35566,
"text": "Read a file line by line in Python"
},
{
"code": null,
"e": 35633,
"s": 35601,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 35655,
"s": 35633,
"text": "Enumerate() in Python"
}
] |
Middle term in the binomial expansion series - GeeksforGeeks
|
14 Apr, 2021
Given three integers A, X, and n. The task is to find the middle term in the binomial expansion series. Examples:
Input : A = 1, X = 1, n = 6
Output : MiddleTerm = 20
Input : A = 2, X = 4, n = 7
Output : MiddleTerm1 = 35840, MiddleTerm2 = 71680
Approach
(A + X)n = nC0 An X0 + nC1 An-1 X1 + nC2 An-2 X2 + ......... + nCn-1 A1 Xn-1 + nCn A0 Xn Total number of term in the binomial expansion of (A + X)n is (n + 1).General term in binomial expansion is given by: Tr+1 = nCr An-r XrIf n is even number: Let m be the middle term of binomial expansion series, then n = 2m m = n / 2 We know that there will be n + 1 term so, n + 1 = 2m +1 In this case, there will is only one middle term. This middle term is (m + 1)th term. Hence, the middle term Tm+1 = nCmAn-mXmif n is odd number: Let m be the middle term of binomial expansion series, then let n = 2m + 1 m = (n-1) / 2 number of terms = n + 1 = 2m + 1 + 1 = 2m + 2 In this case there will be two middle terms. These middle terms will be (m + 1)th and (m + 2)th term. Hence, the middle terms are : Tm+1 = nC(n-1)/2 A(n+1)/2 X(n-1)/2 Tm+2 = nC(n+1)/2 A(n-1)/2 X(n+1)/2
C++
Java
Python3
C#
PHP
Javascript
// C++ program to find the middle term// in binomial expansion series.#include <bits/stdc++.h>using namespace std; // function to calculate// factorial of a numberint factorial(int n){ int fact = 1; for (int i = 1; i <= n; i++) fact *= i; return fact;} // Function to find middle term in// binomial expansion series.void findMiddleTerm(int A, int X, int n){ int i, j, aPow, xPow; float middleTerm1, middleTerm2; if (n % 2 == 0) { // If n is even // calculating the middle term i = n / 2; // calculating the value of A to // the power k and X to the power k aPow = (int)pow(A, n - i); xPow = (int)pow(X, i); middleTerm1 = ((float)factorial(n) / (factorial(n - i) * factorial(i))) * aPow * xPow; cout << "MiddleTerm = " << middleTerm1 << endl; } else { // If n is odd // calculating the middle term i = (n - 1) / 2; j = (n + 1) / 2; // calculating the value of A to the // power k and X to the power k aPow = (int)pow(A, n - i); xPow = (int)pow(X, i); middleTerm1 = ((float)factorial(n) / (factorial(n - i) * factorial(i))) * aPow * xPow; // calculating the value of A to the // power k and X to the power k aPow = (int)pow(A, n - j); xPow = (int)pow(X, j); middleTerm2 = ((float)factorial(n) / (factorial(n - j) * factorial(j))) * aPow * xPow; cout << "MiddleTerm1 = " << middleTerm1 << endl; cout << "MiddleTerm2 = " << middleTerm2 << endl; }} // Driver codeint main(){ int n = 5, A = 2, X = 3; // function call findMiddleTerm(A, X, n); return 0;}
// Java program to find the middle term// in binomial expansion series.import java.math.*; class GFG { // function to calculate factorial // of a number static int factorial(int n) { int fact = 1, i; if (n == 0) return 1; for (i = 1; i <= n; i++) fact *= i; return fact; } // Function to find middle term in // binomial expansion series. static void findmiddle(int A, int X, int n) { int i, j, aPow, xPow; float middleTerm1, middleTerm2; if (n % 2 == 0) { // If n is even // calculating the middle term i = n / 2; // calculating the value of A to // the power k and X to the power k aPow = (int)Math.pow(A, n - i); xPow = (int)Math.pow(X, i); middleTerm1 = ((float)factorial(n) / (factorial(n - i) * factorial(i))) * aPow * xPow; System.out.println("MiddleTerm = " + middleTerm1); } else { // If n is odd // calculating the middle term i = (n - 1) / 2; j = (n + 1) / 2; // calculating the value of A to the // power k and X to the power k aPow = (int)Math.pow(A, n - i); xPow = (int)Math.pow(X, i); middleTerm1 = ((float)factorial(n) / (factorial(n - i) * factorial(i))) * aPow * xPow; // calculating the value of A to the // power k and X to the power k aPow = (int)Math.pow(A, n - j); xPow = (int)Math.pow(X, j); middleTerm2 = ((float)factorial(n) / (factorial(n - j) * factorial(j))) * aPow * xPow; System.out.println("MiddleTerm1 = " + middleTerm1); System.out.println("MiddleTerm2 = " + middleTerm2); } } // Driver code public static void main(String[] args) { int n = 6, A = 2, X = 4; // calling the function findmiddle(A, X, n); }}
# Python3 program to find the middle term# in binomial expansion series.import math # function to calculate# factorial of a numberdef factorial(n) : fact = 1 for i in range(1, n+1) : fact = fact * i return fact; # Function to find middle term in# binomial expansion series.def findMiddleTerm(A, X, n) : if (n % 2 == 0) : # If n is even # calculating the middle term i = int(n / 2) # calculating the value of A to # the power k and X to the power k aPow = int(math.pow(A, n - i)) xPow = int(math.pow(X, i)) middleTerm1 = ((math.factorial(n) / (math.factorial(n - i) * math.factorial(i))) * aPow * xPow) print ("MiddleTerm = {}" . format(middleTerm1)) else : # If n is odd # calculating the middle term i = int((n - 1) / 2) j = int((n + 1) / 2) # calculating the value of A to the # power k and X to the power k aPow = int(math.pow(A, n - i)) xPow = int(math.pow(X, i)) middleTerm1 = ((math.factorial(n) / (math.factorial(n - i) * math.factorial(i))) * aPow * xPow) # calculating the value of A to the # power k and X to the power k aPow = int(math.pow(A, n - j)) xPow = int(math.pow(X, j)) middleTerm2 = ((math.factorial(n) / (math.factorial(n - j) * math.factorial(j))) * aPow * xPow) print ("MiddleTerm1 = {}" . format(int(middleTerm1))) print ("MiddleTerm2 = {}" . format(int(middleTerm2))) # Driver coden = 5A = 2X = 3 # function callfindMiddleTerm(A, X, n) # This code is contributed by# manishshaw1.
// C# program to find the middle term// in binomial expansion series.using System; class GFG { // function to calculate factorial // of a number static int factorial(int n) { int fact = 1, i; if (n == 0) return 1; for (i = 1; i <= n; i++) fact *= i; return fact; } // Function to find middle term in // binomial expansion series. static void findmiddle(int A, int X, int n) { int i, j, aPow, xPow; float middleTerm1, middleTerm2; if (n % 2 == 0) { // If n is even // calculating the middle term i = n / 2; // calculating the value of A to // the power k and X to the power k aPow = (int)Math.Pow(A, n - i); xPow = (int)Math.Pow(X, i); middleTerm1 = ((float)factorial(n) / (factorial(n - i) * factorial(i))) * aPow * xPow; Console.WriteLine("MiddleTerm = " + middleTerm1); } else { // If n is odd // calculating the middle term i = (n - 1) / 2; j = (n + 1) / 2; // calculating the value of A to the // power k and X to the power k aPow = (int)Math.Pow(A, n - i); xPow = (int)Math.Pow(X, i); middleTerm1 = ((float)factorial(n) / (factorial(n - i) * factorial(i))) * aPow * xPow; // calculating the value of A to the // power k and X to the power k aPow = (int)Math.Pow(A, n - j); xPow = (int)Math.Pow(X, j); middleTerm2 = ((float)factorial(n) / (factorial(n - j) * factorial(j))) * aPow * xPow; Console.WriteLine("MiddleTerm1 = " + middleTerm1); Console.WriteLine("MiddleTerm2 = " + middleTerm2); } } // Driver code public static void Main() { int n = 5, A = 2, X = 3; // calling the function findmiddle(A, X, n); }} // This code is contributed by anuj_67.
<?php// PHP program to find the middle term// in binomial expansion series. // function to calculate// factorial of a numberfunction factorial(int $n){ $fact = 1; for($i = 1; $i <= $n; $i++) $fact *= $i; return $fact;} // Function to find middle term in// binomial expansion series.function findMiddleTerm($A, $X, $n){ $i; $j; $aPow; $xPow; $middleTerm1; $middleTerm2; if ($n % 2 == 0) { // If n is even // calculating the middle term $i = $n / 2; // calculating the value of A to // the power k and X to the power k $aPow = pow($A, $n - i); $xPow = pow($X, $i); $middleTerm1 = $factorial($n) / (factorial($n - $i) * factorial($i)) * $aPow * $xPow; echo "MiddleTerm = ","\n", $middleTerm1 ; } else { // If n is odd // calculating the middle term $i = ($n - 1) / 2; $j = ($n + 1) / 2; // calculating the value of A to the // power k and X to the power k $aPow = pow($A, $n - $i); $xPow = pow($X, $i); $middleTerm1 = ((float)factorial($n) / (factorial($n - $i) * factorial($i))) * $aPow * $xPow; // calculating the value of A to the // power k and X to the power k $aPow = pow($A, $n - $j); $xPow = pow($X, $j); $middleTerm2 = factorial($n) / (factorial($n - $j) * factorial($j)) * $aPow * $xPow; echo "MiddleTerm1 = " , $middleTerm1,"\n" ; echo "MiddleTerm2 = " , $middleTerm2 ; }} // Driver code $n = 5; $A = 2; $X = 3; // function call findMiddleTerm($A, $X, $n); // This code is contributed by Vishal Tripathi.?>
<script> // JavaScript program to find the middle term// in binomial expansion series. // function to calculate// factorial of a numberfunction factorial(n){ let fact = 1; for (let i = 1; i <= n; i++) fact *= i; return fact;} // Function to find middle term in// binomial expansion series.function findMiddleTerm(A, X, n){ let i, j, aPow, xPow; let middleTerm1, middleTerm2; if (n % 2 == 0) { // If n is even // calculating the middle term i = Math.floor(n / 2); // calculating the value of A to // the power k and X to the power k aPow = Math.floor(Math.pow(A, n - i)); xPow = Math.floor(Math.pow(X, i)); middleTerm1 = Math.floor(factorial(n) / (factorial(n - i) * factorial(i))) * aPow * xPow; document.write("MiddleTerm = " + middleTerm1 + "<br>"); } else { // If n is odd // calculating the middle term i = Math.floor((n - 1) / 2); j = Math.floor((n + 1) / 2); // calculating the value of A to the // power k and X to the power k aPow = Math.floor(Math.pow(A, n - i)); xPow = Math.floor(Math.pow(X, i)); middleTerm1 = Math.floor(factorial(n) / (factorial(n - i) * factorial(i))) * aPow * xPow; // calculating the value of A to the // power k and X to the power k aPow = Math.floor(Math.pow(A, n - j)); xPow = Math.floor(Math.pow(X, j)); middleTerm2 = Math.floor(factorial(n) / (factorial(n - j) * factorial(j))) * aPow * xPow; document.write("MiddleTerm1 = " + middleTerm1 + "<br>"); document.write("MiddleTerm2 = " + middleTerm2 + "<br>"); }} // Driver code let n = 5, A = 2, X = 3; // function call findMiddleTerm(A, X, n); // This code is contributed by Surbhi Tyagi. </script>
MiddleTerm1 = 720
MiddleTerm2 = 1080
vt_m
manishshaw1
surbhityagi15
binomial coefficient
series
Mathematical
Mathematical
series
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Program to print prime numbers from 1 to N.
Segment Tree | Set 1 (Sum of given range)
Modular multiplicative inverse
Count all possible paths from top left to bottom right of a mXn matrix
Fizz Buzz Implementation
Check if a number is Palindrome
Program to multiply two matrices
Merge two sorted arrays with O(1) extra space
Generate all permutation of a set in Python
Count ways to reach the n'th stair
|
[
{
"code": null,
"e": 25961,
"s": 25933,
"text": "\n14 Apr, 2021"
},
{
"code": null,
"e": 26077,
"s": 25961,
"text": "Given three integers A, X, and n. The task is to find the middle term in the binomial expansion series. Examples: "
},
{
"code": null,
"e": 26209,
"s": 26077,
"text": "Input : A = 1, X = 1, n = 6\nOutput : MiddleTerm = 20\n\nInput : A = 2, X = 4, n = 7\nOutput : MiddleTerm1 = 35840, MiddleTerm2 = 71680"
},
{
"code": null,
"e": 26220,
"s": 26209,
"text": "Approach "
},
{
"code": null,
"e": 27083,
"s": 26220,
"text": "(A + X)n = nC0 An X0 + nC1 An-1 X1 + nC2 An-2 X2 + ......... + nCn-1 A1 Xn-1 + nCn A0 Xn Total number of term in the binomial expansion of (A + X)n is (n + 1).General term in binomial expansion is given by: Tr+1 = nCr An-r XrIf n is even number: Let m be the middle term of binomial expansion series, then n = 2m m = n / 2 We know that there will be n + 1 term so, n + 1 = 2m +1 In this case, there will is only one middle term. This middle term is (m + 1)th term. Hence, the middle term Tm+1 = nCmAn-mXmif n is odd number: Let m be the middle term of binomial expansion series, then let n = 2m + 1 m = (n-1) / 2 number of terms = n + 1 = 2m + 1 + 1 = 2m + 2 In this case there will be two middle terms. These middle terms will be (m + 1)th and (m + 2)th term. Hence, the middle terms are : Tm+1 = nC(n-1)/2 A(n+1)/2 X(n-1)/2 Tm+2 = nC(n+1)/2 A(n-1)/2 X(n+1)/2 "
},
{
"code": null,
"e": 27091,
"s": 27087,
"text": "C++"
},
{
"code": null,
"e": 27096,
"s": 27091,
"text": "Java"
},
{
"code": null,
"e": 27104,
"s": 27096,
"text": "Python3"
},
{
"code": null,
"e": 27107,
"s": 27104,
"text": "C#"
},
{
"code": null,
"e": 27111,
"s": 27107,
"text": "PHP"
},
{
"code": null,
"e": 27122,
"s": 27111,
"text": "Javascript"
},
{
"code": "// C++ program to find the middle term// in binomial expansion series.#include <bits/stdc++.h>using namespace std; // function to calculate// factorial of a numberint factorial(int n){ int fact = 1; for (int i = 1; i <= n; i++) fact *= i; return fact;} // Function to find middle term in// binomial expansion series.void findMiddleTerm(int A, int X, int n){ int i, j, aPow, xPow; float middleTerm1, middleTerm2; if (n % 2 == 0) { // If n is even // calculating the middle term i = n / 2; // calculating the value of A to // the power k and X to the power k aPow = (int)pow(A, n - i); xPow = (int)pow(X, i); middleTerm1 = ((float)factorial(n) / (factorial(n - i) * factorial(i))) * aPow * xPow; cout << \"MiddleTerm = \" << middleTerm1 << endl; } else { // If n is odd // calculating the middle term i = (n - 1) / 2; j = (n + 1) / 2; // calculating the value of A to the // power k and X to the power k aPow = (int)pow(A, n - i); xPow = (int)pow(X, i); middleTerm1 = ((float)factorial(n) / (factorial(n - i) * factorial(i))) * aPow * xPow; // calculating the value of A to the // power k and X to the power k aPow = (int)pow(A, n - j); xPow = (int)pow(X, j); middleTerm2 = ((float)factorial(n) / (factorial(n - j) * factorial(j))) * aPow * xPow; cout << \"MiddleTerm1 = \" << middleTerm1 << endl; cout << \"MiddleTerm2 = \" << middleTerm2 << endl; }} // Driver codeint main(){ int n = 5, A = 2, X = 3; // function call findMiddleTerm(A, X, n); return 0;}",
"e": 29062,
"s": 27122,
"text": null
},
{
"code": "// Java program to find the middle term// in binomial expansion series.import java.math.*; class GFG { // function to calculate factorial // of a number static int factorial(int n) { int fact = 1, i; if (n == 0) return 1; for (i = 1; i <= n; i++) fact *= i; return fact; } // Function to find middle term in // binomial expansion series. static void findmiddle(int A, int X, int n) { int i, j, aPow, xPow; float middleTerm1, middleTerm2; if (n % 2 == 0) { // If n is even // calculating the middle term i = n / 2; // calculating the value of A to // the power k and X to the power k aPow = (int)Math.pow(A, n - i); xPow = (int)Math.pow(X, i); middleTerm1 = ((float)factorial(n) / (factorial(n - i) * factorial(i))) * aPow * xPow; System.out.println(\"MiddleTerm = \" + middleTerm1); } else { // If n is odd // calculating the middle term i = (n - 1) / 2; j = (n + 1) / 2; // calculating the value of A to the // power k and X to the power k aPow = (int)Math.pow(A, n - i); xPow = (int)Math.pow(X, i); middleTerm1 = ((float)factorial(n) / (factorial(n - i) * factorial(i))) * aPow * xPow; // calculating the value of A to the // power k and X to the power k aPow = (int)Math.pow(A, n - j); xPow = (int)Math.pow(X, j); middleTerm2 = ((float)factorial(n) / (factorial(n - j) * factorial(j))) * aPow * xPow; System.out.println(\"MiddleTerm1 = \" + middleTerm1); System.out.println(\"MiddleTerm2 = \" + middleTerm2); } } // Driver code public static void main(String[] args) { int n = 6, A = 2, X = 4; // calling the function findmiddle(A, X, n); }}",
"e": 31369,
"s": 29062,
"text": null
},
{
"code": "# Python3 program to find the middle term# in binomial expansion series.import math # function to calculate# factorial of a numberdef factorial(n) : fact = 1 for i in range(1, n+1) : fact = fact * i return fact; # Function to find middle term in# binomial expansion series.def findMiddleTerm(A, X, n) : if (n % 2 == 0) : # If n is even # calculating the middle term i = int(n / 2) # calculating the value of A to # the power k and X to the power k aPow = int(math.pow(A, n - i)) xPow = int(math.pow(X, i)) middleTerm1 = ((math.factorial(n) / (math.factorial(n - i) * math.factorial(i))) * aPow * xPow) print (\"MiddleTerm = {}\" . format(middleTerm1)) else : # If n is odd # calculating the middle term i = int((n - 1) / 2) j = int((n + 1) / 2) # calculating the value of A to the # power k and X to the power k aPow = int(math.pow(A, n - i)) xPow = int(math.pow(X, i)) middleTerm1 = ((math.factorial(n) / (math.factorial(n - i) * math.factorial(i))) * aPow * xPow) # calculating the value of A to the # power k and X to the power k aPow = int(math.pow(A, n - j)) xPow = int(math.pow(X, j)) middleTerm2 = ((math.factorial(n) / (math.factorial(n - j) * math.factorial(j))) * aPow * xPow) print (\"MiddleTerm1 = {}\" . format(int(middleTerm1))) print (\"MiddleTerm2 = {}\" . format(int(middleTerm2))) # Driver coden = 5A = 2X = 3 # function callfindMiddleTerm(A, X, n) # This code is contributed by# manishshaw1.",
"e": 33304,
"s": 31369,
"text": null
},
{
"code": "// C# program to find the middle term// in binomial expansion series.using System; class GFG { // function to calculate factorial // of a number static int factorial(int n) { int fact = 1, i; if (n == 0) return 1; for (i = 1; i <= n; i++) fact *= i; return fact; } // Function to find middle term in // binomial expansion series. static void findmiddle(int A, int X, int n) { int i, j, aPow, xPow; float middleTerm1, middleTerm2; if (n % 2 == 0) { // If n is even // calculating the middle term i = n / 2; // calculating the value of A to // the power k and X to the power k aPow = (int)Math.Pow(A, n - i); xPow = (int)Math.Pow(X, i); middleTerm1 = ((float)factorial(n) / (factorial(n - i) * factorial(i))) * aPow * xPow; Console.WriteLine(\"MiddleTerm = \" + middleTerm1); } else { // If n is odd // calculating the middle term i = (n - 1) / 2; j = (n + 1) / 2; // calculating the value of A to the // power k and X to the power k aPow = (int)Math.Pow(A, n - i); xPow = (int)Math.Pow(X, i); middleTerm1 = ((float)factorial(n) / (factorial(n - i) * factorial(i))) * aPow * xPow; // calculating the value of A to the // power k and X to the power k aPow = (int)Math.Pow(A, n - j); xPow = (int)Math.Pow(X, j); middleTerm2 = ((float)factorial(n) / (factorial(n - j) * factorial(j))) * aPow * xPow; Console.WriteLine(\"MiddleTerm1 = \" + middleTerm1); Console.WriteLine(\"MiddleTerm2 = \" + middleTerm2); } } // Driver code public static void Main() { int n = 5, A = 2, X = 3; // calling the function findmiddle(A, X, n); }} // This code is contributed by anuj_67.",
"e": 35604,
"s": 33304,
"text": null
},
{
"code": "<?php// PHP program to find the middle term// in binomial expansion series. // function to calculate// factorial of a numberfunction factorial(int $n){ $fact = 1; for($i = 1; $i <= $n; $i++) $fact *= $i; return $fact;} // Function to find middle term in// binomial expansion series.function findMiddleTerm($A, $X, $n){ $i; $j; $aPow; $xPow; $middleTerm1; $middleTerm2; if ($n % 2 == 0) { // If n is even // calculating the middle term $i = $n / 2; // calculating the value of A to // the power k and X to the power k $aPow = pow($A, $n - i); $xPow = pow($X, $i); $middleTerm1 = $factorial($n) / (factorial($n - $i) * factorial($i)) * $aPow * $xPow; echo \"MiddleTerm = \",\"\\n\", $middleTerm1 ; } else { // If n is odd // calculating the middle term $i = ($n - 1) / 2; $j = ($n + 1) / 2; // calculating the value of A to the // power k and X to the power k $aPow = pow($A, $n - $i); $xPow = pow($X, $i); $middleTerm1 = ((float)factorial($n) / (factorial($n - $i) * factorial($i))) * $aPow * $xPow; // calculating the value of A to the // power k and X to the power k $aPow = pow($A, $n - $j); $xPow = pow($X, $j); $middleTerm2 = factorial($n) / (factorial($n - $j) * factorial($j)) * $aPow * $xPow; echo \"MiddleTerm1 = \" , $middleTerm1,\"\\n\" ; echo \"MiddleTerm2 = \" , $middleTerm2 ; }} // Driver code $n = 5; $A = 2; $X = 3; // function call findMiddleTerm($A, $X, $n); // This code is contributed by Vishal Tripathi.?>",
"e": 37501,
"s": 35604,
"text": null
},
{
"code": "<script> // JavaScript program to find the middle term// in binomial expansion series. // function to calculate// factorial of a numberfunction factorial(n){ let fact = 1; for (let i = 1; i <= n; i++) fact *= i; return fact;} // Function to find middle term in// binomial expansion series.function findMiddleTerm(A, X, n){ let i, j, aPow, xPow; let middleTerm1, middleTerm2; if (n % 2 == 0) { // If n is even // calculating the middle term i = Math.floor(n / 2); // calculating the value of A to // the power k and X to the power k aPow = Math.floor(Math.pow(A, n - i)); xPow = Math.floor(Math.pow(X, i)); middleTerm1 = Math.floor(factorial(n) / (factorial(n - i) * factorial(i))) * aPow * xPow; document.write(\"MiddleTerm = \" + middleTerm1 + \"<br>\"); } else { // If n is odd // calculating the middle term i = Math.floor((n - 1) / 2); j = Math.floor((n + 1) / 2); // calculating the value of A to the // power k and X to the power k aPow = Math.floor(Math.pow(A, n - i)); xPow = Math.floor(Math.pow(X, i)); middleTerm1 = Math.floor(factorial(n) / (factorial(n - i) * factorial(i))) * aPow * xPow; // calculating the value of A to the // power k and X to the power k aPow = Math.floor(Math.pow(A, n - j)); xPow = Math.floor(Math.pow(X, j)); middleTerm2 = Math.floor(factorial(n) / (factorial(n - j) * factorial(j))) * aPow * xPow; document.write(\"MiddleTerm1 = \" + middleTerm1 + \"<br>\"); document.write(\"MiddleTerm2 = \" + middleTerm2 + \"<br>\"); }} // Driver code let n = 5, A = 2, X = 3; // function call findMiddleTerm(A, X, n); // This code is contributed by Surbhi Tyagi. </script>",
"e": 39558,
"s": 37501,
"text": null
},
{
"code": null,
"e": 39595,
"s": 39558,
"text": "MiddleTerm1 = 720\nMiddleTerm2 = 1080"
},
{
"code": null,
"e": 39602,
"s": 39597,
"text": "vt_m"
},
{
"code": null,
"e": 39614,
"s": 39602,
"text": "manishshaw1"
},
{
"code": null,
"e": 39628,
"s": 39614,
"text": "surbhityagi15"
},
{
"code": null,
"e": 39649,
"s": 39628,
"text": "binomial coefficient"
},
{
"code": null,
"e": 39656,
"s": 39649,
"text": "series"
},
{
"code": null,
"e": 39669,
"s": 39656,
"text": "Mathematical"
},
{
"code": null,
"e": 39682,
"s": 39669,
"text": "Mathematical"
},
{
"code": null,
"e": 39689,
"s": 39682,
"text": "series"
},
{
"code": null,
"e": 39787,
"s": 39689,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 39831,
"s": 39787,
"text": "Program to print prime numbers from 1 to N."
},
{
"code": null,
"e": 39873,
"s": 39831,
"text": "Segment Tree | Set 1 (Sum of given range)"
},
{
"code": null,
"e": 39904,
"s": 39873,
"text": "Modular multiplicative inverse"
},
{
"code": null,
"e": 39975,
"s": 39904,
"text": "Count all possible paths from top left to bottom right of a mXn matrix"
},
{
"code": null,
"e": 40000,
"s": 39975,
"text": "Fizz Buzz Implementation"
},
{
"code": null,
"e": 40032,
"s": 40000,
"text": "Check if a number is Palindrome"
},
{
"code": null,
"e": 40065,
"s": 40032,
"text": "Program to multiply two matrices"
},
{
"code": null,
"e": 40111,
"s": 40065,
"text": "Merge two sorted arrays with O(1) extra space"
},
{
"code": null,
"e": 40155,
"s": 40111,
"text": "Generate all permutation of a set in Python"
}
] |
Remove json element - JavaScript?
|
Let’s say the following is our JSON string −
var details =
[
{
customerName: "Chris",
customerAge: 32
},
{
customerName: "David",
customerAge: 26
},
{
customerName: "Bob",
customerAge: 29
},
{
customerName: "Carol",
customerAge: 25
}
]
To remove JSON element, use the delete keyword in JavaScript.
Following is the complete code to remove JSON element −
var details =
[
{
customerName: "Chris",
customerAge: 32
},
{
customerName: "David",
customerAge: 26
},
{
customerName: "Bob",
customerAge: 29
},
{
customerName: "Carol",
customerAge: 25
}
]
delete details[0].customerAge;
console.log(details);
To run the above program, you need to use the following command −
node fileName.js.
Here, my file name is demo211.js −
PS C:\Users\Amit\JavaScript-code> node demo211.js
[
{ customerName: 'Chris' },
{ customerName: 'David', customerAge: 26 },
{ customerName: 'Bob', customerAge: 29 },
{ customerName: 'Carol', customerAge: 25 }
]
|
[
{
"code": null,
"e": 1107,
"s": 1062,
"text": "Let’s say the following is our JSON string −"
},
{
"code": null,
"e": 1370,
"s": 1107,
"text": "var details =\n[\n {\n customerName: \"Chris\",\n customerAge: 32\n },\n {\n customerName: \"David\",\n customerAge: 26\n },\n {\n customerName: \"Bob\",\n customerAge: 29\n },\n {\n customerName: \"Carol\",\n customerAge: 25\n }\n]"
},
{
"code": null,
"e": 1432,
"s": 1370,
"text": "To remove JSON element, use the delete keyword in JavaScript."
},
{
"code": null,
"e": 1488,
"s": 1432,
"text": "Following is the complete code to remove JSON element −"
},
{
"code": null,
"e": 1804,
"s": 1488,
"text": "var details =\n[\n {\n customerName: \"Chris\",\n customerAge: 32\n },\n {\n customerName: \"David\",\n customerAge: 26\n },\n {\n customerName: \"Bob\",\n customerAge: 29\n },\n {\n customerName: \"Carol\",\n customerAge: 25\n }\n]\ndelete details[0].customerAge;\nconsole.log(details);"
},
{
"code": null,
"e": 1870,
"s": 1804,
"text": "To run the above program, you need to use the following command −"
},
{
"code": null,
"e": 1888,
"s": 1870,
"text": "node fileName.js."
},
{
"code": null,
"e": 1923,
"s": 1888,
"text": "Here, my file name is demo211.js −"
},
{
"code": null,
"e": 2145,
"s": 1923,
"text": "PS C:\\Users\\Amit\\JavaScript-code> node demo211.js\n[\n { customerName: 'Chris' },\n { customerName: 'David', customerAge: 26 },\n { customerName: 'Bob', customerAge: 29 },\n { customerName: 'Carol', customerAge: 25 }\n]"
}
] |
Difference Between Method Overloading and Method Overriding in Java - GeeksforGeeks
|
02 Feb, 2022
The differences between Method Overloading and Method Overriding in Java are:
Method Overloading
Method Overriding
Method Overloading is a Compile time polymorphism. In method overloading, more than one method shares the same method name with a different signature in the class. In method overloading, the return type can or can not be the same, but we have to change the parameter because, in java, we can not achieve the method overloading by changing only the return type of the method.
Example of Method Overloading:
Java
import java.io.*; class MethodOverloadingEx { static int add(int a, int b) { return a + b; } static int add(int a, int b, int c) { return a + b + c; } public static void main(String args[]) { System.out.println("add() with 2 parameters"); System.out.println(add(4, 6)); System.out.println("add() with 3 parameters"); System.out.println(add(4, 6, 7)); }}
add() with 2 parameters
10
add() with 3 parameters
17
Method Overriding is a Run time polymorphism. In method overriding, the derived class provides the specific implementation of the method that is already provided by the base class or parent class. In method overriding, the return type must be the same or co-variant (return type may vary in the same direction as the derived class).
Example of Method Overriding:
Java
import java.io.*; class Animal { void eat() { System.out.println("eat() method of base class"); System.out.println("eating."); }} class Dog extends Animal { void eat() { System.out.println("eat() method of derived class"); System.out.println("Dog is eating."); }} class MethodOverridingEx { public static void main(String args[]) { Dog d1 = new Dog(); Animal a1 = new Animal(); d1.eat(); a1.eat(); Animal animal = new Dog(); // eat() method of animal class is overridden by // base class eat() animal.eat(); }}
eat() method of derived class
Dog is eating.
eat() method of base class
eating.
eat() method of derived class
Dog is eating.
Explanation:
Here, we can see that a method eat() has overridden in the derived class name Dog that is already provided by the base class name Animal. When we create the instance of class Dog and call the eat() method, we see that only derived class eat() method run instead of base class method eat(), and When we create the instance of class Animal and call the eat() method, we see that only base class eat() method run instead of derived class method eat().
So, it’s clear that in method overriding, the method is bound to the instances on the run time, which is decided by the JVM. That’s why it is called Run time polymorphism.
nishkarshgandhi
vikush
Java-Overloading
java-overriding
Difference Between
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Difference between BFS and DFS
Class method vs Static method in Python
Differences between TCP and UDP
Difference between var, let and const keywords in JavaScript
Differences between IPv4 and IPv6
Stack vs Heap Memory Allocation
Difference Between == and .equals() Method in Java
Difference between Process and Thread
Differences between Black Box Testing vs White Box Testing
Difference between Clustered and Non-clustered index
|
[
{
"code": null,
"e": 30305,
"s": 30277,
"text": "\n02 Feb, 2022"
},
{
"code": null,
"e": 30383,
"s": 30305,
"text": "The differences between Method Overloading and Method Overriding in Java are:"
},
{
"code": null,
"e": 30402,
"s": 30383,
"text": "Method Overloading"
},
{
"code": null,
"e": 30420,
"s": 30402,
"text": "Method Overriding"
},
{
"code": null,
"e": 30796,
"s": 30420,
"text": "Method Overloading is a Compile time polymorphism. In method overloading, more than one method shares the same method name with a different signature in the class. In method overloading, the return type can or can not be the same, but we have to change the parameter because, in java, we can not achieve the method overloading by changing only the return type of the method. "
},
{
"code": null,
"e": 30828,
"s": 30796,
"text": "Example of Method Overloading: "
},
{
"code": null,
"e": 30833,
"s": 30828,
"text": "Java"
},
{
"code": "import java.io.*; class MethodOverloadingEx { static int add(int a, int b) { return a + b; } static int add(int a, int b, int c) { return a + b + c; } public static void main(String args[]) { System.out.println(\"add() with 2 parameters\"); System.out.println(add(4, 6)); System.out.println(\"add() with 3 parameters\"); System.out.println(add(4, 6, 7)); }}",
"e": 31268,
"s": 30833,
"text": null
},
{
"code": null,
"e": 31322,
"s": 31268,
"text": "add() with 2 parameters\n10\nadd() with 3 parameters\n17"
},
{
"code": null,
"e": 31656,
"s": 31322,
"text": "Method Overriding is a Run time polymorphism. In method overriding, the derived class provides the specific implementation of the method that is already provided by the base class or parent class. In method overriding, the return type must be the same or co-variant (return type may vary in the same direction as the derived class). "
},
{
"code": null,
"e": 31687,
"s": 31656,
"text": "Example of Method Overriding: "
},
{
"code": null,
"e": 31692,
"s": 31687,
"text": "Java"
},
{
"code": "import java.io.*; class Animal { void eat() { System.out.println(\"eat() method of base class\"); System.out.println(\"eating.\"); }} class Dog extends Animal { void eat() { System.out.println(\"eat() method of derived class\"); System.out.println(\"Dog is eating.\"); }} class MethodOverridingEx { public static void main(String args[]) { Dog d1 = new Dog(); Animal a1 = new Animal(); d1.eat(); a1.eat(); Animal animal = new Dog(); // eat() method of animal class is overridden by // base class eat() animal.eat(); }}",
"e": 32319,
"s": 31692,
"text": null
},
{
"code": null,
"e": 32444,
"s": 32319,
"text": "eat() method of derived class\nDog is eating.\neat() method of base class\neating.\neat() method of derived class\nDog is eating."
},
{
"code": null,
"e": 32457,
"s": 32444,
"text": "Explanation:"
},
{
"code": null,
"e": 32907,
"s": 32457,
"text": "Here, we can see that a method eat() has overridden in the derived class name Dog that is already provided by the base class name Animal. When we create the instance of class Dog and call the eat() method, we see that only derived class eat() method run instead of base class method eat(), and When we create the instance of class Animal and call the eat() method, we see that only base class eat() method run instead of derived class method eat(). "
},
{
"code": null,
"e": 33079,
"s": 32907,
"text": "So, it’s clear that in method overriding, the method is bound to the instances on the run time, which is decided by the JVM. That’s why it is called Run time polymorphism."
},
{
"code": null,
"e": 33095,
"s": 33079,
"text": "nishkarshgandhi"
},
{
"code": null,
"e": 33102,
"s": 33095,
"text": "vikush"
},
{
"code": null,
"e": 33119,
"s": 33102,
"text": "Java-Overloading"
},
{
"code": null,
"e": 33135,
"s": 33119,
"text": "java-overriding"
},
{
"code": null,
"e": 33154,
"s": 33135,
"text": "Difference Between"
},
{
"code": null,
"e": 33252,
"s": 33154,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 33283,
"s": 33252,
"text": "Difference between BFS and DFS"
},
{
"code": null,
"e": 33323,
"s": 33283,
"text": "Class method vs Static method in Python"
},
{
"code": null,
"e": 33355,
"s": 33323,
"text": "Differences between TCP and UDP"
},
{
"code": null,
"e": 33416,
"s": 33355,
"text": "Difference between var, let and const keywords in JavaScript"
},
{
"code": null,
"e": 33450,
"s": 33416,
"text": "Differences between IPv4 and IPv6"
},
{
"code": null,
"e": 33482,
"s": 33450,
"text": "Stack vs Heap Memory Allocation"
},
{
"code": null,
"e": 33533,
"s": 33482,
"text": "Difference Between == and .equals() Method in Java"
},
{
"code": null,
"e": 33571,
"s": 33533,
"text": "Difference between Process and Thread"
},
{
"code": null,
"e": 33630,
"s": 33571,
"text": "Differences between Black Box Testing vs White Box Testing"
}
] |
What does built-in class attribute __doc__ do in Python?
|
All functions have a built-in attribute __doc__, which returns the doc string defined in the function source code.
def foo():
""" This is an example of how a doc_string looks like.
This string gives useful information about the function being defined.
"""
pass
print foo.__doc__
Let's see how this would look like when we print it
This is an example of how a doc_string looks like.
This string gives useful information about the function being defined.
|
[
{
"code": null,
"e": 1177,
"s": 1062,
"text": "All functions have a built-in attribute __doc__, which returns the doc string defined in the function source code."
},
{
"code": null,
"e": 1363,
"s": 1177,
"text": "def foo():\n \"\"\" This is an example of how a doc_string looks like.\n This string gives useful information about the function being defined.\n \"\"\"\n pass\nprint foo.__doc__"
},
{
"code": null,
"e": 1416,
"s": 1363,
"text": " Let's see how this would look like when we print it"
},
{
"code": null,
"e": 1548,
"s": 1416,
"text": "This is an example of how a doc_string looks like.\n This string gives useful information about the function being defined."
}
] |
Planning to Travel Around the World, with Python? | by Yin-Ta Pan | Towards Data Science
|
Traveling Around the world is always the dream for everyone, but seldom of us are prepared to do so. To be honest, we even do not know what traveling around the world means. Of course, I cannot provide anything you need when you traveling, such as money and vacation, which are what I am lack of too. However, you can start to plan, or to daydream, with the skills you learned from the articles.
There are two parts in this article:
[Part 1] — this article is about how to draw a map with Basemap package in Python. We need map before and during the trip, and we can use the package in Python to draw what we need. [source code in Jupyter notebook]
[Part 2] — this article is about how to optimize the route for us to travel around the world with Networkx package in Python. Networkx is a powerful package in Python to analyze complex network, and it will be helpful for us to make the plan of traveling around the world, with our goals. [source code in Jupyter notebook]
The matplotlib basemap toolkit is a library for plotting 2D data on map in Python. As everyone agrees that visualization is really important for people to understand data, map is the best visualization method when we are dealing with geographic locations (I believe no one is good at dealing with latitude and longitude data without a map.) Basemap is a powerful package in Python and we will pick some important features to explain in details. To have more understanding about the package, please check out the documentation.
As we all know, the earth is round. Therefore, to make it as a 2D map, we need some projection methods. In basemap package, it supports many projection methods and the list is here. Here are two examples of how to apply different projection methods in basemap.
Projection — Orthographic
Projection — Gall Stereographic
Once we can plot a map, we would like to mark some places on it. In baemap package, we can use the basemap object we defined previously to transfer latitude and longitude to the coordinate system in the matplotlib. After that, we can apply scatter or annotate functions to put points on the map. In the following example, we marked the four major cities in the U.S., New York, Washington DC, Los Angels and San Francisco.
Besides putting points on a map, we also need to draw lines to visualize routes between two places. As we know, the shortest route between two points on the map is not a straight line, but the great circle route. In basemap package, we can plot routes with gcpoints function to make the great circle route. Here is the example for the route from New York to San Francisco with gcpoints function.
There are still a lot of interesting functions in basemap package to make your map more informative and attractive. For example, arcgisimage can create a map with satellite photos. However, we are good enough to move on making our plans for traveling around the world now.
In our plan, we would like to travel around the world with flights. In OpenFlights database, we are able to access Airports and Routes information around the world. With the information, we can make our plan to travel around the world. However, before that, let’s take a look at the data and use basemap tool to visualize it first.
In OpenFlights, it includes all 6,060 airports around the world with completed Name, City, Country, IATA code, Latitude, Longitude and all other information. Besides, since it has latitude and longitude information, we can easily lookup more details, such as the continent the airport belongs to, with Google Map api or other tools. We can also use basemap tool to put the airports on the map with different colors for airports in different continents: North America, South America, Asia, Europe, Africa and Oceania as following.
Though we have all airports information around the world, we still need airline routes information when we think about how to travel around the world, since not all two airports are connected. In OpenFlights, it does have airline routes information. Unfortunately, it was not updating after June 2014. Though not perfect, we can still use the data and assume that the routes did not change a lot from 2014.
There are 67,663 different routes in OpenFlights database. It has Source airport and Destination airport information as well as Airline, Numbers of stops and Equipment details. If we only consider the source and destination airports, there are 33,971 distinct routes in the data. We can apply tools in basemap to visualize those routes as following.
Now we have all knowledge: skillsets to visualize on the map with Python and information about airports and airline routes. It seems like we are ready for our next step: optimizing our routes to travel around the world.
A good definition to a problem is always the most important thing. Before we start our analysis, we need to define what is “Travel Around the World” for us: you traveled around the world if you have visited at least one site in each continent: North America, South America, Asia, Europe, Africa and Oceania.
Networkx is a Python package for the creation, manipulation, and study of the structure, dynamics, and functions of complex networks. We can take the flight routes between airports as a complex networks, and Networkx package is therefore very helpful for us to analyze them. Before we start, there are some terms we need to get familiar first:
Nodes: the points in the network; in our example, airports are nodes in the airline network.
Edges: the connections between two points; in our example, flight routes are edges. Since not all two airports are connected, we need to use route data from OpenFlights to define them.
Directed/ Non-Directed graph: in directed graph, edge from A to B does not equal to edge from B to A; in contrast, in non-directed graph, edge A to B is the same as B to A. In our example, we should use directed graph as a route from A to B is not indicating that there is a corresponding route from B to A.
Simple/ Multigraphs: in simple graph, there is at most one edge between each point; in multigraphs, it allows more than one edge between two nodes, and each edge can have different attributes. To simplify our analysis, we choose to use simple graph model, which means we do not consider the differences of airlines.
Here are some useful functions for us to analyze the air flight network:
dijkstra_path: the shortest path from A to B by Dijkstra’s algorithm. We can put the “weight” in the function to indicate how to calculate the “distance”. For example, we want to find the shortest path from Atlanta to Taipei is to layover in Incheon Airport (ICN) with the following code.
nx.dijkstra_path(G, source='ATL', target='TPE', weight='Distance')>> [Output]: ['ATL', 'ICN', 'TPE']
single_source_dijkstra: when we do not have a specific destination, we can use the function to calculate the distance to all possible destinations, considering the layover options.
Without Networkx package, we can still do some analysis on route data from OpenFlights. For example, we can calculated distance by geodesic function in geopy package from airports’ latitudes and longitudes. We can take a look at the shortest route travel to another continents in each continent with pandas package with the processed dataset, which contains calculated mileage information, as following.
With the table, we can find the minimum distance to another continents and the corresponding airports. Taking North America as an example, the shortest route to South America is from Queen Beatrix International Airport (AUA) to Josefa Camejo International Airport (LSP). To Oceania, the shortest route is from Daniel K. Inouye International Airport (HNL) to Cassidy International Airport (CXI). The shortest routes for each continent to travel between can be visualized on the map as following.
To be noticed, there is no direct route between Europe and Oceania. However, it does not mean people in Europe cannot travel to Oceania, since we can always transfer in other airports. In this complicate situation, we can use Networkx package to handle it efficiently.
For Networkx 2.3 version, we can import edges from pandas with from_pandas_edgelist function and putting other columns as attributes for edges. We can put latitude, longitude and continent information for all airports by set_node_attributes function in Networkx and make our analysis easier in the future through the following codes.
We can define our goal as to travel the 6 continents with shortest distance. Definitely, we can calculate all distances between two airports and optimize the solution. However, since there are 6000+ airports around the world, it would be millions of possible pairs of airports, and the calculation could take forever. Therefore, instead of calculate the distance between all two airports, we can achieve the goal by finding the next closest airport to another continents given the location we currently in. With this logic, we define a customized function as following.
In the function, there are some input parameters we can change:
G: the graph for global airline network. It should be a Graph object in Networkx.
Start_Airport: the airport we start with.
Must_go: a list of airports we must visit during the trip.
Dont_go: a list of airports we do not want to visit during the trip.
With the tool, we can start the plan to travel around the world. Assuming that we start our trip from Atlanta (ATL,) where I am stay in currently. Without putting any Must_go and Dont_go sites, we can visualization the result on the map. The red triangles represent the destination airport we plan to visit and the black dots are where we layover. The trip starts with Atlanta and the first stop is Ernesto Cortissoz International Airport (BAQ) in South America. After that we will fly to TFN in Tenerife, Spain (Europe,) EUN in Western Sahara (Africa,) ADB in Turkey (Asia,) ROR in Palau (Oceania) and come back to Atlanta. As what we want, we have traveled all 6 continents with total distance of 39,905 km.
As shown on previous plan, there are many airports are actually far away from the continents “we think” it should belong to. For example, TFN airport, even though it is under Spain and is part of Europe, it actually closer to Africa. Besides, I would like to be back home, Taipei, during the trip. We can accomplish both goals with Must_go and Dont_go parameters in Globetrotting function. Here is the final plan for me to travel around the world.
In this article, we applied Networkx package to analyze global airline network and using basemap package in matplotlib to visualize the results. As mentioned, Networkx is a powerful analytical package for complex network and provides useful information in difficult scenarios. With the tools, we can plan our trip to travel around the world, which means visiting all 6 continents, under some customized requirements. Also, we can visualize our plan on the map as shown.
However, though we are proficient at Networkx and basemap package now, we are still in shortage of the most important resource, time and money, to actually travel around the world. Therefore, hope all of us have a nice working day tomorrow!
Welcome to discuss anything about Python, R, data analysis, or AI through LinkedIn. Just don’t show off your trip pictures with me!
|
[
{
"code": null,
"e": 443,
"s": 47,
"text": "Traveling Around the world is always the dream for everyone, but seldom of us are prepared to do so. To be honest, we even do not know what traveling around the world means. Of course, I cannot provide anything you need when you traveling, such as money and vacation, which are what I am lack of too. However, you can start to plan, or to daydream, with the skills you learned from the articles."
},
{
"code": null,
"e": 480,
"s": 443,
"text": "There are two parts in this article:"
},
{
"code": null,
"e": 696,
"s": 480,
"text": "[Part 1] — this article is about how to draw a map with Basemap package in Python. We need map before and during the trip, and we can use the package in Python to draw what we need. [source code in Jupyter notebook]"
},
{
"code": null,
"e": 1019,
"s": 696,
"text": "[Part 2] — this article is about how to optimize the route for us to travel around the world with Networkx package in Python. Networkx is a powerful package in Python to analyze complex network, and it will be helpful for us to make the plan of traveling around the world, with our goals. [source code in Jupyter notebook]"
},
{
"code": null,
"e": 1546,
"s": 1019,
"text": "The matplotlib basemap toolkit is a library for plotting 2D data on map in Python. As everyone agrees that visualization is really important for people to understand data, map is the best visualization method when we are dealing with geographic locations (I believe no one is good at dealing with latitude and longitude data without a map.) Basemap is a powerful package in Python and we will pick some important features to explain in details. To have more understanding about the package, please check out the documentation."
},
{
"code": null,
"e": 1807,
"s": 1546,
"text": "As we all know, the earth is round. Therefore, to make it as a 2D map, we need some projection methods. In basemap package, it supports many projection methods and the list is here. Here are two examples of how to apply different projection methods in basemap."
},
{
"code": null,
"e": 1833,
"s": 1807,
"text": "Projection — Orthographic"
},
{
"code": null,
"e": 1865,
"s": 1833,
"text": "Projection — Gall Stereographic"
},
{
"code": null,
"e": 2287,
"s": 1865,
"text": "Once we can plot a map, we would like to mark some places on it. In baemap package, we can use the basemap object we defined previously to transfer latitude and longitude to the coordinate system in the matplotlib. After that, we can apply scatter or annotate functions to put points on the map. In the following example, we marked the four major cities in the U.S., New York, Washington DC, Los Angels and San Francisco."
},
{
"code": null,
"e": 2683,
"s": 2287,
"text": "Besides putting points on a map, we also need to draw lines to visualize routes between two places. As we know, the shortest route between two points on the map is not a straight line, but the great circle route. In basemap package, we can plot routes with gcpoints function to make the great circle route. Here is the example for the route from New York to San Francisco with gcpoints function."
},
{
"code": null,
"e": 2956,
"s": 2683,
"text": "There are still a lot of interesting functions in basemap package to make your map more informative and attractive. For example, arcgisimage can create a map with satellite photos. However, we are good enough to move on making our plans for traveling around the world now."
},
{
"code": null,
"e": 3288,
"s": 2956,
"text": "In our plan, we would like to travel around the world with flights. In OpenFlights database, we are able to access Airports and Routes information around the world. With the information, we can make our plan to travel around the world. However, before that, let’s take a look at the data and use basemap tool to visualize it first."
},
{
"code": null,
"e": 3818,
"s": 3288,
"text": "In OpenFlights, it includes all 6,060 airports around the world with completed Name, City, Country, IATA code, Latitude, Longitude and all other information. Besides, since it has latitude and longitude information, we can easily lookup more details, such as the continent the airport belongs to, with Google Map api or other tools. We can also use basemap tool to put the airports on the map with different colors for airports in different continents: North America, South America, Asia, Europe, Africa and Oceania as following."
},
{
"code": null,
"e": 4225,
"s": 3818,
"text": "Though we have all airports information around the world, we still need airline routes information when we think about how to travel around the world, since not all two airports are connected. In OpenFlights, it does have airline routes information. Unfortunately, it was not updating after June 2014. Though not perfect, we can still use the data and assume that the routes did not change a lot from 2014."
},
{
"code": null,
"e": 4575,
"s": 4225,
"text": "There are 67,663 different routes in OpenFlights database. It has Source airport and Destination airport information as well as Airline, Numbers of stops and Equipment details. If we only consider the source and destination airports, there are 33,971 distinct routes in the data. We can apply tools in basemap to visualize those routes as following."
},
{
"code": null,
"e": 4795,
"s": 4575,
"text": "Now we have all knowledge: skillsets to visualize on the map with Python and information about airports and airline routes. It seems like we are ready for our next step: optimizing our routes to travel around the world."
},
{
"code": null,
"e": 5103,
"s": 4795,
"text": "A good definition to a problem is always the most important thing. Before we start our analysis, we need to define what is “Travel Around the World” for us: you traveled around the world if you have visited at least one site in each continent: North America, South America, Asia, Europe, Africa and Oceania."
},
{
"code": null,
"e": 5447,
"s": 5103,
"text": "Networkx is a Python package for the creation, manipulation, and study of the structure, dynamics, and functions of complex networks. We can take the flight routes between airports as a complex networks, and Networkx package is therefore very helpful for us to analyze them. Before we start, there are some terms we need to get familiar first:"
},
{
"code": null,
"e": 5540,
"s": 5447,
"text": "Nodes: the points in the network; in our example, airports are nodes in the airline network."
},
{
"code": null,
"e": 5725,
"s": 5540,
"text": "Edges: the connections between two points; in our example, flight routes are edges. Since not all two airports are connected, we need to use route data from OpenFlights to define them."
},
{
"code": null,
"e": 6033,
"s": 5725,
"text": "Directed/ Non-Directed graph: in directed graph, edge from A to B does not equal to edge from B to A; in contrast, in non-directed graph, edge A to B is the same as B to A. In our example, we should use directed graph as a route from A to B is not indicating that there is a corresponding route from B to A."
},
{
"code": null,
"e": 6349,
"s": 6033,
"text": "Simple/ Multigraphs: in simple graph, there is at most one edge between each point; in multigraphs, it allows more than one edge between two nodes, and each edge can have different attributes. To simplify our analysis, we choose to use simple graph model, which means we do not consider the differences of airlines."
},
{
"code": null,
"e": 6422,
"s": 6349,
"text": "Here are some useful functions for us to analyze the air flight network:"
},
{
"code": null,
"e": 6711,
"s": 6422,
"text": "dijkstra_path: the shortest path from A to B by Dijkstra’s algorithm. We can put the “weight” in the function to indicate how to calculate the “distance”. For example, we want to find the shortest path from Atlanta to Taipei is to layover in Incheon Airport (ICN) with the following code."
},
{
"code": null,
"e": 6812,
"s": 6711,
"text": "nx.dijkstra_path(G, source='ATL', target='TPE', weight='Distance')>> [Output]: ['ATL', 'ICN', 'TPE']"
},
{
"code": null,
"e": 6993,
"s": 6812,
"text": "single_source_dijkstra: when we do not have a specific destination, we can use the function to calculate the distance to all possible destinations, considering the layover options."
},
{
"code": null,
"e": 7397,
"s": 6993,
"text": "Without Networkx package, we can still do some analysis on route data from OpenFlights. For example, we can calculated distance by geodesic function in geopy package from airports’ latitudes and longitudes. We can take a look at the shortest route travel to another continents in each continent with pandas package with the processed dataset, which contains calculated mileage information, as following."
},
{
"code": null,
"e": 7892,
"s": 7397,
"text": "With the table, we can find the minimum distance to another continents and the corresponding airports. Taking North America as an example, the shortest route to South America is from Queen Beatrix International Airport (AUA) to Josefa Camejo International Airport (LSP). To Oceania, the shortest route is from Daniel K. Inouye International Airport (HNL) to Cassidy International Airport (CXI). The shortest routes for each continent to travel between can be visualized on the map as following."
},
{
"code": null,
"e": 8161,
"s": 7892,
"text": "To be noticed, there is no direct route between Europe and Oceania. However, it does not mean people in Europe cannot travel to Oceania, since we can always transfer in other airports. In this complicate situation, we can use Networkx package to handle it efficiently."
},
{
"code": null,
"e": 8495,
"s": 8161,
"text": "For Networkx 2.3 version, we can import edges from pandas with from_pandas_edgelist function and putting other columns as attributes for edges. We can put latitude, longitude and continent information for all airports by set_node_attributes function in Networkx and make our analysis easier in the future through the following codes."
},
{
"code": null,
"e": 9065,
"s": 8495,
"text": "We can define our goal as to travel the 6 continents with shortest distance. Definitely, we can calculate all distances between two airports and optimize the solution. However, since there are 6000+ airports around the world, it would be millions of possible pairs of airports, and the calculation could take forever. Therefore, instead of calculate the distance between all two airports, we can achieve the goal by finding the next closest airport to another continents given the location we currently in. With this logic, we define a customized function as following."
},
{
"code": null,
"e": 9129,
"s": 9065,
"text": "In the function, there are some input parameters we can change:"
},
{
"code": null,
"e": 9211,
"s": 9129,
"text": "G: the graph for global airline network. It should be a Graph object in Networkx."
},
{
"code": null,
"e": 9253,
"s": 9211,
"text": "Start_Airport: the airport we start with."
},
{
"code": null,
"e": 9312,
"s": 9253,
"text": "Must_go: a list of airports we must visit during the trip."
},
{
"code": null,
"e": 9381,
"s": 9312,
"text": "Dont_go: a list of airports we do not want to visit during the trip."
},
{
"code": null,
"e": 10091,
"s": 9381,
"text": "With the tool, we can start the plan to travel around the world. Assuming that we start our trip from Atlanta (ATL,) where I am stay in currently. Without putting any Must_go and Dont_go sites, we can visualization the result on the map. The red triangles represent the destination airport we plan to visit and the black dots are where we layover. The trip starts with Atlanta and the first stop is Ernesto Cortissoz International Airport (BAQ) in South America. After that we will fly to TFN in Tenerife, Spain (Europe,) EUN in Western Sahara (Africa,) ADB in Turkey (Asia,) ROR in Palau (Oceania) and come back to Atlanta. As what we want, we have traveled all 6 continents with total distance of 39,905 km."
},
{
"code": null,
"e": 10539,
"s": 10091,
"text": "As shown on previous plan, there are many airports are actually far away from the continents “we think” it should belong to. For example, TFN airport, even though it is under Spain and is part of Europe, it actually closer to Africa. Besides, I would like to be back home, Taipei, during the trip. We can accomplish both goals with Must_go and Dont_go parameters in Globetrotting function. Here is the final plan for me to travel around the world."
},
{
"code": null,
"e": 11009,
"s": 10539,
"text": "In this article, we applied Networkx package to analyze global airline network and using basemap package in matplotlib to visualize the results. As mentioned, Networkx is a powerful analytical package for complex network and provides useful information in difficult scenarios. With the tools, we can plan our trip to travel around the world, which means visiting all 6 continents, under some customized requirements. Also, we can visualize our plan on the map as shown."
},
{
"code": null,
"e": 11250,
"s": 11009,
"text": "However, though we are proficient at Networkx and basemap package now, we are still in shortage of the most important resource, time and money, to actually travel around the world. Therefore, hope all of us have a nice working day tomorrow!"
}
] |
JavaScript | RegExp [0-9] Expression - GeeksforGeeks
|
22 Apr, 2019
The RegExp [0-9] Expression in JavaScript is used to search any digit which is between the brackets. The character inside the brackets can be a single digit or a span of digits.
Syntax:
/[0-9]/
or
new RegExp("[0-9]")
Syntax with modifiers:
/[0-9]/g
or
new RegExp("[0-9]", "g")
Example 1: This example searches the digits between [0-4] in the whole string.
<!DOCTYPE html><html> <head> <title> JavaScript RegExp [0-9] Expression </title></head> <body style="text-align:center"> <h1 style="color:green"> GeeksforGeeks </h1> <h2>RegExp [0-9] Expression</h2> <p>Input String: 1234567890</p> <button onclick="geek()"> Click it! </button> <p id="app"></p> <script> function geek() { var str1 = "123456790"; var regex4 = /[0-4]/g; var match4 = str1.match(regex4); document.getElementById("app").innerHTML = "Found " + match4.length + " matches: " + match4; } </script></body> </html>
Output:Before Clicking the button:After Clicking the button:
Example 2: This example searches the digits between [0-9] in the whole string and replaces the characters with hash(#).
<!DOCTYPE html><html> <head> <title> JavaScript RegExp [0-9] Expression </title></head> <body style="text-align:center"> <h1 style="color:green"> GeeksforGeeks </h1> <h2>RegExp [0-9] Expression</h2> <p>Input String: 128@$%</p> <button onclick="geek()"> Click it! </button> <p id="app"></p> <script> function geek() { var str1 = "128@$%"; var replacement = "#"; var regex4 = new RegExp("[0-9]", "g"); var match4 = str1.replace(regex4, replacement); document.getElementById("app").innerHTML = " New string: " + match4; } </script></body> </html>
Output:Before Clicking the button:After Clicking the button:
Supported Browsers: The browsers supported by RegExp [0-9] Expression are listed below:
Google Chrome
Apple Safari
Mozilla Firefox
Opera
Internet Explorer
JavaScript-RegExp
JavaScript
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Difference between var, let and const keywords in JavaScript
Difference Between PUT and PATCH Request
How to get character array from string in JavaScript?
How to detect browser or tab closing in JavaScript ?
How to get selected value in dropdown list using JavaScript ?
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": 25220,
"s": 25192,
"text": "\n22 Apr, 2019"
},
{
"code": null,
"e": 25398,
"s": 25220,
"text": "The RegExp [0-9] Expression in JavaScript is used to search any digit which is between the brackets. The character inside the brackets can be a single digit or a span of digits."
},
{
"code": null,
"e": 25406,
"s": 25398,
"text": "Syntax:"
},
{
"code": null,
"e": 25415,
"s": 25406,
"text": "/[0-9]/ "
},
{
"code": null,
"e": 25418,
"s": 25415,
"text": "or"
},
{
"code": null,
"e": 25438,
"s": 25418,
"text": "new RegExp(\"[0-9]\")"
},
{
"code": null,
"e": 25461,
"s": 25438,
"text": "Syntax with modifiers:"
},
{
"code": null,
"e": 25471,
"s": 25461,
"text": "/[0-9]/g "
},
{
"code": null,
"e": 25474,
"s": 25471,
"text": "or"
},
{
"code": null,
"e": 25499,
"s": 25474,
"text": "new RegExp(\"[0-9]\", \"g\")"
},
{
"code": null,
"e": 25578,
"s": 25499,
"text": "Example 1: This example searches the digits between [0-4] in the whole string."
},
{
"code": "<!DOCTYPE html><html> <head> <title> JavaScript RegExp [0-9] Expression </title></head> <body style=\"text-align:center\"> <h1 style=\"color:green\"> GeeksforGeeks </h1> <h2>RegExp [0-9] Expression</h2> <p>Input String: 1234567890</p> <button onclick=\"geek()\"> Click it! </button> <p id=\"app\"></p> <script> function geek() { var str1 = \"123456790\"; var regex4 = /[0-4]/g; var match4 = str1.match(regex4); document.getElementById(\"app\").innerHTML = \"Found \" + match4.length + \" matches: \" + match4; } </script></body> </html> ",
"e": 26312,
"s": 25578,
"text": null
},
{
"code": null,
"e": 26373,
"s": 26312,
"text": "Output:Before Clicking the button:After Clicking the button:"
},
{
"code": null,
"e": 26493,
"s": 26373,
"text": "Example 2: This example searches the digits between [0-9] in the whole string and replaces the characters with hash(#)."
},
{
"code": "<!DOCTYPE html><html> <head> <title> JavaScript RegExp [0-9] Expression </title></head> <body style=\"text-align:center\"> <h1 style=\"color:green\"> GeeksforGeeks </h1> <h2>RegExp [0-9] Expression</h2> <p>Input String: 128@$%</p> <button onclick=\"geek()\"> Click it! </button> <p id=\"app\"></p> <script> function geek() { var str1 = \"128@$%\"; var replacement = \"#\"; var regex4 = new RegExp(\"[0-9]\", \"g\"); var match4 = str1.replace(regex4, replacement); document.getElementById(\"app\").innerHTML = \" New string: \" + match4; } </script></body> </html> ",
"e": 27245,
"s": 26493,
"text": null
},
{
"code": null,
"e": 27306,
"s": 27245,
"text": "Output:Before Clicking the button:After Clicking the button:"
},
{
"code": null,
"e": 27394,
"s": 27306,
"text": "Supported Browsers: The browsers supported by RegExp [0-9] Expression are listed below:"
},
{
"code": null,
"e": 27408,
"s": 27394,
"text": "Google Chrome"
},
{
"code": null,
"e": 27421,
"s": 27408,
"text": "Apple Safari"
},
{
"code": null,
"e": 27437,
"s": 27421,
"text": "Mozilla Firefox"
},
{
"code": null,
"e": 27443,
"s": 27437,
"text": "Opera"
},
{
"code": null,
"e": 27461,
"s": 27443,
"text": "Internet Explorer"
},
{
"code": null,
"e": 27479,
"s": 27461,
"text": "JavaScript-RegExp"
},
{
"code": null,
"e": 27490,
"s": 27479,
"text": "JavaScript"
},
{
"code": null,
"e": 27507,
"s": 27490,
"text": "Web Technologies"
},
{
"code": null,
"e": 27605,
"s": 27507,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 27614,
"s": 27605,
"text": "Comments"
},
{
"code": null,
"e": 27627,
"s": 27614,
"text": "Old Comments"
},
{
"code": null,
"e": 27688,
"s": 27627,
"text": "Difference between var, let and const keywords in JavaScript"
},
{
"code": null,
"e": 27729,
"s": 27688,
"text": "Difference Between PUT and PATCH Request"
},
{
"code": null,
"e": 27783,
"s": 27729,
"text": "How to get character array from string in JavaScript?"
},
{
"code": null,
"e": 27836,
"s": 27783,
"text": "How to detect browser or tab closing in JavaScript ?"
},
{
"code": null,
"e": 27898,
"s": 27836,
"text": "How to get selected value in dropdown list using JavaScript ?"
},
{
"code": null,
"e": 27940,
"s": 27898,
"text": "Roadmap to Become a Web Developer in 2022"
},
{
"code": null,
"e": 27973,
"s": 27940,
"text": "Installation of Node.js on Linux"
},
{
"code": null,
"e": 28035,
"s": 27973,
"text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills"
},
{
"code": null,
"e": 28078,
"s": 28035,
"text": "How to fetch data from an API in ReactJS ?"
}
] |
Array Basics Shell Scripting | Set 2 (Using Loops) - GeeksforGeeks
|
10 Jul, 2018
It is recommended to go through Array Basics Shell Scripting | Set-1IntroductionSuppose you want to repeat a particular task so many times then it is a better to use loops. Mostly all languages provides the concept of loops. In Bourne Shell there are two types of loops i.e for loop andwhile loop.
To Print the Static Array in Bash
1. By Using while-loop
${#arr[@]} is used to find the size of Array.
# !/bin/bash# To declare static Array arr=(1 12 31 4 5)i=0 # Loop upto size of array# starting from index, i=0while [ $i -lt ${#arr[@]} ]do # To print index, ith # element echo ${arr[$i]} # Increment the i = i + 1 i=`expr $i + 1`done
Output:
1
2
3
4
5
2. By Using for-loop
# !/bin/bash# To declare static Array arr=(1 2 3 4 5) # loops iterate through a # set of values until the# list (arr) is exhaustedfor i in "${arr[@]}"do # access each element # as $i echo $idone
Output:
1
2
3
4
5
To Read the array elements at run time and then Print the Array.
1. Using While-loop
# !/bin/bash# To input array at run# time by using while-loop # echo -n is used to print# message without new lineecho -n "Enter the Total numbers :"read necho "Enter numbers :"i=0 # Read upto the size of # given array starting from# index, i=0while [ $i -lt $n ]do # To input from user read a[$i] # Increment the i = i + 1 i=`expr $i + 1`done # To print array values # starting from index, i=0echo "Output :"i=0 while [ $i -lt $n ]do echo ${a[$i]} # To increment index # by 1, i=i+1 i=`expr $i + 1`done
Output:
Enter the Total numbers :3
Enter numbers :
1
3
5
Output :
1
3
5
2. Using for-loop
# !/bin/bash# To input array at run # time by using for-loop echo -n "Enter the Total numbers :"read necho "Enter numbers:"i=0 # Read upto the size of # given array starting # from index, i=0while [ $i -lt $n ]do # To input from user read a[$i] # To increment index # by 1, i=i+1 i=`expr $i + 1`done # Print the array starting# from index, i=0echo "Output :" for i in "${a[@]}"do # access each element as $i echo $i done
Output:
Enter the Total numbers :3
Enter numbers :
1
3
5
Output :
1
3
5
Shell Script
Linux-Unix
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
TCP Server-Client implementation in C
tar command in Linux with examples
curl command in Linux with Examples
Conditional Statements | Shell Script
Tail command in Linux with examples
UDP Server-Client implementation in C
Cat command in Linux with examples
touch command in Linux with Examples
scp command in Linux with Examples
echo command in Linux with Examples
|
[
{
"code": null,
"e": 25407,
"s": 25379,
"text": "\n10 Jul, 2018"
},
{
"code": null,
"e": 25705,
"s": 25407,
"text": "It is recommended to go through Array Basics Shell Scripting | Set-1IntroductionSuppose you want to repeat a particular task so many times then it is a better to use loops. Mostly all languages provides the concept of loops. In Bourne Shell there are two types of loops i.e for loop andwhile loop."
},
{
"code": null,
"e": 25739,
"s": 25705,
"text": "To Print the Static Array in Bash"
},
{
"code": null,
"e": 25762,
"s": 25739,
"text": "1. By Using while-loop"
},
{
"code": null,
"e": 25808,
"s": 25762,
"text": "${#arr[@]} is used to find the size of Array."
},
{
"code": "# !/bin/bash# To declare static Array arr=(1 12 31 4 5)i=0 # Loop upto size of array# starting from index, i=0while [ $i -lt ${#arr[@]} ]do # To print index, ith # element echo ${arr[$i]} # Increment the i = i + 1 i=`expr $i + 1`done",
"e": 26064,
"s": 25808,
"text": null
},
{
"code": null,
"e": 26072,
"s": 26064,
"text": "Output:"
},
{
"code": null,
"e": 26082,
"s": 26072,
"text": "1\n2\n3\n4\n5"
},
{
"code": null,
"e": 26103,
"s": 26082,
"text": "2. By Using for-loop"
},
{
"code": "# !/bin/bash# To declare static Array arr=(1 2 3 4 5) # loops iterate through a # set of values until the# list (arr) is exhaustedfor i in \"${arr[@]}\"do # access each element # as $i echo $idone",
"e": 26309,
"s": 26103,
"text": null
},
{
"code": null,
"e": 26317,
"s": 26309,
"text": "Output:"
},
{
"code": null,
"e": 26327,
"s": 26317,
"text": "1\n2\n3\n4\n5"
},
{
"code": null,
"e": 26392,
"s": 26327,
"text": "To Read the array elements at run time and then Print the Array."
},
{
"code": null,
"e": 26412,
"s": 26392,
"text": "1. Using While-loop"
},
{
"code": "# !/bin/bash# To input array at run# time by using while-loop # echo -n is used to print# message without new lineecho -n \"Enter the Total numbers :\"read necho \"Enter numbers :\"i=0 # Read upto the size of # given array starting from# index, i=0while [ $i -lt $n ]do # To input from user read a[$i] # Increment the i = i + 1 i=`expr $i + 1`done # To print array values # starting from index, i=0echo \"Output :\"i=0 while [ $i -lt $n ]do echo ${a[$i]} # To increment index # by 1, i=i+1 i=`expr $i + 1`done",
"e": 26949,
"s": 26412,
"text": null
},
{
"code": null,
"e": 26957,
"s": 26949,
"text": "Output:"
},
{
"code": null,
"e": 27021,
"s": 26957,
"text": "Enter the Total numbers :3\nEnter numbers :\n1\n3\n5\nOutput :\n1\n3\n5"
},
{
"code": null,
"e": 27039,
"s": 27021,
"text": "2. Using for-loop"
},
{
"code": "# !/bin/bash# To input array at run # time by using for-loop echo -n \"Enter the Total numbers :\"read necho \"Enter numbers:\"i=0 # Read upto the size of # given array starting # from index, i=0while [ $i -lt $n ]do # To input from user read a[$i] # To increment index # by 1, i=i+1 i=`expr $i + 1`done # Print the array starting# from index, i=0echo \"Output :\" for i in \"${a[@]}\"do # access each element as $i echo $i done",
"e": 27488,
"s": 27039,
"text": null
},
{
"code": null,
"e": 27496,
"s": 27488,
"text": "Output:"
},
{
"code": null,
"e": 27560,
"s": 27496,
"text": "Enter the Total numbers :3\nEnter numbers :\n1\n3\n5\nOutput :\n1\n3\n5"
},
{
"code": null,
"e": 27573,
"s": 27560,
"text": "Shell Script"
},
{
"code": null,
"e": 27584,
"s": 27573,
"text": "Linux-Unix"
},
{
"code": null,
"e": 27682,
"s": 27584,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 27720,
"s": 27682,
"text": "TCP Server-Client implementation in C"
},
{
"code": null,
"e": 27755,
"s": 27720,
"text": "tar command in Linux with examples"
},
{
"code": null,
"e": 27791,
"s": 27755,
"text": "curl command in Linux with Examples"
},
{
"code": null,
"e": 27829,
"s": 27791,
"text": "Conditional Statements | Shell Script"
},
{
"code": null,
"e": 27865,
"s": 27829,
"text": "Tail command in Linux with examples"
},
{
"code": null,
"e": 27903,
"s": 27865,
"text": "UDP Server-Client implementation in C"
},
{
"code": null,
"e": 27938,
"s": 27903,
"text": "Cat command in Linux with examples"
},
{
"code": null,
"e": 27975,
"s": 27938,
"text": "touch command in Linux with Examples"
},
{
"code": null,
"e": 28010,
"s": 27975,
"text": "scp command in Linux with Examples"
}
] |
What are techniques to detect anomalies | Towards Data Science
|
Anomaly detection is the identification of rare items, events, or observations that raise suspicions by differing significantly from the majority of the data. Typically the anomalous items will translate to some kind of problem such as credit card fraud, network intrusion, medical diagnostic, system health monitor.
Anomaly detection works on two basic premise
Anomalies only occur very rarely in the data.
Their features differ from normal instances significantly.
The simplest approach to identifying irregularities in data is to flag the data points that deviate from common statistical properties of distribution, including mean, median, mode, and quartiles.
One of the most popular ways is the Interquartile Range (IQR). IQR is a concept in statistics that is used to measure the statistical dispersion and data variability by dividing the dataset into quartiles.
In simple words, any dataset or any set of observations is divided into four defined intervals based upon the values of the data and how they compare to the entire dataset. A quartile is what divides the data into three points and four intervals.
Image Source: Wikipedia
Interquartile Range (IQR) is important because it is used to define the outliers. It is the difference between the third quartile and the first quartile (IQR = Q3 -Q1). Outliers, in this case, are defined as the observations that are below (Q1 − 1.5x IQR) or above (Q3 + 1.5x IQR)
Image Source: Wikipedia
np.percentile is baked functionality in Python
q75, q25 = np.percentile(x, [75 ,25])iqr = q75 - q25
IQR technique doesn’t work in the following scenarios
The pattern is based on seasonality. This involves more sophisticated methods, such as decomposing the data into multiple trends to identify the change in seasonality.
The pattern is based on seasonality. This involves more sophisticated methods, such as decomposing the data into multiple trends to identify the change in seasonality.
2. The definition of abnormal or normal may frequently change, as malicious adversaries constantly adapt themselves
Clustering is one of the most popular concepts in the domain of unsupervised learning. The underlying premise is similar data points tend to belong to similar groups or clusters, as determined by their distance from local centroids.
K-means is a widely used clustering algorithm. It creates ‘k’ similar clusters of data points. Data instances that fall outside of these groups could potentially be marked as anomalies. Other clustering algorithms such as hierarchal clustering and DB scan can also be used to detect outliers.
The way the K-means algorithm works is as follows:
Specify the number of clusters K.Initialize centroids by first shuffling the dataset and then randomly selecting K data points for the centroids without replacement.Calculate distances between the centroids and the data points.Keep iterating until there is no change to the centroids. i.e assignment of data points to clusters isn’t changing.
Specify the number of clusters K.
Initialize centroids by first shuffling the dataset and then randomly selecting K data points for the centroids without replacement.
Calculate distances between the centroids and the data points.
Keep iterating until there is no change to the centroids. i.e assignment of data points to clusters isn’t changing.
Initialize random centroids
Initialize random centroids
You start the process by taking three(as we decided K to be 3) random points (in the form of (x, y)). These points are called centroids which is just a fancy name for denoting centers. Let’s name these three points — C1, C2, and C3 so that you can refer them later.
2. Calculate distances between the centroids and the data points
Next, you measure the distances of the data points from these three randomly chosen points. A very popular choice of distance measurement function, in this case, is the Euclidean distance.
Briefly, if there are n points on a 2D space(just like the above figure) and their coordinates are denoted by (x_i, y_i), then the Euclidean distance between any two points ((x1, y1) and(x2, y2)) on this space is given by:
Suppose the coordinates of C1, C2 and C3 are — (-1, 4), (-0.2, 1.5), and (2, 2.5) respectively. Let’s now write a few lines of Python code which will calculate the Euclidean distances between the data-points and these randomly chosen centroids. We start by initializing the centroids.
# Initialize the centroidsc1 = (-1, 4)c2 = (-0.2, 1.5)c3 = (2, 2.5)
Next, we write a small helper function to calculate the Euclidean distances between the data points and centroids.
# A helper function to calculate the Euclidean distance between the data points and the centroidsdef calculate_distance(centroid, X, Y): distances = [] # Unpack the x and y coordinates of the centroid c_x, c_y = centroid # Iterate over the data points and calculate the distance using the # given formula for x, y in list(zip(X, Y)): root_diff_x = (x - c_x) ** 2 root_diff_y = (y - c_y) ** 2 distance = np.sqrt(root_diff_x + root_diff_y) distances.append(distance) return distances
We can now apply this function to the data points and assign the results accordingly.
# Calculate the distance and assign them to the DataFrame accordinglydata['C1_Distance'] = calculate_distance(c1, data.X_value, data.Y_value)data['C2_Distance'] = calculate_distance(c2, data.X_value, data.Y_value)data['C3_Distance'] = calculate_distance(c3, data.X_value, data.Y_value)# Preview the dataprint(data.head())
3. Compare, assign, mean and repeat
This is fundamentally the last step of the K-Means clustering algorithm. Once you have the distances between the data points and the centroids, you compare the distances and take the smallest ones. The centroid to which the distance for a particular data point is the smallest, that centroid gets assigned as the cluster for that particular data point.
Let’s do this programmatically.
# Get the minimum distance centroids data['Cluster'] = data[['C1_Distance', 'C2_Distance', 'C3_Distance']].apply(np.argmin, axis =1) # Map the centroids accordingly and rename them data['Cluster'] = data['Cluster'].map({'C1_Distance': 'C1', 'C2_Distance': 'C2', 'C3_Distance': 'C3'}) # Get a preview of the data print(data.head(10))
Now comes the most interesting part of updating the centroids by determining the mean values of the coordinates of the data points (which should be belonging to some centroid by now). Hence the name K-Means. This is how the mean calculation looks like:
The following lines of code do this for you:
# Calculate the coordinates of the new centroid from cluster 1x_new_centroid1 = data[data['Cluster']=='C1']['X_value'].mean()y_new_centroid1 = data[data['Cluster']=='C1']['Y_value'].mean()# Calculate the coordinates of the new centroid from cluster 2x_new_centroid2 = data[data['Cluster']=='C3']['X_value'].mean()y_new_centroid2 = data[data['Cluster']=='C3']['Y_value'].mean()# Print the coordinates of the new centroidsprint('Centroid 1 ({}, {})'.format(x_new_centroid1, y_new_centroid1))print('Centroid 2 ({}, {})'.format(x_new_centroid2, y_new_centroid2))
This process is repeated until the coordinates of the centroids do not get updated anymore.
K-means algorithm is popular and used in a variety of applications such as image compression, document classification. The goal of K-mean is to group data points into distinct non-overlapping subgroups. It does a very good job when the clusters have a kind of spherical shape. However, it suffers as the geometric shapes of clusters deviate from spherical shapes. Moreover, it also doesn’t learn the number of clusters from the data and requires it to be pre-defined.
Isolation Forest is an unsupervised learning algorithm that belongs to the ensemble decision trees family. This approach is different from all previous methods. All the previous ones were trying to find the normal region of the data then identifies anything outside of this defined region to be an outlier or anomalous. This method works differently. It explicitly isolates anomalies instead of profiling and constructing normal points and regions by assigning a score to each data point. It takes advantage of the fact that anomalies are the minority data points and that they have attribute-values that are very different from those of normal instances.
IsolationForest ‘isolates’ observations by randomly selecting a feature and then randomly selecting a split value between the maximum and minimum values of the selected feature.
Since recursive partitioning can be represented by a tree structure, the number of splittings required to isolate a sample is equivalent to the path length from the root node to the terminating node.
This path length averaged over a forest of such random trees, is a measure of normality and our decision function.
Random partitioning produces noticeable shorter paths for anomalies. Hence, when a forest of random trees collectively produces shorter path lengths for particular samples, they are highly likely to be anomalies.
This algorithm works great with very high dimensional datasets and it proved to be a very effective way of detecting anomalies.
This paper covers full details on how isolation forest works.
import numpy as npimport matplotlib.pyplot as pltfrom sklearn.ensemble import IsolationForestrng = np.random.RandomState(42)# Generate train dataX = 0.3 * rng.randn(100, 2)X_train = np.r_[X + 2, X - 2]# Generate some regular novel observationsX = 0.3 * rng.randn(20, 2)X_test = np.r_[X + 2, X - 2]# Generate some abnormal novel observationsX_outliers = rng.uniform(low=-4, high=4, size=(20, 2))# fit the modelclf = IsolationForest(max_samples=100, random_state=rng)clf.fit(X_train)y_pred_train = clf.predict(X_train)y_pred_test = clf.predict(X_test)y_pred_outliers = clf.predict(X_outliers)# plot the line, the samples, and the nearest vectors to the planexx, yy = np.meshgrid(np.linspace(-5, 5, 50), np.linspace(-5, 5, 50))Z = clf.decision_function(np.c_[xx.ravel(), yy.ravel()])Z = Z.reshape(xx.shape)plt.title("IsolationForest")plt.contourf(xx, yy, Z, cmap=plt.cm.Blues_r)b1 = plt.scatter(X_train[:, 0], X_train[:, 1], c='white', s=20, edgecolor='k')b2 = plt.scatter(X_test[:, 0], X_test[:, 1], c='green', s=20, edgecolor='k')c = plt.scatter(X_outliers[:, 0], X_outliers[:, 1], c='red', s=20, edgecolor='k')plt.axis('tight')plt.xlim((-5, 5))plt.ylim((-5, 5))plt.legend([b1, b2, c], ["training observations", "new regular observations", "new abnormal observations"], loc="upper left")plt.show()
Source: scikit-learn.org
This post provides an overview of different techniques to detect anomalies in data. It ranges from the usage of simple statistical methods like standard deviation to the unsupervised learning algorithms like Isolation Forest. Every method has its advantages and disadvantages. E.g. Interquartile (IQR) doesn’t work for seasonal patterns, K-Means clustering is good at grouping data into distinct non-overlapping subgroups. It does a very good job when the clusters have a kind of spherical shape. Isolation Forest offers a contrarian approach to detect anomalies. It takes advantage of the fact that anomalies are the minority data points and that they have attribute-values that are very different from those of normal instances. To be a good practitioner, it’s good to know the assumptions behind algorithms/methods so that you would have a pretty good idea about the strength and weaknesses of each method. This will help you decide when to use each method and under what circumstances.
|
[
{
"code": null,
"e": 489,
"s": 172,
"text": "Anomaly detection is the identification of rare items, events, or observations that raise suspicions by differing significantly from the majority of the data. Typically the anomalous items will translate to some kind of problem such as credit card fraud, network intrusion, medical diagnostic, system health monitor."
},
{
"code": null,
"e": 534,
"s": 489,
"text": "Anomaly detection works on two basic premise"
},
{
"code": null,
"e": 580,
"s": 534,
"text": "Anomalies only occur very rarely in the data."
},
{
"code": null,
"e": 639,
"s": 580,
"text": "Their features differ from normal instances significantly."
},
{
"code": null,
"e": 836,
"s": 639,
"text": "The simplest approach to identifying irregularities in data is to flag the data points that deviate from common statistical properties of distribution, including mean, median, mode, and quartiles."
},
{
"code": null,
"e": 1042,
"s": 836,
"text": "One of the most popular ways is the Interquartile Range (IQR). IQR is a concept in statistics that is used to measure the statistical dispersion and data variability by dividing the dataset into quartiles."
},
{
"code": null,
"e": 1289,
"s": 1042,
"text": "In simple words, any dataset or any set of observations is divided into four defined intervals based upon the values of the data and how they compare to the entire dataset. A quartile is what divides the data into three points and four intervals."
},
{
"code": null,
"e": 1313,
"s": 1289,
"text": "Image Source: Wikipedia"
},
{
"code": null,
"e": 1594,
"s": 1313,
"text": "Interquartile Range (IQR) is important because it is used to define the outliers. It is the difference between the third quartile and the first quartile (IQR = Q3 -Q1). Outliers, in this case, are defined as the observations that are below (Q1 − 1.5x IQR) or above (Q3 + 1.5x IQR)"
},
{
"code": null,
"e": 1618,
"s": 1594,
"text": "Image Source: Wikipedia"
},
{
"code": null,
"e": 1665,
"s": 1618,
"text": "np.percentile is baked functionality in Python"
},
{
"code": null,
"e": 1718,
"s": 1665,
"text": "q75, q25 = np.percentile(x, [75 ,25])iqr = q75 - q25"
},
{
"code": null,
"e": 1772,
"s": 1718,
"text": "IQR technique doesn’t work in the following scenarios"
},
{
"code": null,
"e": 1940,
"s": 1772,
"text": "The pattern is based on seasonality. This involves more sophisticated methods, such as decomposing the data into multiple trends to identify the change in seasonality."
},
{
"code": null,
"e": 2108,
"s": 1940,
"text": "The pattern is based on seasonality. This involves more sophisticated methods, such as decomposing the data into multiple trends to identify the change in seasonality."
},
{
"code": null,
"e": 2224,
"s": 2108,
"text": "2. The definition of abnormal or normal may frequently change, as malicious adversaries constantly adapt themselves"
},
{
"code": null,
"e": 2457,
"s": 2224,
"text": "Clustering is one of the most popular concepts in the domain of unsupervised learning. The underlying premise is similar data points tend to belong to similar groups or clusters, as determined by their distance from local centroids."
},
{
"code": null,
"e": 2750,
"s": 2457,
"text": "K-means is a widely used clustering algorithm. It creates ‘k’ similar clusters of data points. Data instances that fall outside of these groups could potentially be marked as anomalies. Other clustering algorithms such as hierarchal clustering and DB scan can also be used to detect outliers."
},
{
"code": null,
"e": 2801,
"s": 2750,
"text": "The way the K-means algorithm works is as follows:"
},
{
"code": null,
"e": 3144,
"s": 2801,
"text": "Specify the number of clusters K.Initialize centroids by first shuffling the dataset and then randomly selecting K data points for the centroids without replacement.Calculate distances between the centroids and the data points.Keep iterating until there is no change to the centroids. i.e assignment of data points to clusters isn’t changing."
},
{
"code": null,
"e": 3178,
"s": 3144,
"text": "Specify the number of clusters K."
},
{
"code": null,
"e": 3311,
"s": 3178,
"text": "Initialize centroids by first shuffling the dataset and then randomly selecting K data points for the centroids without replacement."
},
{
"code": null,
"e": 3374,
"s": 3311,
"text": "Calculate distances between the centroids and the data points."
},
{
"code": null,
"e": 3490,
"s": 3374,
"text": "Keep iterating until there is no change to the centroids. i.e assignment of data points to clusters isn’t changing."
},
{
"code": null,
"e": 3518,
"s": 3490,
"text": "Initialize random centroids"
},
{
"code": null,
"e": 3546,
"s": 3518,
"text": "Initialize random centroids"
},
{
"code": null,
"e": 3812,
"s": 3546,
"text": "You start the process by taking three(as we decided K to be 3) random points (in the form of (x, y)). These points are called centroids which is just a fancy name for denoting centers. Let’s name these three points — C1, C2, and C3 so that you can refer them later."
},
{
"code": null,
"e": 3877,
"s": 3812,
"text": "2. Calculate distances between the centroids and the data points"
},
{
"code": null,
"e": 4066,
"s": 3877,
"text": "Next, you measure the distances of the data points from these three randomly chosen points. A very popular choice of distance measurement function, in this case, is the Euclidean distance."
},
{
"code": null,
"e": 4289,
"s": 4066,
"text": "Briefly, if there are n points on a 2D space(just like the above figure) and their coordinates are denoted by (x_i, y_i), then the Euclidean distance between any two points ((x1, y1) and(x2, y2)) on this space is given by:"
},
{
"code": null,
"e": 4574,
"s": 4289,
"text": "Suppose the coordinates of C1, C2 and C3 are — (-1, 4), (-0.2, 1.5), and (2, 2.5) respectively. Let’s now write a few lines of Python code which will calculate the Euclidean distances between the data-points and these randomly chosen centroids. We start by initializing the centroids."
},
{
"code": null,
"e": 4642,
"s": 4574,
"text": "# Initialize the centroidsc1 = (-1, 4)c2 = (-0.2, 1.5)c3 = (2, 2.5)"
},
{
"code": null,
"e": 4757,
"s": 4642,
"text": "Next, we write a small helper function to calculate the Euclidean distances between the data points and centroids."
},
{
"code": null,
"e": 5319,
"s": 4757,
"text": "# A helper function to calculate the Euclidean distance between the data points and the centroidsdef calculate_distance(centroid, X, Y): distances = [] # Unpack the x and y coordinates of the centroid c_x, c_y = centroid # Iterate over the data points and calculate the distance using the # given formula for x, y in list(zip(X, Y)): root_diff_x = (x - c_x) ** 2 root_diff_y = (y - c_y) ** 2 distance = np.sqrt(root_diff_x + root_diff_y) distances.append(distance) return distances"
},
{
"code": null,
"e": 5405,
"s": 5319,
"text": "We can now apply this function to the data points and assign the results accordingly."
},
{
"code": null,
"e": 5727,
"s": 5405,
"text": "# Calculate the distance and assign them to the DataFrame accordinglydata['C1_Distance'] = calculate_distance(c1, data.X_value, data.Y_value)data['C2_Distance'] = calculate_distance(c2, data.X_value, data.Y_value)data['C3_Distance'] = calculate_distance(c3, data.X_value, data.Y_value)# Preview the dataprint(data.head())"
},
{
"code": null,
"e": 5763,
"s": 5727,
"text": "3. Compare, assign, mean and repeat"
},
{
"code": null,
"e": 6116,
"s": 5763,
"text": "This is fundamentally the last step of the K-Means clustering algorithm. Once you have the distances between the data points and the centroids, you compare the distances and take the smallest ones. The centroid to which the distance for a particular data point is the smallest, that centroid gets assigned as the cluster for that particular data point."
},
{
"code": null,
"e": 6148,
"s": 6116,
"text": "Let’s do this programmatically."
},
{
"code": null,
"e": 6496,
"s": 6148,
"text": "# Get the minimum distance centroids data['Cluster'] = data[['C1_Distance', 'C2_Distance', 'C3_Distance']].apply(np.argmin, axis =1) # Map the centroids accordingly and rename them data['Cluster'] = data['Cluster'].map({'C1_Distance': 'C1', 'C2_Distance': 'C2', 'C3_Distance': 'C3'}) # Get a preview of the data print(data.head(10))"
},
{
"code": null,
"e": 6749,
"s": 6496,
"text": "Now comes the most interesting part of updating the centroids by determining the mean values of the coordinates of the data points (which should be belonging to some centroid by now). Hence the name K-Means. This is how the mean calculation looks like:"
},
{
"code": null,
"e": 6794,
"s": 6749,
"text": "The following lines of code do this for you:"
},
{
"code": null,
"e": 7353,
"s": 6794,
"text": "# Calculate the coordinates of the new centroid from cluster 1x_new_centroid1 = data[data['Cluster']=='C1']['X_value'].mean()y_new_centroid1 = data[data['Cluster']=='C1']['Y_value'].mean()# Calculate the coordinates of the new centroid from cluster 2x_new_centroid2 = data[data['Cluster']=='C3']['X_value'].mean()y_new_centroid2 = data[data['Cluster']=='C3']['Y_value'].mean()# Print the coordinates of the new centroidsprint('Centroid 1 ({}, {})'.format(x_new_centroid1, y_new_centroid1))print('Centroid 2 ({}, {})'.format(x_new_centroid2, y_new_centroid2))"
},
{
"code": null,
"e": 7445,
"s": 7353,
"text": "This process is repeated until the coordinates of the centroids do not get updated anymore."
},
{
"code": null,
"e": 7913,
"s": 7445,
"text": "K-means algorithm is popular and used in a variety of applications such as image compression, document classification. The goal of K-mean is to group data points into distinct non-overlapping subgroups. It does a very good job when the clusters have a kind of spherical shape. However, it suffers as the geometric shapes of clusters deviate from spherical shapes. Moreover, it also doesn’t learn the number of clusters from the data and requires it to be pre-defined."
},
{
"code": null,
"e": 8569,
"s": 7913,
"text": "Isolation Forest is an unsupervised learning algorithm that belongs to the ensemble decision trees family. This approach is different from all previous methods. All the previous ones were trying to find the normal region of the data then identifies anything outside of this defined region to be an outlier or anomalous. This method works differently. It explicitly isolates anomalies instead of profiling and constructing normal points and regions by assigning a score to each data point. It takes advantage of the fact that anomalies are the minority data points and that they have attribute-values that are very different from those of normal instances."
},
{
"code": null,
"e": 8747,
"s": 8569,
"text": "IsolationForest ‘isolates’ observations by randomly selecting a feature and then randomly selecting a split value between the maximum and minimum values of the selected feature."
},
{
"code": null,
"e": 8947,
"s": 8747,
"text": "Since recursive partitioning can be represented by a tree structure, the number of splittings required to isolate a sample is equivalent to the path length from the root node to the terminating node."
},
{
"code": null,
"e": 9062,
"s": 8947,
"text": "This path length averaged over a forest of such random trees, is a measure of normality and our decision function."
},
{
"code": null,
"e": 9275,
"s": 9062,
"text": "Random partitioning produces noticeable shorter paths for anomalies. Hence, when a forest of random trees collectively produces shorter path lengths for particular samples, they are highly likely to be anomalies."
},
{
"code": null,
"e": 9403,
"s": 9275,
"text": "This algorithm works great with very high dimensional datasets and it proved to be a very effective way of detecting anomalies."
},
{
"code": null,
"e": 9465,
"s": 9403,
"text": "This paper covers full details on how isolation forest works."
},
{
"code": null,
"e": 10840,
"s": 9465,
"text": "import numpy as npimport matplotlib.pyplot as pltfrom sklearn.ensemble import IsolationForestrng = np.random.RandomState(42)# Generate train dataX = 0.3 * rng.randn(100, 2)X_train = np.r_[X + 2, X - 2]# Generate some regular novel observationsX = 0.3 * rng.randn(20, 2)X_test = np.r_[X + 2, X - 2]# Generate some abnormal novel observationsX_outliers = rng.uniform(low=-4, high=4, size=(20, 2))# fit the modelclf = IsolationForest(max_samples=100, random_state=rng)clf.fit(X_train)y_pred_train = clf.predict(X_train)y_pred_test = clf.predict(X_test)y_pred_outliers = clf.predict(X_outliers)# plot the line, the samples, and the nearest vectors to the planexx, yy = np.meshgrid(np.linspace(-5, 5, 50), np.linspace(-5, 5, 50))Z = clf.decision_function(np.c_[xx.ravel(), yy.ravel()])Z = Z.reshape(xx.shape)plt.title(\"IsolationForest\")plt.contourf(xx, yy, Z, cmap=plt.cm.Blues_r)b1 = plt.scatter(X_train[:, 0], X_train[:, 1], c='white', s=20, edgecolor='k')b2 = plt.scatter(X_test[:, 0], X_test[:, 1], c='green', s=20, edgecolor='k')c = plt.scatter(X_outliers[:, 0], X_outliers[:, 1], c='red', s=20, edgecolor='k')plt.axis('tight')plt.xlim((-5, 5))plt.ylim((-5, 5))plt.legend([b1, b2, c], [\"training observations\", \"new regular observations\", \"new abnormal observations\"], loc=\"upper left\")plt.show()"
},
{
"code": null,
"e": 10865,
"s": 10840,
"text": "Source: scikit-learn.org"
}
] |
How to rename columns in Pandas DataFrame
|
01 Jul, 2022
Given a Pandas DataFrame, let’s see how to rename columns in Pandas with examples. Here, we will discuss 6 different ways to rename column names in pandas DataFrame.
About Pandas DataFrame:
Pandas DataFrame is a rectangular grid that is used to store data. It is easy to visualize and work with data when stored in dataFrame.
It consists of rows and columns.
Each row is a measurement of some instance while the column is a vector that contains data for some specific attribute/variable.
Each Dataframe column has homogeneous data throughout any specific column but Dataframe rows can contain homogeneous or heterogeneous data throughout any specific row.
Unlike two-dimensional arrays, pandas’ Dataframe axes are labeled.
One way of renaming the columns in a Pandas Dataframe is by using the rename() function. This method is quite useful when we need to rename some selected columns because we need to specify information only for the columns which are to be renamed.
Example 1: Rename a single column.
Python3
# Import pandas packageimport pandas as pd # Define a dictionary containing ICC rankingsrankings = {'test': ['India', 'South Africa', 'England', 'New Zealand', 'Australia'], 'odi': ['England', 'India', 'New Zealand', 'South Africa', 'Pakistan'], 't20': ['Pakistan', 'India', 'Australia', 'England', 'New Zealand']} # Convert the dictionary into DataFramerankings_pd = pd.DataFrame(rankings) # Before renaming the columnsprint(rankings_pd) rankings_pd.rename(columns = {'test':'TEST'}, inplace = True) # After renaming the columnsprint("\nAfter modifying first column:\n", rankings_pd.columns)
Output:
Example 2: Rename multiple columns.
Python3
# Import pandas packageimport pandas as pd # Define a dictionary containing ICC rankingsrankings = {'test': ['India', 'South Africa', 'England', 'New Zealand', 'Australia'], 'odi': ['England', 'India', 'New Zealand', 'South Africa', 'Pakistan'], 't20': ['Pakistan', 'India', 'Australia', 'England', 'New Zealand']} # Convert the dictionary into DataFramerankings_pd = pd.DataFrame(rankings) # Before renaming the columnsprint(rankings_pd.columns) rankings_pd.rename(columns = {'test':'TEST', 'odi':'ODI', 't20':'T20'}, inplace = True) # After renaming the columnsprint(rankings_pd.columns)
Output:
The columns can also be renamed by directly assigning a list containing the new names to the columns attribute of the Dataframe object for which we want to rename the columns. The disadvantage of this method is that we need to provide new names for all the columns even if want to rename only some of the columns.
Python3
# Import pandas packageimport pandas as pd # Define a dictionary containing ICC rankingsrankings = {'test': ['India', 'South Africa', 'England', 'New Zealand', 'Australia'], 'odi': ['England', 'India', 'New Zealand', 'South Africa', 'Pakistan'], 't20': ['Pakistan', 'India', 'Australia', 'England', 'New Zealand']} # Convert the dictionary into DataFramerankings_pd = pd.DataFrame(rankings) # Before renaming the columnsprint(rankings_pd.columns) rankings_pd.columns = ['TEST', 'ODI', 'T-20'] # After renaming the columnsprint(rankings_pd.columns)
Output:
In this example, we will rename the column name using the set_axis function, we will pass the new column name and axis that should be replaced with a new name in the column as a parameter.
Python3
# Import pandas packageimport pandas as pd # Define a dictionary containing ICC rankingsrankings = {'test': ['India', 'South Africa', 'England', 'New Zealand', 'Australia'], 'odi': ['England', 'India', 'New Zealand', 'South Africa', 'Pakistan'], 't20': ['Pakistan', 'India', 'Australia', 'England', 'New Zealand']} # Convert the dictionary into DataFramerankings_pd = pd.DataFrame(rankings) # Before renaming the columnsprint(rankings_pd.columns) rankings_pd.set_axis(['A', 'B', 'C'], axis='columns', inplace=True) # After renaming the columnsprint(rankings_pd.columns)rankings_pd.head()
Output:
In this example, we will rename the column name using the add_Sufix and add_Prefix function, we will pass the prefix and suffix that should be added to the first and last name of the column name.
Python3
# Import pandas packageimport pandas as pd # Define a dictionary containing ICC rankingsrankings = {'test': ['India', 'South Africa', 'England', 'New Zealand', 'Australia'], 'odi': ['England', 'India', 'New Zealand', 'South Africa', 'Pakistan'], 't20': ['Pakistan', 'India', 'Australia', 'England', 'New Zealand']} # Convert the dictionary into DataFramerankings_pd = pd.DataFrame(rankings) # Before renaming the columnsprint(rankings_pd.columns) rankings_pd = rankings_pd.add_prefix('col_')rankings_pd = rankings_pd.add_suffix('_1') # After renaming the columnsrankings_pd.head()
Output:
col_test_1 col_odi_1 col_t20_1
0 India England Pakistan
1 South Africa India India
2 England New Zealand Australia
3 New Zealand South Africa England
4 Australia Pakistan New Zealand
In this example, we will rename the column name using the replace function, we will pass the old name with the new name as a parameter for the column.
Python3
# Import pandas packageimport pandas as pd # Define a dictionary containing ICC rankingsrankings = {'test': ['India', 'South Africa', 'England', 'New Zealand', 'Australia'], 'odi': ['England', 'India', 'New Zealand', 'South Africa', 'Pakistan'], 't20': ['Pakistan', 'India', 'Australia', 'England', 'New Zealand']} # Convert the dictionary into DataFramerankings_pd = pd.DataFrame(rankings) # Before renaming the columnsprint(rankings_pd.columns)# df = rankings_pd rankings_pd.columns = rankings_pd.columns.str.replace('test', 'Col_TEST')rankings_pd.columns = rankings_pd.columns.str.replace('odi', 'Col_ODI')rankings_pd.columns = rankings_pd.columns.str.replace('t20', 'Col_T20') rankings_pd.head()
Output:
surajkumarguptaintern
pandas-dataframe-program
Picked
Python pandas-dataFrame
Python-pandas
Technical Scripter 2018
Python
Technical Scripter
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
|
[
{
"code": null,
"e": 53,
"s": 25,
"text": "\n01 Jul, 2022"
},
{
"code": null,
"e": 219,
"s": 53,
"text": "Given a Pandas DataFrame, let’s see how to rename columns in Pandas with examples. Here, we will discuss 6 different ways to rename column names in pandas DataFrame."
},
{
"code": null,
"e": 244,
"s": 219,
"text": "About Pandas DataFrame: "
},
{
"code": null,
"e": 380,
"s": 244,
"text": "Pandas DataFrame is a rectangular grid that is used to store data. It is easy to visualize and work with data when stored in dataFrame."
},
{
"code": null,
"e": 413,
"s": 380,
"text": "It consists of rows and columns."
},
{
"code": null,
"e": 542,
"s": 413,
"text": "Each row is a measurement of some instance while the column is a vector that contains data for some specific attribute/variable."
},
{
"code": null,
"e": 710,
"s": 542,
"text": "Each Dataframe column has homogeneous data throughout any specific column but Dataframe rows can contain homogeneous or heterogeneous data throughout any specific row."
},
{
"code": null,
"e": 777,
"s": 710,
"text": "Unlike two-dimensional arrays, pandas’ Dataframe axes are labeled."
},
{
"code": null,
"e": 1025,
"s": 777,
"text": "One way of renaming the columns in a Pandas Dataframe is by using the rename() function. This method is quite useful when we need to rename some selected columns because we need to specify information only for the columns which are to be renamed. "
},
{
"code": null,
"e": 1061,
"s": 1025,
"text": "Example 1: Rename a single column. "
},
{
"code": null,
"e": 1069,
"s": 1061,
"text": "Python3"
},
{
"code": "# Import pandas packageimport pandas as pd # Define a dictionary containing ICC rankingsrankings = {'test': ['India', 'South Africa', 'England', 'New Zealand', 'Australia'], 'odi': ['England', 'India', 'New Zealand', 'South Africa', 'Pakistan'], 't20': ['Pakistan', 'India', 'Australia', 'England', 'New Zealand']} # Convert the dictionary into DataFramerankings_pd = pd.DataFrame(rankings) # Before renaming the columnsprint(rankings_pd) rankings_pd.rename(columns = {'test':'TEST'}, inplace = True) # After renaming the columnsprint(\"\\nAfter modifying first column:\\n\", rankings_pd.columns)",
"e": 1770,
"s": 1069,
"text": null
},
{
"code": null,
"e": 1779,
"s": 1770,
"text": "Output: "
},
{
"code": null,
"e": 1818,
"s": 1781,
"text": "Example 2: Rename multiple columns. "
},
{
"code": null,
"e": 1826,
"s": 1818,
"text": "Python3"
},
{
"code": "# Import pandas packageimport pandas as pd # Define a dictionary containing ICC rankingsrankings = {'test': ['India', 'South Africa', 'England', 'New Zealand', 'Australia'], 'odi': ['England', 'India', 'New Zealand', 'South Africa', 'Pakistan'], 't20': ['Pakistan', 'India', 'Australia', 'England', 'New Zealand']} # Convert the dictionary into DataFramerankings_pd = pd.DataFrame(rankings) # Before renaming the columnsprint(rankings_pd.columns) rankings_pd.rename(columns = {'test':'TEST', 'odi':'ODI', 't20':'T20'}, inplace = True) # After renaming the columnsprint(rankings_pd.columns)",
"e": 2565,
"s": 1826,
"text": null
},
{
"code": null,
"e": 2574,
"s": 2565,
"text": "Output: "
},
{
"code": null,
"e": 2891,
"s": 2576,
"text": "The columns can also be renamed by directly assigning a list containing the new names to the columns attribute of the Dataframe object for which we want to rename the columns. The disadvantage of this method is that we need to provide new names for all the columns even if want to rename only some of the columns. "
},
{
"code": null,
"e": 2899,
"s": 2891,
"text": "Python3"
},
{
"code": "# Import pandas packageimport pandas as pd # Define a dictionary containing ICC rankingsrankings = {'test': ['India', 'South Africa', 'England', 'New Zealand', 'Australia'], 'odi': ['England', 'India', 'New Zealand', 'South Africa', 'Pakistan'], 't20': ['Pakistan', 'India', 'Australia', 'England', 'New Zealand']} # Convert the dictionary into DataFramerankings_pd = pd.DataFrame(rankings) # Before renaming the columnsprint(rankings_pd.columns) rankings_pd.columns = ['TEST', 'ODI', 'T-20'] # After renaming the columnsprint(rankings_pd.columns)",
"e": 3562,
"s": 2899,
"text": null
},
{
"code": null,
"e": 3571,
"s": 3562,
"text": "Output: "
},
{
"code": null,
"e": 3762,
"s": 3573,
"text": "In this example, we will rename the column name using the set_axis function, we will pass the new column name and axis that should be replaced with a new name in the column as a parameter."
},
{
"code": null,
"e": 3770,
"s": 3762,
"text": "Python3"
},
{
"code": "# Import pandas packageimport pandas as pd # Define a dictionary containing ICC rankingsrankings = {'test': ['India', 'South Africa', 'England', 'New Zealand', 'Australia'], 'odi': ['England', 'India', 'New Zealand', 'South Africa', 'Pakistan'], 't20': ['Pakistan', 'India', 'Australia', 'England', 'New Zealand']} # Convert the dictionary into DataFramerankings_pd = pd.DataFrame(rankings) # Before renaming the columnsprint(rankings_pd.columns) rankings_pd.set_axis(['A', 'B', 'C'], axis='columns', inplace=True) # After renaming the columnsprint(rankings_pd.columns)rankings_pd.head()",
"e": 4443,
"s": 3770,
"text": null
},
{
"code": null,
"e": 4451,
"s": 4443,
"text": "Output:"
},
{
"code": null,
"e": 4649,
"s": 4453,
"text": "In this example, we will rename the column name using the add_Sufix and add_Prefix function, we will pass the prefix and suffix that should be added to the first and last name of the column name."
},
{
"code": null,
"e": 4657,
"s": 4649,
"text": "Python3"
},
{
"code": "# Import pandas packageimport pandas as pd # Define a dictionary containing ICC rankingsrankings = {'test': ['India', 'South Africa', 'England', 'New Zealand', 'Australia'], 'odi': ['England', 'India', 'New Zealand', 'South Africa', 'Pakistan'], 't20': ['Pakistan', 'India', 'Australia', 'England', 'New Zealand']} # Convert the dictionary into DataFramerankings_pd = pd.DataFrame(rankings) # Before renaming the columnsprint(rankings_pd.columns) rankings_pd = rankings_pd.add_prefix('col_')rankings_pd = rankings_pd.add_suffix('_1') # After renaming the columnsrankings_pd.head()",
"e": 5323,
"s": 4657,
"text": null
},
{
"code": null,
"e": 5331,
"s": 5323,
"text": "Output:"
},
{
"code": null,
"e": 5569,
"s": 5331,
"text": " col_test_1 col_odi_1 col_t20_1\n0 India England Pakistan\n1 South Africa India India\n2 England New Zealand Australia\n3 New Zealand South Africa England\n4 Australia Pakistan New Zealand"
},
{
"code": null,
"e": 5720,
"s": 5569,
"text": "In this example, we will rename the column name using the replace function, we will pass the old name with the new name as a parameter for the column."
},
{
"code": null,
"e": 5728,
"s": 5720,
"text": "Python3"
},
{
"code": "# Import pandas packageimport pandas as pd # Define a dictionary containing ICC rankingsrankings = {'test': ['India', 'South Africa', 'England', 'New Zealand', 'Australia'], 'odi': ['England', 'India', 'New Zealand', 'South Africa', 'Pakistan'], 't20': ['Pakistan', 'India', 'Australia', 'England', 'New Zealand']} # Convert the dictionary into DataFramerankings_pd = pd.DataFrame(rankings) # Before renaming the columnsprint(rankings_pd.columns)# df = rankings_pd rankings_pd.columns = rankings_pd.columns.str.replace('test', 'Col_TEST')rankings_pd.columns = rankings_pd.columns.str.replace('odi', 'Col_ODI')rankings_pd.columns = rankings_pd.columns.str.replace('t20', 'Col_T20') rankings_pd.head()",
"e": 6513,
"s": 5728,
"text": null
},
{
"code": null,
"e": 6521,
"s": 6513,
"text": "Output:"
},
{
"code": null,
"e": 6545,
"s": 6523,
"text": "surajkumarguptaintern"
},
{
"code": null,
"e": 6570,
"s": 6545,
"text": "pandas-dataframe-program"
},
{
"code": null,
"e": 6577,
"s": 6570,
"text": "Picked"
},
{
"code": null,
"e": 6601,
"s": 6577,
"text": "Python pandas-dataFrame"
},
{
"code": null,
"e": 6615,
"s": 6601,
"text": "Python-pandas"
},
{
"code": null,
"e": 6639,
"s": 6615,
"text": "Technical Scripter 2018"
},
{
"code": null,
"e": 6646,
"s": 6639,
"text": "Python"
},
{
"code": null,
"e": 6665,
"s": 6646,
"text": "Technical Scripter"
}
] |
Hashtable clear() Method in Java
|
28 Jun, 2018
The java.util.Hashtable.clear() method in Java is used to clear and remove all of the keys from a specified Hashtable.
Syntax:
Hash_table.clear()
Parameters: The method does not accept any parameters.
Return Value: The method does not return any value.
Below programs are used to illustrate the working of java.util.Hashtable.clear() Method:Program 1:
// Java code to illustrate the clear() methodimport java.util.*; public class Hash_Table_Demo { public static void main(String[] args) { // Creating an empty Hashtable Hashtable<Integer, String> hash_table = new Hashtable<Integer, String>(); // Inserting Values into table hash_table.put(10, "Geeks"); hash_table.put(15, "4"); hash_table.put(20, "Geeks"); hash_table.put(25, "Welcomes"); hash_table.put(30, "You"); // Displaying the Hashtable System.out.println("The Hashtable is: " + hash_table); // Clearing the hash table using clear() hash_table.clear(); // Displaying the final Hashtable System.out.println("Finally the table looks like this: " + hash_table); }}
The Hashtable is: {10=Geeks, 20=Geeks, 30=You, 15=4, 25=Welcomes}
Finally the table looks like this: {}
Program 2:
// Java code to illustrate the clear() methodimport java.util.*; public class Hash_Table_Demo { public static void main(String[] args) { // Creating an empty Hashtable Hashtable<String, Integer> hash_table = new Hashtable<String, Integer>(); // Inserting Values into table hash_table.put("Geeks", 10); hash_table.put("4", 15); hash_table.put("Geeks", 20); hash_table.put("Welcomes", 25); hash_table.put("You", 30); // Displaying the Hashtable System.out.println("The Hashtable is: " + hash_table); // Clearing the hash table using clear() hash_table.clear(); // Displaying the final Hashtable System.out.println("Finally the table looks like this: " + hash_table); }}
The Hashtable is: {You=30, Welcomes=25, 4=15, Geeks=20}
Finally the table looks like this: {}
Note: The same operation can be performed with any type of variation and combination of different data types.
Java - util package
Java-Collections
Java-HashTable
Java
Java
Java-Collections
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n28 Jun, 2018"
},
{
"code": null,
"e": 147,
"s": 28,
"text": "The java.util.Hashtable.clear() method in Java is used to clear and remove all of the keys from a specified Hashtable."
},
{
"code": null,
"e": 155,
"s": 147,
"text": "Syntax:"
},
{
"code": null,
"e": 174,
"s": 155,
"text": "Hash_table.clear()"
},
{
"code": null,
"e": 229,
"s": 174,
"text": "Parameters: The method does not accept any parameters."
},
{
"code": null,
"e": 281,
"s": 229,
"text": "Return Value: The method does not return any value."
},
{
"code": null,
"e": 380,
"s": 281,
"text": "Below programs are used to illustrate the working of java.util.Hashtable.clear() Method:Program 1:"
},
{
"code": "// Java code to illustrate the clear() methodimport java.util.*; public class Hash_Table_Demo { public static void main(String[] args) { // Creating an empty Hashtable Hashtable<Integer, String> hash_table = new Hashtable<Integer, String>(); // Inserting Values into table hash_table.put(10, \"Geeks\"); hash_table.put(15, \"4\"); hash_table.put(20, \"Geeks\"); hash_table.put(25, \"Welcomes\"); hash_table.put(30, \"You\"); // Displaying the Hashtable System.out.println(\"The Hashtable is: \" + hash_table); // Clearing the hash table using clear() hash_table.clear(); // Displaying the final Hashtable System.out.println(\"Finally the table looks like this: \" + hash_table); }}",
"e": 1166,
"s": 380,
"text": null
},
{
"code": null,
"e": 1271,
"s": 1166,
"text": "The Hashtable is: {10=Geeks, 20=Geeks, 30=You, 15=4, 25=Welcomes}\nFinally the table looks like this: {}\n"
},
{
"code": null,
"e": 1282,
"s": 1271,
"text": "Program 2:"
},
{
"code": "// Java code to illustrate the clear() methodimport java.util.*; public class Hash_Table_Demo { public static void main(String[] args) { // Creating an empty Hashtable Hashtable<String, Integer> hash_table = new Hashtable<String, Integer>(); // Inserting Values into table hash_table.put(\"Geeks\", 10); hash_table.put(\"4\", 15); hash_table.put(\"Geeks\", 20); hash_table.put(\"Welcomes\", 25); hash_table.put(\"You\", 30); // Displaying the Hashtable System.out.println(\"The Hashtable is: \" + hash_table); // Clearing the hash table using clear() hash_table.clear(); // Displaying the final Hashtable System.out.println(\"Finally the table looks like this: \" + hash_table); }}",
"e": 2068,
"s": 1282,
"text": null
},
{
"code": null,
"e": 2163,
"s": 2068,
"text": "The Hashtable is: {You=30, Welcomes=25, 4=15, Geeks=20}\nFinally the table looks like this: {}\n"
},
{
"code": null,
"e": 2273,
"s": 2163,
"text": "Note: The same operation can be performed with any type of variation and combination of different data types."
},
{
"code": null,
"e": 2293,
"s": 2273,
"text": "Java - util package"
},
{
"code": null,
"e": 2310,
"s": 2293,
"text": "Java-Collections"
},
{
"code": null,
"e": 2325,
"s": 2310,
"text": "Java-HashTable"
},
{
"code": null,
"e": 2330,
"s": 2325,
"text": "Java"
},
{
"code": null,
"e": 2335,
"s": 2330,
"text": "Java"
},
{
"code": null,
"e": 2352,
"s": 2335,
"text": "Java-Collections"
}
] |
Convert a number into negative base representation
|
22 Jun, 2022
A number n and a negative base negBase is given to us, we need to represent n in that negative base. Negative base works similar to positive base. For example in base 2 we multiply bits to 1, 2, 4, 8 and so on to get actual number in decimal. In case of base -2 we need to multiply bits with 1, -2, 4, -8 and so on to get number in decimal. Examples:
Input : n = 13, negBase = -2
Output : 11101
1*(16) + 1*(-8) + 1*(4) + 0*(-2) + 1*(1) = 13
It is possible to represent a number into any negative base with same procedure (Refer Wiki for details). For simplicity (to get rid of A, B etc characters in output), we are allowing our base to be in between -2 and -10 only.
We can solve this problem similar to solving problem with positive bases but one important thing to remember is, remainder will always be positive whether we work with positive base or negative base but in most compilers, the result of dividing a negative number by a negative number is rounded towards 0, usually leaving a negative remainder. So whenever we get a negative remainder, we can convert it to positive as below,
Let
n = (?negBase) * quotient + remainder
= (?negBase) * quotient + negBase ? negBase + negBase
= (?negBase) * (quotient + 1) + (remainder + negBase).
So if after doing "remainder = n % negBase" and
"n = n/negBase", we get negative remainder, we do
following.
remainder = remainder + (-negBase)
n = n + 1
Example : n = -4, negBase = -3
In C++, we get
remainder = n % negBase = -4/-3 = -1
n = n/negBase [Next step for base conversion]
= -4/-3
= 1
To avoid negative remainder, we do,
remainder = -1 + (-negBase) = -1 - (-3) = 2
n = n + 1 = 1 + 1 = 2.
So when we will get negative remainder, we will make it positive by adding absolute value of base to it and adding 1 to our quotient.Above explained approach is implemented in below code,
C++
Java
Python3
C#
Javascript
// C/C++ program to convert n into negative base form#include <bits/stdc++.h>using namespace std; // Utility method to convert integer into stringstring toString(int n){ string str; stringstream ss; ss << n; ss >> str; return str;} // Method to convert n to base negBasestring toNegativeBase(int n, int negBase){ // If n is zero then in any base it will be 0 only if (n == 0) return "0"; string converted = ""; while (n != 0) { // Get remainder by negative base, it can be // negative also int remainder = n % negBase; n /= negBase; // if remainder is negative, add abs(base) to // it and add 1 to n if (remainder < 0) { remainder += (-negBase); n += 1; } // convert remainder to string add into the result converted = toString(remainder) + converted; } return converted;} // Driver code to test above methodsint main(){ int n = 13; int negBase = -2; cout << toNegativeBase(n, negBase); return 0;}
// Java program to convert n into// negative base formclass GFG{ // Method to convert n to base negBasestatic String toNegativeBase(int n, int negBase){ // If n is zero then in any base // it will be 0 only if (n == 0) return "0"; String converted = ""; while (n != 0) { // Get remainder by negative base, // it can be negative also int remainder = n % negBase; n /= negBase; // if remainder is negative, // add Math.abs(base) to it // and add 1 to n if (remainder < 0) { remainder += (-negBase); n += 1; } // convert remainder to String add into the result converted = String.valueOf(remainder) + converted; } return converted;} // Driver Codepublic static void main(String[] args){ int n = 13; int negBase = -2; System.out.print(toNegativeBase(n, negBase));}} // This code is contributed by 29AjayKumar
# Python 3 program to convert n into# negative base form # Method to convert n to base negBasedef toNegativeBase(n, negBase): # If n is zero then in any base it # will be 0 only if (n == 0): return "0" converted = "01" while (n != 0): # Get remainder by negative base, # it can be negative also remainder = n % (negBase) n = int(n/negBase) # if remainder is negative, add # abs(base) to it and add 1 to n if (remainder < 0): remainder += ((-1) * negBase) n += 1 # convert remainder to string add # into the result converted = str(remainder) + converted return converted # Driver Codeif __name__ == '__main__': n = 13 negBase = -2 print(toNegativeBase(n, negBase)) # This code is contributed by# Surendra_Gangwar
// C# program to convert n into// negative base formusing System; class GFG{ // Method to convert n to base negBasestatic String toNegativeBase(int n, int negBase){ // If n is zero then in any base // it will be 0 only if (n == 0) return "0"; String converted = ""; while (n != 0) { // Get remainder by negative base, // it can be negative also int remainder = n % negBase; n /= negBase; // if remainder is negative, // add Math.Abs(base) to it // and add 1 to n if (remainder < 0) { remainder += (-negBase); n += 1; } // convert remainder to String add into the result converted = String.Join("", remainder) + converted; } return converted;} // Driver Codepublic static void Main(String[] args){ int n = 13; int negBase = -2; Console.Write(toNegativeBase(n, negBase));}} // This code is contributed by Rajput-Ji
<script> // JavaScript program to convert n into// negative base form // Method to convert n to base negBasefunction toNegativeBase(n, negBase){ // If n is zero then in any base // it will be 0 only if (n == 0) return "0"; let converted = "01"; while (n != 0) { // Get remainder by negative base, // it can be negative also let remainder = (-1)*(Math.abs(n) % Math.abs(negBase)); n = parseInt(n/negBase); // if remainder is negative, // add Math.abs(base) to it // and add 1 to n if (remainder < 0) { remainder += ((-1)*negBase); n += 1; } // convert remainder to String add into the result converted = remainder.toString() + converted; } return converted;} // Driver Code let n = 13;let negBase = -2; document.write(toNegativeBase(n, negBase),"</br>"); // This code is contributed by shinjanpatra </script>
Output:
11101
Time Complexity: O(N)Auxiliary Space: O(1) Reference : https://en.wikipedia.org/wiki/Negative_baseThis article is contributed by Utkarsh Trivedi. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
SURENDRA_GANGWAR
Harshit Singhal 2
29AjayKumar
Rajput-Ji
aditya_panwar
pankajsharmagfg
shinjanpatra
base-conversion
Algorithms
Algorithms
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
What is Hashing | A Complete Tutorial
Find if there is a path between two vertices in an undirected graph
How to Start Learning DSA?
Complete Roadmap To Learn DSA From Scratch
Types of Complexity Classes | P, NP, CoNP, NP hard and NP complete
Difference between NP hard and NP complete problem
What Should I Learn First: Data Structures or Algorithms?
Ternary Search
Find maximum meetings in one room
K means Clustering - Introduction
|
[
{
"code": null,
"e": 54,
"s": 26,
"text": "\n22 Jun, 2022"
},
{
"code": null,
"e": 407,
"s": 54,
"text": "A number n and a negative base negBase is given to us, we need to represent n in that negative base. Negative base works similar to positive base. For example in base 2 we multiply bits to 1, 2, 4, 8 and so on to get actual number in decimal. In case of base -2 we need to multiply bits with 1, -2, 4, -8 and so on to get number in decimal. Examples: "
},
{
"code": null,
"e": 499,
"s": 407,
"text": "Input : n = 13, negBase = -2\nOutput : 11101\n1*(16) + 1*(-8) + 1*(4) + 0*(-2) + 1*(1) = 13"
},
{
"code": null,
"e": 728,
"s": 499,
"text": "It is possible to represent a number into any negative base with same procedure (Refer Wiki for details). For simplicity (to get rid of A, B etc characters in output), we are allowing our base to be in between -2 and -10 only. "
},
{
"code": null,
"e": 1155,
"s": 728,
"text": "We can solve this problem similar to solving problem with positive bases but one important thing to remember is, remainder will always be positive whether we work with positive base or negative base but in most compilers, the result of dividing a negative number by a negative number is rounded towards 0, usually leaving a negative remainder. So whenever we get a negative remainder, we can convert it to positive as below, "
},
{
"code": null,
"e": 1746,
"s": 1155,
"text": "Let \nn = (?negBase) * quotient + remainder \n = (?negBase) * quotient + negBase ? negBase + negBase \n = (?negBase) * (quotient + 1) + (remainder + negBase). \n\nSo if after doing \"remainder = n % negBase\" and \n\"n = n/negBase\", we get negative remainder, we do \nfollowing.\nremainder = remainder + (-negBase)\nn = n + 1\n\nExample : n = -4, negBase = -3\nIn C++, we get\n remainder = n % negBase = -4/-3 = -1\n n = n/negBase [Next step for base conversion]\n = -4/-3 \n = 1\nTo avoid negative remainder, we do,\n remainder = -1 + (-negBase) = -1 - (-3) = 2\n n = n + 1 = 1 + 1 = 2."
},
{
"code": null,
"e": 1935,
"s": 1746,
"text": "So when we will get negative remainder, we will make it positive by adding absolute value of base to it and adding 1 to our quotient.Above explained approach is implemented in below code, "
},
{
"code": null,
"e": 1939,
"s": 1935,
"text": "C++"
},
{
"code": null,
"e": 1944,
"s": 1939,
"text": "Java"
},
{
"code": null,
"e": 1952,
"s": 1944,
"text": "Python3"
},
{
"code": null,
"e": 1955,
"s": 1952,
"text": "C#"
},
{
"code": null,
"e": 1966,
"s": 1955,
"text": "Javascript"
},
{
"code": "// C/C++ program to convert n into negative base form#include <bits/stdc++.h>using namespace std; // Utility method to convert integer into stringstring toString(int n){ string str; stringstream ss; ss << n; ss >> str; return str;} // Method to convert n to base negBasestring toNegativeBase(int n, int negBase){ // If n is zero then in any base it will be 0 only if (n == 0) return \"0\"; string converted = \"\"; while (n != 0) { // Get remainder by negative base, it can be // negative also int remainder = n % negBase; n /= negBase; // if remainder is negative, add abs(base) to // it and add 1 to n if (remainder < 0) { remainder += (-negBase); n += 1; } // convert remainder to string add into the result converted = toString(remainder) + converted; } return converted;} // Driver code to test above methodsint main(){ int n = 13; int negBase = -2; cout << toNegativeBase(n, negBase); return 0;}",
"e": 3028,
"s": 1966,
"text": null
},
{
"code": "// Java program to convert n into// negative base formclass GFG{ // Method to convert n to base negBasestatic String toNegativeBase(int n, int negBase){ // If n is zero then in any base // it will be 0 only if (n == 0) return \"0\"; String converted = \"\"; while (n != 0) { // Get remainder by negative base, // it can be negative also int remainder = n % negBase; n /= negBase; // if remainder is negative, // add Math.abs(base) to it // and add 1 to n if (remainder < 0) { remainder += (-negBase); n += 1; } // convert remainder to String add into the result converted = String.valueOf(remainder) + converted; } return converted;} // Driver Codepublic static void main(String[] args){ int n = 13; int negBase = -2; System.out.print(toNegativeBase(n, negBase));}} // This code is contributed by 29AjayKumar",
"e": 3983,
"s": 3028,
"text": null
},
{
"code": "# Python 3 program to convert n into# negative base form # Method to convert n to base negBasedef toNegativeBase(n, negBase): # If n is zero then in any base it # will be 0 only if (n == 0): return \"0\" converted = \"01\" while (n != 0): # Get remainder by negative base, # it can be negative also remainder = n % (negBase) n = int(n/negBase) # if remainder is negative, add # abs(base) to it and add 1 to n if (remainder < 0): remainder += ((-1) * negBase) n += 1 # convert remainder to string add # into the result converted = str(remainder) + converted return converted # Driver Codeif __name__ == '__main__': n = 13 negBase = -2 print(toNegativeBase(n, negBase)) # This code is contributed by# Surendra_Gangwar",
"e": 4848,
"s": 3983,
"text": null
},
{
"code": "// C# program to convert n into// negative base formusing System; class GFG{ // Method to convert n to base negBasestatic String toNegativeBase(int n, int negBase){ // If n is zero then in any base // it will be 0 only if (n == 0) return \"0\"; String converted = \"\"; while (n != 0) { // Get remainder by negative base, // it can be negative also int remainder = n % negBase; n /= negBase; // if remainder is negative, // add Math.Abs(base) to it // and add 1 to n if (remainder < 0) { remainder += (-negBase); n += 1; } // convert remainder to String add into the result converted = String.Join(\"\", remainder) + converted; } return converted;} // Driver Codepublic static void Main(String[] args){ int n = 13; int negBase = -2; Console.Write(toNegativeBase(n, negBase));}} // This code is contributed by Rajput-Ji",
"e": 5811,
"s": 4848,
"text": null
},
{
"code": "<script> // JavaScript program to convert n into// negative base form // Method to convert n to base negBasefunction toNegativeBase(n, negBase){ // If n is zero then in any base // it will be 0 only if (n == 0) return \"0\"; let converted = \"01\"; while (n != 0) { // Get remainder by negative base, // it can be negative also let remainder = (-1)*(Math.abs(n) % Math.abs(negBase)); n = parseInt(n/negBase); // if remainder is negative, // add Math.abs(base) to it // and add 1 to n if (remainder < 0) { remainder += ((-1)*negBase); n += 1; } // convert remainder to String add into the result converted = remainder.toString() + converted; } return converted;} // Driver Code let n = 13;let negBase = -2; document.write(toNegativeBase(n, negBase),\"</br>\"); // This code is contributed by shinjanpatra </script>",
"e": 6761,
"s": 5811,
"text": null
},
{
"code": null,
"e": 6771,
"s": 6761,
"text": "Output: "
},
{
"code": null,
"e": 6777,
"s": 6771,
"text": "11101"
},
{
"code": null,
"e": 7299,
"s": 6777,
"text": "Time Complexity: O(N)Auxiliary Space: O(1) Reference : https://en.wikipedia.org/wiki/Negative_baseThis article is contributed by Utkarsh Trivedi. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. "
},
{
"code": null,
"e": 7316,
"s": 7299,
"text": "SURENDRA_GANGWAR"
},
{
"code": null,
"e": 7334,
"s": 7316,
"text": "Harshit Singhal 2"
},
{
"code": null,
"e": 7346,
"s": 7334,
"text": "29AjayKumar"
},
{
"code": null,
"e": 7356,
"s": 7346,
"text": "Rajput-Ji"
},
{
"code": null,
"e": 7370,
"s": 7356,
"text": "aditya_panwar"
},
{
"code": null,
"e": 7386,
"s": 7370,
"text": "pankajsharmagfg"
},
{
"code": null,
"e": 7399,
"s": 7386,
"text": "shinjanpatra"
},
{
"code": null,
"e": 7415,
"s": 7399,
"text": "base-conversion"
},
{
"code": null,
"e": 7426,
"s": 7415,
"text": "Algorithms"
},
{
"code": null,
"e": 7437,
"s": 7426,
"text": "Algorithms"
},
{
"code": null,
"e": 7535,
"s": 7437,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 7573,
"s": 7535,
"text": "What is Hashing | A Complete Tutorial"
},
{
"code": null,
"e": 7641,
"s": 7573,
"text": "Find if there is a path between two vertices in an undirected graph"
},
{
"code": null,
"e": 7668,
"s": 7641,
"text": "How to Start Learning DSA?"
},
{
"code": null,
"e": 7711,
"s": 7668,
"text": "Complete Roadmap To Learn DSA From Scratch"
},
{
"code": null,
"e": 7778,
"s": 7711,
"text": "Types of Complexity Classes | P, NP, CoNP, NP hard and NP complete"
},
{
"code": null,
"e": 7829,
"s": 7778,
"text": "Difference between NP hard and NP complete problem"
},
{
"code": null,
"e": 7887,
"s": 7829,
"text": "What Should I Learn First: Data Structures or Algorithms?"
},
{
"code": null,
"e": 7902,
"s": 7887,
"text": "Ternary Search"
},
{
"code": null,
"e": 7936,
"s": 7902,
"text": "Find maximum meetings in one room"
}
] |
Perform MySQL delete under safe mode?
|
To delete under safe mode, you can use the below query −
SET SQL_SAFE_UPDATES = 0;
To understand the above query, let us create a table. The following is the query to create a table −
mysql> create table SafeDeleteDemo
−> (
−> Price int
−> );
Query OK, 0 rows affected (0.50 sec)
Insert some records in the table with the help of insert command. The query is as follows −
mysql> insert into SafeDeleteDemo values(100);
Query OK, 1 row affected (0.11 sec)
mysql> insert into SafeDeleteDemo values(200);
Query OK, 1 row affected (0.19 sec)
mysql> insert into SafeDeleteDemo values(300);
Query OK, 1 row affected (0.09 sec)
mysql> insert into SafeDeleteDemo values(500);
Query OK, 1 row affected (0.14 sec)
mysql> insert into SafeDeleteDemo values(1000);
Query OK, 1 row affected (0.10 sec)
mysql> insert into SafeDeleteDemo values(150);
Query OK, 1 row affected (0.11 sec)
Display all records from the table before deleting records. The query is as follows −
mysql> select *from SafeDeleteDemo;
The following is the output −
+-------+
| Price |
+-------+
| 100 |
| 200 |
| 300 |
| 500 |
| 1000 |
| 150 |
+-------+
6 rows in set (0.00 sec)
Now delete under safe mode with the help of SET command. The query is as follows −
mysql> SET SQL_SAFE_UPDATES = 0;
Query OK, 0 rows affected (0.00 sec)
Begin with deleting some records the table now. We are in safe mode −
mysql> delete from SafeDeleteDemo where Price >=500;
Query OK, 2 rows affected (0.14 sec)
Now you can check how many records are present in the table after deleting records. The query is as follows −
mysql> select *from SafeDeleteDemo;
The following is the output displaying that we have successfully deleted records >= 500 −
+-------+
| Price |
+-------+
| 100 |
| 200 |
| 300 |
| 150 |
+-------+
4 rows in set (0.00 sec)
Now you can remove delete under safe mode with the help of the same SET command. The query is as follows −
mysql> SET SQL_SAFE_UPDATES = 1;
Query OK, 0 rows affected (0.00 sec)
|
[
{
"code": null,
"e": 1244,
"s": 1187,
"text": "To delete under safe mode, you can use the below query −"
},
{
"code": null,
"e": 1270,
"s": 1244,
"text": "SET SQL_SAFE_UPDATES = 0;"
},
{
"code": null,
"e": 1371,
"s": 1270,
"text": "To understand the above query, let us create a table. The following is the query to create a table −"
},
{
"code": null,
"e": 1476,
"s": 1371,
"text": "mysql> create table SafeDeleteDemo\n −> (\n −> Price int\n −> );\nQuery OK, 0 rows affected (0.50 sec)"
},
{
"code": null,
"e": 1568,
"s": 1476,
"text": "Insert some records in the table with the help of insert command. The query is as follows −"
},
{
"code": null,
"e": 2072,
"s": 1568,
"text": "mysql> insert into SafeDeleteDemo values(100);\nQuery OK, 1 row affected (0.11 sec)\n\nmysql> insert into SafeDeleteDemo values(200);\nQuery OK, 1 row affected (0.19 sec)\n\nmysql> insert into SafeDeleteDemo values(300);\nQuery OK, 1 row affected (0.09 sec)\n\nmysql> insert into SafeDeleteDemo values(500);\nQuery OK, 1 row affected (0.14 sec)\n\nmysql> insert into SafeDeleteDemo values(1000);\nQuery OK, 1 row affected (0.10 sec)\n\nmysql> insert into SafeDeleteDemo values(150);\nQuery OK, 1 row affected (0.11 sec)"
},
{
"code": null,
"e": 2158,
"s": 2072,
"text": "Display all records from the table before deleting records. The query is as follows −"
},
{
"code": null,
"e": 2194,
"s": 2158,
"text": "mysql> select *from SafeDeleteDemo;"
},
{
"code": null,
"e": 2224,
"s": 2194,
"text": "The following is the output −"
},
{
"code": null,
"e": 2349,
"s": 2224,
"text": "+-------+\n| Price |\n+-------+\n| 100 |\n| 200 |\n| 300 |\n| 500 |\n| 1000 |\n| 150 |\n+-------+\n6 rows in set (0.00 sec)"
},
{
"code": null,
"e": 2432,
"s": 2349,
"text": "Now delete under safe mode with the help of SET command. The query is as follows −"
},
{
"code": null,
"e": 2502,
"s": 2432,
"text": "mysql> SET SQL_SAFE_UPDATES = 0;\nQuery OK, 0 rows affected (0.00 sec)"
},
{
"code": null,
"e": 2572,
"s": 2502,
"text": "Begin with deleting some records the table now. We are in safe mode −"
},
{
"code": null,
"e": 2662,
"s": 2572,
"text": "mysql> delete from SafeDeleteDemo where Price >=500;\nQuery OK, 2 rows affected (0.14 sec)"
},
{
"code": null,
"e": 2772,
"s": 2662,
"text": "Now you can check how many records are present in the table after deleting records. The query is as follows −"
},
{
"code": null,
"e": 2808,
"s": 2772,
"text": "mysql> select *from SafeDeleteDemo;"
},
{
"code": null,
"e": 2898,
"s": 2808,
"text": "The following is the output displaying that we have successfully deleted records >= 500 −"
},
{
"code": null,
"e": 3003,
"s": 2898,
"text": "+-------+\n| Price |\n+-------+\n| 100 |\n| 200 |\n| 300 |\n| 150 |\n+-------+\n4 rows in set (0.00 sec)"
},
{
"code": null,
"e": 3110,
"s": 3003,
"text": "Now you can remove delete under safe mode with the help of the same SET command. The query is as follows −"
},
{
"code": null,
"e": 3180,
"s": 3110,
"text": "mysql> SET SQL_SAFE_UPDATES = 1;\nQuery OK, 0 rows affected (0.00 sec)"
}
] |
How to convert Map keys to an array in JavaScript ?
|
18 Jun, 2019
Given a Map and the task is to get the keys of the map into an array using JavaScript.
Approach 1:
Declare new map object
Display the map content
Use keys() method on Map Object to get the keys of Map.
Then use the array.from() method to convert map object to array.
Example 1: This example uses array.from() method to get the keys of the Map in the array.
<!DOCTYPE HTML> <html> <head> <title> How to convert Map keys to array in JavaScript ? </title> </head> <body style = "text-align:center;"> <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 up = document.getElementById('GFG_UP'); var down = document.getElementById('GFG_DOWN'); let myMap = new Map().set('GFG', 1).set('Geeks', 2); up.innerHTML = 'myMap = ("GFG" => 1, "Geeks" => 2)'; function GFG_Fun() { var array = Array.from(myMap.keys()); down.innerHTML = "Elements in array are " + array + " and Length of array = " + array.length; } </script> </body> </html>
Output:
Before clicking on the button:
After clicking on the button:
Approach 2:
Declare new map object
Display the map content
Use [ ...myMap.keys() ] method on Map Object to get the keys of Map as an array.
Example 2: This example uses the [ ...Map.keys() ] method to get the keys of the Map in the array.
<!DOCTYPE HTML> <html> <head> <title> How to convert Map keys to array in JavaScript </title> </head> <body style = "text-align:center;"> <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 up = document.getElementById('GFG_UP'); var down = document.getElementById('GFG_DOWN'); let myMap = new Map().set('GFG', 1).set('Geeks', 2); up.innerHTML = 'myMap = ("GFG" => 1, "Geeks" => 2)'; function GFG_Fun() { var array = [ ...myMap.keys() ]; down.innerHTML = "Elements in array are " + array + " and Length of array = " + array.length; } </script> </body> </html>
Output:
Before clicking on the button:
After clicking on the button:
javascript-array
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
Node.js | fs.writeFileSync() Method
Remove elements from a JavaScript Array
How do you run JavaScript script through the Terminal?
How to insert spaces/tabs in text using HTML/CSS?
Installation of Node.js on Linux
Top 10 Projects For Beginners To Practice HTML and CSS Skills
Node.js fs.readFileSync() Method
How to set the default value for an HTML <select> element ?
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n18 Jun, 2019"
},
{
"code": null,
"e": 115,
"s": 28,
"text": "Given a Map and the task is to get the keys of the map into an array using JavaScript."
},
{
"code": null,
"e": 127,
"s": 115,
"text": "Approach 1:"
},
{
"code": null,
"e": 150,
"s": 127,
"text": "Declare new map object"
},
{
"code": null,
"e": 174,
"s": 150,
"text": "Display the map content"
},
{
"code": null,
"e": 230,
"s": 174,
"text": "Use keys() method on Map Object to get the keys of Map."
},
{
"code": null,
"e": 295,
"s": 230,
"text": "Then use the array.from() method to convert map object to array."
},
{
"code": null,
"e": 385,
"s": 295,
"text": "Example 1: This example uses array.from() method to get the keys of the Map in the array."
},
{
"code": "<!DOCTYPE HTML> <html> <head> <title> How to convert Map keys to array in JavaScript ? </title> </head> <body style = \"text-align:center;\"> <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 up = document.getElementById('GFG_UP'); var down = document.getElementById('GFG_DOWN'); let myMap = new Map().set('GFG', 1).set('Geeks', 2); up.innerHTML = 'myMap = (\"GFG\" => 1, \"Geeks\" => 2)'; function GFG_Fun() { var array = Array.from(myMap.keys()); down.innerHTML = \"Elements in array are \" + array + \" and Length of array = \" + array.length; } </script> </body> </html> ",
"e": 1570,
"s": 385,
"text": null
},
{
"code": null,
"e": 1578,
"s": 1570,
"text": "Output:"
},
{
"code": null,
"e": 1609,
"s": 1578,
"text": "Before clicking on the button:"
},
{
"code": null,
"e": 1639,
"s": 1609,
"text": "After clicking on the button:"
},
{
"code": null,
"e": 1651,
"s": 1639,
"text": "Approach 2:"
},
{
"code": null,
"e": 1674,
"s": 1651,
"text": "Declare new map object"
},
{
"code": null,
"e": 1698,
"s": 1674,
"text": "Display the map content"
},
{
"code": null,
"e": 1779,
"s": 1698,
"text": "Use [ ...myMap.keys() ] method on Map Object to get the keys of Map as an array."
},
{
"code": null,
"e": 1878,
"s": 1779,
"text": "Example 2: This example uses the [ ...Map.keys() ] method to get the keys of the Map in the array."
},
{
"code": "<!DOCTYPE HTML> <html> <head> <title> How to convert Map keys to array in JavaScript </title> </head> <body style = \"text-align:center;\"> <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 up = document.getElementById('GFG_UP'); var down = document.getElementById('GFG_DOWN'); let myMap = new Map().set('GFG', 1).set('Geeks', 2); up.innerHTML = 'myMap = (\"GFG\" => 1, \"Geeks\" => 2)'; function GFG_Fun() { var array = [ ...myMap.keys() ]; down.innerHTML = \"Elements in array are \" + array + \" and Length of array = \" + array.length; } </script> </body> </html>",
"e": 3036,
"s": 1878,
"text": null
},
{
"code": null,
"e": 3044,
"s": 3036,
"text": "Output:"
},
{
"code": null,
"e": 3075,
"s": 3044,
"text": "Before clicking on the button:"
},
{
"code": null,
"e": 3105,
"s": 3075,
"text": "After clicking on the button:"
},
{
"code": null,
"e": 3122,
"s": 3105,
"text": "javascript-array"
},
{
"code": null,
"e": 3133,
"s": 3122,
"text": "JavaScript"
},
{
"code": null,
"e": 3150,
"s": 3133,
"text": "Web Technologies"
},
{
"code": null,
"e": 3177,
"s": 3150,
"text": "Web technologies Questions"
},
{
"code": null,
"e": 3275,
"s": 3177,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 3336,
"s": 3275,
"text": "Difference between var, let and const keywords in JavaScript"
},
{
"code": null,
"e": 3408,
"s": 3336,
"text": "Differences between Functional Components and Class Components in React"
},
{
"code": null,
"e": 3444,
"s": 3408,
"text": "Node.js | fs.writeFileSync() Method"
},
{
"code": null,
"e": 3484,
"s": 3444,
"text": "Remove elements from a JavaScript Array"
},
{
"code": null,
"e": 3539,
"s": 3484,
"text": "How do you run JavaScript script through the Terminal?"
},
{
"code": null,
"e": 3589,
"s": 3539,
"text": "How to insert spaces/tabs in text using HTML/CSS?"
},
{
"code": null,
"e": 3622,
"s": 3589,
"text": "Installation of Node.js on Linux"
},
{
"code": null,
"e": 3684,
"s": 3622,
"text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills"
},
{
"code": null,
"e": 3717,
"s": 3684,
"text": "Node.js fs.readFileSync() Method"
}
] |
Python | Reraise the Last Exception and Issue Warning
|
12 Jun, 2019
Problem – Reraising the exception, that has been caught in the except block.
def example(): try: int('N/A') except ValueError: print("Didn't work") raise example()
Output :
Didn't work
Traceback (most recent call last):
File "", line 1, in
File "", line 3, in example
ValueError: invalid literal for int() with base 10: 'N/A'
This problem typically arises when there is no need to take any action in response to an exception (e.g., logging, cleanup, etc.). A very common use might be in catch-all exception handlers.
Code #2 : Catching all exception handlers.
try: ...except Exception as e: # Process exception information in some way ... # Propagate the exception raise
Problem 2 – To have a program issue warning messages (e.g., about deprecated features or usage problems).
Code #3: Using the warnings.warn() function
import warningsdef func(x, y, logfile = None, debug = False): if logfile is not None: warnings.warn('logfile argument deprecated', DeprecationWarning)
The arguments to warn() are a warning message along with a warning class, which is typically one of the following:UserWarning, DeprecationWarning, SyntaxWarning, RuntimeWarning, ResourceWarning, or FutureWarning.The handling of warnings depends on how the interpreter is executed and other configuration.
Output when running Python with the -W all option.
bash % python3 -W all example.py
example.py:5: DeprecationWarning: logfile argument is deprecated
warnings.warn('logfile argument is deprecated', DeprecationWarning)
Normally, warnings just produce output messages on standard error. To turn warnings into exceptions, use the -W error option.
bash % python3 -W error example.py
Traceback (most recent call last):
File "example.py", line 10, in
func(2, 3, logfile ='log.txt')
File "example.py", line 5, in func
warnings.warn('logfile argument is deprecated', DeprecationWarning)
DeprecationWarning: logfile argument is deprecated
bash %
Python-exceptions
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": 28,
"s": 0,
"text": "\n12 Jun, 2019"
},
{
"code": null,
"e": 105,
"s": 28,
"text": "Problem – Reraising the exception, that has been caught in the except block."
},
{
"code": "def example(): try: int('N/A') except ValueError: print(\"Didn't work\") raise example()",
"e": 228,
"s": 105,
"text": null
},
{
"code": null,
"e": 237,
"s": 228,
"text": "Output :"
},
{
"code": null,
"e": 400,
"s": 237,
"text": "Didn't work\nTraceback (most recent call last):\n File \"\", line 1, in \n File \"\", line 3, in example\nValueError: invalid literal for int() with base 10: 'N/A'\n"
},
{
"code": null,
"e": 591,
"s": 400,
"text": "This problem typically arises when there is no need to take any action in response to an exception (e.g., logging, cleanup, etc.). A very common use might be in catch-all exception handlers."
},
{
"code": null,
"e": 634,
"s": 591,
"text": "Code #2 : Catching all exception handlers."
},
{
"code": "try: ...except Exception as e: # Process exception information in some way ... # Propagate the exception raise",
"e": 757,
"s": 634,
"text": null
},
{
"code": null,
"e": 864,
"s": 757,
"text": " Problem 2 – To have a program issue warning messages (e.g., about deprecated features or usage problems)."
},
{
"code": null,
"e": 908,
"s": 864,
"text": "Code #3: Using the warnings.warn() function"
},
{
"code": "import warningsdef func(x, y, logfile = None, debug = False): if logfile is not None: warnings.warn('logfile argument deprecated', DeprecationWarning)",
"e": 1100,
"s": 908,
"text": null
},
{
"code": null,
"e": 1405,
"s": 1100,
"text": "The arguments to warn() are a warning message along with a warning class, which is typically one of the following:UserWarning, DeprecationWarning, SyntaxWarning, RuntimeWarning, ResourceWarning, or FutureWarning.The handling of warnings depends on how the interpreter is executed and other configuration."
},
{
"code": null,
"e": 1456,
"s": 1405,
"text": "Output when running Python with the -W all option."
},
{
"code": null,
"e": 1625,
"s": 1456,
"text": "bash % python3 -W all example.py\nexample.py:5: DeprecationWarning: logfile argument is deprecated\n warnings.warn('logfile argument is deprecated', DeprecationWarning)\n"
},
{
"code": null,
"e": 1751,
"s": 1625,
"text": "Normally, warnings just produce output messages on standard error. To turn warnings into exceptions, use the -W error option."
},
{
"code": null,
"e": 2070,
"s": 1751,
"text": "bash % python3 -W error example.py\nTraceback (most recent call last):\n File \"example.py\", line 10, in \n func(2, 3, logfile ='log.txt')\n File \"example.py\", line 5, in func\n warnings.warn('logfile argument is deprecated', DeprecationWarning)\nDeprecationWarning: logfile argument is deprecated\nbash %\n"
},
{
"code": null,
"e": 2088,
"s": 2070,
"text": "Python-exceptions"
},
{
"code": null,
"e": 2095,
"s": 2088,
"text": "Python"
},
{
"code": null,
"e": 2193,
"s": 2095,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 2225,
"s": 2193,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 2252,
"s": 2225,
"text": "Python Classes and Objects"
},
{
"code": null,
"e": 2273,
"s": 2252,
"text": "Python OOPs Concepts"
},
{
"code": null,
"e": 2296,
"s": 2273,
"text": "Introduction To PYTHON"
},
{
"code": null,
"e": 2352,
"s": 2296,
"text": "How to drop one or multiple columns in Pandas Dataframe"
},
{
"code": null,
"e": 2383,
"s": 2352,
"text": "Python | os.path.join() method"
},
{
"code": null,
"e": 2425,
"s": 2383,
"text": "Check if element exists in list in Python"
},
{
"code": null,
"e": 2467,
"s": 2425,
"text": "How To Convert Python Dictionary To JSON?"
},
{
"code": null,
"e": 2506,
"s": 2467,
"text": "Python | Get unique values from a list"
}
] |
Output of Java Programs | Set 52 (Strings Class)
|
18 Sep, 2018
Prerequisite : Basics of Strings class in java
1. What is the Output Of the following Program
class demo1 { public static void main(String args[]) { String str1 = "java"; char arr[] = { 'j', 'a', 'v', 'a', ' ', 'p', 'r', 'o', 'g', 'r', 'a', 'm', 'm', 'i', 'n', 'g' }; String str2 = new String(arr); System.out.println(str1); System.out.println(str2); }}
Output:
java
java programming
2. What is the Output Of the following Program
class demo2 { public static void main(String args[]) { String str1 = ""; char arr[] = { 'j', 'a', 'v', 'a', ' ', 'p', 'r', 'o', 'g', 'r', 'a', 'm', 'm', 'i', 'n', 'g' }; String str2 = new String(arr); String str3 = new String(str2); System.out.println(str1); System.out.println(str2); System.out.println(str3); }}
Output:
java programming
java programming
3. What is the Output Of the following Program
class demo3 { public static void main(String args[]) { byte[] arr = { 97, 98, 99, 100, 101 }; String str2 = new String(arr); System.out.println(str2); }}
Output:
abcde
Explanation:The constructor String( byte[] ) converts the bytes to corresponding characters i.e. 97 converted to character ‘a’
4. What is the Output Of the following Program
class demo4 { public static void main(String args[]) { String str = "Java Programming"; char ch = str.charAt(2); System.out.println(ch); }}
Output:
v
Explanation:charAt() function returns the character at the specified index.
5. What is the Output Of the following Program
class demo5 { public static void main(String args[]) { String str = "Java Programming"; char arr[] = new char[10]; str.getChars(0, 4, arr, 0); System.out.println(arr); }}
Output:
Java
Explanation:The syntax of the method is: getChars(startindex, numOfCharacters, arrayName, startindexOfArrat). So from the string, starting from 0th index, first four characters are taken.
6. What is the Output Of the following Program
class demo6 { public static void main(String args[]) { String str = "Java Programming"; char arr[] = new char[20]; arr = str.toCharArray(); System.out.println(arr); }}
Output:
Java Programming
Explanation:toCharArray() method converts the string into a character array.
7. What is the Output Of the following Program
class demo7 { public static void main(String args[]) { String str = "Java Programming"; String str1 = "Java Programming"; String str2 = str1; if (str.equals(str1)) System.out.println("Equal Case 1"); if (str == str1) System.out.println("Equal Case 2"); }}
Output:
Equal Case 1
Equal Case 2
Explanation:The equals() method compares the characters inside a String object.Thus str.equals(str1) comes out to be true.The == operator compares two object references to see whether they refer to the same instance. Now str points to “Java Programming” and then str1 also points to “Java Programming”, hence str == str1 is also true.
8. What is the Output Of the following Program
class demo8 { public static void main(String args[]) { String str = "Java Programming"; String str1 = "Programminggggg"; if (str.regionMatches(5, str1, 0, 11)) System.out.println("Same"); }}
Output:
Same
Explanation:The syntax of the function is: regionMatches( startIndex, stringS, stringS’s_startIndex, numOfCharacters)so starting from index 5, string str1 is compared from index 0 till 11 characters only.Hence output is ‘Same’
9. What is the Output Of the following Program
class demo9 { public static void main(String args[]) { String str = "Java Programming"; String str1 = "Java"; if (str.startsWith("J")) System.out.println("Start Same"); if (str.endsWith("T")) System.out.println("End Same"); }}
Output:
Start Same
Explanation:The startsWith() method determines whether a given String begins with a specified string.The endsWith() determines whether the String in question ends with a specified string.
10. What is the Output Of the following Program
class demo10 { public static void main(String args[]) { String str = "JavaProgramming"; String str1 = "Java"; System.out.println(str.compareTo(str1)); System.out.println(str1.compareTo(str)); }}
Output:
11
-11
Explanation:The String method compareTo( ) serves the purpose of comparing two strings. Whether one string is less than, greater than or equal to the second string.In case 1, comparing JavaProgramming with Java implies JavaProgramming is greater than Java by 11 characters.In case 2, comparing Java with JavaProgramming implies Java is lesser than JavaProgramming by 11 characters (-11).
11. What is the Output Of the following Program
class demo11 { public static void main(String args[]) { String str = "Java Programming"; String str1 = "Java"; System.out.println(str.indexOf("a")); System.out.println(str.indexOf("m")); System.out.println(str.lastIndexOf("a")); System.out.println(str.lastIndexOf("m")); }}
Output:
1
11
10
12
Explanation:indexOf( ) Searches for the first occurrence of a character or substring. lastIndexOf( ) Searches for the last occurrence of a character or substring.
12. What is the Output Of the following Program
class demo12 { public static void main(String args[]) { String str = "Java Programming"; String str1 = "Java"; String str2 = str.substring(5); System.out.println(str2); System.out.println(str.substring(5, 9)); }}
Output:
Programming
Prog
Explanation:constructor substring(int startIndex) takes the substring starting from the specified index till end of the stringconstructor substring(int startIndex, int endIndex) takes the substring from startIndex to endIndex-1
13. What is the Output Of the following Program
class demo13 { public static void main(String args[]) { String str = "Java Programming"; System.out.println(str.replace('a', '9')); }}
Output:
J9v9 Progr9mming
Explanation:The replace( ) method replaces all occurrences of one character in the invoking string with another character.Hence ‘a’ replaced with a ‘9’.
14. What is the Output Of the following Program
class demo14 { public static void main(String args[]) { String str = "Java"; String str1 = "Programming"; System.out.println(str.concat(str1)); }}
Output:
JavaProgramming
Explanation:concat() method simply concatenates one string to the end of the other.
15. What is the Output Of the following Program
class demo15 { public static void main(String args[]) { String str = " Java Programming "; System.out.println(str.trim()); }}
Output:
Java Programming
Explanation:The trim( ) method returns a copy of the invoking string from which any leading and trailing whitespace has been removed. But it does not remove the spaces present between two words.
shubh276
Java-Output
Java-Strings
Program Output
Java-Strings
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
|
[
{
"code": null,
"e": 52,
"s": 24,
"text": "\n18 Sep, 2018"
},
{
"code": null,
"e": 99,
"s": 52,
"text": "Prerequisite : Basics of Strings class in java"
},
{
"code": null,
"e": 146,
"s": 99,
"text": "1. What is the Output Of the following Program"
},
{
"code": "class demo1 { public static void main(String args[]) { String str1 = \"java\"; char arr[] = { 'j', 'a', 'v', 'a', ' ', 'p', 'r', 'o', 'g', 'r', 'a', 'm', 'm', 'i', 'n', 'g' }; String str2 = new String(arr); System.out.println(str1); System.out.println(str2); }}",
"e": 458,
"s": 146,
"text": null
},
{
"code": null,
"e": 466,
"s": 458,
"text": "Output:"
},
{
"code": null,
"e": 489,
"s": 466,
"text": "java\njava programming\n"
},
{
"code": null,
"e": 536,
"s": 489,
"text": "2. What is the Output Of the following Program"
},
{
"code": "class demo2 { public static void main(String args[]) { String str1 = \"\"; char arr[] = { 'j', 'a', 'v', 'a', ' ', 'p', 'r', 'o', 'g', 'r', 'a', 'm', 'm', 'i', 'n', 'g' }; String str2 = new String(arr); String str3 = new String(str2); System.out.println(str1); System.out.println(str2); System.out.println(str3); }}",
"e": 918,
"s": 536,
"text": null
},
{
"code": null,
"e": 926,
"s": 918,
"text": "Output:"
},
{
"code": null,
"e": 962,
"s": 926,
"text": "\njava programming\njava programming\n"
},
{
"code": null,
"e": 1009,
"s": 962,
"text": "3. What is the Output Of the following Program"
},
{
"code": "class demo3 { public static void main(String args[]) { byte[] arr = { 97, 98, 99, 100, 101 }; String str2 = new String(arr); System.out.println(str2); }}",
"e": 1195,
"s": 1009,
"text": null
},
{
"code": null,
"e": 1203,
"s": 1195,
"text": "Output:"
},
{
"code": null,
"e": 1210,
"s": 1203,
"text": "abcde\n"
},
{
"code": null,
"e": 1337,
"s": 1210,
"text": "Explanation:The constructor String( byte[] ) converts the bytes to corresponding characters i.e. 97 converted to character ‘a’"
},
{
"code": null,
"e": 1384,
"s": 1337,
"text": "4. What is the Output Of the following Program"
},
{
"code": "class demo4 { public static void main(String args[]) { String str = \"Java Programming\"; char ch = str.charAt(2); System.out.println(ch); }}",
"e": 1554,
"s": 1384,
"text": null
},
{
"code": null,
"e": 1562,
"s": 1554,
"text": "Output:"
},
{
"code": null,
"e": 1565,
"s": 1562,
"text": "v\n"
},
{
"code": null,
"e": 1641,
"s": 1565,
"text": "Explanation:charAt() function returns the character at the specified index."
},
{
"code": null,
"e": 1688,
"s": 1641,
"text": "5. What is the Output Of the following Program"
},
{
"code": "class demo5 { public static void main(String args[]) { String str = \"Java Programming\"; char arr[] = new char[10]; str.getChars(0, 4, arr, 0); System.out.println(arr); }}",
"e": 1896,
"s": 1688,
"text": null
},
{
"code": null,
"e": 1904,
"s": 1896,
"text": "Output:"
},
{
"code": null,
"e": 1910,
"s": 1904,
"text": "Java\n"
},
{
"code": null,
"e": 2098,
"s": 1910,
"text": "Explanation:The syntax of the method is: getChars(startindex, numOfCharacters, arrayName, startindexOfArrat). So from the string, starting from 0th index, first four characters are taken."
},
{
"code": null,
"e": 2145,
"s": 2098,
"text": "6. What is the Output Of the following Program"
},
{
"code": "class demo6 { public static void main(String args[]) { String str = \"Java Programming\"; char arr[] = new char[20]; arr = str.toCharArray(); System.out.println(arr); }}",
"e": 2350,
"s": 2145,
"text": null
},
{
"code": null,
"e": 2358,
"s": 2350,
"text": "Output:"
},
{
"code": null,
"e": 2376,
"s": 2358,
"text": "Java Programming\n"
},
{
"code": null,
"e": 2453,
"s": 2376,
"text": "Explanation:toCharArray() method converts the string into a character array."
},
{
"code": null,
"e": 2500,
"s": 2453,
"text": "7. What is the Output Of the following Program"
},
{
"code": "class demo7 { public static void main(String args[]) { String str = \"Java Programming\"; String str1 = \"Java Programming\"; String str2 = str1; if (str.equals(str1)) System.out.println(\"Equal Case 1\"); if (str == str1) System.out.println(\"Equal Case 2\"); }}",
"e": 2824,
"s": 2500,
"text": null
},
{
"code": null,
"e": 2832,
"s": 2824,
"text": "Output:"
},
{
"code": null,
"e": 2859,
"s": 2832,
"text": "Equal Case 1\nEqual Case 2\n"
},
{
"code": null,
"e": 3194,
"s": 2859,
"text": "Explanation:The equals() method compares the characters inside a String object.Thus str.equals(str1) comes out to be true.The == operator compares two object references to see whether they refer to the same instance. Now str points to “Java Programming” and then str1 also points to “Java Programming”, hence str == str1 is also true."
},
{
"code": null,
"e": 3241,
"s": 3194,
"text": "8. What is the Output Of the following Program"
},
{
"code": "class demo8 { public static void main(String args[]) { String str = \"Java Programming\"; String str1 = \"Programminggggg\"; if (str.regionMatches(5, str1, 0, 11)) System.out.println(\"Same\"); }}",
"e": 3475,
"s": 3241,
"text": null
},
{
"code": null,
"e": 3483,
"s": 3475,
"text": "Output:"
},
{
"code": null,
"e": 3489,
"s": 3483,
"text": "Same\n"
},
{
"code": null,
"e": 3716,
"s": 3489,
"text": "Explanation:The syntax of the function is: regionMatches( startIndex, stringS, stringS’s_startIndex, numOfCharacters)so starting from index 5, string str1 is compared from index 0 till 11 characters only.Hence output is ‘Same’"
},
{
"code": null,
"e": 3763,
"s": 3716,
"text": "9. What is the Output Of the following Program"
},
{
"code": "class demo9 { public static void main(String args[]) { String str = \"Java Programming\"; String str1 = \"Java\"; if (str.startsWith(\"J\")) System.out.println(\"Start Same\"); if (str.endsWith(\"T\")) System.out.println(\"End Same\"); }}",
"e": 4051,
"s": 3763,
"text": null
},
{
"code": null,
"e": 4059,
"s": 4051,
"text": "Output:"
},
{
"code": null,
"e": 4071,
"s": 4059,
"text": "Start Same\n"
},
{
"code": null,
"e": 4259,
"s": 4071,
"text": "Explanation:The startsWith() method determines whether a given String begins with a specified string.The endsWith() determines whether the String in question ends with a specified string."
},
{
"code": null,
"e": 4307,
"s": 4259,
"text": "10. What is the Output Of the following Program"
},
{
"code": "class demo10 { public static void main(String args[]) { String str = \"JavaProgramming\"; String str1 = \"Java\"; System.out.println(str.compareTo(str1)); System.out.println(str1.compareTo(str)); }}",
"e": 4541,
"s": 4307,
"text": null
},
{
"code": null,
"e": 4549,
"s": 4541,
"text": "Output:"
},
{
"code": null,
"e": 4557,
"s": 4549,
"text": "11\n-11\n"
},
{
"code": null,
"e": 4945,
"s": 4557,
"text": "Explanation:The String method compareTo( ) serves the purpose of comparing two strings. Whether one string is less than, greater than or equal to the second string.In case 1, comparing JavaProgramming with Java implies JavaProgramming is greater than Java by 11 characters.In case 2, comparing Java with JavaProgramming implies Java is lesser than JavaProgramming by 11 characters (-11)."
},
{
"code": null,
"e": 4993,
"s": 4945,
"text": "11. What is the Output Of the following Program"
},
{
"code": "class demo11 { public static void main(String args[]) { String str = \"Java Programming\"; String str1 = \"Java\"; System.out.println(str.indexOf(\"a\")); System.out.println(str.indexOf(\"m\")); System.out.println(str.lastIndexOf(\"a\")); System.out.println(str.lastIndexOf(\"m\")); }}",
"e": 5322,
"s": 4993,
"text": null
},
{
"code": null,
"e": 5330,
"s": 5322,
"text": "Output:"
},
{
"code": null,
"e": 5342,
"s": 5330,
"text": "1\n11\n10\n12\n"
},
{
"code": null,
"e": 5505,
"s": 5342,
"text": "Explanation:indexOf( ) Searches for the first occurrence of a character or substring. lastIndexOf( ) Searches for the last occurrence of a character or substring."
},
{
"code": null,
"e": 5553,
"s": 5505,
"text": "12. What is the Output Of the following Program"
},
{
"code": "class demo12 { public static void main(String args[]) { String str = \"Java Programming\"; String str1 = \"Java\"; String str2 = str.substring(5); System.out.println(str2); System.out.println(str.substring(5, 9)); }}",
"e": 5810,
"s": 5553,
"text": null
},
{
"code": null,
"e": 5818,
"s": 5810,
"text": "Output:"
},
{
"code": null,
"e": 5836,
"s": 5818,
"text": "Programming\nProg\n"
},
{
"code": null,
"e": 6064,
"s": 5836,
"text": "Explanation:constructor substring(int startIndex) takes the substring starting from the specified index till end of the stringconstructor substring(int startIndex, int endIndex) takes the substring from startIndex to endIndex-1"
},
{
"code": null,
"e": 6112,
"s": 6064,
"text": "13. What is the Output Of the following Program"
},
{
"code": "class demo13 { public static void main(String args[]) { String str = \"Java Programming\"; System.out.println(str.replace('a', '9')); }}",
"e": 6272,
"s": 6112,
"text": null
},
{
"code": null,
"e": 6280,
"s": 6272,
"text": "Output:"
},
{
"code": null,
"e": 6298,
"s": 6280,
"text": "J9v9 Progr9mming\n"
},
{
"code": null,
"e": 6451,
"s": 6298,
"text": "Explanation:The replace( ) method replaces all occurrences of one character in the invoking string with another character.Hence ‘a’ replaced with a ‘9’."
},
{
"code": null,
"e": 6499,
"s": 6451,
"text": "14. What is the Output Of the following Program"
},
{
"code": "class demo14 { public static void main(String args[]) { String str = \"Java\"; String str1 = \"Programming\"; System.out.println(str.concat(str1)); }}",
"e": 6678,
"s": 6499,
"text": null
},
{
"code": null,
"e": 6686,
"s": 6678,
"text": "Output:"
},
{
"code": null,
"e": 6703,
"s": 6686,
"text": "JavaProgramming\n"
},
{
"code": null,
"e": 6787,
"s": 6703,
"text": "Explanation:concat() method simply concatenates one string to the end of the other."
},
{
"code": null,
"e": 6835,
"s": 6787,
"text": "15. What is the Output Of the following Program"
},
{
"code": "class demo15 { public static void main(String args[]) { String str = \" Java Programming \"; System.out.println(str.trim()); }}",
"e": 7015,
"s": 6835,
"text": null
},
{
"code": null,
"e": 7023,
"s": 7015,
"text": "Output:"
},
{
"code": null,
"e": 7050,
"s": 7023,
"text": "Java Programming\n"
},
{
"code": null,
"e": 7245,
"s": 7050,
"text": "Explanation:The trim( ) method returns a copy of the invoking string from which any leading and trailing whitespace has been removed. But it does not remove the spaces present between two words."
},
{
"code": null,
"e": 7254,
"s": 7245,
"text": "shubh276"
},
{
"code": null,
"e": 7266,
"s": 7254,
"text": "Java-Output"
},
{
"code": null,
"e": 7279,
"s": 7266,
"text": "Java-Strings"
},
{
"code": null,
"e": 7294,
"s": 7279,
"text": "Program Output"
},
{
"code": null,
"e": 7307,
"s": 7294,
"text": "Java-Strings"
}
] |
Exporting Bokeh Plots
|
28 Jul, 2021
Bokeh is an interactive data visualization library available for Python. Using Bokeh we can embed our plot in any HTML file. It internally uses HTML and JavaScript to render the plot in Web Browsers for representation. Under the hood, it converts the data source into a JSON file which is used as input for BokehJS (a JavaScript library) and renders the visualizations in modern browsers. In this article, we will see how we can export/save a Bokeh plot to local storage.
We will need the following dependencies to export the plots in bokeh:
Selenium
WebDriver
To install these two using conda, run the following command one after another:
conda install selenium geckodriver -c conda-forge
conda install selenium python-chromedriver-binary -c conda-forge
using pip:
pip install selenium geckodriver firefox
Using the export_png() function, we can export our plot as a PNG image directly from the Python code.
Syntax: export_png(obj, filename, width, height, webdriver)
Arguments:
obj: obj can be any plot that we are going to export.
filename: It is an optional argument, the default plot filename will be the python file name.
width: It is an optional argument, used to set the width of the exported plot layout obj, by default it will be ignored.
height: It is an optional argument, used to set the height of the exported plot layout obj, by default it will be ignored.
webdriver: It is an optional argument, used to set the default web driver instance to use to export the plot. A selenium web driver is by default if we don’t specify anything.
First, prepare the data to be visualized then call the figure() function to creates a plot with the default properties, such as its title and axes labels. Use the different varieties of renderers to create different varieties of plots. For example, to render a circle, we can use the circle() function instead of line() to render circles. Save the plot using export_png(plot_obj, filename) function and then display the resultant plot using show() function.
Python3
# importing necessary librariesfrom bokeh.plotting import figurefrom bokeh.plotting import output_filefrom bokeh.plotting import showfrom bokeh.io import export_png # dummy datax = [2, 4, 8, 10, 12, 14]y = [22, 54, 18, 50, 22, 24] # set output to static HTML fileoutput_file("line.html") # Adding plotfig = figure( title="Bokeh Plot", x_axis_label='x-axis', y_axis_label='y-axis',) # add a line renderer to plot linefig.line(x, y) # saving the plot on diskprint('Exporting bokeh_plot.png.....')export_png(fig, filename = "bokeh_plot.png") # displaying plotshow(fig)
Output:
Exporting bokeh_plot.png....
Exported as PNG
Using the export_svg() function from bokeh.io, we can export our plot as an SVG image directly from the Python code.
Syntax: export_png(obj, filename, width, height, webdriver, timeout)
Arguments:
obj: obj can be any plot that we are going to export.
filename: It is an optional argument, the default plot filename will be the python file name.
width: It is an optional argument, used to set the width of the exported plot layout obj, by default it will be ignored.
height: It is an optional argument, used to set the height of the exported plot layout obj, by default it will be ignored.
webdriver: It is an optional argument, used to set the default web driver instance to use to export the plot. A selenium web driver is by default if we don’t specify anything.
timeout: The maximum amount of time (in seconds) to wait for Bokeh to initialize. Its default value is 5s.
First, prepare the data to be visualized, then call the figure() function to creates a plot with the default properties, such as its title and axes labels. Use different varieties of renderers to create a different variety of plots and save the plot using export_svg(plot_obj, filename) function and then display the resultant plot using show() function.
Python3
# importing necessary librariesfrom bokeh.plotting import figurefrom bokeh.plotting import output_filefrom bokeh.plotting import showfrom bokeh.io import export_svgs # dummy datax = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]y = [11, 12, 13, 14, 15, 16, 18, 17, 19, 20] output_file("circle_bokeh.html") # Adding plotfig = figure( title="SVG Bokeh Plot", x_axis_label='x-axis', y_axis_label='y-axis',) # add a circle renderer to plotfig.circle(x, y, fill_color="green", size=20) # saving the plot on diskprint('Exporting circle_bokeh.svg.....')fig.output_backend = "svg"export_svgs(fig, filename = "circle_bokeh.svg") # displaying plotshow(fig)
Output:
Exporting circle_bokeh.svg.....
Exported as SVG
Note: The exported plot will be saved in the folder where the python code file is presented.
Picked
Python-Bokeh
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
Python | os.path.join() method
How to drop one or multiple columns in Pandas Dataframe
How To Convert Python Dictionary To JSON?
Check if element exists in list in Python
Python | Get unique values from a list
Python | datetime.timedelta() function
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n28 Jul, 2021"
},
{
"code": null,
"e": 500,
"s": 28,
"text": "Bokeh is an interactive data visualization library available for Python. Using Bokeh we can embed our plot in any HTML file. It internally uses HTML and JavaScript to render the plot in Web Browsers for representation. Under the hood, it converts the data source into a JSON file which is used as input for BokehJS (a JavaScript library) and renders the visualizations in modern browsers. In this article, we will see how we can export/save a Bokeh plot to local storage."
},
{
"code": null,
"e": 570,
"s": 500,
"text": "We will need the following dependencies to export the plots in bokeh:"
},
{
"code": null,
"e": 579,
"s": 570,
"text": "Selenium"
},
{
"code": null,
"e": 589,
"s": 579,
"text": "WebDriver"
},
{
"code": null,
"e": 668,
"s": 589,
"text": "To install these two using conda, run the following command one after another:"
},
{
"code": null,
"e": 783,
"s": 668,
"text": "conda install selenium geckodriver -c conda-forge\nconda install selenium python-chromedriver-binary -c conda-forge"
},
{
"code": null,
"e": 794,
"s": 783,
"text": "using pip:"
},
{
"code": null,
"e": 835,
"s": 794,
"text": "pip install selenium geckodriver firefox"
},
{
"code": null,
"e": 937,
"s": 835,
"text": "Using the export_png() function, we can export our plot as a PNG image directly from the Python code."
},
{
"code": null,
"e": 997,
"s": 937,
"text": "Syntax: export_png(obj, filename, width, height, webdriver)"
},
{
"code": null,
"e": 1008,
"s": 997,
"text": "Arguments:"
},
{
"code": null,
"e": 1062,
"s": 1008,
"text": "obj: obj can be any plot that we are going to export."
},
{
"code": null,
"e": 1156,
"s": 1062,
"text": "filename: It is an optional argument, the default plot filename will be the python file name."
},
{
"code": null,
"e": 1278,
"s": 1156,
"text": "width: It is an optional argument, used to set the width of the exported plot layout obj, by default it will be ignored."
},
{
"code": null,
"e": 1401,
"s": 1278,
"text": "height: It is an optional argument, used to set the height of the exported plot layout obj, by default it will be ignored."
},
{
"code": null,
"e": 1577,
"s": 1401,
"text": "webdriver: It is an optional argument, used to set the default web driver instance to use to export the plot. A selenium web driver is by default if we don’t specify anything."
},
{
"code": null,
"e": 2035,
"s": 1577,
"text": "First, prepare the data to be visualized then call the figure() function to creates a plot with the default properties, such as its title and axes labels. Use the different varieties of renderers to create different varieties of plots. For example, to render a circle, we can use the circle() function instead of line() to render circles. Save the plot using export_png(plot_obj, filename) function and then display the resultant plot using show() function."
},
{
"code": null,
"e": 2043,
"s": 2035,
"text": "Python3"
},
{
"code": "# importing necessary librariesfrom bokeh.plotting import figurefrom bokeh.plotting import output_filefrom bokeh.plotting import showfrom bokeh.io import export_png # dummy datax = [2, 4, 8, 10, 12, 14]y = [22, 54, 18, 50, 22, 24] # set output to static HTML fileoutput_file(\"line.html\") # Adding plotfig = figure( title=\"Bokeh Plot\", x_axis_label='x-axis', y_axis_label='y-axis',) # add a line renderer to plot linefig.line(x, y) # saving the plot on diskprint('Exporting bokeh_plot.png.....')export_png(fig, filename = \"bokeh_plot.png\") # displaying plotshow(fig)",
"e": 2624,
"s": 2043,
"text": null
},
{
"code": null,
"e": 2632,
"s": 2624,
"text": "Output:"
},
{
"code": null,
"e": 2661,
"s": 2632,
"text": "Exporting bokeh_plot.png...."
},
{
"code": null,
"e": 2677,
"s": 2661,
"text": "Exported as PNG"
},
{
"code": null,
"e": 2794,
"s": 2677,
"text": "Using the export_svg() function from bokeh.io, we can export our plot as an SVG image directly from the Python code."
},
{
"code": null,
"e": 2863,
"s": 2794,
"text": "Syntax: export_png(obj, filename, width, height, webdriver, timeout)"
},
{
"code": null,
"e": 2874,
"s": 2863,
"text": "Arguments:"
},
{
"code": null,
"e": 2928,
"s": 2874,
"text": "obj: obj can be any plot that we are going to export."
},
{
"code": null,
"e": 3022,
"s": 2928,
"text": "filename: It is an optional argument, the default plot filename will be the python file name."
},
{
"code": null,
"e": 3144,
"s": 3022,
"text": "width: It is an optional argument, used to set the width of the exported plot layout obj, by default it will be ignored."
},
{
"code": null,
"e": 3267,
"s": 3144,
"text": "height: It is an optional argument, used to set the height of the exported plot layout obj, by default it will be ignored."
},
{
"code": null,
"e": 3443,
"s": 3267,
"text": "webdriver: It is an optional argument, used to set the default web driver instance to use to export the plot. A selenium web driver is by default if we don’t specify anything."
},
{
"code": null,
"e": 3550,
"s": 3443,
"text": "timeout: The maximum amount of time (in seconds) to wait for Bokeh to initialize. Its default value is 5s."
},
{
"code": null,
"e": 3905,
"s": 3550,
"text": "First, prepare the data to be visualized, then call the figure() function to creates a plot with the default properties, such as its title and axes labels. Use different varieties of renderers to create a different variety of plots and save the plot using export_svg(plot_obj, filename) function and then display the resultant plot using show() function."
},
{
"code": null,
"e": 3913,
"s": 3905,
"text": "Python3"
},
{
"code": "# importing necessary librariesfrom bokeh.plotting import figurefrom bokeh.plotting import output_filefrom bokeh.plotting import showfrom bokeh.io import export_svgs # dummy datax = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]y = [11, 12, 13, 14, 15, 16, 18, 17, 19, 20] output_file(\"circle_bokeh.html\") # Adding plotfig = figure( title=\"SVG Bokeh Plot\", x_axis_label='x-axis', y_axis_label='y-axis',) # add a circle renderer to plotfig.circle(x, y, fill_color=\"green\", size=20) # saving the plot on diskprint('Exporting circle_bokeh.svg.....')fig.output_backend = \"svg\"export_svgs(fig, filename = \"circle_bokeh.svg\") # displaying plotshow(fig)",
"e": 4562,
"s": 3913,
"text": null
},
{
"code": null,
"e": 4570,
"s": 4562,
"text": "Output:"
},
{
"code": null,
"e": 4602,
"s": 4570,
"text": "Exporting circle_bokeh.svg....."
},
{
"code": null,
"e": 4619,
"s": 4602,
"text": "Exported as SVG "
},
{
"code": null,
"e": 4712,
"s": 4619,
"text": "Note: The exported plot will be saved in the folder where the python code file is presented."
},
{
"code": null,
"e": 4719,
"s": 4712,
"text": "Picked"
},
{
"code": null,
"e": 4732,
"s": 4719,
"text": "Python-Bokeh"
},
{
"code": null,
"e": 4739,
"s": 4732,
"text": "Python"
},
{
"code": null,
"e": 4837,
"s": 4739,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 4869,
"s": 4837,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 4896,
"s": 4869,
"text": "Python Classes and Objects"
},
{
"code": null,
"e": 4917,
"s": 4896,
"text": "Python OOPs Concepts"
},
{
"code": null,
"e": 4940,
"s": 4917,
"text": "Introduction To PYTHON"
},
{
"code": null,
"e": 4971,
"s": 4940,
"text": "Python | os.path.join() method"
},
{
"code": null,
"e": 5027,
"s": 4971,
"text": "How to drop one or multiple columns in Pandas Dataframe"
},
{
"code": null,
"e": 5069,
"s": 5027,
"text": "How To Convert Python Dictionary To JSON?"
},
{
"code": null,
"e": 5111,
"s": 5069,
"text": "Check if element exists in list in Python"
},
{
"code": null,
"e": 5150,
"s": 5111,
"text": "Python | Get unique values from a list"
}
] |
SQL | CREATE
|
21 Mar, 2018
There are two CREATE statements available in SQL:
CREATE DATABASECREATE TABLE
CREATE DATABASE
CREATE TABLE
CREATE DATABASE
A Database is defined as a structured set of data. So, in SQL the very first step to store the data in a well structured manner is to create a database. The CREATE DATABASE statement is used to create a new database in SQL.
Syntax:
CREATE DATABASE database_name;
database_name: name of the database.
Example Query:This query will create a new database in SQL and name the database as my_database.
CREATE DATABASE my_database;
CREATE TABLE
We have learned above about creating databases. Now to store the data we need a table to do that. The CREATE TABLE statement is used to create a table in SQL. We know that a table comprises of rows and columns. So while creating tables we have to provide all the information to SQL about the names of the columns, type of data to be stored in columns, size of the data etc. Let us now dive into details on how to use CREATE TABLE statement to create tables in SQL.
Syntax:
CREATE TABLE table_name
(
column1 data_type(size),
column2 data_type(size),
column3 data_type(size),
....
);
table_name: name of the table.
column1 name of the first column.
data_type: Type of data we want to store in the particular column.
For example,int for integer data.
size: Size of the data we can store in a particular column. For example if for
a column we specify the data_type as int and size as 10 then this column can store an integer
number of maximum 10 digits.
Example Query:This query will create a table named Students with three columns, ROLL_NO, NAME and SUBJECT.
CREATE TABLE Students
(
ROLL_NO int(3),
NAME varchar(20),
SUBJECT varchar(20),
);
This query will create a table named Students. The ROLL_NO field is of type int and can store an integer number of size 3. The next two columns NAME and SUBJECT are of type varchar and can store characters and the size 20 specifies that these two fields can hold maximum of 20 characters.
This article is contributed by Harsh Agarwal. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
SQL-Clauses-Operators
Articles
DBMS
SQL
DBMS
SQL
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Time Complexity and Space Complexity
SQL Interview Questions
Understanding "extern" keyword in C
SQL | Views
Java Tutorial
ACID Properties in DBMS
SQL query to find second highest salary?
Normal Forms in DBMS
CTE in SQL
Difference between Clustered and Non-clustered index
|
[
{
"code": null,
"e": 53,
"s": 25,
"text": "\n21 Mar, 2018"
},
{
"code": null,
"e": 103,
"s": 53,
"text": "There are two CREATE statements available in SQL:"
},
{
"code": null,
"e": 131,
"s": 103,
"text": "CREATE DATABASECREATE TABLE"
},
{
"code": null,
"e": 147,
"s": 131,
"text": "CREATE DATABASE"
},
{
"code": null,
"e": 160,
"s": 147,
"text": "CREATE TABLE"
},
{
"code": null,
"e": 176,
"s": 160,
"text": "CREATE DATABASE"
},
{
"code": null,
"e": 400,
"s": 176,
"text": "A Database is defined as a structured set of data. So, in SQL the very first step to store the data in a well structured manner is to create a database. The CREATE DATABASE statement is used to create a new database in SQL."
},
{
"code": null,
"e": 408,
"s": 400,
"text": "Syntax:"
},
{
"code": null,
"e": 478,
"s": 408,
"text": "CREATE DATABASE database_name;\n\ndatabase_name: name of the database.\n"
},
{
"code": null,
"e": 575,
"s": 478,
"text": "Example Query:This query will create a new database in SQL and name the database as my_database."
},
{
"code": null,
"e": 605,
"s": 575,
"text": "CREATE DATABASE my_database;\n"
},
{
"code": null,
"e": 618,
"s": 605,
"text": "CREATE TABLE"
},
{
"code": null,
"e": 1083,
"s": 618,
"text": "We have learned above about creating databases. Now to store the data we need a table to do that. The CREATE TABLE statement is used to create a table in SQL. We know that a table comprises of rows and columns. So while creating tables we have to provide all the information to SQL about the names of the columns, type of data to be stored in columns, size of the data etc. Let us now dive into details on how to use CREATE TABLE statement to create tables in SQL."
},
{
"code": null,
"e": 1091,
"s": 1083,
"text": "Syntax:"
},
{
"code": null,
"e": 1585,
"s": 1091,
"text": "CREATE TABLE table_name\n(\ncolumn1 data_type(size),\ncolumn2 data_type(size),\ncolumn3 data_type(size),\n....\n);\n\ntable_name: name of the table.\ncolumn1 name of the first column.\ndata_type: Type of data we want to store in the particular column. \n For example,int for integer data.\nsize: Size of the data we can store in a particular column. For example if for\na column we specify the data_type as int and size as 10 then this column can store an integer\nnumber of maximum 10 digits. \n"
},
{
"code": null,
"e": 1692,
"s": 1585,
"text": "Example Query:This query will create a table named Students with three columns, ROLL_NO, NAME and SUBJECT."
},
{
"code": null,
"e": 1775,
"s": 1692,
"text": "CREATE TABLE Students\n(\nROLL_NO int(3),\nNAME varchar(20),\nSUBJECT varchar(20),\n);\n"
},
{
"code": null,
"e": 2064,
"s": 1775,
"text": "This query will create a table named Students. The ROLL_NO field is of type int and can store an integer number of size 3. The next two columns NAME and SUBJECT are of type varchar and can store characters and the size 20 specifies that these two fields can hold maximum of 20 characters."
},
{
"code": null,
"e": 2365,
"s": 2064,
"text": "This article is contributed by Harsh Agarwal. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks."
},
{
"code": null,
"e": 2490,
"s": 2365,
"text": "Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above."
},
{
"code": null,
"e": 2512,
"s": 2490,
"text": "SQL-Clauses-Operators"
},
{
"code": null,
"e": 2521,
"s": 2512,
"text": "Articles"
},
{
"code": null,
"e": 2526,
"s": 2521,
"text": "DBMS"
},
{
"code": null,
"e": 2530,
"s": 2526,
"text": "SQL"
},
{
"code": null,
"e": 2535,
"s": 2530,
"text": "DBMS"
},
{
"code": null,
"e": 2539,
"s": 2535,
"text": "SQL"
},
{
"code": null,
"e": 2637,
"s": 2539,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 2674,
"s": 2637,
"text": "Time Complexity and Space Complexity"
},
{
"code": null,
"e": 2698,
"s": 2674,
"text": "SQL Interview Questions"
},
{
"code": null,
"e": 2734,
"s": 2698,
"text": "Understanding \"extern\" keyword in C"
},
{
"code": null,
"e": 2746,
"s": 2734,
"text": "SQL | Views"
},
{
"code": null,
"e": 2760,
"s": 2746,
"text": "Java Tutorial"
},
{
"code": null,
"e": 2784,
"s": 2760,
"text": "ACID Properties in DBMS"
},
{
"code": null,
"e": 2825,
"s": 2784,
"text": "SQL query to find second highest salary?"
},
{
"code": null,
"e": 2846,
"s": 2825,
"text": "Normal Forms in DBMS"
},
{
"code": null,
"e": 2857,
"s": 2846,
"text": "CTE in SQL"
}
] |
FREE Online Courses By GeeksforGeeks – Learn New Tech Skills!
|
06 Jan, 2022
Learning should never stop! And what can be better than quality Online Learning resources to keep continuing your learning endeavors especially amidst this covid outbreak. Truly, Online courses give you the flexibility to learn at your own pace and comfort place. Now, for every techie, here’s an announcement – GeeksforGeeks is here with various exciting courses that cost you nothing more than your time and effort!
These courses provided by GeeksforGeeks are absolutely free and bring the best quality content be it video-based or theoretical. Each course has lifetime accessibility, is track-based, has assessments and practice sessions (to implement your learning), and is also updated. You can go through any one of these at your own pace. Here, the quality and quantity are the best on their own.
You’re a guy from computer science, mechanical, civil, automobile, or any other streams, it doesn’t matter. These are the courses that every individual will be needing to start a specialized career in the tech world. As these courses are free of cost, all are welcome to grab this opportunity and learn as much as they can. Go through each one of the courses which are relevant to you.
So, let’s start.
If you want to build your career in web development you must definitely go through this. From scratch to end, everything is available here about the basic functions, events, and objects of JavaScript. This is purely free and consists of 10 series where after completing 7 series, you’ll be asked to work on LIVE projects which will enhance your ability to learn it efficiently and make you industry-ready. Also, they’re accessible lifetime so you don’t need to worry if you couldn’t understand in one go.
HTML (HyperText Markup Language) is the basic language to develop your own webpage. If you’re one of those who are interested in how the web page is created, you must dive here. Even if you’re not from the CSE/IT background, no worries. It’s as simple as sipping a glass of water. It makes you clear on all the topics like how to create headings, paragraphs, add images, add links, create tables, and a lot more. There will also be Q&A sessions to get you rid of your doubts.
Java is something that most of us are afraid of. But, here we provide you with ease to enjoy learning it. This is the Core Java course that will help you master the basics of Java. You’ll get to know about the functions, loops, patterns, and Java Collections. Since “PRACTICE MAKES A HUMAN PERFECT”, there’ll be practice sessions that will help you to implement what you learn. Once you master this, you can move to the advanced section through our other course – Fundamentals of Java and Java Collections.
Python is the easiest language anyone can learn and trendy too. In this course, you’ll get all the basics of Python which is the foundation to build a project. Using objects, classes, functions, constructors, understanding the difference between tuple, list, set, and dictionary to use it as per the requirement. The looping structure is also well explained here. Register for this course and try to gain as much as possible.
If you understand Java, you can learn any language easily. Since Java describes each operation particularly. This course elucidates(describes) the basics of Java on how to perform string operations, control functions, work on operators, arrays. To start your learning, this is a beginner-level course to have an idea about the stepping stones of Java. There’ll also be assessments to check your progress.
C/C++ can be considered as the basic and root of all languages. Once you enter into this course, you’ll enhance your technical skills by learning about pointers, arrays, strings, and many more things. You’ll learn about C++, how to take input/output, data types, etc. Some topics like stacks, queues, which appear to be so tough, will seem easy once you learn through this course. To explore more, dive deep into the course.
All the above-mentioned courses are purely free and give you the best of it. Each topic is explained so clearly that even a beginner can grasp the knowledge so well. These courses provide lifetime accessibility (anytime and anywhere), assessments (to check how well you’ve learned things), theories (if you couldn’t get it through the video), and many more things. Be the first to register and have fun with the courses!
GFG-Course
GFG-Update
GBlog
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
|
[
{
"code": null,
"e": 52,
"s": 24,
"text": "\n06 Jan, 2022"
},
{
"code": null,
"e": 470,
"s": 52,
"text": "Learning should never stop! And what can be better than quality Online Learning resources to keep continuing your learning endeavors especially amidst this covid outbreak. Truly, Online courses give you the flexibility to learn at your own pace and comfort place. Now, for every techie, here’s an announcement – GeeksforGeeks is here with various exciting courses that cost you nothing more than your time and effort!"
},
{
"code": null,
"e": 858,
"s": 470,
"text": "These courses provided by GeeksforGeeks are absolutely free and bring the best quality content be it video-based or theoretical. Each course has lifetime accessibility, is track-based, has assessments and practice sessions (to implement your learning), and is also updated. You can go through any one of these at your own pace. Here, the quality and quantity are the best on their own. "
},
{
"code": null,
"e": 1244,
"s": 858,
"text": "You’re a guy from computer science, mechanical, civil, automobile, or any other streams, it doesn’t matter. These are the courses that every individual will be needing to start a specialized career in the tech world. As these courses are free of cost, all are welcome to grab this opportunity and learn as much as they can. Go through each one of the courses which are relevant to you."
},
{
"code": null,
"e": 1261,
"s": 1244,
"text": "So, let’s start."
},
{
"code": null,
"e": 1768,
"s": 1261,
"text": "If you want to build your career in web development you must definitely go through this. From scratch to end, everything is available here about the basic functions, events, and objects of JavaScript. This is purely free and consists of 10 series where after completing 7 series, you’ll be asked to work on LIVE projects which will enhance your ability to learn it efficiently and make you industry-ready. Also, they’re accessible lifetime so you don’t need to worry if you couldn’t understand in one go. "
},
{
"code": null,
"e": 2246,
"s": 1768,
"text": "HTML (HyperText Markup Language) is the basic language to develop your own webpage. If you’re one of those who are interested in how the web page is created, you must dive here. Even if you’re not from the CSE/IT background, no worries. It’s as simple as sipping a glass of water. It makes you clear on all the topics like how to create headings, paragraphs, add images, add links, create tables, and a lot more. There will also be Q&A sessions to get you rid of your doubts. "
},
{
"code": null,
"e": 2753,
"s": 2246,
"text": "Java is something that most of us are afraid of. But, here we provide you with ease to enjoy learning it. This is the Core Java course that will help you master the basics of Java. You’ll get to know about the functions, loops, patterns, and Java Collections. Since “PRACTICE MAKES A HUMAN PERFECT”, there’ll be practice sessions that will help you to implement what you learn. Once you master this, you can move to the advanced section through our other course – Fundamentals of Java and Java Collections."
},
{
"code": null,
"e": 3181,
"s": 2753,
"text": "Python is the easiest language anyone can learn and trendy too. In this course, you’ll get all the basics of Python which is the foundation to build a project. Using objects, classes, functions, constructors, understanding the difference between tuple, list, set, and dictionary to use it as per the requirement. The looping structure is also well explained here. Register for this course and try to gain as much as possible. "
},
{
"code": null,
"e": 3588,
"s": 3181,
"text": "If you understand Java, you can learn any language easily. Since Java describes each operation particularly. This course elucidates(describes) the basics of Java on how to perform string operations, control functions, work on operators, arrays. To start your learning, this is a beginner-level course to have an idea about the stepping stones of Java. There’ll also be assessments to check your progress. "
},
{
"code": null,
"e": 4013,
"s": 3588,
"text": "C/C++ can be considered as the basic and root of all languages. Once you enter into this course, you’ll enhance your technical skills by learning about pointers, arrays, strings, and many more things. You’ll learn about C++, how to take input/output, data types, etc. Some topics like stacks, queues, which appear to be so tough, will seem easy once you learn through this course. To explore more, dive deep into the course."
},
{
"code": null,
"e": 4434,
"s": 4013,
"text": "All the above-mentioned courses are purely free and give you the best of it. Each topic is explained so clearly that even a beginner can grasp the knowledge so well. These courses provide lifetime accessibility (anytime and anywhere), assessments (to check how well you’ve learned things), theories (if you couldn’t get it through the video), and many more things. Be the first to register and have fun with the courses!"
},
{
"code": null,
"e": 4445,
"s": 4434,
"text": "GFG-Course"
},
{
"code": null,
"e": 4456,
"s": 4445,
"text": "GFG-Update"
},
{
"code": null,
"e": 4462,
"s": 4456,
"text": "GBlog"
}
] |
How to print a list in Scala
|
15 Apr, 2019
In Scala, list is defined under scala.collection.immutable package. A list is a collection of same type elements which contains immutable data.
There are multiple ways to create a List in Scala. Let’s see few basic on how to create a Scala List.
Create an empty ListExample :// Scala program to create an empty list import scala.collection.immutable._ // Creating object object GFG{ // Main method def main(args:Array[String]) { // Creating an Empty List. val emptylist: List[Nothing] = List() println("The empty list is: " + emptylist) } } Output:The empty list is: List()
// Scala program to create an empty list import scala.collection.immutable._ // Creating object object GFG{ // Main method def main(args:Array[String]) { // Creating an Empty List. val emptylist: List[Nothing] = List() println("The empty list is: " + emptylist) } }
Output:
The empty list is: List()
Create a simple listExample :// Scala program to create a simple Immutable lists import scala.collection.immutable._ // Creating object object GFG { // Main method def main(args:Array[String]) { // Creating and initializing immutable lists val mylist: List[String] = List("Geeks", "For", "geeks") // Display the value of mylist1 println("List is: " + mylist) } } Output:List is: List(Geeks, For, geeks)
// Scala program to create a simple Immutable lists import scala.collection.immutable._ // Creating object object GFG { // Main method def main(args:Array[String]) { // Creating and initializing immutable lists val mylist: List[String] = List("Geeks", "For", "geeks") // Display the value of mylist1 println("List is: " + mylist) } }
Output:
List is: List(Geeks, For, geeks)
Using for loop to print elements of ListExample :// Scala program to print immutable lists import scala.collection.immutable._ // Creating object object GFG{ // Main method def main(args:Array[String]) { // Creating and initializing immutable lists val mylist: List[String] = List("Geeks", "For", "geeks", "is", "a", "fabulous", "portal") // Display the value of mylist using for loop for(element<-mylist) { println(element) } } } Output:Geeks
For
geeks
is
a
fabulous
portal
// Scala program to print immutable lists import scala.collection.immutable._ // Creating object object GFG{ // Main method def main(args:Array[String]) { // Creating and initializing immutable lists val mylist: List[String] = List("Geeks", "For", "geeks", "is", "a", "fabulous", "portal") // Display the value of mylist using for loop for(element<-mylist) { println(element) } } }
Output:
Geeks
For
geeks
is
a
fabulous
portal
Scala
scala-collection
Scala
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Type Casting in Scala
Class and Object in Scala
Scala Tutorial – Learn Scala with Step By Step Guide
Scala String substring() method with example
Operators in Scala
Scala Constructors
Enumeration in Scala
Lambda Expression in Scala
How to Install Scala with VSCode?
Scala String replace() method with example
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n15 Apr, 2019"
},
{
"code": null,
"e": 172,
"s": 28,
"text": "In Scala, list is defined under scala.collection.immutable package. A list is a collection of same type elements which contains immutable data."
},
{
"code": null,
"e": 274,
"s": 172,
"text": "There are multiple ways to create a List in Scala. Let’s see few basic on how to create a Scala List."
},
{
"code": null,
"e": 646,
"s": 274,
"text": "Create an empty ListExample :// Scala program to create an empty list import scala.collection.immutable._ // Creating object object GFG{ // Main method def main(args:Array[String]) { // Creating an Empty List. val emptylist: List[Nothing] = List() println(\"The empty list is: \" + emptylist) } } Output:The empty list is: List() "
},
{
"code": "// Scala program to create an empty list import scala.collection.immutable._ // Creating object object GFG{ // Main method def main(args:Array[String]) { // Creating an Empty List. val emptylist: List[Nothing] = List() println(\"The empty list is: \" + emptylist) } } ",
"e": 956,
"s": 646,
"text": null
},
{
"code": null,
"e": 964,
"s": 956,
"text": "Output:"
},
{
"code": null,
"e": 990,
"s": 964,
"text": "The empty list is: List()"
},
{
"code": null,
"e": 1461,
"s": 992,
"text": "Create a simple listExample :// Scala program to create a simple Immutable lists import scala.collection.immutable._ // Creating object object GFG { // Main method def main(args:Array[String]) { // Creating and initializing immutable lists val mylist: List[String] = List(\"Geeks\", \"For\", \"geeks\") // Display the value of mylist1 println(\"List is: \" + mylist) } } Output:List is: List(Geeks, For, geeks) "
},
{
"code": "// Scala program to create a simple Immutable lists import scala.collection.immutable._ // Creating object object GFG { // Main method def main(args:Array[String]) { // Creating and initializing immutable lists val mylist: List[String] = List(\"Geeks\", \"For\", \"geeks\") // Display the value of mylist1 println(\"List is: \" + mylist) } } ",
"e": 1861,
"s": 1461,
"text": null
},
{
"code": null,
"e": 1869,
"s": 1861,
"text": "Output:"
},
{
"code": null,
"e": 1902,
"s": 1869,
"text": "List is: List(Geeks, For, geeks)"
},
{
"code": null,
"e": 2576,
"s": 1904,
"text": "Using for loop to print elements of ListExample :// Scala program to print immutable lists import scala.collection.immutable._ // Creating object object GFG{ // Main method def main(args:Array[String]) { // Creating and initializing immutable lists val mylist: List[String] = List(\"Geeks\", \"For\", \"geeks\", \"is\", \"a\", \"fabulous\", \"portal\") // Display the value of mylist using for loop for(element<-mylist) { println(element) } } } Output:Geeks\nFor\ngeeks\nis\na\nfabulous\nportal"
},
{
"code": "// Scala program to print immutable lists import scala.collection.immutable._ // Creating object object GFG{ // Main method def main(args:Array[String]) { // Creating and initializing immutable lists val mylist: List[String] = List(\"Geeks\", \"For\", \"geeks\", \"is\", \"a\", \"fabulous\", \"portal\") // Display the value of mylist using for loop for(element<-mylist) { println(element) } } } ",
"e": 3156,
"s": 2576,
"text": null
},
{
"code": null,
"e": 3164,
"s": 3156,
"text": "Output:"
},
{
"code": null,
"e": 3201,
"s": 3164,
"text": "Geeks\nFor\ngeeks\nis\na\nfabulous\nportal"
},
{
"code": null,
"e": 3207,
"s": 3201,
"text": "Scala"
},
{
"code": null,
"e": 3224,
"s": 3207,
"text": "scala-collection"
},
{
"code": null,
"e": 3230,
"s": 3224,
"text": "Scala"
},
{
"code": null,
"e": 3328,
"s": 3230,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 3350,
"s": 3328,
"text": "Type Casting in Scala"
},
{
"code": null,
"e": 3376,
"s": 3350,
"text": "Class and Object in Scala"
},
{
"code": null,
"e": 3429,
"s": 3376,
"text": "Scala Tutorial – Learn Scala with Step By Step Guide"
},
{
"code": null,
"e": 3474,
"s": 3429,
"text": "Scala String substring() method with example"
},
{
"code": null,
"e": 3493,
"s": 3474,
"text": "Operators in Scala"
},
{
"code": null,
"e": 3512,
"s": 3493,
"text": "Scala Constructors"
},
{
"code": null,
"e": 3533,
"s": 3512,
"text": "Enumeration in Scala"
},
{
"code": null,
"e": 3560,
"s": 3533,
"text": "Lambda Expression in Scala"
},
{
"code": null,
"e": 3594,
"s": 3560,
"text": "How to Install Scala with VSCode?"
}
] |
Python – Characters occurring in multiple Strings
|
22 Apr, 2020
Sometimes, while working with Python strings, we can have problem in which we need to extract the characters which have occurrences in more than one string in string list. This kind of problem usually occurs in web development and Data Science domains. Lets discuss certain ways in which this task can be performed.
Method #1 : Using Counter() + set()This is one of the ways in which this task can be performed. In this, we check for all the strings and compute the character frequency in each string and return the character which have more than one string occurrence.
# Python3 code to demonstrate working of # Characters occurring in multiple Strings# Using Counter() + set()from itertools import chainfrom collections import Counter # initializing listtest_list = ['gfg', 'is', 'best', 'for', 'geeks', 'and', 'cs'] # printing original listprint("The original list is : " + str(test_list)) # Characters occurring in multiple Strings# Using Counter() + set()temp = (set(sub) for sub in test_list)cntr = Counter(chain.from_iterable(temp))res = [chr for chr, count in cntr.items() if count >= 2] # printing result print("Characters with Multiple String occurrence : " + str(res))
The original list is : [‘gfg’, ‘is’, ‘best’, ‘for’, ‘geeks’, ‘and’, ‘cs’]Characters with Multiple String occurrence : [‘g’, ‘e’, ‘f’, ‘s’]
Method #2 : Using list comprehension + Counter() + set()This is one of the way in which this task can be performed. In this, we perform similar task as above, the difference is that we perform in compact and one-liner way using list comprehension.
# Python3 code to demonstrate working of # Characters occurring in multiple Strings# Using list comprehension + Counter() + set()from itertools import chainfrom collections import Counter # initializing listtest_list = ['gfg', 'is', 'best', 'for', 'geeks', 'and', 'cs'] # printing original listprint("The original list is : " + str(test_list)) # Characters occurring in multiple Strings# Using list comprehension + Counter() + set()res = [key for key, val in Counter([ele for sub in test_list for ele in set(sub)]).items() if val > 1] # printing result print("Characters with Multiple String occurrence : " + str(res))
The original list is : [‘gfg’, ‘is’, ‘best’, ‘for’, ‘geeks’, ‘and’, ‘cs’]Characters with Multiple String occurrence : [‘g’, ‘e’, ‘f’, ‘s’]
Python list-programs
Python
Python Programs
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n22 Apr, 2020"
},
{
"code": null,
"e": 344,
"s": 28,
"text": "Sometimes, while working with Python strings, we can have problem in which we need to extract the characters which have occurrences in more than one string in string list. This kind of problem usually occurs in web development and Data Science domains. Lets discuss certain ways in which this task can be performed."
},
{
"code": null,
"e": 598,
"s": 344,
"text": "Method #1 : Using Counter() + set()This is one of the ways in which this task can be performed. In this, we check for all the strings and compute the character frequency in each string and return the character which have more than one string occurrence."
},
{
"code": "# Python3 code to demonstrate working of # Characters occurring in multiple Strings# Using Counter() + set()from itertools import chainfrom collections import Counter # initializing listtest_list = ['gfg', 'is', 'best', 'for', 'geeks', 'and', 'cs'] # printing original listprint(\"The original list is : \" + str(test_list)) # Characters occurring in multiple Strings# Using Counter() + set()temp = (set(sub) for sub in test_list)cntr = Counter(chain.from_iterable(temp))res = [chr for chr, count in cntr.items() if count >= 2] # printing result print(\"Characters with Multiple String occurrence : \" + str(res)) ",
"e": 1218,
"s": 598,
"text": null
},
{
"code": null,
"e": 1357,
"s": 1218,
"text": "The original list is : [‘gfg’, ‘is’, ‘best’, ‘for’, ‘geeks’, ‘and’, ‘cs’]Characters with Multiple String occurrence : [‘g’, ‘e’, ‘f’, ‘s’]"
},
{
"code": null,
"e": 1607,
"s": 1359,
"text": "Method #2 : Using list comprehension + Counter() + set()This is one of the way in which this task can be performed. In this, we perform similar task as above, the difference is that we perform in compact and one-liner way using list comprehension."
},
{
"code": "# Python3 code to demonstrate working of # Characters occurring in multiple Strings# Using list comprehension + Counter() + set()from itertools import chainfrom collections import Counter # initializing listtest_list = ['gfg', 'is', 'best', 'for', 'geeks', 'and', 'cs'] # printing original listprint(\"The original list is : \" + str(test_list)) # Characters occurring in multiple Strings# Using list comprehension + Counter() + set()res = [key for key, val in Counter([ele for sub in test_list for ele in set(sub)]).items() if val > 1] # printing result print(\"Characters with Multiple String occurrence : \" + str(res)) ",
"e": 2292,
"s": 1607,
"text": null
},
{
"code": null,
"e": 2431,
"s": 2292,
"text": "The original list is : [‘gfg’, ‘is’, ‘best’, ‘for’, ‘geeks’, ‘and’, ‘cs’]Characters with Multiple String occurrence : [‘g’, ‘e’, ‘f’, ‘s’]"
},
{
"code": null,
"e": 2452,
"s": 2431,
"text": "Python list-programs"
},
{
"code": null,
"e": 2459,
"s": 2452,
"text": "Python"
},
{
"code": null,
"e": 2475,
"s": 2459,
"text": "Python Programs"
}
] |
Python | Pandas Series.str.wrap()
|
24 Sep, 2018
Python is a great language for doing data analysis, primarily because of the fantastic ecosystem of data-centric Python packages. Pandas is one of those packages and makes importing and analyzing data much easier.
Pandas str.wrap() is an important method when dealing with long text data (Paragraphs or messages). This is used to distribute long text data into new lines or handle tab spaces when it exceeds the passed width. Since this is a string method, .str has to be prefixed every time before calling this method.
Syntax: Series.str.wrap(width, **kwargs)
Parameters:width: Integer value, defines maximum line width
**kwargs[Optional parameters]expand_tabs: Boolean value, expands tab characters to spaces if Truereplace_whitespace: Boolean value, if true, each white space character is replaced by single white space.drop_whitespace: Boolean value, If true, removes whitespace if any at the beginning of new linesbreak_long_words: Boolean value, if True, breaks word that are longer than the passed width.break_on_hyphens: Boolean value, if true, breaks string on hyphens where string length is less than width.
Return type: Series with splitted lines/added characters(‘\n’)
To download the data set used in code, click here.
In the following examples, the data frame used contains data of some NBA players. The image of data frame before any operations is attached below.
Example :In this example, the Team column is wrapped with a line width of 5 characters. Hence \n will be put after every 5 character. A random element from new team column and old team column is printed to see the working. Before applying any operations, null elements are removed using .dropna() method.
# importing pandas module import pandas as pd # reading csv file from url data = pd.read_csv("https://media.geeksforgeeks.org/wp-content/uploads/nba.csv") # dropping null value columns to avoid errorsdata.dropna(inplace = True) # displaydata["New Team"]= data["Team"].str.wrap(5) # data frame displaydata # printing same index separatelyprint(data["Team"][120])print("------------")print(data["New Team"][120])
Output:As shown in the output images, the New column has ‘\n’ after every 5 characters. After printing same index of old and New team columns, it can be seen that without adding new line character in print statement, python automatically read ‘\n’ in the string and put it in new line.
Data frame with New Team column-
Output:
Los Angeles Lakers
------------
Los A
ngele
s Lak
ers
Python pandas-series
Python pandas-series-methods
Python-pandas
Python-pandas-series-str
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Different ways to create Pandas Dataframe
Enumerate() in Python
How to Install PIP on Windows ?
*args and **kwargs in Python
Python Classes and Objects
Python OOPs Concepts
Introduction To PYTHON
Convert integer to string in Python
How to drop one or multiple columns in Pandas Dataframe
Python | os.path.join() method
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n24 Sep, 2018"
},
{
"code": null,
"e": 242,
"s": 28,
"text": "Python is a great language for doing data analysis, primarily because of the fantastic ecosystem of data-centric Python packages. Pandas is one of those packages and makes importing and analyzing data much easier."
},
{
"code": null,
"e": 548,
"s": 242,
"text": "Pandas str.wrap() is an important method when dealing with long text data (Paragraphs or messages). This is used to distribute long text data into new lines or handle tab spaces when it exceeds the passed width. Since this is a string method, .str has to be prefixed every time before calling this method."
},
{
"code": null,
"e": 589,
"s": 548,
"text": "Syntax: Series.str.wrap(width, **kwargs)"
},
{
"code": null,
"e": 649,
"s": 589,
"text": "Parameters:width: Integer value, defines maximum line width"
},
{
"code": null,
"e": 1146,
"s": 649,
"text": "**kwargs[Optional parameters]expand_tabs: Boolean value, expands tab characters to spaces if Truereplace_whitespace: Boolean value, if true, each white space character is replaced by single white space.drop_whitespace: Boolean value, If true, removes whitespace if any at the beginning of new linesbreak_long_words: Boolean value, if True, breaks word that are longer than the passed width.break_on_hyphens: Boolean value, if true, breaks string on hyphens where string length is less than width."
},
{
"code": null,
"e": 1209,
"s": 1146,
"text": "Return type: Series with splitted lines/added characters(‘\\n’)"
},
{
"code": null,
"e": 1260,
"s": 1209,
"text": "To download the data set used in code, click here."
},
{
"code": null,
"e": 1407,
"s": 1260,
"text": "In the following examples, the data frame used contains data of some NBA players. The image of data frame before any operations is attached below."
},
{
"code": null,
"e": 1712,
"s": 1407,
"text": "Example :In this example, the Team column is wrapped with a line width of 5 characters. Hence \\n will be put after every 5 character. A random element from new team column and old team column is printed to see the working. Before applying any operations, null elements are removed using .dropna() method."
},
{
"code": "# importing pandas module import pandas as pd # reading csv file from url data = pd.read_csv(\"https://media.geeksforgeeks.org/wp-content/uploads/nba.csv\") # dropping null value columns to avoid errorsdata.dropna(inplace = True) # displaydata[\"New Team\"]= data[\"Team\"].str.wrap(5) # data frame displaydata # printing same index separatelyprint(data[\"Team\"][120])print(\"------------\")print(data[\"New Team\"][120])",
"e": 2129,
"s": 1712,
"text": null
},
{
"code": null,
"e": 2415,
"s": 2129,
"text": "Output:As shown in the output images, the New column has ‘\\n’ after every 5 characters. After printing same index of old and New team columns, it can be seen that without adding new line character in print statement, python automatically read ‘\\n’ in the string and put it in new line."
},
{
"code": null,
"e": 2448,
"s": 2415,
"text": "Data frame with New Team column-"
},
{
"code": null,
"e": 2456,
"s": 2448,
"text": "Output:"
},
{
"code": null,
"e": 2511,
"s": 2456,
"text": "Los Angeles Lakers\n------------\nLos A\nngele\ns Lak\ners\n"
},
{
"code": null,
"e": 2532,
"s": 2511,
"text": "Python pandas-series"
},
{
"code": null,
"e": 2561,
"s": 2532,
"text": "Python pandas-series-methods"
},
{
"code": null,
"e": 2575,
"s": 2561,
"text": "Python-pandas"
},
{
"code": null,
"e": 2600,
"s": 2575,
"text": "Python-pandas-series-str"
},
{
"code": null,
"e": 2607,
"s": 2600,
"text": "Python"
},
{
"code": null,
"e": 2705,
"s": 2607,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 2747,
"s": 2705,
"text": "Different ways to create Pandas Dataframe"
},
{
"code": null,
"e": 2769,
"s": 2747,
"text": "Enumerate() in Python"
},
{
"code": null,
"e": 2801,
"s": 2769,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 2830,
"s": 2801,
"text": "*args and **kwargs in Python"
},
{
"code": null,
"e": 2857,
"s": 2830,
"text": "Python Classes and Objects"
},
{
"code": null,
"e": 2878,
"s": 2857,
"text": "Python OOPs Concepts"
},
{
"code": null,
"e": 2901,
"s": 2878,
"text": "Introduction To PYTHON"
},
{
"code": null,
"e": 2937,
"s": 2901,
"text": "Convert integer to string in Python"
},
{
"code": null,
"e": 2993,
"s": 2937,
"text": "How to drop one or multiple columns in Pandas Dataframe"
}
] |
Inverse Gamma Distribution in Python
|
02 Aug, 2019
Inverse Gamma distribution is a continuous probability distribution with two parameters on the positive real line. It is the reciprocate distribution of a variable distributed according to the gamma distribution. It is very useful in Bayesian statistics as the marginal distribution for the unknown variance of a normal distribution. It is used for considering the alternate parameter for the normal distribution in terms of the precision which is actually the reciprocal of the variance.
It is an inverted gamma continuous random variable. It is an instance of the rv_continuous class. It inherits from the collection of generic methods and combines them with the complete specification of distribution.
Code #1 : Creating inverted gamma continuous random variable
from scipy.stats import invgamma numargs = invgamma.numargs[a] = [0.3] * numargsrv = invgamma (a) print ("RV : \n", rv)
Output :
RV :scipy.stats._distn_infrastructure.rv_frozen object at 0x00000230B0B28748
Code #2 : Inverse Gamma continuous variates and probability distribution
import numpy as npquantile = np.arange (0.01, 1, 0.1) # Random VariatesR = invgamma.rvs(a, scale = 2, size = 10)print ("Random Variates : \n", R) # PDFR = invgamma .pdf(a, quantile, loc = 0, scale = 1)print ("\nProbability Distribution : \n", R)
Output :
Random Variates :
[4.18816252e+00 2.02807957e+03 8.37914946e+01 1.94368997e+00
3.78345091e+00 1.00496176e+06 3.42396458e+03 3.45520522e+00
2.81037118e+00 1.72359706e+03]
Probability Distribution :
[0.0012104 0.0157619 0.03512042 0.05975504 0.09007126 0.12639944
0.16898506 0.21798098 0.27344182 0.33532072]
Code #3 : Graphical Representation.
import numpy as npimport matplotlib.pyplot as plt distribution = np.linspace(0, np.minimum(rv.dist.b, 3))print("Distribution : \n", distribution) plot = plt.plot(distribution, rv.pdf(distribution))
Output :
Distribution :
[0. 0.06122449 0.12244898 0.18367347 0.24489796 0.30612245
0.36734694 0.42857143 0.48979592 0.55102041 0.6122449 0.67346939
0.73469388 0.79591837 0.85714286 0.91836735 0.97959184 1.04081633
1.10204082 1.16326531 1.2244898 1.28571429 1.34693878 1.40816327
1.46938776 1.53061224 1.59183673 1.65306122 1.71428571 1.7755102
1.83673469 1.89795918 1.95918367 2.02040816 2.08163265 2.14285714
2.20408163 2.26530612 2.32653061 2.3877551 2.44897959 2.51020408
2.57142857 2.63265306 2.69387755 2.75510204 2.81632653 2.87755102
2.93877551 3. ]
Code #4 : Varying Positional Arguments
import matplotlib.pyplot as pltimport numpy as np x = np.linspace(0, 5, 100) # Varying positional argumentsy1 = invgamma .pdf(x, 1, 3)y2 = invgamma .pdf(x, 1, 4)plt.plot(x, y1, "*", x, y2, "r--")
Output :
Machine Learning
Python
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": "\n02 Aug, 2019"
},
{
"code": null,
"e": 517,
"s": 28,
"text": "Inverse Gamma distribution is a continuous probability distribution with two parameters on the positive real line. It is the reciprocate distribution of a variable distributed according to the gamma distribution. It is very useful in Bayesian statistics as the marginal distribution for the unknown variance of a normal distribution. It is used for considering the alternate parameter for the normal distribution in terms of the precision which is actually the reciprocal of the variance."
},
{
"code": null,
"e": 733,
"s": 517,
"text": "It is an inverted gamma continuous random variable. It is an instance of the rv_continuous class. It inherits from the collection of generic methods and combines them with the complete specification of distribution."
},
{
"code": null,
"e": 794,
"s": 733,
"text": "Code #1 : Creating inverted gamma continuous random variable"
},
{
"code": "from scipy.stats import invgamma numargs = invgamma.numargs[a] = [0.3] * numargsrv = invgamma (a) print (\"RV : \\n\", rv) ",
"e": 923,
"s": 794,
"text": null
},
{
"code": null,
"e": 932,
"s": 923,
"text": "Output :"
},
{
"code": null,
"e": 1009,
"s": 932,
"text": "RV :scipy.stats._distn_infrastructure.rv_frozen object at 0x00000230B0B28748"
},
{
"code": null,
"e": 1083,
"s": 1009,
"text": " Code #2 : Inverse Gamma continuous variates and probability distribution"
},
{
"code": "import numpy as npquantile = np.arange (0.01, 1, 0.1) # Random VariatesR = invgamma.rvs(a, scale = 2, size = 10)print (\"Random Variates : \\n\", R) # PDFR = invgamma .pdf(a, quantile, loc = 0, scale = 1)print (\"\\nProbability Distribution : \\n\", R)",
"e": 1337,
"s": 1083,
"text": null
},
{
"code": null,
"e": 1346,
"s": 1337,
"text": "Output :"
},
{
"code": null,
"e": 1663,
"s": 1346,
"text": "Random Variates : \n [4.18816252e+00 2.02807957e+03 8.37914946e+01 1.94368997e+00\n 3.78345091e+00 1.00496176e+06 3.42396458e+03 3.45520522e+00\n 2.81037118e+00 1.72359706e+03]\n\nProbability Distribution : \n [0.0012104 0.0157619 0.03512042 0.05975504 0.09007126 0.12639944\n 0.16898506 0.21798098 0.27344182 0.33532072]"
},
{
"code": null,
"e": 1700,
"s": 1663,
"text": " Code #3 : Graphical Representation."
},
{
"code": "import numpy as npimport matplotlib.pyplot as plt distribution = np.linspace(0, np.minimum(rv.dist.b, 3))print(\"Distribution : \\n\", distribution) plot = plt.plot(distribution, rv.pdf(distribution))",
"e": 1904,
"s": 1700,
"text": null
},
{
"code": null,
"e": 1913,
"s": 1904,
"text": "Output :"
},
{
"code": null,
"e": 2489,
"s": 1913,
"text": "Distribution : \n [0. 0.06122449 0.12244898 0.18367347 0.24489796 0.30612245\n 0.36734694 0.42857143 0.48979592 0.55102041 0.6122449 0.67346939\n 0.73469388 0.79591837 0.85714286 0.91836735 0.97959184 1.04081633\n 1.10204082 1.16326531 1.2244898 1.28571429 1.34693878 1.40816327\n 1.46938776 1.53061224 1.59183673 1.65306122 1.71428571 1.7755102\n 1.83673469 1.89795918 1.95918367 2.02040816 2.08163265 2.14285714\n 2.20408163 2.26530612 2.32653061 2.3877551 2.44897959 2.51020408\n 2.57142857 2.63265306 2.69387755 2.75510204 2.81632653 2.87755102\n 2.93877551 3. ]"
},
{
"code": null,
"e": 2528,
"s": 2489,
"text": "Code #4 : Varying Positional Arguments"
},
{
"code": "import matplotlib.pyplot as pltimport numpy as np x = np.linspace(0, 5, 100) # Varying positional argumentsy1 = invgamma .pdf(x, 1, 3)y2 = invgamma .pdf(x, 1, 4)plt.plot(x, y1, \"*\", x, y2, \"r--\")",
"e": 2730,
"s": 2528,
"text": null
},
{
"code": null,
"e": 2739,
"s": 2730,
"text": "Output :"
},
{
"code": null,
"e": 2756,
"s": 2739,
"text": "Machine Learning"
},
{
"code": null,
"e": 2763,
"s": 2756,
"text": "Python"
},
{
"code": null,
"e": 2780,
"s": 2763,
"text": "Machine Learning"
}
] |
Regular grammar (Model regular grammars )
|
26 Apr, 2022
Prerequisites: Chomsky hierarchy
Regular grammar generates regular language. They have a single non-terminal on the left-hand side and a right-hand side consisting of a single terminal or single terminal followed by a non-terminal.
The productions must be in the form:
A ⇢ xB
A ⇢ x
A ⇢ Bx
where A, B ∈ Variable(V) and x ∈ T* i.e. string of terminals.
Left Linear grammar(LLG)
Right linear grammar(RLG)
1. Left linear grammar(LLG):In LLG, the productions are in the form if all the productions are of the form
A ⇢ Bx
A ⇢ x
where A,B ∈ V and x ∈ T*
2. Right linear grammar(RLG):In RLG, the productions are in the form if all the productions are of the form
A ⇢ xB
A ⇢ x
where A,B ∈ V and x ∈ T*
The language generated by type-3 grammar is a regular language, for which a FA can be designed. The FA can also be converted into type-3 grammar
Example: FA for accepting strings that start with b
.
∑ = {a,b}
Initial state(q0) = A
Final state(F) = B
The RLG corresponding to FA is
A ⇢ bB
B ⇢ ∈/aB/bB
The above grammar is RLG, which can be written directly through FA.
This grammar derives strings that are stated with B
The above RLG can derive strings that start with b and after that any input symbol(i.e. ∑ ={a, b} can be accepted).
The regular language corresponding to RLG is
L= {b, ba, bb, baa, bab ,bba,bbb ..... }
If we reverse the above production of the above RLG, then we get
A ⇢ Bb
B ⇢ ∈/Ba/Bb
It derives the language that contains all the strings which end with b.
i.e. L' = {b, bb, ab, aab, bab, abb, bbb .....}
So we can conclude that if we have FA that represents language L and if we convert it, into RLG, which again represents language L, but after reversing RLG we get LLG which represents language L'(i.e. reverse of L).
For converting the RLG into LLG for language L, the following procedure needs to be followed:
Step 1: Reverse the FA for language L
Step 2: Write the RLG for it.
Step 3: Reverse the right linear grammar.
after this we get the grammar that generates the language that represents the LLG for the same language L.
This represents the same procedure as above for converting RLG to LLG
Here L is a language for FA and LR is a reversal of the language L.Example:The above FA represents language L(i.e. set of all strings over input symbols a and b which start with b).We are converting it into LLG.
Step1: The reversal of FA is
The reversal of FA represents all strings starting with b.
Step 2: The corresponding RLG for this reversed FA is
B ⇢ aB/bB/bA
A ⇢ ∈
Step 3: The reversing the above RLG we get
B ⇢ Ba/Bb/Ab
A ⇢ ∈
So this is LLG for language L( which represents all strings that start with b).L= {b, ba, bb, baa, bab ,bba, bbb ..... }
Conversion of RLG to FA:
Start from the first production.
From every left alphabet (or variable) go to the symbol followed by it.
Start state: It will be the first production state.
Final state: Take those states which end up with terminals without further non-terminals.
Example: The RLL grammar for Language(L), represents a set of all strings which end with 0.
A ⇢ 0A/1B/0B
B ⇢ ∈
So the FA for corresponding to RLG can be found out asStart with variable A and use its production.
For production A ⇢ 0A, this means after getting input symbol 0, the transition will remain in the same state.
For production, A ⇢ 1B, this means after getting input symbol 1, the state transition will take place from State A to B.
For production A ⇢ 0B, this means after getting input symbol 0, the state transition will take place from State A to B.
For production B ⇢ ∈, this means there is no need for state transition. This means it would be the final state in the corresponding FA as RHS is terminal.
So the final NFA for the corresponding RLG is
Set of all strings that end with 0
Explanation: First convert the LLG which represents the Language(L) to RLG, which represents, the reversal of language L(i.e.LR) then design FA corresponding to it(i.e. FA for Language LR ). Then reverse the FA. Then the final FA is FA for language L).
Conversion of LLG to RLG: For example, the above grammar is taken which represents language L(i.e. set of all strings that start with b)The LLG for this grammar is
B ⇢ Ba/Bb/Ab
A ⇢ ∈
Step 1: Convert the LLG into FA(i.e. the conversion procedure is the same as above)
Step 2: Reverse the FA(i.e. initial state is converted into final state and convert final state to initial state and reverse all edges)
Step 3: Write RLG corresponding to reversed FA.
A ⇢ bB
B ⇢ aB/bB/∈
They can be easily converted to other
All have the same power and can be converted to other
jasminjoyp
yuganshchauhan21
Picked
GATE CS
Theory of Computation & Automata
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
|
[
{
"code": null,
"e": 54,
"s": 26,
"text": "\n26 Apr, 2022"
},
{
"code": null,
"e": 87,
"s": 54,
"text": "Prerequisites: Chomsky hierarchy"
},
{
"code": null,
"e": 286,
"s": 87,
"text": "Regular grammar generates regular language. They have a single non-terminal on the left-hand side and a right-hand side consisting of a single terminal or single terminal followed by a non-terminal."
},
{
"code": null,
"e": 323,
"s": 286,
"text": "The productions must be in the form:"
},
{
"code": null,
"e": 407,
"s": 323,
"text": "A ⇢ xB \nA ⇢ x\nA ⇢ Bx\nwhere A, B ∈ Variable(V) and x ∈ T* i.e. string of terminals."
},
{
"code": null,
"e": 432,
"s": 407,
"text": "Left Linear grammar(LLG)"
},
{
"code": null,
"e": 458,
"s": 432,
"text": "Right linear grammar(RLG)"
},
{
"code": null,
"e": 566,
"s": 458,
"text": "1. Left linear grammar(LLG):In LLG, the productions are in the form if all the productions are of the form "
},
{
"code": null,
"e": 604,
"s": 566,
"text": "A ⇢ Bx\nA ⇢ x\nwhere A,B ∈ V and x ∈ T*"
},
{
"code": null,
"e": 712,
"s": 604,
"text": "2. Right linear grammar(RLG):In RLG, the productions are in the form if all the productions are of the form"
},
{
"code": null,
"e": 751,
"s": 712,
"text": "A ⇢ xB\nA ⇢ x\nwhere A,B ∈ V and x ∈ T*"
},
{
"code": null,
"e": 896,
"s": 751,
"text": "The language generated by type-3 grammar is a regular language, for which a FA can be designed. The FA can also be converted into type-3 grammar"
},
{
"code": null,
"e": 948,
"s": 896,
"text": "Example: FA for accepting strings that start with b"
},
{
"code": null,
"e": 951,
"s": 948,
"text": ". "
},
{
"code": null,
"e": 1004,
"s": 951,
"text": "∑ = {a,b}\nInitial state(q0) = A\nFinal state(F) = B"
},
{
"code": null,
"e": 1036,
"s": 1004,
"text": "The RLG corresponding to FA is "
},
{
"code": null,
"e": 1060,
"s": 1036,
"text": "A ⇢ bB \nB ⇢ ∈/aB/bB "
},
{
"code": null,
"e": 1128,
"s": 1060,
"text": "The above grammar is RLG, which can be written directly through FA."
},
{
"code": null,
"e": 1180,
"s": 1128,
"text": "This grammar derives strings that are stated with B"
},
{
"code": null,
"e": 1296,
"s": 1180,
"text": "The above RLG can derive strings that start with b and after that any input symbol(i.e. ∑ ={a, b} can be accepted)."
},
{
"code": null,
"e": 1383,
"s": 1296,
"text": "The regular language corresponding to RLG is\n L= {b, ba, bb, baa, bab ,bba,bbb ..... }"
},
{
"code": null,
"e": 1448,
"s": 1383,
"text": "If we reverse the above production of the above RLG, then we get"
},
{
"code": null,
"e": 1591,
"s": 1448,
"text": "A ⇢ Bb \nB ⇢ ∈/Ba/Bb \nIt derives the language that contains all the strings which end with b.\ni.e. L' = {b, bb, ab, aab, bab, abb, bbb .....}"
},
{
"code": null,
"e": 1808,
"s": 1591,
"text": "So we can conclude that if we have FA that represents language L and if we convert it, into RLG, which again represents language L, but after reversing RLG we get LLG which represents language L'(i.e. reverse of L). "
},
{
"code": null,
"e": 1903,
"s": 1808,
"text": "For converting the RLG into LLG for language L, the following procedure needs to be followed: "
},
{
"code": null,
"e": 2120,
"s": 1903,
"text": "Step 1: Reverse the FA for language L\nStep 2: Write the RLG for it.\nStep 3: Reverse the right linear grammar.\nafter this we get the grammar that generates the language that represents the LLG for the same language L."
},
{
"code": null,
"e": 2190,
"s": 2120,
"text": "This represents the same procedure as above for converting RLG to LLG"
},
{
"code": null,
"e": 2402,
"s": 2190,
"text": "Here L is a language for FA and LR is a reversal of the language L.Example:The above FA represents language L(i.e. set of all strings over input symbols a and b which start with b).We are converting it into LLG."
},
{
"code": null,
"e": 2431,
"s": 2402,
"text": "Step1: The reversal of FA is"
},
{
"code": null,
"e": 2490,
"s": 2431,
"text": "The reversal of FA represents all strings starting with b."
},
{
"code": null,
"e": 2544,
"s": 2490,
"text": "Step 2: The corresponding RLG for this reversed FA is"
},
{
"code": null,
"e": 2564,
"s": 2544,
"text": "B ⇢ aB/bB/bA\nA ⇢ ∈"
},
{
"code": null,
"e": 2607,
"s": 2564,
"text": "Step 3: The reversing the above RLG we get"
},
{
"code": null,
"e": 2627,
"s": 2607,
"text": "B ⇢ Ba/Bb/Ab\nA ⇢ ∈"
},
{
"code": null,
"e": 2748,
"s": 2627,
"text": "So this is LLG for language L( which represents all strings that start with b).L= {b, ba, bb, baa, bab ,bba, bbb ..... }"
},
{
"code": null,
"e": 2773,
"s": 2748,
"text": "Conversion of RLG to FA:"
},
{
"code": null,
"e": 2806,
"s": 2773,
"text": "Start from the first production."
},
{
"code": null,
"e": 2878,
"s": 2806,
"text": "From every left alphabet (or variable) go to the symbol followed by it."
},
{
"code": null,
"e": 2930,
"s": 2878,
"text": "Start state: It will be the first production state."
},
{
"code": null,
"e": 3020,
"s": 2930,
"text": "Final state: Take those states which end up with terminals without further non-terminals."
},
{
"code": null,
"e": 3113,
"s": 3020,
"text": "Example: The RLL grammar for Language(L), represents a set of all strings which end with 0. "
},
{
"code": null,
"e": 3132,
"s": 3113,
"text": "A ⇢ 0A/1B/0B\nB ⇢ ∈"
},
{
"code": null,
"e": 3232,
"s": 3132,
"text": "So the FA for corresponding to RLG can be found out asStart with variable A and use its production."
},
{
"code": null,
"e": 3342,
"s": 3232,
"text": "For production A ⇢ 0A, this means after getting input symbol 0, the transition will remain in the same state."
},
{
"code": null,
"e": 3463,
"s": 3342,
"text": "For production, A ⇢ 1B, this means after getting input symbol 1, the state transition will take place from State A to B."
},
{
"code": null,
"e": 3583,
"s": 3463,
"text": "For production A ⇢ 0B, this means after getting input symbol 0, the state transition will take place from State A to B."
},
{
"code": null,
"e": 3738,
"s": 3583,
"text": "For production B ⇢ ∈, this means there is no need for state transition. This means it would be the final state in the corresponding FA as RHS is terminal."
},
{
"code": null,
"e": 3784,
"s": 3738,
"text": "So the final NFA for the corresponding RLG is"
},
{
"code": null,
"e": 3819,
"s": 3784,
"text": "Set of all strings that end with 0"
},
{
"code": null,
"e": 4074,
"s": 3819,
"text": "Explanation: First convert the LLG which represents the Language(L) to RLG, which represents, the reversal of language L(i.e.LR) then design FA corresponding to it(i.e. FA for Language LR ). Then reverse the FA. Then the final FA is FA for language L). "
},
{
"code": null,
"e": 4238,
"s": 4074,
"text": "Conversion of LLG to RLG: For example, the above grammar is taken which represents language L(i.e. set of all strings that start with b)The LLG for this grammar is"
},
{
"code": null,
"e": 4258,
"s": 4238,
"text": "B ⇢ Ba/Bb/Ab\nA ⇢ ∈"
},
{
"code": null,
"e": 4342,
"s": 4258,
"text": "Step 1: Convert the LLG into FA(i.e. the conversion procedure is the same as above)"
},
{
"code": null,
"e": 4479,
"s": 4342,
"text": "Step 2: Reverse the FA(i.e. initial state is converted into final state and convert final state to initial state and reverse all edges)"
},
{
"code": null,
"e": 4527,
"s": 4479,
"text": "Step 3: Write RLG corresponding to reversed FA."
},
{
"code": null,
"e": 4547,
"s": 4527,
"text": "A ⇢ bB\nB ⇢ aB/bB/∈"
},
{
"code": null,
"e": 4585,
"s": 4547,
"text": "They can be easily converted to other"
},
{
"code": null,
"e": 4641,
"s": 4585,
"text": "All have the same power and can be converted to other "
},
{
"code": null,
"e": 4652,
"s": 4641,
"text": "jasminjoyp"
},
{
"code": null,
"e": 4669,
"s": 4652,
"text": "yuganshchauhan21"
},
{
"code": null,
"e": 4676,
"s": 4669,
"text": "Picked"
},
{
"code": null,
"e": 4684,
"s": 4676,
"text": "GATE CS"
},
{
"code": null,
"e": 4717,
"s": 4684,
"text": "Theory of Computation & Automata"
}
] |
What are the differences between an event listener interface and an event adapter class in Java?
|
An EventListener interface defines the methods that must be implemented by an event handler for a particular kind of an event whereas an Event Adapter class provides a default implementation of an EventListener interface.
The Event Listeners are the backbone of every component to handle the events.
Every method of a particular EventListener will have a single parameter as an instance which is the subclass of EventObject class.
An EventListener interface needs to be extended and it will be defined in java.util package.
A few EventListener interfaces are ActionListener, KeyListener, MouseListener, FocusListener, ItemListener and etc.
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class KeyListenerTest implements KeyListener, ActionListener {
JFrame frame;
JTextField tf;
JLabel lbl;
JButton btn;
public KeyListenerTest() {
frame = new JFrame();
lbl = new JLabel();
tf = new JTextField(15);
tf.addKeyListener(this);
btn = new JButton("Clear");
btn.addActionListener(this);
JPanel panel = new JPanel();
panel.add(tf);
panel.add(btn);
frame.setLayout(new BorderLayout());
frame.add(lbl, BorderLayout.NORTH);
frame.add(panel, BorderLayout.SOUTH);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLocationRelativeTo(null);
frame.setSize(300, 200);
frame.setVisible(true);
}
@Override
public void keyTyped(KeyEvent ke) {
lbl.setText("You have typed "+ ke.getKeyChar());
}
@Override
public void keyPressed(KeyEvent ke) {
lbl.setText("You have pressed "+ ke.getKeyChar());
}
@Override
public void keyReleased(KeyEvent ke) {
lbl.setText("You have released "+ ke.getKeyChar());
}
@Override
public void actionPerformed(ActionEvent ae) {
tf.setText("");
}
public static void main(String args[]) {
new KeyListenerTest();
}
}
The Abstract classes can be called as Event Adapter for receiving various events.
An Event Adapter class gives a default implementation of all the methods in an EventListener interface.
Few Event Adapter classes are FocusAdapter, KeyAdapter, MouseAdapter, WindowAdapter and etc.
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class KeyAdapterTest {
private JFrame frame;
private JLabel headLabel;
private JLabel msgLabel;
private JPanel controlPanel;
public KeyAdapterTest() {
initializeUI();
}
private void initializeUI() {
frame = new JFrame("KeyAdapter class");
frame.setSize(350, 275);
frame.setLayout(new GridLayout(3, 1));
headLabel = new JLabel("", JLabel.CENTER);
msgLabel = new JLabel("", JLabel.CENTER);
msgLabel.setSize(300, 100);
frame.addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent windowEvent) {
System.exit(0);
}
});
controlPanel = new JPanel();
controlPanel.setLayout(new FlowLayout());
frame.add(headLabel);
frame.add(controlPanel);
frame.add(msgLabel);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
private void showMouseApapter() {
headLabel.setText("KeyAdapter Test");
final JTextField textField = new JTextField(10);
JButton displayButton = new JButton("Display");
displayButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
msgLabel.setText("You entered : " + textField.getText());
}
});
textField.addKeyListener(new KeyAdapter() {
public void keyPressed(KeyEvent e) {
if (e.getKeyCode() == KeyEvent.VK_ENTER) {
msgLabel.setText("You entered : " + textField.getText());
}
}
});
controlPanel.add(textField);
controlPanel.add(displayButton);
frame.setVisible(true);
}
public static void main(String[] args) {
KeyAdapterTest test = new KeyAdapterTest();
test.showMouseApapter();
}
}
|
[
{
"code": null,
"e": 1409,
"s": 1187,
"text": "An EventListener interface defines the methods that must be implemented by an event handler for a particular kind of an event whereas an Event Adapter class provides a default implementation of an EventListener interface."
},
{
"code": null,
"e": 1487,
"s": 1409,
"text": "The Event Listeners are the backbone of every component to handle the events."
},
{
"code": null,
"e": 1618,
"s": 1487,
"text": "Every method of a particular EventListener will have a single parameter as an instance which is the subclass of EventObject class."
},
{
"code": null,
"e": 1711,
"s": 1618,
"text": "An EventListener interface needs to be extended and it will be defined in java.util package."
},
{
"code": null,
"e": 1827,
"s": 1711,
"text": "A few EventListener interfaces are ActionListener, KeyListener, MouseListener, FocusListener, ItemListener and etc."
},
{
"code": null,
"e": 3133,
"s": 1827,
"text": "import java.awt.*;\nimport java.awt.event.*;\nimport javax.swing.*;\npublic class KeyListenerTest implements KeyListener, ActionListener {\n JFrame frame;\n JTextField tf;\n JLabel lbl;\n JButton btn;\n public KeyListenerTest() {\n frame = new JFrame();\n lbl = new JLabel();\n tf = new JTextField(15);\n tf.addKeyListener(this);\n btn = new JButton(\"Clear\");\n btn.addActionListener(this);\n JPanel panel = new JPanel();\n panel.add(tf);\n panel.add(btn);\n frame.setLayout(new BorderLayout());\n frame.add(lbl, BorderLayout.NORTH);\n frame.add(panel, BorderLayout.SOUTH);\n frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);\n frame.setLocationRelativeTo(null);\n frame.setSize(300, 200);\n frame.setVisible(true);\n }\n @Override\n public void keyTyped(KeyEvent ke) {\n lbl.setText(\"You have typed \"+ ke.getKeyChar());\n }\n @Override\n public void keyPressed(KeyEvent ke) {\n lbl.setText(\"You have pressed \"+ ke.getKeyChar());\n }\n @Override\n public void keyReleased(KeyEvent ke) {\n lbl.setText(\"You have released \"+ ke.getKeyChar());\n }\n @Override\n public void actionPerformed(ActionEvent ae) {\n tf.setText(\"\");\n }\n public static void main(String args[]) {\n new KeyListenerTest();\n }\n}"
},
{
"code": null,
"e": 3215,
"s": 3133,
"text": "The Abstract classes can be called as Event Adapter for receiving various events."
},
{
"code": null,
"e": 3319,
"s": 3215,
"text": "An Event Adapter class gives a default implementation of all the methods in an EventListener interface."
},
{
"code": null,
"e": 3412,
"s": 3319,
"text": "Few Event Adapter classes are FocusAdapter, KeyAdapter, MouseAdapter, WindowAdapter and etc."
},
{
"code": null,
"e": 5328,
"s": 3412,
"text": "import java.awt.*;\nimport java.awt.event.*;\nimport javax.swing.*;\npublic class KeyAdapterTest {\n private JFrame frame;\n private JLabel headLabel;\n private JLabel msgLabel;\n private JPanel controlPanel;\n public KeyAdapterTest() {\n initializeUI();\n }\n private void initializeUI() {\n frame = new JFrame(\"KeyAdapter class\");\n frame.setSize(350, 275);\n frame.setLayout(new GridLayout(3, 1));\n headLabel = new JLabel(\"\", JLabel.CENTER);\n msgLabel = new JLabel(\"\", JLabel.CENTER);\n msgLabel.setSize(300, 100);\n frame.addWindowListener(new WindowAdapter() {\n public void windowClosing(WindowEvent windowEvent) {\n System.exit(0);\n }\n });\n controlPanel = new JPanel();\n controlPanel.setLayout(new FlowLayout());\n frame.add(headLabel);\n frame.add(controlPanel);\n frame.add(msgLabel);\n frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);\n frame.setLocationRelativeTo(null);\n frame.setVisible(true);\n }\n private void showMouseApapter() {\n headLabel.setText(\"KeyAdapter Test\");\n final JTextField textField = new JTextField(10);\n JButton displayButton = new JButton(\"Display\");\n displayButton.addActionListener(new ActionListener() {\n public void actionPerformed(ActionEvent e) {\n msgLabel.setText(\"You entered : \" + textField.getText());\n }\n });\n textField.addKeyListener(new KeyAdapter() {\n public void keyPressed(KeyEvent e) {\n if (e.getKeyCode() == KeyEvent.VK_ENTER) {\n msgLabel.setText(\"You entered : \" + textField.getText());\n }\n }\n });\n controlPanel.add(textField);\n controlPanel.add(displayButton);\n frame.setVisible(true);\n }\n public static void main(String[] args) {\n KeyAdapterTest test = new KeyAdapterTest();\n test.showMouseApapter();\n }\n}"
}
] |
How to access variables from another file using JavaScript ?
|
26 Jul, 2021
In JavaScript, variables can be accessed from another file using the <script> tags or the import or export statement. The script tag is mainly used when we want to access variable of a JavaScript file in an HTML file. This works well for client-side scripting as well as for server-side scripting. The import or export statement however cannot be used for client-side scripting. The import or export statement works in Node.js during server-side scripting.
First Approach: At first the “module1.js” file is created and a Student object with properties “name”, “age”, “dept” and “score” is defined. The module1.js JavaScript file is imported using the src attribute of script tag within the “head” section of the HTML file. Since the JavaScript file is imported, the contents are accessible within the HTML file.
We create a button which when clicked triggers the JavaScript function. The Student object properties are accessed through the f() function and all the Student object properties are concatenated to a string variable. This string is placed within the <p> tag having ‘text’ id using the document.getElementById() and innerHTML property of HTML DOM. This is an example of a client side program.
Code Implementation:
variable_access.html
HTML
<!DOCTYPE html><html> <head> <script type="text/javascript" src="module1.js"> </script></head> <body> <button onclick="f()"> Click Me To Get Student Details </button> <div> <p id="text" style="color:purple; font-weight:bold;font-size:20px;"> </p> </div> <script type="text/javascript"> function f() { var name = Student.name; var age = Student.age; var dept = Student.dept; var score = Student.score; var str = "Name:" + name + "\nAge: " + age + "\nDepartment:" + dept + "\nScore: " + score; document.getElementById( 'text').innerHTML = str; } </script></body> </html>
module1.js This file is used in the above HTML code.
Javascript
var Student ={ name : "ABC", age : 18, dept : "CSE", score : 90};
Output:
Second Approach: In this approach, we create a JavaScript file “module1.js” and define a Student object having properties “name”, “age”, “dept” and “score”. The Student object is exported using module.exports. In another JavaScript module file “module2.js“, we import “module1.js” using the import statement at the beginning of the file. The objects Hostel and Hostel_Allocation are defined in “module2.js” file and the Student object is accessed in the Hostel_Allocation object.
A HTTP server is created and hosted at port no. 8080. The properties of Hostel_Allocation are concatenated in a string. This string is printed on the landing page of the web application whenever it is run. This is an example of server side scripting.
Code Implementation:
module1.js
Javascript
var Student = { name : "ABC", age : 18, dept : "CSE", score : 90};module.exports = {Student};
module2.js
Javascript
var http = require('http');const {Student} = require('./module1.js'); var Hostel = { student_count: 500, no_of_rooms: 250, hostel_fees: 12000} var Hostel_Allocation = { room_no : 151, student_name: Student.name, student_age: Student.age, student_dept: Student.dept, total_fees: 12000} var str = "Room No: " + Hostel_Allocation.room_no + "\nStudent Name: " + Hostel_Allocation.student_name + "\nTotal Fees: " + Hostel_Allocation.total_fees; http.createServer(function (req, res) { res.write(str); res.end(); }).listen(8080);
Output:
Start the server
node module2.js
Run the application in the browser
localhost:8080
JavaScript is best known for web page development but it is also used in a variety of non-browser environments. You can learn JavaScript from the ground up by following this JavaScript Tutorial and JavaScript Examples.
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": "\n26 Jul, 2021"
},
{
"code": null,
"e": 485,
"s": 28,
"text": "In JavaScript, variables can be accessed from another file using the <script> tags or the import or export statement. The script tag is mainly used when we want to access variable of a JavaScript file in an HTML file. This works well for client-side scripting as well as for server-side scripting. The import or export statement however cannot be used for client-side scripting. The import or export statement works in Node.js during server-side scripting."
},
{
"code": null,
"e": 840,
"s": 485,
"text": "First Approach: At first the “module1.js” file is created and a Student object with properties “name”, “age”, “dept” and “score” is defined. The module1.js JavaScript file is imported using the src attribute of script tag within the “head” section of the HTML file. Since the JavaScript file is imported, the contents are accessible within the HTML file."
},
{
"code": null,
"e": 1232,
"s": 840,
"text": "We create a button which when clicked triggers the JavaScript function. The Student object properties are accessed through the f() function and all the Student object properties are concatenated to a string variable. This string is placed within the <p> tag having ‘text’ id using the document.getElementById() and innerHTML property of HTML DOM. This is an example of a client side program."
},
{
"code": null,
"e": 1253,
"s": 1232,
"text": "Code Implementation:"
},
{
"code": null,
"e": 1274,
"s": 1253,
"text": "variable_access.html"
},
{
"code": null,
"e": 1279,
"s": 1274,
"text": "HTML"
},
{
"code": "<!DOCTYPE html><html> <head> <script type=\"text/javascript\" src=\"module1.js\"> </script></head> <body> <button onclick=\"f()\"> Click Me To Get Student Details </button> <div> <p id=\"text\" style=\"color:purple; font-weight:bold;font-size:20px;\"> </p> </div> <script type=\"text/javascript\"> function f() { var name = Student.name; var age = Student.age; var dept = Student.dept; var score = Student.score; var str = \"Name:\" + name + \"\\nAge: \" + age + \"\\nDepartment:\" + dept + \"\\nScore: \" + score; document.getElementById( 'text').innerHTML = str; } </script></body> </html>",
"e": 2050,
"s": 1279,
"text": null
},
{
"code": null,
"e": 2103,
"s": 2050,
"text": "module1.js This file is used in the above HTML code."
},
{
"code": null,
"e": 2114,
"s": 2103,
"text": "Javascript"
},
{
"code": "var Student ={ name : \"ABC\", age : 18, dept : \"CSE\", score : 90};",
"e": 2192,
"s": 2114,
"text": null
},
{
"code": null,
"e": 2200,
"s": 2192,
"text": "Output:"
},
{
"code": null,
"e": 2680,
"s": 2200,
"text": "Second Approach: In this approach, we create a JavaScript file “module1.js” and define a Student object having properties “name”, “age”, “dept” and “score”. The Student object is exported using module.exports. In another JavaScript module file “module2.js“, we import “module1.js” using the import statement at the beginning of the file. The objects Hostel and Hostel_Allocation are defined in “module2.js” file and the Student object is accessed in the Hostel_Allocation object."
},
{
"code": null,
"e": 2931,
"s": 2680,
"text": "A HTTP server is created and hosted at port no. 8080. The properties of Hostel_Allocation are concatenated in a string. This string is printed on the landing page of the web application whenever it is run. This is an example of server side scripting."
},
{
"code": null,
"e": 2952,
"s": 2931,
"text": "Code Implementation:"
},
{
"code": null,
"e": 2963,
"s": 2952,
"text": "module1.js"
},
{
"code": null,
"e": 2974,
"s": 2963,
"text": "Javascript"
},
{
"code": "var Student = { name : \"ABC\", age : 18, dept : \"CSE\", score : 90};module.exports = {Student};",
"e": 3080,
"s": 2974,
"text": null
},
{
"code": null,
"e": 3091,
"s": 3080,
"text": "module2.js"
},
{
"code": null,
"e": 3102,
"s": 3091,
"text": "Javascript"
},
{
"code": "var http = require('http');const {Student} = require('./module1.js'); var Hostel = { student_count: 500, no_of_rooms: 250, hostel_fees: 12000} var Hostel_Allocation = { room_no : 151, student_name: Student.name, student_age: Student.age, student_dept: Student.dept, total_fees: 12000} var str = \"Room No: \" + Hostel_Allocation.room_no + \"\\nStudent Name: \" + Hostel_Allocation.student_name + \"\\nTotal Fees: \" + Hostel_Allocation.total_fees; http.createServer(function (req, res) { res.write(str); res.end(); }).listen(8080);",
"e": 3693,
"s": 3102,
"text": null
},
{
"code": null,
"e": 3701,
"s": 3693,
"text": "Output:"
},
{
"code": null,
"e": 3718,
"s": 3701,
"text": "Start the server"
},
{
"code": null,
"e": 3734,
"s": 3718,
"text": "node module2.js"
},
{
"code": null,
"e": 3769,
"s": 3734,
"text": "Run the application in the browser"
},
{
"code": null,
"e": 3784,
"s": 3769,
"text": "localhost:8080"
},
{
"code": null,
"e": 4003,
"s": 3784,
"text": "JavaScript is best known for web page development but it is also used in a variety of non-browser environments. You can learn JavaScript from the ground up by following this JavaScript Tutorial and JavaScript Examples."
},
{
"code": null,
"e": 4019,
"s": 4003,
"text": "JavaScript-Misc"
},
{
"code": null,
"e": 4030,
"s": 4019,
"text": "JavaScript"
},
{
"code": null,
"e": 4047,
"s": 4030,
"text": "Web Technologies"
}
] |
Swift - Variables
|
A variable provides us with named storage that our programs can manipulate. Each variable in Swift 4 has a specific type, which determines the size and layout of the variable's memory; the range of values that can be stored within that memory; and the set of operations that can be applied to the variable.
Swift 4 supports the following basic types of variables −
Int or UInt − This is used for whole numbers. More specifically, you can use Int32, Int64 to define 32 or 64 bit signed integer, whereas UInt32 or UInt64 to define 32 or 64 bit unsigned integer variables. For example, 42 and -23.
Int or UInt − This is used for whole numbers. More specifically, you can use Int32, Int64 to define 32 or 64 bit signed integer, whereas UInt32 or UInt64 to define 32 or 64 bit unsigned integer variables. For example, 42 and -23.
Float − This is used to represent a 32-bit floating-point number. It is used to hold numbers with smaller decimal points. For example, 3.14159, 0.1, and -273.158.
Float − This is used to represent a 32-bit floating-point number. It is used to hold numbers with smaller decimal points. For example, 3.14159, 0.1, and -273.158.
Double − This is used to represent a 64-bit floating-point number and used when floating-point values must be very large. For example 3.14159, 0.1, and -273.158.
Double − This is used to represent a 64-bit floating-point number and used when floating-point values must be very large. For example 3.14159, 0.1, and -273.158.
Bool − This represents a Boolean value which is either true or false.
Bool − This represents a Boolean value which is either true or false.
String − This is an ordered collection of characters. For example, "Hello, World!"
String − This is an ordered collection of characters. For example, "Hello, World!"
Character − This is a single-character string literal. For example, "C"
Character − This is a single-character string literal. For example, "C"
Swift 4 also allows to define various other types of variables, which we will cover in subsequent chapters, such as Optional, Array, Dictionaries, Structures, and Classes.
The following section will cover how to declare and use various types of variables in Swift 4 programming.
A variable declaration tells the compiler where and how much to create the storage for the variable. Before you use variables, you must declare them using var keyword as follows −
var variableName = <initial value>
The following example shows how to declare a variable in Swift 4 −
var varA = 42
print(varA)
When we run the above program using playground, we get the following result −
42
You can provide a type annotation when you declare a variable, to be clear about the kind of values the variable can store. Here is the syntax −
var variableName:<data type> = <optional initial value>
The following example shows how to declare a variable in Swift 4 using Annotation. Here it is important to note that if we are not using type annotation, then it becomes mandatory to provide an initial value for the variable, otherwise we can just declare our variable using type annotation.
var varA = 42
print(varA)
var varB:Float
varB = 3.14159
print(varB)
When we run the above program using playground, we get the following result −
42
3.1415901184082
The name of a variable can be composed of letters, digits, and the underscore character. It must begin with either a letter or an underscore. Upper and lowercase letters are distinct because Swift 4 is a case-sensitive programming language.
You can use simple or Unicode characters to name your variables. The following examples shows how you can name the variables −
var _var = "Hello, Swift 4!"
print(_var)
var 你好 = "你好世界"
print(你好)
When we run the above program using playground, we get the following result.
Hello, Swift 4!
你好世界
You can print the current value of a constant or variable with the print function. You can interpolate a variable value by wrapping the name in parentheses and escape it with a backslash before the opening parenthesis: Following are valid examples −
var varA = "Godzilla"
var varB = 1000.00
print("Value of \(varA) is more than \(varB) millions")
When we run the above program using playground, we get the following result.
Value of Godzilla is more than 1000.0 millions
38 Lectures
1 hours
Ashish Sharma
13 Lectures
2 hours
Three Millennials
7 Lectures
1 hours
Three Millennials
22 Lectures
1 hours
Frahaan Hussain
12 Lectures
39 mins
Devasena Rajendran
40 Lectures
2.5 hours
Grant Klimaytys
Print
Add Notes
Bookmark this page
|
[
{
"code": null,
"e": 2560,
"s": 2253,
"text": "A variable provides us with named storage that our programs can manipulate. Each variable in Swift 4 has a specific type, which determines the size and layout of the variable's memory; the range of values that can be stored within that memory; and the set of operations that can be applied to the variable."
},
{
"code": null,
"e": 2618,
"s": 2560,
"text": "Swift 4 supports the following basic types of variables −"
},
{
"code": null,
"e": 2848,
"s": 2618,
"text": "Int or UInt − This is used for whole numbers. More specifically, you can use Int32, Int64 to define 32 or 64 bit signed integer, whereas UInt32 or UInt64 to define 32 or 64 bit unsigned integer variables. For example, 42 and -23."
},
{
"code": null,
"e": 3078,
"s": 2848,
"text": "Int or UInt − This is used for whole numbers. More specifically, you can use Int32, Int64 to define 32 or 64 bit signed integer, whereas UInt32 or UInt64 to define 32 or 64 bit unsigned integer variables. For example, 42 and -23."
},
{
"code": null,
"e": 3241,
"s": 3078,
"text": "Float − This is used to represent a 32-bit floating-point number. It is used to hold numbers with smaller decimal points. For example, 3.14159, 0.1, and -273.158."
},
{
"code": null,
"e": 3404,
"s": 3241,
"text": "Float − This is used to represent a 32-bit floating-point number. It is used to hold numbers with smaller decimal points. For example, 3.14159, 0.1, and -273.158."
},
{
"code": null,
"e": 3566,
"s": 3404,
"text": "Double − This is used to represent a 64-bit floating-point number and used when floating-point values must be very large. For example 3.14159, 0.1, and -273.158."
},
{
"code": null,
"e": 3728,
"s": 3566,
"text": "Double − This is used to represent a 64-bit floating-point number and used when floating-point values must be very large. For example 3.14159, 0.1, and -273.158."
},
{
"code": null,
"e": 3798,
"s": 3728,
"text": "Bool − This represents a Boolean value which is either true or false."
},
{
"code": null,
"e": 3868,
"s": 3798,
"text": "Bool − This represents a Boolean value which is either true or false."
},
{
"code": null,
"e": 3951,
"s": 3868,
"text": "String − This is an ordered collection of characters. For example, \"Hello, World!\""
},
{
"code": null,
"e": 4034,
"s": 3951,
"text": "String − This is an ordered collection of characters. For example, \"Hello, World!\""
},
{
"code": null,
"e": 4106,
"s": 4034,
"text": "Character − This is a single-character string literal. For example, \"C\""
},
{
"code": null,
"e": 4178,
"s": 4106,
"text": "Character − This is a single-character string literal. For example, \"C\""
},
{
"code": null,
"e": 4350,
"s": 4178,
"text": "Swift 4 also allows to define various other types of variables, which we will cover in subsequent chapters, such as Optional, Array, Dictionaries, Structures, and Classes."
},
{
"code": null,
"e": 4457,
"s": 4350,
"text": "The following section will cover how to declare and use various types of variables in Swift 4 programming."
},
{
"code": null,
"e": 4637,
"s": 4457,
"text": "A variable declaration tells the compiler where and how much to create the storage for the variable. Before you use variables, you must declare them using var keyword as follows −"
},
{
"code": null,
"e": 4673,
"s": 4637,
"text": "var variableName = <initial value>\n"
},
{
"code": null,
"e": 4740,
"s": 4673,
"text": "The following example shows how to declare a variable in Swift 4 −"
},
{
"code": null,
"e": 4766,
"s": 4740,
"text": "var varA = 42\nprint(varA)"
},
{
"code": null,
"e": 4844,
"s": 4766,
"text": "When we run the above program using playground, we get the following result −"
},
{
"code": null,
"e": 4848,
"s": 4844,
"text": "42\n"
},
{
"code": null,
"e": 4993,
"s": 4848,
"text": "You can provide a type annotation when you declare a variable, to be clear about the kind of values the variable can store. Here is the syntax −"
},
{
"code": null,
"e": 5050,
"s": 4993,
"text": "var variableName:<data type> = <optional initial value>\n"
},
{
"code": null,
"e": 5342,
"s": 5050,
"text": "The following example shows how to declare a variable in Swift 4 using Annotation. Here it is important to note that if we are not using type annotation, then it becomes mandatory to provide an initial value for the variable, otherwise we can just declare our variable using type annotation."
},
{
"code": null,
"e": 5412,
"s": 5342,
"text": "var varA = 42\nprint(varA)\n\nvar varB:Float\n\nvarB = 3.14159\nprint(varB)"
},
{
"code": null,
"e": 5490,
"s": 5412,
"text": "When we run the above program using playground, we get the following result −"
},
{
"code": null,
"e": 5510,
"s": 5490,
"text": "42\n3.1415901184082\n"
},
{
"code": null,
"e": 5751,
"s": 5510,
"text": "The name of a variable can be composed of letters, digits, and the underscore character. It must begin with either a letter or an underscore. Upper and lowercase letters are distinct because Swift 4 is a case-sensitive programming language."
},
{
"code": null,
"e": 5878,
"s": 5751,
"text": "You can use simple or Unicode characters to name your variables. The following examples shows how you can name the variables −"
},
{
"code": null,
"e": 5946,
"s": 5878,
"text": "var _var = \"Hello, Swift 4!\"\nprint(_var)\n\nvar 你好 = \"你好世界\"\nprint(你好)"
},
{
"code": null,
"e": 6023,
"s": 5946,
"text": "When we run the above program using playground, we get the following result."
},
{
"code": null,
"e": 6045,
"s": 6023,
"text": "Hello, Swift 4!\n你好世界\n"
},
{
"code": null,
"e": 6295,
"s": 6045,
"text": "You can print the current value of a constant or variable with the print function. You can interpolate a variable value by wrapping the name in parentheses and escape it with a backslash before the opening parenthesis: Following are valid examples −"
},
{
"code": null,
"e": 6393,
"s": 6295,
"text": "var varA = \"Godzilla\"\nvar varB = 1000.00\n\nprint(\"Value of \\(varA) is more than \\(varB) millions\")"
},
{
"code": null,
"e": 6470,
"s": 6393,
"text": "When we run the above program using playground, we get the following result."
},
{
"code": null,
"e": 6518,
"s": 6470,
"text": "Value of Godzilla is more than 1000.0 millions\n"
},
{
"code": null,
"e": 6551,
"s": 6518,
"text": "\n 38 Lectures \n 1 hours \n"
},
{
"code": null,
"e": 6566,
"s": 6551,
"text": " Ashish Sharma"
},
{
"code": null,
"e": 6599,
"s": 6566,
"text": "\n 13 Lectures \n 2 hours \n"
},
{
"code": null,
"e": 6618,
"s": 6599,
"text": " Three Millennials"
},
{
"code": null,
"e": 6650,
"s": 6618,
"text": "\n 7 Lectures \n 1 hours \n"
},
{
"code": null,
"e": 6669,
"s": 6650,
"text": " Three Millennials"
},
{
"code": null,
"e": 6702,
"s": 6669,
"text": "\n 22 Lectures \n 1 hours \n"
},
{
"code": null,
"e": 6719,
"s": 6702,
"text": " Frahaan Hussain"
},
{
"code": null,
"e": 6751,
"s": 6719,
"text": "\n 12 Lectures \n 39 mins\n"
},
{
"code": null,
"e": 6771,
"s": 6751,
"text": " Devasena Rajendran"
},
{
"code": null,
"e": 6806,
"s": 6771,
"text": "\n 40 Lectures \n 2.5 hours \n"
},
{
"code": null,
"e": 6823,
"s": 6806,
"text": " Grant Klimaytys"
},
{
"code": null,
"e": 6830,
"s": 6823,
"text": " Print"
},
{
"code": null,
"e": 6841,
"s": 6830,
"text": " Add Notes"
}
] |
Python MongoDB - Create Collection
|
A collection in MongoDB holds a set of documents, it is analogous to a table in relational databases.
You can create a collection using the createCollection() method. This method accepts a String value representing the name of the collection to be created and an options (optional) parameter.
Using this you can specify the following −
The size of the collection.
The max number of documents allowed in the capped collection.
Whether the collection we create should be capped collection (fixed size collection).
Whether the collection we create should be auto-indexed.
Following is the syntax to create a collection in MongoDB.
db.createCollection("CollectionName")
Following method creates a collection named ExampleCollection.
> use mydb
switched to db mydb
> db.createCollection("ExampleCollection")
{ "ok" : 1 }
>
Similarly, following is a query that creates a collection using the options of the createCollection() method.
>db.createCollection("mycol", { capped : true, autoIndexId : true, size :
6142800, max : 10000 } )
{ "ok" : 1 }
>
Following python example connects to a database in MongoDB (mydb) and, creates a collection in it.
from pymongo import MongoClient
#Creating a pymongo client
client = MongoClient('localhost', 27017)
#Getting the database instance
db = client['mydb']
#Creating a collection
collection = db['example']
print("Collection created........")
Collection created........
187 Lectures
17.5 hours
Malhar Lathkar
55 Lectures
8 hours
Arnab Chakraborty
136 Lectures
11 hours
In28Minutes Official
75 Lectures
13 hours
Eduonix Learning Solutions
70 Lectures
8.5 hours
Lets Kode It
63 Lectures
6 hours
Abhilash Nelson
Print
Add Notes
Bookmark this page
|
[
{
"code": null,
"e": 3307,
"s": 3205,
"text": "A collection in MongoDB holds a set of documents, it is analogous to a table in relational databases."
},
{
"code": null,
"e": 3498,
"s": 3307,
"text": "You can create a collection using the createCollection() method. This method accepts a String value representing the name of the collection to be created and an options (optional) parameter."
},
{
"code": null,
"e": 3541,
"s": 3498,
"text": "Using this you can specify the following −"
},
{
"code": null,
"e": 3569,
"s": 3541,
"text": "The size of the collection."
},
{
"code": null,
"e": 3631,
"s": 3569,
"text": "The max number of documents allowed in the capped collection."
},
{
"code": null,
"e": 3717,
"s": 3631,
"text": "Whether the collection we create should be capped collection (fixed size collection)."
},
{
"code": null,
"e": 3774,
"s": 3717,
"text": "Whether the collection we create should be auto-indexed."
},
{
"code": null,
"e": 3833,
"s": 3774,
"text": "Following is the syntax to create a collection in MongoDB."
},
{
"code": null,
"e": 3872,
"s": 3833,
"text": "db.createCollection(\"CollectionName\")\n"
},
{
"code": null,
"e": 3935,
"s": 3872,
"text": "Following method creates a collection named ExampleCollection."
},
{
"code": null,
"e": 4025,
"s": 3935,
"text": "> use mydb\nswitched to db mydb\n> db.createCollection(\"ExampleCollection\")\n{ \"ok\" : 1 }\n>\n"
},
{
"code": null,
"e": 4135,
"s": 4025,
"text": "Similarly, following is a query that creates a collection using the options of the createCollection() method."
},
{
"code": null,
"e": 4250,
"s": 4135,
"text": ">db.createCollection(\"mycol\", { capped : true, autoIndexId : true, size :\n6142800, max : 10000 } )\n{ \"ok\" : 1 }\n>\n"
},
{
"code": null,
"e": 4349,
"s": 4250,
"text": "Following python example connects to a database in MongoDB (mydb) and, creates a collection in it."
},
{
"code": null,
"e": 4589,
"s": 4349,
"text": "from pymongo import MongoClient\n\n#Creating a pymongo client\nclient = MongoClient('localhost', 27017)\n\n#Getting the database instance\ndb = client['mydb']\n\n#Creating a collection\ncollection = db['example']\nprint(\"Collection created........\")"
},
{
"code": null,
"e": 4617,
"s": 4589,
"text": "Collection created........\n"
},
{
"code": null,
"e": 4654,
"s": 4617,
"text": "\n 187 Lectures \n 17.5 hours \n"
},
{
"code": null,
"e": 4670,
"s": 4654,
"text": " Malhar Lathkar"
},
{
"code": null,
"e": 4703,
"s": 4670,
"text": "\n 55 Lectures \n 8 hours \n"
},
{
"code": null,
"e": 4722,
"s": 4703,
"text": " Arnab Chakraborty"
},
{
"code": null,
"e": 4757,
"s": 4722,
"text": "\n 136 Lectures \n 11 hours \n"
},
{
"code": null,
"e": 4779,
"s": 4757,
"text": " In28Minutes Official"
},
{
"code": null,
"e": 4813,
"s": 4779,
"text": "\n 75 Lectures \n 13 hours \n"
},
{
"code": null,
"e": 4841,
"s": 4813,
"text": " Eduonix Learning Solutions"
},
{
"code": null,
"e": 4876,
"s": 4841,
"text": "\n 70 Lectures \n 8.5 hours \n"
},
{
"code": null,
"e": 4890,
"s": 4876,
"text": " Lets Kode It"
},
{
"code": null,
"e": 4923,
"s": 4890,
"text": "\n 63 Lectures \n 6 hours \n"
},
{
"code": null,
"e": 4940,
"s": 4923,
"text": " Abhilash Nelson"
},
{
"code": null,
"e": 4947,
"s": 4940,
"text": " Print"
},
{
"code": null,
"e": 4958,
"s": 4947,
"text": " Add Notes"
}
] |
C# program to find node in Linked List
|
Firstly, create a new linked list −
LinkedList<string> myList = new LinkedList<string>();
Now add some elements in the linked list −
// Add 6 elements in the linked list
myList.AddLast("P");
myList.AddLast("Q");
myList.AddLast("R");
myList.AddLast("S");
myList.AddLast("T");
myList.AddLast("U");
Let’s now find a node and add a new node after that −
LinkedListNode<string> node = myList.Find("R");
myList.AddAfter(node, "ADDED");
You can try to run the following code to find a node in the linked list.
Live Demo
using System;
using System.Collections.Generic;
class Program {
static void Main() {
LinkedList<string> myList = new LinkedList<string>();
// Add 6 elements in the linked list
myList.AddLast("P");
myList.AddLast("Q");
myList.AddLast("R");
myList.AddLast("S");
myList.AddLast("T");
myList.AddLast("U");
LinkedListNode<string> node = myList.Find("R");
myList.AddAfter(node, "ADDED");
foreach (var i in myList) {
Console.WriteLine(i);
}
}
}
P
Q
R
ADDED
S
T
U
|
[
{
"code": null,
"e": 1098,
"s": 1062,
"text": "Firstly, create a new linked list −"
},
{
"code": null,
"e": 1152,
"s": 1098,
"text": "LinkedList<string> myList = new LinkedList<string>();"
},
{
"code": null,
"e": 1195,
"s": 1152,
"text": "Now add some elements in the linked list −"
},
{
"code": null,
"e": 1358,
"s": 1195,
"text": "// Add 6 elements in the linked list\nmyList.AddLast(\"P\");\nmyList.AddLast(\"Q\");\nmyList.AddLast(\"R\");\nmyList.AddLast(\"S\");\nmyList.AddLast(\"T\");\nmyList.AddLast(\"U\");"
},
{
"code": null,
"e": 1412,
"s": 1358,
"text": "Let’s now find a node and add a new node after that −"
},
{
"code": null,
"e": 1492,
"s": 1412,
"text": "LinkedListNode<string> node = myList.Find(\"R\");\nmyList.AddAfter(node, \"ADDED\");"
},
{
"code": null,
"e": 1565,
"s": 1492,
"text": "You can try to run the following code to find a node in the linked list."
},
{
"code": null,
"e": 1575,
"s": 1565,
"text": "Live Demo"
},
{
"code": null,
"e": 2100,
"s": 1575,
"text": "using System;\nusing System.Collections.Generic;\nclass Program {\n static void Main() {\n LinkedList<string> myList = new LinkedList<string>();\n // Add 6 elements in the linked list\n myList.AddLast(\"P\");\n myList.AddLast(\"Q\");\n myList.AddLast(\"R\");\n myList.AddLast(\"S\");\n myList.AddLast(\"T\");\n myList.AddLast(\"U\");\n LinkedListNode<string> node = myList.Find(\"R\");\n myList.AddAfter(node, \"ADDED\");\n foreach (var i in myList) {\n Console.WriteLine(i);\n }\n }\n}"
},
{
"code": null,
"e": 2118,
"s": 2100,
"text": "P\nQ\nR\nADDED\nS\nT\nU"
}
] |
Convert HTML source code to JSON Object using Python - GeeksforGeeks
|
03 Mar, 2021
In this post, we will see how we can convert an HTML source code into a JSON object. JSON objects can be easily transferred, and they are supported by most of the modern programming languages. We can read JSON from Javascript and parse it as a Javascript object easily. Javascript can be used to make HTML for your web pages.
We will use xmltojson module in this post. The parse function of this module takes the HTML as the input and returns the parsed JSON string.
Syntax: xmltojson.parse(xml_input, xml_attribs=True, item_depth=0, item_callback)
Parameters:
xml_input can be either a file or a string.
xml_attribs will include attributes if set to True. Otherwise, ignore them if set to False.
item_depth is the depth of children for which item_callback function is called when found.
item_callback is a callback function
Environment Setup:
Install the required modules :
pip install xmltojson
pip install requests
Steps:
Import the libraries
Python3
import xmltojsonimport jsonimport requests
Fetch the HTML code and save it into a file.
Python3
# Sample URL to fetch the html pageurl = "https://geeksforgeeks-example.surge.sh" # Headers to mimic the browserheaders = { 'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_10_1) AppleWebKit/537.36 \ (KHTML, like Gecko) Chrome/39.0.2171.95 Safari/537.36'} # Get the page through get() methodhtml_response = requests.get(url=url, headers = headers) # Save the page content as sample.htmlwith open("sample.html", "w") as html_file: html_file.write(html_response.text)
Use the parse function to convert this HTML into JSON. Open the HTML file and use the parse function of xmltojson module.
Python3
with open("sample.html", "r") as html_file: html = html_file.read() json_ = xmltojson.parse(html)
The json_ variable contains a JSON string that we can print or dump into a file.
Python3
with open("data.json", "w") as file: json.dump(json_, file)
Print the output.
Python3
print(json_)
Complete Code:
Python3
import xmltojsonimport jsonimport requests # Sample URL to fetch the html pageurl = "https://geeksforgeeks-example.surge.sh" # Headers to mimic the browserheaders = { 'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_10_1) AppleWebKit/537.36 \ (KHTML, like Gecko) Chrome/39.0.2171.95 Safari/537.36'} # Get the page through get() methodhtml_response = requests.get(url=url, headers = headers) # Save the page content as sample.htmlwith open("sample.html", "w") as html_file: html_file.write(html_response.text) with open("sample.html", "r") as html_file: html = html_file.read() json_ = xmltojson.parse(html) with open("data.json", "w") as file: json.dump(json_, file) print(json_)
Output:
{“html”: {“@lang”: “en”, “head”: {“title”: “Document”}, “body”: {“div”: {“h1”: “Geeks For Geeks”, “p”:
“Welcome to the world of programming geeks!”, “input”: [{“@type”: “text”, “@placeholder”: “Enter your name”},
{“@type”: “button”, “@value”: “submit”}]}}}}
Picked
Python-json
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
How To Convert Python Dictionary To JSON?
Check if element exists in list in Python
Python | Get unique values from a list
Defaultdict in Python
Python OOPs Concepts
Python | os.path.join() method
Python | Pandas dataframe.groupby()
|
[
{
"code": null,
"e": 24316,
"s": 24288,
"text": "\n03 Mar, 2021"
},
{
"code": null,
"e": 24643,
"s": 24316,
"text": "In this post, we will see how we can convert an HTML source code into a JSON object. JSON objects can be easily transferred, and they are supported by most of the modern programming languages. We can read JSON from Javascript and parse it as a Javascript object easily. Javascript can be used to make HTML for your web pages. "
},
{
"code": null,
"e": 24784,
"s": 24643,
"text": "We will use xmltojson module in this post. The parse function of this module takes the HTML as the input and returns the parsed JSON string."
},
{
"code": null,
"e": 24866,
"s": 24784,
"text": "Syntax: xmltojson.parse(xml_input, xml_attribs=True, item_depth=0, item_callback)"
},
{
"code": null,
"e": 24878,
"s": 24866,
"text": "Parameters:"
},
{
"code": null,
"e": 24922,
"s": 24878,
"text": "xml_input can be either a file or a string."
},
{
"code": null,
"e": 25014,
"s": 24922,
"text": "xml_attribs will include attributes if set to True. Otherwise, ignore them if set to False."
},
{
"code": null,
"e": 25105,
"s": 25014,
"text": "item_depth is the depth of children for which item_callback function is called when found."
},
{
"code": null,
"e": 25142,
"s": 25105,
"text": "item_callback is a callback function"
},
{
"code": null,
"e": 25161,
"s": 25142,
"text": "Environment Setup:"
},
{
"code": null,
"e": 25192,
"s": 25161,
"text": "Install the required modules :"
},
{
"code": null,
"e": 25235,
"s": 25192,
"text": "pip install xmltojson\npip install requests"
},
{
"code": null,
"e": 25242,
"s": 25235,
"text": "Steps:"
},
{
"code": null,
"e": 25263,
"s": 25242,
"text": "Import the libraries"
},
{
"code": null,
"e": 25271,
"s": 25263,
"text": "Python3"
},
{
"code": "import xmltojsonimport jsonimport requests",
"e": 25314,
"s": 25271,
"text": null
},
{
"code": null,
"e": 25359,
"s": 25314,
"text": "Fetch the HTML code and save it into a file."
},
{
"code": null,
"e": 25367,
"s": 25359,
"text": "Python3"
},
{
"code": "# Sample URL to fetch the html pageurl = \"https://geeksforgeeks-example.surge.sh\" # Headers to mimic the browserheaders = { 'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_10_1) AppleWebKit/537.36 \\ (KHTML, like Gecko) Chrome/39.0.2171.95 Safari/537.36'} # Get the page through get() methodhtml_response = requests.get(url=url, headers = headers) # Save the page content as sample.htmlwith open(\"sample.html\", \"w\") as html_file: html_file.write(html_response.text)",
"e": 25853,
"s": 25367,
"text": null
},
{
"code": null,
"e": 25975,
"s": 25853,
"text": "Use the parse function to convert this HTML into JSON. Open the HTML file and use the parse function of xmltojson module."
},
{
"code": null,
"e": 25983,
"s": 25975,
"text": "Python3"
},
{
"code": "with open(\"sample.html\", \"r\") as html_file: html = html_file.read() json_ = xmltojson.parse(html)",
"e": 26087,
"s": 25983,
"text": null
},
{
"code": null,
"e": 26168,
"s": 26087,
"text": "The json_ variable contains a JSON string that we can print or dump into a file."
},
{
"code": null,
"e": 26176,
"s": 26168,
"text": "Python3"
},
{
"code": "with open(\"data.json\", \"w\") as file: json.dump(json_, file)",
"e": 26239,
"s": 26176,
"text": null
},
{
"code": null,
"e": 26257,
"s": 26239,
"text": "Print the output."
},
{
"code": null,
"e": 26265,
"s": 26257,
"text": "Python3"
},
{
"code": "print(json_)",
"e": 26278,
"s": 26265,
"text": null
},
{
"code": null,
"e": 26293,
"s": 26278,
"text": "Complete Code:"
},
{
"code": null,
"e": 26301,
"s": 26293,
"text": "Python3"
},
{
"code": "import xmltojsonimport jsonimport requests # Sample URL to fetch the html pageurl = \"https://geeksforgeeks-example.surge.sh\" # Headers to mimic the browserheaders = { 'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_10_1) AppleWebKit/537.36 \\ (KHTML, like Gecko) Chrome/39.0.2171.95 Safari/537.36'} # Get the page through get() methodhtml_response = requests.get(url=url, headers = headers) # Save the page content as sample.htmlwith open(\"sample.html\", \"w\") as html_file: html_file.write(html_response.text) with open(\"sample.html\", \"r\") as html_file: html = html_file.read() json_ = xmltojson.parse(html) with open(\"data.json\", \"w\") as file: json.dump(json_, file) print(json_)",
"e": 27028,
"s": 26301,
"text": null
},
{
"code": null,
"e": 27036,
"s": 27028,
"text": "Output:"
},
{
"code": null,
"e": 27140,
"s": 27036,
"text": "{“html”: {“@lang”: “en”, “head”: {“title”: “Document”}, “body”: {“div”: {“h1”: “Geeks For Geeks”, “p”: "
},
{
"code": null,
"e": 27251,
"s": 27140,
"text": "“Welcome to the world of programming geeks!”, “input”: [{“@type”: “text”, “@placeholder”: “Enter your name”}, "
},
{
"code": null,
"e": 27296,
"s": 27251,
"text": "{“@type”: “button”, “@value”: “submit”}]}}}}"
},
{
"code": null,
"e": 27303,
"s": 27296,
"text": "Picked"
},
{
"code": null,
"e": 27315,
"s": 27303,
"text": "Python-json"
},
{
"code": null,
"e": 27322,
"s": 27315,
"text": "Python"
},
{
"code": null,
"e": 27420,
"s": 27322,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 27429,
"s": 27420,
"text": "Comments"
},
{
"code": null,
"e": 27442,
"s": 27429,
"text": "Old Comments"
},
{
"code": null,
"e": 27474,
"s": 27442,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 27529,
"s": 27474,
"text": "Selecting rows in pandas DataFrame based on conditions"
},
{
"code": null,
"e": 27585,
"s": 27529,
"text": "How to drop one or multiple columns in Pandas Dataframe"
},
{
"code": null,
"e": 27627,
"s": 27585,
"text": "How To Convert Python Dictionary To JSON?"
},
{
"code": null,
"e": 27669,
"s": 27627,
"text": "Check if element exists in list in Python"
},
{
"code": null,
"e": 27708,
"s": 27669,
"text": "Python | Get unique values from a list"
},
{
"code": null,
"e": 27730,
"s": 27708,
"text": "Defaultdict in Python"
},
{
"code": null,
"e": 27751,
"s": 27730,
"text": "Python OOPs Concepts"
},
{
"code": null,
"e": 27782,
"s": 27751,
"text": "Python | os.path.join() method"
}
] |
Find the maximum sum leaf to root path in a Binary Tree - GeeksforGeeks
|
19 Feb, 2020
Given a Binary Tree, find the maximum sum path from a leaf to root. For example, in the following tree, there are three leaf to root paths 8->-2->10, -4->-2->10 and 7->10. The sums of these three paths are 16, 4 and 17 respectively. The maximum of them is 17 and the path for maximum is 7->10. 10
/ \
-2 7
/ \
8 -4
Recommended PracticeMaximum sum leaf to root pathTry It!Solution1) First find the leaf node that is on the maximum sum path. In the following code getTargetLeaf() does this by assigning the result to *target_leaf_ref.2) Once we have the target leaf node, we can print the maximum sum path by traversing the tree. In the following code, printPath() does this.The main function is maxSumPath() that uses above two functions to get the complete solution.C++CJavaPython3C#C++// CPP program to find maximum sum leaf to root// path in Binary Tree#include <bits/stdc++.h>using namespace std; /* A tree node structure */class node {public: int data; node* left; node* right;}; // A utility function that prints all nodes// on the path from root to target_leafbool printPath(node* root, node* target_leaf){ // base case if (root == NULL) return false; // return true if this node is the target_leaf // or target leaf is present in one of its // descendants if (root == target_leaf || printPath(root->left, target_leaf) || printPath(root->right, target_leaf)) { cout << root->data << " "; return true; } return false;} // This function Sets the target_leaf_ref to refer// the leaf node of the maximum path sum. Also,// returns the max_sum using max_sum_refvoid getTargetLeaf(node* Node, int* max_sum_ref, int curr_sum, node** target_leaf_ref){ if (Node == NULL) return; // Update current sum to hold sum of nodes on path // from root to this node curr_sum = curr_sum + Node->data; // If this is a leaf node and path to this node has // maximum sum so far, then make this node target_leaf if (Node->left == NULL && Node->right == NULL) { if (curr_sum > *max_sum_ref) { *max_sum_ref = curr_sum; *target_leaf_ref = Node; } } // If this is not a leaf node, then recur down // to find the target_leaf getTargetLeaf(Node->left, max_sum_ref, curr_sum, target_leaf_ref); getTargetLeaf(Node->right, max_sum_ref, curr_sum, target_leaf_ref);} // Returns the maximum sum and prints the nodes on max// sum pathint maxSumPath(node* Node){ // base case if (Node == NULL) return 0; node* target_leaf; int max_sum = INT_MIN; // find the target leaf and maximum sum getTargetLeaf(Node, &max_sum, 0, &target_leaf); // print the path from root to the target leaf printPath(Node, target_leaf); return max_sum; // return maximum sum} /* Utility function to create a new Binary Tree node */node* newNode(int data){ node* temp = new node; temp->data = data; temp->left = NULL; temp->right = NULL; return temp;} /* Driver function to test above functions */int main(){ node* root = NULL; /* Constructing tree given in the above figure */ root = newNode(10); root->left = newNode(-2); root->right = newNode(7); root->left->left = newNode(8); root->left->right = newNode(-4); cout << "Following are the nodes on the maximum " "sum path \n"; int sum = maxSumPath(root); cout << "\nSum of the nodes is " << sum; return 0;} // This code is contributed by rathbhupendraC// C program to find maximum sum leaf to root// path in Binary Tree#include <limits.h>#include <stdbool.h>#include <stdio.h>#include <stdlib.h> /* A tree node structure */struct node { int data; struct node* left; struct node* right;}; // A utility function that prints all nodes// on the path from root to target_leafbool printPath(struct node* root, struct node* target_leaf){ // base case if (root == NULL) return false; // return true if this node is the target_leaf // or target leaf is present in one of its // descendants if (root == target_leaf || printPath(root->left, target_leaf) || printPath(root->right, target_leaf)) { printf("%d ", root->data); return true; } return false;} // This function Sets the target_leaf_ref to refer// the leaf node of the maximum path sum. Also,// returns the max_sum using max_sum_refvoid getTargetLeaf(struct node* node, int* max_sum_ref, int curr_sum, struct node** target_leaf_ref){ if (node == NULL) return; // Update current sum to hold sum of nodes on path // from root to this node curr_sum = curr_sum + node->data; // If this is a leaf node and path to this node has // maximum sum so far, then make this node target_leaf if (node->left == NULL && node->right == NULL) { if (curr_sum > *max_sum_ref) { *max_sum_ref = curr_sum; *target_leaf_ref = node; } } // If this is not a leaf node, then recur down // to find the target_leaf getTargetLeaf(node->left, max_sum_ref, curr_sum, target_leaf_ref); getTargetLeaf(node->right, max_sum_ref, curr_sum, target_leaf_ref);} // Returns the maximum sum and prints the nodes on max// sum pathint maxSumPath(struct node* node){ // base case if (node == NULL) return 0; struct node* target_leaf; int max_sum = INT_MIN; // find the target leaf and maximum sum getTargetLeaf(node, &max_sum, 0, &target_leaf); // print the path from root to the target leaf printPath(node, target_leaf); return max_sum; // return maximum sum} /* Utility function to create a new Binary Tree node */struct node* newNode(int data){ struct node* temp = (struct node*)malloc(sizeof(struct node)); temp->data = data; temp->left = NULL; temp->right = NULL; return temp;} /* Driver function to test above functions */int main(){ struct node* root = NULL; /* Constructing tree given in the above figure */ root = newNode(10); root->left = newNode(-2); root->right = newNode(7); root->left->left = newNode(8); root->left->right = newNode(-4); printf("Following are the nodes on the maximum " "sum path \n"); int sum = maxSumPath(root); printf("\nSum of the nodes is %d ", sum); getchar(); return 0;}Java// Java program to find maximum sum leaf to root// path in Binary Tree // A Binary Tree nodeclass Node { int data; Node left, right; Node(int item) { data = item; left = right = null; }} // A wrapper class is used so that max_no// can be updated among function calls.class Maximum { int max_no = Integer.MIN_VALUE;} class BinaryTree { Node root; Maximum max = new Maximum(); Node target_leaf = null; // A utility function that prints all nodes on the // path from root to target_leaf boolean printPath(Node node, Node target_leaf) { // base case if (node == null) return false; // return true if this node is the target_leaf or // target leaf is present in one of its descendants if (node == target_leaf || printPath(node.left, target_leaf) || printPath(node.right, target_leaf)) { System.out.print(node.data + " "); return true; } return false; } // This function Sets the target_leaf_ref to refer // the leaf node of the maximum path sum. Also, // returns the max_sum using max_sum_ref void getTargetLeaf(Node node, Maximum max_sum_ref, int curr_sum) { if (node == null) return; // Update current sum to hold sum of nodes on // path from root to this node curr_sum = curr_sum + node.data; // If this is a leaf node and path to this node // has maximum sum so far, the n make this node // target_leaf if (node.left == null && node.right == null) { if (curr_sum > max_sum_ref.max_no) { max_sum_ref.max_no = curr_sum; target_leaf = node; } } // If this is not a leaf node, then recur down // to find the target_leaf getTargetLeaf(node.left, max_sum_ref, curr_sum); getTargetLeaf(node.right, max_sum_ref, curr_sum); } // Returns the maximum sum and prints the nodes on // max sum path int maxSumPath() { // base case if (root == null) return 0; // find the target leaf and maximum sum getTargetLeaf(root, max, 0); // print the path from root to the target leaf printPath(root, target_leaf); return max.max_no; // return maximum sum } // driver function to test the above functions public static void main(String args[]) { BinaryTree tree = new BinaryTree(); tree.root = new Node(10); tree.root.left = new Node(-2); tree.root.right = new Node(7); tree.root.left.left = new Node(8); tree.root.left.right = new Node(-4); System.out.println("Following are the nodes " + "on maximum sum path"); int sum = tree.maxSumPath(); System.out.println(""); System.out.println("Sum of nodes is : " + sum); }}// This code has been contributed by Mayank JaiswalPython3# Python3 program to find maximum sum leaf to root# path in Binary Tree # A tree node structure class node : def __init__(self): self.data = 0 self.left = None self.right = None # A utility function that prints all nodes# on the path from root to target_leafdef printPath( root,target_leaf): # base case if (root == None): return False # return True if this node is the target_leaf # or target leaf is present in one of its # descendants if (root == target_leaf or printPath(root.left, target_leaf) or printPath(root.right, target_leaf)) : print( root.data, end = " ") return True return False max_sum_ref = 0target_leaf_ref = None # This function Sets the target_leaf_ref to refer# the leaf node of the maximum path sum. Also,# returns the max_sum using max_sum_refdef getTargetLeaf(Node, curr_sum): global max_sum_ref global target_leaf_ref if (Node == None): return # Update current sum to hold sum of nodes on path # from root to this node curr_sum = curr_sum + Node.data # If this is a leaf node and path to this node has # maximum sum so far, then make this node target_leaf if (Node.left == None and Node.right == None): if (curr_sum > max_sum_ref) : max_sum_ref = curr_sum target_leaf_ref = Node # If this is not a leaf node, then recur down # to find the target_leaf getTargetLeaf(Node.left, curr_sum) getTargetLeaf(Node.right, curr_sum) # Returns the maximum sum and prints the nodes on max# sum pathdef maxSumPath( Node): global max_sum_ref global target_leaf_ref # base case if (Node == None): return 0 target_leaf_ref = None max_sum_ref = -32676 # find the target leaf and maximum sum getTargetLeaf(Node, 0) # print the path from root to the target leaf printPath(Node, target_leaf_ref); return max_sum_ref; # return maximum sum # Utility function to create a new Binary Tree node def newNode(data): temp = node(); temp.data = data; temp.left = None; temp.right = None; return temp; # Driver function to test above functions root = None; # Constructing tree given in the above figure root = newNode(10);root.left = newNode(-2);root.right = newNode(7);root.left.left = newNode(8);root.left.right = newNode(-4); print( "Following are the nodes on the maximum sum path ");sum = maxSumPath(root);print( "\nSum of the nodes is " , sum); # This code is contributed by Arnab Kundu C#using System; // C# program to find maximum sum leaf to root// path in Binary Tree // A Binary Tree nodepublic class Node { public int data; public Node left, right; public Node(int item) { data = item; left = right = null; }} // A wrapper class is used so that max_no// can be updated among function calls.public class Maximum { public int max_no = int.MinValue;} public class BinaryTree { public Node root; public Maximum max = new Maximum(); public Node target_leaf = null; // A utility function that prints all nodes on the // path from root to target_leaf public virtual bool printPath(Node node, Node target_leaf) { // base case if (node == null) { return false; } // return true if this node is the target_leaf or // target leaf is present in one of its descendants if (node == target_leaf || printPath(node.left, target_leaf) || printPath(node.right, target_leaf)) { Console.Write(node.data + " "); return true; } return false; } // This function Sets the target_leaf_ref to refer // the leaf node of the maximum path sum. Also, // returns the max_sum using max_sum_ref public virtual void getTargetLeaf(Node node, Maximum max_sum_ref, int curr_sum) { if (node == null) { return; } // Update current sum to hold sum of nodes on // path from root to this node curr_sum = curr_sum + node.data; // If this is a leaf node and path to this node // has maximum sum so far, the n make this node // target_leaf if (node.left == null && node.right == null) { if (curr_sum > max_sum_ref.max_no) { max_sum_ref.max_no = curr_sum; target_leaf = node; } } // If this is not a leaf node, then recur down // to find the target_leaf getTargetLeaf(node.left, max_sum_ref, curr_sum); getTargetLeaf(node.right, max_sum_ref, curr_sum); } // Returns the maximum sum and prints the nodes on // max sum path public virtual int maxSumPath() { // base case if (root == null) { return 0; } // find the target leaf and maximum sum getTargetLeaf(root, max, 0); // print the path from root to the target leaf printPath(root, target_leaf); return max.max_no; // return maximum sum } // driver function to test the above functions public static void Main(string[] args) { BinaryTree tree = new BinaryTree(); tree.root = new Node(10); tree.root.left = new Node(-2); tree.root.right = new Node(7); tree.root.left.left = new Node(8); tree.root.left.right = new Node(-4); Console.WriteLine("Following are the nodes " + "on maximum sum path"); int sum = tree.maxSumPath(); Console.WriteLine(""); Console.WriteLine("Sum of nodes is : " + sum); }} // This code is contributed by Shrikant13Output:Following are the nodes on the maximum sum path
7 10
Sum of the nodes is 17
Time Complexity: Time complexity of the above solution is O(n) as it involves tree traversal two times.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.My Personal Notes
arrow_drop_upSave
10
/ \
-2 7
/ \
8 -4
Solution1) First find the leaf node that is on the maximum sum path. In the following code getTargetLeaf() does this by assigning the result to *target_leaf_ref.2) Once we have the target leaf node, we can print the maximum sum path by traversing the tree. In the following code, printPath() does this.
The main function is maxSumPath() that uses above two functions to get the complete solution.
C++
C
Java
Python3
C#
// CPP program to find maximum sum leaf to root// path in Binary Tree#include <bits/stdc++.h>using namespace std; /* A tree node structure */class node {public: int data; node* left; node* right;}; // A utility function that prints all nodes// on the path from root to target_leafbool printPath(node* root, node* target_leaf){ // base case if (root == NULL) return false; // return true if this node is the target_leaf // or target leaf is present in one of its // descendants if (root == target_leaf || printPath(root->left, target_leaf) || printPath(root->right, target_leaf)) { cout << root->data << " "; return true; } return false;} // This function Sets the target_leaf_ref to refer// the leaf node of the maximum path sum. Also,// returns the max_sum using max_sum_refvoid getTargetLeaf(node* Node, int* max_sum_ref, int curr_sum, node** target_leaf_ref){ if (Node == NULL) return; // Update current sum to hold sum of nodes on path // from root to this node curr_sum = curr_sum + Node->data; // If this is a leaf node and path to this node has // maximum sum so far, then make this node target_leaf if (Node->left == NULL && Node->right == NULL) { if (curr_sum > *max_sum_ref) { *max_sum_ref = curr_sum; *target_leaf_ref = Node; } } // If this is not a leaf node, then recur down // to find the target_leaf getTargetLeaf(Node->left, max_sum_ref, curr_sum, target_leaf_ref); getTargetLeaf(Node->right, max_sum_ref, curr_sum, target_leaf_ref);} // Returns the maximum sum and prints the nodes on max// sum pathint maxSumPath(node* Node){ // base case if (Node == NULL) return 0; node* target_leaf; int max_sum = INT_MIN; // find the target leaf and maximum sum getTargetLeaf(Node, &max_sum, 0, &target_leaf); // print the path from root to the target leaf printPath(Node, target_leaf); return max_sum; // return maximum sum} /* Utility function to create a new Binary Tree node */node* newNode(int data){ node* temp = new node; temp->data = data; temp->left = NULL; temp->right = NULL; return temp;} /* Driver function to test above functions */int main(){ node* root = NULL; /* Constructing tree given in the above figure */ root = newNode(10); root->left = newNode(-2); root->right = newNode(7); root->left->left = newNode(8); root->left->right = newNode(-4); cout << "Following are the nodes on the maximum " "sum path \n"; int sum = maxSumPath(root); cout << "\nSum of the nodes is " << sum; return 0;} // This code is contributed by rathbhupendra
// C program to find maximum sum leaf to root// path in Binary Tree#include <limits.h>#include <stdbool.h>#include <stdio.h>#include <stdlib.h> /* A tree node structure */struct node { int data; struct node* left; struct node* right;}; // A utility function that prints all nodes// on the path from root to target_leafbool printPath(struct node* root, struct node* target_leaf){ // base case if (root == NULL) return false; // return true if this node is the target_leaf // or target leaf is present in one of its // descendants if (root == target_leaf || printPath(root->left, target_leaf) || printPath(root->right, target_leaf)) { printf("%d ", root->data); return true; } return false;} // This function Sets the target_leaf_ref to refer// the leaf node of the maximum path sum. Also,// returns the max_sum using max_sum_refvoid getTargetLeaf(struct node* node, int* max_sum_ref, int curr_sum, struct node** target_leaf_ref){ if (node == NULL) return; // Update current sum to hold sum of nodes on path // from root to this node curr_sum = curr_sum + node->data; // If this is a leaf node and path to this node has // maximum sum so far, then make this node target_leaf if (node->left == NULL && node->right == NULL) { if (curr_sum > *max_sum_ref) { *max_sum_ref = curr_sum; *target_leaf_ref = node; } } // If this is not a leaf node, then recur down // to find the target_leaf getTargetLeaf(node->left, max_sum_ref, curr_sum, target_leaf_ref); getTargetLeaf(node->right, max_sum_ref, curr_sum, target_leaf_ref);} // Returns the maximum sum and prints the nodes on max// sum pathint maxSumPath(struct node* node){ // base case if (node == NULL) return 0; struct node* target_leaf; int max_sum = INT_MIN; // find the target leaf and maximum sum getTargetLeaf(node, &max_sum, 0, &target_leaf); // print the path from root to the target leaf printPath(node, target_leaf); return max_sum; // return maximum sum} /* Utility function to create a new Binary Tree node */struct node* newNode(int data){ struct node* temp = (struct node*)malloc(sizeof(struct node)); temp->data = data; temp->left = NULL; temp->right = NULL; return temp;} /* Driver function to test above functions */int main(){ struct node* root = NULL; /* Constructing tree given in the above figure */ root = newNode(10); root->left = newNode(-2); root->right = newNode(7); root->left->left = newNode(8); root->left->right = newNode(-4); printf("Following are the nodes on the maximum " "sum path \n"); int sum = maxSumPath(root); printf("\nSum of the nodes is %d ", sum); getchar(); return 0;}
// Java program to find maximum sum leaf to root// path in Binary Tree // A Binary Tree nodeclass Node { int data; Node left, right; Node(int item) { data = item; left = right = null; }} // A wrapper class is used so that max_no// can be updated among function calls.class Maximum { int max_no = Integer.MIN_VALUE;} class BinaryTree { Node root; Maximum max = new Maximum(); Node target_leaf = null; // A utility function that prints all nodes on the // path from root to target_leaf boolean printPath(Node node, Node target_leaf) { // base case if (node == null) return false; // return true if this node is the target_leaf or // target leaf is present in one of its descendants if (node == target_leaf || printPath(node.left, target_leaf) || printPath(node.right, target_leaf)) { System.out.print(node.data + " "); return true; } return false; } // This function Sets the target_leaf_ref to refer // the leaf node of the maximum path sum. Also, // returns the max_sum using max_sum_ref void getTargetLeaf(Node node, Maximum max_sum_ref, int curr_sum) { if (node == null) return; // Update current sum to hold sum of nodes on // path from root to this node curr_sum = curr_sum + node.data; // If this is a leaf node and path to this node // has maximum sum so far, the n make this node // target_leaf if (node.left == null && node.right == null) { if (curr_sum > max_sum_ref.max_no) { max_sum_ref.max_no = curr_sum; target_leaf = node; } } // If this is not a leaf node, then recur down // to find the target_leaf getTargetLeaf(node.left, max_sum_ref, curr_sum); getTargetLeaf(node.right, max_sum_ref, curr_sum); } // Returns the maximum sum and prints the nodes on // max sum path int maxSumPath() { // base case if (root == null) return 0; // find the target leaf and maximum sum getTargetLeaf(root, max, 0); // print the path from root to the target leaf printPath(root, target_leaf); return max.max_no; // return maximum sum } // driver function to test the above functions public static void main(String args[]) { BinaryTree tree = new BinaryTree(); tree.root = new Node(10); tree.root.left = new Node(-2); tree.root.right = new Node(7); tree.root.left.left = new Node(8); tree.root.left.right = new Node(-4); System.out.println("Following are the nodes " + "on maximum sum path"); int sum = tree.maxSumPath(); System.out.println(""); System.out.println("Sum of nodes is : " + sum); }}// This code has been contributed by Mayank Jaiswal
# Python3 program to find maximum sum leaf to root# path in Binary Tree # A tree node structure class node : def __init__(self): self.data = 0 self.left = None self.right = None # A utility function that prints all nodes# on the path from root to target_leafdef printPath( root,target_leaf): # base case if (root == None): return False # return True if this node is the target_leaf # or target leaf is present in one of its # descendants if (root == target_leaf or printPath(root.left, target_leaf) or printPath(root.right, target_leaf)) : print( root.data, end = " ") return True return False max_sum_ref = 0target_leaf_ref = None # This function Sets the target_leaf_ref to refer# the leaf node of the maximum path sum. Also,# returns the max_sum using max_sum_refdef getTargetLeaf(Node, curr_sum): global max_sum_ref global target_leaf_ref if (Node == None): return # Update current sum to hold sum of nodes on path # from root to this node curr_sum = curr_sum + Node.data # If this is a leaf node and path to this node has # maximum sum so far, then make this node target_leaf if (Node.left == None and Node.right == None): if (curr_sum > max_sum_ref) : max_sum_ref = curr_sum target_leaf_ref = Node # If this is not a leaf node, then recur down # to find the target_leaf getTargetLeaf(Node.left, curr_sum) getTargetLeaf(Node.right, curr_sum) # Returns the maximum sum and prints the nodes on max# sum pathdef maxSumPath( Node): global max_sum_ref global target_leaf_ref # base case if (Node == None): return 0 target_leaf_ref = None max_sum_ref = -32676 # find the target leaf and maximum sum getTargetLeaf(Node, 0) # print the path from root to the target leaf printPath(Node, target_leaf_ref); return max_sum_ref; # return maximum sum # Utility function to create a new Binary Tree node def newNode(data): temp = node(); temp.data = data; temp.left = None; temp.right = None; return temp; # Driver function to test above functions root = None; # Constructing tree given in the above figure root = newNode(10);root.left = newNode(-2);root.right = newNode(7);root.left.left = newNode(8);root.left.right = newNode(-4); print( "Following are the nodes on the maximum sum path ");sum = maxSumPath(root);print( "\nSum of the nodes is " , sum); # This code is contributed by Arnab Kundu
using System; // C# program to find maximum sum leaf to root// path in Binary Tree // A Binary Tree nodepublic class Node { public int data; public Node left, right; public Node(int item) { data = item; left = right = null; }} // A wrapper class is used so that max_no// can be updated among function calls.public class Maximum { public int max_no = int.MinValue;} public class BinaryTree { public Node root; public Maximum max = new Maximum(); public Node target_leaf = null; // A utility function that prints all nodes on the // path from root to target_leaf public virtual bool printPath(Node node, Node target_leaf) { // base case if (node == null) { return false; } // return true if this node is the target_leaf or // target leaf is present in one of its descendants if (node == target_leaf || printPath(node.left, target_leaf) || printPath(node.right, target_leaf)) { Console.Write(node.data + " "); return true; } return false; } // This function Sets the target_leaf_ref to refer // the leaf node of the maximum path sum. Also, // returns the max_sum using max_sum_ref public virtual void getTargetLeaf(Node node, Maximum max_sum_ref, int curr_sum) { if (node == null) { return; } // Update current sum to hold sum of nodes on // path from root to this node curr_sum = curr_sum + node.data; // If this is a leaf node and path to this node // has maximum sum so far, the n make this node // target_leaf if (node.left == null && node.right == null) { if (curr_sum > max_sum_ref.max_no) { max_sum_ref.max_no = curr_sum; target_leaf = node; } } // If this is not a leaf node, then recur down // to find the target_leaf getTargetLeaf(node.left, max_sum_ref, curr_sum); getTargetLeaf(node.right, max_sum_ref, curr_sum); } // Returns the maximum sum and prints the nodes on // max sum path public virtual int maxSumPath() { // base case if (root == null) { return 0; } // find the target leaf and maximum sum getTargetLeaf(root, max, 0); // print the path from root to the target leaf printPath(root, target_leaf); return max.max_no; // return maximum sum } // driver function to test the above functions public static void Main(string[] args) { BinaryTree tree = new BinaryTree(); tree.root = new Node(10); tree.root.left = new Node(-2); tree.root.right = new Node(7); tree.root.left.left = new Node(8); tree.root.left.right = new Node(-4); Console.WriteLine("Following are the nodes " + "on maximum sum path"); int sum = tree.maxSumPath(); Console.WriteLine(""); Console.WriteLine("Sum of nodes is : " + sum); }} // This code is contributed by Shrikant13
Following are the nodes on the maximum sum path
7 10
Sum of the nodes is 17
Time Complexity: Time complexity of the above solution is O(n) as it involves tree traversal two times.
Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
Subhrajyoti Choudhury
shrikanth13
rathbhupendra
andrew1234
Tree
Tree
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Binary Tree | Set 3 (Types of Binary Tree)
Inorder Tree Traversal without Recursion
Binary Tree | Set 2 (Properties)
Decision Tree
A program to check if a binary tree is BST or not
Construct Tree from given Inorder and Preorder traversals
Introduction to Tree Data Structure
Complexity of different operations in Binary tree, Binary Search Tree and AVL tree
Expression Tree
Lowest Common Ancestor in a Binary Tree | Set 1
|
[
{
"code": null,
"e": 26763,
"s": 26735,
"text": "\n19 Feb, 2020"
},
{
"code": null,
"e": 42442,
"s": 26763,
"text": "Given a Binary Tree, find the maximum sum path from a leaf to root. For example, in the following tree, there are three leaf to root paths 8->-2->10, -4->-2->10 and 7->10. The sums of these three paths are 16, 4 and 17 respectively. The maximum of them is 17 and the path for maximum is 7->10. 10\n / \\\n -2 7\n / \\ \n 8 -4 \nRecommended PracticeMaximum sum leaf to root pathTry It!Solution1) First find the leaf node that is on the maximum sum path. In the following code getTargetLeaf() does this by assigning the result to *target_leaf_ref.2) Once we have the target leaf node, we can print the maximum sum path by traversing the tree. In the following code, printPath() does this.The main function is maxSumPath() that uses above two functions to get the complete solution.C++CJavaPython3C#C++// CPP program to find maximum sum leaf to root// path in Binary Tree#include <bits/stdc++.h>using namespace std; /* A tree node structure */class node {public: int data; node* left; node* right;}; // A utility function that prints all nodes// on the path from root to target_leafbool printPath(node* root, node* target_leaf){ // base case if (root == NULL) return false; // return true if this node is the target_leaf // or target leaf is present in one of its // descendants if (root == target_leaf || printPath(root->left, target_leaf) || printPath(root->right, target_leaf)) { cout << root->data << \" \"; return true; } return false;} // This function Sets the target_leaf_ref to refer// the leaf node of the maximum path sum. Also,// returns the max_sum using max_sum_refvoid getTargetLeaf(node* Node, int* max_sum_ref, int curr_sum, node** target_leaf_ref){ if (Node == NULL) return; // Update current sum to hold sum of nodes on path // from root to this node curr_sum = curr_sum + Node->data; // If this is a leaf node and path to this node has // maximum sum so far, then make this node target_leaf if (Node->left == NULL && Node->right == NULL) { if (curr_sum > *max_sum_ref) { *max_sum_ref = curr_sum; *target_leaf_ref = Node; } } // If this is not a leaf node, then recur down // to find the target_leaf getTargetLeaf(Node->left, max_sum_ref, curr_sum, target_leaf_ref); getTargetLeaf(Node->right, max_sum_ref, curr_sum, target_leaf_ref);} // Returns the maximum sum and prints the nodes on max// sum pathint maxSumPath(node* Node){ // base case if (Node == NULL) return 0; node* target_leaf; int max_sum = INT_MIN; // find the target leaf and maximum sum getTargetLeaf(Node, &max_sum, 0, &target_leaf); // print the path from root to the target leaf printPath(Node, target_leaf); return max_sum; // return maximum sum} /* Utility function to create a new Binary Tree node */node* newNode(int data){ node* temp = new node; temp->data = data; temp->left = NULL; temp->right = NULL; return temp;} /* Driver function to test above functions */int main(){ node* root = NULL; /* Constructing tree given in the above figure */ root = newNode(10); root->left = newNode(-2); root->right = newNode(7); root->left->left = newNode(8); root->left->right = newNode(-4); cout << \"Following are the nodes on the maximum \" \"sum path \\n\"; int sum = maxSumPath(root); cout << \"\\nSum of the nodes is \" << sum; return 0;} // This code is contributed by rathbhupendraC// C program to find maximum sum leaf to root// path in Binary Tree#include <limits.h>#include <stdbool.h>#include <stdio.h>#include <stdlib.h> /* A tree node structure */struct node { int data; struct node* left; struct node* right;}; // A utility function that prints all nodes// on the path from root to target_leafbool printPath(struct node* root, struct node* target_leaf){ // base case if (root == NULL) return false; // return true if this node is the target_leaf // or target leaf is present in one of its // descendants if (root == target_leaf || printPath(root->left, target_leaf) || printPath(root->right, target_leaf)) { printf(\"%d \", root->data); return true; } return false;} // This function Sets the target_leaf_ref to refer// the leaf node of the maximum path sum. Also,// returns the max_sum using max_sum_refvoid getTargetLeaf(struct node* node, int* max_sum_ref, int curr_sum, struct node** target_leaf_ref){ if (node == NULL) return; // Update current sum to hold sum of nodes on path // from root to this node curr_sum = curr_sum + node->data; // If this is a leaf node and path to this node has // maximum sum so far, then make this node target_leaf if (node->left == NULL && node->right == NULL) { if (curr_sum > *max_sum_ref) { *max_sum_ref = curr_sum; *target_leaf_ref = node; } } // If this is not a leaf node, then recur down // to find the target_leaf getTargetLeaf(node->left, max_sum_ref, curr_sum, target_leaf_ref); getTargetLeaf(node->right, max_sum_ref, curr_sum, target_leaf_ref);} // Returns the maximum sum and prints the nodes on max// sum pathint maxSumPath(struct node* node){ // base case if (node == NULL) return 0; struct node* target_leaf; int max_sum = INT_MIN; // find the target leaf and maximum sum getTargetLeaf(node, &max_sum, 0, &target_leaf); // print the path from root to the target leaf printPath(node, target_leaf); return max_sum; // return maximum sum} /* Utility function to create a new Binary Tree node */struct node* newNode(int data){ struct node* temp = (struct node*)malloc(sizeof(struct node)); temp->data = data; temp->left = NULL; temp->right = NULL; return temp;} /* Driver function to test above functions */int main(){ struct node* root = NULL; /* Constructing tree given in the above figure */ root = newNode(10); root->left = newNode(-2); root->right = newNode(7); root->left->left = newNode(8); root->left->right = newNode(-4); printf(\"Following are the nodes on the maximum \" \"sum path \\n\"); int sum = maxSumPath(root); printf(\"\\nSum of the nodes is %d \", sum); getchar(); return 0;}Java// Java program to find maximum sum leaf to root// path in Binary Tree // A Binary Tree nodeclass Node { int data; Node left, right; Node(int item) { data = item; left = right = null; }} // A wrapper class is used so that max_no// can be updated among function calls.class Maximum { int max_no = Integer.MIN_VALUE;} class BinaryTree { Node root; Maximum max = new Maximum(); Node target_leaf = null; // A utility function that prints all nodes on the // path from root to target_leaf boolean printPath(Node node, Node target_leaf) { // base case if (node == null) return false; // return true if this node is the target_leaf or // target leaf is present in one of its descendants if (node == target_leaf || printPath(node.left, target_leaf) || printPath(node.right, target_leaf)) { System.out.print(node.data + \" \"); return true; } return false; } // This function Sets the target_leaf_ref to refer // the leaf node of the maximum path sum. Also, // returns the max_sum using max_sum_ref void getTargetLeaf(Node node, Maximum max_sum_ref, int curr_sum) { if (node == null) return; // Update current sum to hold sum of nodes on // path from root to this node curr_sum = curr_sum + node.data; // If this is a leaf node and path to this node // has maximum sum so far, the n make this node // target_leaf if (node.left == null && node.right == null) { if (curr_sum > max_sum_ref.max_no) { max_sum_ref.max_no = curr_sum; target_leaf = node; } } // If this is not a leaf node, then recur down // to find the target_leaf getTargetLeaf(node.left, max_sum_ref, curr_sum); getTargetLeaf(node.right, max_sum_ref, curr_sum); } // Returns the maximum sum and prints the nodes on // max sum path int maxSumPath() { // base case if (root == null) return 0; // find the target leaf and maximum sum getTargetLeaf(root, max, 0); // print the path from root to the target leaf printPath(root, target_leaf); return max.max_no; // return maximum sum } // driver function to test the above functions public static void main(String args[]) { BinaryTree tree = new BinaryTree(); tree.root = new Node(10); tree.root.left = new Node(-2); tree.root.right = new Node(7); tree.root.left.left = new Node(8); tree.root.left.right = new Node(-4); System.out.println(\"Following are the nodes \" + \"on maximum sum path\"); int sum = tree.maxSumPath(); System.out.println(\"\"); System.out.println(\"Sum of nodes is : \" + sum); }}// This code has been contributed by Mayank JaiswalPython3# Python3 program to find maximum sum leaf to root# path in Binary Tree # A tree node structure class node : def __init__(self): self.data = 0 self.left = None self.right = None # A utility function that prints all nodes# on the path from root to target_leafdef printPath( root,target_leaf): # base case if (root == None): return False # return True if this node is the target_leaf # or target leaf is present in one of its # descendants if (root == target_leaf or printPath(root.left, target_leaf) or printPath(root.right, target_leaf)) : print( root.data, end = \" \") return True return False max_sum_ref = 0target_leaf_ref = None # This function Sets the target_leaf_ref to refer# the leaf node of the maximum path sum. Also,# returns the max_sum using max_sum_refdef getTargetLeaf(Node, curr_sum): global max_sum_ref global target_leaf_ref if (Node == None): return # Update current sum to hold sum of nodes on path # from root to this node curr_sum = curr_sum + Node.data # If this is a leaf node and path to this node has # maximum sum so far, then make this node target_leaf if (Node.left == None and Node.right == None): if (curr_sum > max_sum_ref) : max_sum_ref = curr_sum target_leaf_ref = Node # If this is not a leaf node, then recur down # to find the target_leaf getTargetLeaf(Node.left, curr_sum) getTargetLeaf(Node.right, curr_sum) # Returns the maximum sum and prints the nodes on max# sum pathdef maxSumPath( Node): global max_sum_ref global target_leaf_ref # base case if (Node == None): return 0 target_leaf_ref = None max_sum_ref = -32676 # find the target leaf and maximum sum getTargetLeaf(Node, 0) # print the path from root to the target leaf printPath(Node, target_leaf_ref); return max_sum_ref; # return maximum sum # Utility function to create a new Binary Tree node def newNode(data): temp = node(); temp.data = data; temp.left = None; temp.right = None; return temp; # Driver function to test above functions root = None; # Constructing tree given in the above figure root = newNode(10);root.left = newNode(-2);root.right = newNode(7);root.left.left = newNode(8);root.left.right = newNode(-4); print( \"Following are the nodes on the maximum sum path \");sum = maxSumPath(root);print( \"\\nSum of the nodes is \" , sum); # This code is contributed by Arnab Kundu C#using System; // C# program to find maximum sum leaf to root// path in Binary Tree // A Binary Tree nodepublic class Node { public int data; public Node left, right; public Node(int item) { data = item; left = right = null; }} // A wrapper class is used so that max_no// can be updated among function calls.public class Maximum { public int max_no = int.MinValue;} public class BinaryTree { public Node root; public Maximum max = new Maximum(); public Node target_leaf = null; // A utility function that prints all nodes on the // path from root to target_leaf public virtual bool printPath(Node node, Node target_leaf) { // base case if (node == null) { return false; } // return true if this node is the target_leaf or // target leaf is present in one of its descendants if (node == target_leaf || printPath(node.left, target_leaf) || printPath(node.right, target_leaf)) { Console.Write(node.data + \" \"); return true; } return false; } // This function Sets the target_leaf_ref to refer // the leaf node of the maximum path sum. Also, // returns the max_sum using max_sum_ref public virtual void getTargetLeaf(Node node, Maximum max_sum_ref, int curr_sum) { if (node == null) { return; } // Update current sum to hold sum of nodes on // path from root to this node curr_sum = curr_sum + node.data; // If this is a leaf node and path to this node // has maximum sum so far, the n make this node // target_leaf if (node.left == null && node.right == null) { if (curr_sum > max_sum_ref.max_no) { max_sum_ref.max_no = curr_sum; target_leaf = node; } } // If this is not a leaf node, then recur down // to find the target_leaf getTargetLeaf(node.left, max_sum_ref, curr_sum); getTargetLeaf(node.right, max_sum_ref, curr_sum); } // Returns the maximum sum and prints the nodes on // max sum path public virtual int maxSumPath() { // base case if (root == null) { return 0; } // find the target leaf and maximum sum getTargetLeaf(root, max, 0); // print the path from root to the target leaf printPath(root, target_leaf); return max.max_no; // return maximum sum } // driver function to test the above functions public static void Main(string[] args) { BinaryTree tree = new BinaryTree(); tree.root = new Node(10); tree.root.left = new Node(-2); tree.root.right = new Node(7); tree.root.left.left = new Node(8); tree.root.left.right = new Node(-4); Console.WriteLine(\"Following are the nodes \" + \"on maximum sum path\"); int sum = tree.maxSumPath(); Console.WriteLine(\"\"); Console.WriteLine(\"Sum of nodes is : \" + sum); }} // This code is contributed by Shrikant13Output:Following are the nodes on the maximum sum path\n7 10\nSum of the nodes is 17\nTime Complexity: Time complexity of the above solution is O(n) as it involves tree traversal two times.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.My Personal Notes\narrow_drop_upSave"
},
{
"code": null,
"e": 42558,
"s": 42442,
"text": " 10\n / \\\n -2 7\n / \\ \n 8 -4 \n"
},
{
"code": null,
"e": 42861,
"s": 42558,
"text": "Solution1) First find the leaf node that is on the maximum sum path. In the following code getTargetLeaf() does this by assigning the result to *target_leaf_ref.2) Once we have the target leaf node, we can print the maximum sum path by traversing the tree. In the following code, printPath() does this."
},
{
"code": null,
"e": 42955,
"s": 42861,
"text": "The main function is maxSumPath() that uses above two functions to get the complete solution."
},
{
"code": null,
"e": 42959,
"s": 42955,
"text": "C++"
},
{
"code": null,
"e": 42961,
"s": 42959,
"text": "C"
},
{
"code": null,
"e": 42966,
"s": 42961,
"text": "Java"
},
{
"code": null,
"e": 42974,
"s": 42966,
"text": "Python3"
},
{
"code": null,
"e": 42977,
"s": 42974,
"text": "C#"
},
{
"code": "// CPP program to find maximum sum leaf to root// path in Binary Tree#include <bits/stdc++.h>using namespace std; /* A tree node structure */class node {public: int data; node* left; node* right;}; // A utility function that prints all nodes// on the path from root to target_leafbool printPath(node* root, node* target_leaf){ // base case if (root == NULL) return false; // return true if this node is the target_leaf // or target leaf is present in one of its // descendants if (root == target_leaf || printPath(root->left, target_leaf) || printPath(root->right, target_leaf)) { cout << root->data << \" \"; return true; } return false;} // This function Sets the target_leaf_ref to refer// the leaf node of the maximum path sum. Also,// returns the max_sum using max_sum_refvoid getTargetLeaf(node* Node, int* max_sum_ref, int curr_sum, node** target_leaf_ref){ if (Node == NULL) return; // Update current sum to hold sum of nodes on path // from root to this node curr_sum = curr_sum + Node->data; // If this is a leaf node and path to this node has // maximum sum so far, then make this node target_leaf if (Node->left == NULL && Node->right == NULL) { if (curr_sum > *max_sum_ref) { *max_sum_ref = curr_sum; *target_leaf_ref = Node; } } // If this is not a leaf node, then recur down // to find the target_leaf getTargetLeaf(Node->left, max_sum_ref, curr_sum, target_leaf_ref); getTargetLeaf(Node->right, max_sum_ref, curr_sum, target_leaf_ref);} // Returns the maximum sum and prints the nodes on max// sum pathint maxSumPath(node* Node){ // base case if (Node == NULL) return 0; node* target_leaf; int max_sum = INT_MIN; // find the target leaf and maximum sum getTargetLeaf(Node, &max_sum, 0, &target_leaf); // print the path from root to the target leaf printPath(Node, target_leaf); return max_sum; // return maximum sum} /* Utility function to create a new Binary Tree node */node* newNode(int data){ node* temp = new node; temp->data = data; temp->left = NULL; temp->right = NULL; return temp;} /* Driver function to test above functions */int main(){ node* root = NULL; /* Constructing tree given in the above figure */ root = newNode(10); root->left = newNode(-2); root->right = newNode(7); root->left->left = newNode(8); root->left->right = newNode(-4); cout << \"Following are the nodes on the maximum \" \"sum path \\n\"; int sum = maxSumPath(root); cout << \"\\nSum of the nodes is \" << sum; return 0;} // This code is contributed by rathbhupendra",
"e": 45787,
"s": 42977,
"text": null
},
{
"code": "// C program to find maximum sum leaf to root// path in Binary Tree#include <limits.h>#include <stdbool.h>#include <stdio.h>#include <stdlib.h> /* A tree node structure */struct node { int data; struct node* left; struct node* right;}; // A utility function that prints all nodes// on the path from root to target_leafbool printPath(struct node* root, struct node* target_leaf){ // base case if (root == NULL) return false; // return true if this node is the target_leaf // or target leaf is present in one of its // descendants if (root == target_leaf || printPath(root->left, target_leaf) || printPath(root->right, target_leaf)) { printf(\"%d \", root->data); return true; } return false;} // This function Sets the target_leaf_ref to refer// the leaf node of the maximum path sum. Also,// returns the max_sum using max_sum_refvoid getTargetLeaf(struct node* node, int* max_sum_ref, int curr_sum, struct node** target_leaf_ref){ if (node == NULL) return; // Update current sum to hold sum of nodes on path // from root to this node curr_sum = curr_sum + node->data; // If this is a leaf node and path to this node has // maximum sum so far, then make this node target_leaf if (node->left == NULL && node->right == NULL) { if (curr_sum > *max_sum_ref) { *max_sum_ref = curr_sum; *target_leaf_ref = node; } } // If this is not a leaf node, then recur down // to find the target_leaf getTargetLeaf(node->left, max_sum_ref, curr_sum, target_leaf_ref); getTargetLeaf(node->right, max_sum_ref, curr_sum, target_leaf_ref);} // Returns the maximum sum and prints the nodes on max// sum pathint maxSumPath(struct node* node){ // base case if (node == NULL) return 0; struct node* target_leaf; int max_sum = INT_MIN; // find the target leaf and maximum sum getTargetLeaf(node, &max_sum, 0, &target_leaf); // print the path from root to the target leaf printPath(node, target_leaf); return max_sum; // return maximum sum} /* Utility function to create a new Binary Tree node */struct node* newNode(int data){ struct node* temp = (struct node*)malloc(sizeof(struct node)); temp->data = data; temp->left = NULL; temp->right = NULL; return temp;} /* Driver function to test above functions */int main(){ struct node* root = NULL; /* Constructing tree given in the above figure */ root = newNode(10); root->left = newNode(-2); root->right = newNode(7); root->left->left = newNode(8); root->left->right = newNode(-4); printf(\"Following are the nodes on the maximum \" \"sum path \\n\"); int sum = maxSumPath(root); printf(\"\\nSum of the nodes is %d \", sum); getchar(); return 0;}",
"e": 48701,
"s": 45787,
"text": null
},
{
"code": "// Java program to find maximum sum leaf to root// path in Binary Tree // A Binary Tree nodeclass Node { int data; Node left, right; Node(int item) { data = item; left = right = null; }} // A wrapper class is used so that max_no// can be updated among function calls.class Maximum { int max_no = Integer.MIN_VALUE;} class BinaryTree { Node root; Maximum max = new Maximum(); Node target_leaf = null; // A utility function that prints all nodes on the // path from root to target_leaf boolean printPath(Node node, Node target_leaf) { // base case if (node == null) return false; // return true if this node is the target_leaf or // target leaf is present in one of its descendants if (node == target_leaf || printPath(node.left, target_leaf) || printPath(node.right, target_leaf)) { System.out.print(node.data + \" \"); return true; } return false; } // This function Sets the target_leaf_ref to refer // the leaf node of the maximum path sum. Also, // returns the max_sum using max_sum_ref void getTargetLeaf(Node node, Maximum max_sum_ref, int curr_sum) { if (node == null) return; // Update current sum to hold sum of nodes on // path from root to this node curr_sum = curr_sum + node.data; // If this is a leaf node and path to this node // has maximum sum so far, the n make this node // target_leaf if (node.left == null && node.right == null) { if (curr_sum > max_sum_ref.max_no) { max_sum_ref.max_no = curr_sum; target_leaf = node; } } // If this is not a leaf node, then recur down // to find the target_leaf getTargetLeaf(node.left, max_sum_ref, curr_sum); getTargetLeaf(node.right, max_sum_ref, curr_sum); } // Returns the maximum sum and prints the nodes on // max sum path int maxSumPath() { // base case if (root == null) return 0; // find the target leaf and maximum sum getTargetLeaf(root, max, 0); // print the path from root to the target leaf printPath(root, target_leaf); return max.max_no; // return maximum sum } // driver function to test the above functions public static void main(String args[]) { BinaryTree tree = new BinaryTree(); tree.root = new Node(10); tree.root.left = new Node(-2); tree.root.right = new Node(7); tree.root.left.left = new Node(8); tree.root.left.right = new Node(-4); System.out.println(\"Following are the nodes \" + \"on maximum sum path\"); int sum = tree.maxSumPath(); System.out.println(\"\"); System.out.println(\"Sum of nodes is : \" + sum); }}// This code has been contributed by Mayank Jaiswal",
"e": 51697,
"s": 48701,
"text": null
},
{
"code": "# Python3 program to find maximum sum leaf to root# path in Binary Tree # A tree node structure class node : def __init__(self): self.data = 0 self.left = None self.right = None # A utility function that prints all nodes# on the path from root to target_leafdef printPath( root,target_leaf): # base case if (root == None): return False # return True if this node is the target_leaf # or target leaf is present in one of its # descendants if (root == target_leaf or printPath(root.left, target_leaf) or printPath(root.right, target_leaf)) : print( root.data, end = \" \") return True return False max_sum_ref = 0target_leaf_ref = None # This function Sets the target_leaf_ref to refer# the leaf node of the maximum path sum. Also,# returns the max_sum using max_sum_refdef getTargetLeaf(Node, curr_sum): global max_sum_ref global target_leaf_ref if (Node == None): return # Update current sum to hold sum of nodes on path # from root to this node curr_sum = curr_sum + Node.data # If this is a leaf node and path to this node has # maximum sum so far, then make this node target_leaf if (Node.left == None and Node.right == None): if (curr_sum > max_sum_ref) : max_sum_ref = curr_sum target_leaf_ref = Node # If this is not a leaf node, then recur down # to find the target_leaf getTargetLeaf(Node.left, curr_sum) getTargetLeaf(Node.right, curr_sum) # Returns the maximum sum and prints the nodes on max# sum pathdef maxSumPath( Node): global max_sum_ref global target_leaf_ref # base case if (Node == None): return 0 target_leaf_ref = None max_sum_ref = -32676 # find the target leaf and maximum sum getTargetLeaf(Node, 0) # print the path from root to the target leaf printPath(Node, target_leaf_ref); return max_sum_ref; # return maximum sum # Utility function to create a new Binary Tree node def newNode(data): temp = node(); temp.data = data; temp.left = None; temp.right = None; return temp; # Driver function to test above functions root = None; # Constructing tree given in the above figure root = newNode(10);root.left = newNode(-2);root.right = newNode(7);root.left.left = newNode(8);root.left.right = newNode(-4); print( \"Following are the nodes on the maximum sum path \");sum = maxSumPath(root);print( \"\\nSum of the nodes is \" , sum); # This code is contributed by Arnab Kundu ",
"e": 54273,
"s": 51697,
"text": null
},
{
"code": "using System; // C# program to find maximum sum leaf to root// path in Binary Tree // A Binary Tree nodepublic class Node { public int data; public Node left, right; public Node(int item) { data = item; left = right = null; }} // A wrapper class is used so that max_no// can be updated among function calls.public class Maximum { public int max_no = int.MinValue;} public class BinaryTree { public Node root; public Maximum max = new Maximum(); public Node target_leaf = null; // A utility function that prints all nodes on the // path from root to target_leaf public virtual bool printPath(Node node, Node target_leaf) { // base case if (node == null) { return false; } // return true if this node is the target_leaf or // target leaf is present in one of its descendants if (node == target_leaf || printPath(node.left, target_leaf) || printPath(node.right, target_leaf)) { Console.Write(node.data + \" \"); return true; } return false; } // This function Sets the target_leaf_ref to refer // the leaf node of the maximum path sum. Also, // returns the max_sum using max_sum_ref public virtual void getTargetLeaf(Node node, Maximum max_sum_ref, int curr_sum) { if (node == null) { return; } // Update current sum to hold sum of nodes on // path from root to this node curr_sum = curr_sum + node.data; // If this is a leaf node and path to this node // has maximum sum so far, the n make this node // target_leaf if (node.left == null && node.right == null) { if (curr_sum > max_sum_ref.max_no) { max_sum_ref.max_no = curr_sum; target_leaf = node; } } // If this is not a leaf node, then recur down // to find the target_leaf getTargetLeaf(node.left, max_sum_ref, curr_sum); getTargetLeaf(node.right, max_sum_ref, curr_sum); } // Returns the maximum sum and prints the nodes on // max sum path public virtual int maxSumPath() { // base case if (root == null) { return 0; } // find the target leaf and maximum sum getTargetLeaf(root, max, 0); // print the path from root to the target leaf printPath(root, target_leaf); return max.max_no; // return maximum sum } // driver function to test the above functions public static void Main(string[] args) { BinaryTree tree = new BinaryTree(); tree.root = new Node(10); tree.root.left = new Node(-2); tree.root.right = new Node(7); tree.root.left.left = new Node(8); tree.root.left.right = new Node(-4); Console.WriteLine(\"Following are the nodes \" + \"on maximum sum path\"); int sum = tree.maxSumPath(); Console.WriteLine(\"\"); Console.WriteLine(\"Sum of nodes is : \" + sum); }} // This code is contributed by Shrikant13",
"e": 57422,
"s": 54273,
"text": null
},
{
"code": null,
"e": 57499,
"s": 57422,
"text": "Following are the nodes on the maximum sum path\n7 10\nSum of the nodes is 17\n"
},
{
"code": null,
"e": 57603,
"s": 57499,
"text": "Time Complexity: Time complexity of the above solution is O(n) as it involves tree traversal two times."
},
{
"code": null,
"e": 57728,
"s": 57603,
"text": "Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above."
},
{
"code": null,
"e": 57750,
"s": 57728,
"text": "Subhrajyoti Choudhury"
},
{
"code": null,
"e": 57762,
"s": 57750,
"text": "shrikanth13"
},
{
"code": null,
"e": 57776,
"s": 57762,
"text": "rathbhupendra"
},
{
"code": null,
"e": 57787,
"s": 57776,
"text": "andrew1234"
},
{
"code": null,
"e": 57792,
"s": 57787,
"text": "Tree"
},
{
"code": null,
"e": 57797,
"s": 57792,
"text": "Tree"
},
{
"code": null,
"e": 57895,
"s": 57797,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 57938,
"s": 57895,
"text": "Binary Tree | Set 3 (Types of Binary Tree)"
},
{
"code": null,
"e": 57979,
"s": 57938,
"text": "Inorder Tree Traversal without Recursion"
},
{
"code": null,
"e": 58012,
"s": 57979,
"text": "Binary Tree | Set 2 (Properties)"
},
{
"code": null,
"e": 58026,
"s": 58012,
"text": "Decision Tree"
},
{
"code": null,
"e": 58076,
"s": 58026,
"text": "A program to check if a binary tree is BST or not"
},
{
"code": null,
"e": 58134,
"s": 58076,
"text": "Construct Tree from given Inorder and Preorder traversals"
},
{
"code": null,
"e": 58170,
"s": 58134,
"text": "Introduction to Tree Data Structure"
},
{
"code": null,
"e": 58253,
"s": 58170,
"text": "Complexity of different operations in Binary tree, Binary Search Tree and AVL tree"
},
{
"code": null,
"e": 58269,
"s": 58253,
"text": "Expression Tree"
}
] |
How to detect the duplication of values of input fields ? - GeeksforGeeks
|
08 Jun, 2020
Suppose you are making a registration form in which you are taking phone numbers of users. Now, You want to ask the user for four alternative contact numbers. You want to make sure that all four contact numbers given by users should be different.
This functionality can be implemented in two ways :
At the time of input before submitting form: For this, we can use “oninput” event provided by HTML itself which triggers the function specified in javascript whenever input changes in input fieldAfter submitting form: For this, we can use “onsubmit” or “onclick” event which is also provided by HTML and they work on Buttons. “onclick” event will work for buttons while “onsubmit” event will work for forms
At the time of input before submitting form: For this, we can use “oninput” event provided by HTML itself which triggers the function specified in javascript whenever input changes in input field
After submitting form: For this, we can use “onsubmit” or “onclick” event which is also provided by HTML and they work on Buttons. “onclick” event will work for buttons while “onsubmit” event will work for forms
Below examples illustrate the both approaches:
Example 1:
HTML
<!DOCTYPE html><html> <head> <script> function gfg_check_duplicates() { var myarray = []; for (i = 0; i < 4; i++) { myarray[i] = document.getElementById("gfg_field" + i).value; } for (i = 0; i < 4; i++) { for (j = i + 1; j < 4; j++) { if (i == j || myarray[i] == "" || myarray[j] == "") continue; if (myarray[i] == myarray[j]) { document.getElementById("status" + i) .innerHTML = "duplicated values!"; document.getElementById("status" + j) .innerHTML = "duplicated values!"; } } } } </script> </head> <body> Ph no1: <input id="gfg_field0" oninput="gfg_check_duplicates()" /> <div id="status0"></div> <br /> Ph no2: <input id="gfg_field1" oninput="gfg_check_duplicates()" /> <div id="status1"></div> <br /> Ph no3: <input id="gfg_field2" oninput="gfg_check_duplicates()" /> <div id="status2"></div> <br /> Ph no4: <input id="gfg_field3" oninput="gfg_check_duplicates()" /> <div id="status3"></div> <br /> </body></html>
Output:
Example 2: In this example, we will show which of the values are same and works dynamically as we change input.
HTML
<!DOCTYPE html><html> <head> <script> function gfg_check_duplicates() { var myarray = []; for (i = 0; i < 4; i++) { document.getElementById("status" + i).innerHTML = ""; myarray[i] = document.getElementById("gfg_field" + i).value; } for (i = 0; i < 4; i++) { var flag = false; for (j = 0; j < 4; j++) { if (i == j || myarray[i] == "" || myarray[j] == "") continue; if (myarray[i] == myarray[j]) { flag = true; document.getElementById("status" + i).innerHTML += "<br>Its identical to the phone number " + (j + 1); } } if (flag == false) document.getElementById("status" + i).innerHTML = ""; } } </script> </head> <body> <h4>Phone no. 1</h4> <input id="gfg_field0" oninput="gfg_check_duplicates()" /> <div id="status0"></div> <h4>Phone no. 2</h4> <input id="gfg_field1" oninput="gfg_check_duplicates()" /> <div id="status1"></div> <h4>Phone no. 3</h4> <input id="gfg_field2" oninput="gfg_check_duplicates()" /> <div id="status2"></div> <h4>Phone no. 4</h4> <input id="gfg_field3" oninput="gfg_check_duplicates()" /> <div id="status3"></div> <br /> </body></html>
Output:
HTML
<!DOCTYPE html><html> <head> <script> function gfg_check_duplicates() { var myarray = []; for (i = 0; i < 4; i++) { document.getElementById("status" + i).innerHTML = ""; myarray[i] = document.getElementById("gfg_field" + i).value; } for (i = 0; i < 4; i++) { var flag = false; for (j = 0; j < 4; j++) { if (i == j || myarray[i] == "" || myarray[j] == "") continue; if (myarray[i] == myarray[j]) { flag = true; document.getElementById("status" + i).innerHTML += "<br>Its identical to the phone number " + (j + 1); } } if (flag == false) document.getElementById("status" + i).innerHTML = ""; } } </script> </head> <body> <h4>Phone no. 1</h4> <input id="gfg_field0" /> <div id="status0"></div> <h4>Phone no. 2</h4> <input id="gfg_field1" /> <div id="status1"></div> <h4>Phone no. 3</h4> <input id="gfg_field2" /> <div id="status2"></div> <h4>Phone no. 4</h4> <input id="gfg_field3" /> <div id="status3"></div> <br> <button type="submit" onclick="gfg_check_duplicates()"> Check for Duplicates ! </button> </body></html>
Output:
javascript-array
Picked
JavaScript
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Remove elements from a JavaScript Array
Difference between var, let and const keywords in JavaScript
Difference Between PUT and PATCH Request
JavaScript | Promises
How to get character array from string in JavaScript?
How to filter object array based on attributes?
Lodash _.debounce() Method
Angular File Upload
How to remove duplicate elements from JavaScript Array ?
How to get selected value in dropdown list using JavaScript ?
|
[
{
"code": null,
"e": 26653,
"s": 26625,
"text": "\n08 Jun, 2020"
},
{
"code": null,
"e": 26901,
"s": 26653,
"text": "Suppose you are making a registration form in which you are taking phone numbers of users. Now, You want to ask the user for four alternative contact numbers. You want to make sure that all four contact numbers given by users should be different. "
},
{
"code": null,
"e": 26953,
"s": 26901,
"text": "This functionality can be implemented in two ways :"
},
{
"code": null,
"e": 27362,
"s": 26953,
"text": "At the time of input before submitting form: For this, we can use “oninput” event provided by HTML itself which triggers the function specified in javascript whenever input changes in input fieldAfter submitting form: For this, we can use “onsubmit” or “onclick” event which is also provided by HTML and they work on Buttons. “onclick” event will work for buttons while “onsubmit” event will work for forms "
},
{
"code": null,
"e": 27558,
"s": 27362,
"text": "At the time of input before submitting form: For this, we can use “oninput” event provided by HTML itself which triggers the function specified in javascript whenever input changes in input field"
},
{
"code": null,
"e": 27772,
"s": 27558,
"text": "After submitting form: For this, we can use “onsubmit” or “onclick” event which is also provided by HTML and they work on Buttons. “onclick” event will work for buttons while “onsubmit” event will work for forms "
},
{
"code": null,
"e": 27819,
"s": 27772,
"text": "Below examples illustrate the both approaches:"
},
{
"code": null,
"e": 27830,
"s": 27819,
"text": "Example 1:"
},
{
"code": null,
"e": 27835,
"s": 27830,
"text": "HTML"
},
{
"code": "<!DOCTYPE html><html> <head> <script> function gfg_check_duplicates() { var myarray = []; for (i = 0; i < 4; i++) { myarray[i] = document.getElementById(\"gfg_field\" + i).value; } for (i = 0; i < 4; i++) { for (j = i + 1; j < 4; j++) { if (i == j || myarray[i] == \"\" || myarray[j] == \"\") continue; if (myarray[i] == myarray[j]) { document.getElementById(\"status\" + i) .innerHTML = \"duplicated values!\"; document.getElementById(\"status\" + j) .innerHTML = \"duplicated values!\"; } } } } </script> </head> <body> Ph no1: <input id=\"gfg_field0\" oninput=\"gfg_check_duplicates()\" /> <div id=\"status0\"></div> <br /> Ph no2: <input id=\"gfg_field1\" oninput=\"gfg_check_duplicates()\" /> <div id=\"status1\"></div> <br /> Ph no3: <input id=\"gfg_field2\" oninput=\"gfg_check_duplicates()\" /> <div id=\"status2\"></div> <br /> Ph no4: <input id=\"gfg_field3\" oninput=\"gfg_check_duplicates()\" /> <div id=\"status3\"></div> <br /> </body></html>",
"e": 29210,
"s": 27835,
"text": null
},
{
"code": null,
"e": 29219,
"s": 29210,
"text": "Output: "
},
{
"code": null,
"e": 29331,
"s": 29219,
"text": "Example 2: In this example, we will show which of the values are same and works dynamically as we change input."
},
{
"code": null,
"e": 29336,
"s": 29331,
"text": "HTML"
},
{
"code": "<!DOCTYPE html><html> <head> <script> function gfg_check_duplicates() { var myarray = []; for (i = 0; i < 4; i++) { document.getElementById(\"status\" + i).innerHTML = \"\"; myarray[i] = document.getElementById(\"gfg_field\" + i).value; } for (i = 0; i < 4; i++) { var flag = false; for (j = 0; j < 4; j++) { if (i == j || myarray[i] == \"\" || myarray[j] == \"\") continue; if (myarray[i] == myarray[j]) { flag = true; document.getElementById(\"status\" + i).innerHTML += \"<br>Its identical to the phone number \" + (j + 1); } } if (flag == false) document.getElementById(\"status\" + i).innerHTML = \"\"; } } </script> </head> <body> <h4>Phone no. 1</h4> <input id=\"gfg_field0\" oninput=\"gfg_check_duplicates()\" /> <div id=\"status0\"></div> <h4>Phone no. 2</h4> <input id=\"gfg_field1\" oninput=\"gfg_check_duplicates()\" /> <div id=\"status1\"></div> <h4>Phone no. 3</h4> <input id=\"gfg_field2\" oninput=\"gfg_check_duplicates()\" /> <div id=\"status2\"></div> <h4>Phone no. 4</h4> <input id=\"gfg_field3\" oninput=\"gfg_check_duplicates()\" /> <div id=\"status3\"></div> <br /> </body></html>",
"e": 30773,
"s": 29336,
"text": null
},
{
"code": null,
"e": 30781,
"s": 30773,
"text": "Output:"
},
{
"code": null,
"e": 30786,
"s": 30781,
"text": "HTML"
},
{
"code": "<!DOCTYPE html><html> <head> <script> function gfg_check_duplicates() { var myarray = []; for (i = 0; i < 4; i++) { document.getElementById(\"status\" + i).innerHTML = \"\"; myarray[i] = document.getElementById(\"gfg_field\" + i).value; } for (i = 0; i < 4; i++) { var flag = false; for (j = 0; j < 4; j++) { if (i == j || myarray[i] == \"\" || myarray[j] == \"\") continue; if (myarray[i] == myarray[j]) { flag = true; document.getElementById(\"status\" + i).innerHTML += \"<br>Its identical to the phone number \" + (j + 1); } } if (flag == false) document.getElementById(\"status\" + i).innerHTML = \"\"; } } </script> </head> <body> <h4>Phone no. 1</h4> <input id=\"gfg_field0\" /> <div id=\"status0\"></div> <h4>Phone no. 2</h4> <input id=\"gfg_field1\" /> <div id=\"status1\"></div> <h4>Phone no. 3</h4> <input id=\"gfg_field2\" /> <div id=\"status2\"></div> <h4>Phone no. 4</h4> <input id=\"gfg_field3\" /> <div id=\"status3\"></div> <br> <button type=\"submit\" onclick=\"gfg_check_duplicates()\"> Check for Duplicates ! </button> </body></html>",
"e": 32185,
"s": 30786,
"text": null
},
{
"code": null,
"e": 32193,
"s": 32185,
"text": "Output:"
},
{
"code": null,
"e": 32210,
"s": 32193,
"text": "javascript-array"
},
{
"code": null,
"e": 32217,
"s": 32210,
"text": "Picked"
},
{
"code": null,
"e": 32228,
"s": 32217,
"text": "JavaScript"
},
{
"code": null,
"e": 32326,
"s": 32228,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 32366,
"s": 32326,
"text": "Remove elements from a JavaScript Array"
},
{
"code": null,
"e": 32427,
"s": 32366,
"text": "Difference between var, let and const keywords in JavaScript"
},
{
"code": null,
"e": 32468,
"s": 32427,
"text": "Difference Between PUT and PATCH Request"
},
{
"code": null,
"e": 32490,
"s": 32468,
"text": "JavaScript | Promises"
},
{
"code": null,
"e": 32544,
"s": 32490,
"text": "How to get character array from string in JavaScript?"
},
{
"code": null,
"e": 32592,
"s": 32544,
"text": "How to filter object array based on attributes?"
},
{
"code": null,
"e": 32619,
"s": 32592,
"text": "Lodash _.debounce() Method"
},
{
"code": null,
"e": 32639,
"s": 32619,
"text": "Angular File Upload"
},
{
"code": null,
"e": 32696,
"s": 32639,
"text": "How to remove duplicate elements from JavaScript Array ?"
}
] |
Fetch unique records from table in SAP ABAP
|
As you said you are working in ABAP and SQL, so I would expect that you would be using OpenSQL for your SQL activities.
You can get the unique records just by using a DISTINCT operator.
SELECT DISTINCT Name from <Table name> where <clause>
|
[
{
"code": null,
"e": 1182,
"s": 1062,
"text": "As you said you are working in ABAP and SQL, so I would expect that you would be using OpenSQL for your SQL activities."
},
{
"code": null,
"e": 1248,
"s": 1182,
"text": "You can get the unique records just by using a DISTINCT operator."
},
{
"code": null,
"e": 1302,
"s": 1248,
"text": "SELECT DISTINCT Name from <Table name> where <clause>"
}
] |
CSS | 3D Transforms - GeeksforGeeks
|
04 Jun, 2020
It allows to change elements using 3D transformations. In 3D transformation, the elements are rotated along X-axis, Y-axis and Z-axis.
There are three main types of transformation which are listed below:
rotateX()
rotateY()
rotateZ()
The rotateX() Method: This rotation is used to rotate an elements around X-axis at a given degree.Example:
<!DOCTYPE html><html> <head> <title>3D Transformation</title> <style> .normal_div { width: 300px; height: 150px; color: white; font-size:25px; background-color: green; border: 1px solid black; margin-bottom:20px; } #rotateX { width: 300px; height: 150px; color: white; font-size:25px; background-color: green; border: 1px solid black; -webkit-transform: rotateX(180deg); /* Safari */ transform: rotateX(180deg); /* Standard syntax */ } .gfg { font-size:40px; font-weight:bold; color:#090; } .geeks { font-size:25px; font-weight:bold; margin:20px 0; } </style> </head> <body> <center> <div class = "gfg">GeeksforGeeks</div> <div class = "geeks">rotateX() Method</div> <div class = "normal_div"> Div Contents... </div> <div id="rotateX">180 degree rotated contents...</div> </center> </body></html>
Output:
The rotateY() Method: This method is used to rotate an element around Y-axis at given degrees.Example:
<!DOCTYPE html><html> <head> <title>3D Transformation</title> <style> .normal_div { width: 200px; color:white; font-size:25px; height: 100px; background-color: green; border: 1px solid black; margin-bottom:20px; } #rotateY { width: 200px; color:white; font-size:25px; height: 100px; background-color: green; border: 1px solid black; -webkit-transform: rotateY(180deg); /* Safari */ transform: rotateY(100deg); /* Standard syntax */ } .gfg { font-size:40px; font-weight:bold; color:#090; } .geeks { font-size:25px; font-weight:bold; margin:20px 0; } </style> </head> <body> <center> <div class = "gfg">GeeksforGeeks</div> <div class = "geeks">rotateY() Method</div> <div class = "normal_div"> Div Contents... </div> <div id="rotateY">180 degree rotated div contents...</div> </center> </body></html>
Output:
The rotateZ() Method: This method is used to rotate an element around Z-axis at a given degree.Example:
<!DOCTYPE html><html> <head> <title>3D Transformation</title> <style> .normal_div { width: 200px; height: 100px; font-size:25px; color:white; background-color: green; border: 1px solid black; } #rotateZ { width: 200px; height: 100px; color:white; font-size:25px; background-color: green; border: 1px solid black; -webkit-transform: rotateZ(90deg); /* Safari */ transform: rotateZ(90deg); /* Standard syntax */ } .gfg { font-size:40px; font-weight:bold; color:#090; } .geeks { font-size:25px; font-weight:bold; margin:20px 0; } </style> </head> <body> <center> <div class = "gfg">GeeksforGeeks</div> <div class = "geeks">rotateZ() Method</div> <div class = "normal_div"> Div Contents... </div> <div id="rotateZ">90 degree rotated contents...</div> </center> </body></html>
Output:
Attention reader! Don’t stop learning now. Get hold of all the important HTML concepts with the Web Design for Beginners | HTML course.
jeefailure
CSS-Advanced
CSS
HTML
Web Technologies
HTML
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Top 10 Projects For Beginners To Practice HTML and CSS Skills
How to insert spaces/tabs in text using HTML/CSS?
How to create footer to stay at the bottom of a Web page?
How to update Node.js and NPM to next version ?
Types of CSS (Cascading Style Sheet)
Top 10 Projects For Beginners To Practice HTML and CSS Skills
How to insert spaces/tabs in text using HTML/CSS?
How to set the default value for an HTML <select> element ?
How to update Node.js and NPM to next version ?
How to set input type date in dd-mm-yyyy format using HTML ?
|
[
{
"code": null,
"e": 27655,
"s": 27627,
"text": "\n04 Jun, 2020"
},
{
"code": null,
"e": 27790,
"s": 27655,
"text": "It allows to change elements using 3D transformations. In 3D transformation, the elements are rotated along X-axis, Y-axis and Z-axis."
},
{
"code": null,
"e": 27859,
"s": 27790,
"text": "There are three main types of transformation which are listed below:"
},
{
"code": null,
"e": 27869,
"s": 27859,
"text": "rotateX()"
},
{
"code": null,
"e": 27879,
"s": 27869,
"text": "rotateY()"
},
{
"code": null,
"e": 27889,
"s": 27879,
"text": "rotateZ()"
},
{
"code": null,
"e": 27996,
"s": 27889,
"text": "The rotateX() Method: This rotation is used to rotate an elements around X-axis at a given degree.Example:"
},
{
"code": "<!DOCTYPE html><html> <head> <title>3D Transformation</title> <style> .normal_div { width: 300px; height: 150px; color: white; font-size:25px; background-color: green; border: 1px solid black; margin-bottom:20px; } #rotateX { width: 300px; height: 150px; color: white; font-size:25px; background-color: green; border: 1px solid black; -webkit-transform: rotateX(180deg); /* Safari */ transform: rotateX(180deg); /* Standard syntax */ } .gfg { font-size:40px; font-weight:bold; color:#090; } .geeks { font-size:25px; font-weight:bold; margin:20px 0; } </style> </head> <body> <center> <div class = \"gfg\">GeeksforGeeks</div> <div class = \"geeks\">rotateX() Method</div> <div class = \"normal_div\"> Div Contents... </div> <div id=\"rotateX\">180 degree rotated contents...</div> </center> </body></html> ",
"e": 29351,
"s": 27996,
"text": null
},
{
"code": null,
"e": 29359,
"s": 29351,
"text": "Output:"
},
{
"code": null,
"e": 29462,
"s": 29359,
"text": "The rotateY() Method: This method is used to rotate an element around Y-axis at given degrees.Example:"
},
{
"code": "<!DOCTYPE html><html> <head> <title>3D Transformation</title> <style> .normal_div { width: 200px; color:white; font-size:25px; height: 100px; background-color: green; border: 1px solid black; margin-bottom:20px; } #rotateY { width: 200px; color:white; font-size:25px; height: 100px; background-color: green; border: 1px solid black; -webkit-transform: rotateY(180deg); /* Safari */ transform: rotateY(100deg); /* Standard syntax */ } .gfg { font-size:40px; font-weight:bold; color:#090; } .geeks { font-size:25px; font-weight:bold; margin:20px 0; } </style> </head> <body> <center> <div class = \"gfg\">GeeksforGeeks</div> <div class = \"geeks\">rotateY() Method</div> <div class = \"normal_div\"> Div Contents... </div> <div id=\"rotateY\">180 degree rotated div contents...</div> </center> </body></html> ",
"e": 30805,
"s": 29462,
"text": null
},
{
"code": null,
"e": 30813,
"s": 30805,
"text": "Output:"
},
{
"code": null,
"e": 30917,
"s": 30813,
"text": "The rotateZ() Method: This method is used to rotate an element around Z-axis at a given degree.Example:"
},
{
"code": "<!DOCTYPE html><html> <head> <title>3D Transformation</title> <style> .normal_div { width: 200px; height: 100px; font-size:25px; color:white; background-color: green; border: 1px solid black; } #rotateZ { width: 200px; height: 100px; color:white; font-size:25px; background-color: green; border: 1px solid black; -webkit-transform: rotateZ(90deg); /* Safari */ transform: rotateZ(90deg); /* Standard syntax */ } .gfg { font-size:40px; font-weight:bold; color:#090; } .geeks { font-size:25px; font-weight:bold; margin:20px 0; } </style> </head> <body> <center> <div class = \"gfg\">GeeksforGeeks</div> <div class = \"geeks\">rotateZ() Method</div> <div class = \"normal_div\"> Div Contents... </div> <div id=\"rotateZ\">90 degree rotated contents...</div> </center> </body></html> ",
"e": 32202,
"s": 30917,
"text": null
},
{
"code": null,
"e": 32210,
"s": 32202,
"text": "Output:"
},
{
"code": null,
"e": 32347,
"s": 32210,
"text": "Attention reader! Don’t stop learning now. Get hold of all the important HTML concepts with the Web Design for Beginners | HTML course."
},
{
"code": null,
"e": 32358,
"s": 32347,
"text": "jeefailure"
},
{
"code": null,
"e": 32371,
"s": 32358,
"text": "CSS-Advanced"
},
{
"code": null,
"e": 32375,
"s": 32371,
"text": "CSS"
},
{
"code": null,
"e": 32380,
"s": 32375,
"text": "HTML"
},
{
"code": null,
"e": 32397,
"s": 32380,
"text": "Web Technologies"
},
{
"code": null,
"e": 32402,
"s": 32397,
"text": "HTML"
},
{
"code": null,
"e": 32500,
"s": 32402,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 32509,
"s": 32500,
"text": "Comments"
},
{
"code": null,
"e": 32522,
"s": 32509,
"text": "Old Comments"
},
{
"code": null,
"e": 32584,
"s": 32522,
"text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills"
},
{
"code": null,
"e": 32634,
"s": 32584,
"text": "How to insert spaces/tabs in text using HTML/CSS?"
},
{
"code": null,
"e": 32692,
"s": 32634,
"text": "How to create footer to stay at the bottom of a Web page?"
},
{
"code": null,
"e": 32740,
"s": 32692,
"text": "How to update Node.js and NPM to next version ?"
},
{
"code": null,
"e": 32777,
"s": 32740,
"text": "Types of CSS (Cascading Style Sheet)"
},
{
"code": null,
"e": 32839,
"s": 32777,
"text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills"
},
{
"code": null,
"e": 32889,
"s": 32839,
"text": "How to insert spaces/tabs in text using HTML/CSS?"
},
{
"code": null,
"e": 32949,
"s": 32889,
"text": "How to set the default value for an HTML <select> element ?"
},
{
"code": null,
"e": 32997,
"s": 32949,
"text": "How to update Node.js and NPM to next version ?"
}
] |
Detection and Classification of Blood Cells with Deep Learning (Part 2 — Training and Evaluation) | by Steven | Towards Data Science
|
Tackling the BCCD Dataset with Tensorflow Object Detection API
We are now finally ready for training.
# directory = ...YOUR_DIRECTORY/models/research/object_detection # type the following into Anaconda Promptpython train.py --logtostderr --train_dir=training/ --pipeline_config_path=training/faster_rcnn_inception_v2_pets.config
After about 30 seconds to 1 minute, the training process should begin. If the code runs smoothly, you should see the global step number as well as loss at each step displayed. To better monitor training, we launch Tensorboard.
# directory = ...YOUR_DIRECTORY/models/research/object_detection # type the following into Anaconda Prompttensorboard --logdir=training
Open up Tensorboard by copying http://localhost:6006/ into your browser. I trained my model for around 30 minutes but your training time may vary depending on your system configuration.
Once you are satisfied with the training loss, you can interrupt training by pressing Ctrl + C within the training window. We will now export the inference graph in order to visualize results and run evaluation on the model.
# directory = ...YOUR_DIRECTORY/models/research/object_detection # type the following into Anaconda Promptpython export_inference_graph.py --input_type image_tensor --pipeline_config_path training/faster_rcnn_inception_v2_pets.config --trained_checkpoint_prefix training/model.ckpt-YOUR_CHECKPOINT_NUMBER(e.g.2859) --output_directory inference_graph
The inference_graph folder should be created at ...YOUR_DIRECTORY/models/research/object_detection/inference_graph.
Open up object_detection_tutorial.ipynb notebook in the models/research/object_detection/ folder with Jupyter Notebook. I made some edits to the notebook in order to adapt it to our situation. Feel free to copy the edited code into the respective sections. I did not make any changes to the sections not discussed below.
# Importsimport numpy as npimport osimport six.moves.urllib as urllibimport sysimport tarfileimport tensorflow as tfimport zipfilefrom distutils.version import StrictVersionfrom collections import defaultdictfrom io import StringIOfrom matplotlib import pyplot as pltfrom matplotlib import patchesfrom PIL import Image# This is needed since the notebook is stored in the object_detection folder.sys.path.append("..")from object_detection.utils import ops as utils_opsif StrictVersion(tf.__version__) < StrictVersion('1.12.0'): raise ImportError('Please upgrade your TensorFlow installation to v1.12.*.')
Comment out the “Variables” and “Download Model” sections.
#Load a (frozen) Tensorflow model into memoryPATH_TO_FROZEN_GRAPH = r"...YOUR_DIRECTORY\models\research\object_detection\inference_graph\frozen_inference_graph.pb"detection_graph = tf.Graph()with detection_graph.as_default(): od_graph_def = tf.GraphDef() with tf.gfile.GFile(PATH_TO_FROZEN_GRAPH, 'rb') as fid: serialized_graph = fid.read() od_graph_def.ParseFromString(serialized_graph) tf.import_graph_def(od_graph_def, name='')
We need to make changes to the test images directory in order to display the predictions. I made a separate folder called “test_samples” in the images folder and selected the first 3 images (BloodImage_00333 to 00335) to run the test.
# DetectionPATH_TO_TEST_IMAGES_DIR = r"...YOUR_DIRECTORY\models\research\object_detection\images\test_samples"FILE_NAME = 'BloodImage_00{}.jpg'FILE_NUMBER = range(333,336)TEST_IMAGE_PATHS = [ os.path.join(PATH_TO_TEST_IMAGES_DIR, FILE_NAME.format(i)) for i in FILE_NUMBER]
I planned to display the predictions alongside ground truth and hence we need to make reference to the “test_labels.csv”.
import pandas as pdtrain = pd.read_csv(r"...YOUR_DIRECTORY\models\research\object_detection\images\test_labels.csv")train.head()
The below code will display ground truth images on the left and predictions on the right.
for image_path in TEST_IMAGE_PATHS: image = Image.open(image_path) # the array based representation of the image will be used later in order to prepare the # result image with boxes and labels on it. image_np = load_image_into_numpy_array(image) # Expand dimensions since the model expects images to have shape: [1, None, None, 3] image_np_expanded = np.expand_dims(image_np, axis=0) # Actual detection. output_dict = run_inference_for_single_image(image_np_expanded, detection_graph) # Visualization of the results of a detection. vis_util.visualize_boxes_and_labels_on_image_array( image_np, output_dict['detection_boxes'], output_dict['detection_classes'], output_dict['detection_scores'], category_index, instance_masks=output_dict.get('detection_masks'), use_normalized_coordinates=True, line_thickness=5) figure, (ax2, ax1) = plt.subplots(1, 2, figsize=(20,18))# plots prediction ax1.set_title("Predictions (" + image_path[-20:] + ")", size=25) ax1.imshow(image_np) # plots ground truth original = image ax2.set_title("Ground Truth (" + image_path[-20:] + ")", size=25) ax2.imshow(original) for _,row in train[train.filename == image_path[-20:]].iterrows(): xmin = row.xmin xmax = row.xmax ymin = row.ymin ymax = row.ymaxwidth = xmax - xmin height = ymax - ymin# assign different color to different classes of objects if row["class"] == 'RBC': edgecolor = 'lawngreen' ax2.annotate('RBC', xy=(xmax-40,ymin+20), size=25) elif row["class"] == 'WBC': edgecolor = 'cyan' ax2.annotate('WBC', xy=(xmax-40,ymin+20), size=25) elif row["class"] == 'Platelets': edgecolor = 'aquamarine' ax2.annotate('Platelets', xy=(xmax-40,ymin+20), size=25)# add bounding boxes to the image rect = patches.Rectangle((xmin,ymin), width, height, edgecolor = edgecolor, facecolor = 'none', lw=6) ax2.add_patch(rect) plt.tight_layout() plt.show()
If everything runs correctly, you should see the following:
Just by visual inspection, the model appears to be performing well with only 30 minutes of training time. The bounding boxes are tight and it detected most of the blood cells. Of note, the model is able to detect both large (WBCs) and small (platelets) cells. In certain cases, it even detected RBCs which were not labeled in the ground truth. This bodes well for the generalizability of the model.
As gross visual inspection of the predictions appears satisfactory, we will now run official evaluation using COCO metrics.
First, we have to gitclone the COCO Python API.
# directory = ...YOUR_DIRECTORY/models/research# type the following into Anaconda Promptgit clone https://github.com/cocodataset/cocoapi.git
This will download the “coco” folder and you should see it in YOUR_DIRECTORY/models/research.
# directory = ...YOUR_DIRECTORY/models/research# type the following into Anaconda Promptcd coco/PythonAPI
This will change directory into YOUR_DIRECTORY/models/research/coco/PythonAPI. At this stage, the official instructions calls for typing “make” into the Anaconda Prompt. However, I was unable to get it to work and searching around github and stackoverflow gave me the workaround.
First, you need to have Microsoft Visual C++ Build Tools installed as per answer by “Jason246” here: https://stackoverflow.com/questions/48541801/microsoft-visual-c-14-0-is-required-get-it-with-microsoft-visual-c-build-t
Next, open up the “setup.py” file using code editor at YOUR_DIRECTORY/models/research/coco/PythonAPI and make the following changes.
# change thisext_modules = [ Extension( 'pycocotools._mask', sources=['../common/maskApi.c', 'pycocotools/_mask.pyx'], include_dirs = [np.get_include(), '../common'], extra_compile_args=['-Wno-cpp', '-Wno-unused-function', '-std=c99'], )]# to thisext_modules = [ Extension( 'pycocotools._mask', sources=['../common/maskApi.c', 'pycocotools/_mask.pyx'], include_dirs = [np.get_include(), '../common'], extra_compile_args={'gcc': ['/Qstd=c99']}, )]
Next, run the “setup.py” file.
# directory = ...YOUR_DIRECTORY/models/research/coco/PythonAPI# type the following into Anaconda Promptpython3 setup.py build_ext --inplace
After this, copy the pycocotools folder at YOUR_DIRECTORY/models/research/coco/PythonAPI to YOUR_DIRECTORY/models/research.
Now, go to YOUR_DIRECTORY/models/research/object_detection/legacy and copy the “eval.py” file to the “object_detection” folder. We can finally run the evaluation script.
# directory = ...YOUR_DIRECTORY/models/research/object_detection# type the following into Anaconda Promptpython eval.py --logtostderr --pipeline_config_path=training/faster_rcnn_inception_v2_pets.config --checkpoint_dir=training/ --eval_dir=eval/
This will save the evaluation results into the eval/ directory. Just like training, we can use Tensorboard to visualize the evaluation.
# directory = ...YOUR_DIRECTORY/models/research/object_detection # type the following into Anaconda Prompttensorboard --logdir=eval
The “eval.py” will also generate a report based on COCO metrics. The results for my model are as follows:
Precision (positive predictive value) is the proportion of true positives over true positives + false positives. Recall (sensitivity) is the proportion of true positives over true positives + false negatives.
With a lenient Intersection over Union (IOU) of 0.5, 96.7% of the positive predictions by the model were true positives. This percentage is reduced to 64.5% when we average out the APs for IOU 0.5 to 0.95 with step size of 0.05. Notably, the model performed poorly on smaller objects with AP of 23.4% and 52.5% for small and medium objects respectively.
Looking at recall, the model detected on average 71.9% of true positives, with poorer performance for small objects.
In summary, we built a model using Tensorflow Objection Detection API to locate and classify 3 types of blood cells in the BCCD dataset. Future work includes increasing training time, improving performance on small objects and extending model to other datasets.
Thanks for reading.
|
[
{
"code": null,
"e": 235,
"s": 172,
"text": "Tackling the BCCD Dataset with Tensorflow Object Detection API"
},
{
"code": null,
"e": 274,
"s": 235,
"text": "We are now finally ready for training."
},
{
"code": null,
"e": 501,
"s": 274,
"text": "# directory = ...YOUR_DIRECTORY/models/research/object_detection # type the following into Anaconda Promptpython train.py --logtostderr --train_dir=training/ --pipeline_config_path=training/faster_rcnn_inception_v2_pets.config"
},
{
"code": null,
"e": 728,
"s": 501,
"text": "After about 30 seconds to 1 minute, the training process should begin. If the code runs smoothly, you should see the global step number as well as loss at each step displayed. To better monitor training, we launch Tensorboard."
},
{
"code": null,
"e": 864,
"s": 728,
"text": "# directory = ...YOUR_DIRECTORY/models/research/object_detection # type the following into Anaconda Prompttensorboard --logdir=training"
},
{
"code": null,
"e": 1050,
"s": 864,
"text": "Open up Tensorboard by copying http://localhost:6006/ into your browser. I trained my model for around 30 minutes but your training time may vary depending on your system configuration."
},
{
"code": null,
"e": 1275,
"s": 1050,
"text": "Once you are satisfied with the training loss, you can interrupt training by pressing Ctrl + C within the training window. We will now export the inference graph in order to visualize results and run evaluation on the model."
},
{
"code": null,
"e": 1625,
"s": 1275,
"text": "# directory = ...YOUR_DIRECTORY/models/research/object_detection # type the following into Anaconda Promptpython export_inference_graph.py --input_type image_tensor --pipeline_config_path training/faster_rcnn_inception_v2_pets.config --trained_checkpoint_prefix training/model.ckpt-YOUR_CHECKPOINT_NUMBER(e.g.2859) --output_directory inference_graph"
},
{
"code": null,
"e": 1741,
"s": 1625,
"text": "The inference_graph folder should be created at ...YOUR_DIRECTORY/models/research/object_detection/inference_graph."
},
{
"code": null,
"e": 2062,
"s": 1741,
"text": "Open up object_detection_tutorial.ipynb notebook in the models/research/object_detection/ folder with Jupyter Notebook. I made some edits to the notebook in order to adapt it to our situation. Feel free to copy the edited code into the respective sections. I did not make any changes to the sections not discussed below."
},
{
"code": null,
"e": 2667,
"s": 2062,
"text": "# Importsimport numpy as npimport osimport six.moves.urllib as urllibimport sysimport tarfileimport tensorflow as tfimport zipfilefrom distutils.version import StrictVersionfrom collections import defaultdictfrom io import StringIOfrom matplotlib import pyplot as pltfrom matplotlib import patchesfrom PIL import Image# This is needed since the notebook is stored in the object_detection folder.sys.path.append(\"..\")from object_detection.utils import ops as utils_opsif StrictVersion(tf.__version__) < StrictVersion('1.12.0'): raise ImportError('Please upgrade your TensorFlow installation to v1.12.*.')"
},
{
"code": null,
"e": 2726,
"s": 2667,
"text": "Comment out the “Variables” and “Download Model” sections."
},
{
"code": null,
"e": 3184,
"s": 2726,
"text": "#Load a (frozen) Tensorflow model into memoryPATH_TO_FROZEN_GRAPH = r\"...YOUR_DIRECTORY\\models\\research\\object_detection\\inference_graph\\frozen_inference_graph.pb\"detection_graph = tf.Graph()with detection_graph.as_default(): od_graph_def = tf.GraphDef() with tf.gfile.GFile(PATH_TO_FROZEN_GRAPH, 'rb') as fid: serialized_graph = fid.read() od_graph_def.ParseFromString(serialized_graph) tf.import_graph_def(od_graph_def, name='')"
},
{
"code": null,
"e": 3419,
"s": 3184,
"text": "We need to make changes to the test images directory in order to display the predictions. I made a separate folder called “test_samples” in the images folder and selected the first 3 images (BloodImage_00333 to 00335) to run the test."
},
{
"code": null,
"e": 3692,
"s": 3419,
"text": "# DetectionPATH_TO_TEST_IMAGES_DIR = r\"...YOUR_DIRECTORY\\models\\research\\object_detection\\images\\test_samples\"FILE_NAME = 'BloodImage_00{}.jpg'FILE_NUMBER = range(333,336)TEST_IMAGE_PATHS = [ os.path.join(PATH_TO_TEST_IMAGES_DIR, FILE_NAME.format(i)) for i in FILE_NUMBER]"
},
{
"code": null,
"e": 3814,
"s": 3692,
"text": "I planned to display the predictions alongside ground truth and hence we need to make reference to the “test_labels.csv”."
},
{
"code": null,
"e": 3943,
"s": 3814,
"text": "import pandas as pdtrain = pd.read_csv(r\"...YOUR_DIRECTORY\\models\\research\\object_detection\\images\\test_labels.csv\")train.head()"
},
{
"code": null,
"e": 4033,
"s": 3943,
"text": "The below code will display ground truth images on the left and predictions on the right."
},
{
"code": null,
"e": 6106,
"s": 4033,
"text": "for image_path in TEST_IMAGE_PATHS: image = Image.open(image_path) # the array based representation of the image will be used later in order to prepare the # result image with boxes and labels on it. image_np = load_image_into_numpy_array(image) # Expand dimensions since the model expects images to have shape: [1, None, None, 3] image_np_expanded = np.expand_dims(image_np, axis=0) # Actual detection. output_dict = run_inference_for_single_image(image_np_expanded, detection_graph) # Visualization of the results of a detection. vis_util.visualize_boxes_and_labels_on_image_array( image_np, output_dict['detection_boxes'], output_dict['detection_classes'], output_dict['detection_scores'], category_index, instance_masks=output_dict.get('detection_masks'), use_normalized_coordinates=True, line_thickness=5) figure, (ax2, ax1) = plt.subplots(1, 2, figsize=(20,18))# plots prediction ax1.set_title(\"Predictions (\" + image_path[-20:] + \")\", size=25) ax1.imshow(image_np) # plots ground truth original = image ax2.set_title(\"Ground Truth (\" + image_path[-20:] + \")\", size=25) ax2.imshow(original) for _,row in train[train.filename == image_path[-20:]].iterrows(): xmin = row.xmin xmax = row.xmax ymin = row.ymin ymax = row.ymaxwidth = xmax - xmin height = ymax - ymin# assign different color to different classes of objects if row[\"class\"] == 'RBC': edgecolor = 'lawngreen' ax2.annotate('RBC', xy=(xmax-40,ymin+20), size=25) elif row[\"class\"] == 'WBC': edgecolor = 'cyan' ax2.annotate('WBC', xy=(xmax-40,ymin+20), size=25) elif row[\"class\"] == 'Platelets': edgecolor = 'aquamarine' ax2.annotate('Platelets', xy=(xmax-40,ymin+20), size=25)# add bounding boxes to the image rect = patches.Rectangle((xmin,ymin), width, height, edgecolor = edgecolor, facecolor = 'none', lw=6) ax2.add_patch(rect) plt.tight_layout() plt.show()"
},
{
"code": null,
"e": 6166,
"s": 6106,
"text": "If everything runs correctly, you should see the following:"
},
{
"code": null,
"e": 6565,
"s": 6166,
"text": "Just by visual inspection, the model appears to be performing well with only 30 minutes of training time. The bounding boxes are tight and it detected most of the blood cells. Of note, the model is able to detect both large (WBCs) and small (platelets) cells. In certain cases, it even detected RBCs which were not labeled in the ground truth. This bodes well for the generalizability of the model."
},
{
"code": null,
"e": 6689,
"s": 6565,
"text": "As gross visual inspection of the predictions appears satisfactory, we will now run official evaluation using COCO metrics."
},
{
"code": null,
"e": 6737,
"s": 6689,
"text": "First, we have to gitclone the COCO Python API."
},
{
"code": null,
"e": 6878,
"s": 6737,
"text": "# directory = ...YOUR_DIRECTORY/models/research# type the following into Anaconda Promptgit clone https://github.com/cocodataset/cocoapi.git"
},
{
"code": null,
"e": 6972,
"s": 6878,
"text": "This will download the “coco” folder and you should see it in YOUR_DIRECTORY/models/research."
},
{
"code": null,
"e": 7078,
"s": 6972,
"text": "# directory = ...YOUR_DIRECTORY/models/research# type the following into Anaconda Promptcd coco/PythonAPI"
},
{
"code": null,
"e": 7358,
"s": 7078,
"text": "This will change directory into YOUR_DIRECTORY/models/research/coco/PythonAPI. At this stage, the official instructions calls for typing “make” into the Anaconda Prompt. However, I was unable to get it to work and searching around github and stackoverflow gave me the workaround."
},
{
"code": null,
"e": 7579,
"s": 7358,
"text": "First, you need to have Microsoft Visual C++ Build Tools installed as per answer by “Jason246” here: https://stackoverflow.com/questions/48541801/microsoft-visual-c-14-0-is-required-get-it-with-microsoft-visual-c-build-t"
},
{
"code": null,
"e": 7712,
"s": 7579,
"text": "Next, open up the “setup.py” file using code editor at YOUR_DIRECTORY/models/research/coco/PythonAPI and make the following changes."
},
{
"code": null,
"e": 8227,
"s": 7712,
"text": "# change thisext_modules = [ Extension( 'pycocotools._mask', sources=['../common/maskApi.c', 'pycocotools/_mask.pyx'], include_dirs = [np.get_include(), '../common'], extra_compile_args=['-Wno-cpp', '-Wno-unused-function', '-std=c99'], )]# to thisext_modules = [ Extension( 'pycocotools._mask', sources=['../common/maskApi.c', 'pycocotools/_mask.pyx'], include_dirs = [np.get_include(), '../common'], extra_compile_args={'gcc': ['/Qstd=c99']}, )]"
},
{
"code": null,
"e": 8258,
"s": 8227,
"text": "Next, run the “setup.py” file."
},
{
"code": null,
"e": 8398,
"s": 8258,
"text": "# directory = ...YOUR_DIRECTORY/models/research/coco/PythonAPI# type the following into Anaconda Promptpython3 setup.py build_ext --inplace"
},
{
"code": null,
"e": 8522,
"s": 8398,
"text": "After this, copy the pycocotools folder at YOUR_DIRECTORY/models/research/coco/PythonAPI to YOUR_DIRECTORY/models/research."
},
{
"code": null,
"e": 8692,
"s": 8522,
"text": "Now, go to YOUR_DIRECTORY/models/research/object_detection/legacy and copy the “eval.py” file to the “object_detection” folder. We can finally run the evaluation script."
},
{
"code": null,
"e": 8939,
"s": 8692,
"text": "# directory = ...YOUR_DIRECTORY/models/research/object_detection# type the following into Anaconda Promptpython eval.py --logtostderr --pipeline_config_path=training/faster_rcnn_inception_v2_pets.config --checkpoint_dir=training/ --eval_dir=eval/"
},
{
"code": null,
"e": 9075,
"s": 8939,
"text": "This will save the evaluation results into the eval/ directory. Just like training, we can use Tensorboard to visualize the evaluation."
},
{
"code": null,
"e": 9207,
"s": 9075,
"text": "# directory = ...YOUR_DIRECTORY/models/research/object_detection # type the following into Anaconda Prompttensorboard --logdir=eval"
},
{
"code": null,
"e": 9313,
"s": 9207,
"text": "The “eval.py” will also generate a report based on COCO metrics. The results for my model are as follows:"
},
{
"code": null,
"e": 9522,
"s": 9313,
"text": "Precision (positive predictive value) is the proportion of true positives over true positives + false positives. Recall (sensitivity) is the proportion of true positives over true positives + false negatives."
},
{
"code": null,
"e": 9876,
"s": 9522,
"text": "With a lenient Intersection over Union (IOU) of 0.5, 96.7% of the positive predictions by the model were true positives. This percentage is reduced to 64.5% when we average out the APs for IOU 0.5 to 0.95 with step size of 0.05. Notably, the model performed poorly on smaller objects with AP of 23.4% and 52.5% for small and medium objects respectively."
},
{
"code": null,
"e": 9993,
"s": 9876,
"text": "Looking at recall, the model detected on average 71.9% of true positives, with poorer performance for small objects."
},
{
"code": null,
"e": 10255,
"s": 9993,
"text": "In summary, we built a model using Tensorflow Objection Detection API to locate and classify 3 types of blood cells in the BCCD dataset. Future work includes increasing training time, improving performance on small objects and extending model to other datasets."
}
] |
Kotlin Comments
|
Comments can be used to explain Kotlin code, and to make it more readable. It can also be used to
prevent execution when testing alternative code.
Single-line comments starts with two forward slashes (//).
Any text between // and the end of the line
is ignored by Kotlin (will not be executed).
This example uses a single-line comment before a line of code:
// This is a comment
println("Hello World")
This example uses a single-line comment at the end of a line of code:
println("Hello World") // This is a comment
Multi-line comments start with /* and ends with */.
Any text between /* and */ will be ignored by Kotlin.
This example uses a multi-line comment (a comment block) to explain the code:
/* The code below will print the words Hello World
to the screen, and it is amazing */
println("Hello World")
We just launchedW3Schools videos
Get certifiedby completinga course today!
If you want to report an error, or if you want to make a suggestion, do not hesitate to send us an e-mail:
[email protected]
Your message has been sent to W3Schools.
|
[
{
"code": null,
"e": 148,
"s": 0,
"text": "Comments can be used to explain Kotlin code, and to make it more readable. It can also be used to \nprevent execution when testing alternative code."
},
{
"code": null,
"e": 207,
"s": 148,
"text": "Single-line comments starts with two forward slashes (//)."
},
{
"code": null,
"e": 297,
"s": 207,
"text": "Any text between // and the end of the line \nis ignored by Kotlin (will not be executed)."
},
{
"code": null,
"e": 360,
"s": 297,
"text": "This example uses a single-line comment before a line of code:"
},
{
"code": null,
"e": 405,
"s": 360,
"text": "// This is a comment\nprintln(\"Hello World\") "
},
{
"code": null,
"e": 475,
"s": 405,
"text": "This example uses a single-line comment at the end of a line of code:"
},
{
"code": null,
"e": 520,
"s": 475,
"text": "println(\"Hello World\") // This is a comment"
},
{
"code": null,
"e": 572,
"s": 520,
"text": "Multi-line comments start with /* and ends with */."
},
{
"code": null,
"e": 626,
"s": 572,
"text": "Any text between /* and */ will be ignored by Kotlin."
},
{
"code": null,
"e": 704,
"s": 626,
"text": "This example uses a multi-line comment (a comment block) to explain the code:"
},
{
"code": null,
"e": 816,
"s": 704,
"text": "/* The code below will print the words Hello World\nto the screen, and it is amazing */\nprintln(\"Hello World\") "
},
{
"code": null,
"e": 849,
"s": 816,
"text": "We just launchedW3Schools videos"
},
{
"code": null,
"e": 891,
"s": 849,
"text": "Get certifiedby completinga course today!"
},
{
"code": null,
"e": 998,
"s": 891,
"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": 1017,
"s": 998,
"text": "[email protected]"
}
] |
Elasticsearch - Query DSL
|
In Elasticsearch, searching is carried out by using query based on JSON. A query is made up of two clauses −
Leaf Query Clauses − These clauses are match, term or range, which look for a specific value in specific field.
Leaf Query Clauses − These clauses are match, term or range, which look for a specific value in specific field.
Compound Query Clauses − These queries are a combination of leaf query clauses and other compound queries to extract the desired information.
Compound Query Clauses − These queries are a combination of leaf query clauses and other compound queries to extract the desired information.
Elasticsearch supports a large number of queries. A query starts with a query key word and then has conditions and filters inside in the form of JSON object. The different types of queries have been described below.
This is the most basic query; it returns all the content and with the score of 1.0 for every object.
POST /schools/_search
{
"query":{
"match_all":{}
}
}
On running the above code, we get the following result −
{
"took" : 7,
"timed_out" : false,
"_shards" : {
"total" : 1,
"successful" : 1,
"skipped" : 0,
"failed" : 0
},
"hits" : {
"total" : {
"value" : 2,
"relation" : "eq"
},
"max_score" : 1.0,
"hits" : [
{
"_index" : "schools",
"_type" : "school",
"_id" : "5",
"_score" : 1.0,
"_source" : {
"name" : "Central School",
"description" : "CBSE Affiliation",
"street" : "Nagan",
"city" : "paprola",
"state" : "HP",
"zip" : "176115",
"location" : [
31.8955385,
76.8380405
],
"fees" : 2200,
"tags" : [
"Senior Secondary",
"beautiful campus"
],
"rating" : "3.3"
}
},
{
"_index" : "schools",
"_type" : "school",
"_id" : "4",
"_score" : 1.0,
"_source" : {
"name" : "City Best School",
"description" : "ICSE",
"street" : "West End",
"city" : "Meerut",
"state" : "UP",
"zip" : "250002",
"location" : [
28.9926174,
77.692485
],
"fees" : 3500,
"tags" : [
"fully computerized"
],
"rating" : "4.5"
}
}
]
}
}
These queries are used to search a full body of text like a chapter or a news article. This query works according to the analyser associated with that particular index or document. In this section, we will discuss the different types of full text queries.
This query matches a text or phrase with the values of one or more fields.
POST /schools*/_search
{
"query":{
"match" : {
"rating":"4.5"
}
}
}
On running the above code, we get the response as shown below −
{
"took" : 44,
"timed_out" : false,
"_shards" : {
"total" : 1,
"successful" : 1,
"skipped" : 0,
"failed" : 0
},
"hits" : {
"total" : {
"value" : 1,
"relation" : "eq"
},
"max_score" : 0.47000363,
"hits" : [
{
"_index" : "schools",
"_type" : "school",
"_id" : "4",
"_score" : 0.47000363,
"_source" : {
"name" : "City Best School",
"description" : "ICSE",
"street" : "West End",
"city" : "Meerut",
"state" : "UP",
"zip" : "250002",
"location" : [
28.9926174,
77.692485
],
"fees" : 3500,
"tags" : [
"fully computerized"
],
"rating" : "4.5"
}
}
]
}
}
This query matches a text or phrase with more than one field.
POST /schools*/_search
{
"query":{
"multi_match" : {
"query": "paprola",
"fields": [ "city", "state" ]
}
}
}
On running the above code, we get the response as shown below −
{
"took" : 12,
"timed_out" : false,
"_shards" : {
"total" : 1,
"successful" : 1,
"skipped" : 0,
"failed" : 0
},
"hits" : {
"total" : {
"value" : 1,
"relation" : "eq"
},
"max_score" : 0.9808292,
"hits" : [
{
"_index" : "schools",
"_type" : "school",
"_id" : "5",
"_score" : 0.9808292,
"_source" : {
"name" : "Central School",
"description" : "CBSE Affiliation",
"street" : "Nagan",
"city" : "paprola",
"state" : "HP",
"zip" : "176115",
"location" : [
31.8955385,
76.8380405
],
"fees" : 2200,
"tags" : [
"Senior Secondary",
"beautiful campus"
],
"rating" : "3.3"
}
}
]
}
}
This query uses query parser and query_string keyword.
POST /schools*/_search
{
"query":{
"query_string":{
"query":"beautiful"
}
}
}
On running the above code, we get the response as shown below −
{
"took" : 60,
"timed_out" : false,
"_shards" : {
"total" : 1,
"successful" : 1,
"skipped" : 0,
"failed" : 0
},
"hits" : {
"total" : {
"value" : 1,
"relation" : "eq"
},
........................................
These queries mainly deal with structured data like numbers, dates and enums.
POST /schools*/_search
{
"query":{
"term":{"zip":"176115"}
}
}
On running the above code, we get the response as shown below −
...................................
hits" : [
{
"_index" : "schools",
"_type" : "school",
"_id" : "5",
"_score" : 0.9808292,
"_source" : {
"name" : "Central School",
"description" : "CBSE Affiliation",
"street" : "Nagan",
"city" : "paprola",
"state" : "HP",
"zip" : "176115",
"location" : [
31.8955385,
76.8380405
],
}
}
]
..................................................
This query is used to find the objects having values between the ranges of values given. For this, we need to use operators such as −
gte − greater than equal to
gt − greater-than
lte − less-than equal to
lt − less-than
For example, observe the code given below −
POST /schools*/_search
{
"query":{
"range":{
"rating":{
"gte":3.5
}
}
}
}
On running the above code, we get the response as shown below −
{
"took" : 24,
"timed_out" : false,
"_shards" : {
"total" : 1,
"successful" : 1,
"skipped" : 0,
"failed" : 0
},
"hits" : {
"total" : {
"value" : 1,
"relation" : "eq"
},
"max_score" : 1.0,
"hits" : [
{
"_index" : "schools",
"_type" : "school",
"_id" : "4",
"_score" : 1.0,
"_source" : {
"name" : "City Best School",
"description" : "ICSE",
"street" : "West End",
"city" : "Meerut",
"state" : "UP",
"zip" : "250002",
"location" : [
28.9926174,
77.692485
],
"fees" : 3500,
"tags" : [
"fully computerized"
],
"rating" : "4.5"
}
}
]
}
}
There exist other types of term level queries also such as −
Exists query − If a certain field has non null value.
Exists query − If a certain field has non null value.
Missing query − This is completely opposite to exists query, this query searches for objects without specific fields or fields having null value.
Missing query − This is completely opposite to exists query, this query searches for objects without specific fields or fields having null value.
Wildcard or regexp query − This query uses regular expressions to find patterns in the objects.
Wildcard or regexp query − This query uses regular expressions to find patterns in the objects.
These queries are a collection of different queries merged with each other by using Boolean
operators like and, or, not or for different indices or having function calls etc.
POST /schools/_search
{
"query": {
"bool" : {
"must" : {
"term" : { "state" : "UP" }
},
"filter": {
"term" : { "fees" : "2200" }
},
"minimum_should_match" : 1,
"boost" : 1.0
}
}
}
On running the above code, we get the response as shown below −
{
"took" : 6,
"timed_out" : false,
"_shards" : {
"total" : 1,
"successful" : 1,
"skipped" : 0,
"failed" : 0
},
"hits" : {
"total" : {
"value" : 0,
"relation" : "eq"
},
"max_score" : null,
"hits" : [ ]
}
}
These queries deal with geo locations and geo points. These queries help to find out schools
or any other geographical object near to any location. You need to use geo point data type.
PUT /geo_example
{
"mappings": {
"properties": {
"location": {
"type": "geo_shape"
}
}
}
}
On running the above code, we get the response as shown below −
{ "acknowledged" : true,
"shards_acknowledged" : true,
"index" : "geo_example"
}
Now we post the data in the index created above.
POST /geo_example/_doc?refresh
{
"name": "Chapter One, London, UK",
"location": {
"type": "point",
"coordinates": [11.660544, 57.800286]
}
}
On running the above code, we get the response as shown below −
{
"took" : 1,
"timed_out" : false,
"_shards" : {
"total" : 1,
"successful" : 1,
"skipped" : 0,
"failed" : 0
},
"hits" : {
"total" : {
"value" : 2,
"relation" : "eq"
},
"max_score" : 1.0,
"hits" : [
"_index" : "geo_example",
"_type" : "_doc",
"_id" : "hASWZ2oBbkdGzVfiXHKD",
"_score" : 1.0,
"_source" : {
"name" : "Chapter One, London, UK",
"location" : {
"type" : "point",
"coordinates" : [
11.660544,
57.800286
]
}
}
}
}
14 Lectures
5 hours
Manuj Aggarwal
20 Lectures
1 hours
Faizan Tayyab
Print
Add Notes
Bookmark this page
|
[
{
"code": null,
"e": 2690,
"s": 2581,
"text": "In Elasticsearch, searching is carried out by using query based on JSON. A query is made up of two clauses −"
},
{
"code": null,
"e": 2802,
"s": 2690,
"text": "Leaf Query Clauses − These clauses are match, term or range, which look for a specific value in specific field."
},
{
"code": null,
"e": 2914,
"s": 2802,
"text": "Leaf Query Clauses − These clauses are match, term or range, which look for a specific value in specific field."
},
{
"code": null,
"e": 3056,
"s": 2914,
"text": "Compound Query Clauses − These queries are a combination of leaf query clauses and other compound queries to extract the desired information."
},
{
"code": null,
"e": 3198,
"s": 3056,
"text": "Compound Query Clauses − These queries are a combination of leaf query clauses and other compound queries to extract the desired information."
},
{
"code": null,
"e": 3414,
"s": 3198,
"text": "Elasticsearch supports a large number of queries. A query starts with a query key word and then has conditions and filters inside in the form of JSON object. The different types of queries have been described below."
},
{
"code": null,
"e": 3515,
"s": 3414,
"text": "This is the most basic query; it returns all the content and with the score of 1.0 for every object."
},
{
"code": null,
"e": 3580,
"s": 3515,
"text": "POST /schools/_search\n{\n \"query\":{\n \"match_all\":{}\n }\n}"
},
{
"code": null,
"e": 3637,
"s": 3580,
"text": "On running the above code, we get the following result −"
},
{
"code": null,
"e": 5280,
"s": 3637,
"text": "{\n \"took\" : 7,\n \"timed_out\" : false,\n \"_shards\" : {\n \"total\" : 1,\n \"successful\" : 1,\n \"skipped\" : 0,\n \"failed\" : 0\n },\n \"hits\" : {\n \"total\" : {\n \"value\" : 2,\n \"relation\" : \"eq\"\n },\n \"max_score\" : 1.0,\n \"hits\" : [\n {\n \"_index\" : \"schools\",\n \"_type\" : \"school\",\n \"_id\" : \"5\",\n \"_score\" : 1.0,\n \"_source\" : {\n \"name\" : \"Central School\",\n \"description\" : \"CBSE Affiliation\",\n \"street\" : \"Nagan\",\n \"city\" : \"paprola\",\n \"state\" : \"HP\",\n \"zip\" : \"176115\",\n \"location\" : [\n 31.8955385,\n 76.8380405\n ],\n \"fees\" : 2200,\n \"tags\" : [\n \"Senior Secondary\",\n \"beautiful campus\"\n ],\n \"rating\" : \"3.3\"\n }\n },\n {\n \"_index\" : \"schools\",\n \"_type\" : \"school\",\n \"_id\" : \"4\",\n \"_score\" : 1.0,\n \"_source\" : {\n \"name\" : \"City Best School\",\n \"description\" : \"ICSE\",\n \"street\" : \"West End\",\n \"city\" : \"Meerut\",\n \"state\" : \"UP\",\n \"zip\" : \"250002\",\n \"location\" : [\n 28.9926174,\n 77.692485\n ],\n \"fees\" : 3500,\n \"tags\" : [\n \"fully computerized\"\n ],\n \"rating\" : \"4.5\"\n }\n }\n ]\n }\n}\n"
},
{
"code": null,
"e": 5536,
"s": 5280,
"text": "These queries are used to search a full body of text like a chapter or a news article. This query works according to the analyser associated with that particular index or document. In this section, we will discuss the different types of full text queries."
},
{
"code": null,
"e": 5611,
"s": 5536,
"text": "This query matches a text or phrase with the values of one or more fields."
},
{
"code": null,
"e": 5706,
"s": 5611,
"text": "POST /schools*/_search\n{\n \"query\":{\n \"match\" : {\n \"rating\":\"4.5\"\n }\n }\n}"
},
{
"code": null,
"e": 5770,
"s": 5706,
"text": "On running the above code, we get the response as shown below −"
},
{
"code": null,
"e": 6731,
"s": 5770,
"text": "{\n \"took\" : 44,\n \"timed_out\" : false,\n \"_shards\" : {\n \"total\" : 1,\n \"successful\" : 1,\n \"skipped\" : 0,\n \"failed\" : 0\n },\n \"hits\" : {\n \"total\" : {\n \"value\" : 1,\n \"relation\" : \"eq\"\n },\n \"max_score\" : 0.47000363,\n \"hits\" : [\n {\n \"_index\" : \"schools\",\n \"_type\" : \"school\",\n \"_id\" : \"4\",\n \"_score\" : 0.47000363,\n \"_source\" : {\n \"name\" : \"City Best School\",\n \"description\" : \"ICSE\",\n \"street\" : \"West End\",\n \"city\" : \"Meerut\",\n \"state\" : \"UP\",\n \"zip\" : \"250002\",\n \"location\" : [\n 28.9926174,\n 77.692485\n ],\n \"fees\" : 3500,\n \"tags\" : [\n \"fully computerized\"\n ],\n \"rating\" : \"4.5\"\n }\n }\n ]\n }\n}\n"
},
{
"code": null,
"e": 6793,
"s": 6731,
"text": "This query matches a text or phrase with more than one field."
},
{
"code": null,
"e": 6938,
"s": 6793,
"text": "POST /schools*/_search\n{\n \"query\":{\n \"multi_match\" : {\n \"query\": \"paprola\",\n \"fields\": [ \"city\", \"state\" ]\n }\n }\n}"
},
{
"code": null,
"e": 7002,
"s": 6938,
"text": "On running the above code, we get the response as shown below −"
},
{
"code": null,
"e": 8006,
"s": 7002,
"text": "{\n \"took\" : 12,\n \"timed_out\" : false,\n \"_shards\" : {\n \"total\" : 1,\n \"successful\" : 1,\n \"skipped\" : 0,\n \"failed\" : 0\n },\n \"hits\" : {\n \"total\" : {\n \"value\" : 1,\n \"relation\" : \"eq\"\n },\n \"max_score\" : 0.9808292,\n \"hits\" : [\n {\n \"_index\" : \"schools\",\n \"_type\" : \"school\",\n \"_id\" : \"5\",\n \"_score\" : 0.9808292,\n \"_source\" : {\n \"name\" : \"Central School\",\n \"description\" : \"CBSE Affiliation\",\n \"street\" : \"Nagan\",\n \"city\" : \"paprola\",\n \"state\" : \"HP\",\n \"zip\" : \"176115\",\n \"location\" : [\n 31.8955385,\n 76.8380405\n ],\n \"fees\" : 2200,\n \"tags\" : [\n \"Senior Secondary\",\n \"beautiful campus\"\n ],\n \"rating\" : \"3.3\"\n }\n }\n ]\n }\n}\n"
},
{
"code": null,
"e": 8061,
"s": 8006,
"text": "This query uses query parser and query_string keyword."
},
{
"code": null,
"e": 8168,
"s": 8061,
"text": "POST /schools*/_search\n{\n \"query\":{\n \"query_string\":{\n \"query\":\"beautiful\"\n }\n }\n} "
},
{
"code": null,
"e": 8232,
"s": 8168,
"text": "On running the above code, we get the response as shown below −"
},
{
"code": null,
"e": 8503,
"s": 8232,
"text": "{\n \"took\" : 60,\n \"timed_out\" : false,\n \"_shards\" : {\n \"total\" : 1,\n \"successful\" : 1,\n \"skipped\" : 0,\n \"failed\" : 0\n },\n \"hits\" : {\n \"total\" : {\n \"value\" : 1,\n \"relation\" : \"eq\"\n },\n........................................\n"
},
{
"code": null,
"e": 8581,
"s": 8503,
"text": "These queries mainly deal with structured data like numbers, dates and enums."
},
{
"code": null,
"e": 8656,
"s": 8581,
"text": "POST /schools*/_search\n{\n \"query\":{\n \"term\":{\"zip\":\"176115\"}\n }\n}"
},
{
"code": null,
"e": 8720,
"s": 8656,
"text": "On running the above code, we get the response as shown below −"
},
{
"code": null,
"e": 9236,
"s": 8720,
"text": "...................................\nhits\" : [\n {\n \"_index\" : \"schools\",\n \"_type\" : \"school\",\n \"_id\" : \"5\",\n \"_score\" : 0.9808292,\n \"_source\" : {\n \"name\" : \"Central School\",\n \"description\" : \"CBSE Affiliation\",\n \"street\" : \"Nagan\",\n \"city\" : \"paprola\",\n \"state\" : \"HP\",\n \"zip\" : \"176115\",\n \"location\" : [\n 31.8955385,\n 76.8380405\n ],\n }\n }\n] \n..................................................\n"
},
{
"code": null,
"e": 9370,
"s": 9236,
"text": "This query is used to find the objects having values between the ranges of values given. For this, we need to use operators such as −"
},
{
"code": null,
"e": 9398,
"s": 9370,
"text": "gte − greater than equal to"
},
{
"code": null,
"e": 9416,
"s": 9398,
"text": "gt − greater-than"
},
{
"code": null,
"e": 9441,
"s": 9416,
"text": "lte − less-than equal to"
},
{
"code": null,
"e": 9456,
"s": 9441,
"text": "lt − less-than"
},
{
"code": null,
"e": 9500,
"s": 9456,
"text": "For example, observe the code given below −"
},
{
"code": null,
"e": 9622,
"s": 9500,
"text": "POST /schools*/_search\n{\n \"query\":{\n \"range\":{\n \"rating\":{\n \"gte\":3.5\n }\n }\n }\n}"
},
{
"code": null,
"e": 9686,
"s": 9622,
"text": "On running the above code, we get the response as shown below −"
},
{
"code": null,
"e": 10633,
"s": 9686,
"text": "{\n \"took\" : 24,\n \"timed_out\" : false,\n \"_shards\" : {\n \"total\" : 1,\n \"successful\" : 1,\n \"skipped\" : 0,\n \"failed\" : 0\n },\n \"hits\" : {\n \"total\" : {\n \"value\" : 1,\n \"relation\" : \"eq\"\n },\n \"max_score\" : 1.0,\n \"hits\" : [\n {\n \"_index\" : \"schools\",\n \"_type\" : \"school\",\n \"_id\" : \"4\",\n \"_score\" : 1.0,\n \"_source\" : {\n \"name\" : \"City Best School\",\n \"description\" : \"ICSE\",\n \"street\" : \"West End\",\n \"city\" : \"Meerut\",\n \"state\" : \"UP\",\n \"zip\" : \"250002\",\n \"location\" : [\n 28.9926174,\n 77.692485\n ],\n \"fees\" : 3500,\n \"tags\" : [\n \"fully computerized\"\n ],\n \"rating\" : \"4.5\"\n }\n }\n ]\n }\n}\n"
},
{
"code": null,
"e": 10694,
"s": 10633,
"text": "There exist other types of term level queries also such as −"
},
{
"code": null,
"e": 10748,
"s": 10694,
"text": "Exists query − If a certain field has non null value."
},
{
"code": null,
"e": 10802,
"s": 10748,
"text": "Exists query − If a certain field has non null value."
},
{
"code": null,
"e": 10948,
"s": 10802,
"text": "Missing query − This is completely opposite to exists query, this query searches for objects without specific fields or fields having null value."
},
{
"code": null,
"e": 11094,
"s": 10948,
"text": "Missing query − This is completely opposite to exists query, this query searches for objects without specific fields or fields having null value."
},
{
"code": null,
"e": 11190,
"s": 11094,
"text": "Wildcard or regexp query − This query uses regular expressions to find patterns in the objects."
},
{
"code": null,
"e": 11286,
"s": 11190,
"text": "Wildcard or regexp query − This query uses regular expressions to find patterns in the objects."
},
{
"code": null,
"e": 11461,
"s": 11286,
"text": "These queries are a collection of different queries merged with each other by using Boolean\noperators like and, or, not or for different indices or having function calls etc."
},
{
"code": null,
"e": 11737,
"s": 11461,
"text": "POST /schools/_search\n{\n \"query\": {\n \"bool\" : {\n \"must\" : {\n \"term\" : { \"state\" : \"UP\" }\n },\n \"filter\": {\n \"term\" : { \"fees\" : \"2200\" }\n },\n \"minimum_should_match\" : 1,\n \"boost\" : 1.0\n }\n }\n}"
},
{
"code": null,
"e": 11801,
"s": 11737,
"text": "On running the above code, we get the response as shown below −"
},
{
"code": null,
"e": 12091,
"s": 11801,
"text": "{\n \"took\" : 6,\n \"timed_out\" : false,\n \"_shards\" : {\n \"total\" : 1,\n \"successful\" : 1,\n \"skipped\" : 0,\n \"failed\" : 0\n },\n \"hits\" : {\n \"total\" : {\n \"value\" : 0,\n \"relation\" : \"eq\"\n },\n \"max_score\" : null,\n \"hits\" : [ ]\n }\n}\n"
},
{
"code": null,
"e": 12276,
"s": 12091,
"text": "These queries deal with geo locations and geo points. These queries help to find out schools\nor any other geographical object near to any location. You need to use geo point data type."
},
{
"code": null,
"e": 12416,
"s": 12276,
"text": "PUT /geo_example\n{\n \"mappings\": {\n \"properties\": {\n \"location\": {\n \"type\": \"geo_shape\"\n }\n }\n }\n}\n"
},
{
"code": null,
"e": 12480,
"s": 12416,
"text": "On running the above code, we get the response as shown below −"
},
{
"code": null,
"e": 12569,
"s": 12480,
"text": "{ \"acknowledged\" : true,\n \"shards_acknowledged\" : true,\n \"index\" : \"geo_example\"\n}\n"
},
{
"code": null,
"e": 12618,
"s": 12569,
"text": "Now we post the data in the index created above."
},
{
"code": null,
"e": 12781,
"s": 12618,
"text": "POST /geo_example/_doc?refresh\n{\n \"name\": \"Chapter One, London, UK\",\n \"location\": {\n \"type\": \"point\",\n \"coordinates\": [11.660544, 57.800286]\n }\n}\n"
},
{
"code": null,
"e": 12845,
"s": 12781,
"text": "On running the above code, we get the response as shown below −"
},
{
"code": null,
"e": 13529,
"s": 12845,
"text": "{\n \"took\" : 1,\n \"timed_out\" : false,\n \"_shards\" : {\n \"total\" : 1,\n \"successful\" : 1,\n \"skipped\" : 0,\n \"failed\" : 0\n },\n \"hits\" : {\n \"total\" : {\n \"value\" : 2,\n \"relation\" : \"eq\"\n },\n \"max_score\" : 1.0,\n \"hits\" : [\n \"_index\" : \"geo_example\",\n \"_type\" : \"_doc\",\n \"_id\" : \"hASWZ2oBbkdGzVfiXHKD\",\n \"_score\" : 1.0,\n \"_source\" : {\n \"name\" : \"Chapter One, London, UK\",\n \"location\" : {\n \"type\" : \"point\",\n \"coordinates\" : [\n 11.660544,\n 57.800286\n ]\n }\n }\n }\n }\n"
},
{
"code": null,
"e": 13562,
"s": 13529,
"text": "\n 14 Lectures \n 5 hours \n"
},
{
"code": null,
"e": 13578,
"s": 13562,
"text": " Manuj Aggarwal"
},
{
"code": null,
"e": 13611,
"s": 13578,
"text": "\n 20 Lectures \n 1 hours \n"
},
{
"code": null,
"e": 13626,
"s": 13611,
"text": " Faizan Tayyab"
},
{
"code": null,
"e": 13633,
"s": 13626,
"text": " Print"
},
{
"code": null,
"e": 13644,
"s": 13633,
"text": " Add Notes"
}
] |
Java Switch Case statement | Practice | GeeksforGeeks
|
Given an integer choice denoting the choice of the user and a list containing the single value R or two values L and B depending on the choice.
If the user's choice is 1, calculate the area of the circle having the given radius(R).
Else if choice is 2, calculate the area of the rectangle with given length(L) and breadth(B).
Example 1:
Input:
choice = 1,
R = 5
Output: 78.53981633974483
Explaination: The choice is 1.
So we have to calculate the area of the circle.
Example 2:
Input:
choice = 2,
L = 5, B = 10
Output: 50
Explaination: Here we have to calculate the
area of the rectangle.
Your Task:
You do not need to read input or print anything. Your task is to complete the function switchCase() which takes choice and a list arr[], containing the single value R or the two values L and B, as input parameters. It should return area of the desired geomatrical figure.
Note: Use Math.PI for the value of pi.
Expected Time Complexity: O(1)
Expected Auxiliary Space: O(1)
Constraints:
1 ≤ R, L, B ≤ 100
+2
badgujarsachin835 months ago
static double switchCase(int choice, List<Double> arr){
// code here
double area=0;
switch(choice){
case 1:
area = Math.PI*arr.get(0)*arr.get(0);
break;
case 2:
area=arr.get(0)*arr.get(1);
break;
}
return area;
}
-1
pankajkumarravi6 months ago
*********************** java Logic ***********
static double switchCase(int choice, List<Double> arr){ double area=0; // code here if (choice ==1) area = Math.PI*arr.get(0)*arr.get(0);// area of circle else // area of rectangle area = arr.get(0)*arr.get(1); return area;}
0
Kapil Kant Pal10 months ago
Kapil Kant Pal
class Solution{ static double switchCase(int choice, List<double> arr){ double x = 0.0; double y = 0.0;
switch(choice){
case 1 : x = Math.PI*arr.get(0)*arr.get(0); break;
case 2 : y = arr.get(0)*arr.get(1); break;
} if(choice == 1){ return x; }else{ return y; }
}}
0
Shubham Bhugra2 years ago
Shubham Bhugra
/*package whatever //do not write package name here */
import java.util.*;import java.lang.*;import java.io.*;
class GFG {public static void main (String[] args) {//codeScanner sc = new Scanner(System.in);int t = sc.nextInt();
double Area1;
while(t-->0){ int choice = sc.nextInt();
switch(choice){ case 1: int R = sc.nextInt(); Area1 =Math.PI*R*R; System.out.println(Area1); break; case 2: int L = sc.nextInt(); int B = sc.nextInt(); int Area2 = L*B; System.out.println(Area2); break;
}}
}}
0
Vikash Malakar2 years ago
Vikash Malakar
/*package whatever //do not write package name here */
import java.util.*;import java.lang.*;import java.io.*;
class GFG {public static void main (String[] args) {Scanner s = new Scanner(System.in);int R,L,B;int Area2;double Area1;int T = s.nextInt();while(T-->0){ int choice = s.nextInt(); switch(choice) { case 1: R = s.nextInt(); Area1 =Math.PI*R*R; System.out.println(Area1); break;
case 2: L = s.nextInt(); B = s.nextInt(); Area2 = L*B; System.out.println(Area2); break;
}}}}
0
Rajesh Kumar2 years ago
Rajesh Kumar
class GFG {public static void main (String[] args) { Scanner scan=new Scanner(System.in); int test=scan.nextInt(); while(test-->0){ int choice=scan.nextInt(); switch(choice){ case 1: int R=scan.nextInt(); double radius=Math.PI*R*R; System.out.println(radius); break; case 2: int L=scan.nextInt(); int W=scan.nextInt(); System.out.println(L*W); break; } } }}
0
Larisa Frolova2 years ago
Larisa Frolova
Could anyone check my code please?
https://ide.geeksforgeeks.o...
My code works good. Only thing I can't figure out is how to make user's input of the length and breadth together in one variable (space separated)?
Thanks!
0
itskshitizsh3 years ago
itskshitizsh
Inform me if anything can be improved in below code! By the way it works perfectly./*package whatever //do not write package name here */
import java.util.*;import java.lang.*;import java.io.*;
class GFG {
static Scanner scan;public static void main (String[] args) {//codescan = new Scanner(System.in);int t = scan.nextInt();while(t--!=0){ logicFun();}}
static void logicFun(){ int choice = scan.nextInt(); switch(choice) { case 1: int radius = scan.nextInt(); System.out.println(""+Math.PI*(radius)*(radius)); break; case 2: int l = scan.nextInt(); int b = scan.nextInt(); System.out.println(""+(l)*(b)); break; default: break; }}}
0
Mandar 3 years ago
Mandar
Works correctly/*package whatever //do not write package name here */
import java.util.*;import java.lang.*;import java.io.*;
class GFG {public static void main (String[] args) {Scanner sc = new Scanner(System.in);int t = sc.nextInt();while(t > 0){ t--; int val = sc.nextInt(); if(val == 1){ int r = sc.nextInt(); double area_circle = Math.PI*r*r; System.out.print(area_circle); } else if(val==2){ int l = sc.nextInt(); int b = sc.nextInt(); long area_rect = l*b; System.out.print(area_rect); } System.out.println(); }}}
0
Tanay Chauli
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": 554,
"s": 226,
"text": "Given an integer choice denoting the choice of the user and a list containing the single value R or two values L and B depending on the choice.\nIf the user's choice is 1, calculate the area of the circle having the given radius(R). \nElse if choice is 2, calculate the area of the rectangle with given length(L) and breadth(B)."
},
{
"code": null,
"e": 567,
"s": 556,
"text": "Example 1:"
},
{
"code": null,
"e": 700,
"s": 567,
"text": "Input: \nchoice = 1, \nR = 5\nOutput: 78.53981633974483\nExplaination: The choice is 1. \nSo we have to calculate the area of the circle."
},
{
"code": null,
"e": 713,
"s": 702,
"text": "Example 2:"
},
{
"code": null,
"e": 827,
"s": 713,
"text": "Input: \nchoice = 2, \nL = 5, B = 10\nOutput: 50\nExplaination: Here we have to calculate the \narea of the rectangle."
},
{
"code": null,
"e": 1151,
"s": 829,
"text": "Your Task:\nYou do not need to read input or print anything. Your task is to complete the function switchCase() which takes choice and a list arr[], containing the single value R or the two values L and B, as input parameters. It should return area of the desired geomatrical figure.\nNote: Use Math.PI for the value of pi."
},
{
"code": null,
"e": 1215,
"s": 1153,
"text": "Expected Time Complexity: O(1)\nExpected Auxiliary Space: O(1)"
},
{
"code": null,
"e": 1249,
"s": 1217,
"text": "Constraints:\n1 ≤ R, L, B ≤ 100 "
},
{
"code": null,
"e": 1252,
"s": 1249,
"text": "+2"
},
{
"code": null,
"e": 1281,
"s": 1252,
"text": "badgujarsachin835 months ago"
},
{
"code": null,
"e": 1652,
"s": 1281,
"text": "static double switchCase(int choice, List<Double> arr){\n // code here\n double area=0;\n switch(choice){\n case 1:\n area = Math.PI*arr.get(0)*arr.get(0);\n break;\n case 2:\n area=arr.get(0)*arr.get(1);\n break;\n \n }\n \n return area;\n }"
},
{
"code": null,
"e": 1655,
"s": 1652,
"text": "-1"
},
{
"code": null,
"e": 1683,
"s": 1655,
"text": "pankajkumarravi6 months ago"
},
{
"code": null,
"e": 1730,
"s": 1683,
"text": "*********************** java Logic ***********"
},
{
"code": null,
"e": 2017,
"s": 1730,
"text": "static double switchCase(int choice, List<Double> arr){ double area=0; // code here if (choice ==1) area = Math.PI*arr.get(0)*arr.get(0);// area of circle else // area of rectangle area = arr.get(0)*arr.get(1); return area;}"
},
{
"code": null,
"e": 2019,
"s": 2017,
"text": "0"
},
{
"code": null,
"e": 2047,
"s": 2019,
"text": "Kapil Kant Pal10 months ago"
},
{
"code": null,
"e": 2062,
"s": 2047,
"text": "Kapil Kant Pal"
},
{
"code": null,
"e": 2183,
"s": 2062,
"text": "class Solution{ static double switchCase(int choice, List<double> arr){ double x = 0.0; double y = 0.0;"
},
{
"code": null,
"e": 2207,
"s": 2183,
"text": " switch(choice){"
},
{
"code": null,
"e": 2291,
"s": 2207,
"text": " case 1 : x = Math.PI*arr.get(0)*arr.get(0); break;"
},
{
"code": null,
"e": 2366,
"s": 2291,
"text": " case 2 : y = arr.get(0)*arr.get(1); break;"
},
{
"code": null,
"e": 2485,
"s": 2366,
"text": " } if(choice == 1){ return x; }else{ return y; }"
},
{
"code": null,
"e": 2492,
"s": 2485,
"text": " }}"
},
{
"code": null,
"e": 2494,
"s": 2492,
"text": "0"
},
{
"code": null,
"e": 2520,
"s": 2494,
"text": "Shubham Bhugra2 years ago"
},
{
"code": null,
"e": 2535,
"s": 2520,
"text": "Shubham Bhugra"
},
{
"code": null,
"e": 2590,
"s": 2535,
"text": "/*package whatever //do not write package name here */"
},
{
"code": null,
"e": 2646,
"s": 2590,
"text": "import java.util.*;import java.lang.*;import java.io.*;"
},
{
"code": null,
"e": 2762,
"s": 2646,
"text": "class GFG {public static void main (String[] args) {//codeScanner sc = new Scanner(System.in);int t = sc.nextInt();"
},
{
"code": null,
"e": 2776,
"s": 2762,
"text": "double Area1;"
},
{
"code": null,
"e": 2821,
"s": 2776,
"text": "while(t-->0){ int choice = sc.nextInt();"
},
{
"code": null,
"e": 3140,
"s": 2821,
"text": " switch(choice){ case 1: int R = sc.nextInt(); Area1 =Math.PI*R*R; System.out.println(Area1); break; case 2: int L = sc.nextInt(); int B = sc.nextInt(); int Area2 = L*B; System.out.println(Area2); break;"
},
{
"code": null,
"e": 3147,
"s": 3140,
"text": " }}"
},
{
"code": null,
"e": 3150,
"s": 3147,
"text": "}}"
},
{
"code": null,
"e": 3152,
"s": 3150,
"text": "0"
},
{
"code": null,
"e": 3178,
"s": 3152,
"text": "Vikash Malakar2 years ago"
},
{
"code": null,
"e": 3193,
"s": 3178,
"text": "Vikash Malakar"
},
{
"code": null,
"e": 3248,
"s": 3193,
"text": "/*package whatever //do not write package name here */"
},
{
"code": null,
"e": 3304,
"s": 3248,
"text": "import java.util.*;import java.lang.*;import java.io.*;"
},
{
"code": null,
"e": 3640,
"s": 3304,
"text": "class GFG {public static void main (String[] args) {Scanner s = new Scanner(System.in);int R,L,B;int Area2;double Area1;int T = s.nextInt();while(T-->0){ int choice = s.nextInt(); switch(choice) { case 1: R = s.nextInt(); Area1 =Math.PI*R*R; System.out.println(Area1); break;"
},
{
"code": null,
"e": 3792,
"s": 3640,
"text": " case 2: L = s.nextInt(); B = s.nextInt(); Area2 = L*B; System.out.println(Area2); break;"
},
{
"code": null,
"e": 3801,
"s": 3792,
"text": " }}}}"
},
{
"code": null,
"e": 3803,
"s": 3801,
"text": "0"
},
{
"code": null,
"e": 3827,
"s": 3803,
"text": "Rajesh Kumar2 years ago"
},
{
"code": null,
"e": 3840,
"s": 3827,
"text": "Rajesh Kumar"
},
{
"code": null,
"e": 4437,
"s": 3840,
"text": "class GFG {public static void main (String[] args) { Scanner scan=new Scanner(System.in); int test=scan.nextInt(); while(test-->0){ int choice=scan.nextInt(); switch(choice){ case 1: int R=scan.nextInt(); double radius=Math.PI*R*R; System.out.println(radius); break; case 2: int L=scan.nextInt(); int W=scan.nextInt(); System.out.println(L*W); break; } } }}"
},
{
"code": null,
"e": 4439,
"s": 4437,
"text": "0"
},
{
"code": null,
"e": 4465,
"s": 4439,
"text": "Larisa Frolova2 years ago"
},
{
"code": null,
"e": 4480,
"s": 4465,
"text": "Larisa Frolova"
},
{
"code": null,
"e": 4515,
"s": 4480,
"text": "Could anyone check my code please?"
},
{
"code": null,
"e": 4546,
"s": 4515,
"text": "https://ide.geeksforgeeks.o..."
},
{
"code": null,
"e": 4694,
"s": 4546,
"text": "My code works good. Only thing I can't figure out is how to make user's input of the length and breadth together in one variable (space separated)?"
},
{
"code": null,
"e": 4702,
"s": 4694,
"text": "Thanks!"
},
{
"code": null,
"e": 4704,
"s": 4702,
"text": "0"
},
{
"code": null,
"e": 4728,
"s": 4704,
"text": "itskshitizsh3 years ago"
},
{
"code": null,
"e": 4741,
"s": 4728,
"text": "itskshitizsh"
},
{
"code": null,
"e": 4879,
"s": 4741,
"text": "Inform me if anything can be improved in below code! By the way it works perfectly./*package whatever //do not write package name here */"
},
{
"code": null,
"e": 4935,
"s": 4879,
"text": "import java.util.*;import java.lang.*;import java.io.*;"
},
{
"code": null,
"e": 4947,
"s": 4935,
"text": "class GFG {"
},
{
"code": null,
"e": 5103,
"s": 4947,
"text": " static Scanner scan;public static void main (String[] args) {//codescan = new Scanner(System.in);int t = scan.nextInt();while(t--!=0){ logicFun();}}"
},
{
"code": null,
"e": 5505,
"s": 5103,
"text": "static void logicFun(){ int choice = scan.nextInt(); switch(choice) { case 1: int radius = scan.nextInt(); System.out.println(\"\"+Math.PI*(radius)*(radius)); break; case 2: int l = scan.nextInt(); int b = scan.nextInt(); System.out.println(\"\"+(l)*(b)); break; default: break; }}}"
},
{
"code": null,
"e": 5507,
"s": 5505,
"text": "0"
},
{
"code": null,
"e": 5526,
"s": 5507,
"text": "Mandar 3 years ago"
},
{
"code": null,
"e": 5534,
"s": 5526,
"text": "Mandar "
},
{
"code": null,
"e": 5604,
"s": 5534,
"text": "Works correctly/*package whatever //do not write package name here */"
},
{
"code": null,
"e": 5660,
"s": 5604,
"text": "import java.util.*;import java.lang.*;import java.io.*;"
},
{
"code": null,
"e": 6124,
"s": 5660,
"text": "class GFG {public static void main (String[] args) {Scanner sc = new Scanner(System.in);int t = sc.nextInt();while(t > 0){ t--; int val = sc.nextInt(); if(val == 1){ int r = sc.nextInt(); double area_circle = Math.PI*r*r; System.out.print(area_circle); } else if(val==2){ int l = sc.nextInt(); int b = sc.nextInt(); long area_rect = l*b; System.out.print(area_rect); } System.out.println(); }}}"
},
{
"code": null,
"e": 6126,
"s": 6124,
"text": "0"
},
{
"code": null,
"e": 6139,
"s": 6126,
"text": "Tanay Chauli"
},
{
"code": null,
"e": 6165,
"s": 6139,
"text": "This comment was deleted."
},
{
"code": null,
"e": 6311,
"s": 6165,
"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": 6347,
"s": 6311,
"text": " Login to access your submissions. "
},
{
"code": null,
"e": 6357,
"s": 6347,
"text": "\nProblem\n"
},
{
"code": null,
"e": 6367,
"s": 6357,
"text": "\nContest\n"
},
{
"code": null,
"e": 6430,
"s": 6367,
"text": "Reset the IDE using the second button on the top right corner."
},
{
"code": null,
"e": 6578,
"s": 6430,
"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": 6786,
"s": 6578,
"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": 6892,
"s": 6786,
"text": "You can access the hints to get an idea about what is expected of you as well as the final solution code."
}
] |
Java Program to format time with DateFormat.MEDIUM
|
Use the getTimeInstance() method in Java to get the time format for the locale you have set. DateFormat.MEDIUM is a constant for medium style pattern.
Firstly, we will create a Date object −
Date dt = new Date();
DateFormat dateFormat;
Let us format time for a different locale with DateFormat.MEDIUM
dateFormat = DateFormat.getTimeInstance(DateFormat.MEDIUM, Locale.CANADA);
System.out.println("Locale CANADA = " + dateFormat.format(dt));
dateFormat = DateFormat.getTimeInstance(DateFormat.MEDIUM, Locale.ITALY);
System.out.println("Locale ITALY = " + dateFormat.format(dt));
The following is an example
Live Demo
import java.text.DateFormat;
import java.util.Date;
import java.util.Locale;
public class Demo {
public static void main(String args[]) {
Date dt = new Date();
DateFormat dateFormat;
// Displaying time with MEDIUM constant
dateFormat = DateFormat.getTimeInstance(DateFormat.MEDIUM, Locale.FRENCH);
System.out.println("Locale FRENCH = " + dateFormat.format(dt));
dateFormat = DateFormat.getTimeInstance(DateFormat.MEDIUM, Locale.GERMANY);
System.out.println("Locale GERMANY = " + dateFormat.format(dt));
dateFormat = DateFormat.getTimeInstance(DateFormat.MEDIUM, Locale.CHINESE);
System.out.println("Locale CHINESE = " + dateFormat.format(dt));
dateFormat = DateFormat.getTimeInstance(DateFormat.MEDIUM, Locale.CANADA);
System.out.println("Locale CANADA = " + dateFormat.format(dt));
dateFormat = DateFormat.getTimeInstance(DateFormat.MEDIUM, Locale.ITALY);
System.out.println("Locale ITALY = " + dateFormat.format(dt));
dateFormat = DateFormat.getTimeInstance(DateFormat.MEDIUM, Locale.TAIWAN);
System.out.println("Locale TAIWAN = " + dateFormat.format(dt));
}
}
Locale FRENCH = 09:47:50
Locale GERMANY = 09:47:50
Locale CHINESE = 9:47:50
Locale CANADA = 9:47:50 AM
Locale ITALY = 9.47.50
Locale TAIWAN = 上午 09:47:50
|
[
{
"code": null,
"e": 1213,
"s": 1062,
"text": "Use the getTimeInstance() method in Java to get the time format for the locale you have set. DateFormat.MEDIUM is a constant for medium style pattern."
},
{
"code": null,
"e": 1253,
"s": 1213,
"text": "Firstly, we will create a Date object −"
},
{
"code": null,
"e": 1298,
"s": 1253,
"text": "Date dt = new Date();\nDateFormat dateFormat;"
},
{
"code": null,
"e": 1363,
"s": 1298,
"text": "Let us format time for a different locale with DateFormat.MEDIUM"
},
{
"code": null,
"e": 1639,
"s": 1363,
"text": "dateFormat = DateFormat.getTimeInstance(DateFormat.MEDIUM, Locale.CANADA);\nSystem.out.println(\"Locale CANADA = \" + dateFormat.format(dt));\ndateFormat = DateFormat.getTimeInstance(DateFormat.MEDIUM, Locale.ITALY);\nSystem.out.println(\"Locale ITALY = \" + dateFormat.format(dt));"
},
{
"code": null,
"e": 1667,
"s": 1639,
"text": "The following is an example"
},
{
"code": null,
"e": 1678,
"s": 1667,
"text": " Live Demo"
},
{
"code": null,
"e": 2837,
"s": 1678,
"text": "import java.text.DateFormat;\nimport java.util.Date;\nimport java.util.Locale;\npublic class Demo {\n public static void main(String args[]) {\n Date dt = new Date();\n DateFormat dateFormat;\n // Displaying time with MEDIUM constant\n dateFormat = DateFormat.getTimeInstance(DateFormat.MEDIUM, Locale.FRENCH);\n System.out.println(\"Locale FRENCH = \" + dateFormat.format(dt));\n dateFormat = DateFormat.getTimeInstance(DateFormat.MEDIUM, Locale.GERMANY);\n System.out.println(\"Locale GERMANY = \" + dateFormat.format(dt));\n dateFormat = DateFormat.getTimeInstance(DateFormat.MEDIUM, Locale.CHINESE);\n System.out.println(\"Locale CHINESE = \" + dateFormat.format(dt));\n dateFormat = DateFormat.getTimeInstance(DateFormat.MEDIUM, Locale.CANADA);\n System.out.println(\"Locale CANADA = \" + dateFormat.format(dt));\n dateFormat = DateFormat.getTimeInstance(DateFormat.MEDIUM, Locale.ITALY);\n System.out.println(\"Locale ITALY = \" + dateFormat.format(dt));\n dateFormat = DateFormat.getTimeInstance(DateFormat.MEDIUM, Locale.TAIWAN);\n System.out.println(\"Locale TAIWAN = \" + dateFormat.format(dt));\n }\n}"
},
{
"code": null,
"e": 2991,
"s": 2837,
"text": "Locale FRENCH = 09:47:50\nLocale GERMANY = 09:47:50\nLocale CHINESE = 9:47:50\nLocale CANADA = 9:47:50 AM\nLocale ITALY = 9.47.50\nLocale TAIWAN = 上午 09:47:50"
}
] |
Biconnected Components - GeeksforGeeks
|
19 Jan, 2022
A biconnected component is a maximal biconnected subgraph.Biconnected Graph is already discussed here. In this article, we will see how to find biconnected component in a graph using algorithm by John Hopcroft and Robert Tarjan.
In above graph, following are the biconnected components:
4–2 3–4 3–1 2–3 1–2
8–9
8–5 7–8 5–7
6–0 5–6 1–5 0–1
10–11
Algorithm is based on Disc and Low Values discussed in Strongly Connected Components Article.Idea is to store visited edges in a stack while DFS on a graph and keep looking for Articulation Points (highlighted in above figure). As soon as an Articulation Point u is found, all edges visited while DFS from node u onwards will form one biconnected component. When DFS completes for one connected component, all edges present in stack will form a biconnected component. If there is no Articulation Point in graph, then graph is biconnected and so there will be one biconnected component which is the graph itself.
C++
Java
Python3
C#
Javascript
// A C++ program to find biconnected components in a given undirected graph#include <iostream>#include <list>#include <stack>#define NIL -1using namespace std;int count = 0;class Edge {public: int u; int v; Edge(int u, int v);};Edge::Edge(int u, int v){ this->u = u; this->v = v;} // A class that represents an directed graphclass Graph { int V; // No. of vertices int E; // No. of edges list<int>* adj; // A dynamic array of adjacency lists // A Recursive DFS based function used by BCC() void BCCUtil(int u, int disc[], int low[], list<Edge>* st, int parent[]); public: Graph(int V); // Constructor void addEdge(int v, int w); // function to add an edge to graph void BCC(); // prints strongly connected components}; Graph::Graph(int V){ this->V = V; this->E = 0; adj = new list<int>[V];} void Graph::addEdge(int v, int w){ adj[v].push_back(w); E++;} // A recursive function that finds and prints strongly connected// components using DFS traversal// u --> The vertex to be visited next// disc[] --> Stores discovery times of visited vertices// low[] -- >> earliest visited vertex (the vertex with minimum// discovery time) that can be reached from subtree// rooted with current vertex// *st -- >> To store visited edgesvoid Graph::BCCUtil(int u, int disc[], int low[], list<Edge>* st, int parent[]){ // A static variable is used for simplicity, we can avoid use // of static variable by passing a pointer. static int time = 0; // Initialize discovery time and low value disc[u] = low[u] = ++time; int children = 0; // Go through all vertices adjacent to this list<int>::iterator i; for (i = adj[u].begin(); i != adj[u].end(); ++i) { int v = *i; // v is current adjacent of 'u' // If v is not visited yet, then recur for it if (disc[v] == -1) { children++; parent[v] = u; // store the edge in stack st->push_back(Edge(u, v)); BCCUtil(v, disc, low, st, parent); // Check if the subtree rooted with 'v' has a // connection to one of the ancestors of 'u' // Case 1 -- per Strongly Connected Components Article low[u] = min(low[u], low[v]); // If u is an articulation point, // pop all edges from stack till u -- v if ((disc[u] == 1 && children > 1) || (disc[u] > 1 && low[v] >= disc[u])) { while (st->back().u != u || st->back().v != v) { cout << st->back().u << "--" << st->back().v << " "; st->pop_back(); } cout << st->back().u << "--" << st->back().v; st->pop_back(); cout << endl; count++; } } // Update low value of 'u' only of 'v' is still in stack // (i.e. it's a back edge, not cross edge). // Case 2 -- per Strongly Connected Components Article else if (v != parent[u]) { low[u] = min(low[u], disc[v]); if (disc[v] < disc[u]) { st->push_back(Edge(u, v)); } } }} // The function to do DFS traversal. It uses BCCUtil()void Graph::BCC(){ int* disc = new int[V]; int* low = new int[V]; int* parent = new int[V]; list<Edge>* st = new list<Edge>[E]; // Initialize disc and low, and parent arrays for (int i = 0; i < V; i++) { disc[i] = NIL; low[i] = NIL; parent[i] = NIL; } for (int i = 0; i < V; i++) { if (disc[i] == NIL) BCCUtil(i, disc, low, st, parent); int j = 0; // If stack is not empty, pop all edges from stack while (st->size() > 0) { j = 1; cout << st->back().u << "--" << st->back().v << " "; st->pop_back(); } if (j == 1) { cout << endl; count++; } }} // Driver program to test above functionint main(){ Graph g(12); g.addEdge(0, 1); g.addEdge(1, 0); g.addEdge(1, 2); g.addEdge(2, 1); g.addEdge(1, 3); g.addEdge(3, 1); g.addEdge(2, 3); g.addEdge(3, 2); g.addEdge(2, 4); g.addEdge(4, 2); g.addEdge(3, 4); g.addEdge(4, 3); g.addEdge(1, 5); g.addEdge(5, 1); g.addEdge(0, 6); g.addEdge(6, 0); g.addEdge(5, 6); g.addEdge(6, 5); g.addEdge(5, 7); g.addEdge(7, 5); g.addEdge(5, 8); g.addEdge(8, 5); g.addEdge(7, 8); g.addEdge(8, 7); g.addEdge(8, 9); g.addEdge(9, 8); g.addEdge(10, 11); g.addEdge(11, 10); g.BCC(); cout << "Above are " << count << " biconnected components in graph"; return 0;}
// A Java program to find biconnected components in a given// undirected graphimport java.io.*;import java.util.*; // This class represents a directed graph using adjacency// list representationclass Graph { private int V, E; // No. of vertices & Edges respectively private LinkedList<Integer> adj[]; // Adjacency List // Count is number of biconnected components. time is // used to find discovery times static int count = 0, time = 0; class Edge { int u; int v; Edge(int u, int v) { this.u = u; this.v = v; } }; // Constructor Graph(int v) { V = v; E = 0; adj = new LinkedList[v]; for (int i = 0; i < v; ++i) adj[i] = new LinkedList(); } // Function to add an edge into the graph void addEdge(int v, int w) { adj[v].add(w); E++; } // A recursive function that finds and prints strongly connected // components using DFS traversal // u --> The vertex to be visited next // disc[] --> Stores discovery times of visited vertices // low[] -- >> earliest visited vertex (the vertex with minimum // discovery time) that can be reached from subtree // rooted with current vertex // *st -- >> To store visited edges void BCCUtil(int u, int disc[], int low[], LinkedList<Edge> st, int parent[]) { // Initialize discovery time and low value disc[u] = low[u] = ++time; int children = 0; // Go through all vertices adjacent to this Iterator<Integer> it = adj[u].iterator(); while (it.hasNext()) { int v = it.next(); // v is current adjacent of 'u' // If v is not visited yet, then recur for it if (disc[v] == -1) { children++; parent[v] = u; // store the edge in stack st.add(new Edge(u, v)); BCCUtil(v, disc, low, st, parent); // Check if the subtree rooted with 'v' has a // connection to one of the ancestors of 'u' // Case 1 -- per Strongly Connected Components Article if (low[u] > low[v]) low[u] = low[v]; // If u is an articulation point, // pop all edges from stack till u -- v if ((disc[u] == 1 && children > 1) || (disc[u] > 1 && low[v] >= disc[u])) { while (st.getLast().u != u || st.getLast().v != v) { System.out.print(st.getLast().u + "--" + st.getLast().v + " "); st.removeLast(); } System.out.println(st.getLast().u + "--" + st.getLast().v + " "); st.removeLast(); count++; } } // Update low value of 'u' only if 'v' is still in stack // (i.e. it's a back edge, not cross edge). // Case 2 -- per Strongly Connected Components Article else if (v != parent[u] && disc[v] < disc[u] ) { if (low[u] > disc[v]) low[u] = disc[v]; st.add(new Edge(u, v)); } } } // The function to do DFS traversal. It uses BCCUtil() void BCC() { int disc[] = new int[V]; int low[] = new int[V]; int parent[] = new int[V]; LinkedList<Edge> st = new LinkedList<Edge>(); // Initialize disc and low, and parent arrays for (int i = 0; i < V; i++) { disc[i] = -1; low[i] = -1; parent[i] = -1; } for (int i = 0; i < V; i++) { if (disc[i] == -1) BCCUtil(i, disc, low, st, parent); int j = 0; // If stack is not empty, pop all edges from stack while (st.size() > 0) { j = 1; System.out.print(st.getLast().u + "--" + st.getLast().v + " "); st.removeLast(); } if (j == 1) { System.out.println(); count++; } } } public static void main(String args[]) { Graph g = new Graph(12); g.addEdge(0, 1); g.addEdge(1, 0); g.addEdge(1, 2); g.addEdge(2, 1); g.addEdge(1, 3); g.addEdge(3, 1); g.addEdge(2, 3); g.addEdge(3, 2); g.addEdge(2, 4); g.addEdge(4, 2); g.addEdge(3, 4); g.addEdge(4, 3); g.addEdge(1, 5); g.addEdge(5, 1); g.addEdge(0, 6); g.addEdge(6, 0); g.addEdge(5, 6); g.addEdge(6, 5); g.addEdge(5, 7); g.addEdge(7, 5); g.addEdge(5, 8); g.addEdge(8, 5); g.addEdge(7, 8); g.addEdge(8, 7); g.addEdge(8, 9); g.addEdge(9, 8); g.addEdge(10, 11); g.addEdge(11, 10); g.BCC(); System.out.println("Above are " + g.count + " biconnected components in graph"); }}// This code is contributed by Aakash Hasija
# Python program to find biconnected components in a given# undirected graph# Complexity : O(V + E) from collections import defaultdict # This class represents an directed graph# using adjacency list representationclass Graph: def __init__(self, vertices): # No. of vertices self.V = vertices # default dictionary to store graph self.graph = defaultdict(list) # time is used to find discovery times self.Time = 0 # Count is number of biconnected components self.count = 0 # function to add an edge to graph def addEdge(self, u, v): self.graph[u].append(v) self.graph[v].append(u) '''A recursive function that finds and prints strongly connected components using DFS traversal u --> The vertex to be visited next disc[] --> Stores discovery times of visited vertices low[] -- >> earliest visited vertex (the vertex with minimum discovery time) that can be reached from subtree rooted with current vertex st -- >> To store visited edges''' def BCCUtil(self, u, parent, low, disc, st): # Count of children in current node children = 0 # Initialize discovery time and low value disc[u] = self.Time low[u] = self.Time self.Time += 1 # Recur for all the vertices adjacent to this vertex for v in self.graph[u]: # If v is not visited yet, then make it a child of u # in DFS tree and recur for it if disc[v] == -1 : parent[v] = u children += 1 st.append((u, v)) # store the edge in stack self.BCCUtil(v, parent, low, disc, st) # Check if the subtree rooted with v has a connection to # one of the ancestors of u # Case 1 -- per Strongly Connected Components Article low[u] = min(low[u], low[v]) # If u is an articulation point, pop # all edges from stack till (u, v) if parent[u] == -1 and children > 1 or parent[u] != -1 and low[v] >= disc[u]: self.count += 1 # increment count w = -1 while w != (u, v): w = st.pop() print(w,end=" ") print() elif v != parent[u] and low[u] > disc[v]: '''Update low value of 'u' only of 'v' is still in stack (i.e. it's a back edge, not cross edge). Case 2 -- per Strongly Connected Components Article''' low[u] = min(low [u], disc[v]) st.append((u, v)) # The function to do DFS traversal. # It uses recursive BCCUtil() def BCC(self): # Initialize disc and low, and parent arrays disc = [-1] * (self.V) low = [-1] * (self.V) parent = [-1] * (self.V) st = [] # Call the recursive helper function to # find articulation points # in DFS tree rooted with vertex 'i' for i in range(self.V): if disc[i] == -1: self.BCCUtil(i, parent, low, disc, st) # If stack is not empty, pop all edges from stack if st: self.count = self.count + 1 while st: w = st.pop() print(w,end=" ") print () # Create a graph given in the above diagram g = Graph(12)g.addEdge(0, 1)g.addEdge(1, 2)g.addEdge(1, 3)g.addEdge(2, 3)g.addEdge(2, 4)g.addEdge(3, 4)g.addEdge(1, 5)g.addEdge(0, 6)g.addEdge(5, 6)g.addEdge(5, 7)g.addEdge(5, 8)g.addEdge(7, 8)g.addEdge(8, 9)g.addEdge(10, 11) g.BCC();print ("Above are % d biconnected components in graph" %(g.count)); # This code is contributed by Neelam Yadav
// A C# program to find biconnected components in a given// undirected graphusing System;using System.Collections.Generic; // This class represents a directed graph using adjacency// list representationpublic class Graph{ private int V, E; // No. of vertices & Edges respectively private List<int> []adj; // Adjacency List // Count is number of biconnected components. time is // used to find discovery times int count = 0, time = 0; class Edge { public int u; public int v; public Edge(int u, int v) { this.u = u; this.v = v; } }; // Constructor public Graph(int v) { V = v; E = 0; adj = new List<int>[v]; for (int i = 0; i < v; ++i) adj[i] = new List<int>(); } // Function to add an edge into the graph void addEdge(int v, int w) { adj[v].Add(w); E++; } // A recursive function that finds and prints strongly connected // components using DFS traversal // u --> The vertex to be visited next // disc[] --> Stores discovery times of visited vertices // low[] -- >> earliest visited vertex (the vertex with minimum // discovery time) that can be reached from subtree // rooted with current vertex // *st -- >> To store visited edges void BCCUtil(int u, int []disc, int []low, List<Edge> st, int []parent) { // Initialize discovery time and low value disc[u] = low[u] = ++time; int children = 0; // Go through all vertices adjacent to this foreach(int it in adj[u]) { int v = it; // v is current adjacent of 'u' // If v is not visited yet, then recur for it if (disc[v] == -1) { children++; parent[v] = u; // store the edge in stack st.Add(new Edge(u, v)); BCCUtil(v, disc, low, st, parent); // Check if the subtree rooted with 'v' has a // connection to one of the ancestors of 'u' // Case 1 -- per Strongly Connected Components Article if (low[u] > low[v]) low[u] = low[v]; // If u is an articulation point, // pop all edges from stack till u -- v if ((disc[u] == 1 && children > 1) || (disc[u] > 1 && low[v] >= disc[u])) { while (st[st.Count-1].u != u || st[st.Count-1].v != v) { Console.Write(st[st.Count - 1].u + "--" + st[st.Count - 1].v + " "); st.RemoveAt(st.Count - 1); } Console.WriteLine(st[st.Count - 1].u + "--" + st[st.Count - 1].v + " "); st.RemoveAt(st.Count - 1); count++; } } // Update low value of 'u' only if 'v' is still in stack // (i.e. it's a back edge, not cross edge). // Case 2 -- per Strongly Connected Components Article else if (v != parent[u] && disc[v] < disc[u] ) { if (low[u] > disc[v]) low[u] = disc[v]; st.Add(new Edge(u, v)); } } } // The function to do DFS traversal. It uses BCCUtil() void BCC() { int []disc = new int[V]; int []low = new int[V]; int []parent = new int[V]; List<Edge> st = new List<Edge>(); // Initialize disc and low, and parent arrays for (int i = 0; i < V; i++) { disc[i] = -1; low[i] = -1; parent[i] = -1; } for (int i = 0; i < V; i++) { if (disc[i] == -1) BCCUtil(i, disc, low, st, parent); int j = 0; // If stack is not empty, pop all edges from stack while (st.Count > 0) { j = 1; Console.Write(st[st.Count - 1].u + "--" + st[st.Count - 1].v + " "); st.RemoveAt(st.Count - 1); } if (j == 1) { Console.WriteLine(); count++; } } } // Driver code public static void Main(String []args) { Graph g = new Graph(12); g.addEdge(0, 1); g.addEdge(1, 0); g.addEdge(1, 2); g.addEdge(2, 1); g.addEdge(1, 3); g.addEdge(3, 1); g.addEdge(2, 3); g.addEdge(3, 2); g.addEdge(2, 4); g.addEdge(4, 2); g.addEdge(3, 4); g.addEdge(4, 3); g.addEdge(1, 5); g.addEdge(5, 1); g.addEdge(0, 6); g.addEdge(6, 0); g.addEdge(5, 6); g.addEdge(6, 5); g.addEdge(5, 7); g.addEdge(7, 5); g.addEdge(5, 8); g.addEdge(8, 5); g.addEdge(7, 8); g.addEdge(8, 7); g.addEdge(8, 9); g.addEdge(9, 8); g.addEdge(10, 11); g.addEdge(11, 10); g.BCC(); Console.WriteLine("Above are " + g.count + " biconnected components in graph"); }} // This code is contributed by PrinciRaj1992
<script>// A Javascript program to find biconnected components in a given// undirected graph class Edge{ constructor(u,v) { this.u = u; this.v = v; }} // This class represents a directed graph using adjacency// list representationclass Graph{ // Constructor constructor(v) { this.count=0; this.time = 0; this.V = v; this.E = 0; this.adj = new Array(v); for (let i = 0; i < v; ++i) this.adj[i] = []; } // Function to add an edge into the graph addEdge(v,w) { this.adj[v].push(w); this.E++; } // A recursive function that finds and prints strongly connected // components using DFS traversal // u --> The vertex to be visited next // disc[] --> Stores discovery times of visited vertices // low[] -- >> earliest visited vertex (the vertex with minimum // discovery time) that can be reached from subtree // rooted with current vertex // *st -- >> To store visited edges BCCUtil(u,disc,low,st,parent) { // Initialize discovery time and low value disc[u] = low[u] = ++this.time; let children = 0; // Go through all vertices adjacent to this for(let it of this.adj[u].values()) { let v = it; // v is current adjacent of 'u' // If v is not visited yet, then recur for it if (disc[v] == -1) { children++; parent[v] = u; // store the edge in stack st.push(new Edge(u, v)); this.BCCUtil(v, disc, low, st, parent); // Check if the subtree rooted with 'v' has a // connection to one of the ancestors of 'u' // Case 1 -- per Strongly Connected Components Article if (low[u] > low[v]) low[u] = low[v]; // If u is an articulation point, // pop all edges from stack till u -- v if ((disc[u] == 1 && children > 1) || (disc[u] > 1 && low[v] >= disc[u])) { while (st[st.length-1].u != u || st[st.length-1].v != v) { document.write(st[st.length-1].u + "--" + st[st.length-1].v + " "); st.pop(); } document.write(st[st.length-1].u + "--" + st[st.length-1].v + " <br>"); st.pop(); this.count++; } } // Update low value of 'u' only if 'v' is still in stack // (i.e. it's a back edge, not cross edge). // Case 2 -- per Strongly Connected Components Article else if (v != parent[u] && disc[v] < disc[u] ) { if (low[u] > disc[v]) low[u] = disc[v]; st.push(new Edge(u, v)); } } } // The function to do DFS traversal. It uses BCCUtil() BCC() { let disc = new Array(this.V); let low = new Array(this.V); let parent = new Array(this.V); let st = []; // Initialize disc and low, and parent arrays for (let i = 0; i < this.V; i++) { disc[i] = -1; low[i] = -1; parent[i] = -1; } for (let i = 0; i < this.V; i++) { if (disc[i] == -1) this.BCCUtil(i, disc, low, st, parent); let j = 0; // If stack is not empty, pop all edges from stack while (st.length > 0) { j = 1; document.write(st[st.length-1].u + "--" + st[st.length-1].v + " "); st.pop(); } if (j == 1) { document.write("<br>"); this.count++; } }}} let g = new Graph(12);g.addEdge(0, 1);g.addEdge(1, 0);g.addEdge(1, 2);g.addEdge(2, 1);g.addEdge(1, 3);g.addEdge(3, 1);g.addEdge(2, 3);g.addEdge(3, 2);g.addEdge(2, 4);g.addEdge(4, 2);g.addEdge(3, 4);g.addEdge(4, 3);g.addEdge(1, 5);g.addEdge(5, 1);g.addEdge(0, 6);g.addEdge(6, 0);g.addEdge(5, 6);g.addEdge(6, 5);g.addEdge(5, 7);g.addEdge(7, 5);g.addEdge(5, 8);g.addEdge(8, 5);g.addEdge(7, 8);g.addEdge(8, 7);g.addEdge(8, 9);g.addEdge(9, 8);g.addEdge(10, 11);g.addEdge(11, 10); g.BCC(); document.write("Above are " + g.count + " biconnected components in graph"); // This code is contributed by avanitrachhadiya2155</script>
Output:
4--2 3--4 3--1 2--3 1--2
8--9
8--5 7--8 5--7
6--0 5--6 1--5 0--1
10--11
Above are 5 biconnected components in graph
This article is contributed by Anurag Singh. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above
VismayMalondkar
spattk
princiraj1992
avanitrachhadiya2155
amartyaghoshgfg
graph-connectivity
Graph
Graph
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Topological Sorting
Detect Cycle in a Directed Graph
Disjoint Set (Or Union-Find) | Set 1 (Detect Cycle in an Undirected Graph)
Travelling Salesman Problem | Set 1 (Naive and Dynamic Programming)
Check whether a given graph is Bipartite or not
Ford-Fulkerson Algorithm for Maximum Flow Problem
Traveling Salesman Problem (TSP) Implementation
Detect cycle in an undirected graph
Shortest path in an unweighted graph
Union-Find Algorithm | Set 2 (Union By Rank and Path Compression)
|
[
{
"code": null,
"e": 25066,
"s": 25038,
"text": "\n19 Jan, 2022"
},
{
"code": null,
"e": 25296,
"s": 25066,
"text": "A biconnected component is a maximal biconnected subgraph.Biconnected Graph is already discussed here. In this article, we will see how to find biconnected component in a graph using algorithm by John Hopcroft and Robert Tarjan. "
},
{
"code": null,
"e": 25356,
"s": 25296,
"text": "In above graph, following are the biconnected components: "
},
{
"code": null,
"e": 25376,
"s": 25356,
"text": "4–2 3–4 3–1 2–3 1–2"
},
{
"code": null,
"e": 25380,
"s": 25376,
"text": "8–9"
},
{
"code": null,
"e": 25392,
"s": 25380,
"text": "8–5 7–8 5–7"
},
{
"code": null,
"e": 25408,
"s": 25392,
"text": "6–0 5–6 1–5 0–1"
},
{
"code": null,
"e": 25414,
"s": 25408,
"text": "10–11"
},
{
"code": null,
"e": 26027,
"s": 25414,
"text": "Algorithm is based on Disc and Low Values discussed in Strongly Connected Components Article.Idea is to store visited edges in a stack while DFS on a graph and keep looking for Articulation Points (highlighted in above figure). As soon as an Articulation Point u is found, all edges visited while DFS from node u onwards will form one biconnected component. When DFS completes for one connected component, all edges present in stack will form a biconnected component. If there is no Articulation Point in graph, then graph is biconnected and so there will be one biconnected component which is the graph itself. "
},
{
"code": null,
"e": 26031,
"s": 26027,
"text": "C++"
},
{
"code": null,
"e": 26036,
"s": 26031,
"text": "Java"
},
{
"code": null,
"e": 26044,
"s": 26036,
"text": "Python3"
},
{
"code": null,
"e": 26047,
"s": 26044,
"text": "C#"
},
{
"code": null,
"e": 26058,
"s": 26047,
"text": "Javascript"
},
{
"code": "// A C++ program to find biconnected components in a given undirected graph#include <iostream>#include <list>#include <stack>#define NIL -1using namespace std;int count = 0;class Edge {public: int u; int v; Edge(int u, int v);};Edge::Edge(int u, int v){ this->u = u; this->v = v;} // A class that represents an directed graphclass Graph { int V; // No. of vertices int E; // No. of edges list<int>* adj; // A dynamic array of adjacency lists // A Recursive DFS based function used by BCC() void BCCUtil(int u, int disc[], int low[], list<Edge>* st, int parent[]); public: Graph(int V); // Constructor void addEdge(int v, int w); // function to add an edge to graph void BCC(); // prints strongly connected components}; Graph::Graph(int V){ this->V = V; this->E = 0; adj = new list<int>[V];} void Graph::addEdge(int v, int w){ adj[v].push_back(w); E++;} // A recursive function that finds and prints strongly connected// components using DFS traversal// u --> The vertex to be visited next// disc[] --> Stores discovery times of visited vertices// low[] -- >> earliest visited vertex (the vertex with minimum// discovery time) that can be reached from subtree// rooted with current vertex// *st -- >> To store visited edgesvoid Graph::BCCUtil(int u, int disc[], int low[], list<Edge>* st, int parent[]){ // A static variable is used for simplicity, we can avoid use // of static variable by passing a pointer. static int time = 0; // Initialize discovery time and low value disc[u] = low[u] = ++time; int children = 0; // Go through all vertices adjacent to this list<int>::iterator i; for (i = adj[u].begin(); i != adj[u].end(); ++i) { int v = *i; // v is current adjacent of 'u' // If v is not visited yet, then recur for it if (disc[v] == -1) { children++; parent[v] = u; // store the edge in stack st->push_back(Edge(u, v)); BCCUtil(v, disc, low, st, parent); // Check if the subtree rooted with 'v' has a // connection to one of the ancestors of 'u' // Case 1 -- per Strongly Connected Components Article low[u] = min(low[u], low[v]); // If u is an articulation point, // pop all edges from stack till u -- v if ((disc[u] == 1 && children > 1) || (disc[u] > 1 && low[v] >= disc[u])) { while (st->back().u != u || st->back().v != v) { cout << st->back().u << \"--\" << st->back().v << \" \"; st->pop_back(); } cout << st->back().u << \"--\" << st->back().v; st->pop_back(); cout << endl; count++; } } // Update low value of 'u' only of 'v' is still in stack // (i.e. it's a back edge, not cross edge). // Case 2 -- per Strongly Connected Components Article else if (v != parent[u]) { low[u] = min(low[u], disc[v]); if (disc[v] < disc[u]) { st->push_back(Edge(u, v)); } } }} // The function to do DFS traversal. It uses BCCUtil()void Graph::BCC(){ int* disc = new int[V]; int* low = new int[V]; int* parent = new int[V]; list<Edge>* st = new list<Edge>[E]; // Initialize disc and low, and parent arrays for (int i = 0; i < V; i++) { disc[i] = NIL; low[i] = NIL; parent[i] = NIL; } for (int i = 0; i < V; i++) { if (disc[i] == NIL) BCCUtil(i, disc, low, st, parent); int j = 0; // If stack is not empty, pop all edges from stack while (st->size() > 0) { j = 1; cout << st->back().u << \"--\" << st->back().v << \" \"; st->pop_back(); } if (j == 1) { cout << endl; count++; } }} // Driver program to test above functionint main(){ Graph g(12); g.addEdge(0, 1); g.addEdge(1, 0); g.addEdge(1, 2); g.addEdge(2, 1); g.addEdge(1, 3); g.addEdge(3, 1); g.addEdge(2, 3); g.addEdge(3, 2); g.addEdge(2, 4); g.addEdge(4, 2); g.addEdge(3, 4); g.addEdge(4, 3); g.addEdge(1, 5); g.addEdge(5, 1); g.addEdge(0, 6); g.addEdge(6, 0); g.addEdge(5, 6); g.addEdge(6, 5); g.addEdge(5, 7); g.addEdge(7, 5); g.addEdge(5, 8); g.addEdge(8, 5); g.addEdge(7, 8); g.addEdge(8, 7); g.addEdge(8, 9); g.addEdge(9, 8); g.addEdge(10, 11); g.addEdge(11, 10); g.BCC(); cout << \"Above are \" << count << \" biconnected components in graph\"; return 0;}",
"e": 30731,
"s": 26058,
"text": null
},
{
"code": "// A Java program to find biconnected components in a given// undirected graphimport java.io.*;import java.util.*; // This class represents a directed graph using adjacency// list representationclass Graph { private int V, E; // No. of vertices & Edges respectively private LinkedList<Integer> adj[]; // Adjacency List // Count is number of biconnected components. time is // used to find discovery times static int count = 0, time = 0; class Edge { int u; int v; Edge(int u, int v) { this.u = u; this.v = v; } }; // Constructor Graph(int v) { V = v; E = 0; adj = new LinkedList[v]; for (int i = 0; i < v; ++i) adj[i] = new LinkedList(); } // Function to add an edge into the graph void addEdge(int v, int w) { adj[v].add(w); E++; } // A recursive function that finds and prints strongly connected // components using DFS traversal // u --> The vertex to be visited next // disc[] --> Stores discovery times of visited vertices // low[] -- >> earliest visited vertex (the vertex with minimum // discovery time) that can be reached from subtree // rooted with current vertex // *st -- >> To store visited edges void BCCUtil(int u, int disc[], int low[], LinkedList<Edge> st, int parent[]) { // Initialize discovery time and low value disc[u] = low[u] = ++time; int children = 0; // Go through all vertices adjacent to this Iterator<Integer> it = adj[u].iterator(); while (it.hasNext()) { int v = it.next(); // v is current adjacent of 'u' // If v is not visited yet, then recur for it if (disc[v] == -1) { children++; parent[v] = u; // store the edge in stack st.add(new Edge(u, v)); BCCUtil(v, disc, low, st, parent); // Check if the subtree rooted with 'v' has a // connection to one of the ancestors of 'u' // Case 1 -- per Strongly Connected Components Article if (low[u] > low[v]) low[u] = low[v]; // If u is an articulation point, // pop all edges from stack till u -- v if ((disc[u] == 1 && children > 1) || (disc[u] > 1 && low[v] >= disc[u])) { while (st.getLast().u != u || st.getLast().v != v) { System.out.print(st.getLast().u + \"--\" + st.getLast().v + \" \"); st.removeLast(); } System.out.println(st.getLast().u + \"--\" + st.getLast().v + \" \"); st.removeLast(); count++; } } // Update low value of 'u' only if 'v' is still in stack // (i.e. it's a back edge, not cross edge). // Case 2 -- per Strongly Connected Components Article else if (v != parent[u] && disc[v] < disc[u] ) { if (low[u] > disc[v]) low[u] = disc[v]; st.add(new Edge(u, v)); } } } // The function to do DFS traversal. It uses BCCUtil() void BCC() { int disc[] = new int[V]; int low[] = new int[V]; int parent[] = new int[V]; LinkedList<Edge> st = new LinkedList<Edge>(); // Initialize disc and low, and parent arrays for (int i = 0; i < V; i++) { disc[i] = -1; low[i] = -1; parent[i] = -1; } for (int i = 0; i < V; i++) { if (disc[i] == -1) BCCUtil(i, disc, low, st, parent); int j = 0; // If stack is not empty, pop all edges from stack while (st.size() > 0) { j = 1; System.out.print(st.getLast().u + \"--\" + st.getLast().v + \" \"); st.removeLast(); } if (j == 1) { System.out.println(); count++; } } } public static void main(String args[]) { Graph g = new Graph(12); g.addEdge(0, 1); g.addEdge(1, 0); g.addEdge(1, 2); g.addEdge(2, 1); g.addEdge(1, 3); g.addEdge(3, 1); g.addEdge(2, 3); g.addEdge(3, 2); g.addEdge(2, 4); g.addEdge(4, 2); g.addEdge(3, 4); g.addEdge(4, 3); g.addEdge(1, 5); g.addEdge(5, 1); g.addEdge(0, 6); g.addEdge(6, 0); g.addEdge(5, 6); g.addEdge(6, 5); g.addEdge(5, 7); g.addEdge(7, 5); g.addEdge(5, 8); g.addEdge(8, 5); g.addEdge(7, 8); g.addEdge(8, 7); g.addEdge(8, 9); g.addEdge(9, 8); g.addEdge(10, 11); g.addEdge(11, 10); g.BCC(); System.out.println(\"Above are \" + g.count + \" biconnected components in graph\"); }}// This code is contributed by Aakash Hasija",
"e": 35774,
"s": 30731,
"text": null
},
{
"code": "# Python program to find biconnected components in a given# undirected graph# Complexity : O(V + E) from collections import defaultdict # This class represents an directed graph# using adjacency list representationclass Graph: def __init__(self, vertices): # No. of vertices self.V = vertices # default dictionary to store graph self.graph = defaultdict(list) # time is used to find discovery times self.Time = 0 # Count is number of biconnected components self.count = 0 # function to add an edge to graph def addEdge(self, u, v): self.graph[u].append(v) self.graph[v].append(u) '''A recursive function that finds and prints strongly connected components using DFS traversal u --> The vertex to be visited next disc[] --> Stores discovery times of visited vertices low[] -- >> earliest visited vertex (the vertex with minimum discovery time) that can be reached from subtree rooted with current vertex st -- >> To store visited edges''' def BCCUtil(self, u, parent, low, disc, st): # Count of children in current node children = 0 # Initialize discovery time and low value disc[u] = self.Time low[u] = self.Time self.Time += 1 # Recur for all the vertices adjacent to this vertex for v in self.graph[u]: # If v is not visited yet, then make it a child of u # in DFS tree and recur for it if disc[v] == -1 : parent[v] = u children += 1 st.append((u, v)) # store the edge in stack self.BCCUtil(v, parent, low, disc, st) # Check if the subtree rooted with v has a connection to # one of the ancestors of u # Case 1 -- per Strongly Connected Components Article low[u] = min(low[u], low[v]) # If u is an articulation point, pop # all edges from stack till (u, v) if parent[u] == -1 and children > 1 or parent[u] != -1 and low[v] >= disc[u]: self.count += 1 # increment count w = -1 while w != (u, v): w = st.pop() print(w,end=\" \") print() elif v != parent[u] and low[u] > disc[v]: '''Update low value of 'u' only of 'v' is still in stack (i.e. it's a back edge, not cross edge). Case 2 -- per Strongly Connected Components Article''' low[u] = min(low [u], disc[v]) st.append((u, v)) # The function to do DFS traversal. # It uses recursive BCCUtil() def BCC(self): # Initialize disc and low, and parent arrays disc = [-1] * (self.V) low = [-1] * (self.V) parent = [-1] * (self.V) st = [] # Call the recursive helper function to # find articulation points # in DFS tree rooted with vertex 'i' for i in range(self.V): if disc[i] == -1: self.BCCUtil(i, parent, low, disc, st) # If stack is not empty, pop all edges from stack if st: self.count = self.count + 1 while st: w = st.pop() print(w,end=\" \") print () # Create a graph given in the above diagram g = Graph(12)g.addEdge(0, 1)g.addEdge(1, 2)g.addEdge(1, 3)g.addEdge(2, 3)g.addEdge(2, 4)g.addEdge(3, 4)g.addEdge(1, 5)g.addEdge(0, 6)g.addEdge(5, 6)g.addEdge(5, 7)g.addEdge(5, 8)g.addEdge(7, 8)g.addEdge(8, 9)g.addEdge(10, 11) g.BCC();print (\"Above are % d biconnected components in graph\" %(g.count)); # This code is contributed by Neelam Yadav",
"e": 39647,
"s": 35774,
"text": null
},
{
"code": "// A C# program to find biconnected components in a given// undirected graphusing System;using System.Collections.Generic; // This class represents a directed graph using adjacency// list representationpublic class Graph{ private int V, E; // No. of vertices & Edges respectively private List<int> []adj; // Adjacency List // Count is number of biconnected components. time is // used to find discovery times int count = 0, time = 0; class Edge { public int u; public int v; public Edge(int u, int v) { this.u = u; this.v = v; } }; // Constructor public Graph(int v) { V = v; E = 0; adj = new List<int>[v]; for (int i = 0; i < v; ++i) adj[i] = new List<int>(); } // Function to add an edge into the graph void addEdge(int v, int w) { adj[v].Add(w); E++; } // A recursive function that finds and prints strongly connected // components using DFS traversal // u --> The vertex to be visited next // disc[] --> Stores discovery times of visited vertices // low[] -- >> earliest visited vertex (the vertex with minimum // discovery time) that can be reached from subtree // rooted with current vertex // *st -- >> To store visited edges void BCCUtil(int u, int []disc, int []low, List<Edge> st, int []parent) { // Initialize discovery time and low value disc[u] = low[u] = ++time; int children = 0; // Go through all vertices adjacent to this foreach(int it in adj[u]) { int v = it; // v is current adjacent of 'u' // If v is not visited yet, then recur for it if (disc[v] == -1) { children++; parent[v] = u; // store the edge in stack st.Add(new Edge(u, v)); BCCUtil(v, disc, low, st, parent); // Check if the subtree rooted with 'v' has a // connection to one of the ancestors of 'u' // Case 1 -- per Strongly Connected Components Article if (low[u] > low[v]) low[u] = low[v]; // If u is an articulation point, // pop all edges from stack till u -- v if ((disc[u] == 1 && children > 1) || (disc[u] > 1 && low[v] >= disc[u])) { while (st[st.Count-1].u != u || st[st.Count-1].v != v) { Console.Write(st[st.Count - 1].u + \"--\" + st[st.Count - 1].v + \" \"); st.RemoveAt(st.Count - 1); } Console.WriteLine(st[st.Count - 1].u + \"--\" + st[st.Count - 1].v + \" \"); st.RemoveAt(st.Count - 1); count++; } } // Update low value of 'u' only if 'v' is still in stack // (i.e. it's a back edge, not cross edge). // Case 2 -- per Strongly Connected Components Article else if (v != parent[u] && disc[v] < disc[u] ) { if (low[u] > disc[v]) low[u] = disc[v]; st.Add(new Edge(u, v)); } } } // The function to do DFS traversal. It uses BCCUtil() void BCC() { int []disc = new int[V]; int []low = new int[V]; int []parent = new int[V]; List<Edge> st = new List<Edge>(); // Initialize disc and low, and parent arrays for (int i = 0; i < V; i++) { disc[i] = -1; low[i] = -1; parent[i] = -1; } for (int i = 0; i < V; i++) { if (disc[i] == -1) BCCUtil(i, disc, low, st, parent); int j = 0; // If stack is not empty, pop all edges from stack while (st.Count > 0) { j = 1; Console.Write(st[st.Count - 1].u + \"--\" + st[st.Count - 1].v + \" \"); st.RemoveAt(st.Count - 1); } if (j == 1) { Console.WriteLine(); count++; } } } // Driver code public static void Main(String []args) { Graph g = new Graph(12); g.addEdge(0, 1); g.addEdge(1, 0); g.addEdge(1, 2); g.addEdge(2, 1); g.addEdge(1, 3); g.addEdge(3, 1); g.addEdge(2, 3); g.addEdge(3, 2); g.addEdge(2, 4); g.addEdge(4, 2); g.addEdge(3, 4); g.addEdge(4, 3); g.addEdge(1, 5); g.addEdge(5, 1); g.addEdge(0, 6); g.addEdge(6, 0); g.addEdge(5, 6); g.addEdge(6, 5); g.addEdge(5, 7); g.addEdge(7, 5); g.addEdge(5, 8); g.addEdge(8, 5); g.addEdge(7, 8); g.addEdge(8, 7); g.addEdge(8, 9); g.addEdge(9, 8); g.addEdge(10, 11); g.addEdge(11, 10); g.BCC(); Console.WriteLine(\"Above are \" + g.count + \" biconnected components in graph\"); }} // This code is contributed by PrinciRaj1992",
"e": 44982,
"s": 39647,
"text": null
},
{
"code": "<script>// A Javascript program to find biconnected components in a given// undirected graph class Edge{ constructor(u,v) { this.u = u; this.v = v; }} // This class represents a directed graph using adjacency// list representationclass Graph{ // Constructor constructor(v) { this.count=0; this.time = 0; this.V = v; this.E = 0; this.adj = new Array(v); for (let i = 0; i < v; ++i) this.adj[i] = []; } // Function to add an edge into the graph addEdge(v,w) { this.adj[v].push(w); this.E++; } // A recursive function that finds and prints strongly connected // components using DFS traversal // u --> The vertex to be visited next // disc[] --> Stores discovery times of visited vertices // low[] -- >> earliest visited vertex (the vertex with minimum // discovery time) that can be reached from subtree // rooted with current vertex // *st -- >> To store visited edges BCCUtil(u,disc,low,st,parent) { // Initialize discovery time and low value disc[u] = low[u] = ++this.time; let children = 0; // Go through all vertices adjacent to this for(let it of this.adj[u].values()) { let v = it; // v is current adjacent of 'u' // If v is not visited yet, then recur for it if (disc[v] == -1) { children++; parent[v] = u; // store the edge in stack st.push(new Edge(u, v)); this.BCCUtil(v, disc, low, st, parent); // Check if the subtree rooted with 'v' has a // connection to one of the ancestors of 'u' // Case 1 -- per Strongly Connected Components Article if (low[u] > low[v]) low[u] = low[v]; // If u is an articulation point, // pop all edges from stack till u -- v if ((disc[u] == 1 && children > 1) || (disc[u] > 1 && low[v] >= disc[u])) { while (st[st.length-1].u != u || st[st.length-1].v != v) { document.write(st[st.length-1].u + \"--\" + st[st.length-1].v + \" \"); st.pop(); } document.write(st[st.length-1].u + \"--\" + st[st.length-1].v + \" <br>\"); st.pop(); this.count++; } } // Update low value of 'u' only if 'v' is still in stack // (i.e. it's a back edge, not cross edge). // Case 2 -- per Strongly Connected Components Article else if (v != parent[u] && disc[v] < disc[u] ) { if (low[u] > disc[v]) low[u] = disc[v]; st.push(new Edge(u, v)); } } } // The function to do DFS traversal. It uses BCCUtil() BCC() { let disc = new Array(this.V); let low = new Array(this.V); let parent = new Array(this.V); let st = []; // Initialize disc and low, and parent arrays for (let i = 0; i < this.V; i++) { disc[i] = -1; low[i] = -1; parent[i] = -1; } for (let i = 0; i < this.V; i++) { if (disc[i] == -1) this.BCCUtil(i, disc, low, st, parent); let j = 0; // If stack is not empty, pop all edges from stack while (st.length > 0) { j = 1; document.write(st[st.length-1].u + \"--\" + st[st.length-1].v + \" \"); st.pop(); } if (j == 1) { document.write(\"<br>\"); this.count++; } }}} let g = new Graph(12);g.addEdge(0, 1);g.addEdge(1, 0);g.addEdge(1, 2);g.addEdge(2, 1);g.addEdge(1, 3);g.addEdge(3, 1);g.addEdge(2, 3);g.addEdge(3, 2);g.addEdge(2, 4);g.addEdge(4, 2);g.addEdge(3, 4);g.addEdge(4, 3);g.addEdge(1, 5);g.addEdge(5, 1);g.addEdge(0, 6);g.addEdge(6, 0);g.addEdge(5, 6);g.addEdge(6, 5);g.addEdge(5, 7);g.addEdge(7, 5);g.addEdge(5, 8);g.addEdge(8, 5);g.addEdge(7, 8);g.addEdge(8, 7);g.addEdge(8, 9);g.addEdge(9, 8);g.addEdge(10, 11);g.addEdge(11, 10); g.BCC(); document.write(\"Above are \" + g.count + \" biconnected components in graph\"); // This code is contributed by avanitrachhadiya2155</script>",
"e": 49400,
"s": 44982,
"text": null
},
{
"code": null,
"e": 49408,
"s": 49400,
"text": "Output:"
},
{
"code": null,
"e": 49525,
"s": 49408,
"text": "4--2 3--4 3--1 2--3 1--2\n8--9\n8--5 7--8 5--7\n6--0 5--6 1--5 0--1 \n10--11\nAbove are 5 biconnected components in graph"
},
{
"code": null,
"e": 49695,
"s": 49525,
"text": "This article is contributed by Anurag Singh. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above "
},
{
"code": null,
"e": 49711,
"s": 49695,
"text": "VismayMalondkar"
},
{
"code": null,
"e": 49718,
"s": 49711,
"text": "spattk"
},
{
"code": null,
"e": 49732,
"s": 49718,
"text": "princiraj1992"
},
{
"code": null,
"e": 49753,
"s": 49732,
"text": "avanitrachhadiya2155"
},
{
"code": null,
"e": 49769,
"s": 49753,
"text": "amartyaghoshgfg"
},
{
"code": null,
"e": 49788,
"s": 49769,
"text": "graph-connectivity"
},
{
"code": null,
"e": 49794,
"s": 49788,
"text": "Graph"
},
{
"code": null,
"e": 49800,
"s": 49794,
"text": "Graph"
},
{
"code": null,
"e": 49898,
"s": 49800,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 49918,
"s": 49898,
"text": "Topological Sorting"
},
{
"code": null,
"e": 49951,
"s": 49918,
"text": "Detect Cycle in a Directed Graph"
},
{
"code": null,
"e": 50026,
"s": 49951,
"text": "Disjoint Set (Or Union-Find) | Set 1 (Detect Cycle in an Undirected Graph)"
},
{
"code": null,
"e": 50094,
"s": 50026,
"text": "Travelling Salesman Problem | Set 1 (Naive and Dynamic Programming)"
},
{
"code": null,
"e": 50142,
"s": 50094,
"text": "Check whether a given graph is Bipartite or not"
},
{
"code": null,
"e": 50192,
"s": 50142,
"text": "Ford-Fulkerson Algorithm for Maximum Flow Problem"
},
{
"code": null,
"e": 50240,
"s": 50192,
"text": "Traveling Salesman Problem (TSP) Implementation"
},
{
"code": null,
"e": 50276,
"s": 50240,
"text": "Detect cycle in an undirected graph"
},
{
"code": null,
"e": 50313,
"s": 50276,
"text": "Shortest path in an unweighted graph"
}
] |
Easiest Guide to Getting Stock Data With Python | by Aidan Wilson | Towards Data Science
|
I recently finished up an introductory course for data science at my university and for my final project, I decided I wanted to work with stock market data. I wanted to place my focus on the algorithmic trading and needed a quick and easy way to gather stock data that was easily useable.
I came across a library called yfinance and it made my project a lot easier!
I would highly recommend reading through the documentation. Its a quick read that will aid you with any projects involving stock data.
Before we begin, we will need to install the yfinance library. To do this, simply copy the following into your command prompt:
$ pip install yfinance
Now we’re ready to start analyzing our stock market data. For my project, I chose the SPDR S&P 500 ETF Trust, which has the ticker symbol SPY. You can use whichever ticker symbol you want, but I will be using SPY throughout this article.
Fortunately, yfinance makes it extremely easy to pull our data and quickly start analyzing it. We can start by importing yfinance and downloading the historical data of whichever ticker symbol we choose using the .download() function. We can then get a quick look at our data by calling the .head() function to return the first 5 rows of our data.
import yfinance as yfSPY = yf.download('SPY')SPY.head()
Our stock data is nicely formatted in a Pandas DataFrame. This makes it easy, for example, if you were interested in viewing just the closing prices in the dataset.
SPY['Close']
It is also possible to only download data from a certain range of dates. This will require us to use yfinance’s Ticker module, which allows us to do a bit more with yfinance. Once this is done, we can use the .history() function to all of the stock data, or data within a time frame. Let's say we wanted data from the beginning of January 2020 to the beginning of February 2020.
SPY = yf.Ticker('SPY')SPY_History = SPY.history(start="2020-01-01", end="2020-02-01")SPY_History.head()
Now that we have used the Ticker module, we can call.info to view a much more detailed summary of our data. This will return a dictionary containing 100 keys.
SPY.info
That's a lot of data! We can view individual keys in our dictionary as well. For example, if we wanted to see the current 50 Day Average, we could write:
SPY.info['fiftyDayAverage']
Viewing multiple ticker symbols is just as easy. We can use the .download() function again and separate each ticker symbol with a space. We can then view the last 5 rows in our data to check how it is formatted.
data = yf.download('SPY AAPL')data.tail()
For a quick visualization of our data, we can use matplotlib and write a one-liner to compare both SPY and AAPL.
import matplotlib.pyplot as pltdata['Close'].plot(figsize=(10, 5))
For anyone needing to gather stock data quickly and painlessly, yfinance is a great choice and is by far one of the easiest ways to pull stock market data using Python!
|
[
{
"code": null,
"e": 335,
"s": 46,
"text": "I recently finished up an introductory course for data science at my university and for my final project, I decided I wanted to work with stock market data. I wanted to place my focus on the algorithmic trading and needed a quick and easy way to gather stock data that was easily useable."
},
{
"code": null,
"e": 412,
"s": 335,
"text": "I came across a library called yfinance and it made my project a lot easier!"
},
{
"code": null,
"e": 547,
"s": 412,
"text": "I would highly recommend reading through the documentation. Its a quick read that will aid you with any projects involving stock data."
},
{
"code": null,
"e": 674,
"s": 547,
"text": "Before we begin, we will need to install the yfinance library. To do this, simply copy the following into your command prompt:"
},
{
"code": null,
"e": 697,
"s": 674,
"text": "$ pip install yfinance"
},
{
"code": null,
"e": 935,
"s": 697,
"text": "Now we’re ready to start analyzing our stock market data. For my project, I chose the SPDR S&P 500 ETF Trust, which has the ticker symbol SPY. You can use whichever ticker symbol you want, but I will be using SPY throughout this article."
},
{
"code": null,
"e": 1283,
"s": 935,
"text": "Fortunately, yfinance makes it extremely easy to pull our data and quickly start analyzing it. We can start by importing yfinance and downloading the historical data of whichever ticker symbol we choose using the .download() function. We can then get a quick look at our data by calling the .head() function to return the first 5 rows of our data."
},
{
"code": null,
"e": 1339,
"s": 1283,
"text": "import yfinance as yfSPY = yf.download('SPY')SPY.head()"
},
{
"code": null,
"e": 1504,
"s": 1339,
"text": "Our stock data is nicely formatted in a Pandas DataFrame. This makes it easy, for example, if you were interested in viewing just the closing prices in the dataset."
},
{
"code": null,
"e": 1517,
"s": 1504,
"text": "SPY['Close']"
},
{
"code": null,
"e": 1896,
"s": 1517,
"text": "It is also possible to only download data from a certain range of dates. This will require us to use yfinance’s Ticker module, which allows us to do a bit more with yfinance. Once this is done, we can use the .history() function to all of the stock data, or data within a time frame. Let's say we wanted data from the beginning of January 2020 to the beginning of February 2020."
},
{
"code": null,
"e": 2000,
"s": 1896,
"text": "SPY = yf.Ticker('SPY')SPY_History = SPY.history(start=\"2020-01-01\", end=\"2020-02-01\")SPY_History.head()"
},
{
"code": null,
"e": 2159,
"s": 2000,
"text": "Now that we have used the Ticker module, we can call.info to view a much more detailed summary of our data. This will return a dictionary containing 100 keys."
},
{
"code": null,
"e": 2168,
"s": 2159,
"text": "SPY.info"
},
{
"code": null,
"e": 2322,
"s": 2168,
"text": "That's a lot of data! We can view individual keys in our dictionary as well. For example, if we wanted to see the current 50 Day Average, we could write:"
},
{
"code": null,
"e": 2350,
"s": 2322,
"text": "SPY.info['fiftyDayAverage']"
},
{
"code": null,
"e": 2562,
"s": 2350,
"text": "Viewing multiple ticker symbols is just as easy. We can use the .download() function again and separate each ticker symbol with a space. We can then view the last 5 rows in our data to check how it is formatted."
},
{
"code": null,
"e": 2604,
"s": 2562,
"text": "data = yf.download('SPY AAPL')data.tail()"
},
{
"code": null,
"e": 2717,
"s": 2604,
"text": "For a quick visualization of our data, we can use matplotlib and write a one-liner to compare both SPY and AAPL."
},
{
"code": null,
"e": 2784,
"s": 2717,
"text": "import matplotlib.pyplot as pltdata['Close'].plot(figsize=(10, 5))"
}
] |
How to put a ListView into a ScrollView without it collapsing on Android?
|
This example demonstrates how to put a ListView into a ScrollView without it collapsing on Android.
Step 1 − Create a new project in Android Studio, go to File ⇒ New Project and fill all required details to create a new project.
Step 2 − Add the following code to res/layout/activity_main.xml.
<?xml version="1.0" encoding="utf-8"?>
<ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation ="vertical" >
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="19dp"
android:text="hello_world" />
<ListView
android:id="@+id/listView"
android:layout_width="fill_parent"
android:layout_height="fill_parent" />
</LinearLayout>
</ScrollView>
Step 3 − Add the following code to src/MainActivity.java
package com.example.sample;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.ArrayAdapter;
import android.widget.ListView;
public class MainActivity extends AppCompatActivity {
private String listview_array[]={ "ONE", "TWO", "THREE", "FOUR", "FIVE", "SIX", "SEVEN", "EIGHT", "NINE", "TEN" };
ListView myList;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
myList=(ListView) findViewById(R.id.listView);
myList.setAdapter(new ArrayAdapter<String>(this,android.R.layout.simple_list_item_1, listview_array));
Helper.getListViewSize(myList);
}
}
Step 4 − Add the following code to src/ Helper.java
package com.example.sample;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ListAdapter;
import android.widget.ListView;
public class Helper {
public static void getListViewSize(ListView myListView) {
ListAdapter myListAdapter=myListView.getAdapter();
if (myListAdapter==null) {
//do nothing return null
return;
}
//set listAdapter in loop for getting final size
int totalHeight=0;
for (int size=0; size < myListAdapter.getCount(); size++) {
View listItem=myListAdapter.getView(size, null, myListView);
listItem.measure(0, 0);
totalHeight+=listItem.getMeasuredHeight();
}
//setting listview item in adapter
ViewGroup.LayoutParams params=myListView.getLayoutParams();
params.height=totalHeight + (myListView.getDividerHeight() * (myListAdapter.getCount() - 1));
myListView.setLayoutParams(params);
// print height of adapter on log
Log.i("height of listItem:", String.valueOf(totalHeight));
}
}
Step 5 − Add the following code to app/manifests/AndroidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android" package="com.example.sample">
<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:roundIcon="@mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="@style/AppTheme">
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>
Let's try to run your application. I assume you have connected your actual Android Mobile device with your computer. To run the app from android studio, open one of your project's activity files and click Run icon from the toolbar. Select your mobile device as an option and then check your mobile device which will display your default screen −
Click here to download the project code
|
[
{
"code": null,
"e": 1162,
"s": 1062,
"text": "This example demonstrates how to put a ListView into a ScrollView without it collapsing on Android."
},
{
"code": null,
"e": 1291,
"s": 1162,
"text": "Step 1 − Create a new project in Android Studio, go to File ⇒ New Project and fill all required details to create a new project."
},
{
"code": null,
"e": 1356,
"s": 1291,
"text": "Step 2 − Add the following code to res/layout/activity_main.xml."
},
{
"code": null,
"e": 2190,
"s": 1356,
"text": "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<ScrollView xmlns:android=\"http://schemas.android.com/apk/res/android\"\n xmlns:app=\"http://schemas.android.com/apk/res-auto\"\n xmlns:tools=\"http://schemas.android.com/tools\"\n android:layout_width=\"match_parent\"\n android:layout_height=\"match_parent\"\n tools:context=\".MainActivity\">\n <LinearLayout\n android:layout_width=\"match_parent\"\n android:layout_height=\"match_parent\"\n android:orientation =\"vertical\" >\n <TextView\n android:layout_width=\"wrap_content\"\n android:layout_height=\"wrap_content\"\n android:layout_marginTop=\"19dp\"\n android:text=\"hello_world\" />\n <ListView\n android:id=\"@+id/listView\"\n android:layout_width=\"fill_parent\"\n android:layout_height=\"fill_parent\" />\n </LinearLayout>\n</ScrollView>"
},
{
"code": null,
"e": 2247,
"s": 2190,
"text": "Step 3 − Add the following code to src/MainActivity.java"
},
{
"code": null,
"e": 2974,
"s": 2247,
"text": "package com.example.sample;\nimport android.support.v7.app.AppCompatActivity;\nimport android.os.Bundle;\nimport android.widget.ArrayAdapter;\nimport android.widget.ListView;\npublic class MainActivity extends AppCompatActivity {\n private String listview_array[]={ \"ONE\", \"TWO\", \"THREE\", \"FOUR\", \"FIVE\", \"SIX\", \"SEVEN\", \"EIGHT\", \"NINE\", \"TEN\" };\n ListView myList;\n @Override\n protected void onCreate(Bundle savedInstanceState) {\n super.onCreate(savedInstanceState);\n setContentView(R.layout.activity_main);\n myList=(ListView) findViewById(R.id.listView);\n myList.setAdapter(new ArrayAdapter<String>(this,android.R.layout.simple_list_item_1, listview_array));\n Helper.getListViewSize(myList);\n }\n}"
},
{
"code": null,
"e": 3026,
"s": 2974,
"text": "Step 4 − Add the following code to src/ Helper.java"
},
{
"code": null,
"e": 4105,
"s": 3026,
"text": "package com.example.sample;\nimport android.util.Log;\nimport android.view.View;\nimport android.view.ViewGroup;\nimport android.widget.ListAdapter;\nimport android.widget.ListView;\npublic class Helper {\n public static void getListViewSize(ListView myListView) {\n ListAdapter myListAdapter=myListView.getAdapter();\n if (myListAdapter==null) {\n //do nothing return null\n return;\n }\n //set listAdapter in loop for getting final size\n int totalHeight=0;\n for (int size=0; size < myListAdapter.getCount(); size++) {\n View listItem=myListAdapter.getView(size, null, myListView);\n listItem.measure(0, 0);\n totalHeight+=listItem.getMeasuredHeight();\n }\n //setting listview item in adapter\n ViewGroup.LayoutParams params=myListView.getLayoutParams();\n params.height=totalHeight + (myListView.getDividerHeight() * (myListAdapter.getCount() - 1));\n myListView.setLayoutParams(params);\n // print height of adapter on log\n Log.i(\"height of listItem:\", String.valueOf(totalHeight));\n }\n}"
},
{
"code": null,
"e": 4174,
"s": 4105,
"text": "Step 5 − Add the following code to app/manifests/AndroidManifest.xml"
},
{
"code": null,
"e": 4848,
"s": 4174,
"text": "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<manifest xmlns:android=\"http://schemas.android.com/apk/res/android\" package=\"com.example.sample\">\n <application\n android:allowBackup=\"true\"\n android:icon=\"@mipmap/ic_launcher\"\n android:label=\"@string/app_name\"\n android:roundIcon=\"@mipmap/ic_launcher_round\"\n android:supportsRtl=\"true\"\n android:theme=\"@style/AppTheme\">\n <activity android:name=\".MainActivity\">\n <intent-filter>\n <action android:name=\"android.intent.action.MAIN\" />\n <category android:name=\"android.intent.category.LAUNCHER\" />\n </intent-filter>\n </activity>\n </application>\n</manifest>"
},
{
"code": null,
"e": 5196,
"s": 4848,
"text": "Let's try to run your application. I assume you have connected your actual Android Mobile device with your computer. To run the app from android studio, open one of your project's activity files and click Run icon from the toolbar. Select your mobile device as an option and then check your mobile device which will display your default screen −"
},
{
"code": null,
"e": 5236,
"s": 5196,
"text": "Click here to download the project code"
}
] |
Python Tuples: When to Use Them Over Lists | by Erdem Isbilen | Towards Data Science
|
Lists and dictionaries are the most widely used built-in data types in Python. This makes them also the best-known data types in Python. When it comes to tuples, grasping the details of how they differ from the lists is not an easy task for the beginners as they are very similar to each other.
In this article, I will explain key differences by providing examples for various use cases to better explain when to use tuples over lists.
They are both used to store collection of data
They are both heterogeneous data types means that you can store any kind of data type
They are both ordered means the order in which you put the items are kept.
They are both sequential data types so you can iterate over the items contained.
Items of both types can be accessed by an integer index operator, provided in square brackets, [index]
So well, how they differ then?
The key difference between the tuples and lists is that while the tuples are immutable objects the lists are mutable. This means that tuples cannot be changed while the lists can be modified.
Let’s further understand how this effect our code in terms of time and memory efficiency.
As lists are mutable, Python needs to allocate an extra memory block in case there is a need to extend the size of the list object after it is created. In contrary, as tuples are immutable and fixed size, Python allocates just the minimum memory block required for the data.
As a result, tuples are more memory efficient than the lists.
Let’s check this in the code block below;
import sysa_list = list()a_tuple = tuple()a_list = [1,2,3,4,5]a_tuple = (1,2,3,4,5)print(sys.getsizeof(a_list))print(sys.getsizeof(a_tuple))Output:104 (bytes for the list object88 (bytes for the tuple object)
As you can see from the output of the above code snippet, the memory required for the identical list and tuple objects is different.
When it comes to the time efficiency, again tuples have a slight advantage over the lists especially when lookup to a value is considered.
import sys, platformimport timeprint(platform.python_version())start_time = time.time()b_list = list(range(10000000))end_time = time.time()print("Instantiation time for LIST:", end_time - start_time)start_time = time.time()b_tuple = tuple(range(10000000))end_time = time.time()print("Instantiation time for TUPLE:", end_time - start_time)start_time = time.time()for item in b_list: aa = b_list[20000]end_time = time.time()print("Lookup time for LIST: ", end_time - start_time)start_time = time.time()for item in b_tuple: aa = b_tuple[20000]end_time = time.time()print("Lookup time for TUPLE: ", end_time - start_time)Output:3.6.9Instantiation time for LIST: 0.4149961471557617 Instantiation time for TUPLE: 0.4139530658721924 Lookup time for LIST: 0.8162095546722412 Lookup time for TUPLE: 0.7768714427947998
Well, obviously this depends on your needs.
There may be some occasions you specifically do not what data to be changed. If you have data which is not meant to be changed in the first place, you should choose tuple data type over lists.
But if you know that the data will grow and shrink during the runtime of the application, you need to go with the list data type.
In this short article, I have explained what are the differences between the tuples and lists and when we should use tuples in Python. The key takeaways are;
The key difference between the tuples and lists is that while the tuples are immutable objects the lists are mutable. This means that tuples cannot be changed while the lists can be modified.
Tuples are more memory efficient than the lists.
When it comes to the time efficiency, again tuples have a slight advantage over the lists especially when lookup to a value is considered.
If you have data which is not meant to be changed in the first place, you should choose tuple data type over lists.
I hope you have found the article useful and you will start using tuple data types in your own code.
See my latest article to learn more about Python Type Hints
|
[
{
"code": null,
"e": 467,
"s": 172,
"text": "Lists and dictionaries are the most widely used built-in data types in Python. This makes them also the best-known data types in Python. When it comes to tuples, grasping the details of how they differ from the lists is not an easy task for the beginners as they are very similar to each other."
},
{
"code": null,
"e": 608,
"s": 467,
"text": "In this article, I will explain key differences by providing examples for various use cases to better explain when to use tuples over lists."
},
{
"code": null,
"e": 655,
"s": 608,
"text": "They are both used to store collection of data"
},
{
"code": null,
"e": 741,
"s": 655,
"text": "They are both heterogeneous data types means that you can store any kind of data type"
},
{
"code": null,
"e": 816,
"s": 741,
"text": "They are both ordered means the order in which you put the items are kept."
},
{
"code": null,
"e": 897,
"s": 816,
"text": "They are both sequential data types so you can iterate over the items contained."
},
{
"code": null,
"e": 1000,
"s": 897,
"text": "Items of both types can be accessed by an integer index operator, provided in square brackets, [index]"
},
{
"code": null,
"e": 1031,
"s": 1000,
"text": "So well, how they differ then?"
},
{
"code": null,
"e": 1223,
"s": 1031,
"text": "The key difference between the tuples and lists is that while the tuples are immutable objects the lists are mutable. This means that tuples cannot be changed while the lists can be modified."
},
{
"code": null,
"e": 1313,
"s": 1223,
"text": "Let’s further understand how this effect our code in terms of time and memory efficiency."
},
{
"code": null,
"e": 1588,
"s": 1313,
"text": "As lists are mutable, Python needs to allocate an extra memory block in case there is a need to extend the size of the list object after it is created. In contrary, as tuples are immutable and fixed size, Python allocates just the minimum memory block required for the data."
},
{
"code": null,
"e": 1650,
"s": 1588,
"text": "As a result, tuples are more memory efficient than the lists."
},
{
"code": null,
"e": 1692,
"s": 1650,
"text": "Let’s check this in the code block below;"
},
{
"code": null,
"e": 1901,
"s": 1692,
"text": "import sysa_list = list()a_tuple = tuple()a_list = [1,2,3,4,5]a_tuple = (1,2,3,4,5)print(sys.getsizeof(a_list))print(sys.getsizeof(a_tuple))Output:104 (bytes for the list object88 (bytes for the tuple object)"
},
{
"code": null,
"e": 2034,
"s": 1901,
"text": "As you can see from the output of the above code snippet, the memory required for the identical list and tuple objects is different."
},
{
"code": null,
"e": 2173,
"s": 2034,
"text": "When it comes to the time efficiency, again tuples have a slight advantage over the lists especially when lookup to a value is considered."
},
{
"code": null,
"e": 2986,
"s": 2173,
"text": "import sys, platformimport timeprint(platform.python_version())start_time = time.time()b_list = list(range(10000000))end_time = time.time()print(\"Instantiation time for LIST:\", end_time - start_time)start_time = time.time()b_tuple = tuple(range(10000000))end_time = time.time()print(\"Instantiation time for TUPLE:\", end_time - start_time)start_time = time.time()for item in b_list: aa = b_list[20000]end_time = time.time()print(\"Lookup time for LIST: \", end_time - start_time)start_time = time.time()for item in b_tuple: aa = b_tuple[20000]end_time = time.time()print(\"Lookup time for TUPLE: \", end_time - start_time)Output:3.6.9Instantiation time for LIST: 0.4149961471557617 Instantiation time for TUPLE: 0.4139530658721924 Lookup time for LIST: 0.8162095546722412 Lookup time for TUPLE: 0.7768714427947998"
},
{
"code": null,
"e": 3030,
"s": 2986,
"text": "Well, obviously this depends on your needs."
},
{
"code": null,
"e": 3223,
"s": 3030,
"text": "There may be some occasions you specifically do not what data to be changed. If you have data which is not meant to be changed in the first place, you should choose tuple data type over lists."
},
{
"code": null,
"e": 3353,
"s": 3223,
"text": "But if you know that the data will grow and shrink during the runtime of the application, you need to go with the list data type."
},
{
"code": null,
"e": 3511,
"s": 3353,
"text": "In this short article, I have explained what are the differences between the tuples and lists and when we should use tuples in Python. The key takeaways are;"
},
{
"code": null,
"e": 3703,
"s": 3511,
"text": "The key difference between the tuples and lists is that while the tuples are immutable objects the lists are mutable. This means that tuples cannot be changed while the lists can be modified."
},
{
"code": null,
"e": 3752,
"s": 3703,
"text": "Tuples are more memory efficient than the lists."
},
{
"code": null,
"e": 3891,
"s": 3752,
"text": "When it comes to the time efficiency, again tuples have a slight advantage over the lists especially when lookup to a value is considered."
},
{
"code": null,
"e": 4007,
"s": 3891,
"text": "If you have data which is not meant to be changed in the first place, you should choose tuple data type over lists."
},
{
"code": null,
"e": 4108,
"s": 4007,
"text": "I hope you have found the article useful and you will start using tuple data types in your own code."
}
] |
SQL - INDEX Constraint
|
The INDEX is used to create and retrieve data from the database very quickly. An Index can be created by using a single or group of columns in a table. When the index is created, it is assigned a ROWID for each row before it sorts out the data.
Proper indexes are good for performance in large databases, but you need to be careful while creating an index. A Selection of fields depends on what you are using in your SQL queries.
For example, the following SQL syntax creates a new table called CUSTOMERS and adds five columns in it.
CREATE TABLE CUSTOMERS(
ID INT NOT NULL,
NAME VARCHAR (20) NOT NULL,
AGE INT NOT NULL,
ADDRESS CHAR (25) ,
SALARY DECIMAL (18, 2),
PRIMARY KEY (ID)
);
Now, you can create an index on a single or multiple columns using the syntax given below.
CREATE INDEX index_name
ON table_name ( column1, column2.....);
To create an INDEX on the AGE column, to optimize the search on customers for a specific age, you can use the follow SQL syntax which is given below −
CREATE INDEX idx_age
ON CUSTOMERS ( AGE );
To drop an INDEX constraint, use the following SQL syntax.
ALTER TABLE CUSTOMERS
DROP INDEX idx_age;
42 Lectures
5 hours
Anadi Sharma
14 Lectures
2 hours
Anadi Sharma
44 Lectures
4.5 hours
Anadi Sharma
94 Lectures
7 hours
Abhishek And Pukhraj
80 Lectures
6.5 hours
Oracle Master Training | 150,000+ Students Worldwide
31 Lectures
6 hours
Eduonix Learning Solutions
Print
Add Notes
Bookmark this page
|
[
{
"code": null,
"e": 2698,
"s": 2453,
"text": "The INDEX is used to create and retrieve data from the database very quickly. An Index can be created by using a single or group of columns in a table. When the index is created, it is assigned a ROWID for each row before it sorts out the data."
},
{
"code": null,
"e": 2883,
"s": 2698,
"text": "Proper indexes are good for performance in large databases, but you need to be careful while creating an index. A Selection of fields depends on what you are using in your SQL queries."
},
{
"code": null,
"e": 2987,
"s": 2883,
"text": "For example, the following SQL syntax creates a new table called CUSTOMERS and adds five columns in it."
},
{
"code": null,
"e": 3199,
"s": 2987,
"text": "CREATE TABLE CUSTOMERS(\n ID INT NOT NULL,\n NAME VARCHAR (20) NOT NULL,\n AGE INT NOT NULL,\n ADDRESS CHAR (25) ,\n SALARY DECIMAL (18, 2), \n PRIMARY KEY (ID)\n);"
},
{
"code": null,
"e": 3290,
"s": 3199,
"text": "Now, you can create an index on a single or multiple columns using the syntax given below."
},
{
"code": null,
"e": 3358,
"s": 3290,
"text": "CREATE INDEX index_name\n ON table_name ( column1, column2.....);\n"
},
{
"code": null,
"e": 3509,
"s": 3358,
"text": "To create an INDEX on the AGE column, to optimize the search on customers for a specific age, you can use the follow SQL syntax which is given below −"
},
{
"code": null,
"e": 3556,
"s": 3509,
"text": "CREATE INDEX idx_age\n ON CUSTOMERS ( AGE );\n"
},
{
"code": null,
"e": 3615,
"s": 3556,
"text": "To drop an INDEX constraint, use the following SQL syntax."
},
{
"code": null,
"e": 3661,
"s": 3615,
"text": "ALTER TABLE CUSTOMERS\n DROP INDEX idx_age;\n"
},
{
"code": null,
"e": 3694,
"s": 3661,
"text": "\n 42 Lectures \n 5 hours \n"
},
{
"code": null,
"e": 3708,
"s": 3694,
"text": " Anadi Sharma"
},
{
"code": null,
"e": 3741,
"s": 3708,
"text": "\n 14 Lectures \n 2 hours \n"
},
{
"code": null,
"e": 3755,
"s": 3741,
"text": " Anadi Sharma"
},
{
"code": null,
"e": 3790,
"s": 3755,
"text": "\n 44 Lectures \n 4.5 hours \n"
},
{
"code": null,
"e": 3804,
"s": 3790,
"text": " Anadi Sharma"
},
{
"code": null,
"e": 3837,
"s": 3804,
"text": "\n 94 Lectures \n 7 hours \n"
},
{
"code": null,
"e": 3859,
"s": 3837,
"text": " Abhishek And Pukhraj"
},
{
"code": null,
"e": 3894,
"s": 3859,
"text": "\n 80 Lectures \n 6.5 hours \n"
},
{
"code": null,
"e": 3948,
"s": 3894,
"text": " Oracle Master Training | 150,000+ Students Worldwide"
},
{
"code": null,
"e": 3981,
"s": 3948,
"text": "\n 31 Lectures \n 6 hours \n"
},
{
"code": null,
"e": 4009,
"s": 3981,
"text": " Eduonix Learning Solutions"
},
{
"code": null,
"e": 4016,
"s": 4009,
"text": " Print"
},
{
"code": null,
"e": 4027,
"s": 4016,
"text": " Add Notes"
}
] |
How to remove duplicate elements from JavaScript Array ? - GeeksforGeeks
|
20 Oct, 2021
There are various methods to remove duplicates in the array. We will discuss the most common four ways.
Use the filter() method: The filter() method creates a new array of elements that pass the condition we provide. It will include only those elements for which true is returned. We can remove duplicate values from the array by simply adjusting our condition.
Javascript
<script> var arr = ["apple", "mango", "apple", "orange", "mango", "mango"]; function removeDuplicates(arr) { return arr.filter((item, index) => arr.indexOf(item) === index); } console.log(removeDuplicates(arr));</script>
Output:
["apple", "mango", "orange"]
Using a Set() Method: This method sets a new object type with ES6 (ES2015) that allows you to create collections of unique values.
Javascript
<script> var arr = ["apple", "mango", "apple", "orange", "mango", "mango"]; function removeDuplicates(arr) { return [...new Set(arr)]; } console.log(removeDuplicates(arr));</script>
Output:
["apple", "mango", "orange"]
Using the forEach() Method: By using forEach() method, we can iterate over the elements in the array, and we will push into the new array if it doesn’t exist in the array.
Javascript
<script> var arr = ["apple", "mango", "apple", "orange", "mango", "mango"]; function removeDuplicates(arr) { var unique = []; arr.forEach(element => { if (!unique.includes(element)) { unique.push(element); } }); return unique; } console.log(removeDuplicates(arr));</script>
Output:
["apple", "mango", "orange"]
Using the reduce() Method: The reduce() method is used to reduce the elements of the array and combine them into a final array based on some reducer function that you pass.
Javascript
<script> var arr = ["apple", "mango", "apple", "orange", "mango", "mango"]; function removeDuplicates(arr) { var unique = arr.reduce(function (acc, curr) { if (!acc.includes(curr)) acc.push(curr); return acc; }, []); return unique; } console.log(removeDuplicates(arr));</script>
Output:
["apple", "mango", "orange"]
javascript-array
JavaScript-Questions
Picked
TrueGeek-2021
JavaScript
TrueGeek
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Difference between var, let and const keywords in JavaScript
Convert a string to an integer in JavaScript
Differences between Functional Components and Class Components in React
How to append HTML code to a div using JavaScript ?
How to Open URL in New Tab using JavaScript ?
How to redirect to another page in ReactJS ?
Types of Internet Protocols
Basics of API Testing Using Postman
SQL Statement to Remove Part of a String
How to Convert Char to String in Java?
|
[
{
"code": null,
"e": 24285,
"s": 24257,
"text": "\n20 Oct, 2021"
},
{
"code": null,
"e": 24389,
"s": 24285,
"text": "There are various methods to remove duplicates in the array. We will discuss the most common four ways."
},
{
"code": null,
"e": 24647,
"s": 24389,
"text": "Use the filter() method: The filter() method creates a new array of elements that pass the condition we provide. It will include only those elements for which true is returned. We can remove duplicate values from the array by simply adjusting our condition."
},
{
"code": null,
"e": 24658,
"s": 24647,
"text": "Javascript"
},
{
"code": "<script> var arr = [\"apple\", \"mango\", \"apple\", \"orange\", \"mango\", \"mango\"]; function removeDuplicates(arr) { return arr.filter((item, index) => arr.indexOf(item) === index); } console.log(removeDuplicates(arr));</script>",
"e": 24926,
"s": 24658,
"text": null
},
{
"code": null,
"e": 24934,
"s": 24926,
"text": "Output:"
},
{
"code": null,
"e": 24963,
"s": 24934,
"text": "[\"apple\", \"mango\", \"orange\"]"
},
{
"code": null,
"e": 25094,
"s": 24963,
"text": "Using a Set() Method: This method sets a new object type with ES6 (ES2015) that allows you to create collections of unique values."
},
{
"code": null,
"e": 25105,
"s": 25094,
"text": "Javascript"
},
{
"code": "<script> var arr = [\"apple\", \"mango\", \"apple\", \"orange\", \"mango\", \"mango\"]; function removeDuplicates(arr) { return [...new Set(arr)]; } console.log(removeDuplicates(arr));</script>",
"e": 25321,
"s": 25105,
"text": null
},
{
"code": null,
"e": 25329,
"s": 25321,
"text": "Output:"
},
{
"code": null,
"e": 25358,
"s": 25329,
"text": "[\"apple\", \"mango\", \"orange\"]"
},
{
"code": null,
"e": 25530,
"s": 25358,
"text": "Using the forEach() Method: By using forEach() method, we can iterate over the elements in the array, and we will push into the new array if it doesn’t exist in the array."
},
{
"code": null,
"e": 25541,
"s": 25530,
"text": "Javascript"
},
{
"code": "<script> var arr = [\"apple\", \"mango\", \"apple\", \"orange\", \"mango\", \"mango\"]; function removeDuplicates(arr) { var unique = []; arr.forEach(element => { if (!unique.includes(element)) { unique.push(element); } }); return unique; } console.log(removeDuplicates(arr));</script>",
"e": 25904,
"s": 25541,
"text": null
},
{
"code": null,
"e": 25912,
"s": 25904,
"text": "Output:"
},
{
"code": null,
"e": 25941,
"s": 25912,
"text": "[\"apple\", \"mango\", \"orange\"]"
},
{
"code": null,
"e": 26114,
"s": 25941,
"text": "Using the reduce() Method: The reduce() method is used to reduce the elements of the array and combine them into a final array based on some reducer function that you pass."
},
{
"code": null,
"e": 26125,
"s": 26114,
"text": "Javascript"
},
{
"code": "<script> var arr = [\"apple\", \"mango\", \"apple\", \"orange\", \"mango\", \"mango\"]; function removeDuplicates(arr) { var unique = arr.reduce(function (acc, curr) { if (!acc.includes(curr)) acc.push(curr); return acc; }, []); return unique; } console.log(removeDuplicates(arr));</script>",
"e": 26486,
"s": 26125,
"text": null
},
{
"code": null,
"e": 26494,
"s": 26486,
"text": "Output:"
},
{
"code": null,
"e": 26523,
"s": 26494,
"text": "[\"apple\", \"mango\", \"orange\"]"
},
{
"code": null,
"e": 26540,
"s": 26523,
"text": "javascript-array"
},
{
"code": null,
"e": 26561,
"s": 26540,
"text": "JavaScript-Questions"
},
{
"code": null,
"e": 26568,
"s": 26561,
"text": "Picked"
},
{
"code": null,
"e": 26582,
"s": 26568,
"text": "TrueGeek-2021"
},
{
"code": null,
"e": 26593,
"s": 26582,
"text": "JavaScript"
},
{
"code": null,
"e": 26602,
"s": 26593,
"text": "TrueGeek"
},
{
"code": null,
"e": 26619,
"s": 26602,
"text": "Web Technologies"
},
{
"code": null,
"e": 26717,
"s": 26619,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 26726,
"s": 26717,
"text": "Comments"
},
{
"code": null,
"e": 26739,
"s": 26726,
"text": "Old Comments"
},
{
"code": null,
"e": 26800,
"s": 26739,
"text": "Difference between var, let and const keywords in JavaScript"
},
{
"code": null,
"e": 26845,
"s": 26800,
"text": "Convert a string to an integer in JavaScript"
},
{
"code": null,
"e": 26917,
"s": 26845,
"text": "Differences between Functional Components and Class Components in React"
},
{
"code": null,
"e": 26969,
"s": 26917,
"text": "How to append HTML code to a div using JavaScript ?"
},
{
"code": null,
"e": 27015,
"s": 26969,
"text": "How to Open URL in New Tab using JavaScript ?"
},
{
"code": null,
"e": 27060,
"s": 27015,
"text": "How to redirect to another page in ReactJS ?"
},
{
"code": null,
"e": 27088,
"s": 27060,
"text": "Types of Internet Protocols"
},
{
"code": null,
"e": 27124,
"s": 27088,
"text": "Basics of API Testing Using Postman"
},
{
"code": null,
"e": 27165,
"s": 27124,
"text": "SQL Statement to Remove Part of a String"
}
] |
Julia Programming - Databases
|
Following are the four mechanisms for interfacing with a particular database system −
First method of accessing a database is by using the set of routines in an API (Application Program Interface). In this method, the DBMS will be bundled as a set of query and maintenance utilities. These utilities will communicate with the running database through a shared library which further will be exposed to the user as a set of routines in an API.
First method of accessing a database is by using the set of routines in an API (Application Program Interface). In this method, the DBMS will be bundled as a set of query and maintenance utilities. These utilities will communicate with the running database through a shared library which further will be exposed to the user as a set of routines in an API.
Second method is via an intermediate abstract layer. This abstract layer will communicate with the database API via a driver. Some example of such drivers are ODBC, JDBC, and Database Interface (DBI).
Second method is via an intermediate abstract layer. This abstract layer will communicate with the database API via a driver. Some example of such drivers are ODBC, JDBC, and Database Interface (DBI).
Third approach is to use Python module for a specific database system. PyCall package will be used to call routines in the Python module. It will also handle the interchange of datatypes between Python and Julia.
Third approach is to use Python module for a specific database system. PyCall package will be used to call routines in the Python module. It will also handle the interchange of datatypes between Python and Julia.
The fourth method is sending messages to the database. RESTful is the most common messaging protocol.
The fourth method is sending messages to the database. RESTful is the most common messaging protocol.
Julia provides several APIs to communicate with various database providers.
MySQL.jl is the package to access MySQL from Julia programming language.
Use the following code to install the master version of MySQL API −
Pkg.clone("https://github.com/JuliaComputing/MySQL.jl")
Example
To access MySQL API, we need to first connect to the MySQL server which can be done with the help of following code −`
using MySQL
con = mysql_connect(HOST, USER, PASSWD, DBNAME)
To work with database, use the following code snippet to create a table −
command = """CREATE TABLE Employee
(
ID INT NOT NULL AUTO_INCREMENT,
Name VARCHAR(255),
Salary FLOAT,
JoinDate DATE,
LastLogin DATETIME,
LunchTime TIME,
PRIMARY KEY (ID)
);"""
response = mysql_query(con, command)
if (response == 0)
println("Create table succeeded.")
else
println("Create table failed.")
end
We can use the following command to obtain the SELECT query result as dataframe −
command = """SELECT * FROM Employee;"""
dframe = execute_query(con, command)
We can use the following command to obtain the SELECT query result as Julia Array −
command = """SELECT * FROM Employee;"""
retarr = mysql_execute_query(con, command, opformat=MYSQL_ARRAY)
We can use the following command to obtain the SELECT query result as Julia Array with each row as a tuple −
command = """SELECT * FROM Employee;"""
retarr = mysql_execute_query(con, command, opformat=MYSQL_TUPLES)
We can execute a multi query as follows −
command = """INSERT INTO Employee (Name) VALUES ('');
UPDATE Employee SET LunchTime = '15:00:00' WHERE LENGTH(Name) > 5;"""
data = mysql_execute_query(con, command)
We can get dataframes by using prepared statements as follows −
command = """SELECT * FROM Employee;"""
stmt = mysql_stmt_init(con)
if (stmt == C_NULL)
error("Error in initialization of statement.")
end
response = mysql_stmt_prepare(stmt, command)
mysql_display_error(con, response != 0,
"Error occured while preparing statement for query \"$command\"")
dframe = mysql_stmt_result_to_dataframe(stmt)
mysql_stmt_close(stmt)
Use the following command to close the connection −
mysql_disconnect(con)
JDBC.jl is Julia interface to Java database drivers. The package JDBC.jl enables us the use of Java JDBC drivers to access databases from within Julia programming language.
To start working with it, we need to first add the database driver jar file to the classpath and then initialize the JVM as follows −
using JDBC
JavaCall.addClassPath("path of .jar file") # add the path of your .jar file
JDBC.init()
The JDBC API in Julia is similar to Java JDBC driver. To connect with a database, we need to follow similar steps as shown below −
conn = DriverManager.getConnection("jdbc:gl:test/juliatest")
stmt = createStatement(conn)
rs = executeQuery(stmt, "select * from mytable")
for r in rs
println(getInt(r, 1), getString(r,"NAME"))
end
If you want to get each row as a Julia tuple, use JDBCRowIterator to iterate over the result set. Note that if the values are declared to be nullable in the database, they will be of nullable in tuples also.
for r in JDBCRowIterator(rs)
println(r)
end
Use PrepareStatement to do insert and update. It has setter functions defined for different types corresponding to the getter functions −
ppstmt = prepareStatement(conn, "insert into mytable values (?, ?)")
setInt(ppstmt, 1,10)
setString(ppstmt, 2,"TEN")
executeUpdate(ppstmt)
Use CallableStatement to run the stored procedure −
cstmt = JDBC.prepareCall(conn, "CALL SYSCS_UTIL.SYSCS_SET_DATABASE_PROPERTY(?, ?)")
setString(cstmt, 1, "gl.locks.deadlockTimeout")
setString(cstmt, 2, "10")
execute(cstmt)
In order to get an array of (column_name, column_type) tuples, we need to Pass the JResultSet object from executeQuery to getTableMetaData as follows −
conn = DriverManager.getConnection("jdbc:gl:test/juliatest")
stmt = createStatement(conn)
rs = executeQuery(stmt, "select * from mytable")
metadata = getTableMetaData(rs)
Use the following command to close the connection −
close(conn)
For executing a query, we need a cursor first. Once obtained a cursor you can run execute! command on the cursor as follows −
csr = cursor(conn)
execute!(csr, "insert into ptable (pvalue) values (3.14);")
execute!(csr, "select * from gltable;")
We need to call rows on the cursor to iterate over the rows −
rs = rows(csr)
for row in rs
end
Use the following command to close the cursor call −
close(csr)
ODBC.jl is a package which provides us a Julia ODBC API interface. It is implemented by various ODBC driver managers. We can install it as follows −
julia> Pkg.add(“ODBC”)
Use the command below to install an ODBC driver −
ODBC.adddriver("name of driver", "full, absolute path to driver shared library"; kw...)
We need to pass −
The name of the driver
The name of the driver
The full and absolute path to the driver shared library
The full and absolute path to the driver shared library
And any additional keyword arguments which will be included as KEY=VALUE pairs in the .ini config files.
And any additional keyword arguments which will be included as KEY=VALUE pairs in the .ini config files.
After installing the drivers, we can do the following for enabling connections −
Setup a DSN, via ODBC.adddsn("dsn name", "driver name"; kw...)
Setup a DSN, via ODBC.adddsn("dsn name", "driver name"; kw...)
Connecting directly by using a full connection string like ODBC.Connection(connection_string)
Connecting directly by using a full connection string like ODBC.Connection(connection_string)
Following are two paths to execute queries −
DBInterface.execute(conn, sql, params) − It will directly execute a SQL query and after that will return a Cursor for any resultset.
DBInterface.execute(conn, sql, params) − It will directly execute a SQL query and after that will return a Cursor for any resultset.
stmt = DBInterface.prepare(conn, sql); DBInterface.execute(stmt, params) − It will first prepare a SQL statement and then execute. The execution can be done perhaps multiple times with different parameters.
stmt = DBInterface.prepare(conn, sql); DBInterface.execute(stmt, params) − It will first prepare a SQL statement and then execute. The execution can be done perhaps multiple times with different parameters.
SQLlite is a fast, flexible delimited file reader and writer for Julia programming language. This package is registered in METADATA.jl hence can be installed by using the following command −
julia> Pkg.add("SQLite")
We will discuss two important and useful functions used in SQLite along with the example −
SQLite.DB(file::AbstractString) − This function requires the file string argument as the name of a pre-defined SQLite database to be opened. If the file does not exit, it will create a database.
julia> using SQLite
julia> db = SQLite.DB("Chinook_Sqlite.sqlite")
Here we are using a sample database ‘Chinook’ available for SQLite, SQL Server, MySQL, etc.
SQLite.query(db::SQLite.DB, sql::String, values=[]) − This function returns the result, if any, after executing the prepared sql statement in the context of db.
julia> SQLite.query(db, "SELECT * FROM Genre WHERE regexp('e[trs]', Name)")
6x2 ResultSet
| Row | "GenreId" | "Name" |
|-----|-----------|----------------------|
| 1 | 3 | "Metal" |
| 2 | 4 | "Alternative & Punk" |
| 3 | 6 | "Blues" |
| 4 | 13 | "Heavy Metal" |
| 5 | 23 | "Alternative" |
| 6 | 25 | "Opera" |
PostgreSQL.jl is the PostgreSQL DBI driver. It is an interface to PostgreSQL from Julia programming language. It obeys the DBI.jl protocol for working and uses the C PostgreeSQL API (libpq).
Let’s understand its usage with the help of following code −
using DBI
using PostgreSQL
conn = connect(Postgres, "localhost", "username", "password", "dbname", 5432)
stmt = prepare(conn, "SELECT 1::bigint, 2.0::double precision, 'foo'::character varying, " *
"'foo'::character(10);")
result = execute(stmt)
for row in result
end
finish(stmt)
disconnect(conn)
To use PostgreSQL we need to fulfill the following binary requirements −
DBI.jl
DBI.jl
DataFrames.jl >= v0.5.7
DataFrames.jl >= v0.5.7
DataArrays.jl >= v0.1.2
DataArrays.jl >= v0.1.2
libpq shared library (comes with a standard PostgreSQL client installation)
libpq shared library (comes with a standard PostgreSQL client installation)
julia 0.3 or higher
julia 0.3 or higher
Hive.jl is a client for distributed SQL engine. It provides a HiveServer2, for example: Hive, Spark, SQL, Impala.
To connect to the server, we need to create an instance of the HiveSession as follows −
session = HiveSession()
It can also be connected by specifying the hostname and the port number as follows −
session = HiveSession(“localhost”,10000)
The default implementation as above will authenticates with the same user-id as that of the shell. We can override it as follows −
session = HiveSession("localhost", 10000, HiveAuthSASLPlain("uid", "pwd", "zid"))
We can execute DML, DDL, SET, etc., statements as we can see in the example below −
crs = execute(session, "select * from mytable where formid < 1001";
async=true, config=Dict())
while !isready(crs)
println("waiting...")
sleep(10)
end
crs = result(crs)
DBAPI is a new database interface proposal, inspired by Python’s DB API 2.0, that defies an abstract interface for database drivers in Julia. This module contains the following −
Abstract types
Abstract types
Abstract required functions which throw a NotImplementedError by default
Abstract required functions which throw a NotImplementedError by default
Abstract optional functions which throw a NotSupportedError by default
Abstract optional functions which throw a NotSupportedError by default
To use this API, the database drivers must import this module, subtype its types, and create methods for its functions.
DBPrf is a Julia database which is maintained by JuliaDB. You see its usage below −
The user can provide input in two ways −
$ julia DBPerf.jl <Database_Driver_1.jl> <Database_Driver_2.jl> ....... <Database_Driver_N.jl> <DBMS>
Here, Database_Driver.jl can be of the following types −
ODBC.jl
ODBC.jl
JDBC.jl
JDBC.jl
PostgreSQL.jl
PostgreSQL.jl
MySQL.jl
MySQL.jl
Mongo.jl
Mongo.jl
SQLite.jl
SQLite.jl
DBMS filed is applicable only if we are using JDBC.jl.
The database can be either Oracle or MySQL.
Example
DBPerf.jl ODBC.jl JDBC.jl MySql
julia> include("DBPerf.jl")
julia> DBPerf(<Database_Driver_1.jl>, <Database_Driver_2.jl>, ....... <Database_Driver_N.jl>, <DBMS>)
Example
DBPerf(“ODBC.jl”, “JDBC.jl”, “MySql”)
73 Lectures
4 hours
Lemuel Ogbunude
24 Lectures
3 hours
Mohammad Nauman
29 Lectures
2.5 hours
Stone River ELearning
Print
Add Notes
Bookmark this page
|
[
{
"code": null,
"e": 2164,
"s": 2078,
"text": "Following are the four mechanisms for interfacing with a particular database system −"
},
{
"code": null,
"e": 2520,
"s": 2164,
"text": "First method of accessing a database is by using the set of routines in an API (Application Program Interface). In this method, the DBMS will be bundled as a set of query and maintenance utilities. These utilities will communicate with the running database through a shared library which further will be exposed to the user as a set of routines in an API."
},
{
"code": null,
"e": 2876,
"s": 2520,
"text": "First method of accessing a database is by using the set of routines in an API (Application Program Interface). In this method, the DBMS will be bundled as a set of query and maintenance utilities. These utilities will communicate with the running database through a shared library which further will be exposed to the user as a set of routines in an API."
},
{
"code": null,
"e": 3077,
"s": 2876,
"text": "Second method is via an intermediate abstract layer. This abstract layer will communicate with the database API via a driver. Some example of such drivers are ODBC, JDBC, and Database Interface (DBI)."
},
{
"code": null,
"e": 3278,
"s": 3077,
"text": "Second method is via an intermediate abstract layer. This abstract layer will communicate with the database API via a driver. Some example of such drivers are ODBC, JDBC, and Database Interface (DBI)."
},
{
"code": null,
"e": 3491,
"s": 3278,
"text": "Third approach is to use Python module for a specific database system. PyCall package will be used to call routines in the Python module. It will also handle the interchange of datatypes between Python and Julia."
},
{
"code": null,
"e": 3704,
"s": 3491,
"text": "Third approach is to use Python module for a specific database system. PyCall package will be used to call routines in the Python module. It will also handle the interchange of datatypes between Python and Julia."
},
{
"code": null,
"e": 3806,
"s": 3704,
"text": "The fourth method is sending messages to the database. RESTful is the most common messaging protocol."
},
{
"code": null,
"e": 3908,
"s": 3806,
"text": "The fourth method is sending messages to the database. RESTful is the most common messaging protocol."
},
{
"code": null,
"e": 3984,
"s": 3908,
"text": "Julia provides several APIs to communicate with various database providers."
},
{
"code": null,
"e": 4057,
"s": 3984,
"text": "MySQL.jl is the package to access MySQL from Julia programming language."
},
{
"code": null,
"e": 4125,
"s": 4057,
"text": "Use the following code to install the master version of MySQL API −"
},
{
"code": null,
"e": 4182,
"s": 4125,
"text": "Pkg.clone(\"https://github.com/JuliaComputing/MySQL.jl\")\n"
},
{
"code": null,
"e": 4190,
"s": 4182,
"text": "Example"
},
{
"code": null,
"e": 4309,
"s": 4190,
"text": "To access MySQL API, we need to first connect to the MySQL server which can be done with the help of following code −`"
},
{
"code": null,
"e": 4370,
"s": 4309,
"text": "using MySQL\ncon = mysql_connect(HOST, USER, PASSWD, DBNAME)\n"
},
{
"code": null,
"e": 4444,
"s": 4370,
"text": "To work with database, use the following code snippet to create a table −"
},
{
"code": null,
"e": 4860,
"s": 4444,
"text": "command = \"\"\"CREATE TABLE Employee\n (\n ID INT NOT NULL AUTO_INCREMENT,\n Name VARCHAR(255),\n Salary FLOAT,\n JoinDate DATE,\n LastLogin DATETIME,\n LunchTime TIME,\n PRIMARY KEY (ID)\n );\"\"\"\nresponse = mysql_query(con, command)\nif (response == 0)\n println(\"Create table succeeded.\")\nelse\n println(\"Create table failed.\")\nend"
},
{
"code": null,
"e": 4942,
"s": 4860,
"text": "We can use the following command to obtain the SELECT query result as dataframe −"
},
{
"code": null,
"e": 5019,
"s": 4942,
"text": "command = \"\"\"SELECT * FROM Employee;\"\"\"\ndframe = execute_query(con, command)"
},
{
"code": null,
"e": 5103,
"s": 5019,
"text": "We can use the following command to obtain the SELECT query result as Julia Array −"
},
{
"code": null,
"e": 5208,
"s": 5103,
"text": "command = \"\"\"SELECT * FROM Employee;\"\"\"\nretarr = mysql_execute_query(con, command, opformat=MYSQL_ARRAY)"
},
{
"code": null,
"e": 5317,
"s": 5208,
"text": "We can use the following command to obtain the SELECT query result as Julia Array with each row as a tuple −"
},
{
"code": null,
"e": 5423,
"s": 5317,
"text": "command = \"\"\"SELECT * FROM Employee;\"\"\"\nretarr = mysql_execute_query(con, command, opformat=MYSQL_TUPLES)"
},
{
"code": null,
"e": 5465,
"s": 5423,
"text": "We can execute a multi query as follows −"
},
{
"code": null,
"e": 5630,
"s": 5465,
"text": "command = \"\"\"INSERT INTO Employee (Name) VALUES ('');\nUPDATE Employee SET LunchTime = '15:00:00' WHERE LENGTH(Name) > 5;\"\"\"\ndata = mysql_execute_query(con, command)"
},
{
"code": null,
"e": 5694,
"s": 5630,
"text": "We can get dataframes by using prepared statements as follows −"
},
{
"code": null,
"e": 6096,
"s": 5694,
"text": "command = \"\"\"SELECT * FROM Employee;\"\"\"\n\nstmt = mysql_stmt_init(con)\n\nif (stmt == C_NULL)\n error(\"Error in initialization of statement.\")\nend\n\nresponse = mysql_stmt_prepare(stmt, command)\nmysql_display_error(con, response != 0,\n \"Error occured while preparing statement for query \\\"$command\\\"\")\n \ndframe = mysql_stmt_result_to_dataframe(stmt)\nmysql_stmt_close(stmt)"
},
{
"code": null,
"e": 6148,
"s": 6096,
"text": "Use the following command to close the connection −"
},
{
"code": null,
"e": 6171,
"s": 6148,
"text": "mysql_disconnect(con)\n"
},
{
"code": null,
"e": 6344,
"s": 6171,
"text": "JDBC.jl is Julia interface to Java database drivers. The package JDBC.jl enables us the use of Java JDBC drivers to access databases from within Julia programming language."
},
{
"code": null,
"e": 6478,
"s": 6344,
"text": "To start working with it, we need to first add the database driver jar file to the classpath and then initialize the JVM as follows −"
},
{
"code": null,
"e": 6577,
"s": 6478,
"text": "using JDBC\nJavaCall.addClassPath(\"path of .jar file\") # add the path of your .jar file\nJDBC.init()"
},
{
"code": null,
"e": 6708,
"s": 6577,
"text": "The JDBC API in Julia is similar to Java JDBC driver. To connect with a database, we need to follow similar steps as shown below −"
},
{
"code": null,
"e": 6915,
"s": 6708,
"text": "conn = DriverManager.getConnection(\"jdbc:gl:test/juliatest\")\nstmt = createStatement(conn)\nrs = executeQuery(stmt, \"select * from mytable\")\n for r in rs\n println(getInt(r, 1), getString(r,\"NAME\"))\nend"
},
{
"code": null,
"e": 7123,
"s": 6915,
"text": "If you want to get each row as a Julia tuple, use JDBCRowIterator to iterate over the result set. Note that if the values are declared to be nullable in the database, they will be of nullable in tuples also."
},
{
"code": null,
"e": 7170,
"s": 7123,
"text": "for r in JDBCRowIterator(rs)\n println(r)\nend"
},
{
"code": null,
"e": 7308,
"s": 7170,
"text": "Use PrepareStatement to do insert and update. It has setter functions defined for different types corresponding to the getter functions −"
},
{
"code": null,
"e": 7447,
"s": 7308,
"text": "ppstmt = prepareStatement(conn, \"insert into mytable values (?, ?)\")\nsetInt(ppstmt, 1,10)\nsetString(ppstmt, 2,\"TEN\")\nexecuteUpdate(ppstmt)"
},
{
"code": null,
"e": 7499,
"s": 7447,
"text": "Use CallableStatement to run the stored procedure −"
},
{
"code": null,
"e": 7672,
"s": 7499,
"text": "cstmt = JDBC.prepareCall(conn, \"CALL SYSCS_UTIL.SYSCS_SET_DATABASE_PROPERTY(?, ?)\")\nsetString(cstmt, 1, \"gl.locks.deadlockTimeout\")\nsetString(cstmt, 2, \"10\")\nexecute(cstmt)"
},
{
"code": null,
"e": 7824,
"s": 7672,
"text": "In order to get an array of (column_name, column_type) tuples, we need to Pass the JResultSet object from executeQuery to getTableMetaData as follows −"
},
{
"code": null,
"e": 7995,
"s": 7824,
"text": "conn = DriverManager.getConnection(\"jdbc:gl:test/juliatest\")\nstmt = createStatement(conn)\nrs = executeQuery(stmt, \"select * from mytable\")\nmetadata = getTableMetaData(rs)"
},
{
"code": null,
"e": 8047,
"s": 7995,
"text": "Use the following command to close the connection −"
},
{
"code": null,
"e": 8060,
"s": 8047,
"text": "close(conn)\n"
},
{
"code": null,
"e": 8186,
"s": 8060,
"text": "For executing a query, we need a cursor first. Once obtained a cursor you can run execute! command on the cursor as follows −"
},
{
"code": null,
"e": 8306,
"s": 8186,
"text": "csr = cursor(conn)\nexecute!(csr, \"insert into ptable (pvalue) values (3.14);\")\nexecute!(csr, \"select * from gltable;\")\n"
},
{
"code": null,
"e": 8368,
"s": 8306,
"text": "We need to call rows on the cursor to iterate over the rows −"
},
{
"code": null,
"e": 8403,
"s": 8368,
"text": "rs = rows(csr)\nfor row in rs\n\nend\n"
},
{
"code": null,
"e": 8456,
"s": 8403,
"text": "Use the following command to close the cursor call −"
},
{
"code": null,
"e": 8468,
"s": 8456,
"text": "close(csr)\n"
},
{
"code": null,
"e": 8617,
"s": 8468,
"text": "ODBC.jl is a package which provides us a Julia ODBC API interface. It is implemented by various ODBC driver managers. We can install it as follows −"
},
{
"code": null,
"e": 8641,
"s": 8617,
"text": "julia> Pkg.add(“ODBC”)\n"
},
{
"code": null,
"e": 8691,
"s": 8641,
"text": "Use the command below to install an ODBC driver −"
},
{
"code": null,
"e": 8780,
"s": 8691,
"text": "ODBC.adddriver(\"name of driver\", \"full, absolute path to driver shared library\"; kw...)\n"
},
{
"code": null,
"e": 8798,
"s": 8780,
"text": "We need to pass −"
},
{
"code": null,
"e": 8821,
"s": 8798,
"text": "The name of the driver"
},
{
"code": null,
"e": 8844,
"s": 8821,
"text": "The name of the driver"
},
{
"code": null,
"e": 8900,
"s": 8844,
"text": "The full and absolute path to the driver shared library"
},
{
"code": null,
"e": 8956,
"s": 8900,
"text": "The full and absolute path to the driver shared library"
},
{
"code": null,
"e": 9061,
"s": 8956,
"text": "And any additional keyword arguments which will be included as KEY=VALUE pairs in the .ini config files."
},
{
"code": null,
"e": 9166,
"s": 9061,
"text": "And any additional keyword arguments which will be included as KEY=VALUE pairs in the .ini config files."
},
{
"code": null,
"e": 9247,
"s": 9166,
"text": "After installing the drivers, we can do the following for enabling connections −"
},
{
"code": null,
"e": 9310,
"s": 9247,
"text": "Setup a DSN, via ODBC.adddsn(\"dsn name\", \"driver name\"; kw...)"
},
{
"code": null,
"e": 9373,
"s": 9310,
"text": "Setup a DSN, via ODBC.adddsn(\"dsn name\", \"driver name\"; kw...)"
},
{
"code": null,
"e": 9467,
"s": 9373,
"text": "Connecting directly by using a full connection string like ODBC.Connection(connection_string)"
},
{
"code": null,
"e": 9561,
"s": 9467,
"text": "Connecting directly by using a full connection string like ODBC.Connection(connection_string)"
},
{
"code": null,
"e": 9607,
"s": 9561,
"text": "Following are two paths to execute queries − "
},
{
"code": null,
"e": 9740,
"s": 9607,
"text": "DBInterface.execute(conn, sql, params) − It will directly execute a SQL query and after that will return a Cursor for any resultset."
},
{
"code": null,
"e": 9873,
"s": 9740,
"text": "DBInterface.execute(conn, sql, params) − It will directly execute a SQL query and after that will return a Cursor for any resultset."
},
{
"code": null,
"e": 10080,
"s": 9873,
"text": "stmt = DBInterface.prepare(conn, sql); DBInterface.execute(stmt, params) − It will first prepare a SQL statement and then execute. The execution can be done perhaps multiple times with different parameters."
},
{
"code": null,
"e": 10287,
"s": 10080,
"text": "stmt = DBInterface.prepare(conn, sql); DBInterface.execute(stmt, params) − It will first prepare a SQL statement and then execute. The execution can be done perhaps multiple times with different parameters."
},
{
"code": null,
"e": 10478,
"s": 10287,
"text": "SQLlite is a fast, flexible delimited file reader and writer for Julia programming language. This package is registered in METADATA.jl hence can be installed by using the following command −"
},
{
"code": null,
"e": 10504,
"s": 10478,
"text": "julia> Pkg.add(\"SQLite\")\n"
},
{
"code": null,
"e": 10595,
"s": 10504,
"text": "We will discuss two important and useful functions used in SQLite along with the example −"
},
{
"code": null,
"e": 10790,
"s": 10595,
"text": "SQLite.DB(file::AbstractString) − This function requires the file string argument as the name of a pre-defined SQLite database to be opened. If the file does not exit, it will create a database."
},
{
"code": null,
"e": 10859,
"s": 10790,
"text": "julia> using SQLite\n\njulia> db = SQLite.DB(\"Chinook_Sqlite.sqlite\")\n"
},
{
"code": null,
"e": 10951,
"s": 10859,
"text": "Here we are using a sample database ‘Chinook’ available for SQLite, SQL Server, MySQL, etc."
},
{
"code": null,
"e": 11112,
"s": 10951,
"text": "SQLite.query(db::SQLite.DB, sql::String, values=[]) − This function returns the result, if any, after executing the prepared sql statement in the context of db."
},
{
"code": null,
"e": 11546,
"s": 11112,
"text": "julia> SQLite.query(db, \"SELECT * FROM Genre WHERE regexp('e[trs]', Name)\")\n6x2 ResultSet\n| Row | \"GenreId\" | \"Name\" |\n|-----|-----------|----------------------|\n| 1 | 3 | \"Metal\" |\n| 2 | 4 | \"Alternative & Punk\" |\n| 3 | 6 | \"Blues\" |\n| 4 | 13 | \"Heavy Metal\" |\n| 5 | 23 | \"Alternative\" |\n| 6 | 25 | \"Opera\" |"
},
{
"code": null,
"e": 11737,
"s": 11546,
"text": "PostgreSQL.jl is the PostgreSQL DBI driver. It is an interface to PostgreSQL from Julia programming language. It obeys the DBI.jl protocol for working and uses the C PostgreeSQL API (libpq)."
},
{
"code": null,
"e": 11798,
"s": 11737,
"text": "Let’s understand its usage with the help of following code −"
},
{
"code": null,
"e": 12122,
"s": 11798,
"text": "using DBI\nusing PostgreSQL\n\nconn = connect(Postgres, \"localhost\", \"username\", \"password\", \"dbname\", 5432)\n\nstmt = prepare(conn, \"SELECT 1::bigint, 2.0::double precision, 'foo'::character varying, \" *\n \"'foo'::character(10);\")\nresult = execute(stmt)\nfor row in result\n\nend\n\nfinish(stmt)\n\ndisconnect(conn)"
},
{
"code": null,
"e": 12195,
"s": 12122,
"text": "To use PostgreSQL we need to fulfill the following binary requirements −"
},
{
"code": null,
"e": 12202,
"s": 12195,
"text": "DBI.jl"
},
{
"code": null,
"e": 12209,
"s": 12202,
"text": "DBI.jl"
},
{
"code": null,
"e": 12233,
"s": 12209,
"text": "DataFrames.jl >= v0.5.7"
},
{
"code": null,
"e": 12257,
"s": 12233,
"text": "DataFrames.jl >= v0.5.7"
},
{
"code": null,
"e": 12281,
"s": 12257,
"text": "DataArrays.jl >= v0.1.2"
},
{
"code": null,
"e": 12305,
"s": 12281,
"text": "DataArrays.jl >= v0.1.2"
},
{
"code": null,
"e": 12381,
"s": 12305,
"text": "libpq shared library (comes with a standard PostgreSQL client installation)"
},
{
"code": null,
"e": 12457,
"s": 12381,
"text": "libpq shared library (comes with a standard PostgreSQL client installation)"
},
{
"code": null,
"e": 12477,
"s": 12457,
"text": "julia 0.3 or higher"
},
{
"code": null,
"e": 12497,
"s": 12477,
"text": "julia 0.3 or higher"
},
{
"code": null,
"e": 12611,
"s": 12497,
"text": "Hive.jl is a client for distributed SQL engine. It provides a HiveServer2, for example: Hive, Spark, SQL, Impala."
},
{
"code": null,
"e": 12699,
"s": 12611,
"text": "To connect to the server, we need to create an instance of the HiveSession as follows −"
},
{
"code": null,
"e": 12724,
"s": 12699,
"text": "session = HiveSession()\n"
},
{
"code": null,
"e": 12809,
"s": 12724,
"text": "It can also be connected by specifying the hostname and the port number as follows −"
},
{
"code": null,
"e": 12851,
"s": 12809,
"text": "session = HiveSession(“localhost”,10000)\n"
},
{
"code": null,
"e": 12982,
"s": 12851,
"text": "The default implementation as above will authenticates with the same user-id as that of the shell. We can override it as follows −"
},
{
"code": null,
"e": 13065,
"s": 12982,
"text": "session = HiveSession(\"localhost\", 10000, HiveAuthSASLPlain(\"uid\", \"pwd\", \"zid\"))\n"
},
{
"code": null,
"e": 13149,
"s": 13065,
"text": "We can execute DML, DDL, SET, etc., statements as we can see in the example below −"
},
{
"code": null,
"e": 13336,
"s": 13149,
"text": "crs = execute(session, \"select * from mytable where formid < 1001\";\n async=true, config=Dict())\nwhile !isready(crs)\n println(\"waiting...\")\n sleep(10)\nend\ncrs = result(crs)"
},
{
"code": null,
"e": 13515,
"s": 13336,
"text": "DBAPI is a new database interface proposal, inspired by Python’s DB API 2.0, that defies an abstract interface for database drivers in Julia. This module contains the following −"
},
{
"code": null,
"e": 13530,
"s": 13515,
"text": "Abstract types"
},
{
"code": null,
"e": 13545,
"s": 13530,
"text": "Abstract types"
},
{
"code": null,
"e": 13618,
"s": 13545,
"text": "Abstract required functions which throw a NotImplementedError by default"
},
{
"code": null,
"e": 13691,
"s": 13618,
"text": "Abstract required functions which throw a NotImplementedError by default"
},
{
"code": null,
"e": 13762,
"s": 13691,
"text": "Abstract optional functions which throw a NotSupportedError by default"
},
{
"code": null,
"e": 13833,
"s": 13762,
"text": "Abstract optional functions which throw a NotSupportedError by default"
},
{
"code": null,
"e": 13953,
"s": 13833,
"text": "To use this API, the database drivers must import this module, subtype its types, and create methods for its functions."
},
{
"code": null,
"e": 14037,
"s": 13953,
"text": "DBPrf is a Julia database which is maintained by JuliaDB. You see its usage below −"
},
{
"code": null,
"e": 14078,
"s": 14037,
"text": "The user can provide input in two ways −"
},
{
"code": null,
"e": 14180,
"s": 14078,
"text": "$ julia DBPerf.jl <Database_Driver_1.jl> <Database_Driver_2.jl> ....... <Database_Driver_N.jl> <DBMS>"
},
{
"code": null,
"e": 14237,
"s": 14180,
"text": "Here, Database_Driver.jl can be of the following types −"
},
{
"code": null,
"e": 14245,
"s": 14237,
"text": "ODBC.jl"
},
{
"code": null,
"e": 14253,
"s": 14245,
"text": "ODBC.jl"
},
{
"code": null,
"e": 14261,
"s": 14253,
"text": "JDBC.jl"
},
{
"code": null,
"e": 14269,
"s": 14261,
"text": "JDBC.jl"
},
{
"code": null,
"e": 14283,
"s": 14269,
"text": "PostgreSQL.jl"
},
{
"code": null,
"e": 14297,
"s": 14283,
"text": "PostgreSQL.jl"
},
{
"code": null,
"e": 14306,
"s": 14297,
"text": "MySQL.jl"
},
{
"code": null,
"e": 14315,
"s": 14306,
"text": "MySQL.jl"
},
{
"code": null,
"e": 14324,
"s": 14315,
"text": "Mongo.jl"
},
{
"code": null,
"e": 14333,
"s": 14324,
"text": "Mongo.jl"
},
{
"code": null,
"e": 14343,
"s": 14333,
"text": "SQLite.jl"
},
{
"code": null,
"e": 14353,
"s": 14343,
"text": "SQLite.jl"
},
{
"code": null,
"e": 14408,
"s": 14353,
"text": "DBMS filed is applicable only if we are using JDBC.jl."
},
{
"code": null,
"e": 14452,
"s": 14408,
"text": "The database can be either Oracle or MySQL."
},
{
"code": null,
"e": 14460,
"s": 14452,
"text": "Example"
},
{
"code": null,
"e": 14493,
"s": 14460,
"text": "DBPerf.jl ODBC.jl JDBC.jl MySql\n"
},
{
"code": null,
"e": 14624,
"s": 14493,
"text": "julia> include(\"DBPerf.jl\")\njulia> DBPerf(<Database_Driver_1.jl>, <Database_Driver_2.jl>, ....... <Database_Driver_N.jl>, <DBMS>)\n"
},
{
"code": null,
"e": 14632,
"s": 14624,
"text": "Example"
},
{
"code": null,
"e": 14671,
"s": 14632,
"text": "DBPerf(“ODBC.jl”, “JDBC.jl”, “MySql”)\n"
},
{
"code": null,
"e": 14704,
"s": 14671,
"text": "\n 73 Lectures \n 4 hours \n"
},
{
"code": null,
"e": 14721,
"s": 14704,
"text": " Lemuel Ogbunude"
},
{
"code": null,
"e": 14754,
"s": 14721,
"text": "\n 24 Lectures \n 3 hours \n"
},
{
"code": null,
"e": 14771,
"s": 14754,
"text": " Mohammad Nauman"
},
{
"code": null,
"e": 14806,
"s": 14771,
"text": "\n 29 Lectures \n 2.5 hours \n"
},
{
"code": null,
"e": 14829,
"s": 14806,
"text": " Stone River ELearning"
},
{
"code": null,
"e": 14836,
"s": 14829,
"text": " Print"
},
{
"code": null,
"e": 14847,
"s": 14836,
"text": " Add Notes"
}
] |
How to use bootstrap datepicker - Learn Tutorials Point
|
You can add datepicker to your website design, datepicker add for “datepicker” function in bootstrap.
<link href=”https://maxcdn.bootstrapcdn.com/bootstrap/3.2.0/css/bootstrap.min.css” rel=”stylesheet” type=”text/css” /><link href=”https://cdnjs.cloudflare.com/ajax/libs/bootstrap-datepicker/1.3.0/css/datepicker.css” rel=”stylesheet” type=”text/css” />
<script src=”https://maxcdn.bootstrapcdn.com/bootstrap/3.2.0/js/bootstrap.min.js”></script><script src=”https://cdnjs.cloudflare.com/ajax/libs/bootstrap-datepicker/1.3.0/js/bootstrap-datepicker.js”></script>
HTML Code
<label>Select Date: </label>
<div class="input-group date">
<input class="form-control" id="datepicker" type="text" />
<span class="input-group-addon"><i class="glyphicon glyphicon-calendar"></i></span>
</div>
javascript
<script>
$(function () {
$("#datepicker").datepicker({
autoclose: true,
todayHighlight: true
}).datepicker('update', new Date());
});
</script>
How to add active class in menu using jquery
How to add/remove textbox dynamically with jQuery
Simple Form validation jQuery snippet
How to create admin login page using PHP?
JavaScript Custom Countdown Timer For Advanced Custom Fields plugin in WordPress
Ajax
Bootstrap
CSS
HTML
Javascript
jQuery
PHP
WordPress
Your email address will not be published. Required fields are marked *
Comment
Name *
Email *
Website
Save my name, email, and website in this browser for the next time I comment.
|
[
{
"code": null,
"e": 165,
"s": 61,
"text": "You can add datepicker to your website design, datepicker add for “datepicker” function in bootstrap."
},
{
"code": null,
"e": 417,
"s": 165,
"text": "<link href=”https://maxcdn.bootstrapcdn.com/bootstrap/3.2.0/css/bootstrap.min.css” rel=”stylesheet” type=”text/css” /><link href=”https://cdnjs.cloudflare.com/ajax/libs/bootstrap-datepicker/1.3.0/css/datepicker.css” rel=”stylesheet” type=”text/css” />"
},
{
"code": null,
"e": 625,
"s": 417,
"text": "<script src=”https://maxcdn.bootstrapcdn.com/bootstrap/3.2.0/js/bootstrap.min.js”></script><script src=”https://cdnjs.cloudflare.com/ajax/libs/bootstrap-datepicker/1.3.0/js/bootstrap-datepicker.js”></script>"
},
{
"code": null,
"e": 1028,
"s": 625,
"text": "HTML Code\n\n<label>Select Date: </label>\n<div class=\"input-group date\">\n <input class=\"form-control\" id=\"datepicker\" type=\"text\" />\n <span class=\"input-group-addon\"><i class=\"glyphicon glyphicon-calendar\"></i></span>\n</div>\n\njavascript\n\n<script>\n $(function () {\n $(\"#datepicker\").datepicker({ \n autoclose: true, \n todayHighlight: true\n }).datepicker('update', new Date());\n });\n</script>"
},
{
"code": null,
"e": 1075,
"s": 1028,
"text": "\nHow to add active class in menu using jquery\n"
},
{
"code": null,
"e": 1127,
"s": 1075,
"text": "\nHow to add/remove textbox dynamically with jQuery\n"
},
{
"code": null,
"e": 1167,
"s": 1127,
"text": "\nSimple Form validation jQuery snippet\n"
},
{
"code": null,
"e": 1211,
"s": 1167,
"text": "\nHow to create admin login page using PHP?\n"
},
{
"code": null,
"e": 1294,
"s": 1211,
"text": "\nJavaScript Custom Countdown Timer For Advanced Custom Fields plugin in WordPress\n"
},
{
"code": null,
"e": 1300,
"s": 1294,
"text": "Ajax\n"
},
{
"code": null,
"e": 1311,
"s": 1300,
"text": "Bootstrap\n"
},
{
"code": null,
"e": 1316,
"s": 1311,
"text": "CSS\n"
},
{
"code": null,
"e": 1322,
"s": 1316,
"text": "HTML\n"
},
{
"code": null,
"e": 1334,
"s": 1322,
"text": "Javascript\n"
},
{
"code": null,
"e": 1342,
"s": 1334,
"text": "jQuery\n"
},
{
"code": null,
"e": 1347,
"s": 1342,
"text": "PHP\n"
},
{
"code": null,
"e": 1358,
"s": 1347,
"text": "WordPress\n"
},
{
"code": null,
"e": 1449,
"s": 1378,
"text": "Your email address will not be published. Required fields are marked *"
},
{
"code": null,
"e": 1458,
"s": 1449,
"text": "Comment "
},
{
"code": null,
"e": 1466,
"s": 1458,
"text": "Name * "
},
{
"code": null,
"e": 1475,
"s": 1466,
"text": "Email * "
},
{
"code": null,
"e": 1484,
"s": 1475,
"text": "Website "
}
] |
Create table SQL query in SAP HANA
|
In below SQL query, you can see a create table command in SQL editor to create a new table with name-“Demo_HANA” in schema name AA_HANA11 with column names- ID and NAME and corresponding data types. In the below example, we have defined ID as “Primary Key” which means it is unique and not null.
Create Table Demo_HANA (
ID INTEGER,
NAME VARCHAR(10),
PRIMARY KEY (ID)
);
|
[
{
"code": null,
"e": 1358,
"s": 1062,
"text": "In below SQL query, you can see a create table command in SQL editor to create a new table with name-“Demo_HANA” in schema name AA_HANA11 with column names- ID and NAME and corresponding data types. In the below example, we have defined ID as “Primary Key” which means it is unique and not null."
},
{
"code": null,
"e": 1442,
"s": 1358,
"text": "Create Table Demo_HANA (\n ID INTEGER,\n NAME VARCHAR(10),\n PRIMARY KEY (ID)\n);"
}
] |
C - Arrays
|
Arrays a kind of data structure that can store a fixed-size sequential collection of elements of the same 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 number0, number1, ..., and number99, you declare one array variable such as numbers and use numbers[0], numbers[1], and ..., numbers[99] to represent individual variables. A specific element in an array is accessed by an index.
All arrays consist of contiguous memory locations. The lowest address corresponds to the first element and the highest address to the last element.
To declare an array in C, a programmer specifies the type of the elements and the number of elements required by an array as follows −
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, to declare a 10-element array called balance of type double, use this statement −
double balance[10];
Here balance is a variable array which is sufficient to hold up to 10 double numbers.
You can initialize an array in C either one by one or using a single statement as follows −
double balance[5] = {1000.0, 2.0, 3.4, 7.0, 50.0};
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 −
double balance[] = {1000.0, 2.0, 3.4, 7.0, 50.0};
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 −
balance[4] = 50.0;
The above statement assigns the 5th element in the array with a value of 50.0. 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 total size of the array minus 1. Shown below is 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 −
double salary = balance[9];
The above statement will take the 10th element from the array and assign the value to salary variable. The following example Shows how to use all the three above mentioned concepts viz. declaration, assignment, and accessing arrays −
#include <stdio.h>
int main () {
int n[ 10 ]; /* n is an array of 10 integers */
int i,j;
/* initialize elements of array n to 0 */
for ( i = 0; i < 10; i++ ) {
n[ i ] = i + 100; /* set element at location i to i + 100 */
}
/* output each array element's value */
for (j = 0; j < 10; j++ ) {
printf("Element[%d] = %d\n", j, n[j] );
}
return 0;
}
When the above code is compiled and executed, it produces the following result −
Element[0] = 100
Element[1] = 101
Element[2] = 102
Element[3] = 103
Element[4] = 104
Element[5] = 105
Element[6] = 106
Element[7] = 107
Element[8] = 108
Element[9] = 109
Arrays are important to C and should need a lot more attention. The following important concepts related to array should be clear to a C programmer −
C supports multidimensional arrays. The simplest form of the multidimensional array is the two-dimensional array.
You can pass to the function a pointer to an array by specifying the array's name without an index.
C allows a function to return an array.
You can generate a pointer to the first element of an array by simply specifying the array name, without any index.
Print
Add Notes
Bookmark this page
|
[
{
"code": null,
"e": 2340,
"s": 2084,
"text": "Arrays a kind of data structure that can store a fixed-size sequential collection of elements of the same 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": 2619,
"s": 2340,
"text": "Instead of declaring individual variables, such as number0, number1, ..., and number99, you declare one array variable such as numbers and use numbers[0], numbers[1], and ..., numbers[99] to represent individual variables. A specific element in an array is accessed by an index."
},
{
"code": null,
"e": 2767,
"s": 2619,
"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": 2902,
"s": 2767,
"text": "To declare an array in C, a programmer specifies the type of the elements and the number of elements required by an array as follows −"
},
{
"code": null,
"e": 2933,
"s": 2902,
"text": "type arrayName [ arraySize ];\n"
},
{
"code": null,
"e": 3170,
"s": 2933,
"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, to declare a 10-element array called balance of type double, use this statement −"
},
{
"code": null,
"e": 3191,
"s": 3170,
"text": "double balance[10];\n"
},
{
"code": null,
"e": 3277,
"s": 3191,
"text": "Here balance is a variable array which is sufficient to hold up to 10 double numbers."
},
{
"code": null,
"e": 3369,
"s": 3277,
"text": "You can initialize an array in C either one by one or using a single statement as follows −"
},
{
"code": null,
"e": 3421,
"s": 3369,
"text": "double balance[5] = {1000.0, 2.0, 3.4, 7.0, 50.0};\n"
},
{
"code": null,
"e": 3565,
"s": 3421,
"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": 3690,
"s": 3565,
"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": 3741,
"s": 3690,
"text": "double balance[] = {1000.0, 2.0, 3.4, 7.0, 50.0};\n"
},
{
"code": null,
"e": 3882,
"s": 3741,
"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": 3902,
"s": 3882,
"text": "balance[4] = 50.0;\n"
},
{
"code": null,
"e": 4221,
"s": 3902,
"text": "The above statement assigns the 5th element in the array with a value of 50.0. 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 total size of the array minus 1. Shown below is the pictorial representation of the array we discussed above −"
},
{
"code": null,
"e": 4387,
"s": 4221,
"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": 4416,
"s": 4387,
"text": "double salary = balance[9];\n"
},
{
"code": null,
"e": 4650,
"s": 4416,
"text": "The above statement will take the 10th element from the array and assign the value to salary variable. The following example Shows how to use all the three above mentioned concepts viz. declaration, assignment, and accessing arrays −"
},
{
"code": null,
"e": 5055,
"s": 4650,
"text": "#include <stdio.h>\n \nint main () {\n\n int n[ 10 ]; /* n is an array of 10 integers */\n int i,j;\n \n /* initialize elements of array n to 0 */ \n for ( i = 0; i < 10; i++ ) {\n n[ i ] = i + 100; /* set element at location i to i + 100 */\n }\n \n /* output each array element's value */\n for (j = 0; j < 10; j++ ) {\n printf(\"Element[%d] = %d\\n\", j, n[j] );\n }\n \n return 0;\n}"
},
{
"code": null,
"e": 5136,
"s": 5055,
"text": "When the above code is compiled and executed, it produces the following result −"
},
{
"code": null,
"e": 5307,
"s": 5136,
"text": "Element[0] = 100\nElement[1] = 101\nElement[2] = 102\nElement[3] = 103\nElement[4] = 104\nElement[5] = 105\nElement[6] = 106\nElement[7] = 107\nElement[8] = 108\nElement[9] = 109\n"
},
{
"code": null,
"e": 5457,
"s": 5307,
"text": "Arrays are important to C and should need a lot more attention. The following important concepts related to array should be clear to a C programmer −"
},
{
"code": null,
"e": 5571,
"s": 5457,
"text": "C supports multidimensional arrays. The simplest form of the multidimensional array is the two-dimensional array."
},
{
"code": null,
"e": 5671,
"s": 5571,
"text": "You can pass to the function a pointer to an array by specifying the array's name without an index."
},
{
"code": null,
"e": 5711,
"s": 5671,
"text": "C allows a function to return an array."
},
{
"code": null,
"e": 5827,
"s": 5711,
"text": "You can generate a pointer to the first element of an array by simply specifying the array name, without any index."
},
{
"code": null,
"e": 5834,
"s": 5827,
"text": " Print"
},
{
"code": null,
"e": 5845,
"s": 5834,
"text": " Add Notes"
}
] |
CSS - background-position
|
Sets the initial position of the element's background image, if specified; values normally are paired to provide x, y positions; default position is 0% 0%.
percent
none
length
top
center
bottom
left
right
block-level and replaced elements
object.style.backgroundPosition = "10 30";
Following is the example which demonstrates how to set the background image position 100 pixels away from the left side.
<table style = "background-image:url(/images/pattern1.gif); background-position:100px;">
<tr>
<td>
Background image positioned 100 pixels away from the left.
</td>
</tr>
</table>
Following is the example which demonstrates how to set the background image position 100 pixels away from the left side and 200 pixels down from the top.
<html>
<head>
</head>
<body>
<p style = "background-image:url(/css/images/logo.png);
background-position:100px 200px;">
The background image positioned 100 pixels away from the
left and 200 pixels from the top.up
</p>
</body>
</html>
It will produce the following result −
The background image positioned 100 pixels away from the left and 200 pixels from the top.
33 Lectures
2.5 hours
Anadi Sharma
26 Lectures
2.5 hours
Frahaan Hussain
44 Lectures
4.5 hours
DigiFisk (Programming Is Fun)
21 Lectures
2.5 hours
DigiFisk (Programming Is Fun)
51 Lectures
7.5 hours
DigiFisk (Programming Is Fun)
52 Lectures
4 hours
DigiFisk (Programming Is Fun)
Print
Add Notes
Bookmark this page
|
[
{
"code": null,
"e": 2782,
"s": 2626,
"text": "Sets the initial position of the element's background image, if specified; values normally are paired to provide x, y positions; default position is 0% 0%."
},
{
"code": null,
"e": 2790,
"s": 2782,
"text": "percent"
},
{
"code": null,
"e": 2795,
"s": 2790,
"text": "none"
},
{
"code": null,
"e": 2802,
"s": 2795,
"text": "length"
},
{
"code": null,
"e": 2806,
"s": 2802,
"text": "top"
},
{
"code": null,
"e": 2813,
"s": 2806,
"text": "center"
},
{
"code": null,
"e": 2820,
"s": 2813,
"text": "bottom"
},
{
"code": null,
"e": 2825,
"s": 2820,
"text": "left"
},
{
"code": null,
"e": 2831,
"s": 2825,
"text": "right"
},
{
"code": null,
"e": 2865,
"s": 2831,
"text": "block-level and replaced elements"
},
{
"code": null,
"e": 2909,
"s": 2865,
"text": "object.style.backgroundPosition = \"10 30\";\n"
},
{
"code": null,
"e": 3030,
"s": 2909,
"text": "Following is the example which demonstrates how to set the background image position 100 pixels away from the left side."
},
{
"code": null,
"e": 3236,
"s": 3030,
"text": "<table style = \"background-image:url(/images/pattern1.gif); background-position:100px;\">\n <tr>\n <td>\n Background image positioned 100 pixels away from the left.\n </td>\n </tr>\n</table>"
},
{
"code": null,
"e": 3390,
"s": 3236,
"text": "Following is the example which demonstrates how to set the background image position 100 pixels away from the left side and 200 pixels down from the top."
},
{
"code": null,
"e": 3680,
"s": 3390,
"text": "<html>\n <head>\n </head>\n\n <body>\n <p style = \"background-image:url(/css/images/logo.png); \n background-position:100px 200px;\">\n The background image positioned 100 pixels away from the \n left and 200 pixels from the top.up\n </p>\n </body>\n</html>"
},
{
"code": null,
"e": 3719,
"s": 3680,
"text": "It will produce the following result −"
},
{
"code": null,
"e": 3821,
"s": 3719,
"text": "\n\n The background image positioned 100 pixels away from the left and 200 pixels from the top.\n "
},
{
"code": null,
"e": 3856,
"s": 3821,
"text": "\n 33 Lectures \n 2.5 hours \n"
},
{
"code": null,
"e": 3870,
"s": 3856,
"text": " Anadi Sharma"
},
{
"code": null,
"e": 3905,
"s": 3870,
"text": "\n 26 Lectures \n 2.5 hours \n"
},
{
"code": null,
"e": 3922,
"s": 3905,
"text": " Frahaan Hussain"
},
{
"code": null,
"e": 3957,
"s": 3922,
"text": "\n 44 Lectures \n 4.5 hours \n"
},
{
"code": null,
"e": 3988,
"s": 3957,
"text": " DigiFisk (Programming Is Fun)"
},
{
"code": null,
"e": 4023,
"s": 3988,
"text": "\n 21 Lectures \n 2.5 hours \n"
},
{
"code": null,
"e": 4054,
"s": 4023,
"text": " DigiFisk (Programming Is Fun)"
},
{
"code": null,
"e": 4089,
"s": 4054,
"text": "\n 51 Lectures \n 7.5 hours \n"
},
{
"code": null,
"e": 4120,
"s": 4089,
"text": " DigiFisk (Programming Is Fun)"
},
{
"code": null,
"e": 4153,
"s": 4120,
"text": "\n 52 Lectures \n 4 hours \n"
},
{
"code": null,
"e": 4184,
"s": 4153,
"text": " DigiFisk (Programming Is Fun)"
},
{
"code": null,
"e": 4191,
"s": 4184,
"text": " Print"
},
{
"code": null,
"e": 4202,
"s": 4191,
"text": " Add Notes"
}
] |
Adding new column after a specific column and defining a default in MySQL?
|
You need to follow some steps to add a new column after a specific column and defining default value. In order to achieve this, you need to use ALTER command. Let us first create a table −
mysql> create table DemoTable
(
StudentId int NOT NULL AUTO_INCREMENT PRIMARY KEY,
StudentFirstName varchar(20),
StudentAge int,
StudentCountryName varchar(100)
);
Query OK, 0 rows affected (0.21 sec)
Let us check the description of table −
mysql> desc DemoTable;
This will produce the following output −
+--------------------+--------------+------+-----+---------+----------------+
| Field | Type | Null | Key | Default | Extra |
+--------------------+--------------+------+-----+---------+----------------+
| StudentId | int(11) | NO | PRI | NULL | auto_increment |
| StudentFirstName | varchar(20) | YES | | NULL | |
| StudentAge | int(11) | YES | | NULL | |
| StudentCountryName | varchar(100) | YES | | NULL | |
+--------------------+--------------+------+-----+---------+----------------+
4 rows in set (0.15 sec)
Following is the query to add a new column after a specific column and defining a default. Let us add a new column “StudentLastName” after column name “StudentFirstName”. The default value of StudentLastName column is “Doe”.
mysql> alter table DemoTable add StudentLastName varchar(20) NOT NULL after StudentFirstName;
Query OK, 0 rows affected (0.91 sec)
Records: 0 Duplicates: 0 Warnings: 0
mysql> alter table DemoTable alter StudentLastName set default 'Doe';
Query OK, 0 rows affected (0.32 sec)
Records: 0 Duplicates: 0 Warnings: 0
Let us check the description of table once again.
mysql> desc DemoTable;
This will produce the following output −
+--------------------+--------------+------+-----+---------+----------------+
| Field | Type | Null | Key | Default | Extra |
+--------------------+--------------+------+-----+---------+----------------+
| StudentId | int(11) | NO | PRI | NULL | auto_increment |
| StudentFirstName | varchar(20) | YES | | NULL | |
| StudentLastName | varchar(20) | NO | | Doe | |
| StudentAge | int(11) | YES | | NULL | |
| StudentCountryName | varchar(100) | YES | | NULL | |
+--------------------+--------------+------+-----+---------+----------------+
5 rows in set (0.01 sec)
|
[
{
"code": null,
"e": 1251,
"s": 1062,
"text": "You need to follow some steps to add a new column after a specific column and defining default value. In order to achieve this, you need to use ALTER command. Let us first create a table −"
},
{
"code": null,
"e": 1470,
"s": 1251,
"text": "mysql> create table DemoTable\n (\n StudentId int NOT NULL AUTO_INCREMENT PRIMARY KEY,\n StudentFirstName varchar(20),\n StudentAge int,\n StudentCountryName varchar(100)\n );\nQuery OK, 0 rows affected (0.21 sec)"
},
{
"code": null,
"e": 1510,
"s": 1470,
"text": "Let us check the description of table −"
},
{
"code": null,
"e": 1533,
"s": 1510,
"text": "mysql> desc DemoTable;"
},
{
"code": null,
"e": 1574,
"s": 1533,
"text": "This will produce the following output −"
},
{
"code": null,
"e": 2223,
"s": 1574,
"text": "+--------------------+--------------+------+-----+---------+----------------+\n| Field | Type | Null | Key | Default | Extra |\n+--------------------+--------------+------+-----+---------+----------------+\n| StudentId | int(11) | NO | PRI | NULL | auto_increment |\n| StudentFirstName | varchar(20) | YES | | NULL | |\n| StudentAge | int(11) | YES | | NULL | |\n| StudentCountryName | varchar(100) | YES | | NULL | |\n+--------------------+--------------+------+-----+---------+----------------+\n4 rows in set (0.15 sec)"
},
{
"code": null,
"e": 2448,
"s": 2223,
"text": "Following is the query to add a new column after a specific column and defining a default. Let us add a new column “StudentLastName” after column name “StudentFirstName”. The default value of StudentLastName column is “Doe”."
},
{
"code": null,
"e": 2761,
"s": 2448,
"text": "mysql> alter table DemoTable add StudentLastName varchar(20) NOT NULL after StudentFirstName;\nQuery OK, 0 rows affected (0.91 sec)\nRecords: 0 Duplicates: 0 Warnings: 0\n\nmysql> alter table DemoTable alter StudentLastName set default 'Doe';\nQuery OK, 0 rows affected (0.32 sec)\nRecords: 0 Duplicates: 0 Warnings: 0"
},
{
"code": null,
"e": 2811,
"s": 2761,
"text": "Let us check the description of table once again."
},
{
"code": null,
"e": 2834,
"s": 2811,
"text": "mysql> desc DemoTable;"
},
{
"code": null,
"e": 2875,
"s": 2834,
"text": "This will produce the following output −"
},
{
"code": null,
"e": 3602,
"s": 2875,
"text": "+--------------------+--------------+------+-----+---------+----------------+\n| Field | Type | Null | Key | Default | Extra |\n+--------------------+--------------+------+-----+---------+----------------+\n| StudentId | int(11) | NO | PRI | NULL | auto_increment |\n| StudentFirstName | varchar(20) | YES | | NULL | |\n| StudentLastName | varchar(20) | NO | | Doe | |\n| StudentAge | int(11) | YES | | NULL | |\n| StudentCountryName | varchar(100) | YES | | NULL | |\n+--------------------+--------------+------+-----+---------+----------------+\n5 rows in set (0.01 sec)"
}
] |
Introducing Xverse! — A python package for feature selection and transformation | by Sundar Krishnan | Towards Data Science
|
Xverse short for X Universe is a python package for machine learning to assist Data Scientists with feature transformation and feature selection. Before we talk about the details of the package, let us understand why we need one.
I came across this image and I felt there is no better way to explain this project. As funny as it sounds, it happens in most of the data science life cycle. 80% of the time spent by Data Scientists lies in dealing with features (X), and therefore the name XuniVerse a.k.a “xverse”.
In addition, the entire project is based on the works that I published in Medium in 2018. Based on the feedback I got from readers, I wanted to improve the functionalities of the code. Instead of releasing it as an updated functionality, I thought it would be better to release it as a python package. Well, that is how “xverse” is born.
The articles shown here below are now part of this package.
medium.com
“Weight of evidence (WOE) and Information value (IV) are simple, yet powerful techniques to perform variable transformation and selection. These concepts have huge connection with the logistic regression modeling technique. It is widely used in credit scoring to measure the separation of good vs bad customers.”
medium.com
“The idea is to apply a variety of techniques to select variables. When an algorithm picks a variable, we give a vote for the variable. At the end, we calculate the total votes for each variables and then pick the best ones based on votes. This way, we end up picking the best variables with minimum effort in the variable selection process.”
github.com
The dataset used for all the examples shown below is present in the “data” folder. In addition, you can refer to the Jupyter notebook code “Xverse.ipynb” present in this link.
Monotonic Binning is a data preparation technique widely used in scorecard development. It tries to convert numerical variable to categorical variable by creating bins which have a monotonic relationship with the target. The example given below will demonstrate how it works.
The feature ‘balance’ shown above ranges from $-3,313.001 to $71,188. We can all agree that this is a very wide range. If we have to bin this variable based on domain knowledge, then we don’t have to worry about a monotonic relationship. However, when no prior knowledge exists, then it is hard to determine the bin categories. This is an ideal situation where monotonic binning could help.
It starts with 20 bins (default, which you can change any time) and then reduces bins until it finds a monotonic relationship (either increasing or decreasing) between X variable and target y. If it did not establish a monotonic relationship, then it forces to create bins on X variable using the force_bins option. All this time, it uses spearman correlation to verify if there is a monotonic relationship exists between X and y variable.
Pros in Monotonic Binning:
Handle outliersEstablish a monotonic relationship between a feature and target variable
Handle outliers
Establish a monotonic relationship between a feature and target variable
Cons in Monotonic Binning:
We lose information during variable binningNo proper way to treat missing values
We lose information during variable binning
No proper way to treat missing values
from xverse.transformer import MonotonicBinningclf = MonotonicBinning()clf.fit(X, y)print(clf.bins)output_bins = clf.bins #will be used later in this exercise
Here X represents the features dataset which is a Pandas dataframe and y is a numpy array of target column. We can also use the precomputed monotonic bins to apply on new datasets as shown below.
clf = MonotonicBinning(custom_binning=output_bins) #output_bins was created earlierout_X = clf.transform(X)out_X.head()
The WOE package is available in the transformer function. The advantages of WOE transformation are
Handles missing valuesHandles outliersThe transformation is based on logarithmic value of distributions. This is aligned with the logistic regression output functionNo need for dummy variablesBy using proper binning technique, it can establish monotonic relationship (either increase or decrease) between the independent and dependent variableIV value can be used to select variables quickly.
Handles missing values
Handles outliers
The transformation is based on logarithmic value of distributions. This is aligned with the logistic regression output function
No need for dummy variables
By using proper binning technique, it can establish monotonic relationship (either increase or decrease) between the independent and dependent variable
IV value can be used to select variables quickly.
The formula to calculate WOE and IV is provided below.
or simply,
from xverse.transformer import WOEclf = WOE()clf.fit(X, y)clf.woe_df # weight of evidence transformation dataset. This dataset will be used in making bivariate charts as well. clf.iv_df #information value dataset
To select features, please use the rule below
+-------------------+-----------------------------+| Information Value | Variable Predictiveness |+-------------------+-----------------------------+| Less than 0.02 | Not useful for prediction |+-------------------+-----------------------------+| 0.02 to 0.1 | Weak predictive Power |+-------------------+-----------------------------+| 0.1 to 0.3 | Medium predictive Power |+-------------------+-----------------------------+| 0.3 to 0.5 | Strong predictive Power |+-------------------+-----------------------------+| >0.5 | Suspicious Predictive Power |+-------------------+-----------------------------+
And to transform variable X based on WOE bins calculated before, use the code below.
clf.transform(X) #apply WOE transformation on the dataset
output_woe_bins = clf.woe_bins #future transformationoutput_mono_bins = clf.mono_custom_binning #future transformationclf = WOE(woe_bins=output_woe_bins, mono_custom_binning=output_mono_bins) #output_bins was created earlierout_X = clf.transform(X)
treat_missing: {‘separate’, ‘mode’, ‘least_frequent’} (default=’separate’)This parameter setting is used to handle missing values in the dataset. ‘separate’ — Missing values are treated as a own group (category) ‘mode’ — Missing values are combined with the highest frequent item in the dataset ‘least_frequent’ — Missing values are combined with the least frequent item in the dataset
Bivariate distributions help us explore relationship between X and y variables. This option is available in “xverse” as well.
To make bivariate charts, we need the “woe_df” dataset generated from the WOE option shown above.
woe_df = clf.woe_dffrom xverse.graph import BarChartsclf = BarCharts(bar_type='v')clf.plot(woe_df)
plot_metric: 'count' or 'mean' (default='mean') Metric to be used while plotting the bivariate chart. 'count' - Event counts in the particular bin 'mean' - Mean event rate in the particular binbar_type: 'horizontal' or 'vertical' (default='vertical') Type of bar chart.fig_size: figure size for each of the individual plots (default=(8,6))bar_color: CSS color style picker. Use it with the hashtag in the front. (default='#058caa') Bar color num_color: CSS color style picker. Use it with the hashtag in the front (default='#ed8549') Numbers color. It represents the numbers written on top of the bar.
Variable selection is one of the key process in predictive modeling process. It is an art. To put in simple terms, variable selection is like picking a soccer team to win the World cup. You need to have the best player in each position and you don’t want two or many players who plays the same position.
In python, we have different techniques to select variables. Some of them include Recursive feature elimination, Tree-based selection and L1 based feature selection.
The idea here is to apply a variety of techniques to select variables. When an algorithm picks a variable, we give a vote for the variable. In the end, we calculate the total votes for each variable and then pick the best ones based on votes. This way, we end up picking the best variables with minimum effort in the variable selection process.
from xverse.ensemble import VotingSelectorclf = VotingSelector()clf.fit(X, y)
Now, let’s look at the feature importance using the code below.
clf.feature_importances_
clf.feature_votes_
clf.transform(X).head()
selection_techniques: 'all', 'quick' or list(default='all') List of selection techniques to be applied on the data. Available techniques - Weight of evidence ('WOE'), Random Forest ('RF'), Recursive Feature Elimination ('RFE'), Extra Trees Classifier ('ETC'), Chi Square ('CS'), L1 feature selection ('L_ONE'). 'all' - Apply all selection techniques ['WOE', 'RF', 'RFE', 'ETC', 'CS', 'L_ONE'] 'quick' - ['WOE','RF','ETC'] list - user provided list of feature selection techniques from available techniques no_of_featues: 'auto', 'sqrt' or int(default='auto') Number of features to be selected by each selection technique. 'auto' - len(features)/2 'sqrt' - sqrt(len(features)) rounded to the lowest number int - user provided number in integer format handle_category= 'woe' or 'le' (default='woe') Handle category values transformation using Label encoder or Weight of Evidence option. Takes care of missing values too. It treats missing values as separate level. 'woe' - use weight of evidence transformation 'le' - use label encoder transformation numerical_missing_values= 'median', 'mean' or 0 (default='median') Handle numerical variable missing values. 'median' - use median of the column 'mean' - use mean of the column 0 - use 0 to impute the missing values minimum_votes = int (default=0) Minimum number of votes needed to select a variable after feature selection. Only used in the transform process. Default value is set to 0 to select all variables.
Finally, one important thing about “Xverse” is the pipeline functionality. We can add all the steps as part of the pipeline and make our lives much easier.
Here is a code shown below that shows the pipeline feature.
from sklearn.pipeline import Pipelineclf = Pipeline(steps=[('split_x_y', SplitXY(['target'])),('feature_votes', VotingSelector())])clf.fit(df, df['target'])
Finally, to get the transformation on a new dataset,
clf.transform(df)
XuniVerse is under active development, if you’d like to be involved, we’d love to have you. Please leave a response in this article and we can talk about next steps.
The codes are given in a single notebook here for you to experiment on your own dataset.
|
[
{
"code": null,
"e": 402,
"s": 172,
"text": "Xverse short for X Universe is a python package for machine learning to assist Data Scientists with feature transformation and feature selection. Before we talk about the details of the package, let us understand why we need one."
},
{
"code": null,
"e": 685,
"s": 402,
"text": "I came across this image and I felt there is no better way to explain this project. As funny as it sounds, it happens in most of the data science life cycle. 80% of the time spent by Data Scientists lies in dealing with features (X), and therefore the name XuniVerse a.k.a “xverse”."
},
{
"code": null,
"e": 1023,
"s": 685,
"text": "In addition, the entire project is based on the works that I published in Medium in 2018. Based on the feedback I got from readers, I wanted to improve the functionalities of the code. Instead of releasing it as an updated functionality, I thought it would be better to release it as a python package. Well, that is how “xverse” is born."
},
{
"code": null,
"e": 1083,
"s": 1023,
"text": "The articles shown here below are now part of this package."
},
{
"code": null,
"e": 1094,
"s": 1083,
"text": "medium.com"
},
{
"code": null,
"e": 1407,
"s": 1094,
"text": "“Weight of evidence (WOE) and Information value (IV) are simple, yet powerful techniques to perform variable transformation and selection. These concepts have huge connection with the logistic regression modeling technique. It is widely used in credit scoring to measure the separation of good vs bad customers.”"
},
{
"code": null,
"e": 1418,
"s": 1407,
"text": "medium.com"
},
{
"code": null,
"e": 1761,
"s": 1418,
"text": "“The idea is to apply a variety of techniques to select variables. When an algorithm picks a variable, we give a vote for the variable. At the end, we calculate the total votes for each variables and then pick the best ones based on votes. This way, we end up picking the best variables with minimum effort in the variable selection process.”"
},
{
"code": null,
"e": 1772,
"s": 1761,
"text": "github.com"
},
{
"code": null,
"e": 1948,
"s": 1772,
"text": "The dataset used for all the examples shown below is present in the “data” folder. In addition, you can refer to the Jupyter notebook code “Xverse.ipynb” present in this link."
},
{
"code": null,
"e": 2224,
"s": 1948,
"text": "Monotonic Binning is a data preparation technique widely used in scorecard development. It tries to convert numerical variable to categorical variable by creating bins which have a monotonic relationship with the target. The example given below will demonstrate how it works."
},
{
"code": null,
"e": 2615,
"s": 2224,
"text": "The feature ‘balance’ shown above ranges from $-3,313.001 to $71,188. We can all agree that this is a very wide range. If we have to bin this variable based on domain knowledge, then we don’t have to worry about a monotonic relationship. However, when no prior knowledge exists, then it is hard to determine the bin categories. This is an ideal situation where monotonic binning could help."
},
{
"code": null,
"e": 3055,
"s": 2615,
"text": "It starts with 20 bins (default, which you can change any time) and then reduces bins until it finds a monotonic relationship (either increasing or decreasing) between X variable and target y. If it did not establish a monotonic relationship, then it forces to create bins on X variable using the force_bins option. All this time, it uses spearman correlation to verify if there is a monotonic relationship exists between X and y variable."
},
{
"code": null,
"e": 3082,
"s": 3055,
"text": "Pros in Monotonic Binning:"
},
{
"code": null,
"e": 3170,
"s": 3082,
"text": "Handle outliersEstablish a monotonic relationship between a feature and target variable"
},
{
"code": null,
"e": 3186,
"s": 3170,
"text": "Handle outliers"
},
{
"code": null,
"e": 3259,
"s": 3186,
"text": "Establish a monotonic relationship between a feature and target variable"
},
{
"code": null,
"e": 3286,
"s": 3259,
"text": "Cons in Monotonic Binning:"
},
{
"code": null,
"e": 3367,
"s": 3286,
"text": "We lose information during variable binningNo proper way to treat missing values"
},
{
"code": null,
"e": 3411,
"s": 3367,
"text": "We lose information during variable binning"
},
{
"code": null,
"e": 3449,
"s": 3411,
"text": "No proper way to treat missing values"
},
{
"code": null,
"e": 3608,
"s": 3449,
"text": "from xverse.transformer import MonotonicBinningclf = MonotonicBinning()clf.fit(X, y)print(clf.bins)output_bins = clf.bins #will be used later in this exercise"
},
{
"code": null,
"e": 3804,
"s": 3608,
"text": "Here X represents the features dataset which is a Pandas dataframe and y is a numpy array of target column. We can also use the precomputed monotonic bins to apply on new datasets as shown below."
},
{
"code": null,
"e": 3924,
"s": 3804,
"text": "clf = MonotonicBinning(custom_binning=output_bins) #output_bins was created earlierout_X = clf.transform(X)out_X.head()"
},
{
"code": null,
"e": 4023,
"s": 3924,
"text": "The WOE package is available in the transformer function. The advantages of WOE transformation are"
},
{
"code": null,
"e": 4416,
"s": 4023,
"text": "Handles missing valuesHandles outliersThe transformation is based on logarithmic value of distributions. This is aligned with the logistic regression output functionNo need for dummy variablesBy using proper binning technique, it can establish monotonic relationship (either increase or decrease) between the independent and dependent variableIV value can be used to select variables quickly."
},
{
"code": null,
"e": 4439,
"s": 4416,
"text": "Handles missing values"
},
{
"code": null,
"e": 4456,
"s": 4439,
"text": "Handles outliers"
},
{
"code": null,
"e": 4584,
"s": 4456,
"text": "The transformation is based on logarithmic value of distributions. This is aligned with the logistic regression output function"
},
{
"code": null,
"e": 4612,
"s": 4584,
"text": "No need for dummy variables"
},
{
"code": null,
"e": 4764,
"s": 4612,
"text": "By using proper binning technique, it can establish monotonic relationship (either increase or decrease) between the independent and dependent variable"
},
{
"code": null,
"e": 4814,
"s": 4764,
"text": "IV value can be used to select variables quickly."
},
{
"code": null,
"e": 4869,
"s": 4814,
"text": "The formula to calculate WOE and IV is provided below."
},
{
"code": null,
"e": 4880,
"s": 4869,
"text": "or simply,"
},
{
"code": null,
"e": 5093,
"s": 4880,
"text": "from xverse.transformer import WOEclf = WOE()clf.fit(X, y)clf.woe_df # weight of evidence transformation dataset. This dataset will be used in making bivariate charts as well. clf.iv_df #information value dataset"
},
{
"code": null,
"e": 5139,
"s": 5093,
"text": "To select features, please use the rule below"
},
{
"code": null,
"e": 5803,
"s": 5139,
"text": "+-------------------+-----------------------------+| Information Value | Variable Predictiveness |+-------------------+-----------------------------+| Less than 0.02 | Not useful for prediction |+-------------------+-----------------------------+| 0.02 to 0.1 | Weak predictive Power |+-------------------+-----------------------------+| 0.1 to 0.3 | Medium predictive Power |+-------------------+-----------------------------+| 0.3 to 0.5 | Strong predictive Power |+-------------------+-----------------------------+| >0.5 | Suspicious Predictive Power |+-------------------+-----------------------------+"
},
{
"code": null,
"e": 5888,
"s": 5803,
"text": "And to transform variable X based on WOE bins calculated before, use the code below."
},
{
"code": null,
"e": 5946,
"s": 5888,
"text": "clf.transform(X) #apply WOE transformation on the dataset"
},
{
"code": null,
"e": 6196,
"s": 5946,
"text": "output_woe_bins = clf.woe_bins #future transformationoutput_mono_bins = clf.mono_custom_binning #future transformationclf = WOE(woe_bins=output_woe_bins, mono_custom_binning=output_mono_bins) #output_bins was created earlierout_X = clf.transform(X)"
},
{
"code": null,
"e": 6582,
"s": 6196,
"text": "treat_missing: {‘separate’, ‘mode’, ‘least_frequent’} (default=’separate’)This parameter setting is used to handle missing values in the dataset. ‘separate’ — Missing values are treated as a own group (category) ‘mode’ — Missing values are combined with the highest frequent item in the dataset ‘least_frequent’ — Missing values are combined with the least frequent item in the dataset"
},
{
"code": null,
"e": 6708,
"s": 6582,
"text": "Bivariate distributions help us explore relationship between X and y variables. This option is available in “xverse” as well."
},
{
"code": null,
"e": 6806,
"s": 6708,
"text": "To make bivariate charts, we need the “woe_df” dataset generated from the WOE option shown above."
},
{
"code": null,
"e": 6905,
"s": 6806,
"text": "woe_df = clf.woe_dffrom xverse.graph import BarChartsclf = BarCharts(bar_type='v')clf.plot(woe_df)"
},
{
"code": null,
"e": 7560,
"s": 6905,
"text": "plot_metric: 'count' or 'mean' (default='mean') Metric to be used while plotting the bivariate chart. 'count' - Event counts in the particular bin 'mean' - Mean event rate in the particular binbar_type: 'horizontal' or 'vertical' (default='vertical') Type of bar chart.fig_size: figure size for each of the individual plots (default=(8,6))bar_color: CSS color style picker. Use it with the hashtag in the front. (default='#058caa') Bar color num_color: CSS color style picker. Use it with the hashtag in the front (default='#ed8549') Numbers color. It represents the numbers written on top of the bar."
},
{
"code": null,
"e": 7864,
"s": 7560,
"text": "Variable selection is one of the key process in predictive modeling process. It is an art. To put in simple terms, variable selection is like picking a soccer team to win the World cup. You need to have the best player in each position and you don’t want two or many players who plays the same position."
},
{
"code": null,
"e": 8030,
"s": 7864,
"text": "In python, we have different techniques to select variables. Some of them include Recursive feature elimination, Tree-based selection and L1 based feature selection."
},
{
"code": null,
"e": 8375,
"s": 8030,
"text": "The idea here is to apply a variety of techniques to select variables. When an algorithm picks a variable, we give a vote for the variable. In the end, we calculate the total votes for each variable and then pick the best ones based on votes. This way, we end up picking the best variables with minimum effort in the variable selection process."
},
{
"code": null,
"e": 8453,
"s": 8375,
"text": "from xverse.ensemble import VotingSelectorclf = VotingSelector()clf.fit(X, y)"
},
{
"code": null,
"e": 8517,
"s": 8453,
"text": "Now, let’s look at the feature importance using the code below."
},
{
"code": null,
"e": 8542,
"s": 8517,
"text": "clf.feature_importances_"
},
{
"code": null,
"e": 8561,
"s": 8542,
"text": "clf.feature_votes_"
},
{
"code": null,
"e": 8585,
"s": 8561,
"text": "clf.transform(X).head()"
},
{
"code": null,
"e": 10119,
"s": 8585,
"text": "selection_techniques: 'all', 'quick' or list(default='all') List of selection techniques to be applied on the data. Available techniques - Weight of evidence ('WOE'), Random Forest ('RF'), Recursive Feature Elimination ('RFE'), Extra Trees Classifier ('ETC'), Chi Square ('CS'), L1 feature selection ('L_ONE'). 'all' - Apply all selection techniques ['WOE', 'RF', 'RFE', 'ETC', 'CS', 'L_ONE'] 'quick' - ['WOE','RF','ETC'] list - user provided list of feature selection techniques from available techniques no_of_featues: 'auto', 'sqrt' or int(default='auto') Number of features to be selected by each selection technique. 'auto' - len(features)/2 'sqrt' - sqrt(len(features)) rounded to the lowest number int - user provided number in integer format handle_category= 'woe' or 'le' (default='woe') Handle category values transformation using Label encoder or Weight of Evidence option. Takes care of missing values too. It treats missing values as separate level. 'woe' - use weight of evidence transformation 'le' - use label encoder transformation numerical_missing_values= 'median', 'mean' or 0 (default='median') Handle numerical variable missing values. 'median' - use median of the column 'mean' - use mean of the column 0 - use 0 to impute the missing values minimum_votes = int (default=0) Minimum number of votes needed to select a variable after feature selection. Only used in the transform process. Default value is set to 0 to select all variables."
},
{
"code": null,
"e": 10275,
"s": 10119,
"text": "Finally, one important thing about “Xverse” is the pipeline functionality. We can add all the steps as part of the pipeline and make our lives much easier."
},
{
"code": null,
"e": 10335,
"s": 10275,
"text": "Here is a code shown below that shows the pipeline feature."
},
{
"code": null,
"e": 10492,
"s": 10335,
"text": "from sklearn.pipeline import Pipelineclf = Pipeline(steps=[('split_x_y', SplitXY(['target'])),('feature_votes', VotingSelector())])clf.fit(df, df['target'])"
},
{
"code": null,
"e": 10545,
"s": 10492,
"text": "Finally, to get the transformation on a new dataset,"
},
{
"code": null,
"e": 10563,
"s": 10545,
"text": "clf.transform(df)"
},
{
"code": null,
"e": 10729,
"s": 10563,
"text": "XuniVerse is under active development, if you’d like to be involved, we’d love to have you. Please leave a response in this article and we can talk about next steps."
}
] |
Python | Launch a Web Browser using webbrowser module - GeeksforGeeks
|
31 Oct, 2021
In Python, webbrowser module is a convenient web browser controller. It provides a high-level interface that allows displaying Web-based documents to users.
webbrowser can also be used as a CLI tool. It accepts a URL as the argument with the following optional parameters: -n opens the URL in a new browser window, if possible, and -t opens the URL in a new browser tab.
Python
python -m webbrowser -t "https://www.google.com"
NOTE: webbrowser is part of the python standard library. Therefore, there is no need to install a separate package to use it.
The webbrowser module can be used to launch a browser in a platform-independent manner as shown below:Code #1 :
Python3
import webbrowserwebbrowser.open('http://www.python.org')
Output :
True
This opens the requested page using the default browser. To have a bit more control over how the page gets opened, use one of the following functions given below in the code –Code #2 : Open the page in a new browser window.
Python3
webbrowser.open_new('http://www.python.org')
Output :
True
Code #3 : Open the page in a new browser tab.
Python3
webbrowser.open_new_tab('http://www.python.org')
Output :
True
These will try to open the page in a new browser window or tab, if possible and supported by the browser. To open a page in a specific browser, use the webbrowser.get() function to specify a particular browser.Code #4 :
Python3
c = webbrowser.get('firefox')c.open('http://www.python.org') c.open_new_tab('http://docs.python.org')
Output :
True
True
Being able to easily launch a browser can be a useful operation in many scripts. For example, maybe a script performs some kind of deployment to a server and one would like to have it quickly launch a browser so one can verify that it’s working. Or maybe a program writes data out in the form of HTML pages and just like to fire up a browser to see the result. Either way, the webbrowser module is a simple solution.
stutijain578
python-modules
python-utility
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Python Dictionary
How to Install PIP on Windows ?
Enumerate() in Python
Different ways to create Pandas Dataframe
Create a Pandas DataFrame from Lists
Python String | replace()
Reading and Writing to text files in Python
*args and **kwargs in Python
How to drop one or multiple columns in Pandas Dataframe
sum() function in Python
|
[
{
"code": null,
"e": 24893,
"s": 24865,
"text": "\n31 Oct, 2021"
},
{
"code": null,
"e": 25051,
"s": 24893,
"text": "In Python, webbrowser module is a convenient web browser controller. It provides a high-level interface that allows displaying Web-based documents to users. "
},
{
"code": null,
"e": 25266,
"s": 25051,
"text": "webbrowser can also be used as a CLI tool. It accepts a URL as the argument with the following optional parameters: -n opens the URL in a new browser window, if possible, and -t opens the URL in a new browser tab. "
},
{
"code": null,
"e": 25273,
"s": 25266,
"text": "Python"
},
{
"code": "python -m webbrowser -t \"https://www.google.com\"",
"e": 25322,
"s": 25273,
"text": null
},
{
"code": null,
"e": 25448,
"s": 25322,
"text": "NOTE: webbrowser is part of the python standard library. Therefore, there is no need to install a separate package to use it."
},
{
"code": null,
"e": 25561,
"s": 25448,
"text": "The webbrowser module can be used to launch a browser in a platform-independent manner as shown below:Code #1 : "
},
{
"code": null,
"e": 25569,
"s": 25561,
"text": "Python3"
},
{
"code": "import webbrowserwebbrowser.open('http://www.python.org')",
"e": 25627,
"s": 25569,
"text": null
},
{
"code": null,
"e": 25637,
"s": 25627,
"text": "Output : "
},
{
"code": null,
"e": 25642,
"s": 25637,
"text": "True"
},
{
"code": null,
"e": 25867,
"s": 25642,
"text": "This opens the requested page using the default browser. To have a bit more control over how the page gets opened, use one of the following functions given below in the code –Code #2 : Open the page in a new browser window. "
},
{
"code": null,
"e": 25875,
"s": 25867,
"text": "Python3"
},
{
"code": "webbrowser.open_new('http://www.python.org')",
"e": 25920,
"s": 25875,
"text": null
},
{
"code": null,
"e": 25930,
"s": 25920,
"text": "Output : "
},
{
"code": null,
"e": 25935,
"s": 25930,
"text": "True"
},
{
"code": null,
"e": 25982,
"s": 25935,
"text": "Code #3 : Open the page in a new browser tab. "
},
{
"code": null,
"e": 25990,
"s": 25982,
"text": "Python3"
},
{
"code": "webbrowser.open_new_tab('http://www.python.org')",
"e": 26039,
"s": 25990,
"text": null
},
{
"code": null,
"e": 26049,
"s": 26039,
"text": "Output : "
},
{
"code": null,
"e": 26054,
"s": 26049,
"text": "True"
},
{
"code": null,
"e": 26275,
"s": 26054,
"text": "These will try to open the page in a new browser window or tab, if possible and supported by the browser. To open a page in a specific browser, use the webbrowser.get() function to specify a particular browser.Code #4 : "
},
{
"code": null,
"e": 26283,
"s": 26275,
"text": "Python3"
},
{
"code": "c = webbrowser.get('firefox')c.open('http://www.python.org') c.open_new_tab('http://docs.python.org')",
"e": 26385,
"s": 26283,
"text": null
},
{
"code": null,
"e": 26395,
"s": 26385,
"text": "Output : "
},
{
"code": null,
"e": 26405,
"s": 26395,
"text": "True\nTrue"
},
{
"code": null,
"e": 26823,
"s": 26405,
"text": "Being able to easily launch a browser can be a useful operation in many scripts. For example, maybe a script performs some kind of deployment to a server and one would like to have it quickly launch a browser so one can verify that it’s working. Or maybe a program writes data out in the form of HTML pages and just like to fire up a browser to see the result. Either way, the webbrowser module is a simple solution. "
},
{
"code": null,
"e": 26836,
"s": 26823,
"text": "stutijain578"
},
{
"code": null,
"e": 26851,
"s": 26836,
"text": "python-modules"
},
{
"code": null,
"e": 26866,
"s": 26851,
"text": "python-utility"
},
{
"code": null,
"e": 26873,
"s": 26866,
"text": "Python"
},
{
"code": null,
"e": 26971,
"s": 26873,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 26980,
"s": 26971,
"text": "Comments"
},
{
"code": null,
"e": 26993,
"s": 26980,
"text": "Old Comments"
},
{
"code": null,
"e": 27011,
"s": 26993,
"text": "Python Dictionary"
},
{
"code": null,
"e": 27043,
"s": 27011,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 27065,
"s": 27043,
"text": "Enumerate() in Python"
},
{
"code": null,
"e": 27107,
"s": 27065,
"text": "Different ways to create Pandas Dataframe"
},
{
"code": null,
"e": 27144,
"s": 27107,
"text": "Create a Pandas DataFrame from Lists"
},
{
"code": null,
"e": 27170,
"s": 27144,
"text": "Python String | replace()"
},
{
"code": null,
"e": 27214,
"s": 27170,
"text": "Reading and Writing to text files in Python"
},
{
"code": null,
"e": 27243,
"s": 27214,
"text": "*args and **kwargs in Python"
},
{
"code": null,
"e": 27299,
"s": 27243,
"text": "How to drop one or multiple columns in Pandas Dataframe"
}
] |
Number of siblings of a given Node in n-ary Tree - GeeksforGeeks
|
24 Jun, 2021
Given an N-ary tree, find the number of siblings of given node x. Assume that x exists in the given n-ary tree.
Example :
Input : 30
Output : 3
Approach: For every node in the given n-ary tree, push the children of the current node in the queue. While adding the children of current node in queue, check if any children is equal to the given value x or not. If yes, then return the number of siblings of x. Below is the implementation of the above idea :
C++
Java
Python3
C#
Javascript
// C++ program to find number// of siblings of a given node#include <bits/stdc++.h>using namespace std; // Represents a node of an n-ary treeclass Node {public: int key; vector<Node*> child; Node(int data) { key = data; }}; // Function to calculate number// of siblings of a given nodeint numberOfSiblings(Node* root, int x){ if (root == NULL) return 0; // Creating a queue and // pushing the root queue<Node*> q; q.push(root); while (!q.empty()) { // Dequeue an item from queue and // check if it is equal to x If YES, // then return number of children Node* p = q.front(); q.pop(); // Enqueue all children of // the dequeued item for (int i = 0; i < p->child.size(); i++) { // If the value of children // is equal to x, then return // the number of siblings if (p->child[i]->key == x) return p->child.size() - 1; q.push(p->child[i]); } }} // Driver programint main(){ // Creating a generic tree as shown in above figure Node* root = new Node(50); (root->child).push_back(new Node(2)); (root->child).push_back(new Node(30)); (root->child).push_back(new Node(14)); (root->child).push_back(new Node(60)); (root->child[0]->child).push_back(new Node(15)); (root->child[0]->child).push_back(new Node(25)); (root->child[0]->child[1]->child).push_back(new Node(70)); (root->child[0]->child[1]->child).push_back(new Node(100)); (root->child[1]->child).push_back(new Node(6)); (root->child[1]->child).push_back(new Node(1)); (root->child[2]->child).push_back(new Node(7)); (root->child[2]->child[0]->child).push_back(new Node(17)); (root->child[2]->child[0]->child).push_back(new Node(99)); (root->child[2]->child[0]->child).push_back(new Node(27)); (root->child[3]->child).push_back(new Node(16)); // Node whose number of // siblings is to be calculated int x = 100; // Function calling cout << numberOfSiblings(root, x) << endl; return 0;}
// Java program to find number// of siblings of a given nodeimport java.util.*; class GFG{ // Represents a node of an n-ary treestatic class Node{ int key; Vector<Node> child; Node(int data) { key = data; child = new Vector<Node>(); }}; // Function to calculate number// of siblings of a given nodestatic int numberOfSiblings(Node root, int x){ if (root == null) return 0; // Creating a queue and // pushing the root Queue<Node> q = new LinkedList<>(); q.add(root); while (q.size() > 0) { // Dequeue an item from queue and // check if it is equal to x If YES, // then return number of children Node p = q.peek(); q.remove(); // Enqueue all children of // the dequeued item for (int i = 0; i < p.child.size(); i++) { // If the value of children // is equal to x, then return // the number of siblings if (p.child.get(i).key == x) return p.child.size() - 1; q.add(p.child.get(i)); } } return -1;} // Driver codepublic static void main(String args[]){ // Creating a generic tree as shown in above figure Node root = new Node(50); (root.child).add(new Node(2)); (root.child).add(new Node(30)); (root.child).add(new Node(14)); (root.child).add(new Node(60)); (root.child.get(0).child).add(new Node(15)); (root.child.get(0).child).add(new Node(25)); (root.child.get(0).child.get(1).child).add(new Node(70)); (root.child.get(0).child.get(1).child).add(new Node(100)); (root.child.get(1).child).add(new Node(6)); (root.child.get(1).child).add(new Node(1)); (root.child.get(2).child).add(new Node(7)); (root.child.get(2).child.get(0).child).add(new Node(17)); (root.child.get(2).child.get(0).child).add(new Node(99)); (root.child.get(2).child.get(0).child).add(new Node(27)); (root.child.get(3).child).add(new Node(16)); // Node whose number of // siblings is to be calculated int x = 100; // Function calling System.out.println( numberOfSiblings(root, x) );}} // This code is contributed by Arnab Kundu
# Python3 program to find number# of siblings of a given nodefrom queue import Queue # Represents a node of an n-ary treeclass newNode: def __init__(self,data): self.child = [] self.key = data # Function to calculate number# of siblings of a given nodedef numberOfSiblings(root, x): if (root == None): return 0 # Creating a queue and # pushing the root q = Queue() q.put(root) while (not q.empty()): # Dequeue an item from queue and # check if it is equal to x If YES, # then return number of children p = q.queue[0] q.get() # Enqueue all children of # the dequeued item for i in range(len(p.child)): # If the value of children # is equal to x, then return # the number of siblings if (p.child[i].key == x): return len(p.child) - 1 q.put(p.child[i]) # Driver Codeif __name__ == '__main__': # Creating a generic tree as # shown in above figure root = newNode(50) (root.child).append(newNode(2)) (root.child).append(newNode(30)) (root.child).append(newNode(14)) (root.child).append(newNode(60)) (root.child[0].child).append(newNode(15)) (root.child[0].child).append(newNode(25)) (root.child[0].child[1].child).append(newNode(70)) (root.child[0].child[1].child).append(newNode(100)) (root.child[1].child).append(newNode(6)) (root.child[1].child).append(newNode(1)) (root.child[2].child).append(newNode(7)) (root.child[2].child[0].child).append(newNode(17)) (root.child[2].child[0].child).append(newNode(99)) (root.child[2].child[0].child).append(newNode(27)) (root.child[3].child).append(newNode(16)) # Node whose number of # siblings is to be calculated x = 100 # Function calling print(numberOfSiblings(root, x)) # This code is contributed by PranchalK
// C# program to find number// of siblings of a given nodeusing System;using System.Collections.Generic; class GFG{ // Represents a node of an n-ary treepublic class Node{ public int key; public List<Node> child; public Node(int data) { key = data; child = new List<Node>(); }}; // Function to calculate number// of siblings of a given nodestatic int numberOfSiblings(Node root, int x){ if (root == null) return 0; // Creating a queue and // pushing the root Queue<Node> q = new Queue<Node>(); q.Enqueue(root); while (q.Count > 0) { // Dequeue an item from queue and // check if it is equal to x If YES, // then return number of children Node p = q.Peek(); q.Dequeue(); // Enqueue all children of // the dequeued item for (int i = 0; i < p.child.Count; i++) { // If the value of children // is equal to x, then return // the number of siblings if (p.child[i].key == x) return p.child.Count - 1; q.Enqueue(p.child[i]); } } return -1;} // Driver codepublic static void Main(String []args){ // Creating a generic tree // as shown in above figure Node root = new Node(50); (root.child).Add(new Node(2)); (root.child).Add(new Node(30)); (root.child).Add(new Node(14)); (root.child).Add(new Node(60)); (root.child[0].child).Add(new Node(15)); (root.child[0].child).Add(new Node(25)); (root.child[0].child[1].child).Add(new Node(70)); (root.child[0].child[1].child).Add(new Node(100)); (root.child[1].child).Add(new Node(6)); (root.child[1].child).Add(new Node(1)); (root.child[2].child).Add(new Node(7)); (root.child[2].child[0].child).Add(new Node(17)); (root.child[2].child[0].child).Add(new Node(99)); (root.child[2].child[0].child).Add(new Node(27)); (root.child[3].child).Add(new Node(16)); // Node whose number of // siblings is to be calculated int x = 100; // Function calling Console.WriteLine( numberOfSiblings(root, x));}} // This code is contributed by PrinciRaj1992
<script> // JavaScript program to find number// of siblings of a given node // Represents a node of an n-ary treeclass Node{ constructor(data) { this.key = data; this.child = []; }}; // Function to calculate number// of siblings of a given nodefunction numberOfSiblings(root, x){ if (root == null) return 0; // Creating a queue and // pushing the root var q = []; q.push(root); while (q.length > 0) { // Dequeue an item from queue and // check if it is equal to x If YES, // then return number of children var p = q[0]; q.shift(); // push all children of // the dequeued item for (var i = 0; i < p.child.length; i++) { // If the value of children // is equal to x, then return // the number of siblings if (p.child[i].key == x) return p.child.length - 1; q.push(p.child[i]); } } return -1;} // Driver code// Creating a generic tree// as shown in above figurevar root = new Node(50);(root.child).push(new Node(2));(root.child).push(new Node(30));(root.child).push(new Node(14));(root.child).push(new Node(60));(root.child[0].child).push(new Node(15));(root.child[0].child).push(new Node(25));(root.child[0].child[1].child).push(new Node(70));(root.child[0].child[1].child).push(new Node(100));(root.child[1].child).push(new Node(6));(root.child[1].child).push(new Node(1));(root.child[2].child).push(new Node(7));(root.child[2].child[0].child).push(new Node(17));(root.child[2].child[0].child).push(new Node(99));(root.child[2].child[0].child).push(new Node(27));(root.child[3].child).push(new Node(16));// Node whose number of// siblings is to be calculatedvar x = 100;// Function callingdocument.write( numberOfSiblings(root, x)); </script>
1
Time Complexity: O(N), where N is the number of nodes in tree. Auxiliary Space: O(N), where N is the number of nodes in tree.
YouTubeGeeksforGeeks507K subscribersNumber of siblings of a given Node in n-ary Tree | 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 / 3:02•Live•<div class="player-unavailable"><h1 class="message">An error occurred.</h1><div class="submessage"><a href="https://www.youtube.com/watch?v=Zm8SMMtJkF8" target="_blank">Try watching this video on www.youtube.com</a>, or enable JavaScript if it is disabled in your browser.</div></div>
sahilkhoslaa
PranchalKatiyar
andrew1234
princiraj1992
razor7386
rrrtnx
cpp-queue
Queue
Tree
Queue
Tree
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Construct Complete Binary Tree from its Linked List Representation
Iterative Letter Combinations of a Phone Number
FIFO (First-In-First-Out) approach in Programming
Applications of Priority Queue
Reversing a Queue
Tree Traversals (Inorder, Preorder and Postorder)
Binary Tree | Set 1 (Introduction)
AVL Tree | Set 1 (Insertion)
Binary Tree | Set 3 (Types of Binary Tree)
Inorder Tree Traversal without Recursion
|
[
{
"code": null,
"e": 25977,
"s": 25949,
"text": "\n24 Jun, 2021"
},
{
"code": null,
"e": 26090,
"s": 25977,
"text": "Given an N-ary tree, find the number of siblings of given node x. Assume that x exists in the given n-ary tree. "
},
{
"code": null,
"e": 26102,
"s": 26090,
"text": "Example : "
},
{
"code": null,
"e": 26124,
"s": 26102,
"text": "Input : 30\nOutput : 3"
},
{
"code": null,
"e": 26439,
"s": 26126,
"text": "Approach: For every node in the given n-ary tree, push the children of the current node in the queue. While adding the children of current node in queue, check if any children is equal to the given value x or not. If yes, then return the number of siblings of x. Below is the implementation of the above idea : "
},
{
"code": null,
"e": 26443,
"s": 26439,
"text": "C++"
},
{
"code": null,
"e": 26448,
"s": 26443,
"text": "Java"
},
{
"code": null,
"e": 26456,
"s": 26448,
"text": "Python3"
},
{
"code": null,
"e": 26459,
"s": 26456,
"text": "C#"
},
{
"code": null,
"e": 26470,
"s": 26459,
"text": "Javascript"
},
{
"code": "// C++ program to find number// of siblings of a given node#include <bits/stdc++.h>using namespace std; // Represents a node of an n-ary treeclass Node {public: int key; vector<Node*> child; Node(int data) { key = data; }}; // Function to calculate number// of siblings of a given nodeint numberOfSiblings(Node* root, int x){ if (root == NULL) return 0; // Creating a queue and // pushing the root queue<Node*> q; q.push(root); while (!q.empty()) { // Dequeue an item from queue and // check if it is equal to x If YES, // then return number of children Node* p = q.front(); q.pop(); // Enqueue all children of // the dequeued item for (int i = 0; i < p->child.size(); i++) { // If the value of children // is equal to x, then return // the number of siblings if (p->child[i]->key == x) return p->child.size() - 1; q.push(p->child[i]); } }} // Driver programint main(){ // Creating a generic tree as shown in above figure Node* root = new Node(50); (root->child).push_back(new Node(2)); (root->child).push_back(new Node(30)); (root->child).push_back(new Node(14)); (root->child).push_back(new Node(60)); (root->child[0]->child).push_back(new Node(15)); (root->child[0]->child).push_back(new Node(25)); (root->child[0]->child[1]->child).push_back(new Node(70)); (root->child[0]->child[1]->child).push_back(new Node(100)); (root->child[1]->child).push_back(new Node(6)); (root->child[1]->child).push_back(new Node(1)); (root->child[2]->child).push_back(new Node(7)); (root->child[2]->child[0]->child).push_back(new Node(17)); (root->child[2]->child[0]->child).push_back(new Node(99)); (root->child[2]->child[0]->child).push_back(new Node(27)); (root->child[3]->child).push_back(new Node(16)); // Node whose number of // siblings is to be calculated int x = 100; // Function calling cout << numberOfSiblings(root, x) << endl; return 0;}",
"e": 28563,
"s": 26470,
"text": null
},
{
"code": "// Java program to find number// of siblings of a given nodeimport java.util.*; class GFG{ // Represents a node of an n-ary treestatic class Node{ int key; Vector<Node> child; Node(int data) { key = data; child = new Vector<Node>(); }}; // Function to calculate number// of siblings of a given nodestatic int numberOfSiblings(Node root, int x){ if (root == null) return 0; // Creating a queue and // pushing the root Queue<Node> q = new LinkedList<>(); q.add(root); while (q.size() > 0) { // Dequeue an item from queue and // check if it is equal to x If YES, // then return number of children Node p = q.peek(); q.remove(); // Enqueue all children of // the dequeued item for (int i = 0; i < p.child.size(); i++) { // If the value of children // is equal to x, then return // the number of siblings if (p.child.get(i).key == x) return p.child.size() - 1; q.add(p.child.get(i)); } } return -1;} // Driver codepublic static void main(String args[]){ // Creating a generic tree as shown in above figure Node root = new Node(50); (root.child).add(new Node(2)); (root.child).add(new Node(30)); (root.child).add(new Node(14)); (root.child).add(new Node(60)); (root.child.get(0).child).add(new Node(15)); (root.child.get(0).child).add(new Node(25)); (root.child.get(0).child.get(1).child).add(new Node(70)); (root.child.get(0).child.get(1).child).add(new Node(100)); (root.child.get(1).child).add(new Node(6)); (root.child.get(1).child).add(new Node(1)); (root.child.get(2).child).add(new Node(7)); (root.child.get(2).child.get(0).child).add(new Node(17)); (root.child.get(2).child.get(0).child).add(new Node(99)); (root.child.get(2).child.get(0).child).add(new Node(27)); (root.child.get(3).child).add(new Node(16)); // Node whose number of // siblings is to be calculated int x = 100; // Function calling System.out.println( numberOfSiblings(root, x) );}} // This code is contributed by Arnab Kundu",
"e": 30737,
"s": 28563,
"text": null
},
{
"code": "# Python3 program to find number# of siblings of a given nodefrom queue import Queue # Represents a node of an n-ary treeclass newNode: def __init__(self,data): self.child = [] self.key = data # Function to calculate number# of siblings of a given nodedef numberOfSiblings(root, x): if (root == None): return 0 # Creating a queue and # pushing the root q = Queue() q.put(root) while (not q.empty()): # Dequeue an item from queue and # check if it is equal to x If YES, # then return number of children p = q.queue[0] q.get() # Enqueue all children of # the dequeued item for i in range(len(p.child)): # If the value of children # is equal to x, then return # the number of siblings if (p.child[i].key == x): return len(p.child) - 1 q.put(p.child[i]) # Driver Codeif __name__ == '__main__': # Creating a generic tree as # shown in above figure root = newNode(50) (root.child).append(newNode(2)) (root.child).append(newNode(30)) (root.child).append(newNode(14)) (root.child).append(newNode(60)) (root.child[0].child).append(newNode(15)) (root.child[0].child).append(newNode(25)) (root.child[0].child[1].child).append(newNode(70)) (root.child[0].child[1].child).append(newNode(100)) (root.child[1].child).append(newNode(6)) (root.child[1].child).append(newNode(1)) (root.child[2].child).append(newNode(7)) (root.child[2].child[0].child).append(newNode(17)) (root.child[2].child[0].child).append(newNode(99)) (root.child[2].child[0].child).append(newNode(27)) (root.child[3].child).append(newNode(16)) # Node whose number of # siblings is to be calculated x = 100 # Function calling print(numberOfSiblings(root, x)) # This code is contributed by PranchalK",
"e": 32654,
"s": 30737,
"text": null
},
{
"code": "// C# program to find number// of siblings of a given nodeusing System;using System.Collections.Generic; class GFG{ // Represents a node of an n-ary treepublic class Node{ public int key; public List<Node> child; public Node(int data) { key = data; child = new List<Node>(); }}; // Function to calculate number// of siblings of a given nodestatic int numberOfSiblings(Node root, int x){ if (root == null) return 0; // Creating a queue and // pushing the root Queue<Node> q = new Queue<Node>(); q.Enqueue(root); while (q.Count > 0) { // Dequeue an item from queue and // check if it is equal to x If YES, // then return number of children Node p = q.Peek(); q.Dequeue(); // Enqueue all children of // the dequeued item for (int i = 0; i < p.child.Count; i++) { // If the value of children // is equal to x, then return // the number of siblings if (p.child[i].key == x) return p.child.Count - 1; q.Enqueue(p.child[i]); } } return -1;} // Driver codepublic static void Main(String []args){ // Creating a generic tree // as shown in above figure Node root = new Node(50); (root.child).Add(new Node(2)); (root.child).Add(new Node(30)); (root.child).Add(new Node(14)); (root.child).Add(new Node(60)); (root.child[0].child).Add(new Node(15)); (root.child[0].child).Add(new Node(25)); (root.child[0].child[1].child).Add(new Node(70)); (root.child[0].child[1].child).Add(new Node(100)); (root.child[1].child).Add(new Node(6)); (root.child[1].child).Add(new Node(1)); (root.child[2].child).Add(new Node(7)); (root.child[2].child[0].child).Add(new Node(17)); (root.child[2].child[0].child).Add(new Node(99)); (root.child[2].child[0].child).Add(new Node(27)); (root.child[3].child).Add(new Node(16)); // Node whose number of // siblings is to be calculated int x = 100; // Function calling Console.WriteLine( numberOfSiblings(root, x));}} // This code is contributed by PrinciRaj1992",
"e": 34813,
"s": 32654,
"text": null
},
{
"code": "<script> // JavaScript program to find number// of siblings of a given node // Represents a node of an n-ary treeclass Node{ constructor(data) { this.key = data; this.child = []; }}; // Function to calculate number// of siblings of a given nodefunction numberOfSiblings(root, x){ if (root == null) return 0; // Creating a queue and // pushing the root var q = []; q.push(root); while (q.length > 0) { // Dequeue an item from queue and // check if it is equal to x If YES, // then return number of children var p = q[0]; q.shift(); // push all children of // the dequeued item for (var i = 0; i < p.child.length; i++) { // If the value of children // is equal to x, then return // the number of siblings if (p.child[i].key == x) return p.child.length - 1; q.push(p.child[i]); } } return -1;} // Driver code// Creating a generic tree// as shown in above figurevar root = new Node(50);(root.child).push(new Node(2));(root.child).push(new Node(30));(root.child).push(new Node(14));(root.child).push(new Node(60));(root.child[0].child).push(new Node(15));(root.child[0].child).push(new Node(25));(root.child[0].child[1].child).push(new Node(70));(root.child[0].child[1].child).push(new Node(100));(root.child[1].child).push(new Node(6));(root.child[1].child).push(new Node(1));(root.child[2].child).push(new Node(7));(root.child[2].child[0].child).push(new Node(17));(root.child[2].child[0].child).push(new Node(99));(root.child[2].child[0].child).push(new Node(27));(root.child[3].child).push(new Node(16));// Node whose number of// siblings is to be calculatedvar x = 100;// Function callingdocument.write( numberOfSiblings(root, x)); </script>",
"e": 36642,
"s": 34813,
"text": null
},
{
"code": null,
"e": 36644,
"s": 36642,
"text": "1"
},
{
"code": null,
"e": 36774,
"s": 36646,
"text": "Time Complexity: O(N), where N is the number of nodes in tree. Auxiliary Space: O(N), where N is the number of nodes in tree. "
},
{
"code": null,
"e": 37621,
"s": 36774,
"text": "YouTubeGeeksforGeeks507K subscribersNumber of siblings of a given Node in n-ary Tree | 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 / 3:02•Live•<div class=\"player-unavailable\"><h1 class=\"message\">An error occurred.</h1><div class=\"submessage\"><a href=\"https://www.youtube.com/watch?v=Zm8SMMtJkF8\" 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": 37634,
"s": 37621,
"text": "sahilkhoslaa"
},
{
"code": null,
"e": 37650,
"s": 37634,
"text": "PranchalKatiyar"
},
{
"code": null,
"e": 37661,
"s": 37650,
"text": "andrew1234"
},
{
"code": null,
"e": 37675,
"s": 37661,
"text": "princiraj1992"
},
{
"code": null,
"e": 37685,
"s": 37675,
"text": "razor7386"
},
{
"code": null,
"e": 37692,
"s": 37685,
"text": "rrrtnx"
},
{
"code": null,
"e": 37702,
"s": 37692,
"text": "cpp-queue"
},
{
"code": null,
"e": 37708,
"s": 37702,
"text": "Queue"
},
{
"code": null,
"e": 37713,
"s": 37708,
"text": "Tree"
},
{
"code": null,
"e": 37719,
"s": 37713,
"text": "Queue"
},
{
"code": null,
"e": 37724,
"s": 37719,
"text": "Tree"
},
{
"code": null,
"e": 37822,
"s": 37724,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 37889,
"s": 37822,
"text": "Construct Complete Binary Tree from its Linked List Representation"
},
{
"code": null,
"e": 37937,
"s": 37889,
"text": "Iterative Letter Combinations of a Phone Number"
},
{
"code": null,
"e": 37987,
"s": 37937,
"text": "FIFO (First-In-First-Out) approach in Programming"
},
{
"code": null,
"e": 38018,
"s": 37987,
"text": "Applications of Priority Queue"
},
{
"code": null,
"e": 38036,
"s": 38018,
"text": "Reversing a Queue"
},
{
"code": null,
"e": 38086,
"s": 38036,
"text": "Tree Traversals (Inorder, Preorder and Postorder)"
},
{
"code": null,
"e": 38121,
"s": 38086,
"text": "Binary Tree | Set 1 (Introduction)"
},
{
"code": null,
"e": 38150,
"s": 38121,
"text": "AVL Tree | Set 1 (Insertion)"
},
{
"code": null,
"e": 38193,
"s": 38150,
"text": "Binary Tree | Set 3 (Types of Binary Tree)"
}
] |
Different ways to make Method Parameter Optional in C# - GeeksforGeeks
|
29 Mar, 2019
As the name suggests optional parameters are not compulsory parameters, they are optional. It helps to exclude arguments for some parameters. Or we can say in optional parameters, it is not necessary to pass all the parameters in the method. This concept is introduced in C# 4.0. Here we discuss the different ways to implement the optional parameter. In C#, there are 4 different types of implementation of optional parameters are available as follows:
By using default value: You can implement optional parameters by using default value. It is the simplest and easiest way to implement the optional parameter. In this way, you just simply define the optional parameters with their default value in the method definition. And always remember the optional parameter is the last parameter in the parameter list of the method. In default value method, when you do not pass the value of the optional parameters, then the optional parameters use their default value and when you pass the parameters for optional parameters, then they will take the passed value not their default value.Example: Here, we have two regular parameters, i.e. str1 and str2 and one optional parameter, i.e. str3 with their default value. Here, the optional parameter uses this default value when we do not pass any value to the optional parameter and when we pass the value of the optional parameter in the method call, then it will take the passed value.// C# program to illustrate how to create// optional parameters using default valueusing System; class GFG { // Method containing optional parameter // Here str3 is a optional parameter // with its default value static public void my_add(string str1, string str2, string str3 = "GeeksforGeeks") { Console.WriteLine(str1 + str2 + str3); } // Main method static public void Main() { my_add("Welcome", "to"); my_add("This", "is", "C# Tutorial"); }}Output:WelcometoGeeksforGeeks
ThisisC# Tutorial
By using Method Overloading: You can implement optional parameters concept by using method overloading. In method overloading, we create methods with the same name but with the different parameter list. This method is not the pure way to implement an optional parameter, but you can achieve the optional parameter concept by using this method.Example: Here, we have two methods with the same name but the parameter list of these methods is different, i.e. first my_mul method takes only one argument whereas second mu_mul method takes three arguments.// C# program to illustrate how to create// optional parameters using method overloadingusing System; class GFG { // Creating optional parameters // Using method overloading // Here both methods have the same // name but different parameter list static public void my_mul(int a) { Console.WriteLine(a * a); } static public void my_mul(int a, int b, int c) { Console.WriteLine(a * b * c); } // Main method static public void Main() { my_mul(4); my_mul(5, 6, 100); }}Output:16
3000
By using OptionalAttribute: You can implement optional parameters by using OptionalAttribute. To implement the optional parameter first you need to add System.Runtime.InteropServices namespace in your program, then creates an optional parameter using the Optional keyword enclosed in square brackets before the definition of the parameter in the method. The default value of OptionalAttribut is zero.Example: Here, we create an optional parameter using OptionalAttribute, here num2 is an optional parameter in the my_mul method.// C# program to illustrate how to create// optional parameters using OptionalAttributeusing System;using System.Runtime.InteropServices; class GFG { // Method containing optional parameter // Using OptionalAttribute static public void my_mul(int num, [ Optional ] int num2) { Console.WriteLine(num * num2); } // Main Method static public void Main() { my_mul(4); my_mul(2, 10); }}Output:0
20
By Params Keyword: You can implement optional parameters by using the params keyword. It allows you to pass any variable number of parameters to a method. But you can use the params keyword for only one parameter and that parameter is the last parameter of the method. This method is not the pure way to implement an optional parameter, but you can achieve the optional parameter concept by using this method.Example: Here, optional parameter is created using the params keyword. Here a1 is the optional parameter and in which you can pass from zero to up to any number of variables.// C# program to illustrate how to create// optional parameters using params keywordusing System; class GFG { // Method containing optional // parameter Using params keyword static public void my_mul(int a, params int[] a1) { int mul = 1; foreach(int num in a1) { mul *= num; } Console.WriteLine(mul * a); } // Main method static public void Main() { my_mul(1); my_mul(2, 4); my_mul(3, 3, 100); }}Output:1
8
900
By using default value: You can implement optional parameters by using default value. It is the simplest and easiest way to implement the optional parameter. In this way, you just simply define the optional parameters with their default value in the method definition. And always remember the optional parameter is the last parameter in the parameter list of the method. In default value method, when you do not pass the value of the optional parameters, then the optional parameters use their default value and when you pass the parameters for optional parameters, then they will take the passed value not their default value.Example: Here, we have two regular parameters, i.e. str1 and str2 and one optional parameter, i.e. str3 with their default value. Here, the optional parameter uses this default value when we do not pass any value to the optional parameter and when we pass the value of the optional parameter in the method call, then it will take the passed value.// C# program to illustrate how to create// optional parameters using default valueusing System; class GFG { // Method containing optional parameter // Here str3 is a optional parameter // with its default value static public void my_add(string str1, string str2, string str3 = "GeeksforGeeks") { Console.WriteLine(str1 + str2 + str3); } // Main method static public void Main() { my_add("Welcome", "to"); my_add("This", "is", "C# Tutorial"); }}Output:WelcometoGeeksforGeeks
ThisisC# Tutorial
Example: Here, we have two regular parameters, i.e. str1 and str2 and one optional parameter, i.e. str3 with their default value. Here, the optional parameter uses this default value when we do not pass any value to the optional parameter and when we pass the value of the optional parameter in the method call, then it will take the passed value.
// C# program to illustrate how to create// optional parameters using default valueusing System; class GFG { // Method containing optional parameter // Here str3 is a optional parameter // with its default value static public void my_add(string str1, string str2, string str3 = "GeeksforGeeks") { Console.WriteLine(str1 + str2 + str3); } // Main method static public void Main() { my_add("Welcome", "to"); my_add("This", "is", "C# Tutorial"); }}
WelcometoGeeksforGeeks
ThisisC# Tutorial
By using Method Overloading: You can implement optional parameters concept by using method overloading. In method overloading, we create methods with the same name but with the different parameter list. This method is not the pure way to implement an optional parameter, but you can achieve the optional parameter concept by using this method.Example: Here, we have two methods with the same name but the parameter list of these methods is different, i.e. first my_mul method takes only one argument whereas second mu_mul method takes three arguments.// C# program to illustrate how to create// optional parameters using method overloadingusing System; class GFG { // Creating optional parameters // Using method overloading // Here both methods have the same // name but different parameter list static public void my_mul(int a) { Console.WriteLine(a * a); } static public void my_mul(int a, int b, int c) { Console.WriteLine(a * b * c); } // Main method static public void Main() { my_mul(4); my_mul(5, 6, 100); }}Output:16
3000
Example: Here, we have two methods with the same name but the parameter list of these methods is different, i.e. first my_mul method takes only one argument whereas second mu_mul method takes three arguments.
// C# program to illustrate how to create// optional parameters using method overloadingusing System; class GFG { // Creating optional parameters // Using method overloading // Here both methods have the same // name but different parameter list static public void my_mul(int a) { Console.WriteLine(a * a); } static public void my_mul(int a, int b, int c) { Console.WriteLine(a * b * c); } // Main method static public void Main() { my_mul(4); my_mul(5, 6, 100); }}
16
3000
By using OptionalAttribute: You can implement optional parameters by using OptionalAttribute. To implement the optional parameter first you need to add System.Runtime.InteropServices namespace in your program, then creates an optional parameter using the Optional keyword enclosed in square brackets before the definition of the parameter in the method. The default value of OptionalAttribut is zero.Example: Here, we create an optional parameter using OptionalAttribute, here num2 is an optional parameter in the my_mul method.// C# program to illustrate how to create// optional parameters using OptionalAttributeusing System;using System.Runtime.InteropServices; class GFG { // Method containing optional parameter // Using OptionalAttribute static public void my_mul(int num, [ Optional ] int num2) { Console.WriteLine(num * num2); } // Main Method static public void Main() { my_mul(4); my_mul(2, 10); }}Output:0
20
Example: Here, we create an optional parameter using OptionalAttribute, here num2 is an optional parameter in the my_mul method.
// C# program to illustrate how to create// optional parameters using OptionalAttributeusing System;using System.Runtime.InteropServices; class GFG { // Method containing optional parameter // Using OptionalAttribute static public void my_mul(int num, [ Optional ] int num2) { Console.WriteLine(num * num2); } // Main Method static public void Main() { my_mul(4); my_mul(2, 10); }}
0
20
By Params Keyword: You can implement optional parameters by using the params keyword. It allows you to pass any variable number of parameters to a method. But you can use the params keyword for only one parameter and that parameter is the last parameter of the method. This method is not the pure way to implement an optional parameter, but you can achieve the optional parameter concept by using this method.Example: Here, optional parameter is created using the params keyword. Here a1 is the optional parameter and in which you can pass from zero to up to any number of variables.// C# program to illustrate how to create// optional parameters using params keywordusing System; class GFG { // Method containing optional // parameter Using params keyword static public void my_mul(int a, params int[] a1) { int mul = 1; foreach(int num in a1) { mul *= num; } Console.WriteLine(mul * a); } // Main method static public void Main() { my_mul(1); my_mul(2, 4); my_mul(3, 3, 100); }}Output:1
8
900
Example: Here, optional parameter is created using the params keyword. Here a1 is the optional parameter and in which you can pass from zero to up to any number of variables.
// C# program to illustrate how to create// optional parameters using params keywordusing System; class GFG { // Method containing optional // parameter Using params keyword static public void my_mul(int a, params int[] a1) { int mul = 1; foreach(int num in a1) { mul *= num; } Console.WriteLine(mul * a); } // Main method static public void Main() { my_mul(1); my_mul(2, 4); my_mul(3, 3, 100); }}
1
8
900
CSharp-method
C#
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
C# | Delegates
C# | Abstract Classes
Extension Method in C#
C# | Replace() Method
C# | String.IndexOf( ) Method | Set - 1
Introduction to .NET Framework
C# | Data Types
C# | Arrays
HashSet in C# with Examples
Common Language Runtime (CLR) in C#
|
[
{
"code": null,
"e": 25435,
"s": 25407,
"text": "\n29 Mar, 2019"
},
{
"code": null,
"e": 25889,
"s": 25435,
"text": "As the name suggests optional parameters are not compulsory parameters, they are optional. It helps to exclude arguments for some parameters. Or we can say in optional parameters, it is not necessary to pass all the parameters in the method. This concept is introduced in C# 4.0. Here we discuss the different ways to implement the optional parameter. In C#, there are 4 different types of implementation of optional parameters are available as follows:"
},
{
"code": null,
"e": 30653,
"s": 25889,
"text": "By using default value: You can implement optional parameters by using default value. It is the simplest and easiest way to implement the optional parameter. In this way, you just simply define the optional parameters with their default value in the method definition. And always remember the optional parameter is the last parameter in the parameter list of the method. In default value method, when you do not pass the value of the optional parameters, then the optional parameters use their default value and when you pass the parameters for optional parameters, then they will take the passed value not their default value.Example: Here, we have two regular parameters, i.e. str1 and str2 and one optional parameter, i.e. str3 with their default value. Here, the optional parameter uses this default value when we do not pass any value to the optional parameter and when we pass the value of the optional parameter in the method call, then it will take the passed value.// C# program to illustrate how to create// optional parameters using default valueusing System; class GFG { // Method containing optional parameter // Here str3 is a optional parameter // with its default value static public void my_add(string str1, string str2, string str3 = \"GeeksforGeeks\") { Console.WriteLine(str1 + str2 + str3); } // Main method static public void Main() { my_add(\"Welcome\", \"to\"); my_add(\"This\", \"is\", \"C# Tutorial\"); }}Output:WelcometoGeeksforGeeks\nThisisC# Tutorial\nBy using Method Overloading: You can implement optional parameters concept by using method overloading. In method overloading, we create methods with the same name but with the different parameter list. This method is not the pure way to implement an optional parameter, but you can achieve the optional parameter concept by using this method.Example: Here, we have two methods with the same name but the parameter list of these methods is different, i.e. first my_mul method takes only one argument whereas second mu_mul method takes three arguments.// C# program to illustrate how to create// optional parameters using method overloadingusing System; class GFG { // Creating optional parameters // Using method overloading // Here both methods have the same // name but different parameter list static public void my_mul(int a) { Console.WriteLine(a * a); } static public void my_mul(int a, int b, int c) { Console.WriteLine(a * b * c); } // Main method static public void Main() { my_mul(4); my_mul(5, 6, 100); }}Output:16\n3000\nBy using OptionalAttribute: You can implement optional parameters by using OptionalAttribute. To implement the optional parameter first you need to add System.Runtime.InteropServices namespace in your program, then creates an optional parameter using the Optional keyword enclosed in square brackets before the definition of the parameter in the method. The default value of OptionalAttribut is zero.Example: Here, we create an optional parameter using OptionalAttribute, here num2 is an optional parameter in the my_mul method.// C# program to illustrate how to create// optional parameters using OptionalAttributeusing System;using System.Runtime.InteropServices; class GFG { // Method containing optional parameter // Using OptionalAttribute static public void my_mul(int num, [ Optional ] int num2) { Console.WriteLine(num * num2); } // Main Method static public void Main() { my_mul(4); my_mul(2, 10); }}Output:0\n20\nBy Params Keyword: You can implement optional parameters by using the params keyword. It allows you to pass any variable number of parameters to a method. But you can use the params keyword for only one parameter and that parameter is the last parameter of the method. This method is not the pure way to implement an optional parameter, but you can achieve the optional parameter concept by using this method.Example: Here, optional parameter is created using the params keyword. Here a1 is the optional parameter and in which you can pass from zero to up to any number of variables.// C# program to illustrate how to create// optional parameters using params keywordusing System; class GFG { // Method containing optional // parameter Using params keyword static public void my_mul(int a, params int[] a1) { int mul = 1; foreach(int num in a1) { mul *= num; } Console.WriteLine(mul * a); } // Main method static public void Main() { my_mul(1); my_mul(2, 4); my_mul(3, 3, 100); }}Output:1\n8\n900\n"
},
{
"code": null,
"e": 32201,
"s": 30653,
"text": "By using default value: You can implement optional parameters by using default value. It is the simplest and easiest way to implement the optional parameter. In this way, you just simply define the optional parameters with their default value in the method definition. And always remember the optional parameter is the last parameter in the parameter list of the method. In default value method, when you do not pass the value of the optional parameters, then the optional parameters use their default value and when you pass the parameters for optional parameters, then they will take the passed value not their default value.Example: Here, we have two regular parameters, i.e. str1 and str2 and one optional parameter, i.e. str3 with their default value. Here, the optional parameter uses this default value when we do not pass any value to the optional parameter and when we pass the value of the optional parameter in the method call, then it will take the passed value.// C# program to illustrate how to create// optional parameters using default valueusing System; class GFG { // Method containing optional parameter // Here str3 is a optional parameter // with its default value static public void my_add(string str1, string str2, string str3 = \"GeeksforGeeks\") { Console.WriteLine(str1 + str2 + str3); } // Main method static public void Main() { my_add(\"Welcome\", \"to\"); my_add(\"This\", \"is\", \"C# Tutorial\"); }}Output:WelcometoGeeksforGeeks\nThisisC# Tutorial\n"
},
{
"code": null,
"e": 32549,
"s": 32201,
"text": "Example: Here, we have two regular parameters, i.e. str1 and str2 and one optional parameter, i.e. str3 with their default value. Here, the optional parameter uses this default value when we do not pass any value to the optional parameter and when we pass the value of the optional parameter in the method call, then it will take the passed value."
},
{
"code": "// C# program to illustrate how to create// optional parameters using default valueusing System; class GFG { // Method containing optional parameter // Here str3 is a optional parameter // with its default value static public void my_add(string str1, string str2, string str3 = \"GeeksforGeeks\") { Console.WriteLine(str1 + str2 + str3); } // Main method static public void Main() { my_add(\"Welcome\", \"to\"); my_add(\"This\", \"is\", \"C# Tutorial\"); }}",
"e": 33075,
"s": 32549,
"text": null
},
{
"code": null,
"e": 33117,
"s": 33075,
"text": "WelcometoGeeksforGeeks\nThisisC# Tutorial\n"
},
{
"code": null,
"e": 34250,
"s": 33117,
"text": "By using Method Overloading: You can implement optional parameters concept by using method overloading. In method overloading, we create methods with the same name but with the different parameter list. This method is not the pure way to implement an optional parameter, but you can achieve the optional parameter concept by using this method.Example: Here, we have two methods with the same name but the parameter list of these methods is different, i.e. first my_mul method takes only one argument whereas second mu_mul method takes three arguments.// C# program to illustrate how to create// optional parameters using method overloadingusing System; class GFG { // Creating optional parameters // Using method overloading // Here both methods have the same // name but different parameter list static public void my_mul(int a) { Console.WriteLine(a * a); } static public void my_mul(int a, int b, int c) { Console.WriteLine(a * b * c); } // Main method static public void Main() { my_mul(4); my_mul(5, 6, 100); }}Output:16\n3000\n"
},
{
"code": null,
"e": 34459,
"s": 34250,
"text": "Example: Here, we have two methods with the same name but the parameter list of these methods is different, i.e. first my_mul method takes only one argument whereas second mu_mul method takes three arguments."
},
{
"code": "// C# program to illustrate how to create// optional parameters using method overloadingusing System; class GFG { // Creating optional parameters // Using method overloading // Here both methods have the same // name but different parameter list static public void my_mul(int a) { Console.WriteLine(a * a); } static public void my_mul(int a, int b, int c) { Console.WriteLine(a * b * c); } // Main method static public void Main() { my_mul(4); my_mul(5, 6, 100); }}",
"e": 35026,
"s": 34459,
"text": null
},
{
"code": null,
"e": 35035,
"s": 35026,
"text": "16\n3000\n"
},
{
"code": null,
"e": 36025,
"s": 35035,
"text": "By using OptionalAttribute: You can implement optional parameters by using OptionalAttribute. To implement the optional parameter first you need to add System.Runtime.InteropServices namespace in your program, then creates an optional parameter using the Optional keyword enclosed in square brackets before the definition of the parameter in the method. The default value of OptionalAttribut is zero.Example: Here, we create an optional parameter using OptionalAttribute, here num2 is an optional parameter in the my_mul method.// C# program to illustrate how to create// optional parameters using OptionalAttributeusing System;using System.Runtime.InteropServices; class GFG { // Method containing optional parameter // Using OptionalAttribute static public void my_mul(int num, [ Optional ] int num2) { Console.WriteLine(num * num2); } // Main Method static public void Main() { my_mul(4); my_mul(2, 10); }}Output:0\n20\n"
},
{
"code": null,
"e": 36154,
"s": 36025,
"text": "Example: Here, we create an optional parameter using OptionalAttribute, here num2 is an optional parameter in the my_mul method."
},
{
"code": "// C# program to illustrate how to create// optional parameters using OptionalAttributeusing System;using System.Runtime.InteropServices; class GFG { // Method containing optional parameter // Using OptionalAttribute static public void my_mul(int num, [ Optional ] int num2) { Console.WriteLine(num * num2); } // Main Method static public void Main() { my_mul(4); my_mul(2, 10); }}",
"e": 36604,
"s": 36154,
"text": null
},
{
"code": null,
"e": 36610,
"s": 36604,
"text": "0\n20\n"
},
{
"code": null,
"e": 37706,
"s": 36610,
"text": "By Params Keyword: You can implement optional parameters by using the params keyword. It allows you to pass any variable number of parameters to a method. But you can use the params keyword for only one parameter and that parameter is the last parameter of the method. This method is not the pure way to implement an optional parameter, but you can achieve the optional parameter concept by using this method.Example: Here, optional parameter is created using the params keyword. Here a1 is the optional parameter and in which you can pass from zero to up to any number of variables.// C# program to illustrate how to create// optional parameters using params keywordusing System; class GFG { // Method containing optional // parameter Using params keyword static public void my_mul(int a, params int[] a1) { int mul = 1; foreach(int num in a1) { mul *= num; } Console.WriteLine(mul * a); } // Main method static public void Main() { my_mul(1); my_mul(2, 4); my_mul(3, 3, 100); }}Output:1\n8\n900\n"
},
{
"code": null,
"e": 37881,
"s": 37706,
"text": "Example: Here, optional parameter is created using the params keyword. Here a1 is the optional parameter and in which you can pass from zero to up to any number of variables."
},
{
"code": "// C# program to illustrate how to create// optional parameters using params keywordusing System; class GFG { // Method containing optional // parameter Using params keyword static public void my_mul(int a, params int[] a1) { int mul = 1; foreach(int num in a1) { mul *= num; } Console.WriteLine(mul * a); } // Main method static public void Main() { my_mul(1); my_mul(2, 4); my_mul(3, 3, 100); }}",
"e": 38379,
"s": 37881,
"text": null
},
{
"code": null,
"e": 38388,
"s": 38379,
"text": "1\n8\n900\n"
},
{
"code": null,
"e": 38402,
"s": 38388,
"text": "CSharp-method"
},
{
"code": null,
"e": 38405,
"s": 38402,
"text": "C#"
},
{
"code": null,
"e": 38503,
"s": 38405,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 38518,
"s": 38503,
"text": "C# | Delegates"
},
{
"code": null,
"e": 38540,
"s": 38518,
"text": "C# | Abstract Classes"
},
{
"code": null,
"e": 38563,
"s": 38540,
"text": "Extension Method in C#"
},
{
"code": null,
"e": 38585,
"s": 38563,
"text": "C# | Replace() Method"
},
{
"code": null,
"e": 38625,
"s": 38585,
"text": "C# | String.IndexOf( ) Method | Set - 1"
},
{
"code": null,
"e": 38656,
"s": 38625,
"text": "Introduction to .NET Framework"
},
{
"code": null,
"e": 38672,
"s": 38656,
"text": "C# | Data Types"
},
{
"code": null,
"e": 38684,
"s": 38672,
"text": "C# | Arrays"
},
{
"code": null,
"e": 38712,
"s": 38684,
"text": "HashSet in C# with Examples"
}
] |
Java Program to Use Method Overriding in Inheritance for Subclasses - GeeksforGeeks
|
28 Jan, 2021
Method overriding in Java is when a subclass implements a method that is already present inside the superclass. With the help of method overriding we can achieve runtime polymorphism. When we are overriding a method then we must keep three things in mind.
The method in the subclass must have the same name as the method present inside the superclass.
The method in the subclass should have the same number of parameters.
The return type (or sub-type) of the method in the subclass should be the same as the return type of the method inside the superclass.
In this article, we are going to discuss how we can use method overriding in the Inheritance of subclasses.
Let us understand the overriding of the methods of subclasses with the figure given below.
In the above figure, we have taken the example of the Grandpa class containing only one method i.e. show(). Dad class inherits the Grandpa class and overrides the show() method. After that Dad class is inherited by Me class which overrides the show() method of Dad class. After that, if we want to access the show() method of the above classes then we can make the object of that class since the method which would be invoked solely depends upon the type of the object but not on the type of reference variable referring to that object.
Let us understand the above concept using code.
Java
// Java Program to show the overriding using inheritance in// subclasses // Grandpa class is at the top of// the inheritance hierarchyclass Grandpa { public void show() { System.out.println( "Inside show() method of Grandpa class"); }} class Dad extends Grandpa { // Overriding show method of Grandpa class @Override public void show() { System.out.println( "Inside show() method of Dad class"); }} // class Me is inheriting Dad class (i.e.// a subclass of Grandpa class)class Me extends Dad { // Overriding show method of Dad class @Override public void show() { System.out.println( "Inside show() method of Me class"); }} public class GFG { public static void main(String[] args) { // Creating instance of Grandpa class Grandpa grandpa = new Grandpa(); // Creating instance of Dad class Grandpa dad = new Dad(); // Creating instance of Me class Grandpa me = new Me(); // as discussed which show() function will get // execute depends upon the type of object // show function of Grandpa class will get execute grandpa.show(); // show function of Dad class will get execute dad.show(); // show function of Me class will get execute me.show(); }}
Inside show() method of Grandpa class
Inside show() method of Dad class
Inside show() method of Me class
What happens if a subclass contains methods other than that of the parent/ superclass?
Let us understand this with the help of the figure mentioned below.
In the figure above we have taken one more method named display() inside the Dad class which is being overridden inside the Me class. Now if we try to access the display() method by making objects of Dad and Me class respectively and reference variable of Grandpa class, then it will give an error because a reference variable of that class can only be used to access the methods of subclasses that have been overridden from it down the hierarchy, ie we can’t use here reference variable of Grandpa class while calling display function, since Grandpa class is topmost in the hierarchy and it does not contain display function.
We will get the below error if we try to invoke the display() function using the reference variable of Grandpa() class.
dad.display();
me.display();
GFG.java:52: error: cannot find symbol
dad.display();
^
symbol: method display()
location: variable dad of type Grandpa
GFG.java:53: error: cannot find symbol
me.display();
^
symbol: method display()
location: variable me of type Grandpa
We can solve this problem by making our reference variable of Dad type or Me type refer to the object of Dad and Me class using the syntax mentioned below.
Dad dad1 = new Dad();
Dad me1 = new Me();
dad1.display();
me1.display();
Now, let us understand these concepts with the help of the code mentioned below.
Java
// Java Program to show the overriding using inheritance in// subclasses when subclass contains methods other than that// of the parent/ superclass // Grandpa class is at the top of// the inheritance hierarchyclass Grandpa { public void show() { System.out.println( "Inside show() method of Grandpa class"); }} class Dad extends Grandpa { // Overriding show method of Grandpa class @Override public void show() { System.out.println( "Inside show() method of Dad class"); } // Creating a display method() for Dad class public void display() { System.out.println( "Inside display() method of class B"); }} // class Me is inheriting Dad class (i.e.// a subclass of Grandpa class)class Me extends Dad { // Overriding show method of Dad class @Override public void show() { System.out.println( "Inside show() method of Me class"); } @Override public void display() { System.out.println( "Inside display() method of class C"); }} public class GFG { public static void main(String[] args) { // The code below works the same as in // previous example Grandpa grandpa = new Grandpa(); Grandpa dad = new Dad(); Grandpa me = new Me(); grandpa.show(); dad.show(); me.show(); // Making Dad type point to the // Dad object Dad dad1 = new Dad(); // Making Dad type reference variable point to the // Me object Dad me1 = new Me(); dad1.display(); me1.display(); }}
Inside show() method of Grandpa class
Inside show() method of Dad class
Inside show() method of Me class
Inside display() method of class B
Inside display() method of class C
java-inheritance
Java-Object Oriented
Picked
Java
Java Programs
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Stream In Java
Constructors in Java
Exceptions in Java
Functional Interfaces in Java
Different ways of Reading a text file in Java
Java Programming Examples
Convert Double to Integer in Java
Implementing a Linked List in Java using Class
How to Iterate HashMap in Java?
Program to print ASCII Value of a character
|
[
{
"code": null,
"e": 25225,
"s": 25197,
"text": "\n28 Jan, 2021"
},
{
"code": null,
"e": 25481,
"s": 25225,
"text": "Method overriding in Java is when a subclass implements a method that is already present inside the superclass. With the help of method overriding we can achieve runtime polymorphism. When we are overriding a method then we must keep three things in mind."
},
{
"code": null,
"e": 25577,
"s": 25481,
"text": "The method in the subclass must have the same name as the method present inside the superclass."
},
{
"code": null,
"e": 25647,
"s": 25577,
"text": "The method in the subclass should have the same number of parameters."
},
{
"code": null,
"e": 25782,
"s": 25647,
"text": "The return type (or sub-type) of the method in the subclass should be the same as the return type of the method inside the superclass."
},
{
"code": null,
"e": 25890,
"s": 25782,
"text": "In this article, we are going to discuss how we can use method overriding in the Inheritance of subclasses."
},
{
"code": null,
"e": 25981,
"s": 25890,
"text": "Let us understand the overriding of the methods of subclasses with the figure given below."
},
{
"code": null,
"e": 26519,
"s": 25981,
"text": "In the above figure, we have taken the example of the Grandpa class containing only one method i.e. show(). Dad class inherits the Grandpa class and overrides the show() method. After that Dad class is inherited by Me class which overrides the show() method of Dad class. After that, if we want to access the show() method of the above classes then we can make the object of that class since the method which would be invoked solely depends upon the type of the object but not on the type of reference variable referring to that object. "
},
{
"code": null,
"e": 26567,
"s": 26519,
"text": "Let us understand the above concept using code."
},
{
"code": null,
"e": 26572,
"s": 26567,
"text": "Java"
},
{
"code": "// Java Program to show the overriding using inheritance in// subclasses // Grandpa class is at the top of// the inheritance hierarchyclass Grandpa { public void show() { System.out.println( \"Inside show() method of Grandpa class\"); }} class Dad extends Grandpa { // Overriding show method of Grandpa class @Override public void show() { System.out.println( \"Inside show() method of Dad class\"); }} // class Me is inheriting Dad class (i.e.// a subclass of Grandpa class)class Me extends Dad { // Overriding show method of Dad class @Override public void show() { System.out.println( \"Inside show() method of Me class\"); }} public class GFG { public static void main(String[] args) { // Creating instance of Grandpa class Grandpa grandpa = new Grandpa(); // Creating instance of Dad class Grandpa dad = new Dad(); // Creating instance of Me class Grandpa me = new Me(); // as discussed which show() function will get // execute depends upon the type of object // show function of Grandpa class will get execute grandpa.show(); // show function of Dad class will get execute dad.show(); // show function of Me class will get execute me.show(); }}",
"e": 27966,
"s": 26572,
"text": null
},
{
"code": null,
"e": 28071,
"s": 27966,
"text": "Inside show() method of Grandpa class\nInside show() method of Dad class\nInside show() method of Me class"
},
{
"code": null,
"e": 28158,
"s": 28071,
"text": "What happens if a subclass contains methods other than that of the parent/ superclass?"
},
{
"code": null,
"e": 28226,
"s": 28158,
"text": "Let us understand this with the help of the figure mentioned below."
},
{
"code": null,
"e": 28853,
"s": 28226,
"text": "In the figure above we have taken one more method named display() inside the Dad class which is being overridden inside the Me class. Now if we try to access the display() method by making objects of Dad and Me class respectively and reference variable of Grandpa class, then it will give an error because a reference variable of that class can only be used to access the methods of subclasses that have been overridden from it down the hierarchy, ie we can’t use here reference variable of Grandpa class while calling display function, since Grandpa class is topmost in the hierarchy and it does not contain display function."
},
{
"code": null,
"e": 28973,
"s": 28853,
"text": "We will get the below error if we try to invoke the display() function using the reference variable of Grandpa() class."
},
{
"code": null,
"e": 29290,
"s": 28973,
"text": "dad.display();\nme.display();\n\nGFG.java:52: error: cannot find symbol\n dad.display();\n ^\n symbol: method display()\n location: variable dad of type Grandpa\nGFG.java:53: error: cannot find symbol\n me.display();\n ^\n symbol: method display()\n location: variable me of type Grandpa"
},
{
"code": null,
"e": 29446,
"s": 29290,
"text": "We can solve this problem by making our reference variable of Dad type or Me type refer to the object of Dad and Me class using the syntax mentioned below."
},
{
"code": null,
"e": 29519,
"s": 29446,
"text": "Dad dad1 = new Dad();\nDad me1 = new Me();\ndad1.display();\nme1.display();"
},
{
"code": null,
"e": 29600,
"s": 29519,
"text": "Now, let us understand these concepts with the help of the code mentioned below."
},
{
"code": null,
"e": 29605,
"s": 29600,
"text": "Java"
},
{
"code": "// Java Program to show the overriding using inheritance in// subclasses when subclass contains methods other than that// of the parent/ superclass // Grandpa class is at the top of// the inheritance hierarchyclass Grandpa { public void show() { System.out.println( \"Inside show() method of Grandpa class\"); }} class Dad extends Grandpa { // Overriding show method of Grandpa class @Override public void show() { System.out.println( \"Inside show() method of Dad class\"); } // Creating a display method() for Dad class public void display() { System.out.println( \"Inside display() method of class B\"); }} // class Me is inheriting Dad class (i.e.// a subclass of Grandpa class)class Me extends Dad { // Overriding show method of Dad class @Override public void show() { System.out.println( \"Inside show() method of Me class\"); } @Override public void display() { System.out.println( \"Inside display() method of class C\"); }} public class GFG { public static void main(String[] args) { // The code below works the same as in // previous example Grandpa grandpa = new Grandpa(); Grandpa dad = new Dad(); Grandpa me = new Me(); grandpa.show(); dad.show(); me.show(); // Making Dad type point to the // Dad object Dad dad1 = new Dad(); // Making Dad type reference variable point to the // Me object Dad me1 = new Me(); dad1.display(); me1.display(); }}",
"e": 31241,
"s": 29605,
"text": null
},
{
"code": null,
"e": 31416,
"s": 31241,
"text": "Inside show() method of Grandpa class\nInside show() method of Dad class\nInside show() method of Me class\nInside display() method of class B\nInside display() method of class C"
},
{
"code": null,
"e": 31433,
"s": 31416,
"text": "java-inheritance"
},
{
"code": null,
"e": 31454,
"s": 31433,
"text": "Java-Object Oriented"
},
{
"code": null,
"e": 31461,
"s": 31454,
"text": "Picked"
},
{
"code": null,
"e": 31466,
"s": 31461,
"text": "Java"
},
{
"code": null,
"e": 31480,
"s": 31466,
"text": "Java Programs"
},
{
"code": null,
"e": 31485,
"s": 31480,
"text": "Java"
},
{
"code": null,
"e": 31583,
"s": 31485,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 31598,
"s": 31583,
"text": "Stream In Java"
},
{
"code": null,
"e": 31619,
"s": 31598,
"text": "Constructors in Java"
},
{
"code": null,
"e": 31638,
"s": 31619,
"text": "Exceptions in Java"
},
{
"code": null,
"e": 31668,
"s": 31638,
"text": "Functional Interfaces in Java"
},
{
"code": null,
"e": 31714,
"s": 31668,
"text": "Different ways of Reading a text file in Java"
},
{
"code": null,
"e": 31740,
"s": 31714,
"text": "Java Programming Examples"
},
{
"code": null,
"e": 31774,
"s": 31740,
"text": "Convert Double to Integer in Java"
},
{
"code": null,
"e": 31821,
"s": 31774,
"text": "Implementing a Linked List in Java using Class"
},
{
"code": null,
"e": 31853,
"s": 31821,
"text": "How to Iterate HashMap in Java?"
}
] |
Python - Values Frequency Index List - GeeksforGeeks
|
10 Jul, 2020
Sometimes, while working with Python tuples, we can have a problem in which we need to extract the frequency of each value in tuple. This has been solved earlier. We can have a modification in which we need to create list in which index represents the key and value of it represents the frequency of that index number. This kind of problem can have applications in competitive programming domain. Let’s discuss certain ways in which we need to solve this problem.
Input : test_list = [(‘Gfg’, 1), (‘is’, 1), (‘best’, 1), (‘for’, 1), (‘geeks’, 1)]Output : [0, 5, 0, 0, 0, 0]
Input : test_list = [(‘Gfg’, 5), (‘is’, 5)]Output : [0, 0, 0, 0, 0, 2]
Method #1 : Using loopThis is brute force approach by which this task can be performed. In this, we perform the task of assigning frequency by iterating and assigning pre-initialized list.
# Python3 code to demonstrate working of # Values Frequency Index List# Using loop # initializing listtest_list = [('Gfg', 3), ('is', 3), ('best', 1), ('for', 5), ('geeks', 1)] # printing original listprint("The original list is : " + str(test_list)) # Values Frequency Index List# Using loopres = [0 for _ in range(6)]for ele in test_list: res[ele[1]] = res[ele[1]] + 1 # printing result print("The Frequency list : " + str(res))
The original list is : [('Gfg', 3), ('is', 3), ('best', 1), ('for', 5), ('geeks', 1)]
The Frequency list : [0, 2, 0, 2, 0, 1]
Method #2 : Using Counter() + list comprehensionThe combination of above functionalities is used to solve this problem. In this, we perform the task of computing frequencies using Counter() and rendering in list is done by list comprehension.
# Python3 code to demonstrate working of # Values Frequency Index List# Using Counter() + list comprehensionfrom collections import Counter # initializing listtest_list = [('Gfg', 3), ('is', 3), ('best', 1), ('for', 5), ('geeks', 1)] # printing original listprint("The original list is : " + str(test_list)) # Values Frequency Index List# Using Counter() + list comprehensioncntr = Counter(ele[1] for ele in test_list)res = [cntr[idx] for idx in range(6)] # printing result print("The Frequency list : " + str(res))
The original list is : [('Gfg', 3), ('is', 3), ('best', 1), ('for', 5), ('geeks', 1)]
The Frequency list : [0, 2, 0, 2, 0, 1]
Python List-of-Tuples
Python list-programs
Python
Python Programs
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python Dictionary
How to Install PIP on Windows ?
Enumerate() in Python
Different ways to create Pandas Dataframe
Iterate over a list in Python
Python program to convert a list to string
Defaultdict in Python
Python | Get dictionary keys as a list
Python | Split string into list of characters
Python | Convert a list to dictionary
|
[
{
"code": null,
"e": 26095,
"s": 26067,
"text": "\n10 Jul, 2020"
},
{
"code": null,
"e": 26559,
"s": 26095,
"text": "Sometimes, while working with Python tuples, we can have a problem in which we need to extract the frequency of each value in tuple. This has been solved earlier. We can have a modification in which we need to create list in which index represents the key and value of it represents the frequency of that index number. This kind of problem can have applications in competitive programming domain. Let’s discuss certain ways in which we need to solve this problem."
},
{
"code": null,
"e": 26669,
"s": 26559,
"text": "Input : test_list = [(‘Gfg’, 1), (‘is’, 1), (‘best’, 1), (‘for’, 1), (‘geeks’, 1)]Output : [0, 5, 0, 0, 0, 0]"
},
{
"code": null,
"e": 26740,
"s": 26669,
"text": "Input : test_list = [(‘Gfg’, 5), (‘is’, 5)]Output : [0, 0, 0, 0, 0, 2]"
},
{
"code": null,
"e": 26929,
"s": 26740,
"text": "Method #1 : Using loopThis is brute force approach by which this task can be performed. In this, we perform the task of assigning frequency by iterating and assigning pre-initialized list."
},
{
"code": "# Python3 code to demonstrate working of # Values Frequency Index List# Using loop # initializing listtest_list = [('Gfg', 3), ('is', 3), ('best', 1), ('for', 5), ('geeks', 1)] # printing original listprint(\"The original list is : \" + str(test_list)) # Values Frequency Index List# Using loopres = [0 for _ in range(6)]for ele in test_list: res[ele[1]] = res[ele[1]] + 1 # printing result print(\"The Frequency list : \" + str(res)) ",
"e": 27368,
"s": 26929,
"text": null
},
{
"code": null,
"e": 27495,
"s": 27368,
"text": "The original list is : [('Gfg', 3), ('is', 3), ('best', 1), ('for', 5), ('geeks', 1)]\nThe Frequency list : [0, 2, 0, 2, 0, 1]\n"
},
{
"code": null,
"e": 27740,
"s": 27497,
"text": "Method #2 : Using Counter() + list comprehensionThe combination of above functionalities is used to solve this problem. In this, we perform the task of computing frequencies using Counter() and rendering in list is done by list comprehension."
},
{
"code": "# Python3 code to demonstrate working of # Values Frequency Index List# Using Counter() + list comprehensionfrom collections import Counter # initializing listtest_list = [('Gfg', 3), ('is', 3), ('best', 1), ('for', 5), ('geeks', 1)] # printing original listprint(\"The original list is : \" + str(test_list)) # Values Frequency Index List# Using Counter() + list comprehensioncntr = Counter(ele[1] for ele in test_list)res = [cntr[idx] for idx in range(6)] # printing result print(\"The Frequency list : \" + str(res)) ",
"e": 28261,
"s": 27740,
"text": null
},
{
"code": null,
"e": 28388,
"s": 28261,
"text": "The original list is : [('Gfg', 3), ('is', 3), ('best', 1), ('for', 5), ('geeks', 1)]\nThe Frequency list : [0, 2, 0, 2, 0, 1]\n"
},
{
"code": null,
"e": 28410,
"s": 28388,
"text": "Python List-of-Tuples"
},
{
"code": null,
"e": 28431,
"s": 28410,
"text": "Python list-programs"
},
{
"code": null,
"e": 28438,
"s": 28431,
"text": "Python"
},
{
"code": null,
"e": 28454,
"s": 28438,
"text": "Python Programs"
},
{
"code": null,
"e": 28552,
"s": 28454,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 28570,
"s": 28552,
"text": "Python Dictionary"
},
{
"code": null,
"e": 28602,
"s": 28570,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 28624,
"s": 28602,
"text": "Enumerate() in Python"
},
{
"code": null,
"e": 28666,
"s": 28624,
"text": "Different ways to create Pandas Dataframe"
},
{
"code": null,
"e": 28696,
"s": 28666,
"text": "Iterate over a list in Python"
},
{
"code": null,
"e": 28739,
"s": 28696,
"text": "Python program to convert a list to string"
},
{
"code": null,
"e": 28761,
"s": 28739,
"text": "Defaultdict in Python"
},
{
"code": null,
"e": 28800,
"s": 28761,
"text": "Python | Get dictionary keys as a list"
},
{
"code": null,
"e": 28846,
"s": 28800,
"text": "Python | Split string into list of characters"
}
] |
Python | Check if list contains all unique elements - GeeksforGeeks
|
23 Dec, 2018
Some list operations require us to check if all the elements in the list are unique. This usually happens when we try to perform the set operations in a list. Hence this particular utility is essential at these times. Lets discuss certain methods by which this can be performed.
Method #1 : Naive MethodSolutions usually start from the simplest method one can apply to perform a particular task. Here you can use a nested loop to check if after that element similar element exists in the remaining list.
# Python3 code to demonstrate # to test all elements in list are unique# using naive method # initializing list test_list = [1, 3, 4, 6, 7] # printing original list print ("The original list is : " + str(test_list)) flag = 0 # using naive method # to check all unique list elementsfor i in range(len(test_list)): for i1 in range(len(test_list)): if i != i1: if test_list[i] == test_list[i1]: flag = 1 # printing resultif(not flag) : print ("List contains all unique elements")else : print ("List contains does not contains all unique elements")
Output :
The original list is : [1, 3, 4, 6, 7]
List contains all unique elements
Method #2 : Using len() + set()This is most elegant way in which this problem can be solved by using just a single line. This solution converts the list to set and then tests with original list if contains similar no. of elements.
# Python3 code to demonstrate # to test all elements in list are unique# using set() + len() # initializing list test_list = [1, 3, 4, 6, 7] # printing original list print ("The original list is : " + str(test_list)) flag = 0 # using set() + len()# to check all unique list elementsflag = len(set(test_list)) == len(test_list) # printing resultif(flag) : print ("List contains all unique elements")else : print ("List contains does not contains all unique elements")
Output :
The original list is : [1, 3, 4, 6, 7]
List contains all unique elements
Method #3 : Using Counter.itervalues()This is one of the different methods and uses the frequency obtained of all the elements using Counter, and checks if any of the frequency is greater than 1.
# Python code to demonstrate # to test all elements in list are unique# using Counter.itervalues()from collections import Counter # initializing list test_list = [1, 3, 4, 6, 7] # printing original list print ("The original list is : " + str(test_list)) flag = 0 # using Counter.itervalues() # to check all unique list elementscounter = Counter(test_list)for values in counter.itervalues(): if values > 1: flag = 1 # printing resultif(not flag) : print ("List contains all unique elements")else : print ("List contains does not contains all unique elements")
Output :
The original list is : [1, 3, 4, 6, 7]
List contains all unique elements
Python list-programs
python-list
Python
python-list
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python Dictionary
How to Install PIP on Windows ?
Enumerate() in Python
Different ways to create Pandas Dataframe
Python String | replace()
*args and **kwargs in Python
Reading and Writing to text files in Python
Create a Pandas DataFrame from Lists
Convert integer to string in Python
Check if element exists in list in Python
|
[
{
"code": null,
"e": 26127,
"s": 26099,
"text": "\n23 Dec, 2018"
},
{
"code": null,
"e": 26406,
"s": 26127,
"text": "Some list operations require us to check if all the elements in the list are unique. This usually happens when we try to perform the set operations in a list. Hence this particular utility is essential at these times. Lets discuss certain methods by which this can be performed."
},
{
"code": null,
"e": 26631,
"s": 26406,
"text": "Method #1 : Naive MethodSolutions usually start from the simplest method one can apply to perform a particular task. Here you can use a nested loop to check if after that element similar element exists in the remaining list."
},
{
"code": "# Python3 code to demonstrate # to test all elements in list are unique# using naive method # initializing list test_list = [1, 3, 4, 6, 7] # printing original list print (\"The original list is : \" + str(test_list)) flag = 0 # using naive method # to check all unique list elementsfor i in range(len(test_list)): for i1 in range(len(test_list)): if i != i1: if test_list[i] == test_list[i1]: flag = 1 # printing resultif(not flag) : print (\"List contains all unique elements\")else : print (\"List contains does not contains all unique elements\")",
"e": 27243,
"s": 26631,
"text": null
},
{
"code": null,
"e": 27252,
"s": 27243,
"text": "Output :"
},
{
"code": null,
"e": 27326,
"s": 27252,
"text": "The original list is : [1, 3, 4, 6, 7]\nList contains all unique elements\n"
},
{
"code": null,
"e": 27557,
"s": 27326,
"text": "Method #2 : Using len() + set()This is most elegant way in which this problem can be solved by using just a single line. This solution converts the list to set and then tests with original list if contains similar no. of elements."
},
{
"code": "# Python3 code to demonstrate # to test all elements in list are unique# using set() + len() # initializing list test_list = [1, 3, 4, 6, 7] # printing original list print (\"The original list is : \" + str(test_list)) flag = 0 # using set() + len()# to check all unique list elementsflag = len(set(test_list)) == len(test_list) # printing resultif(flag) : print (\"List contains all unique elements\")else : print (\"List contains does not contains all unique elements\")",
"e": 28038,
"s": 27557,
"text": null
},
{
"code": null,
"e": 28047,
"s": 28038,
"text": "Output :"
},
{
"code": null,
"e": 28121,
"s": 28047,
"text": "The original list is : [1, 3, 4, 6, 7]\nList contains all unique elements\n"
},
{
"code": null,
"e": 28317,
"s": 28121,
"text": "Method #3 : Using Counter.itervalues()This is one of the different methods and uses the frequency obtained of all the elements using Counter, and checks if any of the frequency is greater than 1."
},
{
"code": "# Python code to demonstrate # to test all elements in list are unique# using Counter.itervalues()from collections import Counter # initializing list test_list = [1, 3, 4, 6, 7] # printing original list print (\"The original list is : \" + str(test_list)) flag = 0 # using Counter.itervalues() # to check all unique list elementscounter = Counter(test_list)for values in counter.itervalues(): if values > 1: flag = 1 # printing resultif(not flag) : print (\"List contains all unique elements\")else : print (\"List contains does not contains all unique elements\")",
"e": 28908,
"s": 28317,
"text": null
},
{
"code": null,
"e": 28917,
"s": 28908,
"text": "Output :"
},
{
"code": null,
"e": 28991,
"s": 28917,
"text": "The original list is : [1, 3, 4, 6, 7]\nList contains all unique elements\n"
},
{
"code": null,
"e": 29012,
"s": 28991,
"text": "Python list-programs"
},
{
"code": null,
"e": 29024,
"s": 29012,
"text": "python-list"
},
{
"code": null,
"e": 29031,
"s": 29024,
"text": "Python"
},
{
"code": null,
"e": 29043,
"s": 29031,
"text": "python-list"
},
{
"code": null,
"e": 29141,
"s": 29043,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 29159,
"s": 29141,
"text": "Python Dictionary"
},
{
"code": null,
"e": 29191,
"s": 29159,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 29213,
"s": 29191,
"text": "Enumerate() in Python"
},
{
"code": null,
"e": 29255,
"s": 29213,
"text": "Different ways to create Pandas Dataframe"
},
{
"code": null,
"e": 29281,
"s": 29255,
"text": "Python String | replace()"
},
{
"code": null,
"e": 29310,
"s": 29281,
"text": "*args and **kwargs in Python"
},
{
"code": null,
"e": 29354,
"s": 29310,
"text": "Reading and Writing to text files in Python"
},
{
"code": null,
"e": 29391,
"s": 29354,
"text": "Create a Pandas DataFrame from Lists"
},
{
"code": null,
"e": 29427,
"s": 29391,
"text": "Convert integer to string in Python"
}
] |
How to Install and Configure Synaptic Package Manager in Ubuntu? - GeeksforGeeks
|
05 Oct, 2021
Synaptic Package Manager is a GUI based package management tool that uses APT (Advanced Package Tool) to installing, updating or removing packages from the Linux system. Some of the feature given by Synaptic Package Manager are:
Allow installing, updating or removing packages
Upgrading whole system
Searching and filtering the list of packages available with APT
Fixing broken package dependencies
Force the installation of a specific package version
Step 1: To install Synaptic Package Manager, open terminal on your system and enter a command.
$ sudo apt install synaptic
Enter the password, press “Y” and enter.
Step 2: Once the installation completes, you can open the GUI window by typing.
$ sudo synaptic
Step 1: Search for the required packages in the search bar placed at the top.
Step 2: When you click on the search icon a window will appear, type the name of the package you need.
Step 3: Mark the packages you need from the search list.
and press Apply button on the top bar.
sooda367
how-to-install
How To
Installation Guide
Linux-Unix
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Install FFmpeg on Windows?
How to Add External JAR File to an IntelliJ IDEA Project?
How to Set Git Username and Password in GitBash?
How to Install Jupyter Notebook on MacOS?
How to Create and Setup Spring Boot Project in Eclipse IDE?
Installation of Node.js on Linux
How to Install FFmpeg on Windows?
How to Install Pygame on Windows ?
How to Add External JAR File to an IntelliJ IDEA Project?
How to Install Jupyter Notebook on MacOS?
|
[
{
"code": null,
"e": 26197,
"s": 26169,
"text": "\n05 Oct, 2021"
},
{
"code": null,
"e": 26427,
"s": 26197,
"text": "Synaptic Package Manager is a GUI based package management tool that uses APT (Advanced Package Tool) to installing, updating or removing packages from the Linux system. Some of the feature given by Synaptic Package Manager are: "
},
{
"code": null,
"e": 26477,
"s": 26429,
"text": "Allow installing, updating or removing packages"
},
{
"code": null,
"e": 26500,
"s": 26477,
"text": "Upgrading whole system"
},
{
"code": null,
"e": 26564,
"s": 26500,
"text": "Searching and filtering the list of packages available with APT"
},
{
"code": null,
"e": 26599,
"s": 26564,
"text": "Fixing broken package dependencies"
},
{
"code": null,
"e": 26652,
"s": 26599,
"text": "Force the installation of a specific package version"
},
{
"code": null,
"e": 26752,
"s": 26656,
"text": "Step 1: To install Synaptic Package Manager, open terminal on your system and enter a command. "
},
{
"code": null,
"e": 26782,
"s": 26754,
"text": "$ sudo apt install synaptic"
},
{
"code": null,
"e": 26824,
"s": 26782,
"text": "Enter the password, press “Y” and enter. "
},
{
"code": null,
"e": 26907,
"s": 26826,
"text": "Step 2: Once the installation completes, you can open the GUI window by typing. "
},
{
"code": null,
"e": 26925,
"s": 26909,
"text": "$ sudo synaptic"
},
{
"code": null,
"e": 27008,
"s": 26929,
"text": "Step 1: Search for the required packages in the search bar placed at the top. "
},
{
"code": null,
"e": 27114,
"s": 27010,
"text": "Step 2: When you click on the search icon a window will appear, type the name of the package you need. "
},
{
"code": null,
"e": 27174,
"s": 27116,
"text": "Step 3: Mark the packages you need from the search list. "
},
{
"code": null,
"e": 27216,
"s": 27176,
"text": "and press Apply button on the top bar. "
},
{
"code": null,
"e": 27229,
"s": 27220,
"text": "sooda367"
},
{
"code": null,
"e": 27244,
"s": 27229,
"text": "how-to-install"
},
{
"code": null,
"e": 27251,
"s": 27244,
"text": "How To"
},
{
"code": null,
"e": 27270,
"s": 27251,
"text": "Installation Guide"
},
{
"code": null,
"e": 27281,
"s": 27270,
"text": "Linux-Unix"
},
{
"code": null,
"e": 27379,
"s": 27281,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 27413,
"s": 27379,
"text": "How to Install FFmpeg on Windows?"
},
{
"code": null,
"e": 27471,
"s": 27413,
"text": "How to Add External JAR File to an IntelliJ IDEA Project?"
},
{
"code": null,
"e": 27520,
"s": 27471,
"text": "How to Set Git Username and Password in GitBash?"
},
{
"code": null,
"e": 27562,
"s": 27520,
"text": "How to Install Jupyter Notebook on MacOS?"
},
{
"code": null,
"e": 27622,
"s": 27562,
"text": "How to Create and Setup Spring Boot Project in Eclipse IDE?"
},
{
"code": null,
"e": 27655,
"s": 27622,
"text": "Installation of Node.js on Linux"
},
{
"code": null,
"e": 27689,
"s": 27655,
"text": "How to Install FFmpeg on Windows?"
},
{
"code": null,
"e": 27724,
"s": 27689,
"text": "How to Install Pygame on Windows ?"
},
{
"code": null,
"e": 27782,
"s": 27724,
"text": "How to Add External JAR File to an IntelliJ IDEA Project?"
}
] |
Quiz Game in C++ - GeeksforGeeks
|
12 Nov, 2021
In this article, the task is to create a quiz game where the user will be asked questions and the result of each question whether it is correct or wrong with the updated score will be shown.
Below is the implementation of the same:
C++
// C++ program for the above approach#include <iostream>#include <string>using namespace std; int Guess;int Total; // Question Classclass Question {private: string Question_Text; string Answer_1; string Answer_2; string Answer_3; string Answer_4; int Correct_Answer; int Question_Score; public: // Setter Function void setValues(string, string, string, string, string, int, int); // Function to ask questions void askQuestion();}; // Driver codeint main(){ cout << "\n\n\t\t\t\tTHE DAILY QUIZ" << endl; cout << "\nPress Enter to start " << "the quiz... " << endl; // Input cin.get(); string Name; int Age; // Input the details cout << "What is your name?" << endl; cin >> Name; cout << endl; cout << "How old are you?" << endl; cin >> Age; cout << endl; string Respond; cout << "Are you ready to take" << " the quiz " << Name << "? yes/no" << endl; cin >> Respond; if (Respond == "yes") { cout << endl; cout << "Good Luck!" << endl; } else { cout << "Okay Good Bye!" << endl; return 0; } // Objects of Question Class Question q1; Question q2; Question q3; Question q4; Question q5; Question q6; Question q7; Question q8; Question q9; Question q10; // 3 is the position of // correct answer q1.setValues("Question : ", "Answer 1", "Answer 2", "Answer 3", "Answer 4", 3, 10); q2.setValues("Question : ", "Answer 1", "Answer 2", "Answer 3", "Answer 4", 3, 10); q3.setValues("Question : ", "Answer 1", "Answer 2", "Answer 3", "Answer 4", 3, 10); q4.setValues("Question : ", "Answer 1", "Answer 2", "Answer 3", "Answer 4", 3, 10); q5.setValues("Question : ", "Answer 1", "Answer 2", "Answer 3", "Answer 4", 3, 10); q6.setValues("Question : ", "Answer 1", "Answer 2", "Answer 3", "Answer 4", 3, 10); q7.setValues("Question : ", "Answer 1", "Answer 2", "Answer 3", "Answer 4", 3, 10); q8.setValues("Question : ", "Answer 1", "Answer 2", "Answer 3", "Answer 4", 3, 10); q9.setValues("Question : ", "Answer 1", "Answer 2", "Answer 3", "Answer 4", 3, 10); q10.setValues("Question : ", "Answer 1", "Answer 2", "Answer 3", "Answer 4", 3, 10); q1.askQuestion(); q2.askQuestion(); q3.askQuestion(); q4.askQuestion(); q5.askQuestion(); q6.askQuestion(); q7.askQuestion(); q8.askQuestion(); q9.askQuestion(); q10.askQuestion(); // Display the total score cout << "Total Score = " << Total << "out of 100" << endl; // Display the results // If the player pass the quiz if (Total >= 70) { cout << "Congrats you passed the" << " quiz!" << endl; } // Otherwise else { cout << "Alas! You failed the quiz." << endl; cout << "Better luck next time." << endl; } return 0;} // Function to set the values of// the questionsvoid Question::setValues( string q, string a1, string a2, string a3, string a4, int ca, int pa){ Question_Text = q; Answer_1 = a1; Answer_2 = a2; Answer_3 = a3; Answer_4 = a4; Correct_Answer = ca; Question_Score = pa;} // Function to ask questionsvoid Question::askQuestion(){ cout << endl; // Print the questions cout << Question_Text << endl; cout << "1. " << Answer_1 << endl; cout << "2. " << Answer_2 << endl; cout << "3. " << Answer_3 << endl; cout << "4. " << Answer_4 << endl; cout << endl; // Display the answer cout << "What is your answer?(in number)" << endl; cin >> Guess; // If the answer is correct if (Guess == Correct_Answer) { cout << endl; cout << "Correct !" << endl; // Update the correct score Total = Total + Question_Score; cout << "Score = " << Question_Score << " out of " << Question_Score << "!" << endl; cout << endl; } // Otherwise else { cout << endl; cout << "Wrong !" << endl; cout << "Score = 0" << " out of " << Question_Score << "!" << endl; cout << "Correct answer = " << Correct_Answer << "." << endl; cout << endl; }}
Output:
prachisoda1234
C++
C++ Programs
Project
Technical Scripter
CPP
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Operator Overloading in C++
Polymorphism in C++
Sorting a vector in C++
Friend class and function in C++
std::string class in C++
Header files in C/C++ and its uses
Program to print ASCII Value of a character
How to return multiple values from a function in C or C++?
C++ Program for QuickSort
Sorting a Map by value in C++ STL
|
[
{
"code": null,
"e": 25369,
"s": 25341,
"text": "\n12 Nov, 2021"
},
{
"code": null,
"e": 25560,
"s": 25369,
"text": "In this article, the task is to create a quiz game where the user will be asked questions and the result of each question whether it is correct or wrong with the updated score will be shown."
},
{
"code": null,
"e": 25601,
"s": 25560,
"text": "Below is the implementation of the same:"
},
{
"code": null,
"e": 25605,
"s": 25601,
"text": "C++"
},
{
"code": "// C++ program for the above approach#include <iostream>#include <string>using namespace std; int Guess;int Total; // Question Classclass Question {private: string Question_Text; string Answer_1; string Answer_2; string Answer_3; string Answer_4; int Correct_Answer; int Question_Score; public: // Setter Function void setValues(string, string, string, string, string, int, int); // Function to ask questions void askQuestion();}; // Driver codeint main(){ cout << \"\\n\\n\\t\\t\\t\\tTHE DAILY QUIZ\" << endl; cout << \"\\nPress Enter to start \" << \"the quiz... \" << endl; // Input cin.get(); string Name; int Age; // Input the details cout << \"What is your name?\" << endl; cin >> Name; cout << endl; cout << \"How old are you?\" << endl; cin >> Age; cout << endl; string Respond; cout << \"Are you ready to take\" << \" the quiz \" << Name << \"? yes/no\" << endl; cin >> Respond; if (Respond == \"yes\") { cout << endl; cout << \"Good Luck!\" << endl; } else { cout << \"Okay Good Bye!\" << endl; return 0; } // Objects of Question Class Question q1; Question q2; Question q3; Question q4; Question q5; Question q6; Question q7; Question q8; Question q9; Question q10; // 3 is the position of // correct answer q1.setValues(\"Question : \", \"Answer 1\", \"Answer 2\", \"Answer 3\", \"Answer 4\", 3, 10); q2.setValues(\"Question : \", \"Answer 1\", \"Answer 2\", \"Answer 3\", \"Answer 4\", 3, 10); q3.setValues(\"Question : \", \"Answer 1\", \"Answer 2\", \"Answer 3\", \"Answer 4\", 3, 10); q4.setValues(\"Question : \", \"Answer 1\", \"Answer 2\", \"Answer 3\", \"Answer 4\", 3, 10); q5.setValues(\"Question : \", \"Answer 1\", \"Answer 2\", \"Answer 3\", \"Answer 4\", 3, 10); q6.setValues(\"Question : \", \"Answer 1\", \"Answer 2\", \"Answer 3\", \"Answer 4\", 3, 10); q7.setValues(\"Question : \", \"Answer 1\", \"Answer 2\", \"Answer 3\", \"Answer 4\", 3, 10); q8.setValues(\"Question : \", \"Answer 1\", \"Answer 2\", \"Answer 3\", \"Answer 4\", 3, 10); q9.setValues(\"Question : \", \"Answer 1\", \"Answer 2\", \"Answer 3\", \"Answer 4\", 3, 10); q10.setValues(\"Question : \", \"Answer 1\", \"Answer 2\", \"Answer 3\", \"Answer 4\", 3, 10); q1.askQuestion(); q2.askQuestion(); q3.askQuestion(); q4.askQuestion(); q5.askQuestion(); q6.askQuestion(); q7.askQuestion(); q8.askQuestion(); q9.askQuestion(); q10.askQuestion(); // Display the total score cout << \"Total Score = \" << Total << \"out of 100\" << endl; // Display the results // If the player pass the quiz if (Total >= 70) { cout << \"Congrats you passed the\" << \" quiz!\" << endl; } // Otherwise else { cout << \"Alas! You failed the quiz.\" << endl; cout << \"Better luck next time.\" << endl; } return 0;} // Function to set the values of// the questionsvoid Question::setValues( string q, string a1, string a2, string a3, string a4, int ca, int pa){ Question_Text = q; Answer_1 = a1; Answer_2 = a2; Answer_3 = a3; Answer_4 = a4; Correct_Answer = ca; Question_Score = pa;} // Function to ask questionsvoid Question::askQuestion(){ cout << endl; // Print the questions cout << Question_Text << endl; cout << \"1. \" << Answer_1 << endl; cout << \"2. \" << Answer_2 << endl; cout << \"3. \" << Answer_3 << endl; cout << \"4. \" << Answer_4 << endl; cout << endl; // Display the answer cout << \"What is your answer?(in number)\" << endl; cin >> Guess; // If the answer is correct if (Guess == Correct_Answer) { cout << endl; cout << \"Correct !\" << endl; // Update the correct score Total = Total + Question_Score; cout << \"Score = \" << Question_Score << \" out of \" << Question_Score << \"!\" << endl; cout << endl; } // Otherwise else { cout << endl; cout << \"Wrong !\" << endl; cout << \"Score = 0\" << \" out of \" << Question_Score << \"!\" << endl; cout << \"Correct answer = \" << Correct_Answer << \".\" << endl; cout << endl; }}",
"e": 30261,
"s": 25605,
"text": null
},
{
"code": null,
"e": 30269,
"s": 30261,
"text": "Output:"
},
{
"code": null,
"e": 30284,
"s": 30269,
"text": "prachisoda1234"
},
{
"code": null,
"e": 30288,
"s": 30284,
"text": "C++"
},
{
"code": null,
"e": 30301,
"s": 30288,
"text": "C++ Programs"
},
{
"code": null,
"e": 30309,
"s": 30301,
"text": "Project"
},
{
"code": null,
"e": 30328,
"s": 30309,
"text": "Technical Scripter"
},
{
"code": null,
"e": 30332,
"s": 30328,
"text": "CPP"
},
{
"code": null,
"e": 30430,
"s": 30332,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 30458,
"s": 30430,
"text": "Operator Overloading in C++"
},
{
"code": null,
"e": 30478,
"s": 30458,
"text": "Polymorphism in C++"
},
{
"code": null,
"e": 30502,
"s": 30478,
"text": "Sorting a vector in C++"
},
{
"code": null,
"e": 30535,
"s": 30502,
"text": "Friend class and function in C++"
},
{
"code": null,
"e": 30560,
"s": 30535,
"text": "std::string class in C++"
},
{
"code": null,
"e": 30595,
"s": 30560,
"text": "Header files in C/C++ and its uses"
},
{
"code": null,
"e": 30639,
"s": 30595,
"text": "Program to print ASCII Value of a character"
},
{
"code": null,
"e": 30698,
"s": 30639,
"text": "How to return multiple values from a function in C or C++?"
},
{
"code": null,
"e": 30724,
"s": 30698,
"text": "C++ Program for QuickSort"
}
] |
How to get column names from SQLAlchemy? - GeeksforGeeks
|
04 Jan, 2022
In this article, we will discuss how to get column names using SQLAlchemy in Python.
SQLAlchemy is an open-source SQL toolkit and object-relational mapper for the Python programming language released under the MIT License. It gives full power and flexibility of SQL to an application. To follow along with this article, we need to have sqlalchemy and anyone database installed in our system. We have used the MySQL database for this article’s understanding.
To install sqlalchemy using pip:
pip install sqlalchemy
For our examples, we have already created a Profile table under Geeks4Geeks schema name, which we will be using:
There are different ways through which we can get the column names in SQLAlchemy.
Here we will use key() methods to get the get column names. It returns an iterable view which yields the string keys that would be represented by each Row.
Syntax: sqlalchemy.engine.Result.keys()
Python
import sqlalchemy as dbfrom sqlalchemy.ext.declarative import declarative_base Base = declarative_base() # DEFINE THE ENGINE (CONNECTION OBJECT)engine = db.create_engine( "mysql+pymysql://root:password@localhost/Geeks4Geeks") # CREATE THE TABLE MODEL TO USE IT FOR QUERYINGclass Profile(Base): __tablename__ = 'profile' email = db.Column(db.String(50), primary_key=True) name = db.Column(db.String(100)) contact = db.Column(db.Integer) # PREPARING SQLALCHEMY QUERYwith engine.connect() as conn: result = conn.execute( db.select([Profile.email, Profile.name, Profile.contact])) # VIEW THE COLUMN NAMESprint(result.keys())
Output:
In the above example, we have used SQLAlchemy ORM to create a Profile table.
Firstly, the engine is configured so that it can be used to perform SQL transactions.
Then, the Profile table is defined in the form of ORM class.
Using the sqlalchemy engine we are querying the Profile table to select all the records from the table for columns email, name, and contact. The information is stored in the result variable. This variable holds the column names and the records that have been fetched from the Profile table. The datatype of result variable is sqlalchemy.engine.Result.
To access the column names we can use the method keys() on the result. It returns a list of column names.
Since, we queried only three columns, we can view the same columns on the output as well.
This returns the ‘key’ for the Table Metadata.
Syntax: sqlalchemy.schema.Table.key
Python
import sqlalchemy as dbfrom sqlalchemy.ext.declarative import declarative_base Base = declarative_base() # DEFINE THE ENGINE (CONNECTIO OBJECT)engine = db.create_engine( "mysql+pymysql://root:password@localhost/Geeks4Geeks") # CREATE THE TABLE MODEL TO USE IT FOR QUERYINGclass Profile(Base): __tablename__ = 'profile' email = db.Column(db.String(50), primary_key=True) name = db.Column(db.String(100)) contact = db.Column(db.Integer) # PREPARING SQLALCHEMY QUERYwith engine.connect() as conn: result = conn.execute( db.select([Profile.email, Profile.name, Profile.contact])) # VIEW THE COLUMN NAMESprint(result._metadata.keys)
Output:
Picked
Python SQLAlchemy-ORM
Python-SQLAlchemy
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Install PIP on Windows ?
Check if element exists in list in Python
How To Convert Python Dictionary To JSON?
Python Classes and Objects
How to drop one or multiple columns in Pandas Dataframe
Python | Get unique values from a list
Defaultdict in Python
Python | os.path.join() method
Create a directory in Python
Python | Pandas dataframe.groupby()
|
[
{
"code": null,
"e": 25537,
"s": 25509,
"text": "\n04 Jan, 2022"
},
{
"code": null,
"e": 25622,
"s": 25537,
"text": "In this article, we will discuss how to get column names using SQLAlchemy in Python."
},
{
"code": null,
"e": 25995,
"s": 25622,
"text": "SQLAlchemy is an open-source SQL toolkit and object-relational mapper for the Python programming language released under the MIT License. It gives full power and flexibility of SQL to an application. To follow along with this article, we need to have sqlalchemy and anyone database installed in our system. We have used the MySQL database for this article’s understanding."
},
{
"code": null,
"e": 26028,
"s": 25995,
"text": "To install sqlalchemy using pip:"
},
{
"code": null,
"e": 26051,
"s": 26028,
"text": "pip install sqlalchemy"
},
{
"code": null,
"e": 26164,
"s": 26051,
"text": "For our examples, we have already created a Profile table under Geeks4Geeks schema name, which we will be using:"
},
{
"code": null,
"e": 26246,
"s": 26164,
"text": "There are different ways through which we can get the column names in SQLAlchemy."
},
{
"code": null,
"e": 26402,
"s": 26246,
"text": "Here we will use key() methods to get the get column names. It returns an iterable view which yields the string keys that would be represented by each Row."
},
{
"code": null,
"e": 26442,
"s": 26402,
"text": "Syntax: sqlalchemy.engine.Result.keys()"
},
{
"code": null,
"e": 26449,
"s": 26442,
"text": "Python"
},
{
"code": "import sqlalchemy as dbfrom sqlalchemy.ext.declarative import declarative_base Base = declarative_base() # DEFINE THE ENGINE (CONNECTION OBJECT)engine = db.create_engine( \"mysql+pymysql://root:password@localhost/Geeks4Geeks\") # CREATE THE TABLE MODEL TO USE IT FOR QUERYINGclass Profile(Base): __tablename__ = 'profile' email = db.Column(db.String(50), primary_key=True) name = db.Column(db.String(100)) contact = db.Column(db.Integer) # PREPARING SQLALCHEMY QUERYwith engine.connect() as conn: result = conn.execute( db.select([Profile.email, Profile.name, Profile.contact])) # VIEW THE COLUMN NAMESprint(result.keys())",
"e": 27124,
"s": 26449,
"text": null
},
{
"code": null,
"e": 27132,
"s": 27124,
"text": "Output:"
},
{
"code": null,
"e": 27210,
"s": 27132,
"text": "In the above example, we have used SQLAlchemy ORM to create a Profile table. "
},
{
"code": null,
"e": 27297,
"s": 27210,
"text": "Firstly, the engine is configured so that it can be used to perform SQL transactions. "
},
{
"code": null,
"e": 27358,
"s": 27297,
"text": "Then, the Profile table is defined in the form of ORM class."
},
{
"code": null,
"e": 27710,
"s": 27358,
"text": "Using the sqlalchemy engine we are querying the Profile table to select all the records from the table for columns email, name, and contact. The information is stored in the result variable. This variable holds the column names and the records that have been fetched from the Profile table. The datatype of result variable is sqlalchemy.engine.Result."
},
{
"code": null,
"e": 27816,
"s": 27710,
"text": "To access the column names we can use the method keys() on the result. It returns a list of column names."
},
{
"code": null,
"e": 27906,
"s": 27816,
"text": "Since, we queried only three columns, we can view the same columns on the output as well."
},
{
"code": null,
"e": 27953,
"s": 27906,
"text": "This returns the ‘key’ for the Table Metadata."
},
{
"code": null,
"e": 27989,
"s": 27953,
"text": "Syntax: sqlalchemy.schema.Table.key"
},
{
"code": null,
"e": 27996,
"s": 27989,
"text": "Python"
},
{
"code": "import sqlalchemy as dbfrom sqlalchemy.ext.declarative import declarative_base Base = declarative_base() # DEFINE THE ENGINE (CONNECTIO OBJECT)engine = db.create_engine( \"mysql+pymysql://root:password@localhost/Geeks4Geeks\") # CREATE THE TABLE MODEL TO USE IT FOR QUERYINGclass Profile(Base): __tablename__ = 'profile' email = db.Column(db.String(50), primary_key=True) name = db.Column(db.String(100)) contact = db.Column(db.Integer) # PREPARING SQLALCHEMY QUERYwith engine.connect() as conn: result = conn.execute( db.select([Profile.email, Profile.name, Profile.contact])) # VIEW THE COLUMN NAMESprint(result._metadata.keys)",
"e": 28678,
"s": 27996,
"text": null
},
{
"code": null,
"e": 28686,
"s": 28678,
"text": "Output:"
},
{
"code": null,
"e": 28693,
"s": 28686,
"text": "Picked"
},
{
"code": null,
"e": 28715,
"s": 28693,
"text": "Python SQLAlchemy-ORM"
},
{
"code": null,
"e": 28733,
"s": 28715,
"text": "Python-SQLAlchemy"
},
{
"code": null,
"e": 28740,
"s": 28733,
"text": "Python"
},
{
"code": null,
"e": 28838,
"s": 28740,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 28870,
"s": 28838,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 28912,
"s": 28870,
"text": "Check if element exists in list in Python"
},
{
"code": null,
"e": 28954,
"s": 28912,
"text": "How To Convert Python Dictionary To JSON?"
},
{
"code": null,
"e": 28981,
"s": 28954,
"text": "Python Classes and Objects"
},
{
"code": null,
"e": 29037,
"s": 28981,
"text": "How to drop one or multiple columns in Pandas Dataframe"
},
{
"code": null,
"e": 29076,
"s": 29037,
"text": "Python | Get unique values from a list"
},
{
"code": null,
"e": 29098,
"s": 29076,
"text": "Defaultdict in Python"
},
{
"code": null,
"e": 29129,
"s": 29098,
"text": "Python | os.path.join() method"
},
{
"code": null,
"e": 29158,
"s": 29129,
"text": "Create a directory in Python"
}
] |
File Sharing App using Python - GeeksforGeeks
|
03 Sep, 2021
Computer Networks is an important topic and to understand the concepts, practical application of the concepts is needed. In this particular article, we will see how to make a simple file-sharing app using Python. An HTTP Web Server is software that understands URLs (web address) and HTTP (the protocol used to view webpages). Python has several packages which is a collection of modules. And it has several built-in servers. The modules used in this project are:
The HTTPServer is a socketserver, which creates and listens at the HTTP socket.
The socketserver modules simplify the task of writing network servers.
The webbrowser module provides us with a high-level interface to allow and display Web-based documents, simply calling the open() function.
The pyqrcode module is used to generate QR Code in just two lines of code.
OS module helps for interacting with the operating system. Used for opening files, manipulate paths, and read all lines in all the files on the command line.
PyPNG allows PNG image files to be read and written using pure Python
Install third-party modules:
pip install pyqrcode
pip install pypng
Install the dependencies using pip install at the command line.
Importing necessary modules:http.server and socketserver: To host in the browser.pyqrcode: To generate QRcode.png: To convert the QRCode into a png file.OS: To interact with the Operating system.
http.server and socketserver: To host in the browser.
pyqrcode: To generate QRcode.
png: To convert the QRCode into a png file.
OS: To interact with the Operating system.
Assign port and name of the user.
Find Ip address of the PC and convert it to a QR code.
Create the HTTP request.
Display the QR code in browser.
Python3
# import necessary modules # for implementing the HTTP Web serversimport http.server # provides access to the BSD socket interfaceimport socket # a framework for network serversimport socketserver # to display a Web-based documents to usersimport webbrowser # to generate qrcodeimport pyqrcodefrom pyqrcode import QRCode # convert into png formatimport png # to access operating system controlimport os # assigning the appropriate port valuePORT = 8010# this finds the name of the computer useros.environ['USERPROFILE'] # changing the directory to access the files desktop# with the help of os moduledesktop = os.path.join(os.path.join(os.environ['USERPROFILE']), 'OneDrive')os.chdir(desktop) # creating a http requestHandler = http.server.SimpleHTTPRequestHandler# returns, host name of the system under# which Python interpreter is executedhostname = socket.gethostname() # finding the IP address of the PCs = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)s.connect(("8.8.8.8", 80))IP = "http://" + s.getsockname()[0] + ":" + str(PORT)link = IP # converting the IP address into the form of a QRcode# with the help of pyqrcode module # converts the IP address into a Qrcodeurl = pyqrcode.create(link)# saves the Qrcode inform of svgurl.svg("myqr.svg", scale=8)# opens the Qrcode image in the web browserwebbrowser.open('myqr.svg') # Creating the HTTP request and serving the# folder in the PORT 8010,and the pyqrcode is generated # continuous stream of data between client and serverwith socketserver.TCPServer(("", PORT), Handler) as httpd: print("serving at port", PORT) print("Type this in your Browser", IP) print("or Use the QRCode") httpd.serve_forever()
Output:
Open the python file which has the above code on PC.
This will generate a QR-code.
Either Scan the QR-code or type the IP Address shown in the python shell in your mobile browser.
Share the files with ease by scanning the QR-code that’s generated and get access to the files in PC, from the mobile browser.
Demonstration:
TCP Port 8010 use a defined protocol to communicate depending on the application. A protocol is a set of formalized rules that explains how data is communicated over a network. This is secured and is not infected by Virus/Trojan.
The code finds the name of the USERPROFILE through OS module. And changes the directory to access the files on the desktop.
Finds the hostname to serve the file in a particular port for secured sharing.
Then finds the IP address of the system so that we can connect a particular device.
The IP address is converted into the form of QR-code using the module pyqrcode for easy use.
The generated image is hosted in a web browser.
Once the device connected to the same network either scanned QR code or type the IP address can access the files of the system.
sagartomar9927
Python-projects
Technical Scripter 2020
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 ?
Check if element exists in list in Python
How To Convert Python Dictionary To JSON?
How to drop one or multiple columns in Pandas Dataframe
Python Classes and Objects
Python | os.path.join() method
Python | Get unique values from a list
Create a directory in Python
Defaultdict in Python
Python | Pandas dataframe.groupby()
|
[
{
"code": null,
"e": 25561,
"s": 25533,
"text": "\n03 Sep, 2021"
},
{
"code": null,
"e": 26026,
"s": 25561,
"text": "Computer Networks is an important topic and to understand the concepts, practical application of the concepts is needed. In this particular article, we will see how to make a simple file-sharing app using Python. An HTTP Web Server is software that understands URLs (web address) and HTTP (the protocol used to view webpages). Python has several packages which is a collection of modules. And it has several built-in servers. The modules used in this project are:"
},
{
"code": null,
"e": 26106,
"s": 26026,
"text": "The HTTPServer is a socketserver, which creates and listens at the HTTP socket."
},
{
"code": null,
"e": 26177,
"s": 26106,
"text": "The socketserver modules simplify the task of writing network servers."
},
{
"code": null,
"e": 26317,
"s": 26177,
"text": "The webbrowser module provides us with a high-level interface to allow and display Web-based documents, simply calling the open() function."
},
{
"code": null,
"e": 26392,
"s": 26317,
"text": "The pyqrcode module is used to generate QR Code in just two lines of code."
},
{
"code": null,
"e": 26550,
"s": 26392,
"text": "OS module helps for interacting with the operating system. Used for opening files, manipulate paths, and read all lines in all the files on the command line."
},
{
"code": null,
"e": 26620,
"s": 26550,
"text": "PyPNG allows PNG image files to be read and written using pure Python"
},
{
"code": null,
"e": 26649,
"s": 26620,
"text": "Install third-party modules:"
},
{
"code": null,
"e": 26688,
"s": 26649,
"text": "pip install pyqrcode\npip install pypng"
},
{
"code": null,
"e": 26752,
"s": 26688,
"text": "Install the dependencies using pip install at the command line."
},
{
"code": null,
"e": 26948,
"s": 26752,
"text": "Importing necessary modules:http.server and socketserver: To host in the browser.pyqrcode: To generate QRcode.png: To convert the QRCode into a png file.OS: To interact with the Operating system."
},
{
"code": null,
"e": 27002,
"s": 26948,
"text": "http.server and socketserver: To host in the browser."
},
{
"code": null,
"e": 27032,
"s": 27002,
"text": "pyqrcode: To generate QRcode."
},
{
"code": null,
"e": 27076,
"s": 27032,
"text": "png: To convert the QRCode into a png file."
},
{
"code": null,
"e": 27119,
"s": 27076,
"text": "OS: To interact with the Operating system."
},
{
"code": null,
"e": 27153,
"s": 27119,
"text": "Assign port and name of the user."
},
{
"code": null,
"e": 27208,
"s": 27153,
"text": "Find Ip address of the PC and convert it to a QR code."
},
{
"code": null,
"e": 27233,
"s": 27208,
"text": "Create the HTTP request."
},
{
"code": null,
"e": 27265,
"s": 27233,
"text": "Display the QR code in browser."
},
{
"code": null,
"e": 27273,
"s": 27265,
"text": "Python3"
},
{
"code": "# import necessary modules # for implementing the HTTP Web serversimport http.server # provides access to the BSD socket interfaceimport socket # a framework for network serversimport socketserver # to display a Web-based documents to usersimport webbrowser # to generate qrcodeimport pyqrcodefrom pyqrcode import QRCode # convert into png formatimport png # to access operating system controlimport os # assigning the appropriate port valuePORT = 8010# this finds the name of the computer useros.environ['USERPROFILE'] # changing the directory to access the files desktop# with the help of os moduledesktop = os.path.join(os.path.join(os.environ['USERPROFILE']), 'OneDrive')os.chdir(desktop) # creating a http requestHandler = http.server.SimpleHTTPRequestHandler# returns, host name of the system under# which Python interpreter is executedhostname = socket.gethostname() # finding the IP address of the PCs = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)s.connect((\"8.8.8.8\", 80))IP = \"http://\" + s.getsockname()[0] + \":\" + str(PORT)link = IP # converting the IP address into the form of a QRcode# with the help of pyqrcode module # converts the IP address into a Qrcodeurl = pyqrcode.create(link)# saves the Qrcode inform of svgurl.svg(\"myqr.svg\", scale=8)# opens the Qrcode image in the web browserwebbrowser.open('myqr.svg') # Creating the HTTP request and serving the# folder in the PORT 8010,and the pyqrcode is generated # continuous stream of data between client and serverwith socketserver.TCPServer((\"\", PORT), Handler) as httpd: print(\"serving at port\", PORT) print(\"Type this in your Browser\", IP) print(\"or Use the QRCode\") httpd.serve_forever()",
"e": 28978,
"s": 27273,
"text": null
},
{
"code": null,
"e": 28986,
"s": 28978,
"text": "Output:"
},
{
"code": null,
"e": 29039,
"s": 28986,
"text": "Open the python file which has the above code on PC."
},
{
"code": null,
"e": 29069,
"s": 29039,
"text": "This will generate a QR-code."
},
{
"code": null,
"e": 29166,
"s": 29069,
"text": "Either Scan the QR-code or type the IP Address shown in the python shell in your mobile browser."
},
{
"code": null,
"e": 29293,
"s": 29166,
"text": "Share the files with ease by scanning the QR-code that’s generated and get access to the files in PC, from the mobile browser."
},
{
"code": null,
"e": 29308,
"s": 29293,
"text": "Demonstration:"
},
{
"code": null,
"e": 29538,
"s": 29308,
"text": "TCP Port 8010 use a defined protocol to communicate depending on the application. A protocol is a set of formalized rules that explains how data is communicated over a network. This is secured and is not infected by Virus/Trojan."
},
{
"code": null,
"e": 29662,
"s": 29538,
"text": "The code finds the name of the USERPROFILE through OS module. And changes the directory to access the files on the desktop."
},
{
"code": null,
"e": 29741,
"s": 29662,
"text": "Finds the hostname to serve the file in a particular port for secured sharing."
},
{
"code": null,
"e": 29825,
"s": 29741,
"text": "Then finds the IP address of the system so that we can connect a particular device."
},
{
"code": null,
"e": 29918,
"s": 29825,
"text": "The IP address is converted into the form of QR-code using the module pyqrcode for easy use."
},
{
"code": null,
"e": 29966,
"s": 29918,
"text": "The generated image is hosted in a web browser."
},
{
"code": null,
"e": 30094,
"s": 29966,
"text": "Once the device connected to the same network either scanned QR code or type the IP address can access the files of the system."
},
{
"code": null,
"e": 30109,
"s": 30094,
"text": "sagartomar9927"
},
{
"code": null,
"e": 30125,
"s": 30109,
"text": "Python-projects"
},
{
"code": null,
"e": 30149,
"s": 30125,
"text": "Technical Scripter 2020"
},
{
"code": null,
"e": 30156,
"s": 30149,
"text": "Python"
},
{
"code": null,
"e": 30175,
"s": 30156,
"text": "Technical Scripter"
},
{
"code": null,
"e": 30273,
"s": 30175,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 30305,
"s": 30273,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 30347,
"s": 30305,
"text": "Check if element exists in list in Python"
},
{
"code": null,
"e": 30389,
"s": 30347,
"text": "How To Convert Python Dictionary To JSON?"
},
{
"code": null,
"e": 30445,
"s": 30389,
"text": "How to drop one or multiple columns in Pandas Dataframe"
},
{
"code": null,
"e": 30472,
"s": 30445,
"text": "Python Classes and Objects"
},
{
"code": null,
"e": 30503,
"s": 30472,
"text": "Python | os.path.join() method"
},
{
"code": null,
"e": 30542,
"s": 30503,
"text": "Python | Get unique values from a list"
},
{
"code": null,
"e": 30571,
"s": 30542,
"text": "Create a directory in Python"
},
{
"code": null,
"e": 30593,
"s": 30571,
"text": "Defaultdict in Python"
}
] |
Creating Ownable Contracts in Solidity - GeeksforGeeks
|
11 May, 2022
A Smart Contract (or crypto contract) is a computer program that directly and automatically controls the transfer of digital assets between the parties under certain conditions. Once deployed, a smart contract code cannot be changed. It is also publicly visible to everyone. Solidity is a language used for creating smart contracts which is then compiled to a byte code which in turn is deployed on the Ethereum network. Even though, the code is publicly visible, the calling of functions can be restricted using modifiers.Solidity provides some access modifiers by default:
Public- Accessible by anyonePrivate- Accessible by only contracts where they are defined and not by inheriting contracts.Protected- Accessible by only contracts where they are defined and by contracts that inherit them.Internal- Accessible by only other functions of the contract and not by other people or contracts.External- Accessible by only other people or contracts and not by functions.
Public- Accessible by anyone
Private- Accessible by only contracts where they are defined and not by inheriting contracts.
Protected- Accessible by only contracts where they are defined and by contracts that inherit them.
Internal- Accessible by only other functions of the contract and not by other people or contracts.
External- Accessible by only other people or contracts and not by functions.
Need of Ownable Contracts:Some functions are necessary for only configuration purposes or one-time calculations. Such functions if exposed publicly can be used maliciously or mistakenly to exhaust gas. To prevent misuse or reduce gas cost, such functions must be restricted to only selected external addresses (for simplicity, owner). To solve this, ownable contracts can be used.Following is the code for an ownable contract. It can be inherited by other contracts which intend to have ownable modifiers for selected functions.Below is the Solidity program for the above approach:
Solidity
// SPDX-License-Identifier: GPL-3.0pragma solidity >=0.7.0; contract Ownable { // Variable that maintains // owner address address private _owner; // Sets the original owner of // contract when it is deployed constructor() { _owner = msg.sender; } // Publicly exposes who is the // owner of this contract function owner() public view returns(address) { return _owner; } // onlyOwner modifier that validates only // if caller of function is contract owner, // otherwise not modifier onlyOwner() { require(isOwner(), "Function accessible only by the owner !!"); _; } // function for owners to verify their ownership. // Returns true for owners otherwise false function isOwner() public view returns(bool) { return msg.sender == _owner; }} contract OwnableDemo is Ownable { uint sum = 0; uint[] numbers; // Push number to array function addNumber(uint number) public { numbers.push(number); } // Read sum variable function getSum() public view returns(uint) { return sum; } /* Calculate sum by traversing array The onlyOwner modifier used here prevents this function to be called by people other than owner who deployed it */ function calculateSum() onlyOwner public { sum = 0; for(uint i = 0; i < numbers.length; i++) sum += numbers[i]; }}
Output:Adding numbers from any address (owner or not doesn’t matter): The function was called thrice with arguments: 5, 6, and 2 respectively
Attempt to call calculateSum() from a non-owner address (Unsuccessful):
Calling calculateSum() as owner (Successful):
Blockchain
Solidity
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to connect ReactJS with MetaMask ?
Difference between Public and Private blockchain
Blockchain Merkle Trees
Advantages and Disadvantages of Blockchain
Hyperledger Fabric in Blockchain
Solidity - While, Do-While, and For Loop
Dynamic Arrays and its Operations in Solidity
Solidity - Types
Solidity - Variables
Solidity - Error Handling
|
[
{
"code": null,
"e": 25907,
"s": 25879,
"text": "\n11 May, 2022"
},
{
"code": null,
"e": 26482,
"s": 25907,
"text": "A Smart Contract (or crypto contract) is a computer program that directly and automatically controls the transfer of digital assets between the parties under certain conditions. Once deployed, a smart contract code cannot be changed. It is also publicly visible to everyone. Solidity is a language used for creating smart contracts which is then compiled to a byte code which in turn is deployed on the Ethereum network. Even though, the code is publicly visible, the calling of functions can be restricted using modifiers.Solidity provides some access modifiers by default:"
},
{
"code": null,
"e": 26876,
"s": 26482,
"text": "Public- Accessible by anyonePrivate- Accessible by only contracts where they are defined and not by inheriting contracts.Protected- Accessible by only contracts where they are defined and by contracts that inherit them.Internal- Accessible by only other functions of the contract and not by other people or contracts.External- Accessible by only other people or contracts and not by functions."
},
{
"code": null,
"e": 26905,
"s": 26876,
"text": "Public- Accessible by anyone"
},
{
"code": null,
"e": 26999,
"s": 26905,
"text": "Private- Accessible by only contracts where they are defined and not by inheriting contracts."
},
{
"code": null,
"e": 27098,
"s": 26999,
"text": "Protected- Accessible by only contracts where they are defined and by contracts that inherit them."
},
{
"code": null,
"e": 27197,
"s": 27098,
"text": "Internal- Accessible by only other functions of the contract and not by other people or contracts."
},
{
"code": null,
"e": 27274,
"s": 27197,
"text": "External- Accessible by only other people or contracts and not by functions."
},
{
"code": null,
"e": 27856,
"s": 27274,
"text": "Need of Ownable Contracts:Some functions are necessary for only configuration purposes or one-time calculations. Such functions if exposed publicly can be used maliciously or mistakenly to exhaust gas. To prevent misuse or reduce gas cost, such functions must be restricted to only selected external addresses (for simplicity, owner). To solve this, ownable contracts can be used.Following is the code for an ownable contract. It can be inherited by other contracts which intend to have ownable modifiers for selected functions.Below is the Solidity program for the above approach:"
},
{
"code": null,
"e": 27865,
"s": 27856,
"text": "Solidity"
},
{
"code": "// SPDX-License-Identifier: GPL-3.0pragma solidity >=0.7.0; contract Ownable { // Variable that maintains // owner address address private _owner; // Sets the original owner of // contract when it is deployed constructor() { _owner = msg.sender; } // Publicly exposes who is the // owner of this contract function owner() public view returns(address) { return _owner; } // onlyOwner modifier that validates only // if caller of function is contract owner, // otherwise not modifier onlyOwner() { require(isOwner(), \"Function accessible only by the owner !!\"); _; } // function for owners to verify their ownership. // Returns true for owners otherwise false function isOwner() public view returns(bool) { return msg.sender == _owner; }} contract OwnableDemo is Ownable { uint sum = 0; uint[] numbers; // Push number to array function addNumber(uint number) public { numbers.push(number); } // Read sum variable function getSum() public view returns(uint) { return sum; } /* Calculate sum by traversing array The onlyOwner modifier used here prevents this function to be called by people other than owner who deployed it */ function calculateSum() onlyOwner public { sum = 0; for(uint i = 0; i < numbers.length; i++) sum += numbers[i]; }}",
"e": 29307,
"s": 27865,
"text": null
},
{
"code": null,
"e": 29449,
"s": 29307,
"text": "Output:Adding numbers from any address (owner or not doesn’t matter): The function was called thrice with arguments: 5, 6, and 2 respectively"
},
{
"code": null,
"e": 29521,
"s": 29449,
"text": "Attempt to call calculateSum() from a non-owner address (Unsuccessful):"
},
{
"code": null,
"e": 29567,
"s": 29521,
"text": "Calling calculateSum() as owner (Successful):"
},
{
"code": null,
"e": 29578,
"s": 29567,
"text": "Blockchain"
},
{
"code": null,
"e": 29587,
"s": 29578,
"text": "Solidity"
},
{
"code": null,
"e": 29685,
"s": 29587,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 29724,
"s": 29685,
"text": "How to connect ReactJS with MetaMask ?"
},
{
"code": null,
"e": 29773,
"s": 29724,
"text": "Difference between Public and Private blockchain"
},
{
"code": null,
"e": 29797,
"s": 29773,
"text": "Blockchain Merkle Trees"
},
{
"code": null,
"e": 29840,
"s": 29797,
"text": "Advantages and Disadvantages of Blockchain"
},
{
"code": null,
"e": 29873,
"s": 29840,
"text": "Hyperledger Fabric in Blockchain"
},
{
"code": null,
"e": 29914,
"s": 29873,
"text": "Solidity - While, Do-While, and For Loop"
},
{
"code": null,
"e": 29960,
"s": 29914,
"text": "Dynamic Arrays and its Operations in Solidity"
},
{
"code": null,
"e": 29977,
"s": 29960,
"text": "Solidity - Types"
},
{
"code": null,
"e": 29998,
"s": 29977,
"text": "Solidity - Variables"
}
] |
Face Comparison Using Face++ and Python - GeeksforGeeks
|
01 Oct, 2021
Prerequisites: Python Programming Language
Python is a high-level general-purpose language. It is used for multiple purposes like AI, Web Development, Web Scraping, etc. One such use of Python can be Face Comparison. A module name python-facepp can be used for doing the same. This module is for communicating with Face++ facial recognition service.
python-facepp – To install this module type the below command in the terminal.pip install python-facepp
pip install python-facepp
emoji – To install this module type the below command in the terminal.pip install emoji
pip install emoji
This app compares two photographs of the same person or two different persons against his/her face features like face landmarks, beauty score, face emotion, etc. If both photographs are matching with each other, the app result is “Both photographs are of same person ” otherwise app result is “Both photographs are of two different persons”.
This app is used mainly for a face verification process like “to deliver some confidentialdocument to you, courier boy first verify your face and then deliver a courier.”
Note: A facepp API is allowed only to compare image URL links of two photographs.
Convert Image to URL using postimages.org.
In this website, choose your photograph from your local drive by click on the “choose images” button and then this website will create different URL links after processing your photograph.(See below images)
We will be using two pairs of photos for comparison.
Pair one:
Pair two:
Below is the implementation.
# Python program for face# comparison from __future__ import print_function, unicode_literalsfrom facepplib import FacePP, exceptionsimport emoji # define global variablesface_detection = ""faceset_initialize = ""face_search = ""face_landmarks = ""dense_facial_landmarks = ""face_attributes = ""beauty_score_and_emotion_recognition = "" # define face comparing functiondef face_comparing(app, Image1, Image2): print() print('-'*30) print('Comparing Photographs......') print('-'*30) cmp_ = app.compare.get(image_url1 = Image1, image_url2 = Image2) print('Photo1', '=', cmp_.image1) print('Photo2', '=', cmp_.image2) # Comparing Photos if cmp_.confidence > 70: print('Both photographs are of same person......') else: print('Both photographs are of two different persons......') # Driver Code if __name__ == '__main__': # api details api_key ='xQLsTmMyqp1L2MIt7M3l0h-cQiy0Dwhl' api_secret ='TyBSGw8NBEP9Tbhv_JbQM18mIlorY6-D' try: # create a logo of app by using iteration, # unicode and emoji module------------- for i in range(1,6): for j in range(6,-i): print(" " , end = " ") for j in range(1,i): print('\U0001F600', end =" ") for j in range(i,0,-1): print('\U0001F6A3', end= " ") for j in range(i,1,-2): print('\U0001F62B', end= " ") print() print() #print name of the app-------- print("\t\t\t"+"Photo Comparing App\n") for i in range(1,6): for j in range(6,-i): print(" " , end = " ") for j in range(1,i): print(emoji.emojize(":princess:"), end =" ") for j in range(i,0,-1): print('\U0001F610', end= " ") for j in range(i,1,-2): print(emoji.emojize(":baby:"), end= " ") print() # call api app_ = FacePP(api_key = api_key, api_secret = api_secret) funcs = [ face_detection, face_comparing_localphoto, face_comparing_websitephoto, faceset_initialize, face_search, face_landmarks, dense_facial_landmarks, face_attributes, beauty_score_and_emotion_recognition ] # Pair 1 image1 = 'Image 1 link' image2 = 'Image 2 link' face_comparing(app_, image1, image2) # Pair2 image1 = 'Image 1 link' image2 = 'Image 2 link' face_comparing(app_, image1, image2) except exceptions.BaseFacePPError as e: print('Error:', e)
Output:
ruhelaa48
kashishsoda
python-modules
Python-projects
python-utility
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Install PIP on Windows ?
Check if element exists in list in Python
How To Convert Python Dictionary To JSON?
Python Classes and Objects
How to drop one or multiple columns in Pandas Dataframe
Defaultdict in Python
Python | Get unique values from a list
Python | os.path.join() method
Create a directory in Python
Python | Pandas dataframe.groupby()
|
[
{
"code": null,
"e": 25537,
"s": 25509,
"text": "\n01 Oct, 2021"
},
{
"code": null,
"e": 25580,
"s": 25537,
"text": "Prerequisites: Python Programming Language"
},
{
"code": null,
"e": 25887,
"s": 25580,
"text": "Python is a high-level general-purpose language. It is used for multiple purposes like AI, Web Development, Web Scraping, etc. One such use of Python can be Face Comparison. A module name python-facepp can be used for doing the same. This module is for communicating with Face++ facial recognition service."
},
{
"code": null,
"e": 25991,
"s": 25887,
"text": "python-facepp – To install this module type the below command in the terminal.pip install python-facepp"
},
{
"code": null,
"e": 26017,
"s": 25991,
"text": "pip install python-facepp"
},
{
"code": null,
"e": 26105,
"s": 26017,
"text": "emoji – To install this module type the below command in the terminal.pip install emoji"
},
{
"code": null,
"e": 26123,
"s": 26105,
"text": "pip install emoji"
},
{
"code": null,
"e": 26465,
"s": 26123,
"text": "This app compares two photographs of the same person or two different persons against his/her face features like face landmarks, beauty score, face emotion, etc. If both photographs are matching with each other, the app result is “Both photographs are of same person ” otherwise app result is “Both photographs are of two different persons”."
},
{
"code": null,
"e": 26636,
"s": 26465,
"text": "This app is used mainly for a face verification process like “to deliver some confidentialdocument to you, courier boy first verify your face and then deliver a courier.”"
},
{
"code": null,
"e": 26718,
"s": 26636,
"text": "Note: A facepp API is allowed only to compare image URL links of two photographs."
},
{
"code": null,
"e": 26761,
"s": 26718,
"text": "Convert Image to URL using postimages.org."
},
{
"code": null,
"e": 26968,
"s": 26761,
"text": "In this website, choose your photograph from your local drive by click on the “choose images” button and then this website will create different URL links after processing your photograph.(See below images)"
},
{
"code": null,
"e": 27021,
"s": 26968,
"text": "We will be using two pairs of photos for comparison."
},
{
"code": null,
"e": 27031,
"s": 27021,
"text": "Pair one:"
},
{
"code": null,
"e": 27054,
"s": 27044,
"text": "Pair two:"
},
{
"code": null,
"e": 27093,
"s": 27064,
"text": "Below is the implementation."
},
{
"code": "# Python program for face# comparison from __future__ import print_function, unicode_literalsfrom facepplib import FacePP, exceptionsimport emoji # define global variablesface_detection = \"\"faceset_initialize = \"\"face_search = \"\"face_landmarks = \"\"dense_facial_landmarks = \"\"face_attributes = \"\"beauty_score_and_emotion_recognition = \"\" # define face comparing functiondef face_comparing(app, Image1, Image2): print() print('-'*30) print('Comparing Photographs......') print('-'*30) cmp_ = app.compare.get(image_url1 = Image1, image_url2 = Image2) print('Photo1', '=', cmp_.image1) print('Photo2', '=', cmp_.image2) # Comparing Photos if cmp_.confidence > 70: print('Both photographs are of same person......') else: print('Both photographs are of two different persons......') # Driver Code if __name__ == '__main__': # api details api_key ='xQLsTmMyqp1L2MIt7M3l0h-cQiy0Dwhl' api_secret ='TyBSGw8NBEP9Tbhv_JbQM18mIlorY6-D' try: # create a logo of app by using iteration, # unicode and emoji module------------- for i in range(1,6): for j in range(6,-i): print(\" \" , end = \" \") for j in range(1,i): print('\\U0001F600', end =\" \") for j in range(i,0,-1): print('\\U0001F6A3', end= \" \") for j in range(i,1,-2): print('\\U0001F62B', end= \" \") print() print() #print name of the app-------- print(\"\\t\\t\\t\"+\"Photo Comparing App\\n\") for i in range(1,6): for j in range(6,-i): print(\" \" , end = \" \") for j in range(1,i): print(emoji.emojize(\":princess:\"), end =\" \") for j in range(i,0,-1): print('\\U0001F610', end= \" \") for j in range(i,1,-2): print(emoji.emojize(\":baby:\"), end= \" \") print() # call api app_ = FacePP(api_key = api_key, api_secret = api_secret) funcs = [ face_detection, face_comparing_localphoto, face_comparing_websitephoto, faceset_initialize, face_search, face_landmarks, dense_facial_landmarks, face_attributes, beauty_score_and_emotion_recognition ] # Pair 1 image1 = 'Image 1 link' image2 = 'Image 2 link' face_comparing(app_, image1, image2) # Pair2 image1 = 'Image 1 link' image2 = 'Image 2 link' face_comparing(app_, image1, image2) except exceptions.BaseFacePPError as e: print('Error:', e)",
"e": 30062,
"s": 27093,
"text": null
},
{
"code": null,
"e": 30070,
"s": 30062,
"text": "Output:"
},
{
"code": null,
"e": 30080,
"s": 30070,
"text": "ruhelaa48"
},
{
"code": null,
"e": 30092,
"s": 30080,
"text": "kashishsoda"
},
{
"code": null,
"e": 30107,
"s": 30092,
"text": "python-modules"
},
{
"code": null,
"e": 30123,
"s": 30107,
"text": "Python-projects"
},
{
"code": null,
"e": 30138,
"s": 30123,
"text": "python-utility"
},
{
"code": null,
"e": 30145,
"s": 30138,
"text": "Python"
},
{
"code": null,
"e": 30243,
"s": 30145,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 30275,
"s": 30243,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 30317,
"s": 30275,
"text": "Check if element exists in list in Python"
},
{
"code": null,
"e": 30359,
"s": 30317,
"text": "How To Convert Python Dictionary To JSON?"
},
{
"code": null,
"e": 30386,
"s": 30359,
"text": "Python Classes and Objects"
},
{
"code": null,
"e": 30442,
"s": 30386,
"text": "How to drop one or multiple columns in Pandas Dataframe"
},
{
"code": null,
"e": 30464,
"s": 30442,
"text": "Defaultdict in Python"
},
{
"code": null,
"e": 30503,
"s": 30464,
"text": "Python | Get unique values from a list"
},
{
"code": null,
"e": 30534,
"s": 30503,
"text": "Python | os.path.join() method"
},
{
"code": null,
"e": 30563,
"s": 30534,
"text": "Create a directory in Python"
}
] |
Locale toLanguageTag() Method in Java with Examples - GeeksforGeeks
|
01 May, 2019
The toLanguageTag() method of Locale class in Java is used to return a well-formed IETF BCP 47 language tag representing this locale object. Now there can be few complications when a language, country or variant does not satisfy the above-mentioned tag which is handled well by this method:
If the mentioned language does not satisfy the tag, then it will be emitted as Undetermined or “und”.
If the mentioned country does not satisfy the tag, it will be omitted.
If the same occurs with the Variant, then each sub-segment is emitted as a subtag.
Syntax:
public String toLanguageTag()
Parameters: This method does not take any parameters.
Return Value: This method returns IETF BCP 47 language tag representation of this locale.
Below programs illustrate the working of toLanguageTag() method:Program 1:
// Java code to illustrate// toLanguageTag() method import java.util.*; public class Locale_Demo { public static void main(String[] args) { // Creating a new locale Locale first_locale = new Locale("Germany"); // Displaying first locale System.out.println("Locale: " + first_locale); // Displaying the LanguageTag System.out.println("The LanguageTag: " + first_locale.toLanguageTag()); }}
Locale: germany
The LanguageTag: germany
Program 2:
// Java code to illustrate// toLanguageTag() method import java.util.*; public class Locale_Demo { public static void main(String[] args) { // Creating a new locale Locale first_locale = new Locale("en", "USA"); // Displaying first locale System.out.println("Locale: " + first_locale); // Displaying the LanguageTag System.out.println("The LanguageTag: " + first_locale.toLanguageTag()); }}
Locale: en_USA
The LanguageTag: en
Reference: https://docs.oracle.com/javase/7/docs/api/java/util/Locale.html#toLanguageTag()
Java - util package
Java-Functions
Java-Locale
Java
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Stream In Java
Constructors in Java
Exceptions in Java
Functional Interfaces in Java
Different ways of Reading a text file in Java
Generics in Java
Introduction to Java
Comparator Interface in Java with Examples
Internal Working of HashMap in Java
Strings in Java
|
[
{
"code": null,
"e": 25225,
"s": 25197,
"text": "\n01 May, 2019"
},
{
"code": null,
"e": 25516,
"s": 25225,
"text": "The toLanguageTag() method of Locale class in Java is used to return a well-formed IETF BCP 47 language tag representing this locale object. Now there can be few complications when a language, country or variant does not satisfy the above-mentioned tag which is handled well by this method:"
},
{
"code": null,
"e": 25618,
"s": 25516,
"text": "If the mentioned language does not satisfy the tag, then it will be emitted as Undetermined or “und”."
},
{
"code": null,
"e": 25689,
"s": 25618,
"text": "If the mentioned country does not satisfy the tag, it will be omitted."
},
{
"code": null,
"e": 25772,
"s": 25689,
"text": "If the same occurs with the Variant, then each sub-segment is emitted as a subtag."
},
{
"code": null,
"e": 25780,
"s": 25772,
"text": "Syntax:"
},
{
"code": null,
"e": 25810,
"s": 25780,
"text": "public String toLanguageTag()"
},
{
"code": null,
"e": 25864,
"s": 25810,
"text": "Parameters: This method does not take any parameters."
},
{
"code": null,
"e": 25954,
"s": 25864,
"text": "Return Value: This method returns IETF BCP 47 language tag representation of this locale."
},
{
"code": null,
"e": 26029,
"s": 25954,
"text": "Below programs illustrate the working of toLanguageTag() method:Program 1:"
},
{
"code": "// Java code to illustrate// toLanguageTag() method import java.util.*; public class Locale_Demo { public static void main(String[] args) { // Creating a new locale Locale first_locale = new Locale(\"Germany\"); // Displaying first locale System.out.println(\"Locale: \" + first_locale); // Displaying the LanguageTag System.out.println(\"The LanguageTag: \" + first_locale.toLanguageTag()); }}",
"e": 26540,
"s": 26029,
"text": null
},
{
"code": null,
"e": 26582,
"s": 26540,
"text": "Locale: germany\nThe LanguageTag: germany\n"
},
{
"code": null,
"e": 26593,
"s": 26582,
"text": "Program 2:"
},
{
"code": "// Java code to illustrate// toLanguageTag() method import java.util.*; public class Locale_Demo { public static void main(String[] args) { // Creating a new locale Locale first_locale = new Locale(\"en\", \"USA\"); // Displaying first locale System.out.println(\"Locale: \" + first_locale); // Displaying the LanguageTag System.out.println(\"The LanguageTag: \" + first_locale.toLanguageTag()); }}",
"e": 27106,
"s": 26593,
"text": null
},
{
"code": null,
"e": 27142,
"s": 27106,
"text": "Locale: en_USA\nThe LanguageTag: en\n"
},
{
"code": null,
"e": 27233,
"s": 27142,
"text": "Reference: https://docs.oracle.com/javase/7/docs/api/java/util/Locale.html#toLanguageTag()"
},
{
"code": null,
"e": 27253,
"s": 27233,
"text": "Java - util package"
},
{
"code": null,
"e": 27268,
"s": 27253,
"text": "Java-Functions"
},
{
"code": null,
"e": 27280,
"s": 27268,
"text": "Java-Locale"
},
{
"code": null,
"e": 27285,
"s": 27280,
"text": "Java"
},
{
"code": null,
"e": 27290,
"s": 27285,
"text": "Java"
},
{
"code": null,
"e": 27388,
"s": 27290,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 27403,
"s": 27388,
"text": "Stream In Java"
},
{
"code": null,
"e": 27424,
"s": 27403,
"text": "Constructors in Java"
},
{
"code": null,
"e": 27443,
"s": 27424,
"text": "Exceptions in Java"
},
{
"code": null,
"e": 27473,
"s": 27443,
"text": "Functional Interfaces in Java"
},
{
"code": null,
"e": 27519,
"s": 27473,
"text": "Different ways of Reading a text file in Java"
},
{
"code": null,
"e": 27536,
"s": 27519,
"text": "Generics in Java"
},
{
"code": null,
"e": 27557,
"s": 27536,
"text": "Introduction to Java"
},
{
"code": null,
"e": 27600,
"s": 27557,
"text": "Comparator Interface in Java with Examples"
},
{
"code": null,
"e": 27636,
"s": 27600,
"text": "Internal Working of HashMap in Java"
}
] |
STL Ropes in C++ - GeeksforGeeks
|
13 Dec, 2021
Ropes are scalable string implementation. They are designed for efficient operation that involves the string as a whole. Operations such as assignment, concatenation, and sub-string take time that is nearly independent of the length of the string.
A rope is a binary tree where each leaf (end node) holds a string and a length (also known as a “weight”), and each node further up the tree holds the sum of the lengths of all the leaves in its left subtree. A node with two children thus divides the whole string into two parts: the left sub-tree stores the first part of the string, the right subtree stores the second part of the string, and a node’s weight is the length of the first part.
For rope operations, the strings stored in nodes are assumed to be constant immutable objects in the typical non-destructive case, allowing for some copy-on-write behavior. Leaf nodes are usually implemented as basic fixed-length strings with a reference count attached for deallocation when no longer needed, although other garbage collection methods can be used as well.
Note: The rope class and rope header are SGI extensions; they are not part of the C++ standard library.
Declaration:Ropes are defined in the same way as vectors as “vector<int>”. But for character ropes, we can use crope as “rope<char>”.
Below is the program for the same:
Program 1:
C++
// C++ program to illustrate the use// of ropes using Rope header file#include <ext/rope>#include <iostream> // SGI extensionusing namespace __gnu_cxx; using namespace std; // Driver Codeint main(){ // rope<char> r = "abcdef" crope r = "abcdef"; cout << r << "\n"; return 0;}
abcdef
Operations allowed on Rope:
push_back(): This function is used to input a character at the end of the rope. Time Complexity: O(log N).
pop_back(): Introduced from C++11(for strings), this function is used to delete the last character from the rope. Time Complexity: O(log N).
insert(int x, crope r1): Inserts the contents of r1 before the xth element. Time Complexity: For Best Case: O(log N) and For Worst Case: O(N).
erase(int x, int l): Erases l elements, starting with the xth element. Time Complexity: O(log N).
substr(int x, int l): Returns a new rope whose elements are the l characters starting at the position x. Time Complexity: O(log N).
replace(int x, int l, crope r1): Replaces the l elements beginning with the xth element with the elements in r1. Time Complexity: O(log N).
concatenate(+): concatenate two ropes using the ‘+’ symbol. Time Complexity: O(1).
Below is the program for the same:
Program 2:
C++
// C++ program to illustrate the use// of ropes using Rope header file#include <ext/rope>#include <iostream> // SGI extensionusing namespace __gnu_cxx;using namespace std; // Driver Codeint main(){ // rope<char> r = "abcdef" crope r = "geeksforgeeks"; cout << "Initial rope: " << r << endl; // 'g' is added at the // end of the rope r.push_back('g'); r.push_back('f'); r.push_back('g'); cout << "Rope after pushing f: " << r << endl; int pos = 2; // gfg will be inserted // before position 2 r.insert(pos - 1, "gfg"); cout << "Rope after inserting " << "gfg at position 2: " << r << endl; // gfg will be deleted r.erase(pos - 1, 3); cout << "Rope after removing gfg" << " inserted just before: " << r << endl; // Replace "ee" with "00" r.replace(pos - 1, 2, "00"); cout << "Rope after replacing " << "characters: " << r << endl; // Slice the rope crope r1 = r.substr(pos - 1, 2); cout << "Subrope at position 2: " << r << endl; // Removes the last element r.pop_back(); r.pop_back(); r.pop_back(); cout << "Final rope after poping" << " out 3 elements: " << r; return 0;}
Initial rope: geeksforgeeks
Rope after pushing f: geeksforgeeksgfg
Rope after inserting gfg at position 2: ggfgeeksforgeeksgfg
Rope after removing gfg inserted just before: geeksforgeeksgfg
Rope after replacing characters: g00ksforgeeksgfg
Subrope at position 2: g00ksforgeeksgfg
Final rope after poping out 3 elements: g00ksforgeeks
Capacity Functions:
size(): Returns the length of the rope.
max_size(): Size of longest rope guaranteed to be representable.
Below is the program for the same:
Program 3:
C++
// C++ program to illustrate the use// of ropes using Rope header file#include <ext/rope>#include <iostream> // SGI extensionusing namespace __gnu_cxx;using namespace std; // Driver Codeint main(){ // rope<char> r = "abcdef" crope r = "abcdef"; cout << r.size() << endl; cout << r.max_size() << endl; return 0;}
6
1836311902
Iterators:
mutable_begin(): Returns an iterator pointing to the beginning of the rope.
mutable_end(): Returns an iterator pointing to the end of the rope.
Below is the program for the same:
Program 4:
C++
// C++ program to illustrate the use// of ropes using Rope header file#include <ext/rope>#include <iostream> // SGI extensionusing namespace __gnu_cxx;using namespace std; // Driver Codeint main(){ // rope<char> r = "abcdef" crope r = "abcdef"; rope<char>::iterator it; for (it = r.mutable_begin(); it != r.mutable_end(); it++) { // Print the value cout << char((*it) + 2) << ""; } return 0;}
cdefgh
anikaseth98
anikakapoor
cpp-string
cpp-strings
cpp-strings-library
Advanced Data Structure
Data Structures
Strings
cpp-strings
Data Structures
Strings
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)
Interval Tree
SDE SHEET - A Complete Guide for SDE Preparation
Top 50 Array Coding Problems for Interviews
DSA Sheet by Love Babbar
Doubly Linked List | Set 1 (Introduction and Insertion)
Introduction to Algorithms
|
[
{
"code": null,
"e": 25733,
"s": 25705,
"text": "\n13 Dec, 2021"
},
{
"code": null,
"e": 25981,
"s": 25733,
"text": "Ropes are scalable string implementation. They are designed for efficient operation that involves the string as a whole. Operations such as assignment, concatenation, and sub-string take time that is nearly independent of the length of the string."
},
{
"code": null,
"e": 26425,
"s": 25981,
"text": "A rope is a binary tree where each leaf (end node) holds a string and a length (also known as a “weight”), and each node further up the tree holds the sum of the lengths of all the leaves in its left subtree. A node with two children thus divides the whole string into two parts: the left sub-tree stores the first part of the string, the right subtree stores the second part of the string, and a node’s weight is the length of the first part."
},
{
"code": null,
"e": 26798,
"s": 26425,
"text": "For rope operations, the strings stored in nodes are assumed to be constant immutable objects in the typical non-destructive case, allowing for some copy-on-write behavior. Leaf nodes are usually implemented as basic fixed-length strings with a reference count attached for deallocation when no longer needed, although other garbage collection methods can be used as well."
},
{
"code": null,
"e": 26902,
"s": 26798,
"text": "Note: The rope class and rope header are SGI extensions; they are not part of the C++ standard library."
},
{
"code": null,
"e": 27036,
"s": 26902,
"text": "Declaration:Ropes are defined in the same way as vectors as “vector<int>”. But for character ropes, we can use crope as “rope<char>”."
},
{
"code": null,
"e": 27071,
"s": 27036,
"text": "Below is the program for the same:"
},
{
"code": null,
"e": 27082,
"s": 27071,
"text": "Program 1:"
},
{
"code": null,
"e": 27086,
"s": 27082,
"text": "C++"
},
{
"code": "// C++ program to illustrate the use// of ropes using Rope header file#include <ext/rope>#include <iostream> // SGI extensionusing namespace __gnu_cxx; using namespace std; // Driver Codeint main(){ // rope<char> r = \"abcdef\" crope r = \"abcdef\"; cout << r << \"\\n\"; return 0;}",
"e": 27376,
"s": 27086,
"text": null
},
{
"code": null,
"e": 27386,
"s": 27379,
"text": "abcdef"
},
{
"code": null,
"e": 27418,
"s": 27390,
"text": "Operations allowed on Rope:"
},
{
"code": null,
"e": 27527,
"s": 27420,
"text": "push_back(): This function is used to input a character at the end of the rope. Time Complexity: O(log N)."
},
{
"code": null,
"e": 27668,
"s": 27527,
"text": "pop_back(): Introduced from C++11(for strings), this function is used to delete the last character from the rope. Time Complexity: O(log N)."
},
{
"code": null,
"e": 27811,
"s": 27668,
"text": "insert(int x, crope r1): Inserts the contents of r1 before the xth element. Time Complexity: For Best Case: O(log N) and For Worst Case: O(N)."
},
{
"code": null,
"e": 27909,
"s": 27811,
"text": "erase(int x, int l): Erases l elements, starting with the xth element. Time Complexity: O(log N)."
},
{
"code": null,
"e": 28041,
"s": 27909,
"text": "substr(int x, int l): Returns a new rope whose elements are the l characters starting at the position x. Time Complexity: O(log N)."
},
{
"code": null,
"e": 28181,
"s": 28041,
"text": "replace(int x, int l, crope r1): Replaces the l elements beginning with the xth element with the elements in r1. Time Complexity: O(log N)."
},
{
"code": null,
"e": 28264,
"s": 28181,
"text": "concatenate(+): concatenate two ropes using the ‘+’ symbol. Time Complexity: O(1)."
},
{
"code": null,
"e": 28301,
"s": 28266,
"text": "Below is the program for the same:"
},
{
"code": null,
"e": 28314,
"s": 28303,
"text": "Program 2:"
},
{
"code": null,
"e": 28320,
"s": 28316,
"text": "C++"
},
{
"code": "// C++ program to illustrate the use// of ropes using Rope header file#include <ext/rope>#include <iostream> // SGI extensionusing namespace __gnu_cxx;using namespace std; // Driver Codeint main(){ // rope<char> r = \"abcdef\" crope r = \"geeksforgeeks\"; cout << \"Initial rope: \" << r << endl; // 'g' is added at the // end of the rope r.push_back('g'); r.push_back('f'); r.push_back('g'); cout << \"Rope after pushing f: \" << r << endl; int pos = 2; // gfg will be inserted // before position 2 r.insert(pos - 1, \"gfg\"); cout << \"Rope after inserting \" << \"gfg at position 2: \" << r << endl; // gfg will be deleted r.erase(pos - 1, 3); cout << \"Rope after removing gfg\" << \" inserted just before: \" << r << endl; // Replace \"ee\" with \"00\" r.replace(pos - 1, 2, \"00\"); cout << \"Rope after replacing \" << \"characters: \" << r << endl; // Slice the rope crope r1 = r.substr(pos - 1, 2); cout << \"Subrope at position 2: \" << r << endl; // Removes the last element r.pop_back(); r.pop_back(); r.pop_back(); cout << \"Final rope after poping\" << \" out 3 elements: \" << r; return 0;}",
"e": 29574,
"s": 28320,
"text": null
},
{
"code": null,
"e": 29908,
"s": 29574,
"text": "Initial rope: geeksforgeeks\nRope after pushing f: geeksforgeeksgfg\nRope after inserting gfg at position 2: ggfgeeksforgeeksgfg\nRope after removing gfg inserted just before: geeksforgeeksgfg\nRope after replacing characters: g00ksforgeeksgfg\nSubrope at position 2: g00ksforgeeksgfg\nFinal rope after poping out 3 elements: g00ksforgeeks"
},
{
"code": null,
"e": 29933,
"s": 29913,
"text": "Capacity Functions:"
},
{
"code": null,
"e": 29975,
"s": 29935,
"text": "size(): Returns the length of the rope."
},
{
"code": null,
"e": 30040,
"s": 29975,
"text": "max_size(): Size of longest rope guaranteed to be representable."
},
{
"code": null,
"e": 30077,
"s": 30042,
"text": "Below is the program for the same:"
},
{
"code": null,
"e": 30090,
"s": 30079,
"text": "Program 3:"
},
{
"code": null,
"e": 30096,
"s": 30092,
"text": "C++"
},
{
"code": "// C++ program to illustrate the use// of ropes using Rope header file#include <ext/rope>#include <iostream> // SGI extensionusing namespace __gnu_cxx;using namespace std; // Driver Codeint main(){ // rope<char> r = \"abcdef\" crope r = \"abcdef\"; cout << r.size() << endl; cout << r.max_size() << endl; return 0;}",
"e": 30424,
"s": 30096,
"text": null
},
{
"code": null,
"e": 30440,
"s": 30427,
"text": "6\n1836311902"
},
{
"code": null,
"e": 30455,
"s": 30444,
"text": "Iterators:"
},
{
"code": null,
"e": 30533,
"s": 30457,
"text": "mutable_begin(): Returns an iterator pointing to the beginning of the rope."
},
{
"code": null,
"e": 30601,
"s": 30533,
"text": "mutable_end(): Returns an iterator pointing to the end of the rope."
},
{
"code": null,
"e": 30638,
"s": 30603,
"text": "Below is the program for the same:"
},
{
"code": null,
"e": 30651,
"s": 30640,
"text": "Program 4:"
},
{
"code": null,
"e": 30657,
"s": 30653,
"text": "C++"
},
{
"code": "// C++ program to illustrate the use// of ropes using Rope header file#include <ext/rope>#include <iostream> // SGI extensionusing namespace __gnu_cxx;using namespace std; // Driver Codeint main(){ // rope<char> r = \"abcdef\" crope r = \"abcdef\"; rope<char>::iterator it; for (it = r.mutable_begin(); it != r.mutable_end(); it++) { // Print the value cout << char((*it) + 2) << \"\"; } return 0;}",
"e": 31105,
"s": 30657,
"text": null
},
{
"code": null,
"e": 31115,
"s": 31108,
"text": "cdefgh"
},
{
"code": null,
"e": 31131,
"s": 31119,
"text": "anikaseth98"
},
{
"code": null,
"e": 31143,
"s": 31131,
"text": "anikakapoor"
},
{
"code": null,
"e": 31154,
"s": 31143,
"text": "cpp-string"
},
{
"code": null,
"e": 31166,
"s": 31154,
"text": "cpp-strings"
},
{
"code": null,
"e": 31186,
"s": 31166,
"text": "cpp-strings-library"
},
{
"code": null,
"e": 31210,
"s": 31186,
"text": "Advanced Data Structure"
},
{
"code": null,
"e": 31226,
"s": 31210,
"text": "Data Structures"
},
{
"code": null,
"e": 31234,
"s": 31226,
"text": "Strings"
},
{
"code": null,
"e": 31246,
"s": 31234,
"text": "cpp-strings"
},
{
"code": null,
"e": 31262,
"s": 31246,
"text": "Data Structures"
},
{
"code": null,
"e": 31270,
"s": 31262,
"text": "Strings"
},
{
"code": null,
"e": 31368,
"s": 31270,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 31397,
"s": 31368,
"text": "Ordered Set and GNU C++ PBDS"
},
{
"code": null,
"e": 31439,
"s": 31397,
"text": "2-3 Trees | (Search, Insert and Deletion)"
},
{
"code": null,
"e": 31485,
"s": 31439,
"text": "Extendible Hashing (Dynamic approach to DBMS)"
},
{
"code": null,
"e": 31521,
"s": 31485,
"text": "Suffix Array | Set 1 (Introduction)"
},
{
"code": null,
"e": 31535,
"s": 31521,
"text": "Interval Tree"
},
{
"code": null,
"e": 31584,
"s": 31535,
"text": "SDE SHEET - A Complete Guide for SDE Preparation"
},
{
"code": null,
"e": 31628,
"s": 31584,
"text": "Top 50 Array Coding Problems for Interviews"
},
{
"code": null,
"e": 31653,
"s": 31628,
"text": "DSA Sheet by Love Babbar"
},
{
"code": null,
"e": 31709,
"s": 31653,
"text": "Doubly Linked List | Set 1 (Introduction and Insertion)"
}
] |
Multivariate Linear Regression in Python Step by Step | by Rashida Nasrin Sucky | Towards Data Science
|
Linear regression is probably the most simple machine learning algorithm. It is very good for starters because it uses simple formulas. So, it is good for learning machine-learning concepts. In this article, I will try to explain the multivariate linear regression step by step.
Linear regression uses the simple formula that we all learned in school:
Y = C + AX
Just as a reminder, Y is the output or dependent variable, X is the input or the independent variable, A is the slope, and C is the intercept.
For the linear regression, we follow these notations for the same formula:
If we have multiple independent variables, the formula for linear regression will look like:
Here, ‘h’ is called the hypothesis. This is the predicted output variable. Theta0 is the bias term and all the other theta values are coefficients. They are initiated randomly in the beginning, then optimized with the algorithm so that this formula can predict the dependent variable closely.
When theta values are initiated in the beginning, the formula is not trained to predict the dependent variable. The hypothesis is far away from the original output variable ‘Y’. This is the formula to estimate the cumulative distance of all the training data:
This is called the cost function. If you notice, it deducts y(the original output) from the hypothesis(the predicted output), takes the square to omit the negativity, sum up and divide by 2 times m. Here, m is the number of training data. You probably can see that cost function is the indication of the difference between the original output and the predicted output. The idea of a machine learning algorithm is to minimize the cost function so that the difference between the original output and the predicted output is closer. To achieve just that, we need to optimize the theta values.
Here is how we update the theta values. We take the partial differential of the cost function with respect to each theta value and deduct that value from the existing theta value,
Here, alpha is the learning rate and it is a constant. I am not showing the same formula for all the theta values. But It is the same formula for all the theta values. After the differentiation, the formula comes out to be:
This is called gradient descent.
The dataset I am going to use is from Andre Ng’s machine learning course in Coursera. I will provide the link at the bottom of this page. Please feel free to download the dataset and practice with this tutorial. I encourage you to practice with the dataset as you read if this is new to you. That is the only way to understand it well.
In this dataset, there are only two variables. But I developed the algorithm for any number of variables. If you use the same algorithm for 10 variables or 20 variables, it should work as well. I will use Numpy and Pandas library in Python. All these rich libraries of Python made the machine learning algorithm a lot easier. Import the packages and the dataset:
import pandas as pdimport numpy as npdf = pd.read_csv('ex1data2.txt', header = None)df.head()
Add a column of ones for the bias term. I chose 1 because if you multiply one with any value, that value does not change.
Add a column of ones for the bias term. I chose 1 because if you multiply one with any value, that value does not change.
df = pd.concat([pd.Series(1, index=df.index, name='00'), df], axis=1)df.head()
2. Define the input variables or the independent variables X and the output variable or dependent variable y. In this dataset, columns 0 and 1 are the input variables and column 2 is the output variable.
X = df.drop(columns=2)y = df.iloc[:, 3]
3. Normalize the input variables by dividing each column by the maximum values of that column. That way, each column’s values will be between 0 to 1. This step is not essential. But it makes the algorithm to reach it’s optimum faster. Also, if you notice the dataset, elements of column 0 are too big compared to the elements of column 1. If you normalize the dataset, it prevents column one from being too dominating in the algorithm.
for i in range(1, len(X.columns)): X[i-1] = X[i-1]/np.max(X[i-1])X.head()
4. Initiate the theta values. I am initiating them as zeros. But any other number should be alright.
theta = np.array([0]*len(X.columns))#Output: array([0, 0, 0])
5. Calculate the number of training data that is denoted as m in the formula above:
m = len(df)
6. Define the hypothesis function
def hypothesis(theta, X): return theta*X
7. Define the cost function using the formula of the cost function explained above
def computeCost(X, y, theta): y1 = hypothesis(theta, X) y1=np.sum(y1, axis=1) return sum(np.sqrt((y1-y)**2))/(2*47)
8. Write the function for the gradient descent. This function will take X, y, theta, learning rate(alpha in the formula), and epochs(or iterations) as input. We need to keep updating the theta values until the cost function reaches its minimum.
def gradientDescent(X, y, theta, alpha, i): J = [] #cost function in each iterations k = 0 while k < i: y1 = hypothesis(theta, X) y1 = np.sum(y1, axis=1) for c in range(0, len(X.columns)): theta[c] = theta[c] - alpha*(sum((y1-y)*X.iloc[:,c])/len(X)) j = computeCost(X, y, theta) J.append(j) k += 1 return J, j, theta
9. Use the gradient descent function to get the final cost, the list of cost in each iteration, and the optimized parameters theta. I chose alpha as 0.05. But you can try with some other values like 0.1, 0.01, 0.03, 0.3 to see what happens. I ran it for 10000 iterations. Please try it with more or fewer iterations to see the difference.
J, j, theta = gradientDescent(X, y, theta, 0.05, 10000)
10. Predict the output using the optimized theta
y_hat = hypothesis(theta, X)y_hat = np.sum(y_hat, axis=1)
11. Plot the original y and the predicted output ‘y_hat’
%matplotlib inlineimport matplotlib.pyplot as pltplt.figure()plt.scatter(x=list(range(0, 47)),y= y, color='blue') plt.scatter(x=list(range(0, 47)), y=y_hat, color='black')plt.show()
Some of the output points are almost overlapping with the predicted outputs. Some are close but not overlapping.
12. Plot the cost of each iteration to see the behavior
plt.figure()plt.scatter(x=list(range(0, 10000)), y=J)plt.show()
The cost kept going down with each iteration. This is the indication that the algorithm worked well.
I hope, this was helpful and you are also trying it for yourself. I encourage you to download the dataset and try running all the code for yourself if you are reading this to learn machine learning concepts. Here is the link to the dataset:
github.com
I hope it was helpful. Please feel free to follow me on Twitter and like my Facebook page.
|
[
{
"code": null,
"e": 451,
"s": 172,
"text": "Linear regression is probably the most simple machine learning algorithm. It is very good for starters because it uses simple formulas. So, it is good for learning machine-learning concepts. In this article, I will try to explain the multivariate linear regression step by step."
},
{
"code": null,
"e": 524,
"s": 451,
"text": "Linear regression uses the simple formula that we all learned in school:"
},
{
"code": null,
"e": 535,
"s": 524,
"text": "Y = C + AX"
},
{
"code": null,
"e": 678,
"s": 535,
"text": "Just as a reminder, Y is the output or dependent variable, X is the input or the independent variable, A is the slope, and C is the intercept."
},
{
"code": null,
"e": 753,
"s": 678,
"text": "For the linear regression, we follow these notations for the same formula:"
},
{
"code": null,
"e": 846,
"s": 753,
"text": "If we have multiple independent variables, the formula for linear regression will look like:"
},
{
"code": null,
"e": 1139,
"s": 846,
"text": "Here, ‘h’ is called the hypothesis. This is the predicted output variable. Theta0 is the bias term and all the other theta values are coefficients. They are initiated randomly in the beginning, then optimized with the algorithm so that this formula can predict the dependent variable closely."
},
{
"code": null,
"e": 1399,
"s": 1139,
"text": "When theta values are initiated in the beginning, the formula is not trained to predict the dependent variable. The hypothesis is far away from the original output variable ‘Y’. This is the formula to estimate the cumulative distance of all the training data:"
},
{
"code": null,
"e": 1989,
"s": 1399,
"text": "This is called the cost function. If you notice, it deducts y(the original output) from the hypothesis(the predicted output), takes the square to omit the negativity, sum up and divide by 2 times m. Here, m is the number of training data. You probably can see that cost function is the indication of the difference between the original output and the predicted output. The idea of a machine learning algorithm is to minimize the cost function so that the difference between the original output and the predicted output is closer. To achieve just that, we need to optimize the theta values."
},
{
"code": null,
"e": 2169,
"s": 1989,
"text": "Here is how we update the theta values. We take the partial differential of the cost function with respect to each theta value and deduct that value from the existing theta value,"
},
{
"code": null,
"e": 2393,
"s": 2169,
"text": "Here, alpha is the learning rate and it is a constant. I am not showing the same formula for all the theta values. But It is the same formula for all the theta values. After the differentiation, the formula comes out to be:"
},
{
"code": null,
"e": 2426,
"s": 2393,
"text": "This is called gradient descent."
},
{
"code": null,
"e": 2762,
"s": 2426,
"text": "The dataset I am going to use is from Andre Ng’s machine learning course in Coursera. I will provide the link at the bottom of this page. Please feel free to download the dataset and practice with this tutorial. I encourage you to practice with the dataset as you read if this is new to you. That is the only way to understand it well."
},
{
"code": null,
"e": 3125,
"s": 2762,
"text": "In this dataset, there are only two variables. But I developed the algorithm for any number of variables. If you use the same algorithm for 10 variables or 20 variables, it should work as well. I will use Numpy and Pandas library in Python. All these rich libraries of Python made the machine learning algorithm a lot easier. Import the packages and the dataset:"
},
{
"code": null,
"e": 3219,
"s": 3125,
"text": "import pandas as pdimport numpy as npdf = pd.read_csv('ex1data2.txt', header = None)df.head()"
},
{
"code": null,
"e": 3341,
"s": 3219,
"text": "Add a column of ones for the bias term. I chose 1 because if you multiply one with any value, that value does not change."
},
{
"code": null,
"e": 3463,
"s": 3341,
"text": "Add a column of ones for the bias term. I chose 1 because if you multiply one with any value, that value does not change."
},
{
"code": null,
"e": 3542,
"s": 3463,
"text": "df = pd.concat([pd.Series(1, index=df.index, name='00'), df], axis=1)df.head()"
},
{
"code": null,
"e": 3746,
"s": 3542,
"text": "2. Define the input variables or the independent variables X and the output variable or dependent variable y. In this dataset, columns 0 and 1 are the input variables and column 2 is the output variable."
},
{
"code": null,
"e": 3786,
"s": 3746,
"text": "X = df.drop(columns=2)y = df.iloc[:, 3]"
},
{
"code": null,
"e": 4222,
"s": 3786,
"text": "3. Normalize the input variables by dividing each column by the maximum values of that column. That way, each column’s values will be between 0 to 1. This step is not essential. But it makes the algorithm to reach it’s optimum faster. Also, if you notice the dataset, elements of column 0 are too big compared to the elements of column 1. If you normalize the dataset, it prevents column one from being too dominating in the algorithm."
},
{
"code": null,
"e": 4299,
"s": 4222,
"text": "for i in range(1, len(X.columns)): X[i-1] = X[i-1]/np.max(X[i-1])X.head()"
},
{
"code": null,
"e": 4400,
"s": 4299,
"text": "4. Initiate the theta values. I am initiating them as zeros. But any other number should be alright."
},
{
"code": null,
"e": 4462,
"s": 4400,
"text": "theta = np.array([0]*len(X.columns))#Output: array([0, 0, 0])"
},
{
"code": null,
"e": 4546,
"s": 4462,
"text": "5. Calculate the number of training data that is denoted as m in the formula above:"
},
{
"code": null,
"e": 4558,
"s": 4546,
"text": "m = len(df)"
},
{
"code": null,
"e": 4592,
"s": 4558,
"text": "6. Define the hypothesis function"
},
{
"code": null,
"e": 4636,
"s": 4592,
"text": "def hypothesis(theta, X): return theta*X"
},
{
"code": null,
"e": 4719,
"s": 4636,
"text": "7. Define the cost function using the formula of the cost function explained above"
},
{
"code": null,
"e": 4844,
"s": 4719,
"text": "def computeCost(X, y, theta): y1 = hypothesis(theta, X) y1=np.sum(y1, axis=1) return sum(np.sqrt((y1-y)**2))/(2*47)"
},
{
"code": null,
"e": 5089,
"s": 4844,
"text": "8. Write the function for the gradient descent. This function will take X, y, theta, learning rate(alpha in the formula), and epochs(or iterations) as input. We need to keep updating the theta values until the cost function reaches its minimum."
},
{
"code": null,
"e": 5480,
"s": 5089,
"text": "def gradientDescent(X, y, theta, alpha, i): J = [] #cost function in each iterations k = 0 while k < i: y1 = hypothesis(theta, X) y1 = np.sum(y1, axis=1) for c in range(0, len(X.columns)): theta[c] = theta[c] - alpha*(sum((y1-y)*X.iloc[:,c])/len(X)) j = computeCost(X, y, theta) J.append(j) k += 1 return J, j, theta"
},
{
"code": null,
"e": 5819,
"s": 5480,
"text": "9. Use the gradient descent function to get the final cost, the list of cost in each iteration, and the optimized parameters theta. I chose alpha as 0.05. But you can try with some other values like 0.1, 0.01, 0.03, 0.3 to see what happens. I ran it for 10000 iterations. Please try it with more or fewer iterations to see the difference."
},
{
"code": null,
"e": 5875,
"s": 5819,
"text": "J, j, theta = gradientDescent(X, y, theta, 0.05, 10000)"
},
{
"code": null,
"e": 5924,
"s": 5875,
"text": "10. Predict the output using the optimized theta"
},
{
"code": null,
"e": 5982,
"s": 5924,
"text": "y_hat = hypothesis(theta, X)y_hat = np.sum(y_hat, axis=1)"
},
{
"code": null,
"e": 6039,
"s": 5982,
"text": "11. Plot the original y and the predicted output ‘y_hat’"
},
{
"code": null,
"e": 6229,
"s": 6039,
"text": "%matplotlib inlineimport matplotlib.pyplot as pltplt.figure()plt.scatter(x=list(range(0, 47)),y= y, color='blue') plt.scatter(x=list(range(0, 47)), y=y_hat, color='black')plt.show()"
},
{
"code": null,
"e": 6342,
"s": 6229,
"text": "Some of the output points are almost overlapping with the predicted outputs. Some are close but not overlapping."
},
{
"code": null,
"e": 6398,
"s": 6342,
"text": "12. Plot the cost of each iteration to see the behavior"
},
{
"code": null,
"e": 6462,
"s": 6398,
"text": "plt.figure()plt.scatter(x=list(range(0, 10000)), y=J)plt.show()"
},
{
"code": null,
"e": 6563,
"s": 6462,
"text": "The cost kept going down with each iteration. This is the indication that the algorithm worked well."
},
{
"code": null,
"e": 6804,
"s": 6563,
"text": "I hope, this was helpful and you are also trying it for yourself. I encourage you to download the dataset and try running all the code for yourself if you are reading this to learn machine learning concepts. Here is the link to the dataset:"
},
{
"code": null,
"e": 6815,
"s": 6804,
"text": "github.com"
}
] |
Web scraping: How to handle a calendar with Selenium | by Euge Inzaugarat | Towards Data Science
|
❝ ... Time Moves Slowly, But Passes Quickly...❞— Alice Walker
I was sitting on my favorite sofa looking TV. Well, to tell the truth, I was channel surfing.
Perhaps there was nothing interesting to see or I was too distracted thinking about that issue I couldn’t solve at work.
I took my eyes away for one minute from the TV to answer a message. When I looked back at the screen, there it was. One of those movies I kept watching over and over again.
“Wait a minute. Wait a minute Doc, are you telling me you built a time machine ... out of a DeLorean? ” —Marty McFly was saying
“The way I see it if you’re going to build a time machine into a car, why not do it with some style?” — The Doc replied
Time travel. A lot of movies talk about this topic. And I believe a topic for chitchat among friends late at night.
At first, I was thrilled to find the movie because I liked it very much. But later, it reminded me of the issue I could not resolve.
I was not trying to build a time machine or to work on time travel.
I was just trying to scrape historical data on a particular website. This page has always the same URL. But when you pick a different day from the calendar, the content changed.
I was really struggling. I have previously built scrapers using Scrapy (If you want to learn more, read my previous post).
But I knew that this Python framework has some limitations. One of them is dealing with Javascript.
I decided to stop surfing the channels. I started reading and suddenly, I found the solution: Selenium.
Selenium is a tool that comes in handy for Web Browser Automation. It is able to open a browser of choice and mimics human behavior.
This means that it can perform tasks such as clicking buttons, filling forms or searching for information on a website. That’s cool, right?
Installing the packages is also very easy. We need to use the normal pip syntaxis: pip install selenium .
But there is an extra step that needs to be done. We need to download Chrome Driver. This WebDriver is an open-source tool for automated testing that provides capabilities for navigating to web pages, user input, JavaScript execution, and more.
Pay attention to download the version of ChromeDriver that is compatible with the version of your browser
Let’s start coding!
First of all, we’ll import the modules we need.
The module re to work with Regular Expressions
BeautifulSoup to pull the data from the Website
selenium.webdriver to launch the browser
selenium.webdriver.ActionChains to automate low-level interactions such as mouse movements.
After that, we need to create a new instance of google chrome.
We’ll use webdrive.Chrome() passing as argument the exact path that points where we downloaded the ChromeDrive.
Then, we use the .get() method passing as argument the desired URL.
If we run this, we’ll see that a new window is opened displaying the legend Chrome is being controlled by automated test software.
The first thing to do when scraping a website is to understand the structure of the website. Particularly, how we indicate Selenium how to select the different dates.
Let’s inspect the webpage HTML code, focusing on the calendar element.
We want to scrap the content of the website for the last two years. There are many strategies that can be followed here.
We’ll just indicate to WebDriver to click the previous <button n times. So if we are in March 2020 and we want to go to March 2018, we should press the button 24 times.
Let’s refresh our knowledge about XPath.
XPath stands for XML Path Language. What does it have to do with web scraping? We’ll learn how to identify HTML elements. But the question that arises now is how do I point out the element to the scraper? And the answer is XPath.
XPath is a special syntax that can be used to navigate through elements and attributes in an XML document. Also, it will help us get a path to a certain HTML element and extract its content.
Let’s see how this syntax works.
/ is used to move forward one generation, tag-names gives the direction to which element, [] tell us which of the siblings to choose, // looks for all future generations, @ selects attributes, * is a wildcard indicating we want to ignore tag types?
If we see the following XPath:
Xpath = '//div[@class="first"]/p[2]'
we would understand that from all (//) the div elements with class “first” (div[@class="first"]), we want the second ([2]) paragraph (p) element.
Fortunately, web browsers have an easy way to get the XPath of an element.
We copy the XPath of the element and pass it to the function .find_element_by_xpath().
Now, it’s time to tell WebDriver to go and click this element. We do that by chaining from ActionChains()the following functions:
.click() that will click on the element
.perform() that will perform the action
Once the calendar has gone back in time 24 months, we should tell selenium to click each day and scrape the content.
To understand how to point to the day element, let’s again inspect the website.
Look a the HTML code. We can observe that the different date attributes have different class values assigned.
The days that appeared in grey, have the day disable class. The day that is in black, have the class day , and the selected day (current date) have the class active day .
This last class will be unique to the current date attribute so we can use it to select the current date from the calendar.
First, we will make a list of all the elements with a class attribute containing the word day .
This time, we’ll point towards those elements using the function .find_element_by_class_name(). This comes in handy when we want to locate an element by class attribute name.
Once we have that list, we’ll loop over the list. For each element that we found, we get its attribute and ask if it is strictly equal to day . If it is, we’ll tell webdriver to click on it.
We’ll wait 5 seconds so the website can be loaded.
After that, we’ll use BeautifulSoup to scrape through the website. Here, it’s where we can insert any code to scrap the content of the website. We can just use find() or findall() methods.
Once we scrap the content, the loop we’ll move to the next day element found.
Notice that we need to do this for each month. So once all the elements of the month have been looped over, we need to move to the next month. The procedure is exactly the same as we did with the previous button.
Now, we save this script in a file (e.g. selenium_script.py). To run the script and start scrapping, we open a new terminal window.
We need to go to the same folder we have the file and type:
python3 selenium_script.py
After that, a Chrome window will pop up. And start to automatically click on the different dates. We will see something like this:
Once all the website and dates have been scrapped, we will see the following message in the terminal:
Process finished with exit code 0
This means that everything went well, and no error was encountered.
If we specified a file to save the content of the website, we can now go to the file and check the scrapped content.
If you want to read more about this topic, check these posts:
Introduction to Web Scraping using Selenium
Web Scraping Using Selenium — Python
Some rights reserved
|
[
{
"code": null,
"e": 234,
"s": 172,
"text": "❝ ... Time Moves Slowly, But Passes Quickly...❞— Alice Walker"
},
{
"code": null,
"e": 328,
"s": 234,
"text": "I was sitting on my favorite sofa looking TV. Well, to tell the truth, I was channel surfing."
},
{
"code": null,
"e": 449,
"s": 328,
"text": "Perhaps there was nothing interesting to see or I was too distracted thinking about that issue I couldn’t solve at work."
},
{
"code": null,
"e": 622,
"s": 449,
"text": "I took my eyes away for one minute from the TV to answer a message. When I looked back at the screen, there it was. One of those movies I kept watching over and over again."
},
{
"code": null,
"e": 750,
"s": 622,
"text": "“Wait a minute. Wait a minute Doc, are you telling me you built a time machine ... out of a DeLorean? ” —Marty McFly was saying"
},
{
"code": null,
"e": 870,
"s": 750,
"text": "“The way I see it if you’re going to build a time machine into a car, why not do it with some style?” — The Doc replied"
},
{
"code": null,
"e": 986,
"s": 870,
"text": "Time travel. A lot of movies talk about this topic. And I believe a topic for chitchat among friends late at night."
},
{
"code": null,
"e": 1119,
"s": 986,
"text": "At first, I was thrilled to find the movie because I liked it very much. But later, it reminded me of the issue I could not resolve."
},
{
"code": null,
"e": 1187,
"s": 1119,
"text": "I was not trying to build a time machine or to work on time travel."
},
{
"code": null,
"e": 1365,
"s": 1187,
"text": "I was just trying to scrape historical data on a particular website. This page has always the same URL. But when you pick a different day from the calendar, the content changed."
},
{
"code": null,
"e": 1488,
"s": 1365,
"text": "I was really struggling. I have previously built scrapers using Scrapy (If you want to learn more, read my previous post)."
},
{
"code": null,
"e": 1588,
"s": 1488,
"text": "But I knew that this Python framework has some limitations. One of them is dealing with Javascript."
},
{
"code": null,
"e": 1692,
"s": 1588,
"text": "I decided to stop surfing the channels. I started reading and suddenly, I found the solution: Selenium."
},
{
"code": null,
"e": 1825,
"s": 1692,
"text": "Selenium is a tool that comes in handy for Web Browser Automation. It is able to open a browser of choice and mimics human behavior."
},
{
"code": null,
"e": 1965,
"s": 1825,
"text": "This means that it can perform tasks such as clicking buttons, filling forms or searching for information on a website. That’s cool, right?"
},
{
"code": null,
"e": 2071,
"s": 1965,
"text": "Installing the packages is also very easy. We need to use the normal pip syntaxis: pip install selenium ."
},
{
"code": null,
"e": 2316,
"s": 2071,
"text": "But there is an extra step that needs to be done. We need to download Chrome Driver. This WebDriver is an open-source tool for automated testing that provides capabilities for navigating to web pages, user input, JavaScript execution, and more."
},
{
"code": null,
"e": 2422,
"s": 2316,
"text": "Pay attention to download the version of ChromeDriver that is compatible with the version of your browser"
},
{
"code": null,
"e": 2442,
"s": 2422,
"text": "Let’s start coding!"
},
{
"code": null,
"e": 2490,
"s": 2442,
"text": "First of all, we’ll import the modules we need."
},
{
"code": null,
"e": 2537,
"s": 2490,
"text": "The module re to work with Regular Expressions"
},
{
"code": null,
"e": 2585,
"s": 2537,
"text": "BeautifulSoup to pull the data from the Website"
},
{
"code": null,
"e": 2626,
"s": 2585,
"text": "selenium.webdriver to launch the browser"
},
{
"code": null,
"e": 2718,
"s": 2626,
"text": "selenium.webdriver.ActionChains to automate low-level interactions such as mouse movements."
},
{
"code": null,
"e": 2781,
"s": 2718,
"text": "After that, we need to create a new instance of google chrome."
},
{
"code": null,
"e": 2893,
"s": 2781,
"text": "We’ll use webdrive.Chrome() passing as argument the exact path that points where we downloaded the ChromeDrive."
},
{
"code": null,
"e": 2961,
"s": 2893,
"text": "Then, we use the .get() method passing as argument the desired URL."
},
{
"code": null,
"e": 3092,
"s": 2961,
"text": "If we run this, we’ll see that a new window is opened displaying the legend Chrome is being controlled by automated test software."
},
{
"code": null,
"e": 3259,
"s": 3092,
"text": "The first thing to do when scraping a website is to understand the structure of the website. Particularly, how we indicate Selenium how to select the different dates."
},
{
"code": null,
"e": 3330,
"s": 3259,
"text": "Let’s inspect the webpage HTML code, focusing on the calendar element."
},
{
"code": null,
"e": 3451,
"s": 3330,
"text": "We want to scrap the content of the website for the last two years. There are many strategies that can be followed here."
},
{
"code": null,
"e": 3620,
"s": 3451,
"text": "We’ll just indicate to WebDriver to click the previous <button n times. So if we are in March 2020 and we want to go to March 2018, we should press the button 24 times."
},
{
"code": null,
"e": 3661,
"s": 3620,
"text": "Let’s refresh our knowledge about XPath."
},
{
"code": null,
"e": 3891,
"s": 3661,
"text": "XPath stands for XML Path Language. What does it have to do with web scraping? We’ll learn how to identify HTML elements. But the question that arises now is how do I point out the element to the scraper? And the answer is XPath."
},
{
"code": null,
"e": 4082,
"s": 3891,
"text": "XPath is a special syntax that can be used to navigate through elements and attributes in an XML document. Also, it will help us get a path to a certain HTML element and extract its content."
},
{
"code": null,
"e": 4115,
"s": 4082,
"text": "Let’s see how this syntax works."
},
{
"code": null,
"e": 4364,
"s": 4115,
"text": "/ is used to move forward one generation, tag-names gives the direction to which element, [] tell us which of the siblings to choose, // looks for all future generations, @ selects attributes, * is a wildcard indicating we want to ignore tag types?"
},
{
"code": null,
"e": 4395,
"s": 4364,
"text": "If we see the following XPath:"
},
{
"code": null,
"e": 4432,
"s": 4395,
"text": "Xpath = '//div[@class=\"first\"]/p[2]'"
},
{
"code": null,
"e": 4578,
"s": 4432,
"text": "we would understand that from all (//) the div elements with class “first” (div[@class=\"first\"]), we want the second ([2]) paragraph (p) element."
},
{
"code": null,
"e": 4653,
"s": 4578,
"text": "Fortunately, web browsers have an easy way to get the XPath of an element."
},
{
"code": null,
"e": 4740,
"s": 4653,
"text": "We copy the XPath of the element and pass it to the function .find_element_by_xpath()."
},
{
"code": null,
"e": 4870,
"s": 4740,
"text": "Now, it’s time to tell WebDriver to go and click this element. We do that by chaining from ActionChains()the following functions:"
},
{
"code": null,
"e": 4910,
"s": 4870,
"text": ".click() that will click on the element"
},
{
"code": null,
"e": 4950,
"s": 4910,
"text": ".perform() that will perform the action"
},
{
"code": null,
"e": 5067,
"s": 4950,
"text": "Once the calendar has gone back in time 24 months, we should tell selenium to click each day and scrape the content."
},
{
"code": null,
"e": 5147,
"s": 5067,
"text": "To understand how to point to the day element, let’s again inspect the website."
},
{
"code": null,
"e": 5257,
"s": 5147,
"text": "Look a the HTML code. We can observe that the different date attributes have different class values assigned."
},
{
"code": null,
"e": 5428,
"s": 5257,
"text": "The days that appeared in grey, have the day disable class. The day that is in black, have the class day , and the selected day (current date) have the class active day ."
},
{
"code": null,
"e": 5552,
"s": 5428,
"text": "This last class will be unique to the current date attribute so we can use it to select the current date from the calendar."
},
{
"code": null,
"e": 5648,
"s": 5552,
"text": "First, we will make a list of all the elements with a class attribute containing the word day ."
},
{
"code": null,
"e": 5823,
"s": 5648,
"text": "This time, we’ll point towards those elements using the function .find_element_by_class_name(). This comes in handy when we want to locate an element by class attribute name."
},
{
"code": null,
"e": 6014,
"s": 5823,
"text": "Once we have that list, we’ll loop over the list. For each element that we found, we get its attribute and ask if it is strictly equal to day . If it is, we’ll tell webdriver to click on it."
},
{
"code": null,
"e": 6065,
"s": 6014,
"text": "We’ll wait 5 seconds so the website can be loaded."
},
{
"code": null,
"e": 6254,
"s": 6065,
"text": "After that, we’ll use BeautifulSoup to scrape through the website. Here, it’s where we can insert any code to scrap the content of the website. We can just use find() or findall() methods."
},
{
"code": null,
"e": 6332,
"s": 6254,
"text": "Once we scrap the content, the loop we’ll move to the next day element found."
},
{
"code": null,
"e": 6545,
"s": 6332,
"text": "Notice that we need to do this for each month. So once all the elements of the month have been looped over, we need to move to the next month. The procedure is exactly the same as we did with the previous button."
},
{
"code": null,
"e": 6677,
"s": 6545,
"text": "Now, we save this script in a file (e.g. selenium_script.py). To run the script and start scrapping, we open a new terminal window."
},
{
"code": null,
"e": 6737,
"s": 6677,
"text": "We need to go to the same folder we have the file and type:"
},
{
"code": null,
"e": 6764,
"s": 6737,
"text": "python3 selenium_script.py"
},
{
"code": null,
"e": 6895,
"s": 6764,
"text": "After that, a Chrome window will pop up. And start to automatically click on the different dates. We will see something like this:"
},
{
"code": null,
"e": 6997,
"s": 6895,
"text": "Once all the website and dates have been scrapped, we will see the following message in the terminal:"
},
{
"code": null,
"e": 7031,
"s": 6997,
"text": "Process finished with exit code 0"
},
{
"code": null,
"e": 7099,
"s": 7031,
"text": "This means that everything went well, and no error was encountered."
},
{
"code": null,
"e": 7216,
"s": 7099,
"text": "If we specified a file to save the content of the website, we can now go to the file and check the scrapped content."
},
{
"code": null,
"e": 7278,
"s": 7216,
"text": "If you want to read more about this topic, check these posts:"
},
{
"code": null,
"e": 7322,
"s": 7278,
"text": "Introduction to Web Scraping using Selenium"
},
{
"code": null,
"e": 7359,
"s": 7322,
"text": "Web Scraping Using Selenium — Python"
}
] |
Adding User Authentication in NextJS using Auth0 - GeeksforGeeks
|
27 Oct, 2021
In this article, we will learn How we can add user authentication in our NextJS project using Auth0. NextJS is a React-based framework. It has the power to Develop beautiful Web applications for different platforms like Windows, Linux, and mac. The linking of dynamic paths helps in rendering your NextJS components conditionally.
Approach: To add the user authentication using auth0 in our project first we will install the auth0 module. After that, we will create a dynamic file with [...auth0].js name. Then we will add UserProvider on every page. After that, we will add a login and signout option on our homepage.
Create NextJS Application:
Step 1: Create a new NextJs project using the below command:
npx create-next-app gfg
Project Structure: It will look like this.
Step 2: Create a free account on the auth0 website and create a new application.
Step 3: Get your domain, client id, and client secret key from the setting tab in your account.
Step 4: Add the callback and logout URL. Callback user is used to redirecting the user after logging in and logout URL is used to redirect the user after logging out.
Step 5: Now we will install the auth0 module using the following command:
npm install @auth0/nextjs-auth0
Step 6: Create a new .env.local file with the following code:
AUTH0_SECRET=
"[A 32 characters secret used to encrypt the cookies]"
AUTH0_BASE_URL="http://localhost:3000"
AUTH0_ISSUER_BASE_URL="YOUR_AUTH0_DOMAIN"
AUTH0_CLIENT_ID="YOUR_AUTH0_CLIENT_ID"
AUTH0_CLIENT_SECRET="YOUR_AUTH0_CLIENT_SECRET"
Step 7: Create a new folder inside the page/api directory with name auth. Inside this folder create a new dynamic route file with name [...auth0].js and add the below content inside the file.
Filename: [...auth0].js
Javascript
import { handleAuth } from '@auth0/nextjs-auth0'; export default handleAuth();
Step 8: Now we have to add auth0’s UserProvider on every page. For that, we will change the content of the _app.js file with the below content.
Filename: _app.js
Javascript
import React from 'react';import { UserProvider } from '@auth0/nextjs-auth0'; export default function App({ Component, pageProps }) { return ( <UserProvider> <Component {...pageProps} /> </UserProvider> );}
Step 9: Now we will add the login and logout button on our homepage. For that, add the below lines in the index.js file.
Filename: index.js
Javascript
import { useUser } from "@auth0/nextjs-auth0"; export default function Login(){ const { user, error, isLoading } = useUser() if (user) { return ( <div> <h2>Hey {user.name}, You are logged in</h2> <a href="/api/auth/logout"><h1>Logout</h1></a> </div> ); } return <a href="/api/auth/login"><h1>Login</h1></a>;};
Step to run application: After that run the app with the below command:
npm run dev
Output:
Next.js
NodeJS-Questions
React-Questions
ReactJS
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to set background images in ReactJS ?
How to create a table in ReactJS ?
ReactJS useNavigate() Hook
How to navigate on path by button click in react router ?
React-Router Hooks
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
Convert a string to an integer in JavaScript
How to insert spaces/tabs in text using HTML/CSS?
|
[
{
"code": null,
"e": 24826,
"s": 24798,
"text": "\n27 Oct, 2021"
},
{
"code": null,
"e": 25157,
"s": 24826,
"text": "In this article, we will learn How we can add user authentication in our NextJS project using Auth0. NextJS is a React-based framework. It has the power to Develop beautiful Web applications for different platforms like Windows, Linux, and mac. The linking of dynamic paths helps in rendering your NextJS components conditionally."
},
{
"code": null,
"e": 25445,
"s": 25157,
"text": "Approach: To add the user authentication using auth0 in our project first we will install the auth0 module. After that, we will create a dynamic file with [...auth0].js name. Then we will add UserProvider on every page. After that, we will add a login and signout option on our homepage."
},
{
"code": null,
"e": 25472,
"s": 25445,
"text": "Create NextJS Application:"
},
{
"code": null,
"e": 25533,
"s": 25472,
"text": "Step 1: Create a new NextJs project using the below command:"
},
{
"code": null,
"e": 25557,
"s": 25533,
"text": "npx create-next-app gfg"
},
{
"code": null,
"e": 25600,
"s": 25557,
"text": "Project Structure: It will look like this."
},
{
"code": null,
"e": 25681,
"s": 25600,
"text": "Step 2: Create a free account on the auth0 website and create a new application."
},
{
"code": null,
"e": 25777,
"s": 25681,
"text": "Step 3: Get your domain, client id, and client secret key from the setting tab in your account."
},
{
"code": null,
"e": 25944,
"s": 25777,
"text": "Step 4: Add the callback and logout URL. Callback user is used to redirecting the user after logging in and logout URL is used to redirect the user after logging out."
},
{
"code": null,
"e": 26018,
"s": 25944,
"text": "Step 5: Now we will install the auth0 module using the following command:"
},
{
"code": null,
"e": 26050,
"s": 26018,
"text": "npm install @auth0/nextjs-auth0"
},
{
"code": null,
"e": 26112,
"s": 26050,
"text": "Step 6: Create a new .env.local file with the following code:"
},
{
"code": null,
"e": 26350,
"s": 26112,
"text": "AUTH0_SECRET=\n \"[A 32 characters secret used to encrypt the cookies]\"\nAUTH0_BASE_URL=\"http://localhost:3000\"\nAUTH0_ISSUER_BASE_URL=\"YOUR_AUTH0_DOMAIN\"\nAUTH0_CLIENT_ID=\"YOUR_AUTH0_CLIENT_ID\"\nAUTH0_CLIENT_SECRET=\"YOUR_AUTH0_CLIENT_SECRET\""
},
{
"code": null,
"e": 26542,
"s": 26350,
"text": "Step 7: Create a new folder inside the page/api directory with name auth. Inside this folder create a new dynamic route file with name [...auth0].js and add the below content inside the file."
},
{
"code": null,
"e": 26566,
"s": 26542,
"text": "Filename: [...auth0].js"
},
{
"code": null,
"e": 26577,
"s": 26566,
"text": "Javascript"
},
{
"code": "import { handleAuth } from '@auth0/nextjs-auth0'; export default handleAuth();",
"e": 26657,
"s": 26577,
"text": null
},
{
"code": null,
"e": 26801,
"s": 26657,
"text": "Step 8: Now we have to add auth0’s UserProvider on every page. For that, we will change the content of the _app.js file with the below content."
},
{
"code": null,
"e": 26820,
"s": 26801,
"text": "Filename: _app.js "
},
{
"code": null,
"e": 26831,
"s": 26820,
"text": "Javascript"
},
{
"code": "import React from 'react';import { UserProvider } from '@auth0/nextjs-auth0'; export default function App({ Component, pageProps }) { return ( <UserProvider> <Component {...pageProps} /> </UserProvider> );}",
"e": 27052,
"s": 26831,
"text": null
},
{
"code": null,
"e": 27173,
"s": 27052,
"text": "Step 9: Now we will add the login and logout button on our homepage. For that, add the below lines in the index.js file."
},
{
"code": null,
"e": 27193,
"s": 27173,
"text": "Filename: index.js "
},
{
"code": null,
"e": 27204,
"s": 27193,
"text": "Javascript"
},
{
"code": "import { useUser } from \"@auth0/nextjs-auth0\"; export default function Login(){ const { user, error, isLoading } = useUser() if (user) { return ( <div> <h2>Hey {user.name}, You are logged in</h2> <a href=\"/api/auth/logout\"><h1>Logout</h1></a> </div> ); } return <a href=\"/api/auth/login\"><h1>Login</h1></a>;};",
"e": 27541,
"s": 27204,
"text": null
},
{
"code": null,
"e": 27613,
"s": 27541,
"text": "Step to run application: After that run the app with the below command:"
},
{
"code": null,
"e": 27625,
"s": 27613,
"text": "npm run dev"
},
{
"code": null,
"e": 27633,
"s": 27625,
"text": "Output:"
},
{
"code": null,
"e": 27641,
"s": 27633,
"text": "Next.js"
},
{
"code": null,
"e": 27658,
"s": 27641,
"text": "NodeJS-Questions"
},
{
"code": null,
"e": 27674,
"s": 27658,
"text": "React-Questions"
},
{
"code": null,
"e": 27682,
"s": 27674,
"text": "ReactJS"
},
{
"code": null,
"e": 27699,
"s": 27682,
"text": "Web Technologies"
},
{
"code": null,
"e": 27797,
"s": 27699,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 27839,
"s": 27797,
"text": "How to set background images in ReactJS ?"
},
{
"code": null,
"e": 27874,
"s": 27839,
"text": "How to create a table in ReactJS ?"
},
{
"code": null,
"e": 27901,
"s": 27874,
"text": "ReactJS useNavigate() Hook"
},
{
"code": null,
"e": 27959,
"s": 27901,
"text": "How to navigate on path by button click in react router ?"
},
{
"code": null,
"e": 27978,
"s": 27959,
"text": "React-Router Hooks"
},
{
"code": null,
"e": 28020,
"s": 27978,
"text": "Roadmap to Become a Web Developer in 2022"
},
{
"code": null,
"e": 28053,
"s": 28020,
"text": "Installation of Node.js on Linux"
},
{
"code": null,
"e": 28115,
"s": 28053,
"text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills"
},
{
"code": null,
"e": 28160,
"s": 28115,
"text": "Convert a string to an integer in JavaScript"
}
] |
Largest Prime Number possible from a subsequence of a Binary String - GeeksforGeeks
|
09 Jul, 2021
Given a Binary string, the task is to find the largest Prime Number possible by the decimal representation of a subsequence of the given binary string. If no prime number can be obtained, print -1.
Examples:
Input: S = “1001”Output: 5 Explanation: Out of all subsequences of the string “1001”, the largest prime number that can be obtained is “101” (= 5).
Input: “1011”Output: 11 Explanation: Out of all subsequences of the string “1011”, the largest prime number that can be obtained is “1011” (= 11).
Approach: To solve the problem, the idea is to generate all possible subsequences of the string, and convert each subsequence to its equivalent decimal form. Print the largest prime number obtained from this subsequences.
Follow the steps below to solve this problem:
Initialize a vector of pairs, say vec, for storing pairs of strings and their equivalent decimal values, in Pair.first and Pair.second respectively.
Initialize a variable, say ans, to store the required answer.
Iterate a loop from i = 0 to length of the string s:Iterate a loop from j = 0 to the length of vec:Store the jth pair in temp.If the ith character of string s is ‘1‘:Add the character in temp.first.Update the value of temp.second by left shifting the current value and adding 1 to it.Otherwise:Add the character in temp.first.Update the value of temp.second by left shifting the current value and adding 0 to it.Store this temp pair into vec.If the temp.second is prime:Store max of ans and temp.second in ans.If ans is equal to 0:No prime number can be obtained from the string s.Otherwise:Print ans.
Iterate a loop from j = 0 to the length of vec:Store the jth pair in temp.If the ith character of string s is ‘1‘:Add the character in temp.first.Update the value of temp.second by left shifting the current value and adding 1 to it.Otherwise:Add the character in temp.first.Update the value of temp.second by left shifting the current value and adding 0 to it.Store this temp pair into vec.If the temp.second is prime:Store max of ans and temp.second in ans.
Store the jth pair in temp.
If the ith character of string s is ‘1‘:Add the character in temp.first.Update the value of temp.second by left shifting the current value and adding 1 to it.
Add the character in temp.first.
Update the value of temp.second by left shifting the current value and adding 1 to it.
Otherwise:Add the character in temp.first.Update the value of temp.second by left shifting the current value and adding 0 to it.
Add the character in temp.first.
Update the value of temp.second by left shifting the current value and adding 0 to it.
Store this temp pair into vec.
If the temp.second is prime:Store max of ans and temp.second in ans.
Store max of ans and temp.second in ans.
If ans is equal to 0:No prime number can be obtained from the string s.
No prime number can be obtained from the string s.
Otherwise:Print ans.
Print ans.
Below is the implementation of the above approach:
C++
Python3
Javascript
// C++ Program to implement// the above approach #include <iostream>#include <vector>using namespace std; // Function to check if a// number is prime or notbool isPrime(int x){ if (x <= 1) return false; for (int i = 2; i * i <= x; i++) { if (x % i == 0) // Return not prime return false; } // If prime return true return true;} // Function to find the largest prime// number possible from a subsequencevoid largestPrime(string s){ // Stores pairs of subsequences and // their respective decimal value vector<pair<string, int> > vec{ { "", 0 } }; // Stores the answer int ans = 0; // Traverse the string for (int i = 0; i < s.length(); i++) { // Stores the size of the vector int n = vec.size(); // Traverse the vector for (int j = 0; j < n; j++) { // Extract the current pair pair<string, int> temp = vec[j]; // Get the binary string from the pair string str = temp.first; // Stores equivalent decimal values int val = temp.second; // If the current character is '1' if (s[i] == '1') { // Add the character // to the subsequence temp.first = str + '1'; // Update the value by left // shifting the current // value and adding 1 to it temp.second = ((val << 1) + 1); } // If s[i]=='0' else { // Add the character // to the subsequence temp.first = str + '0'; // Update the value by left // shifting the current // value and adding 0 to it temp.second = ((val << 1) + 0); } // Store the subsequence in the vector vec.push_back(temp); // Check if the decimal // representation of current // subsequence is prime or not int check = temp.second; // If prime if (isPrime(check)) { // Update the answer // with the largest one ans = max(ans, check); } } } // If no prime number // could be obtained if (ans == 0) cout << -1 << endl; else cout << ans << endl;} // Driver Codeint main(){ // Input String string s = "110"; largestPrime(s); return 0;}
# Python3 program to implement# the above approach # Function to check if a# number is prime or notdef isPrime(x): if (x <= 1): return False for i in range(2, x + 1): if i * i > x: break if (x % i == 0): # Return not prime return False # If prime return true return True # Function to find the largest prime# number possible from a subsequencedef largestPrime(s): # Stores pairs of subsequences and # their respective decimal value vec = [["", 0]] # Stores the answer ans = 0 # Traverse the string for i in range(len(s)): # Stores the size of the vector n = len(vec) # Traverse the vector for j in range(n): # Extract the current pair temp = vec[j] # Get the binary string from the pair str = temp[0] # Stores equivalent decimal values val = temp[1] # If the current character is '1' if (s[i] == '1'): # Add the character # to the subsequence temp[0] = str + '1' # Update the value by left # shifting the current # value and adding 1 to it temp[1] = ((val << 1) + 1) # If s[i]=='0' else: # Add the character # to the subsequence temp[0] = str + '0' # Update the value by left # shifting the current # value and adding 0 to it temp[1] = ((val << 1) + 0) # Store the subsequence in the vector vec.append(temp) # Check if the decimal # representation of current # subsequence is prime or not check = temp[1] # If prime if (isPrime(check)): # Update the answer # with the largest one ans = max(ans, check) break # If no prime number # could be obtained if (ans == 0): print(-1) else: print(ans) # Driver Codeif __name__ == '__main__': # Input String s = "110" largestPrime(s) # This code is contributed by mohit kumar 29
<script> // JavaScript Program to implement// the above approach // Function to check if a// number is prime or notfunction isPrime(x) { if (x <= 1) return false; for (let i = 2; i * i <= x; i++) { if(i * i > x){ break } if (x % i == 0) // Return not prime return false; } // If prime return true return true;} // Function to find the largest prime// number possible from a subsequencefunction largestPrime(s) { // Stores pairs of subsequences and // their respective decimal value let vec = [["", 0]]; // Stores the answer let ans = 0; // Traverse the string for (let i = 0; i < s.length; i++) { // Stores the size of the vector let n = vec.length; // Traverse the vector for (let j = 0; j < n; j++) { // Extract the current pair let temp = vec[j]; // Get the binary string from the pair let str = temp[0]; // Stores equivalent decimal values let val = temp[1]; // If the current character is '1' if (s[i] == '1') { // Add the character // to the subsequence temp[0] = str + '1'; // Update the value by left // shifting the current // value and adding 1 to it temp[1] = ((val << 1) + 1); } // If s[i]=='0' else { // Add the character // to the subsequence temp[0] = str + '0'; // Update the value by left // shifting the current // value and adding 0 to it temp[1] = ((val << 1) + 0); } // Store the subsequence in the vector vec.push(temp); // Check if the decimal // representation of current // subsequence is prime or not let check = temp[1]; // If prime if (isPrime(check)) { // Update the answer // with the largest one ans = Math.max(ans, check); break } } } // If no prime number // could be obtained if (ans == 0) document.write(-1 + "<br>"); else document.write(ans + "<br>");} // Driver Code // Input Stringlet s = "110"; largestPrime(s); </script>
3
Time Complexity: O(2N * √N), where N is the length of the string.Auxiliary Space: O(2N * N)
mohit kumar 29
gfgking
binary-representation
binary-string
Prime Number
subsequence
Bit Magic
Mathematical
Strings
Strings
Mathematical
Bit Magic
Prime Number
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Cyclic Redundancy Check and Modulo-2 Division
Little and Big Endian Mystery
Add two numbers without using arithmetic operators
Find the element that appears once
Bits manipulation (Important tactics)
Program for Fibonacci numbers
Write a program to print all permutations of a given string
C++ Data Types
Set in C++ Standard Template Library (STL)
Coin Change | DP-7
|
[
{
"code": null,
"e": 24937,
"s": 24909,
"text": "\n09 Jul, 2021"
},
{
"code": null,
"e": 25135,
"s": 24937,
"text": "Given a Binary string, the task is to find the largest Prime Number possible by the decimal representation of a subsequence of the given binary string. If no prime number can be obtained, print -1."
},
{
"code": null,
"e": 25145,
"s": 25135,
"text": "Examples:"
},
{
"code": null,
"e": 25293,
"s": 25145,
"text": "Input: S = “1001”Output: 5 Explanation: Out of all subsequences of the string “1001”, the largest prime number that can be obtained is “101” (= 5)."
},
{
"code": null,
"e": 25440,
"s": 25293,
"text": "Input: “1011”Output: 11 Explanation: Out of all subsequences of the string “1011”, the largest prime number that can be obtained is “1011” (= 11)."
},
{
"code": null,
"e": 25664,
"s": 25440,
"text": "Approach: To solve the problem, the idea is to generate all possible subsequences of the string, and convert each subsequence to its equivalent decimal form. Print the largest prime number obtained from this subsequences. "
},
{
"code": null,
"e": 25710,
"s": 25664,
"text": "Follow the steps below to solve this problem:"
},
{
"code": null,
"e": 25859,
"s": 25710,
"text": "Initialize a vector of pairs, say vec, for storing pairs of strings and their equivalent decimal values, in Pair.first and Pair.second respectively."
},
{
"code": null,
"e": 25921,
"s": 25859,
"text": "Initialize a variable, say ans, to store the required answer."
},
{
"code": null,
"e": 26523,
"s": 25921,
"text": "Iterate a loop from i = 0 to length of the string s:Iterate a loop from j = 0 to the length of vec:Store the jth pair in temp.If the ith character of string s is ‘1‘:Add the character in temp.first.Update the value of temp.second by left shifting the current value and adding 1 to it.Otherwise:Add the character in temp.first.Update the value of temp.second by left shifting the current value and adding 0 to it.Store this temp pair into vec.If the temp.second is prime:Store max of ans and temp.second in ans.If ans is equal to 0:No prime number can be obtained from the string s.Otherwise:Print ans."
},
{
"code": null,
"e": 26982,
"s": 26523,
"text": "Iterate a loop from j = 0 to the length of vec:Store the jth pair in temp.If the ith character of string s is ‘1‘:Add the character in temp.first.Update the value of temp.second by left shifting the current value and adding 1 to it.Otherwise:Add the character in temp.first.Update the value of temp.second by left shifting the current value and adding 0 to it.Store this temp pair into vec.If the temp.second is prime:Store max of ans and temp.second in ans."
},
{
"code": null,
"e": 27010,
"s": 26982,
"text": "Store the jth pair in temp."
},
{
"code": null,
"e": 27169,
"s": 27010,
"text": "If the ith character of string s is ‘1‘:Add the character in temp.first.Update the value of temp.second by left shifting the current value and adding 1 to it."
},
{
"code": null,
"e": 27202,
"s": 27169,
"text": "Add the character in temp.first."
},
{
"code": null,
"e": 27289,
"s": 27202,
"text": "Update the value of temp.second by left shifting the current value and adding 1 to it."
},
{
"code": null,
"e": 27418,
"s": 27289,
"text": "Otherwise:Add the character in temp.first.Update the value of temp.second by left shifting the current value and adding 0 to it."
},
{
"code": null,
"e": 27451,
"s": 27418,
"text": "Add the character in temp.first."
},
{
"code": null,
"e": 27538,
"s": 27451,
"text": "Update the value of temp.second by left shifting the current value and adding 0 to it."
},
{
"code": null,
"e": 27569,
"s": 27538,
"text": "Store this temp pair into vec."
},
{
"code": null,
"e": 27638,
"s": 27569,
"text": "If the temp.second is prime:Store max of ans and temp.second in ans."
},
{
"code": null,
"e": 27679,
"s": 27638,
"text": "Store max of ans and temp.second in ans."
},
{
"code": null,
"e": 27751,
"s": 27679,
"text": "If ans is equal to 0:No prime number can be obtained from the string s."
},
{
"code": null,
"e": 27802,
"s": 27751,
"text": "No prime number can be obtained from the string s."
},
{
"code": null,
"e": 27823,
"s": 27802,
"text": "Otherwise:Print ans."
},
{
"code": null,
"e": 27834,
"s": 27823,
"text": "Print ans."
},
{
"code": null,
"e": 27885,
"s": 27834,
"text": "Below is the implementation of the above approach:"
},
{
"code": null,
"e": 27889,
"s": 27885,
"text": "C++"
},
{
"code": null,
"e": 27897,
"s": 27889,
"text": "Python3"
},
{
"code": null,
"e": 27908,
"s": 27897,
"text": "Javascript"
},
{
"code": "// C++ Program to implement// the above approach #include <iostream>#include <vector>using namespace std; // Function to check if a// number is prime or notbool isPrime(int x){ if (x <= 1) return false; for (int i = 2; i * i <= x; i++) { if (x % i == 0) // Return not prime return false; } // If prime return true return true;} // Function to find the largest prime// number possible from a subsequencevoid largestPrime(string s){ // Stores pairs of subsequences and // their respective decimal value vector<pair<string, int> > vec{ { \"\", 0 } }; // Stores the answer int ans = 0; // Traverse the string for (int i = 0; i < s.length(); i++) { // Stores the size of the vector int n = vec.size(); // Traverse the vector for (int j = 0; j < n; j++) { // Extract the current pair pair<string, int> temp = vec[j]; // Get the binary string from the pair string str = temp.first; // Stores equivalent decimal values int val = temp.second; // If the current character is '1' if (s[i] == '1') { // Add the character // to the subsequence temp.first = str + '1'; // Update the value by left // shifting the current // value and adding 1 to it temp.second = ((val << 1) + 1); } // If s[i]=='0' else { // Add the character // to the subsequence temp.first = str + '0'; // Update the value by left // shifting the current // value and adding 0 to it temp.second = ((val << 1) + 0); } // Store the subsequence in the vector vec.push_back(temp); // Check if the decimal // representation of current // subsequence is prime or not int check = temp.second; // If prime if (isPrime(check)) { // Update the answer // with the largest one ans = max(ans, check); } } } // If no prime number // could be obtained if (ans == 0) cout << -1 << endl; else cout << ans << endl;} // Driver Codeint main(){ // Input String string s = \"110\"; largestPrime(s); return 0;}",
"e": 30403,
"s": 27908,
"text": null
},
{
"code": "# Python3 program to implement# the above approach # Function to check if a# number is prime or notdef isPrime(x): if (x <= 1): return False for i in range(2, x + 1): if i * i > x: break if (x % i == 0): # Return not prime return False # If prime return true return True # Function to find the largest prime# number possible from a subsequencedef largestPrime(s): # Stores pairs of subsequences and # their respective decimal value vec = [[\"\", 0]] # Stores the answer ans = 0 # Traverse the string for i in range(len(s)): # Stores the size of the vector n = len(vec) # Traverse the vector for j in range(n): # Extract the current pair temp = vec[j] # Get the binary string from the pair str = temp[0] # Stores equivalent decimal values val = temp[1] # If the current character is '1' if (s[i] == '1'): # Add the character # to the subsequence temp[0] = str + '1' # Update the value by left # shifting the current # value and adding 1 to it temp[1] = ((val << 1) + 1) # If s[i]=='0' else: # Add the character # to the subsequence temp[0] = str + '0' # Update the value by left # shifting the current # value and adding 0 to it temp[1] = ((val << 1) + 0) # Store the subsequence in the vector vec.append(temp) # Check if the decimal # representation of current # subsequence is prime or not check = temp[1] # If prime if (isPrime(check)): # Update the answer # with the largest one ans = max(ans, check) break # If no prime number # could be obtained if (ans == 0): print(-1) else: print(ans) # Driver Codeif __name__ == '__main__': # Input String s = \"110\" largestPrime(s) # This code is contributed by mohit kumar 29",
"e": 32748,
"s": 30403,
"text": null
},
{
"code": "<script> // JavaScript Program to implement// the above approach // Function to check if a// number is prime or notfunction isPrime(x) { if (x <= 1) return false; for (let i = 2; i * i <= x; i++) { if(i * i > x){ break } if (x % i == 0) // Return not prime return false; } // If prime return true return true;} // Function to find the largest prime// number possible from a subsequencefunction largestPrime(s) { // Stores pairs of subsequences and // their respective decimal value let vec = [[\"\", 0]]; // Stores the answer let ans = 0; // Traverse the string for (let i = 0; i < s.length; i++) { // Stores the size of the vector let n = vec.length; // Traverse the vector for (let j = 0; j < n; j++) { // Extract the current pair let temp = vec[j]; // Get the binary string from the pair let str = temp[0]; // Stores equivalent decimal values let val = temp[1]; // If the current character is '1' if (s[i] == '1') { // Add the character // to the subsequence temp[0] = str + '1'; // Update the value by left // shifting the current // value and adding 1 to it temp[1] = ((val << 1) + 1); } // If s[i]=='0' else { // Add the character // to the subsequence temp[0] = str + '0'; // Update the value by left // shifting the current // value and adding 0 to it temp[1] = ((val << 1) + 0); } // Store the subsequence in the vector vec.push(temp); // Check if the decimal // representation of current // subsequence is prime or not let check = temp[1]; // If prime if (isPrime(check)) { // Update the answer // with the largest one ans = Math.max(ans, check); break } } } // If no prime number // could be obtained if (ans == 0) document.write(-1 + \"<br>\"); else document.write(ans + \"<br>\");} // Driver Code // Input Stringlet s = \"110\"; largestPrime(s); </script>",
"e": 35190,
"s": 32748,
"text": null
},
{
"code": null,
"e": 35192,
"s": 35190,
"text": "3"
},
{
"code": null,
"e": 35286,
"s": 35194,
"text": "Time Complexity: O(2N * √N), where N is the length of the string.Auxiliary Space: O(2N * N)"
},
{
"code": null,
"e": 35303,
"s": 35288,
"text": "mohit kumar 29"
},
{
"code": null,
"e": 35311,
"s": 35303,
"text": "gfgking"
},
{
"code": null,
"e": 35333,
"s": 35311,
"text": "binary-representation"
},
{
"code": null,
"e": 35347,
"s": 35333,
"text": "binary-string"
},
{
"code": null,
"e": 35360,
"s": 35347,
"text": "Prime Number"
},
{
"code": null,
"e": 35372,
"s": 35360,
"text": "subsequence"
},
{
"code": null,
"e": 35382,
"s": 35372,
"text": "Bit Magic"
},
{
"code": null,
"e": 35395,
"s": 35382,
"text": "Mathematical"
},
{
"code": null,
"e": 35403,
"s": 35395,
"text": "Strings"
},
{
"code": null,
"e": 35411,
"s": 35403,
"text": "Strings"
},
{
"code": null,
"e": 35424,
"s": 35411,
"text": "Mathematical"
},
{
"code": null,
"e": 35434,
"s": 35424,
"text": "Bit Magic"
},
{
"code": null,
"e": 35447,
"s": 35434,
"text": "Prime Number"
},
{
"code": null,
"e": 35545,
"s": 35447,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 35554,
"s": 35545,
"text": "Comments"
},
{
"code": null,
"e": 35567,
"s": 35554,
"text": "Old Comments"
},
{
"code": null,
"e": 35613,
"s": 35567,
"text": "Cyclic Redundancy Check and Modulo-2 Division"
},
{
"code": null,
"e": 35643,
"s": 35613,
"text": "Little and Big Endian Mystery"
},
{
"code": null,
"e": 35694,
"s": 35643,
"text": "Add two numbers without using arithmetic operators"
},
{
"code": null,
"e": 35729,
"s": 35694,
"text": "Find the element that appears once"
},
{
"code": null,
"e": 35767,
"s": 35729,
"text": "Bits manipulation (Important tactics)"
},
{
"code": null,
"e": 35797,
"s": 35767,
"text": "Program for Fibonacci numbers"
},
{
"code": null,
"e": 35857,
"s": 35797,
"text": "Write a program to print all permutations of a given string"
},
{
"code": null,
"e": 35872,
"s": 35857,
"text": "C++ Data Types"
},
{
"code": null,
"e": 35915,
"s": 35872,
"text": "Set in C++ Standard Template Library (STL)"
}
] |
Create a list group heading in Bootstrap
|
To create a list group heading, use the .list-group-item-heading class in Bootstrap.
You can try to run the following code to implement .list-group-item-heading class −
Live Demo
<!DOCTYPE html>
<html>
<head>
<title>Bootstrap Example</title>
<link href = "/bootstrap/css/bootstrap.min.css" rel = "stylesheet">
<script src = "/scripts/jquery.min.js"></script>
<script src = "/bootstrap/js/bootstrap.min.js"></script>
</head>
<body>
<div class = "container">
<h1>Countries</h1>
<ul class = "list-group">
<li class = "list-group-item">
<h3 class = "list-group-item-heading">Asia</h3>
<p class = "list-group-item-text">India</p>
<p class = "list-group-item-text">Nepal</p>
</li>
<li class = "list-group-item">
<h3 class = "list-group-item-heading">Europe</h3>
<p class = "list-group-item-text">Germany</p>
<p class = "list-group-item-text">Italy</p>
<p class = "list-group-item-text">Spain</p>
</li>
</ul>
</div>
</body>
</html>
|
[
{
"code": null,
"e": 1147,
"s": 1062,
"text": "To create a list group heading, use the .list-group-item-heading class in Bootstrap."
},
{
"code": null,
"e": 1231,
"s": 1147,
"text": "You can try to run the following code to implement .list-group-item-heading class −"
},
{
"code": null,
"e": 1241,
"s": 1231,
"text": "Live Demo"
},
{
"code": null,
"e": 2215,
"s": 1241,
"text": "<!DOCTYPE html>\n<html>\n <head>\n <title>Bootstrap Example</title>\n <link href = \"/bootstrap/css/bootstrap.min.css\" rel = \"stylesheet\">\n <script src = \"/scripts/jquery.min.js\"></script>\n <script src = \"/bootstrap/js/bootstrap.min.js\"></script>\n </head>\n <body>\n <div class = \"container\">\n <h1>Countries</h1>\n <ul class = \"list-group\">\n <li class = \"list-group-item\">\n <h3 class = \"list-group-item-heading\">Asia</h3>\n <p class = \"list-group-item-text\">India</p>\n <p class = \"list-group-item-text\">Nepal</p>\n </li>\n <li class = \"list-group-item\">\n <h3 class = \"list-group-item-heading\">Europe</h3>\n <p class = \"list-group-item-text\">Germany</p>\n <p class = \"list-group-item-text\">Italy</p>\n <p class = \"list-group-item-text\">Spain</p>\n </li>\n </ul>\n </div>\n </body>\n</html>"
}
] |
How to Manipulate IP Addresses in Python using ipaddress Module? - GeeksforGeeks
|
21 Sep, 2021
IP Address stands for internet protocol address. It’s an identifying number that’s related to a selected computer or network. When connected to the web, the IP address allows the computers to send and receive information. Python provides ipaddress module which provides the capabilities to create, manipulate and operate on IPv4 and IPv6 addresses and networks. This module comes inbuilt with python 3.3+, so you don’t need to install it if you have python 3.3+. Although you can install it using pip.
pip install ipaddress
The module has IPv4Address class and IPv6Address class to handle IPv4 and IPv6 formats respectively. Since IPv4Address and IPv6Address objects share a lot of common attributes we will see for IPv4 format only and similarly we can do for IPv6 format.
The IPv4Address objects have a lot of attributes for IPv4 address. ipaddress.IPv4Address(‘address’) construct an IPv4Address object representing IPv4 address ‘address’. Some attributes of the class are as follows:
max_prefixlen: Return the total number of bits in the IP address represented by IPv4Address object (32 for IPv4 and 128 for IPv6).
is_multicast: Return True if the address is reserved for multicast use.
is_private: Return True if the address is allocated for private networks.
is_global: Return True if the address is allocated for public networks.
is_unspecified: Return True if the address is unspecified.
is_reserved: Return True if the address is otherwise IETF reserved.
is_loopback: Return True if this is a loopback address.
is_link_local: Return True if the address is reserved for link-local usage.
We can also use comparison operators to compare address objects. Also, we can add or subtract integers from the address object.
Now let’s see an example of these attributes.
Example:
Python3
import ipaddress# Creating an object of IPv4Address class and# initializing it with an IPv4 address.ip = ipaddress.IPv4Address('112.79.234.30') # Print total number of bits in the ip.print("Total no of bits in the ip:", ip.max_prefixlen) # Print True if the IP address is reserved for multicast use.print("Is multicast:", ip.is_multicast) # Print True if the IP address is allocated for private networks.print("Is private:", ip.is_private) # Print True if the IP address is global.print("Is global:", ip.is_global) # Print True if the IP address is unspecified.print("Is unspecified:", ip.is_unspecified) # Print True if the IP address is otherwise IETF reserved.print("Is reversed:", ip.is_reserved) # Print True if the IP address is a loopback address.print("Is loopback:", ip.is_loopback) # Print True if the IP address is Link-localprint("Is link-local:", ip.is_link_local) # next ip addressip1 = ip + 1print("Next ip:", ip1) # previous ip addressip2 = ip - 1print("Previous ip:", ip2) # Print True if ip1 is greater than ip2print("Is ip1 is greater than ip2:", ip1 > ip2)
Output:
Total no of bits in the ip: 32
Is multicast: False
Is private: False
Is global: True
Is unspecified: False
Is reversed: False
Is loopback: False
Is link-local: False
Next ip: 112.79.234.31
Previous ip: 112.79.234.29
Is ip1 is greater than ip2: True
IPv4Network objects are used to inspect and define IP networks. All the attributes for address object are also valid for network object, additionally, network object provides additional attributes. Some of them is listed below.
network_address: Return the network address for the network.
broadcast_address: Return the broadcast address for the network. Packets sent to the broadcast address should be received by every host on the network.
netmask: Return network mask of the network.
with_netmask: Return a string representation of the network, with the mask in netmask notation.
with_hostmask: Return a string representation of the network, with the mask in host mask notation.
prefixlen: Return the length of the network prefix in bits.
num_addresses: Return the total number of the address of this network.
hosts(): Returns an iterator over the usable hosts in the network. The usable hosts are all the IP addresses that belong to the network, except the network address itself and the network broadcast address.
overlaps(other): Return True if this network is partly or wholly contained in other or other is wholly contained in this network.
subnets(prefixlen_diff): Return the subnets that join to make the current network definition, depending on the argument values. The prefixlen_diff parameter is the integer that indicates the amount our prefix length should be increased by.
supernet(prefixlen_diff): Return the supernet containing this network definition, the prefixlen_diff is the amount our prefix length should be decreased by.
subnet_of(other): Return True if this network is a subnet of other (new in python 3.7).
supernet_of(other): Return True if this network is a supernet of other (new in python 3.7).
compare_networks(other): Compare ip network with the other IP network. In this comparison only the network addresses are considered, host bits aren’t. It returns either -1, 0, or 1.
Now let’s see an example of the above methods.
Example:
Python3
import ipaddress # Initializing an IPv4 Network.network = ipaddress.IPv4Network("192.168.1.0/24") # Print the network address of the network.print("Network address of the network:", network.network_address) # Print the broadcast addressprint("Broadcast address:", network.broadcast_address) # Print the network mask.print("Network mask:", network.netmask) # Print with_netmask.print("with netmask:", network.with_netmask) # Print with_hostmask.print("with_hostmask:", network.with_hostmask) # Print Length of network prefix in bits.print("Length of network prefix in bits:", network.prefixlen) # Print the number of hosts under the network.print("Total number of hosts under the network:", network.num_addresses) # Print if this network is under (or overlaps) 192.168.0.0/16print("Overlaps 192.168.0.0/16:", network.overlaps(ipaddress.IPv4Network("192.168.0.0/16"))) # Print the supernet of this networkprint("Supernet:", network.supernet(prefixlen_diff=1)) # Print if the network is subnet of 192.168.0.0/16.print("The network is subnet of 192.168.0.0/16:", network.subnet_of(ipaddress.IPv4Network("192.168.0.0/16"))) # Print if the network is supernet of 192.168.0.0/16.print("The network is supernet of 192.168.0.0/16:", network.supernet_of(ipaddress.IPv4Network("192.168.0.0/16"))) # Compare the ip network with 192.168.0.0/16.print("Compare the network with 192.168.0.0/16:", network.compare_networks(ipaddress.IPv4Network("192.168.0.0/16")))
Output:
Network address of the network: 192.168.1.0
Broadcast address: 192.168.1.255
Network mask: 255.255.255.0
with netmask: 192.168.1.0/255.255.255.0
with_hostmask: 192.168.1.0/0.0.0.255
Length of network prefix in bits: 24
Total number of hosts under the network: 256
Overlaps 192.168.0.0/16: True
Supernet: 192.168.0.0/23
The network is subnet of 192.168.0.0/16: True
The network is supernet of 192.168.0.0/16: False
Compare the network with 192.168.0.0/16: 1
simmytarika5
Picked
python-modules
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
How to Install PIP on Windows ?
How to drop one or multiple columns in Pandas Dataframe
How To Convert Python Dictionary To JSON?
Check if element exists in list in Python
Python | Pandas dataframe.groupby()
Defaultdict in Python
Python | Get unique values from a list
Python Classes and Objects
Python | os.path.join() method
Create a directory in Python
|
[
{
"code": null,
"e": 23901,
"s": 23873,
"text": "\n21 Sep, 2021"
},
{
"code": null,
"e": 24403,
"s": 23901,
"text": "IP Address stands for internet protocol address. It’s an identifying number that’s related to a selected computer or network. When connected to the web, the IP address allows the computers to send and receive information. Python provides ipaddress module which provides the capabilities to create, manipulate and operate on IPv4 and IPv6 addresses and networks. This module comes inbuilt with python 3.3+, so you don’t need to install it if you have python 3.3+. Although you can install it using pip."
},
{
"code": null,
"e": 24425,
"s": 24403,
"text": "pip install ipaddress"
},
{
"code": null,
"e": 24676,
"s": 24425,
"text": "The module has IPv4Address class and IPv6Address class to handle IPv4 and IPv6 formats respectively. Since IPv4Address and IPv6Address objects share a lot of common attributes we will see for IPv4 format only and similarly we can do for IPv6 format."
},
{
"code": null,
"e": 24890,
"s": 24676,
"text": "The IPv4Address objects have a lot of attributes for IPv4 address. ipaddress.IPv4Address(‘address’) construct an IPv4Address object representing IPv4 address ‘address’. Some attributes of the class are as follows:"
},
{
"code": null,
"e": 25021,
"s": 24890,
"text": "max_prefixlen: Return the total number of bits in the IP address represented by IPv4Address object (32 for IPv4 and 128 for IPv6)."
},
{
"code": null,
"e": 25093,
"s": 25021,
"text": "is_multicast: Return True if the address is reserved for multicast use."
},
{
"code": null,
"e": 25167,
"s": 25093,
"text": "is_private: Return True if the address is allocated for private networks."
},
{
"code": null,
"e": 25239,
"s": 25167,
"text": "is_global: Return True if the address is allocated for public networks."
},
{
"code": null,
"e": 25298,
"s": 25239,
"text": "is_unspecified: Return True if the address is unspecified."
},
{
"code": null,
"e": 25366,
"s": 25298,
"text": "is_reserved: Return True if the address is otherwise IETF reserved."
},
{
"code": null,
"e": 25422,
"s": 25366,
"text": "is_loopback: Return True if this is a loopback address."
},
{
"code": null,
"e": 25498,
"s": 25422,
"text": "is_link_local: Return True if the address is reserved for link-local usage."
},
{
"code": null,
"e": 25626,
"s": 25498,
"text": "We can also use comparison operators to compare address objects. Also, we can add or subtract integers from the address object."
},
{
"code": null,
"e": 25672,
"s": 25626,
"text": "Now let’s see an example of these attributes."
},
{
"code": null,
"e": 25681,
"s": 25672,
"text": "Example:"
},
{
"code": null,
"e": 25689,
"s": 25681,
"text": "Python3"
},
{
"code": "import ipaddress# Creating an object of IPv4Address class and# initializing it with an IPv4 address.ip = ipaddress.IPv4Address('112.79.234.30') # Print total number of bits in the ip.print(\"Total no of bits in the ip:\", ip.max_prefixlen) # Print True if the IP address is reserved for multicast use.print(\"Is multicast:\", ip.is_multicast) # Print True if the IP address is allocated for private networks.print(\"Is private:\", ip.is_private) # Print True if the IP address is global.print(\"Is global:\", ip.is_global) # Print True if the IP address is unspecified.print(\"Is unspecified:\", ip.is_unspecified) # Print True if the IP address is otherwise IETF reserved.print(\"Is reversed:\", ip.is_reserved) # Print True if the IP address is a loopback address.print(\"Is loopback:\", ip.is_loopback) # Print True if the IP address is Link-localprint(\"Is link-local:\", ip.is_link_local) # next ip addressip1 = ip + 1print(\"Next ip:\", ip1) # previous ip addressip2 = ip - 1print(\"Previous ip:\", ip2) # Print True if ip1 is greater than ip2print(\"Is ip1 is greater than ip2:\", ip1 > ip2)",
"e": 26766,
"s": 25689,
"text": null
},
{
"code": null,
"e": 26774,
"s": 26766,
"text": "Output:"
},
{
"code": null,
"e": 27023,
"s": 26774,
"text": "Total no of bits in the ip: 32\nIs multicast: False\nIs private: False\nIs global: True\nIs unspecified: False\nIs reversed: False\nIs loopback: False\nIs link-local: False\nNext ip: 112.79.234.31\nPrevious ip: 112.79.234.29\nIs ip1 is greater than ip2: True"
},
{
"code": null,
"e": 27251,
"s": 27023,
"text": "IPv4Network objects are used to inspect and define IP networks. All the attributes for address object are also valid for network object, additionally, network object provides additional attributes. Some of them is listed below."
},
{
"code": null,
"e": 27312,
"s": 27251,
"text": "network_address: Return the network address for the network."
},
{
"code": null,
"e": 27464,
"s": 27312,
"text": "broadcast_address: Return the broadcast address for the network. Packets sent to the broadcast address should be received by every host on the network."
},
{
"code": null,
"e": 27509,
"s": 27464,
"text": "netmask: Return network mask of the network."
},
{
"code": null,
"e": 27605,
"s": 27509,
"text": "with_netmask: Return a string representation of the network, with the mask in netmask notation."
},
{
"code": null,
"e": 27704,
"s": 27605,
"text": "with_hostmask: Return a string representation of the network, with the mask in host mask notation."
},
{
"code": null,
"e": 27764,
"s": 27704,
"text": "prefixlen: Return the length of the network prefix in bits."
},
{
"code": null,
"e": 27835,
"s": 27764,
"text": "num_addresses: Return the total number of the address of this network."
},
{
"code": null,
"e": 28041,
"s": 27835,
"text": "hosts(): Returns an iterator over the usable hosts in the network. The usable hosts are all the IP addresses that belong to the network, except the network address itself and the network broadcast address."
},
{
"code": null,
"e": 28171,
"s": 28041,
"text": "overlaps(other): Return True if this network is partly or wholly contained in other or other is wholly contained in this network."
},
{
"code": null,
"e": 28411,
"s": 28171,
"text": "subnets(prefixlen_diff): Return the subnets that join to make the current network definition, depending on the argument values. The prefixlen_diff parameter is the integer that indicates the amount our prefix length should be increased by."
},
{
"code": null,
"e": 28568,
"s": 28411,
"text": "supernet(prefixlen_diff): Return the supernet containing this network definition, the prefixlen_diff is the amount our prefix length should be decreased by."
},
{
"code": null,
"e": 28656,
"s": 28568,
"text": "subnet_of(other): Return True if this network is a subnet of other (new in python 3.7)."
},
{
"code": null,
"e": 28748,
"s": 28656,
"text": "supernet_of(other): Return True if this network is a supernet of other (new in python 3.7)."
},
{
"code": null,
"e": 28930,
"s": 28748,
"text": "compare_networks(other): Compare ip network with the other IP network. In this comparison only the network addresses are considered, host bits aren’t. It returns either -1, 0, or 1."
},
{
"code": null,
"e": 28977,
"s": 28930,
"text": "Now let’s see an example of the above methods."
},
{
"code": null,
"e": 28987,
"s": 28977,
"text": "Example: "
},
{
"code": null,
"e": 28995,
"s": 28987,
"text": "Python3"
},
{
"code": "import ipaddress # Initializing an IPv4 Network.network = ipaddress.IPv4Network(\"192.168.1.0/24\") # Print the network address of the network.print(\"Network address of the network:\", network.network_address) # Print the broadcast addressprint(\"Broadcast address:\", network.broadcast_address) # Print the network mask.print(\"Network mask:\", network.netmask) # Print with_netmask.print(\"with netmask:\", network.with_netmask) # Print with_hostmask.print(\"with_hostmask:\", network.with_hostmask) # Print Length of network prefix in bits.print(\"Length of network prefix in bits:\", network.prefixlen) # Print the number of hosts under the network.print(\"Total number of hosts under the network:\", network.num_addresses) # Print if this network is under (or overlaps) 192.168.0.0/16print(\"Overlaps 192.168.0.0/16:\", network.overlaps(ipaddress.IPv4Network(\"192.168.0.0/16\"))) # Print the supernet of this networkprint(\"Supernet:\", network.supernet(prefixlen_diff=1)) # Print if the network is subnet of 192.168.0.0/16.print(\"The network is subnet of 192.168.0.0/16:\", network.subnet_of(ipaddress.IPv4Network(\"192.168.0.0/16\"))) # Print if the network is supernet of 192.168.0.0/16.print(\"The network is supernet of 192.168.0.0/16:\", network.supernet_of(ipaddress.IPv4Network(\"192.168.0.0/16\"))) # Compare the ip network with 192.168.0.0/16.print(\"Compare the network with 192.168.0.0/16:\", network.compare_networks(ipaddress.IPv4Network(\"192.168.0.0/16\")))",
"e": 30458,
"s": 28995,
"text": null
},
{
"code": null,
"e": 30466,
"s": 30458,
"text": "Output:"
},
{
"code": null,
"e": 30923,
"s": 30466,
"text": "Network address of the network: 192.168.1.0\nBroadcast address: 192.168.1.255\nNetwork mask: 255.255.255.0\nwith netmask: 192.168.1.0/255.255.255.0\nwith_hostmask: 192.168.1.0/0.0.0.255\nLength of network prefix in bits: 24\nTotal number of hosts under the network: 256\nOverlaps 192.168.0.0/16: True\nSupernet: 192.168.0.0/23\nThe network is subnet of 192.168.0.0/16: True\nThe network is supernet of 192.168.0.0/16: False\nCompare the network with 192.168.0.0/16: 1"
},
{
"code": null,
"e": 30938,
"s": 30925,
"text": "simmytarika5"
},
{
"code": null,
"e": 30945,
"s": 30938,
"text": "Picked"
},
{
"code": null,
"e": 30960,
"s": 30945,
"text": "python-modules"
},
{
"code": null,
"e": 30967,
"s": 30960,
"text": "Python"
},
{
"code": null,
"e": 31065,
"s": 30967,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 31074,
"s": 31065,
"text": "Comments"
},
{
"code": null,
"e": 31087,
"s": 31074,
"text": "Old Comments"
},
{
"code": null,
"e": 31119,
"s": 31087,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 31175,
"s": 31119,
"text": "How to drop one or multiple columns in Pandas Dataframe"
},
{
"code": null,
"e": 31217,
"s": 31175,
"text": "How To Convert Python Dictionary To JSON?"
},
{
"code": null,
"e": 31259,
"s": 31217,
"text": "Check if element exists in list in Python"
},
{
"code": null,
"e": 31295,
"s": 31259,
"text": "Python | Pandas dataframe.groupby()"
},
{
"code": null,
"e": 31317,
"s": 31295,
"text": "Defaultdict in Python"
},
{
"code": null,
"e": 31356,
"s": 31317,
"text": "Python | Get unique values from a list"
},
{
"code": null,
"e": 31383,
"s": 31356,
"text": "Python Classes and Objects"
},
{
"code": null,
"e": 31414,
"s": 31383,
"text": "Python | os.path.join() method"
}
] |
Create a Random Sequence of Numbers within t-Distribution in R Programming - rt() Function - GeeksforGeeks
|
19 Jun, 2020
rt() function in R Language is used to create a random sequence of values from Student t-distribution.
Syntax: rt(n, df, ncp)
Parameters:n: Number of observationsdf: Degree of Freedomncp: Numeric vector of non-centrality parameters.
Example 1:
# R Program to create random sequence# from t distribution # Calling rt() Functionrt(15, 2)rt(15, 1)
Output:
[1] 2.09851925 -1.76883434 -0.56019367 0.23263458 1.02778818 -0.82274015
[7] -1.33110401 4.19230931 0.80622707 0.02468189 -4.00469465 0.02974788
[13] 1.28649412 -0.19235704 0.21665196
[1] 2.21010764 -11.70663704 -1.00452125 2.07828752 1.95781361
[6] -0.53603661 0.02068073 -1.32464307 -49.93080321 0.82594818
[11] -0.46109805 -0.18965787 0.60498953 -0.44659619 -0.08968020
Example 2:
# R Program to create random sequence# from t distribution # Calling rt() Functionrt(5, 1, 1:5 * 5)rt(5, 2, 1:10)
Output:
[1] 23.88663 20.26813 62.95437 14.59003 20.58296
[1] 0.1745755 4.5298859 1.1175184 7.4660938 45.1399588
R Math-Function
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 Change Axis Scales in R Plots?
Group by function in R using Dplyr
How to Split Column Into Multiple Columns in R DataFrame?
How to filter R DataFrame by values in a column?
How to import an Excel File into R ?
How to filter R dataframe by multiple conditions?
Replace Specific Characters in String in R
Time Series Analysis in R
R - if statement
|
[
{
"code": null,
"e": 25242,
"s": 25214,
"text": "\n19 Jun, 2020"
},
{
"code": null,
"e": 25345,
"s": 25242,
"text": "rt() function in R Language is used to create a random sequence of values from Student t-distribution."
},
{
"code": null,
"e": 25368,
"s": 25345,
"text": "Syntax: rt(n, df, ncp)"
},
{
"code": null,
"e": 25475,
"s": 25368,
"text": "Parameters:n: Number of observationsdf: Degree of Freedomncp: Numeric vector of non-centrality parameters."
},
{
"code": null,
"e": 25486,
"s": 25475,
"text": "Example 1:"
},
{
"code": "# R Program to create random sequence# from t distribution # Calling rt() Functionrt(15, 2)rt(15, 1)",
"e": 25588,
"s": 25486,
"text": null
},
{
"code": null,
"e": 25596,
"s": 25588,
"text": "Output:"
},
{
"code": null,
"e": 26002,
"s": 25596,
"text": " [1] 2.09851925 -1.76883434 -0.56019367 0.23263458 1.02778818 -0.82274015\n [7] -1.33110401 4.19230931 0.80622707 0.02468189 -4.00469465 0.02974788\n[13] 1.28649412 -0.19235704 0.21665196\n [1] 2.21010764 -11.70663704 -1.00452125 2.07828752 1.95781361\n [6] -0.53603661 0.02068073 -1.32464307 -49.93080321 0.82594818\n[11] -0.46109805 -0.18965787 0.60498953 -0.44659619 -0.08968020\n"
},
{
"code": null,
"e": 26013,
"s": 26002,
"text": "Example 2:"
},
{
"code": "# R Program to create random sequence# from t distribution # Calling rt() Functionrt(5, 1, 1:5 * 5)rt(5, 2, 1:10)",
"e": 26128,
"s": 26013,
"text": null
},
{
"code": null,
"e": 26136,
"s": 26128,
"text": "Output:"
},
{
"code": null,
"e": 26245,
"s": 26136,
"text": "[1] 23.88663 20.26813 62.95437 14.59003 20.58296\n[1] 0.1745755 4.5298859 1.1175184 7.4660938 45.1399588\n"
},
{
"code": null,
"e": 26261,
"s": 26245,
"text": "R Math-Function"
},
{
"code": null,
"e": 26272,
"s": 26261,
"text": "R Language"
},
{
"code": null,
"e": 26370,
"s": 26272,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 26422,
"s": 26370,
"text": "Change Color of Bars in Barchart using ggplot2 in R"
},
{
"code": null,
"e": 26460,
"s": 26422,
"text": "How to Change Axis Scales in R Plots?"
},
{
"code": null,
"e": 26495,
"s": 26460,
"text": "Group by function in R using Dplyr"
},
{
"code": null,
"e": 26553,
"s": 26495,
"text": "How to Split Column Into Multiple Columns in R DataFrame?"
},
{
"code": null,
"e": 26602,
"s": 26553,
"text": "How to filter R DataFrame by values in a column?"
},
{
"code": null,
"e": 26639,
"s": 26602,
"text": "How to import an Excel File into R ?"
},
{
"code": null,
"e": 26689,
"s": 26639,
"text": "How to filter R dataframe by multiple conditions?"
},
{
"code": null,
"e": 26732,
"s": 26689,
"text": "Replace Specific Characters in String in R"
},
{
"code": null,
"e": 26758,
"s": 26732,
"text": "Time Series Analysis in R"
}
] |
How to validate IFSC Code using Regular Expression
|
25 May, 2021
Given string str, the task is to check whether the given string is a valid IFSC (Indian Financial System) Code or not by using Regular Expression. The valid IFSC (Indian Financial System) Code must satisfy the following conditions:
It should be 11 characters long.The first four characters should be upper case alphabets.The fifth character should be 0.The last six characters usually numeric, but can also be alphabetic.
It should be 11 characters long.
The first four characters should be upper case alphabets.
The fifth character should be 0.
The last six characters usually numeric, but can also be alphabetic.
Examples:
Input: str = “SBIN0125620”; Output: true Explanation: The given string satisfies all the above-mentioned conditions. Therefore, it is a valid IFSC (Indian Financial System) Code.Input: str = “SBIN0125”; Output: false Explanation: The given string has 8 characters. Therefore it is not a valid IFSC (Indian Financial System) Code.Input: str = “1234SBIN012”; Output: false Explanation: The given string doesn’t starts with alphabets. Therefore it is not a valid IFSC (Indian Financial System) Code.
Approach: The idea is to use Regular Expression to solve this problem. The following steps can be followed to compute the answer.
Get the String.
Create a regular expression to check valid IFSC (Indian Financial System) Code as mentioned below:
regex = "^[A-Z]{4}0[A-Z0-9]{6}$";
Where: ^ represents the starting of the string.[A-Z]{4} represents the first four characters should be upper case alphabets.0 represents the fifth character should be 0.[A-Z0-9]{6} represents the next six characters usually numeric, but can also be alphabetic.$ represents the ending of the string.
^ represents the starting of the string.
[A-Z]{4} represents the first four characters should be upper case alphabets.
0 represents the fifth character should be 0.
[A-Z0-9]{6} represents the next six characters usually numeric, but can also be alphabetic.
$ represents the ending of the string.
Below is the implementation of the above approach:
C++
Java
Python3
// C++ program to validate the// IFSC (Indian Financial System) Code using Regular Expression#include <iostream>#include <regex>using namespace std; // Function to validate the IFSC (Indian Financial System) Code.bool isValidIFSCode(string str){ // Regex to check valid IFSC (Indian Financial System) Code. const regex pattern("^[A-Z]{4}0[A-Z0-9]{6}$"); // If the IFSC (Indian Financial System) Code // is empty return false if (str.empty()) { return false; } // Return true if the IFSC (Indian Financial System) Code // matched the ReGex if(regex_match(str, pattern)) { return true; } else { return false; }} // Driver Codeint main(){ // Test Case 1: string str1 = "SBIN0125620"; cout << boolalpha << isValidIFSCode(str1) << endl; // Test Case 2: string str2 = "SBIN0125"; cout << boolalpha << isValidIFSCode(str2) << endl; // Test Case 3: string str3 = "1234SBIN012"; cout << boolalpha << isValidIFSCode(str3) << endl; // Test Case 4: string str4 = "SBIN7125620"; cout << boolalpha <<isValidIFSCode(str4) << endl; return 0;} // This code is contributed by yuvraj_chandra
// Java program to validate// IFSC (Indian Financial System) Code// using regular expression.import java.util.regex.*;class GFG { // Function to validate // IFSC (Indian Financial System) Code // using regular expression. public static boolean isValidIFSCode(String str) { // Regex to check valid IFSC Code. String regex = "^[A-Z]{4}0[A-Z0-9]{6}$"; // Compile the ReGex Pattern p = Pattern.compile(regex); // If the string is empty // return false if (str == null) { return false; } // Pattern class contains matcher() // method to find matching between // the given string and // the regular expression. Matcher m = p.matcher(str); // Return if the string // matched the ReGex return m.matches(); } // Driver Code. public static void main(String args[]) { // Test Case 1: String str1 = "SBIN0125620"; System.out.println(isValidIFSCode(str1)); // Test Case 2: String str2 = "SBIN0125"; System.out.println(isValidIFSCode(str2)); // Test Case 3: String str3 = "1234SBIN012"; System.out.println(isValidIFSCode(str3)); // Test Case 4: String str4 = "SBIN7125620"; System.out.println(isValidIFSCode(str4)); }}
# Python3 program to validate# IFSC (Indian Financial System) Code # using regular expressionimport re # Function to validate# IFSC (Indian Financial System) Code# using regular expression.def isValidIFSCode(str): # Regex to check valid IFSC Code. regex = "^[A-Z]{4}0[A-Z0-9]{6}$" # Compile the ReGex p = re.compile(regex) # If the string is empty # return false if (str == None): return False # Return if the string # matched the ReGex if(re.search(p, str)): return True else: return False # Driver code # Test Case 1:str1 = "SBIN0125620"print(isValidIFSCode(str1)) # Test Case 2:str2 = "SBIN0125"print(isValidIFSCode(str2)) # Test Case 3:str3 = "1234SBIN012"print(isValidIFSCode(str3)) # Test Case 4:str4 = "SBIN7125620"print(isValidIFSCode(str4)) # This code is contributed by avanitrachhadiya2155
true
false
false
false
Using String.matches() method
This method tells whether or not this string matches the given regular expression. An invocation of this method of the form str.matches(regex) yields exactly the same result as the expression Pattern.matches(regex, str). Pattern.compile(regex) compiles the pattern so that when you execute Matcher.matches(), the pattern is not recompiled again and again. Pattern.compile pre compiles it. However, if you use string.matches, it compiles the pattern every time you execute this line. So, it is better to use Pattern.compile().
Java
// Java program to validate// IFSC (Indian Financial System) Code// using regular expression.class GFG { // Function to validate // IFSC (Indian Financial System) Code // using regular expression. public static boolean isValidIFSCode(String str) { // Regex to check valid IFSC Code. String regex = "^[A-Z]{4}0[A-Z0-9]{6}$"; return str.trim().matches(regex); } // Driver Code. public static void main(String args[]) { // Test Case 1: String str1 = "SBIN0125620"; System.out.println(isValidIFSCode(str1)); // Test Case 2: String str2 = "SBIN0125"; System.out.println(isValidIFSCode(str2)); // Test Case 3: String str3 = "1234SBIN012"; System.out.println(isValidIFSCode(str3)); // Test Case 4: String str4 = "SBIN7125620"; System.out.println(isValidIFSCode(str4)); }}
true
false
false
false
avanitrachhadiya2155
yuvraj_chandra
subho57
CPP-regex
java-regular-expression
regular-expression
Pattern Searching
Strings
Strings
Pattern Searching
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
|
[
{
"code": null,
"e": 53,
"s": 25,
"text": "\n25 May, 2021"
},
{
"code": null,
"e": 286,
"s": 53,
"text": "Given string str, the task is to check whether the given string is a valid IFSC (Indian Financial System) Code or not by using Regular Expression. The valid IFSC (Indian Financial System) Code must satisfy the following conditions: "
},
{
"code": null,
"e": 476,
"s": 286,
"text": "It should be 11 characters long.The first four characters should be upper case alphabets.The fifth character should be 0.The last six characters usually numeric, but can also be alphabetic."
},
{
"code": null,
"e": 509,
"s": 476,
"text": "It should be 11 characters long."
},
{
"code": null,
"e": 567,
"s": 509,
"text": "The first four characters should be upper case alphabets."
},
{
"code": null,
"e": 600,
"s": 567,
"text": "The fifth character should be 0."
},
{
"code": null,
"e": 669,
"s": 600,
"text": "The last six characters usually numeric, but can also be alphabetic."
},
{
"code": null,
"e": 680,
"s": 669,
"text": "Examples: "
},
{
"code": null,
"e": 1177,
"s": 680,
"text": "Input: str = “SBIN0125620”; Output: true Explanation: The given string satisfies all the above-mentioned conditions. Therefore, it is a valid IFSC (Indian Financial System) Code.Input: str = “SBIN0125”; Output: false Explanation: The given string has 8 characters. Therefore it is not a valid IFSC (Indian Financial System) Code.Input: str = “1234SBIN012”; Output: false Explanation: The given string doesn’t starts with alphabets. Therefore it is not a valid IFSC (Indian Financial System) Code."
},
{
"code": null,
"e": 1308,
"s": 1177,
"text": "Approach: The idea is to use Regular Expression to solve this problem. The following steps can be followed to compute the answer. "
},
{
"code": null,
"e": 1324,
"s": 1308,
"text": "Get the String."
},
{
"code": null,
"e": 1423,
"s": 1324,
"text": "Create a regular expression to check valid IFSC (Indian Financial System) Code as mentioned below:"
},
{
"code": null,
"e": 1457,
"s": 1423,
"text": "regex = \"^[A-Z]{4}0[A-Z0-9]{6}$\";"
},
{
"code": null,
"e": 1756,
"s": 1457,
"text": "Where: ^ represents the starting of the string.[A-Z]{4} represents the first four characters should be upper case alphabets.0 represents the fifth character should be 0.[A-Z0-9]{6} represents the next six characters usually numeric, but can also be alphabetic.$ represents the ending of the string."
},
{
"code": null,
"e": 1797,
"s": 1756,
"text": "^ represents the starting of the string."
},
{
"code": null,
"e": 1875,
"s": 1797,
"text": "[A-Z]{4} represents the first four characters should be upper case alphabets."
},
{
"code": null,
"e": 1921,
"s": 1875,
"text": "0 represents the fifth character should be 0."
},
{
"code": null,
"e": 2013,
"s": 1921,
"text": "[A-Z0-9]{6} represents the next six characters usually numeric, but can also be alphabetic."
},
{
"code": null,
"e": 2052,
"s": 2013,
"text": "$ represents the ending of the string."
},
{
"code": null,
"e": 2104,
"s": 2052,
"text": "Below is the implementation of the above approach: "
},
{
"code": null,
"e": 2108,
"s": 2104,
"text": "C++"
},
{
"code": null,
"e": 2113,
"s": 2108,
"text": "Java"
},
{
"code": null,
"e": 2121,
"s": 2113,
"text": "Python3"
},
{
"code": "// C++ program to validate the// IFSC (Indian Financial System) Code using Regular Expression#include <iostream>#include <regex>using namespace std; // Function to validate the IFSC (Indian Financial System) Code.bool isValidIFSCode(string str){ // Regex to check valid IFSC (Indian Financial System) Code. const regex pattern(\"^[A-Z]{4}0[A-Z0-9]{6}$\"); // If the IFSC (Indian Financial System) Code // is empty return false if (str.empty()) { return false; } // Return true if the IFSC (Indian Financial System) Code // matched the ReGex if(regex_match(str, pattern)) { return true; } else { return false; }} // Driver Codeint main(){ // Test Case 1: string str1 = \"SBIN0125620\"; cout << boolalpha << isValidIFSCode(str1) << endl; // Test Case 2: string str2 = \"SBIN0125\"; cout << boolalpha << isValidIFSCode(str2) << endl; // Test Case 3: string str3 = \"1234SBIN012\"; cout << boolalpha << isValidIFSCode(str3) << endl; // Test Case 4: string str4 = \"SBIN7125620\"; cout << boolalpha <<isValidIFSCode(str4) << endl; return 0;} // This code is contributed by yuvraj_chandra",
"e": 3243,
"s": 2121,
"text": null
},
{
"code": "// Java program to validate// IFSC (Indian Financial System) Code// using regular expression.import java.util.regex.*;class GFG { // Function to validate // IFSC (Indian Financial System) Code // using regular expression. public static boolean isValidIFSCode(String str) { // Regex to check valid IFSC Code. String regex = \"^[A-Z]{4}0[A-Z0-9]{6}$\"; // Compile the ReGex Pattern p = Pattern.compile(regex); // If the string is empty // return false if (str == null) { return false; } // Pattern class contains matcher() // method to find matching between // the given string and // the regular expression. Matcher m = p.matcher(str); // Return if the string // matched the ReGex return m.matches(); } // Driver Code. public static void main(String args[]) { // Test Case 1: String str1 = \"SBIN0125620\"; System.out.println(isValidIFSCode(str1)); // Test Case 2: String str2 = \"SBIN0125\"; System.out.println(isValidIFSCode(str2)); // Test Case 3: String str3 = \"1234SBIN012\"; System.out.println(isValidIFSCode(str3)); // Test Case 4: String str4 = \"SBIN7125620\"; System.out.println(isValidIFSCode(str4)); }}",
"e": 4595,
"s": 3243,
"text": null
},
{
"code": "# Python3 program to validate# IFSC (Indian Financial System) Code # using regular expressionimport re # Function to validate# IFSC (Indian Financial System) Code# using regular expression.def isValidIFSCode(str): # Regex to check valid IFSC Code. regex = \"^[A-Z]{4}0[A-Z0-9]{6}$\" # Compile the ReGex p = re.compile(regex) # If the string is empty # return false if (str == None): return False # Return if the string # matched the ReGex if(re.search(p, str)): return True else: return False # Driver code # Test Case 1:str1 = \"SBIN0125620\"print(isValidIFSCode(str1)) # Test Case 2:str2 = \"SBIN0125\"print(isValidIFSCode(str2)) # Test Case 3:str3 = \"1234SBIN012\"print(isValidIFSCode(str3)) # Test Case 4:str4 = \"SBIN7125620\"print(isValidIFSCode(str4)) # This code is contributed by avanitrachhadiya2155",
"e": 5459,
"s": 4595,
"text": null
},
{
"code": null,
"e": 5483,
"s": 5459,
"text": "true\nfalse\nfalse\nfalse\n"
},
{
"code": null,
"e": 5513,
"s": 5483,
"text": "Using String.matches() method"
},
{
"code": null,
"e": 6039,
"s": 5513,
"text": "This method tells whether or not this string matches the given regular expression. An invocation of this method of the form str.matches(regex) yields exactly the same result as the expression Pattern.matches(regex, str). Pattern.compile(regex) compiles the pattern so that when you execute Matcher.matches(), the pattern is not recompiled again and again. Pattern.compile pre compiles it. However, if you use string.matches, it compiles the pattern every time you execute this line. So, it is better to use Pattern.compile()."
},
{
"code": null,
"e": 6044,
"s": 6039,
"text": "Java"
},
{
"code": "// Java program to validate// IFSC (Indian Financial System) Code// using regular expression.class GFG { // Function to validate // IFSC (Indian Financial System) Code // using regular expression. public static boolean isValidIFSCode(String str) { // Regex to check valid IFSC Code. String regex = \"^[A-Z]{4}0[A-Z0-9]{6}$\"; return str.trim().matches(regex); } // Driver Code. public static void main(String args[]) { // Test Case 1: String str1 = \"SBIN0125620\"; System.out.println(isValidIFSCode(str1)); // Test Case 2: String str2 = \"SBIN0125\"; System.out.println(isValidIFSCode(str2)); // Test Case 3: String str3 = \"1234SBIN012\"; System.out.println(isValidIFSCode(str3)); // Test Case 4: String str4 = \"SBIN7125620\"; System.out.println(isValidIFSCode(str4)); }}",
"e": 6950,
"s": 6044,
"text": null
},
{
"code": null,
"e": 6974,
"s": 6950,
"text": "true\nfalse\nfalse\nfalse\n"
},
{
"code": null,
"e": 6995,
"s": 6974,
"text": "avanitrachhadiya2155"
},
{
"code": null,
"e": 7010,
"s": 6995,
"text": "yuvraj_chandra"
},
{
"code": null,
"e": 7018,
"s": 7010,
"text": "subho57"
},
{
"code": null,
"e": 7028,
"s": 7018,
"text": "CPP-regex"
},
{
"code": null,
"e": 7052,
"s": 7028,
"text": "java-regular-expression"
},
{
"code": null,
"e": 7071,
"s": 7052,
"text": "regular-expression"
},
{
"code": null,
"e": 7089,
"s": 7071,
"text": "Pattern Searching"
},
{
"code": null,
"e": 7097,
"s": 7089,
"text": "Strings"
},
{
"code": null,
"e": 7105,
"s": 7097,
"text": "Strings"
},
{
"code": null,
"e": 7123,
"s": 7105,
"text": "Pattern Searching"
}
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.