title
stringlengths 3
221
| text
stringlengths 17
477k
| parsed
listlengths 0
3.17k
|
---|---|---|
Numbers in range [L, R] such that the count of their divisors is both even and prime | 06 May, 2021
Given a range [L, R], the task is to find the numbers from the range which have the count of their divisors as even as well as prime. Then, print the count of the numbers found. The values of L and R are less than 10^6 and L< R.Examples:
Input: L=3, R=9
Output: Count = 3
Explanation: The numbers are 3, 5, 7
Input : L=3, R=17
Output : Count: 6
The only number that is prime, as well as even, is ‘2’.So, we need to find all the numbers within the given range that have exactly 2 divisors, i.e. prime numbers.
The only number that is prime, as well as even, is ‘2’.
So, we need to find all the numbers within the given range that have exactly 2 divisors, i.e. prime numbers.
A simple approach:
Start a loop from ‘l’ to ‘r’ and check whether the number is prime(it will take more time for bigger range).If the number is prime then increment the count variable.At the end, print the value of count.
Start a loop from ‘l’ to ‘r’ and check whether the number is prime(it will take more time for bigger range).
If the number is prime then increment the count variable.
At the end, print the value of count.
An efficient approach:
We have to count the prime numbers in range [L, R].
First, create a sieve which will help in determining whether the number is prime or not in O(1) time.
Then, create a prefix array to store the count of prime numbers where, element at index ‘i’ holds the count of the prime numbers from ‘1’ to ‘i’.
Now, if we want to find the count of prime numbers in range [L, R], the count will be (sum[R] – sum[L-1])
Finally, print the result i.e. (sum[R] – sum[L-1])
Below is the implementation of the above approach:
C++
Java
Python 3
C#
PHP
Javascript
// C++ implementation of the approach#include <bits/stdc++.h>using namespace std;#define MAX 1000000 // stores whether the number is prime or notbool prime[MAX + 1]; // stores the count of prime numbers// less than or equal to the indexint sum[MAX + 1]; // create the sievevoid SieveOfEratosthenes(){ // Create a boolean array "prime[0..n]" and initialize // all the entries as true. A value in prime[i] will // finally be false if 'i' is Not a prime, else true. memset(prime, true, sizeof(prime)); memset(sum, 0, sizeof(sum)); prime[1] = false; for (int p = 2; p * p <= MAX; p++) { // If prime[p] is not changed, then it is a prime if (prime[p]) { // Update all multiples of p for (int i = p * 2; i <= MAX; i += p) prime[i] = false; } } // stores the prefix sum of number // of primes less than or equal to 'i' for (int i = 1; i <= MAX; i++) { if (prime[i] == true) sum[i] = 1; sum[i] += sum[i - 1]; }} // Driver codeint main(){ // create the sieve SieveOfEratosthenes(); // 'l' and 'r' are the lower and upper bounds // of the range int l = 3, r = 9; // get the value of count int c = (sum[r] - sum[l - 1]); // display the count cout << "Count: " << c << endl; return 0;}
// Java implementation of the approachclass GFG{ static final int MAX=1000000; // stores whether the number is prime or not static boolean []prime=new boolean[MAX + 1]; // stores the count of prime numbers // less than or equal to the index static int []sum=new int[MAX + 1]; // create the sieve static void SieveOfEratosthenes() { // Create a boolean array "prime[0..n]" and initialize // all the entries as true. A value in prime[i] will // finally be false if 'i' is Not a prime, else true. for(int i=0;i<=MAX;i++) prime[i]=true; for(int i=0;i<=MAX;i++) sum[i]=0; prime[1] = false; for (int p = 2; p * p <= MAX; p++) { // If prime[p] is not changed, then it is a prime if (prime[p]) { // Update all multiples of p for (int i = p * 2; i <= MAX; i += p) prime[i] = false; } } // stores the prefix sum of number // of primes less than or equal to 'i' for (int i = 1; i <= MAX; i++) { if (prime[i] == true) sum[i] = 1; sum[i] += sum[i - 1]; } } // Driver code public static void main(String []args) { // create the sieve SieveOfEratosthenes(); // 'l' and 'r' are the lower and upper bounds // of the range int l = 3, r = 9; // get the value of count int c = (sum[r] - sum[l - 1]); // display the count System.out.println("Count: " + c); } }
# Python 3 implementation of the approachMAX = 1000000 # stores whether the number is prime or notprime = [True] * (MAX + 1) # stores the count of prime numbers# less than or equal to the indexsum = [0] * (MAX + 1) # create the sievedef SieveOfEratosthenes(): prime[1] = False p = 2 while p * p <= MAX: # If prime[p] is not changed, # then it is a prime if (prime[p]): # Update all multiples of p i = p * 2 while i <= MAX: prime[i] = False i += p p += 1 # stores the prefix sum of number # of primes less than or equal to 'i' for i in range(1, MAX + 1): if (prime[i] == True): sum[i] = 1 sum[i] += sum[i - 1] # Driver codeif __name__ == "__main__": # create the sieve SieveOfEratosthenes() # 'l' and 'r' are the lower and # upper bounds of the range l = 3 r = 9 # get the value of count c = (sum[r] - sum[l - 1]) # display the count print("Count:", c) # This code is contributed by ita_c
// C# implementation of the approach using System;class GFG{ static int MAX=1000000; // stores whether the number is prime or not static bool []prime=new bool[MAX + 1]; // stores the count of prime numbers // less than or equal to the index static int []sum=new int[MAX + 1]; // create the sieve static void SieveOfEratosthenes() { // Create a boolean array "prime[0..n]" and initialize // all the entries as true. A value in prime[i] will // finally be false if 'i' is Not a prime, else true. for(int i=0;i<=MAX;i++) prime[i]=true; for(int i=0;i<=MAX;i++) sum[i]=0; prime[1] = false; for (int p = 2; p * p <= MAX; p++) { // If prime[p] is not changed, then it is a prime if (prime[p]) { // Update all multiples of p for (int i = p * 2; i <= MAX; i += p) prime[i] = false; } } // stores the prefix sum of number // of primes less than or equal to 'i' for (int i = 1; i <= MAX; i++) { if (prime[i] == true) sum[i] = 1; sum[i] += sum[i - 1]; } } // Driver code public static void Main() { // create the sieve SieveOfEratosthenes(); // 'l' and 'r' are the lower and upper bounds // of the range int l = 3, r = 9; // get the value of count int c = (sum[r] - sum[l - 1]); // display the count Console.WriteLine("Count: " + c); } }
<?php// PHP implementation of the approach$MAX = 100000; // Create a boolean array "prime[0..n]"// and initialize all the entries as// true. A value in prime[i] will finally// be false if 'i' is Not a prime, else true. // stores whether the number// is prime or not$prime = array_fill(0, $MAX + 1, true); // stores the count of prime numbers// less than or equal to the index$sum = array_fill(0, $MAX + 1, 0); // create the sievefunction SieveOfEratosthenes(){ global $MAX, $sum, $prime; $prime[1] = false; for ($p = 2; $p * $p <= $MAX; $p++) { // If prime[p] is not changed, // then it is a prime if ($prime[$p]) { // Update all multiples of p for ($i = $p * 2; $i <= $MAX; $i += $p) $prime[$i] = false; } } // stores the prefix sum of number // of primes less than or equal to 'i' for ($i = 1; $i <= $MAX; $i++) { if ($prime[$i] == true) $sum[$i] = 1; $sum[$i] += $sum[$i - 1]; }} // Driver code // create the sieveSieveOfEratosthenes(); // 'l' and 'r' are the lower// and upper bounds of the range$l = 3;$r = 9; // get the value of count$c = ($sum[$r] - $sum[$l - 1]); // display the countecho "Count: " . $c . "\n"; // This code is contributed by mits?>
<script> // Javascript implementation of the approachvar MAX = 1000000; // stores whether the number is prime or notvar prime = Array(MAX+1).fill(true); // stores the count of prime numbers// less than or equal to the indexvar sum = Array(MAX+1).fill(0); // create the sievefunction SieveOfEratosthenes(){ // Create a boolean array "prime[0..n]" and initialize // all the entries as true. A value in prime[i] will // finally be false if 'i' is Not a prime, else true. prime[1] = false; for (var p = 2; p * p <= MAX; p++) { // If prime[p] is not changed, then it is a prime if (prime[p]) { // Update all multiples of p for (var i = p * 2; i <= MAX; i += p) prime[i] = false; } } // stores the prefix sum of number // of primes less than or equal to 'i' for (var i = 1; i <= MAX; i++) { if (prime[i] == true) sum[i] = 1; sum[i] += sum[i - 1]; }} // Driver code// create the sieveSieveOfEratosthenes();// 'l' and 'r' are the lower and upper bounds// of the rangevar l = 3, r = 9;// get the value of countvar c = (sum[r] - sum[l - 1]);// display the countdocument.write( "Count: " + c ); </script>
Count: 3
ihritik
Mithun Kumar
ukasp
itsok
Prime Number
sieve
Competitive Programming
Mathematical
Mathematical
Prime Number
sieve
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here. | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n06 May, 2021"
},
{
"code": null,
"e": 268,
"s": 28,
"text": "Given a range [L, R], the task is to find the numbers from the range which have the count of their divisors as even as well as prime. Then, print the count of the numbers found. The values of L and R are less than 10^6 and L< R.Examples: "
},
{
"code": null,
"e": 377,
"s": 268,
"text": "Input: L=3, R=9\nOutput: Count = 3\nExplanation: The numbers are 3, 5, 7 \n\nInput : L=3, R=17\nOutput : Count: 6"
},
{
"code": null,
"e": 545,
"s": 381,
"text": "The only number that is prime, as well as even, is ‘2’.So, we need to find all the numbers within the given range that have exactly 2 divisors, i.e. prime numbers."
},
{
"code": null,
"e": 601,
"s": 545,
"text": "The only number that is prime, as well as even, is ‘2’."
},
{
"code": null,
"e": 710,
"s": 601,
"text": "So, we need to find all the numbers within the given range that have exactly 2 divisors, i.e. prime numbers."
},
{
"code": null,
"e": 731,
"s": 710,
"text": "A simple approach: "
},
{
"code": null,
"e": 934,
"s": 731,
"text": "Start a loop from ‘l’ to ‘r’ and check whether the number is prime(it will take more time for bigger range).If the number is prime then increment the count variable.At the end, print the value of count."
},
{
"code": null,
"e": 1043,
"s": 934,
"text": "Start a loop from ‘l’ to ‘r’ and check whether the number is prime(it will take more time for bigger range)."
},
{
"code": null,
"e": 1101,
"s": 1043,
"text": "If the number is prime then increment the count variable."
},
{
"code": null,
"e": 1139,
"s": 1101,
"text": "At the end, print the value of count."
},
{
"code": null,
"e": 1164,
"s": 1139,
"text": "An efficient approach: "
},
{
"code": null,
"e": 1216,
"s": 1164,
"text": "We have to count the prime numbers in range [L, R]."
},
{
"code": null,
"e": 1318,
"s": 1216,
"text": "First, create a sieve which will help in determining whether the number is prime or not in O(1) time."
},
{
"code": null,
"e": 1464,
"s": 1318,
"text": "Then, create a prefix array to store the count of prime numbers where, element at index ‘i’ holds the count of the prime numbers from ‘1’ to ‘i’."
},
{
"code": null,
"e": 1570,
"s": 1464,
"text": "Now, if we want to find the count of prime numbers in range [L, R], the count will be (sum[R] – sum[L-1])"
},
{
"code": null,
"e": 1621,
"s": 1570,
"text": "Finally, print the result i.e. (sum[R] – sum[L-1])"
},
{
"code": null,
"e": 1674,
"s": 1621,
"text": "Below is the implementation of the above approach: "
},
{
"code": null,
"e": 1678,
"s": 1674,
"text": "C++"
},
{
"code": null,
"e": 1683,
"s": 1678,
"text": "Java"
},
{
"code": null,
"e": 1692,
"s": 1683,
"text": "Python 3"
},
{
"code": null,
"e": 1695,
"s": 1692,
"text": "C#"
},
{
"code": null,
"e": 1699,
"s": 1695,
"text": "PHP"
},
{
"code": null,
"e": 1710,
"s": 1699,
"text": "Javascript"
},
{
"code": "// C++ implementation of the approach#include <bits/stdc++.h>using namespace std;#define MAX 1000000 // stores whether the number is prime or notbool prime[MAX + 1]; // stores the count of prime numbers// less than or equal to the indexint sum[MAX + 1]; // create the sievevoid SieveOfEratosthenes(){ // Create a boolean array \"prime[0..n]\" and initialize // all the entries as true. A value in prime[i] will // finally be false if 'i' is Not a prime, else true. memset(prime, true, sizeof(prime)); memset(sum, 0, sizeof(sum)); prime[1] = false; for (int p = 2; p * p <= MAX; p++) { // If prime[p] is not changed, then it is a prime if (prime[p]) { // Update all multiples of p for (int i = p * 2; i <= MAX; i += p) prime[i] = false; } } // stores the prefix sum of number // of primes less than or equal to 'i' for (int i = 1; i <= MAX; i++) { if (prime[i] == true) sum[i] = 1; sum[i] += sum[i - 1]; }} // Driver codeint main(){ // create the sieve SieveOfEratosthenes(); // 'l' and 'r' are the lower and upper bounds // of the range int l = 3, r = 9; // get the value of count int c = (sum[r] - sum[l - 1]); // display the count cout << \"Count: \" << c << endl; return 0;}",
"e": 3042,
"s": 1710,
"text": null
},
{
"code": "// Java implementation of the approachclass GFG{ static final int MAX=1000000; // stores whether the number is prime or not static boolean []prime=new boolean[MAX + 1]; // stores the count of prime numbers // less than or equal to the index static int []sum=new int[MAX + 1]; // create the sieve static void SieveOfEratosthenes() { // Create a boolean array \"prime[0..n]\" and initialize // all the entries as true. A value in prime[i] will // finally be false if 'i' is Not a prime, else true. for(int i=0;i<=MAX;i++) prime[i]=true; for(int i=0;i<=MAX;i++) sum[i]=0; prime[1] = false; for (int p = 2; p * p <= MAX; p++) { // If prime[p] is not changed, then it is a prime if (prime[p]) { // Update all multiples of p for (int i = p * 2; i <= MAX; i += p) prime[i] = false; } } // stores the prefix sum of number // of primes less than or equal to 'i' for (int i = 1; i <= MAX; i++) { if (prime[i] == true) sum[i] = 1; sum[i] += sum[i - 1]; } } // Driver code public static void main(String []args) { // create the sieve SieveOfEratosthenes(); // 'l' and 'r' are the lower and upper bounds // of the range int l = 3, r = 9; // get the value of count int c = (sum[r] - sum[l - 1]); // display the count System.out.println(\"Count: \" + c); } }",
"e": 4700,
"s": 3042,
"text": null
},
{
"code": "# Python 3 implementation of the approachMAX = 1000000 # stores whether the number is prime or notprime = [True] * (MAX + 1) # stores the count of prime numbers# less than or equal to the indexsum = [0] * (MAX + 1) # create the sievedef SieveOfEratosthenes(): prime[1] = False p = 2 while p * p <= MAX: # If prime[p] is not changed, # then it is a prime if (prime[p]): # Update all multiples of p i = p * 2 while i <= MAX: prime[i] = False i += p p += 1 # stores the prefix sum of number # of primes less than or equal to 'i' for i in range(1, MAX + 1): if (prime[i] == True): sum[i] = 1 sum[i] += sum[i - 1] # Driver codeif __name__ == \"__main__\": # create the sieve SieveOfEratosthenes() # 'l' and 'r' are the lower and # upper bounds of the range l = 3 r = 9 # get the value of count c = (sum[r] - sum[l - 1]) # display the count print(\"Count:\", c) # This code is contributed by ita_c",
"e": 5783,
"s": 4700,
"text": null
},
{
"code": "// C# implementation of the approach using System;class GFG{ static int MAX=1000000; // stores whether the number is prime or not static bool []prime=new bool[MAX + 1]; // stores the count of prime numbers // less than or equal to the index static int []sum=new int[MAX + 1]; // create the sieve static void SieveOfEratosthenes() { // Create a boolean array \"prime[0..n]\" and initialize // all the entries as true. A value in prime[i] will // finally be false if 'i' is Not a prime, else true. for(int i=0;i<=MAX;i++) prime[i]=true; for(int i=0;i<=MAX;i++) sum[i]=0; prime[1] = false; for (int p = 2; p * p <= MAX; p++) { // If prime[p] is not changed, then it is a prime if (prime[p]) { // Update all multiples of p for (int i = p * 2; i <= MAX; i += p) prime[i] = false; } } // stores the prefix sum of number // of primes less than or equal to 'i' for (int i = 1; i <= MAX; i++) { if (prime[i] == true) sum[i] = 1; sum[i] += sum[i - 1]; } } // Driver code public static void Main() { // create the sieve SieveOfEratosthenes(); // 'l' and 'r' are the lower and upper bounds // of the range int l = 3, r = 9; // get the value of count int c = (sum[r] - sum[l - 1]); // display the count Console.WriteLine(\"Count: \" + c); } }",
"e": 7428,
"s": 5783,
"text": null
},
{
"code": "<?php// PHP implementation of the approach$MAX = 100000; // Create a boolean array \"prime[0..n]\"// and initialize all the entries as// true. A value in prime[i] will finally// be false if 'i' is Not a prime, else true. // stores whether the number// is prime or not$prime = array_fill(0, $MAX + 1, true); // stores the count of prime numbers// less than or equal to the index$sum = array_fill(0, $MAX + 1, 0); // create the sievefunction SieveOfEratosthenes(){ global $MAX, $sum, $prime; $prime[1] = false; for ($p = 2; $p * $p <= $MAX; $p++) { // If prime[p] is not changed, // then it is a prime if ($prime[$p]) { // Update all multiples of p for ($i = $p * 2; $i <= $MAX; $i += $p) $prime[$i] = false; } } // stores the prefix sum of number // of primes less than or equal to 'i' for ($i = 1; $i <= $MAX; $i++) { if ($prime[$i] == true) $sum[$i] = 1; $sum[$i] += $sum[$i - 1]; }} // Driver code // create the sieveSieveOfEratosthenes(); // 'l' and 'r' are the lower// and upper bounds of the range$l = 3;$r = 9; // get the value of count$c = ($sum[$r] - $sum[$l - 1]); // display the countecho \"Count: \" . $c . \"\\n\"; // This code is contributed by mits?>",
"e": 8718,
"s": 7428,
"text": null
},
{
"code": "<script> // Javascript implementation of the approachvar MAX = 1000000; // stores whether the number is prime or notvar prime = Array(MAX+1).fill(true); // stores the count of prime numbers// less than or equal to the indexvar sum = Array(MAX+1).fill(0); // create the sievefunction SieveOfEratosthenes(){ // Create a boolean array \"prime[0..n]\" and initialize // all the entries as true. A value in prime[i] will // finally be false if 'i' is Not a prime, else true. prime[1] = false; for (var p = 2; p * p <= MAX; p++) { // If prime[p] is not changed, then it is a prime if (prime[p]) { // Update all multiples of p for (var i = p * 2; i <= MAX; i += p) prime[i] = false; } } // stores the prefix sum of number // of primes less than or equal to 'i' for (var i = 1; i <= MAX; i++) { if (prime[i] == true) sum[i] = 1; sum[i] += sum[i - 1]; }} // Driver code// create the sieveSieveOfEratosthenes();// 'l' and 'r' are the lower and upper bounds// of the rangevar l = 3, r = 9;// get the value of countvar c = (sum[r] - sum[l - 1]);// display the countdocument.write( \"Count: \" + c ); </script>",
"e": 9931,
"s": 8718,
"text": null
},
{
"code": null,
"e": 9940,
"s": 9931,
"text": "Count: 3"
},
{
"code": null,
"e": 9950,
"s": 9942,
"text": "ihritik"
},
{
"code": null,
"e": 9963,
"s": 9950,
"text": "Mithun Kumar"
},
{
"code": null,
"e": 9969,
"s": 9963,
"text": "ukasp"
},
{
"code": null,
"e": 9975,
"s": 9969,
"text": "itsok"
},
{
"code": null,
"e": 9988,
"s": 9975,
"text": "Prime Number"
},
{
"code": null,
"e": 9994,
"s": 9988,
"text": "sieve"
},
{
"code": null,
"e": 10018,
"s": 9994,
"text": "Competitive Programming"
},
{
"code": null,
"e": 10031,
"s": 10018,
"text": "Mathematical"
},
{
"code": null,
"e": 10044,
"s": 10031,
"text": "Mathematical"
},
{
"code": null,
"e": 10057,
"s": 10044,
"text": "Prime Number"
},
{
"code": null,
"e": 10063,
"s": 10057,
"text": "sieve"
}
] |
Zoho Interview | Set 5 (On-Campus Drive) | 22 Jul, 2019
Round 1:Questions based on aptitude (10) and c program output (20)Time 2hr.
Round 2:5 problem given we have to solve at least 3Program 1:Help john to find new friends in social networkInput:3Mani 3 ram raj gunaRam 2 kumar KishoreMughil 3 praveen Naveen Ramesh
Output:Raj guna kumar Kishore praveen Naveen Ramesh
Program 2:Input:With the starting and ending time of work given find the minimum no of workers needed
Start time end time
1230 0130
1200 0100
1600 1700
Output:2
Program 3:Find the union intersection of two list and also find except (remove even elements from list1 and odd elements from list2)Input
List 1: 1,3,4,5,6,8,9
List 2: 1, 5,8,9,2
Union: 1, 3,4,5,6,8,9,2
Intersection: 1,5,8,9
Except: 1, 3, 5,9,8,2
Program 4:
Rotate the matrix elements
For 3*3 matrix
Input
1 2 3
4 5 6
7 8 9
Output:
4 1 2
7 5 3
8 9 6
For 4*4 matrix
Input:
1 2 3 4
5 6 7 8
9 10 11 12
13 14 15 16
Output:
5 1 2 3
9 10 6 4
13 11 7 8
14 15 16 12
Program 5:Find the largest possible prime number with given noInput54691Output:9461
Round 3:For one batch of peopleBasic programs like pattern printing1223334444And12 43 5 76 8 10 12
Others had app developmentScenario: text editorOnly 40 characters per line and words should be wrapped if they brakeAlso perform insert delete operations
Round 4:Tech hr: Topics revolved around OOPS and java thread and Ubuntu commands.
Round 5:General hr: As usual stuffs like personal info and about projects and why zoho?Good luck friendsThanks for geeks for geeks team it helped me a lot.
If you like GeeksforGeeks and would like to contribute, you can also write an article and mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Zoho
Interview Experiences
Zoho
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here. | [
{
"code": null,
"e": 54,
"s": 26,
"text": "\n22 Jul, 2019"
},
{
"code": null,
"e": 130,
"s": 54,
"text": "Round 1:Questions based on aptitude (10) and c program output (20)Time 2hr."
},
{
"code": null,
"e": 314,
"s": 130,
"text": "Round 2:5 problem given we have to solve at least 3Program 1:Help john to find new friends in social networkInput:3Mani 3 ram raj gunaRam 2 kumar KishoreMughil 3 praveen Naveen Ramesh"
},
{
"code": null,
"e": 366,
"s": 314,
"text": "Output:Raj guna kumar Kishore praveen Naveen Ramesh"
},
{
"code": null,
"e": 468,
"s": 366,
"text": "Program 2:Input:With the starting and ending time of work given find the minimum no of workers needed"
},
{
"code": null,
"e": 559,
"s": 468,
"text": "Start time end time\n1230 0130\n1200 0100\n1600 1700"
},
{
"code": null,
"e": 568,
"s": 559,
"text": "Output:2"
},
{
"code": null,
"e": 706,
"s": 568,
"text": "Program 3:Find the union intersection of two list and also find except (remove even elements from list1 and odd elements from list2)Input"
},
{
"code": null,
"e": 817,
"s": 706,
"text": "List 1: 1,3,4,5,6,8,9\nList 2: 1, 5,8,9,2\n\nUnion: 1, 3,4,5,6,8,9,2\nIntersection: 1,5,8,9\nExcept: 1, 3, 5,9,8,2 "
},
{
"code": null,
"e": 828,
"s": 817,
"text": "Program 4:"
},
{
"code": null,
"e": 1143,
"s": 828,
"text": "Rotate the matrix elements\nFor 3*3 matrix\nInput\n1 2 3\n4 5 6\n7 8 9\n\nOutput:\n4 1 2\n7 5 3\n8 9 6\n\nFor 4*4 matrix\nInput:\n1 2 3 4 \n5 6 7 8\n9 10 11 12\n13 14 15 16\n\nOutput:\n5 1 2 3\n9 10 6 4\n13 11 7 8\n14 15 16 12"
},
{
"code": null,
"e": 1227,
"s": 1143,
"text": "Program 5:Find the largest possible prime number with given noInput54691Output:9461"
},
{
"code": null,
"e": 1326,
"s": 1227,
"text": "Round 3:For one batch of peopleBasic programs like pattern printing1223334444And12 43 5 76 8 10 12"
},
{
"code": null,
"e": 1480,
"s": 1326,
"text": "Others had app developmentScenario: text editorOnly 40 characters per line and words should be wrapped if they brakeAlso perform insert delete operations"
},
{
"code": null,
"e": 1562,
"s": 1480,
"text": "Round 4:Tech hr: Topics revolved around OOPS and java thread and Ubuntu commands."
},
{
"code": null,
"e": 1718,
"s": 1562,
"text": "Round 5:General hr: As usual stuffs like personal info and about projects and why zoho?Good luck friendsThanks for geeks for geeks team it helped me a lot."
},
{
"code": null,
"e": 1939,
"s": 1718,
"text": "If you like GeeksforGeeks and would like to contribute, you can also write an article and mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks."
},
{
"code": null,
"e": 1944,
"s": 1939,
"text": "Zoho"
},
{
"code": null,
"e": 1966,
"s": 1944,
"text": "Interview Experiences"
},
{
"code": null,
"e": 1971,
"s": 1966,
"text": "Zoho"
}
] |
Circular Queue or Ring Buffer. Python and C Implementation. | by Brian Ward | Towards Data Science | There are many different implementations of the circular queue all of which may be better suited for specific applications. This blog post is to help understand how a circular queue works along with its uses and advantages.
A Queue is a simple data structure that implements the FIFO (First-In-First-Out) ordering. This simply means that the first item added to your queue is the first one out. Just like a line or queue of customers at the deli, the first customer in line is the first to be served. A circular queue is essentially a queue with a maximum size or capacity which will continue to loop back over itself in a circular motion.
Ring Buffers are common data structures frequently used when the input and output to a data stream occur at different rates.
Buffering Data Streams
Computer Controlled Trafficking signal systems
Memory Management
CPU scheduling
Circular Queues offer a quick and clean way to store FIFO data with a maximum size.
Doesn’t use dynamic memory → No memory leaks
Conserves memory as we only store up to our capacity (opposed to a queue which could continue to grow if input outpaces output.)
Simple Implementation → easy to trust and test
Never has to reorganize / copy data around
All operations occur in constant time O(1)
Circular Queues can only store the pre-determined maximum number of elements.
Have to know the max size beforehand
There are two primary operations on a circular Queue :
1: Enqueue(item) : add item to the Queue.
if Queue.isfull() print "Queue is Full"else increase tail by 1 Queue[tail] = item size++
2: Dequeue(): return the item at the front (head) of the line and remove it.
if Queue.isEmpty() print "Queue is Empty"else tmp = Queue[head] increase head by 1 size-- return tmp
Note: We aren’t actually removing anything from the array, we are just increasing the head to point at the next item “in line”.
Let’s take a Look at how these operations look on an Array of size 6:
Notice how the tail wraps back around to zero as we enqueue our seventh item (35).
Notice how the head increases as we dequeue, but no values are removed from the array, they are only over-written as Enqueue( ) reaches that location in the array.
If we’re supposed to be increasing the head and the tail by 1 spot in the array how do we set it back to zero when we get to the end to ensure we keep looping through the array?
We could do something like this:
if (head + 1) = capacity head = 0else head = head + 1
There's really nothing wrong with that, however, there’s a much more elegant method using the modulo operator. The modulo operator (%) gives the remainder after division. When looking at the relationship between two integers a and b; a will be the product of b times some integer q plus some integer r :
a = b x q + r q : quotient = a div b r : remainder = a mod b
Let’s look at some quick examples:
a = b x q + r a % b = r5 = 3 x 1 + 2 5 % 3 = 22 = 5 x 0 + 2 2 % 5 = 29 = 3 x 3 + 0 9 % 3 = 09 = 2 X 4 + 1 9 % 2 = 1
Note: This is the basis of Euclid’s Algorithm for determining GCD.
Let's apply it to our circular queue implementation:
self.head = (self.head + 1) % self.capacity
Now every time we get to the end of the array we will automatically start back at zero. Beautiful! Let’s see what this would look like with a circular queue of size 6 :
0 % 6 = 01 % 6 = 12 % 6 = 23 % 6 = 34 % 6 = 45 % 6 = 56 % 6 = 0...
This is a simple implementation where we only have the two primary methods, Enqueue(item), Dequeue( ), as well as a display( ) method which I think is helpful in understanding. Many other implementations might also include :
isFull( ): true if queue is full, false otherwise.
isEmpty( ): true if queue is empty, false otherwise.
peek( ) : see what is at the head of the queue without “removing” it.
etc..
Many other implementations won’t store the current size and will determine isFull( ) and isEmpty( ) by simply comparing the head and tail. I think storing the size makes it easier to follow exactly what is going on.
You can see the C implementation is very similar to the Python implementation with the addition of the fun C stuff like structs and memory allocation. Here we also need a create_queue( ) function as we are using structs. We also use some helper functions that we talked about earlier like isFull( ), isEmpty( ), etc..
What are some boundary cases?
What assumptions are we making?
How would we implement the circular queue to have the ability to change capacity on the fly? How would this affect our advantages and disadvantages of the circular queue?
Both of these implementations won’t allow you to enqueue a new item if the queue is full. Can you think of some applications of a circular queue where this might be bad? How would we change the implementations to allow for over-writing?
I would encourage anyone reading this to look at other implementations around the web and compare them as well as think about different applications of the circular queue. I am still a student myself and still have a lot to learn. Nevertheless, I hope this might have been helpful for some of you learning about circular queues for the first time. Thanks for reading! | [
{
"code": null,
"e": 396,
"s": 172,
"text": "There are many different implementations of the circular queue all of which may be better suited for specific applications. This blog post is to help understand how a circular queue works along with its uses and advantages."
},
{
"code": null,
"e": 812,
"s": 396,
"text": "A Queue is a simple data structure that implements the FIFO (First-In-First-Out) ordering. This simply means that the first item added to your queue is the first one out. Just like a line or queue of customers at the deli, the first customer in line is the first to be served. A circular queue is essentially a queue with a maximum size or capacity which will continue to loop back over itself in a circular motion."
},
{
"code": null,
"e": 937,
"s": 812,
"text": "Ring Buffers are common data structures frequently used when the input and output to a data stream occur at different rates."
},
{
"code": null,
"e": 960,
"s": 937,
"text": "Buffering Data Streams"
},
{
"code": null,
"e": 1007,
"s": 960,
"text": "Computer Controlled Trafficking signal systems"
},
{
"code": null,
"e": 1025,
"s": 1007,
"text": "Memory Management"
},
{
"code": null,
"e": 1040,
"s": 1025,
"text": "CPU scheduling"
},
{
"code": null,
"e": 1124,
"s": 1040,
"text": "Circular Queues offer a quick and clean way to store FIFO data with a maximum size."
},
{
"code": null,
"e": 1169,
"s": 1124,
"text": "Doesn’t use dynamic memory → No memory leaks"
},
{
"code": null,
"e": 1298,
"s": 1169,
"text": "Conserves memory as we only store up to our capacity (opposed to a queue which could continue to grow if input outpaces output.)"
},
{
"code": null,
"e": 1345,
"s": 1298,
"text": "Simple Implementation → easy to trust and test"
},
{
"code": null,
"e": 1388,
"s": 1345,
"text": "Never has to reorganize / copy data around"
},
{
"code": null,
"e": 1431,
"s": 1388,
"text": "All operations occur in constant time O(1)"
},
{
"code": null,
"e": 1509,
"s": 1431,
"text": "Circular Queues can only store the pre-determined maximum number of elements."
},
{
"code": null,
"e": 1546,
"s": 1509,
"text": "Have to know the max size beforehand"
},
{
"code": null,
"e": 1601,
"s": 1546,
"text": "There are two primary operations on a circular Queue :"
},
{
"code": null,
"e": 1643,
"s": 1601,
"text": "1: Enqueue(item) : add item to the Queue."
},
{
"code": null,
"e": 1745,
"s": 1643,
"text": "if Queue.isfull() print \"Queue is Full\"else increase tail by 1 Queue[tail] = item size++"
},
{
"code": null,
"e": 1822,
"s": 1745,
"text": "2: Dequeue(): return the item at the front (head) of the line and remove it."
},
{
"code": null,
"e": 1939,
"s": 1822,
"text": "if Queue.isEmpty() print \"Queue is Empty\"else tmp = Queue[head] increase head by 1 size-- return tmp"
},
{
"code": null,
"e": 2067,
"s": 1939,
"text": "Note: We aren’t actually removing anything from the array, we are just increasing the head to point at the next item “in line”."
},
{
"code": null,
"e": 2137,
"s": 2067,
"text": "Let’s take a Look at how these operations look on an Array of size 6:"
},
{
"code": null,
"e": 2220,
"s": 2137,
"text": "Notice how the tail wraps back around to zero as we enqueue our seventh item (35)."
},
{
"code": null,
"e": 2384,
"s": 2220,
"text": "Notice how the head increases as we dequeue, but no values are removed from the array, they are only over-written as Enqueue( ) reaches that location in the array."
},
{
"code": null,
"e": 2562,
"s": 2384,
"text": "If we’re supposed to be increasing the head and the tail by 1 spot in the array how do we set it back to zero when we get to the end to ensure we keep looping through the array?"
},
{
"code": null,
"e": 2595,
"s": 2562,
"text": "We could do something like this:"
},
{
"code": null,
"e": 2657,
"s": 2595,
"text": "if (head + 1) = capacity head = 0else head = head + 1"
},
{
"code": null,
"e": 2961,
"s": 2657,
"text": "There's really nothing wrong with that, however, there’s a much more elegant method using the modulo operator. The modulo operator (%) gives the remainder after division. When looking at the relationship between two integers a and b; a will be the product of b times some integer q plus some integer r :"
},
{
"code": null,
"e": 3028,
"s": 2961,
"text": "a = b x q + r q : quotient = a div b r : remainder = a mod b"
},
{
"code": null,
"e": 3063,
"s": 3028,
"text": "Let’s look at some quick examples:"
},
{
"code": null,
"e": 3274,
"s": 3063,
"text": "a = b x q + r a % b = r5 = 3 x 1 + 2 5 % 3 = 22 = 5 x 0 + 2 2 % 5 = 29 = 3 x 3 + 0 9 % 3 = 09 = 2 X 4 + 1 9 % 2 = 1"
},
{
"code": null,
"e": 3341,
"s": 3274,
"text": "Note: This is the basis of Euclid’s Algorithm for determining GCD."
},
{
"code": null,
"e": 3394,
"s": 3341,
"text": "Let's apply it to our circular queue implementation:"
},
{
"code": null,
"e": 3438,
"s": 3394,
"text": "self.head = (self.head + 1) % self.capacity"
},
{
"code": null,
"e": 3607,
"s": 3438,
"text": "Now every time we get to the end of the array we will automatically start back at zero. Beautiful! Let’s see what this would look like with a circular queue of size 6 :"
},
{
"code": null,
"e": 3674,
"s": 3607,
"text": "0 % 6 = 01 % 6 = 12 % 6 = 23 % 6 = 34 % 6 = 45 % 6 = 56 % 6 = 0..."
},
{
"code": null,
"e": 3899,
"s": 3674,
"text": "This is a simple implementation where we only have the two primary methods, Enqueue(item), Dequeue( ), as well as a display( ) method which I think is helpful in understanding. Many other implementations might also include :"
},
{
"code": null,
"e": 3950,
"s": 3899,
"text": "isFull( ): true if queue is full, false otherwise."
},
{
"code": null,
"e": 4003,
"s": 3950,
"text": "isEmpty( ): true if queue is empty, false otherwise."
},
{
"code": null,
"e": 4073,
"s": 4003,
"text": "peek( ) : see what is at the head of the queue without “removing” it."
},
{
"code": null,
"e": 4079,
"s": 4073,
"text": "etc.."
},
{
"code": null,
"e": 4295,
"s": 4079,
"text": "Many other implementations won’t store the current size and will determine isFull( ) and isEmpty( ) by simply comparing the head and tail. I think storing the size makes it easier to follow exactly what is going on."
},
{
"code": null,
"e": 4613,
"s": 4295,
"text": "You can see the C implementation is very similar to the Python implementation with the addition of the fun C stuff like structs and memory allocation. Here we also need a create_queue( ) function as we are using structs. We also use some helper functions that we talked about earlier like isFull( ), isEmpty( ), etc.."
},
{
"code": null,
"e": 4643,
"s": 4613,
"text": "What are some boundary cases?"
},
{
"code": null,
"e": 4675,
"s": 4643,
"text": "What assumptions are we making?"
},
{
"code": null,
"e": 4846,
"s": 4675,
"text": "How would we implement the circular queue to have the ability to change capacity on the fly? How would this affect our advantages and disadvantages of the circular queue?"
},
{
"code": null,
"e": 5083,
"s": 4846,
"text": "Both of these implementations won’t allow you to enqueue a new item if the queue is full. Can you think of some applications of a circular queue where this might be bad? How would we change the implementations to allow for over-writing?"
}
] |
Virtual environment: What, Why, How? | by Eric Li | Towards Data Science | Mac is pre-installed with python 2. More python environments can be installed on your Mac in different directories with different versions of python and different packages installed. It is important to be aware of which python you are working with.
You can check the python you are currently working with by typing the following code in your terminal:
ericli@ERICYNLI-MB0 ~ % which python /usr/bin/python
In the example, the python I’m currently working with is the pre-installed python 2. If the python isn’t the one you want to use, then you might have a little problem here. You can resolve this problem by putting the directory of the desired python at the beginning of the path variable on your Mac. But this method is not recommended, since if you need to use different versions of python or python package for different projects, you will have to upgrade or downgrade your python or python packages consistently. In this situation, it is highly recommended to use virtual environments.
A virtual environment is a directory that contains a specific version of python and its related packages. The virtual environments are perfectly isolated, so you may have as many virtual environments as you want on your Mac, and always be crystal clear about which one you are working with.
I highly recommend everyone to install Anaconda before they proceed to the next step for its simplicity. After you install Anaconda ( https://docs.anaconda.com/anaconda/install/), you need to add the directory of the Anaconda bin to the paths. To add the directory, simply input the following code and type in your Mac password:
ericli@ERICYNLI-MB0 ~ % sudo vim /etc/paths Password:
For those of you that are interested, “sudo” means “superuser do”, it grants the current user administrator privilege. After you input your password and hit enter, you will see something like this:
/usr/local/bin /usr/bin /bin /usr/sbin /sbin
In the file, create a new line, and add the Anaconda bin directory to the file.
/usr/local/bin /usr/bin /bin /usr/sbin /sbin /opt/anaconda3/bin
Once the file is saved, you can use the “conda” command in your terminal.
Vim command hints: “o”: open a new line under the cursor “O”: open a new line above the cursor “:wq”: save and quit “:q”: quit “:q!”: force to quit(when there are unwanted changes)
With conda command, you can create virtual environments with your desired python versions and python packages. By activating the virtual environment, your path on your Mac is modified — the directory of your virtual environment is placed at the beginning of the path file, so any command you input will be searched and executed once found in the virtual environment.
To create a virtual environment with python version 3.8, and activate it:
ericli@ERICYNLI-MB0 ~ % conda create --name py38 python=3.8 ericli@ERICYNLI-MB0 ~ % source activate py38
To check the virtual environment list and current environment (marked with a star):
(py38) ericli@ERICYNLI-MB0 ~ % conda env list # conda environments:#base /opt/anaconda3py38 * /opt/anaconda3/envs/py38
To check what packages are installed in the current environment, and install other packages:
(py38) ericli@ERICYNLI-MB0 ~ % conda list (py38) ericli@ERICYNLI-MB0 ~ % conda install PACKAGENAME
After activating the new environment, you can find the python you are using is the one in your virtual environment.
(py38) ericli@ERICYNLI-MB0 ~ % which python /opt/anaconda3/envs/py38/bin/python
Now your new virtual environment is all set. You can begin to work with this environment by input “python” in the terminal, or “jupyter lab” if you installed jupyterlab.
Originally published at http://github.com. | [
{
"code": null,
"e": 421,
"s": 172,
"text": "Mac is pre-installed with python 2. More python environments can be installed on your Mac in different directories with different versions of python and different packages installed. It is important to be aware of which python you are working with."
},
{
"code": null,
"e": 524,
"s": 421,
"text": "You can check the python you are currently working with by typing the following code in your terminal:"
},
{
"code": null,
"e": 577,
"s": 524,
"text": "ericli@ERICYNLI-MB0 ~ % which python /usr/bin/python"
},
{
"code": null,
"e": 1165,
"s": 577,
"text": "In the example, the python I’m currently working with is the pre-installed python 2. If the python isn’t the one you want to use, then you might have a little problem here. You can resolve this problem by putting the directory of the desired python at the beginning of the path variable on your Mac. But this method is not recommended, since if you need to use different versions of python or python package for different projects, you will have to upgrade or downgrade your python or python packages consistently. In this situation, it is highly recommended to use virtual environments."
},
{
"code": null,
"e": 1456,
"s": 1165,
"text": "A virtual environment is a directory that contains a specific version of python and its related packages. The virtual environments are perfectly isolated, so you may have as many virtual environments as you want on your Mac, and always be crystal clear about which one you are working with."
},
{
"code": null,
"e": 1785,
"s": 1456,
"text": "I highly recommend everyone to install Anaconda before they proceed to the next step for its simplicity. After you install Anaconda ( https://docs.anaconda.com/anaconda/install/), you need to add the directory of the Anaconda bin to the paths. To add the directory, simply input the following code and type in your Mac password:"
},
{
"code": null,
"e": 1839,
"s": 1785,
"text": "ericli@ERICYNLI-MB0 ~ % sudo vim /etc/paths Password:"
},
{
"code": null,
"e": 2037,
"s": 1839,
"text": "For those of you that are interested, “sudo” means “superuser do”, it grants the current user administrator privilege. After you input your password and hit enter, you will see something like this:"
},
{
"code": null,
"e": 2082,
"s": 2037,
"text": "/usr/local/bin /usr/bin /bin /usr/sbin /sbin"
},
{
"code": null,
"e": 2162,
"s": 2082,
"text": "In the file, create a new line, and add the Anaconda bin directory to the file."
},
{
"code": null,
"e": 2226,
"s": 2162,
"text": "/usr/local/bin /usr/bin /bin /usr/sbin /sbin /opt/anaconda3/bin"
},
{
"code": null,
"e": 2300,
"s": 2226,
"text": "Once the file is saved, you can use the “conda” command in your terminal."
},
{
"code": null,
"e": 2481,
"s": 2300,
"text": "Vim command hints: “o”: open a new line under the cursor “O”: open a new line above the cursor “:wq”: save and quit “:q”: quit “:q!”: force to quit(when there are unwanted changes)"
},
{
"code": null,
"e": 2848,
"s": 2481,
"text": "With conda command, you can create virtual environments with your desired python versions and python packages. By activating the virtual environment, your path on your Mac is modified — the directory of your virtual environment is placed at the beginning of the path file, so any command you input will be searched and executed once found in the virtual environment."
},
{
"code": null,
"e": 2922,
"s": 2848,
"text": "To create a virtual environment with python version 3.8, and activate it:"
},
{
"code": null,
"e": 3027,
"s": 2922,
"text": "ericli@ERICYNLI-MB0 ~ % conda create --name py38 python=3.8 ericli@ERICYNLI-MB0 ~ % source activate py38"
},
{
"code": null,
"e": 3111,
"s": 3027,
"text": "To check the virtual environment list and current environment (marked with a star):"
},
{
"code": null,
"e": 3268,
"s": 3111,
"text": "(py38) ericli@ERICYNLI-MB0 ~ % conda env list # conda environments:#base /opt/anaconda3py38 * /opt/anaconda3/envs/py38"
},
{
"code": null,
"e": 3361,
"s": 3268,
"text": "To check what packages are installed in the current environment, and install other packages:"
},
{
"code": null,
"e": 3460,
"s": 3361,
"text": "(py38) ericli@ERICYNLI-MB0 ~ % conda list (py38) ericli@ERICYNLI-MB0 ~ % conda install PACKAGENAME"
},
{
"code": null,
"e": 3576,
"s": 3460,
"text": "After activating the new environment, you can find the python you are using is the one in your virtual environment."
},
{
"code": null,
"e": 3656,
"s": 3576,
"text": "(py38) ericli@ERICYNLI-MB0 ~ % which python /opt/anaconda3/envs/py38/bin/python"
},
{
"code": null,
"e": 3826,
"s": 3656,
"text": "Now your new virtual environment is all set. You can begin to work with this environment by input “python” in the terminal, or “jupyter lab” if you installed jupyterlab."
}
] |
Program for Volume and Surface Area of Cube in C++ | Cube is a three-dimensional object with six faces of square shape which means it has sides of same length and breadth. Cube is the only regular hexahedron with following properties −
six faces
12 edges
8 vertices
Given below is the figure of cube
Given with the side, the task is to find the total surface area and volume of a cube where surface area is the space occupied by the faces and volume is the space that a shape can contain.
To calculate surface area and volume of a cube there is a formula −
Surface Area = 6*Side*side
Volume = Side*side*side
Input-: side=3
Output-: volume of cube is: 27
Total surface area of cube is 54
Start
Step 1 -> declare function to find volume of cube
double volume(double a)
return (a*a*a)
Step 2 -> declare function to find area of cube
double volume(double a)
return (6*a*a)
Step 3 -> In main()
Declare variable double a=3
Print volume(a)
Print area(a)
Stop
#include <bits/stdc++.h>
using namespace std;
// function for volume of cube
double volume(double a){
return (a * a * a);
}
//function for surface area of cube
double area(double a){
return (6 * a * a);
}
int main(){
double a = 3;
cout<< "volume of cube is: "<<volume(a)<<endl;
cout<< "Total surface area of cube is "<<area(a);
return 0;
}
volume of cube is: 27
Total surface area of cube is 54 | [
{
"code": null,
"e": 1245,
"s": 1062,
"text": "Cube is a three-dimensional object with six faces of square shape which means it has sides of same length and breadth. Cube is the only regular hexahedron with following properties −"
},
{
"code": null,
"e": 1255,
"s": 1245,
"text": "six faces"
},
{
"code": null,
"e": 1264,
"s": 1255,
"text": "12 edges"
},
{
"code": null,
"e": 1275,
"s": 1264,
"text": "8 vertices"
},
{
"code": null,
"e": 1309,
"s": 1275,
"text": "Given below is the figure of cube"
},
{
"code": null,
"e": 1498,
"s": 1309,
"text": "Given with the side, the task is to find the total surface area and volume of a cube where surface area is the space occupied by the faces and volume is the space that a shape can contain."
},
{
"code": null,
"e": 1566,
"s": 1498,
"text": "To calculate surface area and volume of a cube there is a formula −"
},
{
"code": null,
"e": 1593,
"s": 1566,
"text": "Surface Area = 6*Side*side"
},
{
"code": null,
"e": 1617,
"s": 1593,
"text": "Volume = Side*side*side"
},
{
"code": null,
"e": 1699,
"s": 1617,
"text": "Input-: side=3\nOutput-: volume of cube is: 27\n Total surface area of cube is 54"
},
{
"code": null,
"e": 1991,
"s": 1699,
"text": "Start\nStep 1 -> declare function to find volume of cube\n double volume(double a)\n return (a*a*a)\nStep 2 -> declare function to find area of cube\n double volume(double a)\n return (6*a*a)\nStep 3 -> In main()\n Declare variable double a=3\n Print volume(a)\n Print area(a)\nStop"
},
{
"code": null,
"e": 2349,
"s": 1991,
"text": "#include <bits/stdc++.h>\nusing namespace std;\n// function for volume of cube\ndouble volume(double a){\n return (a * a * a);\n}\n//function for surface area of cube\ndouble area(double a){\n return (6 * a * a);\n}\nint main(){\n double a = 3;\n cout<< \"volume of cube is: \"<<volume(a)<<endl;\n cout<< \"Total surface area of cube is \"<<area(a);\n return 0;\n}"
},
{
"code": null,
"e": 2404,
"s": 2349,
"text": "volume of cube is: 27\nTotal surface area of cube is 54"
}
] |
How to get first and last elements from ArrayList in Java? | The get() method of the ArrayList class accepts an integer representing the index value and, returns the element of the current ArrayList object at the specified index.
Therefore, if you pass 0 to this method you can get the first element of the current ArrayList and, if you pass list.size()-1 you can get the last element.
Live Demo
import java.util.ArrayList;
public class FirstandLastElemets{
public static void main(String[] args){
ArrayList<String> list = new ArrayList<String>();
//Instantiating an ArrayList object
list.add("JavaFX");
list.add("Java");
list.add("WebGL");
list.add("OpenCV");
list.add("OpenNLP");
list.add("JOGL");
list.add("Hadoop");
list.add("HBase");
list.add("Flume");
list.add("Mahout");
list.add("Impala");
System.out.println("Contents of the Array List: \n"+list);
//Removing the sub list
System.out.println("First element of the array list: "+list.get(0));
System.out.println("Last element of the array list: "+list.get(list.size()-1));
}
}
Contents of the Array List:
[JavaFX, Java, WebGL, OpenCV, OpenNLP, JOGL, Hadoop, HBase, Flume, Mahout, Impala]
First element of the array list: JavaFX
Last element of the array list: Impala
To get minimum and maximum values of an ArrayList −
Create an ArrayList object.
Create an ArrayList object.
Add elements to it.
Add elements to it.
Sort it using the sort() method of the Collections class.
Sort it using the sort() method of the Collections class.
Then, the first element of the ArrayList will be the minimum value and the last element of the ArrayList will be the maximum value.
Then, the first element of the ArrayList will be the minimum value and the last element of the ArrayList will be the maximum value.
Live Demo
import java.util.ArrayList;
import java.util.Collections;
public class MinandMax{
public static void main(String[] args){
ArrayList<Integer> list = new ArrayList<Integer>();
//Instantiating an ArrayList object
list.add(1001);
list.add(2015);
list.add(4566);
list.add(90012);
list.add(100);
list.add(21);
list.add(43);
list.add(2345);
list.add(785);
list.add(6665);
list.add(6435);
System.out.println("Contents of the Array List: \n"+list);
//Sorting the array list
Collections.sort(list);
System.out.println("Minimum value: "+list.get(0));
System.out.println("Maximum value: "+list.get(list.size()-1));
}
}
Contents of the Array List:
[1001, 2015, 4566, 90012, 100, 21, 43, 2345, 785, 6665, 6435]
Minimum value: 21
Maximum value: 90012 | [
{
"code": null,
"e": 1231,
"s": 1062,
"text": "The get() method of the ArrayList class accepts an integer representing the index value and, returns the element of the current ArrayList object at the specified index."
},
{
"code": null,
"e": 1387,
"s": 1231,
"text": "Therefore, if you pass 0 to this method you can get the first element of the current ArrayList and, if you pass list.size()-1 you can get the last element."
},
{
"code": null,
"e": 1398,
"s": 1387,
"text": " Live Demo"
},
{
"code": null,
"e": 2144,
"s": 1398,
"text": "import java.util.ArrayList;\npublic class FirstandLastElemets{\n public static void main(String[] args){\n ArrayList<String> list = new ArrayList<String>();\n //Instantiating an ArrayList object\n list.add(\"JavaFX\");\n list.add(\"Java\");\n list.add(\"WebGL\");\n list.add(\"OpenCV\");\n list.add(\"OpenNLP\");\n list.add(\"JOGL\");\n list.add(\"Hadoop\");\n list.add(\"HBase\");\n list.add(\"Flume\");\n list.add(\"Mahout\");\n list.add(\"Impala\");\n System.out.println(\"Contents of the Array List: \\n\"+list);\n //Removing the sub list\n System.out.println(\"First element of the array list: \"+list.get(0));\n System.out.println(\"Last element of the array list: \"+list.get(list.size()-1));\n }\n}"
},
{
"code": null,
"e": 2334,
"s": 2144,
"text": "Contents of the Array List:\n[JavaFX, Java, WebGL, OpenCV, OpenNLP, JOGL, Hadoop, HBase, Flume, Mahout, Impala]\nFirst element of the array list: JavaFX\nLast element of the array list: Impala"
},
{
"code": null,
"e": 2386,
"s": 2334,
"text": "To get minimum and maximum values of an ArrayList −"
},
{
"code": null,
"e": 2414,
"s": 2386,
"text": "Create an ArrayList object."
},
{
"code": null,
"e": 2442,
"s": 2414,
"text": "Create an ArrayList object."
},
{
"code": null,
"e": 2462,
"s": 2442,
"text": "Add elements to it."
},
{
"code": null,
"e": 2482,
"s": 2462,
"text": "Add elements to it."
},
{
"code": null,
"e": 2540,
"s": 2482,
"text": "Sort it using the sort() method of the Collections class."
},
{
"code": null,
"e": 2598,
"s": 2540,
"text": "Sort it using the sort() method of the Collections class."
},
{
"code": null,
"e": 2730,
"s": 2598,
"text": "Then, the first element of the ArrayList will be the minimum value and the last element of the ArrayList will be the maximum value."
},
{
"code": null,
"e": 2862,
"s": 2730,
"text": "Then, the first element of the ArrayList will be the minimum value and the last element of the ArrayList will be the maximum value."
},
{
"code": null,
"e": 2873,
"s": 2862,
"text": " Live Demo"
},
{
"code": null,
"e": 3594,
"s": 2873,
"text": "import java.util.ArrayList;\nimport java.util.Collections;\npublic class MinandMax{\n public static void main(String[] args){\n ArrayList<Integer> list = new ArrayList<Integer>();\n //Instantiating an ArrayList object\n list.add(1001);\n list.add(2015);\n list.add(4566);\n list.add(90012);\n list.add(100);\n list.add(21);\n list.add(43);\n list.add(2345);\n list.add(785);\n list.add(6665);\n list.add(6435);\n System.out.println(\"Contents of the Array List: \\n\"+list);\n //Sorting the array list\n Collections.sort(list);\n System.out.println(\"Minimum value: \"+list.get(0));\n System.out.println(\"Maximum value: \"+list.get(list.size()-1));\n }\n}"
},
{
"code": null,
"e": 3723,
"s": 3594,
"text": "Contents of the Array List:\n[1001, 2015, 4566, 90012, 100, 21, 43, 2345, 785, 6665, 6435]\nMinimum value: 21\nMaximum value: 90012"
}
] |
Vaadin - User Interface Components | Vaadin is used to build rich user interface components in a webpage. In this chapter, you will learn about different user interface components that have been introduced by Vaadin in order to maintain a good quality web page. The first part of the chapter discusses the basic web components and their uses, while the second part talks about binding the components in the backend.
Fields are the web components that a user can manipulate through IO operations. Vaadin is based on JAVA, hence in Vaadin all the web components have an implemented class along with Vaadin library functions. The image shown below shows how different field components are inherited from the base class named AbstractField<T>.
Note that all these modules are similar to that of those in UI development. In Vaadin we have separate class to implement each of them. You will learn in detail about these in the coming chapters.
Label is used to mention any non-editable text in the web page. The example given below shows how to use label in our application. Note that in the given example, we created a JAVA class and named it as LabelExam.javanterface and we will override its init() method to run it.
package com.MyTutorials.MyFirstApp;
import javax.servlet.annotation.WebServlet;
import com.vaadin.annotations.VaadinServletConfiguration;
import com.vaadin.server.VaadinRequest;
import com.vaadin.server.VaadinServlet;
import com.vaadin.ui.HorizontalLayout;
import com.vaadin.ui.Label;
import com.vaadin.ui.UI;
//extending UI
public class LabelExam extends UI {
@Override
protected void init(VaadinRequest request) {
final HorizontalLayout hLayout = new HorizontalLayout(); //creating a Layout
Label l1 = new Label(" Welcome to the World of Vaadin Tutorials.");
Label l2 = new Label("\n Happy Learning .." ,ContentMode.PREFORMATTED); // Content Mode tells JVM to interpret the String mentioned in the label. Hence label2 will be printed in next line because of “\n”.
hLayout.addComponents(l1,l2); // adding labels to layout
setContent(hLayout); // setting the layout as a content of the web page.
}
// Code to control URL
@WebServlet(urlPatterns = "/*", name = "MyUIServlet", asyncSupported = true)
@VaadinServletConfiguration(ui = LabelExam.class, productionMode = false)
public static class MyUIServlet extends VaadinServlet {}
}
In the above example, we have created two labels and at the end we have added that label to our layout. You will learn more about layouts in the upcoming chapters. The VaadinServlet has been implemented in order to control the URL. However, in real life projects, you need not define servlet in every java application as it will be interlinked. Select the file and click Run on Server and code given above will yield the output as shown below.
Link is useful to implement external links to the other website. This class works exactly similar to the hyperlink tag of HTML. In the example given below, we will be using Link to redirect our user to another website depending on an event called Click here. Now, modify the MyUI.java class as shown below.
package com.example.myapplication;
import javax.servlet.annotation.WebServlet;
import com.vaadin.annotations.Theme;
import com.vaadin.annotations.VaadinServletConfiguration;
import com.vaadin.server.ExternalResource;
import com.vaadin.server.VaadinRequest;
import com.vaadin.server.VaadinServlet;
import com.vaadin.shared.ui.ContentMode;
import com.vaadin.ui.Button;
import com.vaadin.ui.HorizontalLayout;
import com.vaadin.ui.Label;
import com.vaadin.ui.Link;
import com.vaadin.ui.TextField;
import com.vaadin.ui.UI;
import com.vaadin.ui.VerticalLayout;
@Theme("mytheme")
public class MyUI extends UI {
@Override
protected void init(VaadinRequest vaadinRequest) {
final VerticalLayout layout = new VerticalLayout();
final HorizontalLayout hLayout = new HorizontalLayout();
Link link = new Link("Click Me",new ExternalResource("https://www.tutorialspoint.com/"));
hLayout.addComponent(link);
setContent(hLayout);
}
@WebServlet(urlPatterns = "/*", name = "MyUIServlet", asyncSupported = true)
@VaadinServletConfiguration(ui = MyUI.class, productionMode = false)
public static class MyUIServlet extends VaadinServlet {}
}
In the above example, we have created an external hyperlink to another website. It will give us the following output in the browser.
Once users click the link, they will be redirected to www.tutorialspoint.com
This section talks about how to generate a text field using Vaadin build in class. For this, update your MyUI.java class as shown below.
package com.example.myapplication;
import javax.servlet.annotation.WebServlet;
import com.vaadin.annotations.Theme;
import com.vaadin.annotations.VaadinServletConfiguration;
import com.vaadin.server.VaadinRequest;
import com.vaadin.server.VaadinServlet;
import com.vaadin.shared.ui.ContentMode;
import com.vaadin.ui.Label;
import com.vaadin.ui.TextField;
import com.vaadin.ui.UI;
import com.vaadin.ui.VerticalLayout;
@Theme("mytheme")
public class MyUI extends UI {
@Override
protected void init(VaadinRequest vaadinRequest) {
final VerticalLayout layout = new VerticalLayout();
Label l1 = new Label("Example of TextField--\n ",ContentMode.PREFORMATTED);
TextField text = new TextField();
text.setValue("----");
layout.addComponents(l1,text);
setContent(layout);
}
@WebServlet(urlPatterns = "/*", name = "MyUIServlet", asyncSupported = true)
@VaadinServletConfiguration(ui = MyUI.class, productionMode = false)
public static class MyUIServlet extends VaadinServlet {}
}
Now, refresh your project and clean build it. You can observe the output shown below in your browser. Remember to restart your browser to get its recent changes.
This section explains you how to create a text area in the browser using Vaadin predefined class. Observe the code given below for example.
package com.example.myapplication;
import javax.servlet.annotation.WebServlet;
import com.vaadin.annotations.Theme;
import com.vaadin.annotations.VaadinServletConfiguration;
import com.vaadin.server.VaadinRequest;
import com.vaadin.server.VaadinServlet;
import com.vaadin.ui.Alignment;
import com.vaadin.ui.TextArea;
import com.vaadin.ui.UI;
import com.vaadin.ui.VerticalLayout;
@Theme("mytheme")
public class MyUI extends UI {
@Override
protected void init(VaadinRequest vaadinRequest) {
final VerticalLayout layout = new VerticalLayout();
final VerticalLayout hLayout = new VerticalLayout();
TextArea text = new TextArea();
text.setValue(" I am the example of Text Area in Vaadin");
hLayout.addComponent(text);
hLayout.setComponentAlignment(text,Alignment.BOTTOM_CENTER);
setContent(hLayout);
}
@WebServlet(urlPatterns = "/*", name = "MyUIServlet", asyncSupported = true)
@VaadinServletConfiguration(ui = MyUI.class, productionMode = false)
public static class MyUIServlet extends VaadinServlet {}
}
The above piece of code will yield below output in the browser −
package com.example.myapplication;
import java.time.LocalDate;
import java.util.Locale;
import javax.servlet.annotation.WebServlet;
import com.vaadin.annotations.Theme;
import com.vaadin.annotations.VaadinServletConfiguration;
import com.vaadin.server.VaadinRequest;
import com.vaadin.server.VaadinServlet;
import com.vaadin.shared.ui.ContentMode;
import com.vaadin.ui.Alignment;
import com.vaadin.ui.DateField;
import com.vaadin.ui.Label;
import com.vaadin.ui.UI;
import com.vaadin.ui.VerticalLayout;
@Theme("mytheme")
public class MyUI extends UI {
@Override
protected void init(VaadinRequest vaadinRequest) {
final VerticalLayout layout = new VerticalLayout();
final VerticalLayout hLayout = new VerticalLayout();
Label l1 = new Label("Enter today's Date\n",ContentMode.PREFORMATTED);
DateField date = new DateField();
date.setValue(LocalDate.now());
date.setLocale(new Locale("en","IND"));
hLayout.addComponents(l1,date);
hLayout.setComponentAlignment(l1,Alignment.BOTTOM_CENTER);
hLayout.setComponentAlignment(date,Alignment.BOTTOM_CENTER);
setContent(hLayout);
}
@WebServlet(urlPatterns = "/*", name = "MyUIServlet", asyncSupported = true)
@VaadinServletConfiguration(ui = MyUI.class, productionMode = false)
public static class MyUIServlet extends VaadinServlet {
}
In the above example, we have used Vaadin predefined date function to populate the date component in the webpage. This code will give you the output as shown in the screenshot below −
The code given below will explain you how to apply a button in the web page. Here, we have used a button named Click Me.
package com.example.myapplication;
import javax.servlet.annotation.WebServlet;
import com.vaadin.annotations.Theme;
import com.vaadin.annotations.VaadinServletConfiguration;
import com.vaadin.server.ExternalResource;
import com.vaadin.server.VaadinRequest;
import com.vaadin.server.VaadinServlet;
import com.vaadin.shared.ui.ContentMode;
import com.vaadin.ui.Alignment;
import com.vaadin.ui.Button;
import com.vaadin.ui.HorizontalLayout;
import com.vaadin.ui.Label;
import com.vaadin.ui.Link;
import com.vaadin.ui.TextArea;
import com.vaadin.ui.TextField;
import com.vaadin.ui.UI;
import com.vaadin.ui.VerticalLayout;
@Theme("mytheme")
public class MyUI extends UI {
@Override
protected void init(VaadinRequest vaadinRequest) {
final VerticalLayout layout = new VerticalLayout();
final VerticalLayout hLayout = new VerticalLayout();
TextArea text = new TextArea();
text.setValue("Please enter some Value");
Button b = new Button("Click Me");
hLayout.addComponent(text);
hLayout.addComponent(b);
hLayout.setComponentAlignment(text,Alignment.BOTTOM_CENTER);
hLayout.setComponentAlignment(b,Alignment.BOTTOM_CENTER);
setContent(hLayout);
}
@WebServlet(urlPatterns = "/*", name = "MyUIServlet", asyncSupported = true)
@VaadinServletConfiguration(ui = MyUI.class, productionMode = false)
public static class MyUIServlet extends VaadinServlet {}
}
Vaadin also provides inbuilt class to create a checkbox in the webpage. In the below example we will create a checkbox using Vaadin rich web component.
package com.example.myapplication;
import java.time.LocalDate;
import java.util.Locale;
import javax.servlet.annotation.WebServlet;
import com.vaadin.annotations.Theme;
import com.vaadin.annotations.VaadinServletConfiguration;
import com.vaadin.server.VaadinRequest;
import com.vaadin.server.VaadinServlet;
import com.vaadin.shared.ui.ContentMode;
import com.vaadin.ui.Alignment;
import com.vaadin.ui.CheckBox;
import com.vaadin.ui.DateField;
import com.vaadin.ui.Label;
import com.vaadin.ui.UI;
import com.vaadin.ui.VerticalLayout;
@Theme("mytheme")
public class MyUI extends UI {
@Override
protected void init(VaadinRequest vaadinRequest) {
final VerticalLayout layout = new VerticalLayout();
final VerticalLayout hLayout = new VerticalLayout();
Label l1 = new Label("Example of Check Box\n",ContentMode.PREFORMATTED);
CheckBox chk1 = new CheckBox("Option1");
CheckBox chk2 = new CheckBox("Option2");
CheckBox chk3 = new CheckBox("Option3");
hLayout.addComponents(l1,chk1,chk2,chk3);
hLayout.setComponentAlignment(l1,Alignment.BOTTOM_CENTER);
hLayout.setComponentAlignment(chk1,Alignment.BOTTOM_CENTER);
hLayout.setComponentAlignment(chk2,Alignment.BOTTOM_CENTER);
hLayout.setComponentAlignment(chk3,Alignment.BOTTOM_CENTER);
setContent(hLayout);
}
@WebServlet(urlPatterns = "/*", name = "MyUIServlet", asyncSupported = true)
@VaadinServletConfiguration(ui = MyUI.class, productionMode = false)
public static class MyUIServlet extends VaadinServlet {}
}
The code given above will yield output in the browser as shown below. You can also create any number of check boxes for the user. In the subsequent chapters, you will learn about different ways to populate the Check Box in the webpage.
This section explains you how to bind the data from the front end to back end using Vaadin as framework. Note that the code shown below takes input from the front end with the data field. Let us create a bean class in order to bind the data field. Create a java class and name it as Employee.java.
package com.example.myapplication;
public class EmployeeBean {
private String name = "";
private String Email = " ";
public EmployeeBean() {
super();
// TODO Auto-generated constructor stub
}
public EmployeeBean(String name, String email) {
super();
this.name = name;
Email = email;
}
public String getName() {
return name;
}
public void setName(String name) {
System.out.println("asdassd");
this.name = name;
}
public String getEmail() {
return Email;
}
public void setEmail(String email) {
Email = email;
}
}
We have to modify MyUI.java class in order to bind the data field of employee class. Observe the following code for modified class.
package com.example.myapplication;
import javax.servlet.annotation.WebServlet;
import com.vaadin.annotations.PropertyId;
import com.vaadin.annotations.Theme;
import com.vaadin.annotations.VaadinServletConfiguration;
import com.vaadin.data.Binder;
import com.vaadin.server.VaadinRequest;
import com.vaadin.server.VaadinServlet;
import com.vaadin.shared.ui.ContentMode;
import com.vaadin.ui.Alignment;
import com.vaadin.ui.Button;
import com.vaadin.ui.Button.ClickEvent;
import com.vaadin.ui.CheckBox;
import com.vaadin.ui.FormLayout;
import com.vaadin.ui.Label;
import com.vaadin.ui.TextField;
import com.vaadin.ui.UI;
import com.vaadin.ui.VerticalLayout;
@Theme("mytheme")
public class MyUI extends UI {
@Override
protected void init(VaadinRequest vaadinRequest) {
EmployeeBean bean = new EmployeeBean("TutorialsPoint","[email protected]");
Binder<EmployeeBean> binder = new Binder <EmployeeBean>();
final FormLayout form = new FormLayout();
Label l1 = new Label("Please fill Below Form");
Label labelName = new Label("Name--");
TextField name = new TextField();
binder.bind(name,EmployeeBean::getName,EmployeeBean::setName);
Label labelEmail = new Label("Email---");
TextField email = new TextField();
binder.bind(email,EmployeeBean::getEmail,EmployeeBean::setEmail);
Button button = new Button("Process..");
form.addComponents(l1,labelName,name,labelEmail,email,button);
setContent(form);
binder.setBean(bean); //auto binding using in built method
}
@WebServlet(urlPatterns = "/*", name = "MyUIServlet", asyncSupported = true)
@VaadinServletConfiguration(ui = MyUI.class, productionMode = false)
public static class MyUIServlet extends VaadinServlet {
}
}
The code given above will yield the following output in the browser.
Table is one of the most usable features of Vaadin. Table cells can include any type of data. Table component is developed for showing all data in a tabular format organized into a row and column structure. However, since Vaadin 8 release table feature has been absolute and the same feature has been modified with the Grid component. If you are still using an older version of Vaadin, then you are free to use table as shown in the format given below.
/* Create the table with a caption. */
Table table = new Table("This is my Table");
/* Define the names and data types of columns.
* The "default value" parameter is meaningless here. */
table.addContainerProperty("First Name", String.class, null);
table.addContainerProperty("Last Name", String.class, null);
table.addContainerProperty("Year", Integer.class, null);
/* Add a few items in the table. */
table.addItem(new Object[] {"Nicolaus","Copernicus",new Integer(1473)}, new Integer(1));
table.addItem(new Object[] {"Tycho", "Brahe", new Integer(1546)}, new Integer(2));
table.addItem(new Object[] {"Giordano","Bruno", new Integer(1548)}, new Integer(3));
table.addItem(new Object[] {"Galileo", "Galilei", new Integer(1564)}, new Integer(4));
table.addItem(new Object[] {"Johannes","Kepler", new Integer(1571)}, new Integer(5));
table.addItem(new Object[] {"Isaac", "Newton", new Integer(1643)}, new Integer(6));
In the upcoming chapter on GRID, you will learn more about Grid creation and populating data using the same.
Tree Component is used to populate directory structure in the website. In this section, you will learn how to populate a tree in the webpage using Vaadin framework. Update the required MyUI class as shown below.
package com.example.myapplication;
import javax.servlet.annotation.WebServlet;
import com.vaadin.annotations.Theme;
import com.vaadin.annotations.VaadinServletConfiguration;
import com.vaadin.data.TreeData;
import com.vaadin.server.VaadinRequest;
import com.vaadin.server.VaadinServlet;
import com.vaadin.ui.Component;
import com.vaadin.ui.Tree;
import com.vaadin.ui.UI;
import com.vaadin.ui.VerticalLayout;
@Theme("mytheme")
public class MyUI extends UI {
@Override
protected void init(VaadinRequest vaadinRequest) {
VerticalLayout layout = new VerticalLayout();
Tree<String> tree = new Tree<>();
TreeData<String> treeData =tree.getTreeData();
// Couple of childless root items
treeData.addItem(null, "Option1");
treeData.addItem("Option1", "Child1");
treeData.addItem(null, "Option2");
treeData.addItem("Option2", "Child2");
// Items with hierarchy
treeData.addItem(null, "Option3");
treeData.addItem("Option3", "Child3");
layout.addComponent(tree);
setContent(layout);
}
@WebServlet(urlPatterns = "/*", name = "MyUIServlet", asyncSupported = true)
@VaadinServletConfiguration(ui = MyUI.class, productionMode = false)
public static class MyUIServlet extends VaadinServlet {}
}
The above piece of code will produce the following output in the browser.
Menu Bar component helps us to create a menu in the website. It can be dynamic as well as it can be nested. Find below example where we have created a nested menu bar using Vaadin Menu Bar component. Go ahead and modify our class like below.
package com.example.myapplication;
import javax.servlet.annotation.WebServlet;
import com.vaadin.annotations.Theme;
import com.vaadin.annotations.VaadinServletConfiguration;
import com.vaadin.data.TreeData;
import com.vaadin.server.VaadinRequest;
import com.vaadin.server.VaadinServlet;
import com.vaadin.ui.Component;
import com.vaadin.ui.Label;
import com.vaadin.ui.MenuBar;
import com.vaadin.ui.MenuBar.MenuItem;
import com.vaadin.ui.Tree;
import com.vaadin.ui.UI;
import com.vaadin.ui.VerticalLayout;
@Theme("mytheme")
public class MyUI extends UI {
@Override
protected void init(VaadinRequest vaadinRequest) {
VerticalLayout layout = new VerticalLayout();
MenuBar barmenu = new MenuBar();
layout.addComponent(barmenu);
// A feedback component
final Label selection = new Label("-");
layout.addComponent(selection);
// Define a common menu command for all the menu items.
MenuBar.Command mycommand = new MenuBar.Command() {
public void menuSelected(MenuItem selectedItem) {
selection.setValue("Ordered a " +
selectedItem.getText() +
" from menu.");
}
};
// Put some items in the menu hierarchically
MenuBar.MenuItem beverages =
barmenu.addItem("Beverages", null, null);
MenuBar.MenuItem hot_beverages =
beverages.addItem("Hot", null, null);
hot_beverages.addItem("Tea", null, mycommand);
hot_beverages.addItem("Coffee", null, mycommand);
MenuBar.MenuItem cold_beverages =
beverages.addItem("Cold", null, null);
cold_beverages.addItem("Milk", null, mycommand);
cold_beverages.addItem("Weissbier", null, mycommand);
// Another top-level item
MenuBar.MenuItem snacks =
barmenu.addItem("Snacks", null, null);
snacks.addItem("Weisswurst", null, mycommand);
snacks.addItem("Bratwurst", null, mycommand);
snacks.addItem("Currywurst", null, mycommand);
// Yet another top-level item
MenuBar.MenuItem services =
barmenu.addItem("Services", null, null);
services.addItem("Car Service", null, mycommand);
setContent(layout);
}
@WebServlet(urlPatterns = "/*", name = "MyUIServlet", asyncSupported = true)
@VaadinServletConfiguration(ui = MyUI.class, productionMode = false)
public static class MyUIServlet extends VaadinServlet {}
}
In the example discussed above, we have created a nested menu bar. Run the above piece of code and you can observe the output in your browser as shown below −
Print
Add Notes
Bookmark this page | [
{
"code": null,
"e": 2148,
"s": 1769,
"text": "Vaadin is used to build rich user interface components in a webpage. In this chapter, you will learn about different user interface components that have been introduced by Vaadin in order to maintain a good quality web page. The first part of the chapter discusses the basic web components and their uses, while the second part talks about binding the components in the backend."
},
{
"code": null,
"e": 2472,
"s": 2148,
"text": "Fields are the web components that a user can manipulate through IO operations. Vaadin is based on JAVA, hence in Vaadin all the web components have an implemented class along with Vaadin library functions. The image shown below shows how different field components are inherited from the base class named AbstractField<T>."
},
{
"code": null,
"e": 2669,
"s": 2472,
"text": "Note that all these modules are similar to that of those in UI development. In Vaadin we have separate class to implement each of them. You will learn in detail about these in the coming chapters."
},
{
"code": null,
"e": 2945,
"s": 2669,
"text": "Label is used to mention any non-editable text in the web page. The example given below shows how to use label in our application. Note that in the given example, we created a JAVA class and named it as LabelExam.javanterface and we will override its init() method to run it."
},
{
"code": null,
"e": 4133,
"s": 2945,
"text": "package com.MyTutorials.MyFirstApp;\n\nimport javax.servlet.annotation.WebServlet;\nimport com.vaadin.annotations.VaadinServletConfiguration;\nimport com.vaadin.server.VaadinRequest;\nimport com.vaadin.server.VaadinServlet;\nimport com.vaadin.ui.HorizontalLayout;\nimport com.vaadin.ui.Label;\nimport com.vaadin.ui.UI;\n\n//extending UI\npublic class LabelExam extends UI {\n @Override\n protected void init(VaadinRequest request) {\n final HorizontalLayout hLayout = new HorizontalLayout(); //creating a Layout\n Label l1 = new Label(\" Welcome to the World of Vaadin Tutorials.\");\n Label l2 = new Label(\"\\n Happy Learning ..\" ,ContentMode.PREFORMATTED); // Content Mode tells JVM to interpret the String mentioned in the label. Hence label2 will be printed in next line because of “\\n”.\n hLayout.addComponents(l1,l2); // adding labels to layout\n setContent(hLayout); // setting the layout as a content of the web page.\n }\n // Code to control URL\n @WebServlet(urlPatterns = \"/*\", name = \"MyUIServlet\", asyncSupported = true)\n \n @VaadinServletConfiguration(ui = LabelExam.class, productionMode = false)\n public static class MyUIServlet extends VaadinServlet {}\n}"
},
{
"code": null,
"e": 4577,
"s": 4133,
"text": "In the above example, we have created two labels and at the end we have added that label to our layout. You will learn more about layouts in the upcoming chapters. The VaadinServlet has been implemented in order to control the URL. However, in real life projects, you need not define servlet in every java application as it will be interlinked. Select the file and click Run on Server and code given above will yield the output as shown below."
},
{
"code": null,
"e": 4884,
"s": 4577,
"text": "Link is useful to implement external links to the other website. This class works exactly similar to the hyperlink tag of HTML. In the example given below, we will be using Link to redirect our user to another website depending on an event called Click here. Now, modify the MyUI.java class as shown below."
},
{
"code": null,
"e": 6069,
"s": 4884,
"text": "package com.example.myapplication;\n\nimport javax.servlet.annotation.WebServlet;\nimport com.vaadin.annotations.Theme;\nimport com.vaadin.annotations.VaadinServletConfiguration;\nimport com.vaadin.server.ExternalResource;\nimport com.vaadin.server.VaadinRequest;\nimport com.vaadin.server.VaadinServlet;\nimport com.vaadin.shared.ui.ContentMode;\n\nimport com.vaadin.ui.Button;\nimport com.vaadin.ui.HorizontalLayout;\nimport com.vaadin.ui.Label;\nimport com.vaadin.ui.Link;\nimport com.vaadin.ui.TextField;\nimport com.vaadin.ui.UI;\nimport com.vaadin.ui.VerticalLayout;\n\n@Theme(\"mytheme\")\npublic class MyUI extends UI {\n @Override\n protected void init(VaadinRequest vaadinRequest) {\n final VerticalLayout layout = new VerticalLayout();\n \n final HorizontalLayout hLayout = new HorizontalLayout();\n \n Link link = new Link(\"Click Me\",new ExternalResource(\"https://www.tutorialspoint.com/\"));\n hLayout.addComponent(link);\n setContent(hLayout);\n }\n @WebServlet(urlPatterns = \"/*\", name = \"MyUIServlet\", asyncSupported = true)\n @VaadinServletConfiguration(ui = MyUI.class, productionMode = false)\n public static class MyUIServlet extends VaadinServlet {}\n}"
},
{
"code": null,
"e": 6202,
"s": 6069,
"text": "In the above example, we have created an external hyperlink to another website. It will give us the following output in the browser."
},
{
"code": null,
"e": 6279,
"s": 6202,
"text": "Once users click the link, they will be redirected to www.tutorialspoint.com"
},
{
"code": null,
"e": 6416,
"s": 6279,
"text": "This section talks about how to generate a text field using Vaadin build in class. For this, update your MyUI.java class as shown below."
},
{
"code": null,
"e": 7443,
"s": 6416,
"text": "package com.example.myapplication;\n\nimport javax.servlet.annotation.WebServlet;\nimport com.vaadin.annotations.Theme;\nimport com.vaadin.annotations.VaadinServletConfiguration;\nimport com.vaadin.server.VaadinRequest;\n\nimport com.vaadin.server.VaadinServlet;\nimport com.vaadin.shared.ui.ContentMode;\nimport com.vaadin.ui.Label;\nimport com.vaadin.ui.TextField;\nimport com.vaadin.ui.UI;\nimport com.vaadin.ui.VerticalLayout;\n\n@Theme(\"mytheme\")\npublic class MyUI extends UI {\n @Override\n protected void init(VaadinRequest vaadinRequest) {\n final VerticalLayout layout = new VerticalLayout();\n Label l1 = new Label(\"Example of TextField--\\n \",ContentMode.PREFORMATTED);\n TextField text = new TextField();\n text.setValue(\"----\");\n layout.addComponents(l1,text);\n setContent(layout);\n }\n @WebServlet(urlPatterns = \"/*\", name = \"MyUIServlet\", asyncSupported = true)\n @VaadinServletConfiguration(ui = MyUI.class, productionMode = false)\n public static class MyUIServlet extends VaadinServlet {}\n}"
},
{
"code": null,
"e": 7605,
"s": 7443,
"text": "Now, refresh your project and clean build it. You can observe the output shown below in your browser. Remember to restart your browser to get its recent changes."
},
{
"code": null,
"e": 7745,
"s": 7605,
"text": "This section explains you how to create a text area in the browser using Vaadin predefined class. Observe the code given below for example."
},
{
"code": null,
"e": 8810,
"s": 7745,
"text": "package com.example.myapplication;\n\nimport javax.servlet.annotation.WebServlet;\nimport com.vaadin.annotations.Theme;\nimport com.vaadin.annotations.VaadinServletConfiguration;\nimport com.vaadin.server.VaadinRequest;\nimport com.vaadin.server.VaadinServlet;\n\nimport com.vaadin.ui.Alignment;\nimport com.vaadin.ui.TextArea;\nimport com.vaadin.ui.UI;\nimport com.vaadin.ui.VerticalLayout;\n\n@Theme(\"mytheme\")\npublic class MyUI extends UI {\n @Override\n protected void init(VaadinRequest vaadinRequest) {\n final VerticalLayout layout = new VerticalLayout();\n final VerticalLayout hLayout = new VerticalLayout();\n TextArea text = new TextArea();\n text.setValue(\" I am the example of Text Area in Vaadin\");\n hLayout.addComponent(text);\n hLayout.setComponentAlignment(text,Alignment.BOTTOM_CENTER);\n setContent(hLayout);\n }\n @WebServlet(urlPatterns = \"/*\", name = \"MyUIServlet\", asyncSupported = true)\n @VaadinServletConfiguration(ui = MyUI.class, productionMode = false)\n public static class MyUIServlet extends VaadinServlet {}\n}"
},
{
"code": null,
"e": 8875,
"s": 8810,
"text": "The above piece of code will yield below output in the browser −"
},
{
"code": null,
"e": 10229,
"s": 8875,
"text": "package com.example.myapplication;\n\nimport java.time.LocalDate;\nimport java.util.Locale;\nimport javax.servlet.annotation.WebServlet;\nimport com.vaadin.annotations.Theme;\nimport com.vaadin.annotations.VaadinServletConfiguration;\nimport com.vaadin.server.VaadinRequest;\n\nimport com.vaadin.server.VaadinServlet;\nimport com.vaadin.shared.ui.ContentMode;\nimport com.vaadin.ui.Alignment;\nimport com.vaadin.ui.DateField;\nimport com.vaadin.ui.Label;\nimport com.vaadin.ui.UI;\nimport com.vaadin.ui.VerticalLayout;\n\n@Theme(\"mytheme\")\npublic class MyUI extends UI {\n @Override\n protected void init(VaadinRequest vaadinRequest) {\n final VerticalLayout layout = new VerticalLayout();\n final VerticalLayout hLayout = new VerticalLayout();\n Label l1 = new Label(\"Enter today's Date\\n\",ContentMode.PREFORMATTED);\n DateField date = new DateField();\n date.setValue(LocalDate.now());\n date.setLocale(new Locale(\"en\",\"IND\"));\n hLayout.addComponents(l1,date);\n hLayout.setComponentAlignment(l1,Alignment.BOTTOM_CENTER);\n hLayout.setComponentAlignment(date,Alignment.BOTTOM_CENTER);\n setContent(hLayout);\n }\n @WebServlet(urlPatterns = \"/*\", name = \"MyUIServlet\", asyncSupported = true)\n @VaadinServletConfiguration(ui = MyUI.class, productionMode = false)\n public static class MyUIServlet extends VaadinServlet {\n}"
},
{
"code": null,
"e": 10413,
"s": 10229,
"text": "In the above example, we have used Vaadin predefined date function to populate the date component in the webpage. This code will give you the output as shown in the screenshot below −"
},
{
"code": null,
"e": 10534,
"s": 10413,
"text": "The code given below will explain you how to apply a button in the web page. Here, we have used a button named Click Me."
},
{
"code": null,
"e": 11961,
"s": 10534,
"text": "package com.example.myapplication;\n\nimport javax.servlet.annotation.WebServlet;\nimport com.vaadin.annotations.Theme;\nimport com.vaadin.annotations.VaadinServletConfiguration;\nimport com.vaadin.server.ExternalResource;\nimport com.vaadin.server.VaadinRequest;\nimport com.vaadin.server.VaadinServlet;\nimport com.vaadin.shared.ui.ContentMode;\nimport com.vaadin.ui.Alignment;\nimport com.vaadin.ui.Button;\n\nimport com.vaadin.ui.HorizontalLayout;\nimport com.vaadin.ui.Label;\nimport com.vaadin.ui.Link;\nimport com.vaadin.ui.TextArea;\nimport com.vaadin.ui.TextField;\nimport com.vaadin.ui.UI;\nimport com.vaadin.ui.VerticalLayout;\n\n@Theme(\"mytheme\")\npublic class MyUI extends UI {\n @Override\n protected void init(VaadinRequest vaadinRequest) {\n final VerticalLayout layout = new VerticalLayout();\n final VerticalLayout hLayout = new VerticalLayout();\n TextArea text = new TextArea();\n text.setValue(\"Please enter some Value\");\n Button b = new Button(\"Click Me\");\n hLayout.addComponent(text);\n hLayout.addComponent(b);\n hLayout.setComponentAlignment(text,Alignment.BOTTOM_CENTER);\n hLayout.setComponentAlignment(b,Alignment.BOTTOM_CENTER);\n setContent(hLayout);\n }\n @WebServlet(urlPatterns = \"/*\", name = \"MyUIServlet\", asyncSupported = true)\n \n @VaadinServletConfiguration(ui = MyUI.class, productionMode = false)\n public static class MyUIServlet extends VaadinServlet {}\n}"
},
{
"code": null,
"e": 12113,
"s": 11961,
"text": "Vaadin also provides inbuilt class to create a checkbox in the webpage. In the below example we will create a checkbox using Vaadin rich web component."
},
{
"code": null,
"e": 13662,
"s": 12113,
"text": "package com.example.myapplication;\n\nimport java.time.LocalDate;\nimport java.util.Locale;\nimport javax.servlet.annotation.WebServlet;\nimport com.vaadin.annotations.Theme;\nimport com.vaadin.annotations.VaadinServletConfiguration;\nimport com.vaadin.server.VaadinRequest;\nimport com.vaadin.server.VaadinServlet;\nimport com.vaadin.shared.ui.ContentMode;\nimport com.vaadin.ui.Alignment;\n\nimport com.vaadin.ui.CheckBox;\nimport com.vaadin.ui.DateField;\nimport com.vaadin.ui.Label;\nimport com.vaadin.ui.UI;\nimport com.vaadin.ui.VerticalLayout;\n\n@Theme(\"mytheme\")\npublic class MyUI extends UI {\n @Override\n protected void init(VaadinRequest vaadinRequest) {\n final VerticalLayout layout = new VerticalLayout();\n final VerticalLayout hLayout = new VerticalLayout();\n Label l1 = new Label(\"Example of Check Box\\n\",ContentMode.PREFORMATTED);\n CheckBox chk1 = new CheckBox(\"Option1\");\n CheckBox chk2 = new CheckBox(\"Option2\");\n CheckBox chk3 = new CheckBox(\"Option3\");\n hLayout.addComponents(l1,chk1,chk2,chk3);\n hLayout.setComponentAlignment(l1,Alignment.BOTTOM_CENTER);\n hLayout.setComponentAlignment(chk1,Alignment.BOTTOM_CENTER);\n hLayout.setComponentAlignment(chk2,Alignment.BOTTOM_CENTER);\n hLayout.setComponentAlignment(chk3,Alignment.BOTTOM_CENTER);\n setContent(hLayout);\n }\n @WebServlet(urlPatterns = \"/*\", name = \"MyUIServlet\", asyncSupported = true)\n @VaadinServletConfiguration(ui = MyUI.class, productionMode = false)\n public static class MyUIServlet extends VaadinServlet {}\n}"
},
{
"code": null,
"e": 13898,
"s": 13662,
"text": "The code given above will yield output in the browser as shown below. You can also create any number of check boxes for the user. In the subsequent chapters, you will learn about different ways to populate the Check Box in the webpage."
},
{
"code": null,
"e": 14196,
"s": 13898,
"text": "This section explains you how to bind the data from the front end to back end using Vaadin as framework. Note that the code shown below takes input from the front end with the data field. Let us create a bean class in order to bind the data field. Create a java class and name it as Employee.java."
},
{
"code": null,
"e": 14815,
"s": 14196,
"text": "package com.example.myapplication;\n\npublic class EmployeeBean {\n \n private String name = \"\";\n private String Email = \" \";\n public EmployeeBean() {\n super();\n // TODO Auto-generated constructor stub\n }\n public EmployeeBean(String name, String email) {\n super();\n this.name = name;\n Email = email;\n }\n public String getName() {\n return name;\n }\n public void setName(String name) {\n System.out.println(\"asdassd\");\n this.name = name;\n }\n public String getEmail() {\n return Email;\n }\n public void setEmail(String email) {\n Email = email; \n }\n}"
},
{
"code": null,
"e": 14947,
"s": 14815,
"text": "We have to modify MyUI.java class in order to bind the data field of employee class. Observe the following code for modified class."
},
{
"code": null,
"e": 16719,
"s": 14947,
"text": "package com.example.myapplication;\n\nimport javax.servlet.annotation.WebServlet;\nimport com.vaadin.annotations.PropertyId;\nimport com.vaadin.annotations.Theme;\nimport com.vaadin.annotations.VaadinServletConfiguration;\nimport com.vaadin.data.Binder;\nimport com.vaadin.server.VaadinRequest;\nimport com.vaadin.server.VaadinServlet;\nimport com.vaadin.shared.ui.ContentMode;\nimport com.vaadin.ui.Alignment;\n\nimport com.vaadin.ui.Button;\nimport com.vaadin.ui.Button.ClickEvent;\nimport com.vaadin.ui.CheckBox;\nimport com.vaadin.ui.FormLayout;\nimport com.vaadin.ui.Label;\nimport com.vaadin.ui.TextField;\nimport com.vaadin.ui.UI;\nimport com.vaadin.ui.VerticalLayout;\n\n@Theme(\"mytheme\")\npublic class MyUI extends UI {\n @Override\n protected void init(VaadinRequest vaadinRequest) {\n EmployeeBean bean = new EmployeeBean(\"TutorialsPoint\",\"[email protected]\");\n Binder<EmployeeBean> binder = new Binder <EmployeeBean>();\n final FormLayout form = new FormLayout();\n Label l1 = new Label(\"Please fill Below Form\");\n Label labelName = new Label(\"Name--\");\n TextField name = new TextField();\n binder.bind(name,EmployeeBean::getName,EmployeeBean::setName);\n Label labelEmail = new Label(\"Email---\");\n TextField email = new TextField();\n binder.bind(email,EmployeeBean::getEmail,EmployeeBean::setEmail);\n Button button = new Button(\"Process..\");\n form.addComponents(l1,labelName,name,labelEmail,email,button);\n setContent(form);\n binder.setBean(bean); //auto binding using in built method\n }\n @WebServlet(urlPatterns = \"/*\", name = \"MyUIServlet\", asyncSupported = true)\n @VaadinServletConfiguration(ui = MyUI.class, productionMode = false)\n public static class MyUIServlet extends VaadinServlet {\n }\n}"
},
{
"code": null,
"e": 16788,
"s": 16719,
"text": "The code given above will yield the following output in the browser."
},
{
"code": null,
"e": 17241,
"s": 16788,
"text": "Table is one of the most usable features of Vaadin. Table cells can include any type of data. Table component is developed for showing all data in a tabular format organized into a row and column structure. However, since Vaadin 8 release table feature has been absolute and the same feature has been modified with the Grid component. If you are still using an older version of Vaadin, then you are free to use table as shown in the format given below."
},
{
"code": null,
"e": 18160,
"s": 17241,
"text": "/* Create the table with a caption. */\nTable table = new Table(\"This is my Table\");\n/* Define the names and data types of columns.\n* The \"default value\" parameter is meaningless here. */\n\ntable.addContainerProperty(\"First Name\", String.class, null);\ntable.addContainerProperty(\"Last Name\", String.class, null);\ntable.addContainerProperty(\"Year\", Integer.class, null);\n\n/* Add a few items in the table. */\ntable.addItem(new Object[] {\"Nicolaus\",\"Copernicus\",new Integer(1473)}, new Integer(1));\ntable.addItem(new Object[] {\"Tycho\", \"Brahe\", new Integer(1546)}, new Integer(2));\ntable.addItem(new Object[] {\"Giordano\",\"Bruno\", new Integer(1548)}, new Integer(3));\ntable.addItem(new Object[] {\"Galileo\", \"Galilei\", new Integer(1564)}, new Integer(4));\ntable.addItem(new Object[] {\"Johannes\",\"Kepler\", new Integer(1571)}, new Integer(5));\ntable.addItem(new Object[] {\"Isaac\", \"Newton\", new Integer(1643)}, new Integer(6));"
},
{
"code": null,
"e": 18269,
"s": 18160,
"text": "In the upcoming chapter on GRID, you will learn more about Grid creation and populating data using the same."
},
{
"code": null,
"e": 18481,
"s": 18269,
"text": "Tree Component is used to populate directory structure in the website. In this section, you will learn how to populate a tree in the webpage using Vaadin framework. Update the required MyUI class as shown below."
},
{
"code": null,
"e": 19760,
"s": 18481,
"text": "package com.example.myapplication;\n\nimport javax.servlet.annotation.WebServlet;\nimport com.vaadin.annotations.Theme;\nimport com.vaadin.annotations.VaadinServletConfiguration;\nimport com.vaadin.data.TreeData;\nimport com.vaadin.server.VaadinRequest;\nimport com.vaadin.server.VaadinServlet;\nimport com.vaadin.ui.Component;\nimport com.vaadin.ui.Tree;\nimport com.vaadin.ui.UI;\nimport com.vaadin.ui.VerticalLayout;\n\n@Theme(\"mytheme\")\npublic class MyUI extends UI {\n @Override\n protected void init(VaadinRequest vaadinRequest) {\n VerticalLayout layout = new VerticalLayout();\n Tree<String> tree = new Tree<>();\n TreeData<String> treeData =tree.getTreeData();\n\n // Couple of childless root items\n treeData.addItem(null, \"Option1\");\n treeData.addItem(\"Option1\", \"Child1\");\n treeData.addItem(null, \"Option2\");\n treeData.addItem(\"Option2\", \"Child2\");\n\n // Items with hierarchy\n treeData.addItem(null, \"Option3\");\n treeData.addItem(\"Option3\", \"Child3\");\n layout.addComponent(tree);\n setContent(layout);\n }\n @WebServlet(urlPatterns = \"/*\", name = \"MyUIServlet\", asyncSupported = true)\n @VaadinServletConfiguration(ui = MyUI.class, productionMode = false)\n public static class MyUIServlet extends VaadinServlet {}\n}"
},
{
"code": null,
"e": 19834,
"s": 19760,
"text": "The above piece of code will produce the following output in the browser."
},
{
"code": null,
"e": 20076,
"s": 19834,
"text": "Menu Bar component helps us to create a menu in the website. It can be dynamic as well as it can be nested. Find below example where we have created a nested menu bar using Vaadin Menu Bar component. Go ahead and modify our class like below."
},
{
"code": null,
"e": 22485,
"s": 20076,
"text": "package com.example.myapplication;\n\nimport javax.servlet.annotation.WebServlet;\nimport com.vaadin.annotations.Theme;\nimport com.vaadin.annotations.VaadinServletConfiguration;\nimport com.vaadin.data.TreeData;\nimport com.vaadin.server.VaadinRequest;\nimport com.vaadin.server.VaadinServlet;\n\nimport com.vaadin.ui.Component;\nimport com.vaadin.ui.Label;\nimport com.vaadin.ui.MenuBar;\nimport com.vaadin.ui.MenuBar.MenuItem;\nimport com.vaadin.ui.Tree;\nimport com.vaadin.ui.UI;\nimport com.vaadin.ui.VerticalLayout;\n\n@Theme(\"mytheme\")\npublic class MyUI extends UI {\n @Override\n protected void init(VaadinRequest vaadinRequest) {\n VerticalLayout layout = new VerticalLayout();\n MenuBar barmenu = new MenuBar();\n layout.addComponent(barmenu);\n\n // A feedback component\n final Label selection = new Label(\"-\");\n layout.addComponent(selection);\n\n // Define a common menu command for all the menu items.\n MenuBar.Command mycommand = new MenuBar.Command() {\n public void menuSelected(MenuItem selectedItem) {\n selection.setValue(\"Ordered a \" +\n selectedItem.getText() +\n \" from menu.\");\n }\n };\n \n // Put some items in the menu hierarchically\n MenuBar.MenuItem beverages =\n barmenu.addItem(\"Beverages\", null, null);\n MenuBar.MenuItem hot_beverages =\n beverages.addItem(\"Hot\", null, null);\n hot_beverages.addItem(\"Tea\", null, mycommand);\n hot_beverages.addItem(\"Coffee\", null, mycommand);\n MenuBar.MenuItem cold_beverages =\n beverages.addItem(\"Cold\", null, null);\n cold_beverages.addItem(\"Milk\", null, mycommand);\n cold_beverages.addItem(\"Weissbier\", null, mycommand);\n \n // Another top-level item\n MenuBar.MenuItem snacks =\n barmenu.addItem(\"Snacks\", null, null);\n snacks.addItem(\"Weisswurst\", null, mycommand);\n snacks.addItem(\"Bratwurst\", null, mycommand);\n snacks.addItem(\"Currywurst\", null, mycommand);\n \n // Yet another top-level item\n MenuBar.MenuItem services =\n barmenu.addItem(\"Services\", null, null);\n services.addItem(\"Car Service\", null, mycommand);\n setContent(layout);\n }\n @WebServlet(urlPatterns = \"/*\", name = \"MyUIServlet\", asyncSupported = true)\n @VaadinServletConfiguration(ui = MyUI.class, productionMode = false)\n public static class MyUIServlet extends VaadinServlet {}\n}"
},
{
"code": null,
"e": 22644,
"s": 22485,
"text": "In the example discussed above, we have created a nested menu bar. Run the above piece of code and you can observe the output in your browser as shown below −"
},
{
"code": null,
"e": 22651,
"s": 22644,
"text": " Print"
},
{
"code": null,
"e": 22662,
"s": 22651,
"text": " Add Notes"
}
] |
Safely Test and Apply Changes to Your Database: Getting Started with Alembic | by Mike Huls | Towards Data Science | If you are not working with migrations in your database you’re missing out. Database migrations establish the structure and history of changes of our database in code and provide us with the ability to safely apply and revert these changes to our database.
In this article we’ll take a look at a Alembic; a Python tool that makes working with migrations very easy. With it we’ll create migrations that are database-agnostic (meaning you can execute them on any database. These migrations are defined in code which means that we can apply Git-like version control; tracking changes, having a single source of the truth and the ability to collaborate with multiple developers. When you’ve read this article you’ll be able to:
Define changes to the database structure in code
version control the changes
Apply and revert the migrations
Apply the migrations to multiple databases (e.g. testing on a dev database and then migrating the definitive structure to a production database)
Not only create your required tables but also add indices and associations
In order to show you all of the features you’ll need to impress your coworkers, I’ve defined 5steps:
Installation and setting upCreating MigrationsExecuting and undoing migrationsApplying changes to existing databasesApplying new migrations to a different database
Installation and setting up
Creating Migrations
Executing and undoing migrations
Applying changes to existing databases
Applying new migrations to a different database
We’re going to use a Python package called Alembic. This package makes it easy to create the database migrations.
Installation is simple. Open a terminal, navigate to your project directory and execute the code below. This will install and initialize Alembic. Notice that a folder is created in the root called /alembic.
Unfamiliar with using a terminal? Check out this article.
pip install alembicalembic init alembic
Next we’ll set up a database connection. Alembic has to know to which database to connect. Normally we’d specify this in /alembic.ini by adjusting the sqlalchemy.url but it’s better to overwrite this value. Open /alembic/env.py and find config = context.config. Below this insert the following:
Keep your credentials safe: it is recommended to load the connection string from an environment variable. If you upload this project to a public repository anyone can see your credentials. Using environment variables you can keep your credentials safe by putting all of your confidential information like passwords and connections strings in a single file that we can .gitignore. Check out how this works in this article.
Let’s test our connection with by running alembic current in the terminal. This shows in which state our database is at the moment. If you see something like the text below you’ve successfully connected to the database.
INFO [alembic.runtime.migration] Context impl PostgresqlImpl.INFO [alembic.runtime.migration] Will assume transactional DDL.
Execute the following code to create your first migration: alembic revison -m "create test schema" This creates a new file in /alembic/versions. This file is our actual migration and it contains two functions:1. upgrade2. downgrade
In the first function we’ll put the code we want to execute, for example creating a schema. In the second function we’ll put the code that undoes our actions in the first function, for example dropping the schema:
In the upgrade we tell alembic to execute some SQL for creating a schema. In the downgrade we place instructions to undo exactly this, dropping the schema.
Pretty clear right? Let’s create some tables! We’ll create three tables: students, classes and student_classes. Students and classes will be tables that, obviously, store information on students and classes. Student_classes will connect one or more student-id’s to one or more class-id’s. This is because a student can have multiple classes while a class can have multiple students:
Students table
As you can see we use the op.create_table function to create a table. First we’ll specify the table name, then all columns. Lastly we specify the schema name. If you just want to use the default schema this can be omitted. Also notice that we add constraints like the primary key and ‘nullable’. Again the downgrade function undoes the upgrade.
The classes tableWe’ll only look at the upgrade function here:
The student_classes tableIn this table we need to do something fancy. Because this table just exists to bind students to classes and vice versa we can define some more functionalities:
You see that in the code above we define foreignKeys with an ondelete=”CASCADE” flag. This means that if a class or a student gets deleted from their tables (a student graduates or a class is discontinued), then these deletions cascade into the student_class table; deleting associated records. This keeps our data nice and clean.
Now that we’ve defined all of our tables and relations it’s time to reflect them in the database. In your terminal simply execute:alembic upgrade head
This tells alembic to upgrade all scripts until the head like in Git. Afterwards we can call alembic history to show something like this:
(venv) C:\rnd\med_alembic>alembic historya3e1bb14f43b -> a46099cad4d5 (head), student_classes058a1e623c60 -> a3e1bb14f43b, create classes table73d31032477a -> 058a1e623c60, create students tableRevision ID: 058a1e623c60Revises: 73d31032477aCreate Date: 2021–10–22 12:58:23.303590<base> -> 73d31032477a, create test schema
This shows all of the migrations we’ve performed with a code in front of it. We can use this code to downgrade like:alembic downgrade 058a1e623c60
This will undo all migrations until the creation of the “create students table” migration.To go back one migration: alembic downgrade -1 (the number, not an L)To revert all migrations: alembic downgrade base
If you’re still testing and developing the database you can really easily reset. Image that you’ve inserted some data and found a bug in one of your migrations; maybe a wrong column name. Just adjust the errors in the upgrade functions and call:alembic downgrade base && alembic upgrade headThis will reset your entire database in just one statement! While this is very handy for your development database I wouldn’t recommend performing this command on your production database because all data will be lost.fenv
Sometimes you need to make adjustments to existing tables; renaming a column, adjusting a datatype or adding indices or constraints. With Alembic you can design, test and validate these changes by first developing them on a development database. Once your satisfied that everything works you can just plug in a different .env file and migrate all new changes to the production database! Below are some examples on how to this.
Imagine that these tables are in production but there’s something missing. First we’d like to add a UNIQUE constraint to the name column in the classes table; we can’t have multiple classes with the same name. We create a new migration with alembic revision -m “create unique constraint classes.name”
Then add the following content:
Easy as that!
Next problem: our student table has grown quite a lot. Let’s add an index! alembic revision -m “add index on students.nameThe code below will create the index.
Renaming a column, changing data types and adjusting some constraints (nullable etc) can be changed with the alter_column function:
This changes the column name from “name” to “student_name” and the from a String() to a String with a length of max 100 characters.Notice that the downgrade undoes all of our changes again.
Don’t forget to check out the difference before and after alembic upgrade head!
No that we’ve tested all of our migrations on our Postgres dev database it’s time to migrate all changes to our production database. For this we only have to connect to the production database and perform our migrations. The best way to do this is using a file that securely holds all of our connection info.
Remember the /alembic/env.py file from part 1? This is where we define our database connection string. All we have to do is to plug a different .env file into Alembic. Then we can load the parts of the connection string from the environment. In this case I would use the python-dotenv package to load the .env file and create the connection string like below. More on how to use env file here.
db_user = os.environ.get("DB_USER")db_pass = os.environ.get("DB_PASS")db_host = os.environ.get("DB_HOST")db_name = os.environ.get("DB_NAME")db_type = os.environ.get("DB_TYPE")config.set_main_option('sqlalchemy.url', f'{db_type}://{db_user}:{db_pass}@{db_host}/{db_name}')
Database migrations provide us with the ability to safely test and apply changes to our database. Because we write out all of the changes in code we can include them into our version control which offers even more security. All in all using Alembic is easy, safe and a great idea for designing, testing and changing your database. I hope to have shed some light on how these migrations work and how to use Alembic.
If you have suggestions/clarifications please comment so I can improve this article. In the meantime, check out my other articles on all kinds of programming-related topics like these:
Create a fast auto-documented, maintainable and easy-to-use Python API in 5 lines of code with FastAPI
Python to SQL — UPSERT Safely, Easily and Fast
Create and publish your own Python package
Create Your Custom, private Python Package That You Can PIP Install From Your Git Repository
Virtual environments for absolute beginners — what is it and how to create one (+ examples)
Dramatically improve your database insert speed with a simple upgrade
Happy coding!
— Mike
P.S: like what I’m doing? Follow me! | [
{
"code": null,
"e": 428,
"s": 171,
"text": "If you are not working with migrations in your database you’re missing out. Database migrations establish the structure and history of changes of our database in code and provide us with the ability to safely apply and revert these changes to our database."
},
{
"code": null,
"e": 895,
"s": 428,
"text": "In this article we’ll take a look at a Alembic; a Python tool that makes working with migrations very easy. With it we’ll create migrations that are database-agnostic (meaning you can execute them on any database. These migrations are defined in code which means that we can apply Git-like version control; tracking changes, having a single source of the truth and the ability to collaborate with multiple developers. When you’ve read this article you’ll be able to:"
},
{
"code": null,
"e": 944,
"s": 895,
"text": "Define changes to the database structure in code"
},
{
"code": null,
"e": 972,
"s": 944,
"text": "version control the changes"
},
{
"code": null,
"e": 1004,
"s": 972,
"text": "Apply and revert the migrations"
},
{
"code": null,
"e": 1149,
"s": 1004,
"text": "Apply the migrations to multiple databases (e.g. testing on a dev database and then migrating the definitive structure to a production database)"
},
{
"code": null,
"e": 1224,
"s": 1149,
"text": "Not only create your required tables but also add indices and associations"
},
{
"code": null,
"e": 1325,
"s": 1224,
"text": "In order to show you all of the features you’ll need to impress your coworkers, I’ve defined 5steps:"
},
{
"code": null,
"e": 1489,
"s": 1325,
"text": "Installation and setting upCreating MigrationsExecuting and undoing migrationsApplying changes to existing databasesApplying new migrations to a different database"
},
{
"code": null,
"e": 1517,
"s": 1489,
"text": "Installation and setting up"
},
{
"code": null,
"e": 1537,
"s": 1517,
"text": "Creating Migrations"
},
{
"code": null,
"e": 1570,
"s": 1537,
"text": "Executing and undoing migrations"
},
{
"code": null,
"e": 1609,
"s": 1570,
"text": "Applying changes to existing databases"
},
{
"code": null,
"e": 1657,
"s": 1609,
"text": "Applying new migrations to a different database"
},
{
"code": null,
"e": 1771,
"s": 1657,
"text": "We’re going to use a Python package called Alembic. This package makes it easy to create the database migrations."
},
{
"code": null,
"e": 1978,
"s": 1771,
"text": "Installation is simple. Open a terminal, navigate to your project directory and execute the code below. This will install and initialize Alembic. Notice that a folder is created in the root called /alembic."
},
{
"code": null,
"e": 2036,
"s": 1978,
"text": "Unfamiliar with using a terminal? Check out this article."
},
{
"code": null,
"e": 2076,
"s": 2036,
"text": "pip install alembicalembic init alembic"
},
{
"code": null,
"e": 2371,
"s": 2076,
"text": "Next we’ll set up a database connection. Alembic has to know to which database to connect. Normally we’d specify this in /alembic.ini by adjusting the sqlalchemy.url but it’s better to overwrite this value. Open /alembic/env.py and find config = context.config. Below this insert the following:"
},
{
"code": null,
"e": 2793,
"s": 2371,
"text": "Keep your credentials safe: it is recommended to load the connection string from an environment variable. If you upload this project to a public repository anyone can see your credentials. Using environment variables you can keep your credentials safe by putting all of your confidential information like passwords and connections strings in a single file that we can .gitignore. Check out how this works in this article."
},
{
"code": null,
"e": 3013,
"s": 2793,
"text": "Let’s test our connection with by running alembic current in the terminal. This shows in which state our database is at the moment. If you see something like the text below you’ve successfully connected to the database."
},
{
"code": null,
"e": 3138,
"s": 3013,
"text": "INFO [alembic.runtime.migration] Context impl PostgresqlImpl.INFO [alembic.runtime.migration] Will assume transactional DDL."
},
{
"code": null,
"e": 3370,
"s": 3138,
"text": "Execute the following code to create your first migration: alembic revison -m \"create test schema\" This creates a new file in /alembic/versions. This file is our actual migration and it contains two functions:1. upgrade2. downgrade"
},
{
"code": null,
"e": 3584,
"s": 3370,
"text": "In the first function we’ll put the code we want to execute, for example creating a schema. In the second function we’ll put the code that undoes our actions in the first function, for example dropping the schema:"
},
{
"code": null,
"e": 3740,
"s": 3584,
"text": "In the upgrade we tell alembic to execute some SQL for creating a schema. In the downgrade we place instructions to undo exactly this, dropping the schema."
},
{
"code": null,
"e": 4123,
"s": 3740,
"text": "Pretty clear right? Let’s create some tables! We’ll create three tables: students, classes and student_classes. Students and classes will be tables that, obviously, store information on students and classes. Student_classes will connect one or more student-id’s to one or more class-id’s. This is because a student can have multiple classes while a class can have multiple students:"
},
{
"code": null,
"e": 4138,
"s": 4123,
"text": "Students table"
},
{
"code": null,
"e": 4483,
"s": 4138,
"text": "As you can see we use the op.create_table function to create a table. First we’ll specify the table name, then all columns. Lastly we specify the schema name. If you just want to use the default schema this can be omitted. Also notice that we add constraints like the primary key and ‘nullable’. Again the downgrade function undoes the upgrade."
},
{
"code": null,
"e": 4546,
"s": 4483,
"text": "The classes tableWe’ll only look at the upgrade function here:"
},
{
"code": null,
"e": 4731,
"s": 4546,
"text": "The student_classes tableIn this table we need to do something fancy. Because this table just exists to bind students to classes and vice versa we can define some more functionalities:"
},
{
"code": null,
"e": 5062,
"s": 4731,
"text": "You see that in the code above we define foreignKeys with an ondelete=”CASCADE” flag. This means that if a class or a student gets deleted from their tables (a student graduates or a class is discontinued), then these deletions cascade into the student_class table; deleting associated records. This keeps our data nice and clean."
},
{
"code": null,
"e": 5213,
"s": 5062,
"text": "Now that we’ve defined all of our tables and relations it’s time to reflect them in the database. In your terminal simply execute:alembic upgrade head"
},
{
"code": null,
"e": 5351,
"s": 5213,
"text": "This tells alembic to upgrade all scripts until the head like in Git. Afterwards we can call alembic history to show something like this:"
},
{
"code": null,
"e": 5673,
"s": 5351,
"text": "(venv) C:\\rnd\\med_alembic>alembic historya3e1bb14f43b -> a46099cad4d5 (head), student_classes058a1e623c60 -> a3e1bb14f43b, create classes table73d31032477a -> 058a1e623c60, create students tableRevision ID: 058a1e623c60Revises: 73d31032477aCreate Date: 2021–10–22 12:58:23.303590<base> -> 73d31032477a, create test schema"
},
{
"code": null,
"e": 5820,
"s": 5673,
"text": "This shows all of the migrations we’ve performed with a code in front of it. We can use this code to downgrade like:alembic downgrade 058a1e623c60"
},
{
"code": null,
"e": 6028,
"s": 5820,
"text": "This will undo all migrations until the creation of the “create students table” migration.To go back one migration: alembic downgrade -1 (the number, not an L)To revert all migrations: alembic downgrade base"
},
{
"code": null,
"e": 6542,
"s": 6028,
"text": "If you’re still testing and developing the database you can really easily reset. Image that you’ve inserted some data and found a bug in one of your migrations; maybe a wrong column name. Just adjust the errors in the upgrade functions and call:alembic downgrade base && alembic upgrade headThis will reset your entire database in just one statement! While this is very handy for your development database I wouldn’t recommend performing this command on your production database because all data will be lost.fenv"
},
{
"code": null,
"e": 6969,
"s": 6542,
"text": "Sometimes you need to make adjustments to existing tables; renaming a column, adjusting a datatype or adding indices or constraints. With Alembic you can design, test and validate these changes by first developing them on a development database. Once your satisfied that everything works you can just plug in a different .env file and migrate all new changes to the production database! Below are some examples on how to this."
},
{
"code": null,
"e": 7270,
"s": 6969,
"text": "Imagine that these tables are in production but there’s something missing. First we’d like to add a UNIQUE constraint to the name column in the classes table; we can’t have multiple classes with the same name. We create a new migration with alembic revision -m “create unique constraint classes.name”"
},
{
"code": null,
"e": 7302,
"s": 7270,
"text": "Then add the following content:"
},
{
"code": null,
"e": 7316,
"s": 7302,
"text": "Easy as that!"
},
{
"code": null,
"e": 7476,
"s": 7316,
"text": "Next problem: our student table has grown quite a lot. Let’s add an index! alembic revision -m “add index on students.nameThe code below will create the index."
},
{
"code": null,
"e": 7608,
"s": 7476,
"text": "Renaming a column, changing data types and adjusting some constraints (nullable etc) can be changed with the alter_column function:"
},
{
"code": null,
"e": 7798,
"s": 7608,
"text": "This changes the column name from “name” to “student_name” and the from a String() to a String with a length of max 100 characters.Notice that the downgrade undoes all of our changes again."
},
{
"code": null,
"e": 7878,
"s": 7798,
"text": "Don’t forget to check out the difference before and after alembic upgrade head!"
},
{
"code": null,
"e": 8187,
"s": 7878,
"text": "No that we’ve tested all of our migrations on our Postgres dev database it’s time to migrate all changes to our production database. For this we only have to connect to the production database and perform our migrations. The best way to do this is using a file that securely holds all of our connection info."
},
{
"code": null,
"e": 8581,
"s": 8187,
"text": "Remember the /alembic/env.py file from part 1? This is where we define our database connection string. All we have to do is to plug a different .env file into Alembic. Then we can load the parts of the connection string from the environment. In this case I would use the python-dotenv package to load the .env file and create the connection string like below. More on how to use env file here."
},
{
"code": null,
"e": 8853,
"s": 8581,
"text": "db_user = os.environ.get(\"DB_USER\")db_pass = os.environ.get(\"DB_PASS\")db_host = os.environ.get(\"DB_HOST\")db_name = os.environ.get(\"DB_NAME\")db_type = os.environ.get(\"DB_TYPE\")config.set_main_option('sqlalchemy.url', f'{db_type}://{db_user}:{db_pass}@{db_host}/{db_name}')"
},
{
"code": null,
"e": 9268,
"s": 8853,
"text": "Database migrations provide us with the ability to safely test and apply changes to our database. Because we write out all of the changes in code we can include them into our version control which offers even more security. All in all using Alembic is easy, safe and a great idea for designing, testing and changing your database. I hope to have shed some light on how these migrations work and how to use Alembic."
},
{
"code": null,
"e": 9453,
"s": 9268,
"text": "If you have suggestions/clarifications please comment so I can improve this article. In the meantime, check out my other articles on all kinds of programming-related topics like these:"
},
{
"code": null,
"e": 9556,
"s": 9453,
"text": "Create a fast auto-documented, maintainable and easy-to-use Python API in 5 lines of code with FastAPI"
},
{
"code": null,
"e": 9603,
"s": 9556,
"text": "Python to SQL — UPSERT Safely, Easily and Fast"
},
{
"code": null,
"e": 9646,
"s": 9603,
"text": "Create and publish your own Python package"
},
{
"code": null,
"e": 9739,
"s": 9646,
"text": "Create Your Custom, private Python Package That You Can PIP Install From Your Git Repository"
},
{
"code": null,
"e": 9831,
"s": 9739,
"text": "Virtual environments for absolute beginners — what is it and how to create one (+ examples)"
},
{
"code": null,
"e": 9901,
"s": 9831,
"text": "Dramatically improve your database insert speed with a simple upgrade"
},
{
"code": null,
"e": 9915,
"s": 9901,
"text": "Happy coding!"
},
{
"code": null,
"e": 9922,
"s": 9915,
"text": "— Mike"
}
] |
Add perpendicular caps to error bars in Matplotlib - GeeksforGeeks | 26 Dec, 2020
Prerequisites: Matplotlib
The errorbar() function in pyplot module of matplotlib library is used to plot y versus x as lines and/or markers with attached errorbars. For our requirement we need to specifically focussing on capsize attribute of this function. Simply providing a value to it will produce our required functionality.
Syntax: matplotlib.pyplot.errorbar(x, y, yerr=None, xerr=None, fmt=”, ecolor=None, elinewidth=None, capsize=None, barsabove=False, lolims=False, uplims=False, xlolims=False, xuplims=False, errorevery=1, capthick=None, \*, data=None, \*\*kwargs)
Parameters: This method accept the following parameters that are described below:
x, y: These parameters are the horizontal and vertical coordinates of the data points.
fmt: This parameter is an optional parameter and it contains the string value.
capsize: This parameter is also an optional parameter. And it is the length of the error bar caps in points with default value NONE.
barsabove: This parameter is also an optional parameter. It contains boolean value True for plotting errorsbars above the plot symbols.Its default value is False.
errorevery: This parameter is also an optional parameter. They contain integer values which is used to draw error bars on a subset of the data.
Import module
Create data
Provide error values
Pass all the values to errorbar() function along with capsize attribute and its value
Display plot
Example 1:
Python3
import matplotlib.pyplot as plt x_values = [5, 4, 3, 2, 1]y_values = [8, 4, 9, 1, 0] y_error = [0, 0.3, 1, 0.2, 0.75] plt.errorbar(x_values, y_values, yerr=y_error, fmt='o', markersize=8, capsize=10) plt.show()
Output:
Example 2:
Python3
import matplotlib.pyplot as plt x_values = [0, 1, 2, 3, 4, 5]y_values = [8, 4, 9, 1, 0, 5] plt.plot(x_values, y_values)x_error = [0, 0.3, 1, 0.2, 0.75, 2] plt.errorbar(x_values, y_values, xerr=x_error, fmt='o', markersize=8, capsize=6, color="r") plt.show()
Output:
Example 3:
Python3
import matplotlib.pyplot as plt x_values = [0, 1, 2, 3, 4, 5]y_values = [8, 4, 9, 1, 0, 5] x_error = [0, 0.3, 1, 0.2, 0.75, 2]y_error = [0.3, 0.3, 2, 0.5, 0.7, 0.6] plt.errorbar(x_values, y_values, xerr=x_error, yerr=y_error, fmt='D', markersize=8, capsize=3, color="r") plt.show()
Output:
Picked
Python-matplotlib
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Enumerate() in Python
Read a file line by line in Python
Defaultdict in Python
Different ways to create Pandas Dataframe
sum() function in Python
Iterate over a list in Python
How to Install PIP on Windows ?
Deque in Python
Python String | replace()
Convert integer to string in Python | [
{
"code": null,
"e": 23865,
"s": 23837,
"text": "\n26 Dec, 2020"
},
{
"code": null,
"e": 23891,
"s": 23865,
"text": "Prerequisites: Matplotlib"
},
{
"code": null,
"e": 24195,
"s": 23891,
"text": "The errorbar() function in pyplot module of matplotlib library is used to plot y versus x as lines and/or markers with attached errorbars. For our requirement we need to specifically focussing on capsize attribute of this function. Simply providing a value to it will produce our required functionality."
},
{
"code": null,
"e": 24440,
"s": 24195,
"text": "Syntax: matplotlib.pyplot.errorbar(x, y, yerr=None, xerr=None, fmt=”, ecolor=None, elinewidth=None, capsize=None, barsabove=False, lolims=False, uplims=False, xlolims=False, xuplims=False, errorevery=1, capthick=None, \\*, data=None, \\*\\*kwargs)"
},
{
"code": null,
"e": 24522,
"s": 24440,
"text": "Parameters: This method accept the following parameters that are described below:"
},
{
"code": null,
"e": 24609,
"s": 24522,
"text": "x, y: These parameters are the horizontal and vertical coordinates of the data points."
},
{
"code": null,
"e": 24688,
"s": 24609,
"text": "fmt: This parameter is an optional parameter and it contains the string value."
},
{
"code": null,
"e": 24821,
"s": 24688,
"text": "capsize: This parameter is also an optional parameter. And it is the length of the error bar caps in points with default value NONE."
},
{
"code": null,
"e": 24984,
"s": 24821,
"text": "barsabove: This parameter is also an optional parameter. It contains boolean value True for plotting errorsbars above the plot symbols.Its default value is False."
},
{
"code": null,
"e": 25128,
"s": 24984,
"text": "errorevery: This parameter is also an optional parameter. They contain integer values which is used to draw error bars on a subset of the data."
},
{
"code": null,
"e": 25142,
"s": 25128,
"text": "Import module"
},
{
"code": null,
"e": 25154,
"s": 25142,
"text": "Create data"
},
{
"code": null,
"e": 25175,
"s": 25154,
"text": "Provide error values"
},
{
"code": null,
"e": 25261,
"s": 25175,
"text": "Pass all the values to errorbar() function along with capsize attribute and its value"
},
{
"code": null,
"e": 25274,
"s": 25261,
"text": "Display plot"
},
{
"code": null,
"e": 25285,
"s": 25274,
"text": "Example 1:"
},
{
"code": null,
"e": 25293,
"s": 25285,
"text": "Python3"
},
{
"code": "import matplotlib.pyplot as plt x_values = [5, 4, 3, 2, 1]y_values = [8, 4, 9, 1, 0] y_error = [0, 0.3, 1, 0.2, 0.75] plt.errorbar(x_values, y_values, yerr=y_error, fmt='o', markersize=8, capsize=10) plt.show()",
"e": 25521,
"s": 25293,
"text": null
},
{
"code": null,
"e": 25530,
"s": 25521,
"text": "Output: "
},
{
"code": null,
"e": 25541,
"s": 25530,
"text": "Example 2:"
},
{
"code": null,
"e": 25549,
"s": 25541,
"text": "Python3"
},
{
"code": "import matplotlib.pyplot as plt x_values = [0, 1, 2, 3, 4, 5]y_values = [8, 4, 9, 1, 0, 5] plt.plot(x_values, y_values)x_error = [0, 0.3, 1, 0.2, 0.75, 2] plt.errorbar(x_values, y_values, xerr=x_error, fmt='o', markersize=8, capsize=6, color=\"r\") plt.show()",
"e": 25824,
"s": 25549,
"text": null
},
{
"code": null,
"e": 25832,
"s": 25824,
"text": "Output:"
},
{
"code": null,
"e": 25844,
"s": 25832,
"text": "Example 3: "
},
{
"code": null,
"e": 25852,
"s": 25844,
"text": "Python3"
},
{
"code": "import matplotlib.pyplot as plt x_values = [0, 1, 2, 3, 4, 5]y_values = [8, 4, 9, 1, 0, 5] x_error = [0, 0.3, 1, 0.2, 0.75, 2]y_error = [0.3, 0.3, 2, 0.5, 0.7, 0.6] plt.errorbar(x_values, y_values, xerr=x_error, yerr=y_error, fmt='D', markersize=8, capsize=3, color=\"r\") plt.show()",
"e": 26153,
"s": 25852,
"text": null
},
{
"code": null,
"e": 26161,
"s": 26153,
"text": "Output:"
},
{
"code": null,
"e": 26168,
"s": 26161,
"text": "Picked"
},
{
"code": null,
"e": 26186,
"s": 26168,
"text": "Python-matplotlib"
},
{
"code": null,
"e": 26193,
"s": 26186,
"text": "Python"
},
{
"code": null,
"e": 26291,
"s": 26193,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 26300,
"s": 26291,
"text": "Comments"
},
{
"code": null,
"e": 26313,
"s": 26300,
"text": "Old Comments"
},
{
"code": null,
"e": 26335,
"s": 26313,
"text": "Enumerate() in Python"
},
{
"code": null,
"e": 26370,
"s": 26335,
"text": "Read a file line by line in Python"
},
{
"code": null,
"e": 26392,
"s": 26370,
"text": "Defaultdict in Python"
},
{
"code": null,
"e": 26434,
"s": 26392,
"text": "Different ways to create Pandas Dataframe"
},
{
"code": null,
"e": 26459,
"s": 26434,
"text": "sum() function in Python"
},
{
"code": null,
"e": 26489,
"s": 26459,
"text": "Iterate over a list in Python"
},
{
"code": null,
"e": 26521,
"s": 26489,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 26537,
"s": 26521,
"text": "Deque in Python"
},
{
"code": null,
"e": 26563,
"s": 26537,
"text": "Python String | replace()"
}
] |
Sum of Digit is Pallindrome or not | Practice | GeeksforGeeks | Given a number N.Find if the digit sum(or sum of digits) of N is a Palindrome number or not.
Note:A Palindrome number is a number which stays the same when reversed.Example- 121,131,7 etc.
Example 1:
Input:
N=56
Output:
1
Explanation:
The digit sum of 56 is 5+6=11.
Since, 11 is a palindrome number.Thus,
answer is 1.
Example 2:
Input:
N=98
Output:
0
Explanation:
The digit sum of 98 is 9+8=17.
Since 17 is not a palindrome,thus, answer
is 0.
Your Task:
You don't need to read input or print aything.Your Task is to complete the function isDigitSumPalindrome() which takes a number N as input parameter and returns 1 if the Digit sum of N is a palindrome.Otherwise it returns 0.
Expected Time Complexity:O(LogN)
Expected Auxillary Space:O(1)
Constraints:
1<=N<=109
+1
rapuriteja11 hours ago
class Solution: def isDigitSumPalindrome(self,N): num1 = 0 for i in str(N): num1 += int(i) num2 = str(num1)[::-1] if num1 == int(num2): return 1 else: return 0
0
mayank180919991 week ago
int isDigitSumPalindrome(int N) {
// code here
int sum=0,digit;
while(N!=0){
digit=N%10;
sum+=digit;
N=N/10;
}
int m=sum,rem;
int rev=0;
while(m!=0){
rem=m%10;
rev=rev*10+rem;
m=m/10;
}
if(sum==rev){
return 1;
}
return 0;
}
0
rsbly7300951 week ago
class Solution {
isDigitSumPalindrome(N){
// here time complexity is 4.72;
// let sum = N.toString().split("").reduce((a,b)=> Number(a) + Number(b));
// let rev = sum.toString().split('').reverse().join("");
// if(sum == rev){
// return 1;
// }
// else return 0;
// time complexity is 3.7;
let sum = 0;
while(N) {
sum = sum + (N%10);
N = Math.trunc(N/10);
}
let rev = 0;
N = sum;
while(N) {
rev = rev * 10 + (N%10);
N = Math.trunc(N/10);
}
if (sum == rev){
return 1;
}else return 0;
}
}
0
harshilrpanchal19982 weeks ago
java solution
String temp = String.valueOf(N); int sum=0;
for (int i=0 ; i < temp.length() ; i++){ sum += (temp.charAt(i) - '0'); } StringBuilder sb = new StringBuilder(String.valueOf(sum)); temp = sb.reverse().toString(); if (temp.equals(String.valueOf(sum))){ return 1; } return 0;
0
pranjalverma83492 weeks ago
// { Driver Code Starts// Initial Template for C++
#include <bits/stdc++.h>using namespace std;
// } Driver Code Ends// User function Template for C++
class Solution { public: int isDigitSumPalindrome(int N) { int c=N,d,s,v,n,g; while(c) { d=c%10; s=s+d; c=c/10; } v=s; while(v) { n=v%10; g=g*10+n; v=v/10; } if(g==s) {
return 1; } else return 0; }};
// { Driver Code Starts.int main() { int t; cin >> t; while (t--) { int N; cin >> N; Solution ob; cout << ob.isDigitSumPalindrome(N) << "\n"; }} // } Driver Code Ends
0
nyapparel17723 weeks ago
static boolean isPallindrome(int n) { int inputNum = n/10; // not chaing n to compare later int res=n%10; int pow =1; while(inputNum !=0) { res += ((inputNum%10) *10 *pow); inputNum /= 10; pow *=10; } return ( res == n) ? true : false;}
0
ershubhamkewat3 weeks ago
//Recursive solution without using java library
int isDigitSumPalindrome(int N) {
// code here
int sum = 0;
//doing sum of digits--================
while(N!=0){
sum = sum+N%10;
N=N/10;
}
String s = sum+"";
Solution sol = new Solution();
boolean flag = sol.checkPallindrome(0,s.length()-1,s);
if(flag==true)
return 1;
return 0;
}
//============= checking pallindrome=======
public boolean checkPallindrome(int i,int j,String str){
if((str.charAt(i)==str.charAt(j))&&i<j){
return checkPallindrome(i+1,j-1,str);
}else if(i>=j){
return true;
}
return false;
}
0
sayanmazumder9991 month ago
JAVA
String n = String.valueOf(N); int sum = 0; for(int i = 0; i < n.length(); i++) sum += (n.charAt(i) - '0'); StringBuilder str = new StringBuilder(String.valueOf(sum)); n = str.reverse().toString(); if(n.equals(String.valueOf(sum))) return 1; return 0;
0
0niharika22 months ago
int sum=0, x=N, rev=0; while(x){ sum+=x%10; x/=10; } x = sum; while(x){ rev = rev*10 + x%10; x/=10; } if(rev==sum) return 1; else return 0;
+1
krishnakshirsagar412 months ago
class Solution: def isDigitSumPalindrome(self,N): strr = str(N) list1 = [] list1 = list(map(int, strr.strip())) sum1 = sum(list1) if str(sum1) == str(sum1)[::-1]: return 1 return 0
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": 427,
"s": 238,
"text": "Given a number N.Find if the digit sum(or sum of digits) of N is a Palindrome number or not.\nNote:A Palindrome number is a number which stays the same when reversed.Example- 121,131,7 etc."
},
{
"code": null,
"e": 438,
"s": 427,
"text": "Example 1:"
},
{
"code": null,
"e": 556,
"s": 438,
"text": "Input:\nN=56\nOutput:\n1\nExplanation:\nThe digit sum of 56 is 5+6=11.\nSince, 11 is a palindrome number.Thus,\nanswer is 1."
},
{
"code": null,
"e": 567,
"s": 556,
"text": "Example 2:"
},
{
"code": null,
"e": 681,
"s": 567,
"text": "Input:\nN=98\nOutput:\n0\nExplanation:\nThe digit sum of 98 is 9+8=17.\nSince 17 is not a palindrome,thus, answer\nis 0."
},
{
"code": null,
"e": 918,
"s": 681,
"text": "\nYour Task:\nYou don't need to read input or print aything.Your Task is to complete the function isDigitSumPalindrome() which takes a number N as input parameter and returns 1 if the Digit sum of N is a palindrome.Otherwise it returns 0."
},
{
"code": null,
"e": 982,
"s": 918,
"text": "\nExpected Time Complexity:O(LogN)\nExpected Auxillary Space:O(1)"
},
{
"code": null,
"e": 1005,
"s": 982,
"text": "Constraints:\n1<=N<=109"
},
{
"code": null,
"e": 1008,
"s": 1005,
"text": "+1"
},
{
"code": null,
"e": 1031,
"s": 1008,
"text": "rapuriteja11 hours ago"
},
{
"code": null,
"e": 1260,
"s": 1031,
"text": "class Solution: def isDigitSumPalindrome(self,N): num1 = 0 for i in str(N): num1 += int(i) num2 = str(num1)[::-1] if num1 == int(num2): return 1 else: return 0"
},
{
"code": null,
"e": 1262,
"s": 1260,
"text": "0"
},
{
"code": null,
"e": 1287,
"s": 1262,
"text": "mayank180919991 week ago"
},
{
"code": null,
"e": 1684,
"s": 1287,
"text": " int isDigitSumPalindrome(int N) {\n // code here\n int sum=0,digit;\n while(N!=0){\n digit=N%10;\n sum+=digit;\n N=N/10;\n }\n int m=sum,rem;\n int rev=0;\n while(m!=0){\n rem=m%10;\n rev=rev*10+rem;\n m=m/10;\n }\n if(sum==rev){\n return 1;\n }\n return 0;\n }"
},
{
"code": null,
"e": 1686,
"s": 1684,
"text": "0"
},
{
"code": null,
"e": 1708,
"s": 1686,
"text": "rsbly7300951 week ago"
},
{
"code": null,
"e": 2395,
"s": 1708,
"text": "class Solution {\n isDigitSumPalindrome(N){\n // here time complexity is 4.72;\n // let sum = N.toString().split(\"\").reduce((a,b)=> Number(a) + Number(b));\n // let rev = sum.toString().split('').reverse().join(\"\");\n // if(sum == rev){\n // return 1;\n // }\n // else return 0;\n \n // time complexity is 3.7;\n let sum = 0;\n while(N) {\n sum = sum + (N%10);\n N = Math.trunc(N/10);\n }\n let rev = 0;\n N = sum;\n \n while(N) {\n rev = rev * 10 + (N%10);\n N = Math.trunc(N/10);\n }\n if (sum == rev){\n return 1;\n }else return 0;\n }\n}"
},
{
"code": null,
"e": 2397,
"s": 2395,
"text": "0"
},
{
"code": null,
"e": 2428,
"s": 2397,
"text": "harshilrpanchal19982 weeks ago"
},
{
"code": null,
"e": 2442,
"s": 2428,
"text": "java solution"
},
{
"code": null,
"e": 2491,
"s": 2444,
"text": " String temp = String.valueOf(N); int sum=0;"
},
{
"code": null,
"e": 2744,
"s": 2491,
"text": " for (int i=0 ; i < temp.length() ; i++){ sum += (temp.charAt(i) - '0'); } StringBuilder sb = new StringBuilder(String.valueOf(sum)); temp = sb.reverse().toString(); if (temp.equals(String.valueOf(sum))){ return 1; } return 0;"
},
{
"code": null,
"e": 2746,
"s": 2744,
"text": "0"
},
{
"code": null,
"e": 2774,
"s": 2746,
"text": "pranjalverma83492 weeks ago"
},
{
"code": null,
"e": 2825,
"s": 2774,
"text": "// { Driver Code Starts// Initial Template for C++"
},
{
"code": null,
"e": 2870,
"s": 2825,
"text": "#include <bits/stdc++.h>using namespace std;"
},
{
"code": null,
"e": 2925,
"s": 2870,
"text": "// } Driver Code Ends// User function Template for C++"
},
{
"code": null,
"e": 3209,
"s": 2925,
"text": "class Solution { public: int isDigitSumPalindrome(int N) { int c=N,d,s,v,n,g; while(c) { d=c%10; s=s+d; c=c/10; } v=s; while(v) { n=v%10; g=g*10+n; v=v/10; } if(g==s) {"
},
{
"code": null,
"e": 3292,
"s": 3209,
"text": " return 1; } else return 0; }};"
},
{
"code": null,
"e": 3491,
"s": 3292,
"text": "// { Driver Code Starts.int main() { int t; cin >> t; while (t--) { int N; cin >> N; Solution ob; cout << ob.isDigitSumPalindrome(N) << \"\\n\"; }} // } Driver Code Ends"
},
{
"code": null,
"e": 3493,
"s": 3491,
"text": "0"
},
{
"code": null,
"e": 3518,
"s": 3493,
"text": "nyapparel17723 weeks ago"
},
{
"code": null,
"e": 3758,
"s": 3518,
"text": "static boolean isPallindrome(int n) { int inputNum = n/10; // not chaing n to compare later int res=n%10; int pow =1; while(inputNum !=0) { res += ((inputNum%10) *10 *pow); inputNum /= 10; pow *=10; } return ( res == n) ? true : false;}"
},
{
"code": null,
"e": 3760,
"s": 3758,
"text": "0"
},
{
"code": null,
"e": 3786,
"s": 3760,
"text": "ershubhamkewat3 weeks ago"
},
{
"code": null,
"e": 3834,
"s": 3786,
"text": "//Recursive solution without using java library"
},
{
"code": null,
"e": 4580,
"s": 3836,
"text": "int isDigitSumPalindrome(int N) {\n // code here\n int sum = 0;\n //doing sum of digits--================\n while(N!=0){\n sum = sum+N%10;\n N=N/10;\n }\n \n \n \n String s = sum+\"\";\n Solution sol = new Solution();\n boolean flag = sol.checkPallindrome(0,s.length()-1,s);\n if(flag==true)\n return 1;\n return 0;\n \n }\n \n //============= checking pallindrome=======\n \n public boolean checkPallindrome(int i,int j,String str){\n if((str.charAt(i)==str.charAt(j))&&i<j){\n return checkPallindrome(i+1,j-1,str);\n }else if(i>=j){\n return true;\n }\n \n return false;\n }"
},
{
"code": null,
"e": 4586,
"s": 4584,
"text": "0"
},
{
"code": null,
"e": 4614,
"s": 4586,
"text": "sayanmazumder9991 month ago"
},
{
"code": null,
"e": 4619,
"s": 4614,
"text": "JAVA"
},
{
"code": null,
"e": 4919,
"s": 4619,
"text": " String n = String.valueOf(N); int sum = 0; for(int i = 0; i < n.length(); i++) sum += (n.charAt(i) - '0'); StringBuilder str = new StringBuilder(String.valueOf(sum)); n = str.reverse().toString(); if(n.equals(String.valueOf(sum))) return 1; return 0;"
},
{
"code": null,
"e": 4921,
"s": 4919,
"text": "0"
},
{
"code": null,
"e": 4944,
"s": 4921,
"text": "0niharika22 months ago"
},
{
"code": null,
"e": 5186,
"s": 4944,
"text": "int sum=0, x=N, rev=0; while(x){ sum+=x%10; x/=10; } x = sum; while(x){ rev = rev*10 + x%10; x/=10; } if(rev==sum) return 1; else return 0;"
},
{
"code": null,
"e": 5189,
"s": 5186,
"text": "+1"
},
{
"code": null,
"e": 5221,
"s": 5189,
"text": "krishnakshirsagar412 months ago"
},
{
"code": null,
"e": 5464,
"s": 5221,
"text": "class Solution: def isDigitSumPalindrome(self,N): strr = str(N) list1 = [] list1 = list(map(int, strr.strip())) sum1 = sum(list1) if str(sum1) == str(sum1)[::-1]: return 1 return 0"
},
{
"code": null,
"e": 5610,
"s": 5464,
"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": 5646,
"s": 5610,
"text": " Login to access your submissions. "
},
{
"code": null,
"e": 5656,
"s": 5646,
"text": "\nProblem\n"
},
{
"code": null,
"e": 5666,
"s": 5656,
"text": "\nContest\n"
},
{
"code": null,
"e": 5729,
"s": 5666,
"text": "Reset the IDE using the second button on the top right corner."
},
{
"code": null,
"e": 5877,
"s": 5729,
"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": 6085,
"s": 5877,
"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": 6191,
"s": 6085,
"text": "You can access the hints to get an idea about what is expected of you as well as the final solution code."
}
] |
How do I run two python loops concurrently? | You will need to use a multiprocessing library. You will need to spawn a new process and provide the code to it as an argument. For example,
from multiprocessing import Process
def loop_a():
for i in range(5):
print("a")
def loop_b():
for i in range(5):
print("b")
Process(target=loop_a).start()
Process(target=loop_b).start()
This might process different outputs at different times. This is because we don't know which print will be executed when. | [
{
"code": null,
"e": 1203,
"s": 1062,
"text": "You will need to use a multiprocessing library. You will need to spawn a new process and provide the code to it as an argument. For example,"
},
{
"code": null,
"e": 1239,
"s": 1203,
"text": "from multiprocessing import Process"
},
{
"code": null,
"e": 1409,
"s": 1239,
"text": "def loop_a():\n for i in range(5):\n print(\"a\")\n\ndef loop_b():\n for i in range(5):\n print(\"b\")\n\nProcess(target=loop_a).start()\nProcess(target=loop_b).start()"
},
{
"code": null,
"e": 1531,
"s": 1409,
"text": "This might process different outputs at different times. This is because we don't know which print will be executed when."
}
] |
Wait until page is loaded with Selenium WebDriver for Python. | We can wait until the page is loaded with Selenium webdriver. There is a synchronization concept in Selenium which describes implicit and explicit wait. To wait until the page is loaded we shall use the explicit wait concept.
The explicit wait is designed such that it is dependent on the expected condition for a particular behavior of an element. For waiting until the page is loaded we shall use the expected condition presence_of_element_loaded for a particular element. Once the wait time is elapsed, the timeout error shall be thrown.
To implement explicit wait conditions, we have to take help of the WebDriverWait and ExpectedCondition class. Let us check the presence of the element below on the page and verify if the page is loaded.
Code Implementation
from selenium import webdriver
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from selenium.common.exceptions import TimeoutException
from selenium.webdriver.common.by import By
driver = webdriver.Chrome (executable_path="C:\\chromedriver.exe")
driver.get("https://www.tutorialspoint.com/about/about_careers.htm")
// presence_of_element_located expected condition wait for 8 seconds
try:
w = WebDriverWait(driver, 8)
w.until(expected_conditions.presence_of_element_located((By.TA
G_NAME,"h1")))
print("Page load happened")
exception TimeException:
print("Timeout happened no page load")
driver.close() | [
{
"code": null,
"e": 1288,
"s": 1062,
"text": "We can wait until the page is loaded with Selenium webdriver. There is a synchronization concept in Selenium which describes implicit and explicit wait. To wait until the page is loaded we shall use the explicit wait concept."
},
{
"code": null,
"e": 1603,
"s": 1288,
"text": "The explicit wait is designed such that it is dependent on the expected condition for a particular behavior of an element. For waiting until the page is loaded we shall use the expected condition presence_of_element_loaded for a particular element. Once the wait time is elapsed, the timeout error shall be thrown."
},
{
"code": null,
"e": 1806,
"s": 1603,
"text": "To implement explicit wait conditions, we have to take help of the WebDriverWait and ExpectedCondition class. Let us check the presence of the element below on the page and verify if the page is loaded."
},
{
"code": null,
"e": 1826,
"s": 1806,
"text": "Code Implementation"
},
{
"code": null,
"e": 2517,
"s": 1826,
"text": "from selenium import webdriver\nfrom selenium.webdriver.support.ui import WebDriverWait\nfrom selenium.webdriver.support import expected_conditions as EC\nfrom selenium.common.exceptions import TimeoutException\nfrom selenium.webdriver.common.by import By\ndriver = webdriver.Chrome (executable_path=\"C:\\\\chromedriver.exe\")\ndriver.get(\"https://www.tutorialspoint.com/about/about_careers.htm\")\n// presence_of_element_located expected condition wait for 8 seconds\ntry:\n w = WebDriverWait(driver, 8)\n w.until(expected_conditions.presence_of_element_located((By.TA\n G_NAME,\"h1\")))\n print(\"Page load happened\")\nexception TimeException:\n print(\"Timeout happened no page load\")\ndriver.close()"
}
] |
Queue.Enqueue() Method in C# | 13 Apr, 2021
This method is used to add an object to the end of the Queue. This comes under the System.Collections namespace. The value can null and if the Count is less than the capacity of the internal array, this method is an O(1) operation. If the internal array needs to be reallocated to accommodate the new element, this method becomes an O(n) operation, where n is Count.Syntax :
public virtual void Enqueue (object obj);
Here, obj is the object which is added to the Queue.Example:
CSHARP
// C# code to illustrate the// Queue.Enqueue() Methodusing System;using System.Collections; class GFG { // Driver code public static void Main() { // Creating a Queue Queue myQueue = new Queue(); // Inserting the elements into the Queue myQueue.Enqueue("one"); // Displaying the count of elements // contained in the Queue Console.Write("Total number of elements in the Queue are : "); Console.WriteLine(myQueue.Count); myQueue.Enqueue("two"); // Displaying the count of elements // contained in the Queue Console.Write("Total number of elements in the Queue are : "); Console.WriteLine(myQueue.Count); myQueue.Enqueue("three"); // Displaying the count of elements // contained in the Queue Console.Write("Total number of elements in the Queue are : "); Console.WriteLine(myQueue.Count); myQueue.Enqueue("four"); // Displaying the count of elements // contained in the Queue Console.Write("Total number of elements in the Queue are : "); Console.WriteLine(myQueue.Count); myQueue.Enqueue("five"); // Displaying the count of elements // contained in the Queue Console.Write("Total number of elements in the Queue are : "); Console.WriteLine(myQueue.Count); myQueue.Enqueue("six"); // Displaying the count of elements // contained in the Queue Console.Write("Total number of elements in the Queue are : "); Console.WriteLine(myQueue.Count); }}
Total number of elements in the Queue are : 1
Total number of elements in the Queue are : 2
Total number of elements in the Queue are : 3
Total number of elements in the Queue are : 4
Total number of elements in the Queue are : 5
Total number of elements in the Queue are : 6
Reference:
https://docs.microsoft.com/en-us/dotnet/api/system.collections.queue.enqueue?view=netframework-4.7.2
simmytarika5
CSharp-Collections-Namespace
CSharp-Collections-Queue
CSharp-method
C#
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here. | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n13 Apr, 2021"
},
{
"code": null,
"e": 405,
"s": 28,
"text": "This method is used to add an object to the end of the Queue. This comes under the System.Collections namespace. The value can null and if the Count is less than the capacity of the internal array, this method is an O(1) operation. If the internal array needs to be reallocated to accommodate the new element, this method becomes an O(n) operation, where n is Count.Syntax : "
},
{
"code": null,
"e": 447,
"s": 405,
"text": "public virtual void Enqueue (object obj);"
},
{
"code": null,
"e": 509,
"s": 447,
"text": "Here, obj is the object which is added to the Queue.Example: "
},
{
"code": null,
"e": 516,
"s": 509,
"text": "CSHARP"
},
{
"code": "// C# code to illustrate the// Queue.Enqueue() Methodusing System;using System.Collections; class GFG { // Driver code public static void Main() { // Creating a Queue Queue myQueue = new Queue(); // Inserting the elements into the Queue myQueue.Enqueue(\"one\"); // Displaying the count of elements // contained in the Queue Console.Write(\"Total number of elements in the Queue are : \"); Console.WriteLine(myQueue.Count); myQueue.Enqueue(\"two\"); // Displaying the count of elements // contained in the Queue Console.Write(\"Total number of elements in the Queue are : \"); Console.WriteLine(myQueue.Count); myQueue.Enqueue(\"three\"); // Displaying the count of elements // contained in the Queue Console.Write(\"Total number of elements in the Queue are : \"); Console.WriteLine(myQueue.Count); myQueue.Enqueue(\"four\"); // Displaying the count of elements // contained in the Queue Console.Write(\"Total number of elements in the Queue are : \"); Console.WriteLine(myQueue.Count); myQueue.Enqueue(\"five\"); // Displaying the count of elements // contained in the Queue Console.Write(\"Total number of elements in the Queue are : \"); Console.WriteLine(myQueue.Count); myQueue.Enqueue(\"six\"); // Displaying the count of elements // contained in the Queue Console.Write(\"Total number of elements in the Queue are : \"); Console.WriteLine(myQueue.Count); }}",
"e": 2121,
"s": 516,
"text": null
},
{
"code": null,
"e": 2397,
"s": 2121,
"text": "Total number of elements in the Queue are : 1\nTotal number of elements in the Queue are : 2\nTotal number of elements in the Queue are : 3\nTotal number of elements in the Queue are : 4\nTotal number of elements in the Queue are : 5\nTotal number of elements in the Queue are : 6"
},
{
"code": null,
"e": 2411,
"s": 2399,
"text": "Reference: "
},
{
"code": null,
"e": 2512,
"s": 2411,
"text": "https://docs.microsoft.com/en-us/dotnet/api/system.collections.queue.enqueue?view=netframework-4.7.2"
},
{
"code": null,
"e": 2527,
"s": 2514,
"text": "simmytarika5"
},
{
"code": null,
"e": 2556,
"s": 2527,
"text": "CSharp-Collections-Namespace"
},
{
"code": null,
"e": 2581,
"s": 2556,
"text": "CSharp-Collections-Queue"
},
{
"code": null,
"e": 2595,
"s": 2581,
"text": "CSharp-method"
},
{
"code": null,
"e": 2598,
"s": 2595,
"text": "C#"
}
] |
How to Install Keras in Windows? | 21 Sep, 2021
Keras is a neural Network python library primarily used for image classification. In this article we will look into the process of installing Keras on a Windows machine.
The only thing that you need for installing Numpy on Windows are:
Python
PIP or Conda (depending upon user preference)
The Keras library has the following dependencies:
Numpy
Pandas
Scikit-learn
Matplotlib
Scipy
Seaborn
Note: All these dependencies can be manually installed. But if you are missing one or all of these dependencies, they get installed when you run the command to install Keras automatically.
If you want the installation to be done through conda, open up the Anaconda Powershell Prompt and use the below command:
conda install -c conda-forge keras
Type y for yes when prompted.
You will get a similar message once the installation is complete:
Make sure you follow the best practices for installation using conda as:
Use an environment for installation rather than in the base environment using the below command:
conda create -n my-env
conda activate my-env
Note: If your preferred method of installation is conda-forge, use the below command:
conda config --env --add channels conda-forge
To verify if Keras library has been successfully installed in your system run the below command in Anaconda Powershell Prompt:
conda list keras
You’ll get the below message if the installation is complete:
Users who prefer to use pip can use the below command to install the Keras library on Windows:
pip install keras
You will get a similar message once the installation is complete:
To verify if Keras library has been successfully installed in your system run the below command in your command prompt:
python -m pip show keras
You’ll get the below message if the installation is complete:
Blogathon-2021
how-to-install
Picked
Blogathon
How To
Installation Guide
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here. | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n21 Sep, 2021"
},
{
"code": null,
"e": 198,
"s": 28,
"text": "Keras is a neural Network python library primarily used for image classification. In this article we will look into the process of installing Keras on a Windows machine."
},
{
"code": null,
"e": 264,
"s": 198,
"text": "The only thing that you need for installing Numpy on Windows are:"
},
{
"code": null,
"e": 272,
"s": 264,
"text": "Python "
},
{
"code": null,
"e": 318,
"s": 272,
"text": "PIP or Conda (depending upon user preference)"
},
{
"code": null,
"e": 368,
"s": 318,
"text": "The Keras library has the following dependencies:"
},
{
"code": null,
"e": 374,
"s": 368,
"text": "Numpy"
},
{
"code": null,
"e": 381,
"s": 374,
"text": "Pandas"
},
{
"code": null,
"e": 394,
"s": 381,
"text": "Scikit-learn"
},
{
"code": null,
"e": 405,
"s": 394,
"text": "Matplotlib"
},
{
"code": null,
"e": 411,
"s": 405,
"text": "Scipy"
},
{
"code": null,
"e": 419,
"s": 411,
"text": "Seaborn"
},
{
"code": null,
"e": 608,
"s": 419,
"text": "Note: All these dependencies can be manually installed. But if you are missing one or all of these dependencies, they get installed when you run the command to install Keras automatically."
},
{
"code": null,
"e": 730,
"s": 608,
"text": "If you want the installation to be done through conda, open up the Anaconda Powershell Prompt and use the below command:"
},
{
"code": null,
"e": 765,
"s": 730,
"text": "conda install -c conda-forge keras"
},
{
"code": null,
"e": 795,
"s": 765,
"text": "Type y for yes when prompted."
},
{
"code": null,
"e": 861,
"s": 795,
"text": "You will get a similar message once the installation is complete:"
},
{
"code": null,
"e": 934,
"s": 861,
"text": "Make sure you follow the best practices for installation using conda as:"
},
{
"code": null,
"e": 1031,
"s": 934,
"text": "Use an environment for installation rather than in the base environment using the below command:"
},
{
"code": null,
"e": 1076,
"s": 1031,
"text": "conda create -n my-env\nconda activate my-env"
},
{
"code": null,
"e": 1162,
"s": 1076,
"text": "Note: If your preferred method of installation is conda-forge, use the below command:"
},
{
"code": null,
"e": 1208,
"s": 1162,
"text": "conda config --env --add channels conda-forge"
},
{
"code": null,
"e": 1335,
"s": 1208,
"text": "To verify if Keras library has been successfully installed in your system run the below command in Anaconda Powershell Prompt:"
},
{
"code": null,
"e": 1352,
"s": 1335,
"text": "conda list keras"
},
{
"code": null,
"e": 1414,
"s": 1352,
"text": "You’ll get the below message if the installation is complete:"
},
{
"code": null,
"e": 1509,
"s": 1414,
"text": "Users who prefer to use pip can use the below command to install the Keras library on Windows:"
},
{
"code": null,
"e": 1527,
"s": 1509,
"text": "pip install keras"
},
{
"code": null,
"e": 1593,
"s": 1527,
"text": "You will get a similar message once the installation is complete:"
},
{
"code": null,
"e": 1713,
"s": 1593,
"text": "To verify if Keras library has been successfully installed in your system run the below command in your command prompt:"
},
{
"code": null,
"e": 1738,
"s": 1713,
"text": "python -m pip show keras"
},
{
"code": null,
"e": 1800,
"s": 1738,
"text": "You’ll get the below message if the installation is complete:"
},
{
"code": null,
"e": 1815,
"s": 1800,
"text": "Blogathon-2021"
},
{
"code": null,
"e": 1830,
"s": 1815,
"text": "how-to-install"
},
{
"code": null,
"e": 1837,
"s": 1830,
"text": "Picked"
},
{
"code": null,
"e": 1847,
"s": 1837,
"text": "Blogathon"
},
{
"code": null,
"e": 1854,
"s": 1847,
"text": "How To"
},
{
"code": null,
"e": 1873,
"s": 1854,
"text": "Installation Guide"
}
] |
Shuffle array {a1, a2, .. an, b1, b2, .. bn} as {a1, b1, a2, b2, a3, b3, ......, an, bn} without using extra space | 13 Oct, 2020
Given an array of 2n elements in the following format { a1, a2, a3, a4, ....., an, b1, b2, b3, b4, ...., bn }. The task is shuffle the array to {a1, b1, a2, b2, a3, b3, ......, an, bn } without using extra space.Examples :
Input : arr[] = { 1, 2, 9, 15 }
Output : 1 9 2 15
Input : arr[] = { 1, 2, 3, 4, 5, 6 }
Output : 1 4 2 5 3 6
We have discussed O(n2) and O(n Log n) solutions of this problem in below post.Shuffle 2n integers in format {a1, b1, a2, b2, a3, b3, ......, an, bn} without using extra spaceHere a new solution is discussed that works in linear time. We know that the first and last numbers don’t move from their places. And, we keep track of the index from which any number is picked and where the target index is. We know that, if we’re picking ai, it has to go to the index 2 * i – 1 and if bi, it has to go 2 * i. We can check from where we have picked a certain number based on the picking index if it greater or less than n. We will have to do this for 2 * n – 2 times, assuming that n = half of length of array. We, get two cases, when n is even and odd, hence we initialize appropriately the start variable. Note: Indexes are considered 1 based in array for simplicity.
C++
// C++ program to shuffle an array in O(n) time
// and O(1) extra space
#include <bits/stdc++.h>
using namespace std;
// Shuffles an array of size 2n. Indexes
// are considered starting from 1.
void shufleArray(int a[], int n)
{
n = n / 2;
for (int start = n + 1, j = n + 1, done = 0, i;
done < 2 * n - 2; done++) {
if (start == j) {
start--;
j--;
}
i = j > n ? j - n : j;
j = j > n ? 2 * i : 2 * i - 1;
swap(a[start], a[j]);
}
}
// Driven Program
int main()
{
// The first element is bogus. We have used
// one based indexing for simplicity.
int a[] = { -1, 1, 3, 5, 7, 2, 4, 6, 8 };
int n = sizeof(a) / sizeof(a[0]);
shufleArray(a, n);
for (int i = 1; i < n; i++)
cout << a[i] << " ";
return 0;
}
Java
// Java program to shuffle an
// array in O(n) time and O(1)
// extra space
import java.io.*;
public class GFG {
// Shuffles an array of size 2n.
// Indexes are considered starting
// from 1.
static void shufleArray(int[] a, int n)
{
int temp;
n = n / 2;
for (int start = n + 1, j = n + 1, done = 0, i;
done < 2 * n - 2; done++) {
if (start == j) {
start--;
j--;
}
i = j > n ? j - n : j;
j = j > n ? 2 * i : 2 * i - 1;
temp = a[start];
a[start] = a[j];
a[j] = temp;
}
}
// Driver code
static public void main(String[] args)
{
// The first element is bogus. We have used
// one based indexing for simplicity.
int[] a = { -1, 1, 3, 5, 7, 2, 4, 6, 8 };
int n = a.length;
shufleArray(a, n);
for (int i = 1; i < n; i++)
System.out.print(a[i] + " ");
}
}
// This Code is contributed by vt_m.
Python 3
# Python 3 program to shuffle an array
# in O(n) time and O(1) extra space
# Shuffles an array of size 2n. Indexes
# are considered starting from 1.
def shufleArray(a, n):
n = n // 2
start = n + 1
j = n + 1
for done in range( 2 * n - 2) :
if (start == j) :
start -= 1
j -= 1
i = j - n if j > n else j
j = 2 * i if j > n else 2 * i - 1
a[start], a[j] = a[j], a[start]
# Driver Code
if __name__ == "__main__":
# The first element is bogus. We have used
# one based indexing for simplicity.
a = [ -1, 1, 3, 5, 7, 2, 4, 6, 8 ]
n = len(a)
shufleArray(a, n)
for i in range(1, n):
print(a[i], end = " ")
# This code is contributed
# by ChitraNayal
C#
// C# program to shuffle an
// array in O(n) time and O(1)
// extra space
using System;
public class GFG {
// Shuffles an array of size 2n.
// Indexes are considered starting
// from 1.
static void shufleArray(int[] a, int n)
{
int temp;
n = n / 2;
for (int start = n + 1, j = n + 1, done = 0, i;
done < 2 * n - 2; done++) {
if (start == j) {
start--;
j--;
}
i = j > n ? j - n : j;
j = j > n ? 2 * i : 2 * i - 1;
temp = a[start];
a[start] = a[j];
a[j] = temp;
}
}
// Driven code
static public void Main(String[] args)
{
// The first element is bogus. We have used
// one based indexing for simplicity.
int[] a = { -1, 1, 3, 5, 7, 2, 4, 6, 8 };
int n = a.Length;
shufleArray(a, n);
for (int i = 1; i < n; i++)
Console.Write(a[i] + " ");
}
}
// This Code is contributed by vt_m.
PHP
<?php
// PHP program to shuffle an
// array in O(n) time and O(1)
// extra space
// Shuffles an array of size 2n.
// Indexes are considered starting
// from 1.
function shufleArray($a, $n)
{
$k = intval($n / 2);
for ($start = $k + 1,
$j = $k + 1, $done = 0;
$done < 2 * $k - 2; $done++)
{
if ($start == $j)
{
$start--;
$j--;
}
$i = $j > $k ? $j - $k : $j;
$j = $j > $k ? 2 * $i : 2 * $i - 1;
$temp = $a[$start];
$a[$start] = $a[$j];
$a[$j] = $temp;
}
for ($i = 1; $i < $n; $i++)
echo $a[$i] . " ";
}
// Driver code
// The first element is bogus.
// We have used one based
// indexing for simplicity.
$a = array(-1, 1, 3, 5, 7, 2, 4, 6, 8);
$n = count($a);
shufleArray($a, $n);
// This code is contributed by Sam007
?>
1 2 3 4 5 6 7 8
Another Efficient Approach:
The O(n) approach can be improved by sequentially placing the elements at their correct position. The criteria of finding the target index remains same. The main thing here to realize is that if we swap the current element with an element with greater index, then we can end up traversing on this element which has been placed at its correct position. In order to avoid this we increment this element by the max value in the array so when we come to this index we can simply ignore it. When we have traversed the array from 2 to n-1, we need to re-produce the original array by subtracting the max value from element which is greater than max value.. Note : Indexes are considered 1 based in array for simplicity.Below is the implementation of the above approach:
C#
// C# program for above approach
using System;
class GFG
{
// Function to shuffle arrays
static void Shuffle(int[] arr, int n)
{
int max = (arr[n] > arr[n / 2]) ?
arr[n] : arr[n / 2];
// 'i' is traversing index and
// j index for right half series
for (int i = 2, j = 0; i <= n - 1; i++)
{
// Check if on left half of array
if (i <= n / 2)
{
// Check if this index
// has been visited or not
if (arr[i] < max)
{
int temp = arr[2 * i - 1];
// Increase the element by max
arr[2 * i - 1] = arr[i] + max;
// As it i on left half
arr[i] = temp;
}
}
// Right half
else
{
// Index of right half
// series(b1, b2, b3)
j++;
// Check if this index
// has been visited or not
if (arr[i] < max)
{
int temp = arr[2 * j];
// No need to add max
// as element is
arr[2 * j] = arr[i];
// On right half
arr[i] = temp;
}
}
}
// Re-produce the original array
for (int i = 2; i <= n - 1; i++)
{
if (arr[i] > max)
{
arr[i] = arr[i] - max;
}
}
}
// Driver Program
public static void Main()
{
int[] arr = { -1, 1, 3, 5, 7, 2, 4, 6, 8 };
int n = arr.Length - 1;
// Function Call
Shuffle(arr, n);
for (int i = 1; i <= n; i++)
{
Console.Write(arr[i] + " ");
}
Console.WriteLine();
}
}
// This code is contributed by Armaan23
1 2 3 4 5 6 7 8
This article is contributed by azam58. 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.
vt_m
Sam007
ukasp
dce23
array-rearrange
Arrays
Arrays
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here. | [
{
"code": null,
"e": 52,
"s": 24,
"text": "\n13 Oct, 2020"
},
{
"code": null,
"e": 276,
"s": 52,
"text": "Given an array of 2n elements in the following format { a1, a2, a3, a4, ....., an, b1, b2, b3, b4, ...., bn }. The task is shuffle the array to {a1, b1, a2, b2, a3, b3, ......, an, bn } without using extra space.Examples : "
},
{
"code": null,
"e": 387,
"s": 276,
"text": "Input : arr[] = { 1, 2, 9, 15 }\nOutput : 1 9 2 15\n\nInput : arr[] = { 1, 2, 3, 4, 5, 6 }\nOutput : 1 4 2 5 3 6\n"
},
{
"code": null,
"e": 1250,
"s": 387,
"text": "We have discussed O(n2) and O(n Log n) solutions of this problem in below post.Shuffle 2n integers in format {a1, b1, a2, b2, a3, b3, ......, an, bn} without using extra spaceHere a new solution is discussed that works in linear time. We know that the first and last numbers don’t move from their places. And, we keep track of the index from which any number is picked and where the target index is. We know that, if we’re picking ai, it has to go to the index 2 * i – 1 and if bi, it has to go 2 * i. We can check from where we have picked a certain number based on the picking index if it greater or less than n. We will have to do this for 2 * n – 2 times, assuming that n = half of length of array. We, get two cases, when n is even and odd, hence we initialize appropriately the start variable. Note: Indexes are considered 1 based in array for simplicity. "
},
{
"code": null,
"e": 1254,
"s": 1250,
"text": "C++"
},
{
"code": null,
"e": 2084,
"s": 1254,
"text": "\n// C++ program to shuffle an array in O(n) time\n// and O(1) extra space\n#include <bits/stdc++.h>\nusing namespace std;\n\n// Shuffles an array of size 2n. Indexes\n// are considered starting from 1.\nvoid shufleArray(int a[], int n)\n{\n n = n / 2;\n\n for (int start = n + 1, j = n + 1, done = 0, i;\n done < 2 * n - 2; done++) {\n if (start == j) {\n start--;\n j--;\n }\n\n i = j > n ? j - n : j;\n j = j > n ? 2 * i : 2 * i - 1;\n\n swap(a[start], a[j]);\n }\n}\n\n// Driven Program\nint main()\n{\n // The first element is bogus. We have used\n // one based indexing for simplicity.\n int a[] = { -1, 1, 3, 5, 7, 2, 4, 6, 8 };\n int n = sizeof(a) / sizeof(a[0]);\n\n shufleArray(a, n);\n\n for (int i = 1; i < n; i++)\n cout << a[i] << \" \";\n\n return 0;\n}\n"
},
{
"code": null,
"e": 2089,
"s": 2084,
"text": "Java"
},
{
"code": null,
"e": 3146,
"s": 2089,
"text": "\n// Java program to shuffle an\n// array in O(n) time and O(1)\n// extra space\nimport java.io.*;\n\npublic class GFG {\n\n // Shuffles an array of size 2n.\n // Indexes are considered starting\n // from 1.\n static void shufleArray(int[] a, int n)\n {\n int temp;\n n = n / 2;\n\n for (int start = n + 1, j = n + 1, done = 0, i;\n done < 2 * n - 2; done++) {\n if (start == j) {\n start--;\n j--;\n }\n\n i = j > n ? j - n : j;\n j = j > n ? 2 * i : 2 * i - 1;\n temp = a[start];\n a[start] = a[j];\n a[j] = temp;\n }\n }\n\n // Driver code\n static public void main(String[] args)\n {\n // The first element is bogus. We have used\n // one based indexing for simplicity.\n int[] a = { -1, 1, 3, 5, 7, 2, 4, 6, 8 };\n int n = a.length;\n\n shufleArray(a, n);\n\n for (int i = 1; i < n; i++)\n System.out.print(a[i] + \" \");\n }\n}\n\n// This Code is contributed by vt_m.\n"
},
{
"code": null,
"e": 3155,
"s": 3146,
"text": "Python 3"
},
{
"code": null,
"e": 3922,
"s": 3155,
"text": "\n# Python 3 program to shuffle an array \n# in O(n) time and O(1) extra space\n\n# Shuffles an array of size 2n. Indexes\n# are considered starting from 1.\ndef shufleArray(a, n):\n \n n = n // 2\n\n start = n + 1\n j = n + 1\n for done in range( 2 * n - 2) :\n if (start == j) :\n start -= 1\n j -= 1\n\n i = j - n if j > n else j\n j = 2 * i if j > n else 2 * i - 1\n\n a[start], a[j] = a[j], a[start]\n\n# Driver Code\nif __name__ == \"__main__\":\n \n # The first element is bogus. We have used\n # one based indexing for simplicity.\n a = [ -1, 1, 3, 5, 7, 2, 4, 6, 8 ]\n n = len(a)\n\n shufleArray(a, n)\n\n for i in range(1, n):\n print(a[i], end = \" \")\n\n# This code is contributed \n# by ChitraNayal\n"
},
{
"code": null,
"e": 3925,
"s": 3922,
"text": "C#"
},
{
"code": null,
"e": 4973,
"s": 3925,
"text": "\n// C# program to shuffle an\n// array in O(n) time and O(1)\n// extra space\nusing System;\n\npublic class GFG {\n\n // Shuffles an array of size 2n.\n // Indexes are considered starting\n // from 1.\n static void shufleArray(int[] a, int n)\n {\n int temp;\n n = n / 2;\n\n for (int start = n + 1, j = n + 1, done = 0, i;\n done < 2 * n - 2; done++) {\n if (start == j) {\n start--;\n j--;\n }\n\n i = j > n ? j - n : j;\n j = j > n ? 2 * i : 2 * i - 1;\n temp = a[start];\n a[start] = a[j];\n a[j] = temp;\n }\n }\n\n // Driven code\n static public void Main(String[] args)\n {\n // The first element is bogus. We have used\n // one based indexing for simplicity.\n int[] a = { -1, 1, 3, 5, 7, 2, 4, 6, 8 };\n int n = a.Length;\n\n shufleArray(a, n);\n\n for (int i = 1; i < n; i++)\n Console.Write(a[i] + \" \");\n }\n}\n\n// This Code is contributed by vt_m.\n"
},
{
"code": null,
"e": 4977,
"s": 4973,
"text": "PHP"
},
{
"code": null,
"e": 5861,
"s": 4977,
"text": "\n<?php\n// PHP program to shuffle an \n// array in O(n) time and O(1)\n// extra space\n\n// Shuffles an array of size 2n.\n// Indexes are considered starting\n// from 1.\nfunction shufleArray($a, $n)\n{\n \n $k = intval($n / 2);\n\n for ($start = $k + 1, \n $j = $k + 1, $done = 0; \n $done < 2 * $k - 2; $done++)\n {\n if ($start == $j)\n {\n $start--;\n $j--;\n }\n\n $i = $j > $k ? $j - $k : $j;\n $j = $j > $k ? 2 * $i : 2 * $i - 1;\n $temp = $a[$start];\n $a[$start] = $a[$j];\n $a[$j] = $temp;\n\n }\n for ($i = 1; $i < $n; $i++)\n echo $a[$i] . \" \";\n}\n\n// Driver code\n\n// The first element is bogus. \n// We have used one based \n// indexing for simplicity.\n$a = array(-1, 1, 3, 5, 7, 2, 4, 6, 8);\n$n = count($a);\nshufleArray($a, $n);\n \n// This code is contributed by Sam007\n?>\n\n"
},
{
"code": null,
"e": 5879,
"s": 5861,
"text": "1 2 3 4 5 6 7 8\n\n"
},
{
"code": null,
"e": 5909,
"s": 5881,
"text": "Another Efficient Approach:"
},
{
"code": null,
"e": 6673,
"s": 5909,
"text": "The O(n) approach can be improved by sequentially placing the elements at their correct position. The criteria of finding the target index remains same. The main thing here to realize is that if we swap the current element with an element with greater index, then we can end up traversing on this element which has been placed at its correct position. In order to avoid this we increment this element by the max value in the array so when we come to this index we can simply ignore it. When we have traversed the array from 2 to n-1, we need to re-produce the original array by subtracting the max value from element which is greater than max value.. Note : Indexes are considered 1 based in array for simplicity.Below is the implementation of the above approach:"
},
{
"code": null,
"e": 6676,
"s": 6673,
"text": "C#"
},
{
"code": null,
"e": 8766,
"s": 6676,
"text": "// C# program for above approach\nusing System; \n\nclass GFG \n{\n \n // Function to shuffle arrays\n static void Shuffle(int[] arr, int n)\n {\n int max = (arr[n] > arr[n / 2]) ? \n arr[n] : arr[n / 2];\n\n // 'i' is traversing index and \n // j index for right half series\n for (int i = 2, j = 0; i <= n - 1; i++) \n {\n\n // Check if on left half of array\n if (i <= n / 2) \n {\n \n // Check if this index \n // has been visited or not\n if (arr[i] < max) \n {\n int temp = arr[2 * i - 1];\n\n // Increase the element by max\n arr[2 * i - 1] = arr[i] + max;\n\n // As it i on left half\n arr[i] = temp;\n }\n }\n \n // Right half\n else \n {\n \n // Index of right half \n // series(b1, b2, b3)\n j++; \n\n // Check if this index \n // has been visited or not\n if (arr[i] < max) \n {\n int temp = arr[2 * j];\n\n // No need to add max \n // as element is\n arr[2 * j] = arr[i];\n \n // On right half\n arr[i] = temp; \n }\n }\n }\n\n // Re-produce the original array\n for (int i = 2; i <= n - 1; i++) \n {\n if (arr[i] > max) \n {\n arr[i] = arr[i] - max;\n }\n }\n }\n // Driver Program\n public static void Main()\n {\n int[] arr = { -1, 1, 3, 5, 7, 2, 4, 6, 8 };\n int n = arr.Length - 1;\n \n // Function Call\n Shuffle(arr, n);\n for (int i = 1; i <= n; i++) \n {\n Console.Write(arr[i] + \" \");\n }\n Console.WriteLine();\n }\n}\n// This code is contributed by Armaan23\n"
},
{
"code": null,
"e": 8784,
"s": 8766,
"text": "1 2 3 4 5 6 7 8\n\n"
},
{
"code": null,
"e": 9205,
"s": 8786,
"text": "This article is contributed by azam58. 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. "
},
{
"code": null,
"e": 9210,
"s": 9205,
"text": "vt_m"
},
{
"code": null,
"e": 9217,
"s": 9210,
"text": "Sam007"
},
{
"code": null,
"e": 9223,
"s": 9217,
"text": "ukasp"
},
{
"code": null,
"e": 9229,
"s": 9223,
"text": "dce23"
},
{
"code": null,
"e": 9245,
"s": 9229,
"text": "array-rearrange"
},
{
"code": null,
"e": 9252,
"s": 9245,
"text": "Arrays"
},
{
"code": null,
"e": 9259,
"s": 9252,
"text": "Arrays"
}
] |
K-Nearest Neighbours | 13 Jul, 2022
K-Nearest Neighbours is one of the most basic yet essential classification algorithms in Machine Learning. It belongs to the supervised learning domain and finds intense application in pattern recognition, data mining and intrusion detection.It is widely disposable in real-life scenarios since it is non-parametric, meaning, it does not make any underlying assumptions about the distribution of data (as opposed to other algorithms such as GMM, which assume a Gaussian distribution of the given data).We are given some prior data (also called training data), which classifies coordinates into groups identified by an attribute.As an example, consider the following table of data points containing two features:
Chapters
descriptions off, selected
captions settings, opens captions settings dialog
captions off, selected
English
This is a modal window.
Beginning of dialog window. Escape will cancel and close the window.
End of dialog window.
Now, given another set of data points (also called testing data), allocate these points a group by analyzing the training set. Note that the unclassified points are marked as ‘White’.
Intuition If we plot these points on a graph, we may be able to locate some clusters or groups. Now, given an unclassified point, we can assign it to a group by observing what group its nearest neighbours belong to. This means a point close to a cluster of points classified as ‘Red’ has a higher probability of getting classified as ‘Red’.Intuitively, we can see that the first point (2.5, 7) should be classified as ‘Green’ and the second point (5.5, 4.5) should be classified as ‘Red’.Algorithm Let m be the number of training data samples. Let p be an unknown point.
Store the training samples in an array of data points arr[]. This means each element of this array represents a tuple (x, y).
Store the training samples in an array of data points arr[]. This means each element of this array represents a tuple (x, y).
for i=0 to m:
Calculate Euclidean distance d(arr[i], p).
Make set S of K smallest distances obtained. Each of these distances corresponds to an already classified data point.Return the majority label among S.
Make set S of K smallest distances obtained. Each of these distances corresponds to an already classified data point.
Return the majority label among S.
K can be kept as an odd number so that we can calculate a clear majority in the case where only two groups are possible (e.g. Red/Blue). With increasing K, we get smoother, more defined boundaries across different classifications. Also, the accuracy of the above classifier increases as we increase the number of data points in the training set.Example Program Assume 0 and 1 as the two classifiers (groups).
C++
Java
Python3
// C++ program to find groups of unknown// Points using K nearest neighbour algorithm.#include <bits/stdc++.h>using namespace std; struct Point{ int val; // Group of point double x, y; // Co-ordinate of point double distance; // Distance from test point}; // Used to sort an array of points by increasing// order of distancebool comparison(Point a, Point b){ return (a.distance < b.distance);} // This function finds classification of point p using// k nearest neighbour algorithm. It assumes only two// groups and returns 0 if p belongs to group 0, else// 1 (belongs to group 1).int classifyAPoint(Point arr[], int n, int k, Point p){ // Fill distances of all points from p for (int i = 0; i < n; i++) arr[i].distance = sqrt((arr[i].x - p.x) * (arr[i].x - p.x) + (arr[i].y - p.y) * (arr[i].y - p.y)); // Sort the Points by distance from p sort(arr, arr+n, comparison); // Now consider the first k elements and only // two groups int freq1 = 0; // Frequency of group 0 int freq2 = 0; // Frequency of group 1 for (int i = 0; i < k; i++) { if (arr[i].val == 0) freq1++; else if (arr[i].val == 1) freq2++; } return (freq1 > freq2 ? 0 : 1);} // Driver codeint main(){ int n = 17; // Number of data points Point arr[n]; arr[0].x = 1; arr[0].y = 12; arr[0].val = 0; arr[1].x = 2; arr[1].y = 5; arr[1].val = 0; arr[2].x = 5; arr[2].y = 3; arr[2].val = 1; arr[3].x = 3; arr[3].y = 2; arr[3].val = 1; arr[4].x = 3; arr[4].y = 6; arr[4].val = 0; arr[5].x = 1.5; arr[5].y = 9; arr[5].val = 1; arr[6].x = 7; arr[6].y = 2; arr[6].val = 1; arr[7].x = 6; arr[7].y = 1; arr[7].val = 1; arr[8].x = 3.8; arr[8].y = 3; arr[8].val = 1; arr[9].x = 3; arr[9].y = 10; arr[9].val = 0; arr[10].x = 5.6; arr[10].y = 4; arr[10].val = 1; arr[11].x = 4; arr[11].y = 2; arr[11].val = 1; arr[12].x = 3.5; arr[12].y = 8; arr[12].val = 0; arr[13].x = 2; arr[13].y = 11; arr[13].val = 0; arr[14].x = 2; arr[14].y = 5; arr[14].val = 1; arr[15].x = 2; arr[15].y = 9; arr[15].val = 0; arr[16].x = 1; arr[16].y = 7; arr[16].val = 0; /*Testing Point*/ Point p; p.x = 2.5; p.y = 7; // Parameter to decide group of the testing point int k = 3; printf ("The value classified to unknown point" " is %d.\n", classifyAPoint(arr, n, k, p)); return 0;}
// Java program to find groups of unknown// Points using K nearest neighbour algorithm.import java.io.*;import java.util.*; class GFG { static class Point { int val; // Group of point double x, y; // Co-ordinate of point double distance; // Distance from test point } // Used to sort an array of points by increasing // order of distance static class comparison implements Comparator<Point> { public int compare(Point a, Point b) { if (a.distance < b.distance) return -1; else if (a.distance > b.distance) return 1; return 0; } } // This function finds classification of point p using // k nearest neighbour algorithm. It assumes only two // groups and returns 0 if p belongs to group 0, else // 1 (belongs to group 1). static int classifyAPoint(Point arr[], int n, int k, Point p) { // Fill distances of all points from p for (int i = 0; i < n; i++) arr[i].distance = Math.sqrt( (arr[i].x - p.x) * (arr[i].x - p.x) + (arr[i].y - p.y) * (arr[i].y - p.y)); // Sort the Points by distance from p Arrays.sort(arr, new comparison()); // Now consider the first k elements and only // two groups int freq1 = 0; // Frequency of group 0 int freq2 = 0; // Frequency of group 1 for (int i = 0; i < k; i++) { if (arr[i].val == 0) freq1++; else if (arr[i].val == 1) freq2++; } return (freq1 > freq2 ? 0 : 1); } // Driver code public static void main(String[] args) { int n = 17; // Number of data points Point[] arr = new Point[n]; for (int i = 0; i < 17; i++) { arr[i] = new Point(); } arr[0].x = 1; arr[0].y = 12; arr[0].val = 0; arr[1].x = 2; arr[1].y = 5; arr[1].val = 0; arr[2].x = 5; arr[2].y = 3; arr[2].val = 1; arr[3].x = 3; arr[3].y = 2; arr[3].val = 1; arr[4].x = 3; arr[4].y = 6; arr[4].val = 0; arr[5].x = 1.5; arr[5].y = 9; arr[5].val = 1; arr[6].x = 7; arr[6].y = 2; arr[6].val = 1; arr[7].x = 6; arr[7].y = 1; arr[7].val = 1; arr[8].x = 3.8; arr[8].y = 3; arr[8].val = 1; arr[9].x = 3; arr[9].y = 10; arr[9].val = 0; arr[10].x = 5.6; arr[10].y = 4; arr[10].val = 1; arr[11].x = 4; arr[11].y = 2; arr[11].val = 1; arr[12].x = 3.5; arr[12].y = 8; arr[12].val = 0; arr[13].x = 2; arr[13].y = 11; arr[13].val = 0; arr[14].x = 2; arr[14].y = 5; arr[14].val = 1; arr[15].x = 2; arr[15].y = 9; arr[15].val = 0; arr[16].x = 1; arr[16].y = 7; arr[16].val = 0; /*Testing Point*/ Point p = new Point(); p.x = 2.5; p.y = 7; // Parameter to decide group of the testing point int k = 3; System.out.println( "The value classified to unknown point is " + classifyAPoint(arr, n, k, p)); }} // This code is contributed by Karandeep1234
# Python3 program to find groups of unknown# Points using K nearest neighbour algorithm. import math def classifyAPoint(points,p,k=3): ''' This function finds the classification of p using k nearest neighbor algorithm. It assumes only two groups and returns 0 if p belongs to group 0, else 1 (belongs to group 1). Parameters - points: Dictionary of training points having two keys - 0 and 1 Each key have a list of training data points belong to that p : A tuple, test data point of the form (x,y) k : number of nearest neighbour to consider, default is 3 ''' distance=[] for group in points: for feature in points[group]: #calculate the euclidean distance of p from training points euclidean_distance = math.sqrt((feature[0]-p[0])**2 +(feature[1]-p[1])**2) # Add a tuple of form (distance,group) in the distance list distance.append((euclidean_distance,group)) # sort the distance list in ascending order # and select first k distances distance = sorted(distance)[:k] freq1 = 0 #frequency of group 0 freq2 = 0 #frequency og group 1 for d in distance: if d[1] == 0: freq1 += 1 else if d[1] == 1: freq2 += 1 return 0 if freq1>freq2 else 1 # driver functiondef main(): # Dictionary of training points having two keys - 0 and 1 # key 0 have points belong to class 0 # key 1 have points belong to class 1 points = {0:[(1,12),(2,5),(3,6),(3,10),(3.5,8),(2,11),(2,9),(1,7)], 1:[(5,3),(3,2),(1.5,9),(7,2),(6,1),(3.8,1),(5.6,4),(4,2),(2,5)]} # testing point p(x,y) p = (2.5,7) # Number of neighbours k = 3 print("The value classified to unknown point is: {}".\ format(classifyAPoint(points,p,k))) if __name__ == '__main__': main() # This code is contributed by Atul Kumar (www.fb.com/atul.kr.007)
Output:
The value classified to unknown point is 0.
Time Complexity: O(N * logN)Auxiliary Space: O(1)
This article is contributed by Anannya Uberoi. 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.
NIRBHAYKUMAR1
snk_pan
pankajsharmagfg
gurukiranx
prachisoda1234
amartyaghoshgfg
simmytarika5
karandeep1234
Directi
Advanced Computer Subject
Algorithms
Machine Learning
Directi
Algorithms
Machine Learning
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here. | [
{
"code": null,
"e": 54,
"s": 26,
"text": "\n13 Jul, 2022"
},
{
"code": null,
"e": 768,
"s": 54,
"text": "K-Nearest Neighbours is one of the most basic yet essential classification algorithms in Machine Learning. It belongs to the supervised learning domain and finds intense application in pattern recognition, data mining and intrusion detection.It is widely disposable in real-life scenarios since it is non-parametric, meaning, it does not make any underlying assumptions about the distribution of data (as opposed to other algorithms such as GMM, which assume a Gaussian distribution of the given data).We are given some prior data (also called training data), which classifies coordinates into groups identified by an attribute.As an example, consider the following table of data points containing two features: "
},
{
"code": null,
"e": 777,
"s": 768,
"text": "Chapters"
},
{
"code": null,
"e": 804,
"s": 777,
"text": "descriptions off, selected"
},
{
"code": null,
"e": 854,
"s": 804,
"text": "captions settings, opens captions settings dialog"
},
{
"code": null,
"e": 877,
"s": 854,
"text": "captions off, selected"
},
{
"code": null,
"e": 885,
"s": 877,
"text": "English"
},
{
"code": null,
"e": 909,
"s": 885,
"text": "This is a modal window."
},
{
"code": null,
"e": 978,
"s": 909,
"text": "Beginning of dialog window. Escape will cancel and close the window."
},
{
"code": null,
"e": 1000,
"s": 978,
"text": "End of dialog window."
},
{
"code": null,
"e": 1185,
"s": 1000,
"text": "Now, given another set of data points (also called testing data), allocate these points a group by analyzing the training set. Note that the unclassified points are marked as ‘White’. "
},
{
"code": null,
"e": 1758,
"s": 1185,
"text": "Intuition If we plot these points on a graph, we may be able to locate some clusters or groups. Now, given an unclassified point, we can assign it to a group by observing what group its nearest neighbours belong to. This means a point close to a cluster of points classified as ‘Red’ has a higher probability of getting classified as ‘Red’.Intuitively, we can see that the first point (2.5, 7) should be classified as ‘Green’ and the second point (5.5, 4.5) should be classified as ‘Red’.Algorithm Let m be the number of training data samples. Let p be an unknown point. "
},
{
"code": null,
"e": 1884,
"s": 1758,
"text": "Store the training samples in an array of data points arr[]. This means each element of this array represents a tuple (x, y)."
},
{
"code": null,
"e": 2010,
"s": 1884,
"text": "Store the training samples in an array of data points arr[]. This means each element of this array represents a tuple (x, y)."
},
{
"code": null,
"e": 2069,
"s": 2010,
"text": "for i=0 to m:\n Calculate Euclidean distance d(arr[i], p)."
},
{
"code": null,
"e": 2221,
"s": 2069,
"text": "Make set S of K smallest distances obtained. Each of these distances corresponds to an already classified data point.Return the majority label among S."
},
{
"code": null,
"e": 2339,
"s": 2221,
"text": "Make set S of K smallest distances obtained. Each of these distances corresponds to an already classified data point."
},
{
"code": null,
"e": 2374,
"s": 2339,
"text": "Return the majority label among S."
},
{
"code": null,
"e": 2786,
"s": 2376,
"text": "K can be kept as an odd number so that we can calculate a clear majority in the case where only two groups are possible (e.g. Red/Blue). With increasing K, we get smoother, more defined boundaries across different classifications. Also, the accuracy of the above classifier increases as we increase the number of data points in the training set.Example Program Assume 0 and 1 as the two classifiers (groups). "
},
{
"code": null,
"e": 2792,
"s": 2788,
"text": "C++"
},
{
"code": null,
"e": 2797,
"s": 2792,
"text": "Java"
},
{
"code": null,
"e": 2805,
"s": 2797,
"text": "Python3"
},
{
"code": "// C++ program to find groups of unknown// Points using K nearest neighbour algorithm.#include <bits/stdc++.h>using namespace std; struct Point{ int val; // Group of point double x, y; // Co-ordinate of point double distance; // Distance from test point}; // Used to sort an array of points by increasing// order of distancebool comparison(Point a, Point b){ return (a.distance < b.distance);} // This function finds classification of point p using// k nearest neighbour algorithm. It assumes only two// groups and returns 0 if p belongs to group 0, else// 1 (belongs to group 1).int classifyAPoint(Point arr[], int n, int k, Point p){ // Fill distances of all points from p for (int i = 0; i < n; i++) arr[i].distance = sqrt((arr[i].x - p.x) * (arr[i].x - p.x) + (arr[i].y - p.y) * (arr[i].y - p.y)); // Sort the Points by distance from p sort(arr, arr+n, comparison); // Now consider the first k elements and only // two groups int freq1 = 0; // Frequency of group 0 int freq2 = 0; // Frequency of group 1 for (int i = 0; i < k; i++) { if (arr[i].val == 0) freq1++; else if (arr[i].val == 1) freq2++; } return (freq1 > freq2 ? 0 : 1);} // Driver codeint main(){ int n = 17; // Number of data points Point arr[n]; arr[0].x = 1; arr[0].y = 12; arr[0].val = 0; arr[1].x = 2; arr[1].y = 5; arr[1].val = 0; arr[2].x = 5; arr[2].y = 3; arr[2].val = 1; arr[3].x = 3; arr[3].y = 2; arr[3].val = 1; arr[4].x = 3; arr[4].y = 6; arr[4].val = 0; arr[5].x = 1.5; arr[5].y = 9; arr[5].val = 1; arr[6].x = 7; arr[6].y = 2; arr[6].val = 1; arr[7].x = 6; arr[7].y = 1; arr[7].val = 1; arr[8].x = 3.8; arr[8].y = 3; arr[8].val = 1; arr[9].x = 3; arr[9].y = 10; arr[9].val = 0; arr[10].x = 5.6; arr[10].y = 4; arr[10].val = 1; arr[11].x = 4; arr[11].y = 2; arr[11].val = 1; arr[12].x = 3.5; arr[12].y = 8; arr[12].val = 0; arr[13].x = 2; arr[13].y = 11; arr[13].val = 0; arr[14].x = 2; arr[14].y = 5; arr[14].val = 1; arr[15].x = 2; arr[15].y = 9; arr[15].val = 0; arr[16].x = 1; arr[16].y = 7; arr[16].val = 0; /*Testing Point*/ Point p; p.x = 2.5; p.y = 7; // Parameter to decide group of the testing point int k = 3; printf (\"The value classified to unknown point\" \" is %d.\\n\", classifyAPoint(arr, n, k, p)); return 0;}",
"e": 5387,
"s": 2805,
"text": null
},
{
"code": "// Java program to find groups of unknown// Points using K nearest neighbour algorithm.import java.io.*;import java.util.*; class GFG { static class Point { int val; // Group of point double x, y; // Co-ordinate of point double distance; // Distance from test point } // Used to sort an array of points by increasing // order of distance static class comparison implements Comparator<Point> { public int compare(Point a, Point b) { if (a.distance < b.distance) return -1; else if (a.distance > b.distance) return 1; return 0; } } // This function finds classification of point p using // k nearest neighbour algorithm. It assumes only two // groups and returns 0 if p belongs to group 0, else // 1 (belongs to group 1). static int classifyAPoint(Point arr[], int n, int k, Point p) { // Fill distances of all points from p for (int i = 0; i < n; i++) arr[i].distance = Math.sqrt( (arr[i].x - p.x) * (arr[i].x - p.x) + (arr[i].y - p.y) * (arr[i].y - p.y)); // Sort the Points by distance from p Arrays.sort(arr, new comparison()); // Now consider the first k elements and only // two groups int freq1 = 0; // Frequency of group 0 int freq2 = 0; // Frequency of group 1 for (int i = 0; i < k; i++) { if (arr[i].val == 0) freq1++; else if (arr[i].val == 1) freq2++; } return (freq1 > freq2 ? 0 : 1); } // Driver code public static void main(String[] args) { int n = 17; // Number of data points Point[] arr = new Point[n]; for (int i = 0; i < 17; i++) { arr[i] = new Point(); } arr[0].x = 1; arr[0].y = 12; arr[0].val = 0; arr[1].x = 2; arr[1].y = 5; arr[1].val = 0; arr[2].x = 5; arr[2].y = 3; arr[2].val = 1; arr[3].x = 3; arr[3].y = 2; arr[3].val = 1; arr[4].x = 3; arr[4].y = 6; arr[4].val = 0; arr[5].x = 1.5; arr[5].y = 9; arr[5].val = 1; arr[6].x = 7; arr[6].y = 2; arr[6].val = 1; arr[7].x = 6; arr[7].y = 1; arr[7].val = 1; arr[8].x = 3.8; arr[8].y = 3; arr[8].val = 1; arr[9].x = 3; arr[9].y = 10; arr[9].val = 0; arr[10].x = 5.6; arr[10].y = 4; arr[10].val = 1; arr[11].x = 4; arr[11].y = 2; arr[11].val = 1; arr[12].x = 3.5; arr[12].y = 8; arr[12].val = 0; arr[13].x = 2; arr[13].y = 11; arr[13].val = 0; arr[14].x = 2; arr[14].y = 5; arr[14].val = 1; arr[15].x = 2; arr[15].y = 9; arr[15].val = 0; arr[16].x = 1; arr[16].y = 7; arr[16].val = 0; /*Testing Point*/ Point p = new Point(); p.x = 2.5; p.y = 7; // Parameter to decide group of the testing point int k = 3; System.out.println( \"The value classified to unknown point is \" + classifyAPoint(arr, n, k, p)); }} // This code is contributed by Karandeep1234",
"e": 8783,
"s": 5387,
"text": null
},
{
"code": "# Python3 program to find groups of unknown# Points using K nearest neighbour algorithm. import math def classifyAPoint(points,p,k=3): ''' This function finds the classification of p using k nearest neighbor algorithm. It assumes only two groups and returns 0 if p belongs to group 0, else 1 (belongs to group 1). Parameters - points: Dictionary of training points having two keys - 0 and 1 Each key have a list of training data points belong to that p : A tuple, test data point of the form (x,y) k : number of nearest neighbour to consider, default is 3 ''' distance=[] for group in points: for feature in points[group]: #calculate the euclidean distance of p from training points euclidean_distance = math.sqrt((feature[0]-p[0])**2 +(feature[1]-p[1])**2) # Add a tuple of form (distance,group) in the distance list distance.append((euclidean_distance,group)) # sort the distance list in ascending order # and select first k distances distance = sorted(distance)[:k] freq1 = 0 #frequency of group 0 freq2 = 0 #frequency og group 1 for d in distance: if d[1] == 0: freq1 += 1 else if d[1] == 1: freq2 += 1 return 0 if freq1>freq2 else 1 # driver functiondef main(): # Dictionary of training points having two keys - 0 and 1 # key 0 have points belong to class 0 # key 1 have points belong to class 1 points = {0:[(1,12),(2,5),(3,6),(3,10),(3.5,8),(2,11),(2,9),(1,7)], 1:[(5,3),(3,2),(1.5,9),(7,2),(6,1),(3.8,1),(5.6,4),(4,2),(2,5)]} # testing point p(x,y) p = (2.5,7) # Number of neighbours k = 3 print(\"The value classified to unknown point is: {}\".\\ format(classifyAPoint(points,p,k))) if __name__ == '__main__': main() # This code is contributed by Atul Kumar (www.fb.com/atul.kr.007)",
"e": 10755,
"s": 8783,
"text": null
},
{
"code": null,
"e": 10765,
"s": 10755,
"text": "Output: "
},
{
"code": null,
"e": 10809,
"s": 10765,
"text": "The value classified to unknown point is 0."
},
{
"code": null,
"e": 10861,
"s": 10809,
"text": "Time Complexity: O(N * logN)Auxiliary Space: O(1) "
},
{
"code": null,
"e": 11284,
"s": 10861,
"text": "This article is contributed by Anannya Uberoi. 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": 11298,
"s": 11284,
"text": "NIRBHAYKUMAR1"
},
{
"code": null,
"e": 11306,
"s": 11298,
"text": "snk_pan"
},
{
"code": null,
"e": 11322,
"s": 11306,
"text": "pankajsharmagfg"
},
{
"code": null,
"e": 11333,
"s": 11322,
"text": "gurukiranx"
},
{
"code": null,
"e": 11348,
"s": 11333,
"text": "prachisoda1234"
},
{
"code": null,
"e": 11364,
"s": 11348,
"text": "amartyaghoshgfg"
},
{
"code": null,
"e": 11377,
"s": 11364,
"text": "simmytarika5"
},
{
"code": null,
"e": 11391,
"s": 11377,
"text": "karandeep1234"
},
{
"code": null,
"e": 11399,
"s": 11391,
"text": "Directi"
},
{
"code": null,
"e": 11425,
"s": 11399,
"text": "Advanced Computer Subject"
},
{
"code": null,
"e": 11436,
"s": 11425,
"text": "Algorithms"
},
{
"code": null,
"e": 11453,
"s": 11436,
"text": "Machine Learning"
},
{
"code": null,
"e": 11461,
"s": 11453,
"text": "Directi"
},
{
"code": null,
"e": 11472,
"s": 11461,
"text": "Algorithms"
},
{
"code": null,
"e": 11489,
"s": 11472,
"text": "Machine Learning"
}
] |
Private Methods in Java 9 Interfaces | 26 Apr, 2018
Java 9 onwards, you can include private methods in interfaces. Before Java 9 it was not possible.
Interfaces till Java 7
In Java SE 7 or earlier versions, an interface can have only two things i.e. Constant variables and Abstract methods. These interface methods MUST be implemented by classes which choose to implement the interface.
// Java 7 program to illustrate// private methods in interfacespublic interface TempI { public abstract void method(int n);} class Temp implements TempI { @Override public void method(int n) { if (n % 2 == 0) System.out.println("geeksforgeeks"); else System.out.println("GEEKSFORGEEKS"); } public static void main(String[] args) { TempI in1 = new Temp(); TempI in2 = new Temp(); in1.method(4); in2.method(3); }}
OUTPUT : geeksforgeeks
GEEKSFORGEEKS
Java 8 Interface Changes
Some new features to interface were introduced in Java 8 i.e. Default methods and Static methods feature. In Java 8, an interface can have only four types:
Constant variablesAbstract methodsDefault methodsStatic methods
Constant variables
Abstract methods
Default methods
Static methods
Example
// Java 8 program to illustrate// static, default and abstract methods in interfacespublic interface TempI { public abstract void div(int a, int b); public default void add(int a, int b) { System.out.print("Answer by Default method = "); System.out.println(a + b); } public static void mul(int a, int b) { System.out.print("Answer by Static method = "); System.out.println(a * b); }} class Temp implements TempI { @Override public void div(int a, int b) { System.out.print("Answer by Abstract method = "); System.out.println(a / b); } public static void main(String[] args) { TempI in = new Temp(); in.div(8, 2); in.add(3, 1); TempI.mul(4, 1); }}
OUTPUT : Answer by Abstract method = 4
Answer by Default method = 4
Answer by Static method = 4
Java 9 Interface Changes
Java 9 introduced private methods and private static method in interfaces. In Java 9 and later versions, an interface can have six different things:
Constant variablesAbstract methodsDefault methodsStatic methodsPrivate methodsPrivate Static methodsThese private methods will improve code re-usability inside interfaces and will provide choice to expose only our intended methods implementations to users.These methods are only accessible within that interface only and cannot be accessed or inherited from an interface to another interface or class.// Java 9 program to illustrate// private methods in interfacespublic interface TempI { public abstract void mul(int a, int b); public default void add(int a, int b) {// private method inside default method sub(a, b); // static method inside other non-static method div(a, b); System.out.print("Answer by Default method = "); System.out.println(a + b); } public static void mod(int a, int b) { div(a, b); // static method inside other static method System.out.print("Answer by Static method = "); System.out.println(a % b); } private void sub(int a, int b) { System.out.print("Answer by Private method = "); System.out.println(a - b); } private static void div(int a, int b) { System.out.print("Answer by Private static method = "); System.out.println(a / b); }} class Temp implements TempI { @Override public void mul(int a, int b) { System.out.print("Answer by Abstract method = "); System.out.println(a * b); } public static void main(String[] args) { TempI in = new Temp(); in.mul(2, 3); in.add(6, 2); TempI.mod(5, 3); }}OUTPUT : Answer by Abstract method = 6 // mul(2, 3) = 2*3 = 6
Answer by Private method = 4 // sub(6, 2) = 6-2 = 4
Answer by Private static method = 3 // div(6, 2) = 6/2 = 3
Answer by Default method = 8 // add(6, 2) = 6+2 = 8
Answer by Private static method = 1 // div(5, 3) = 5/3 = 1
Answer by Static method = 2 // mod(5, 3) = 5%3 = 2
Rules For using Private Methods in InterfacesPrivate interface method cannot be abstract and no private and abstract modifiers together.Private method can be used only inside interface and other static and non-static interface methods.Private non-static methods cannot be used inside private static methods.We should use private modifier to define these methods and no lesser accessibility than private modifier. So, from above it can be conlcuded that java 9 private interface methods can be static or instance. In both cases, the private method is not inherited by sub-interfaces or implementations. They are mainly there to improve code re-usability within interface only – thus improving encapsulation.My Personal Notes
arrow_drop_upSave
Constant variables
Abstract methods
Default methods
Static methods
Private methods
Private Static methods
These private methods will improve code re-usability inside interfaces and will provide choice to expose only our intended methods implementations to users.These methods are only accessible within that interface only and cannot be accessed or inherited from an interface to another interface or class.
// Java 9 program to illustrate// private methods in interfacespublic interface TempI { public abstract void mul(int a, int b); public default void add(int a, int b) {// private method inside default method sub(a, b); // static method inside other non-static method div(a, b); System.out.print("Answer by Default method = "); System.out.println(a + b); } public static void mod(int a, int b) { div(a, b); // static method inside other static method System.out.print("Answer by Static method = "); System.out.println(a % b); } private void sub(int a, int b) { System.out.print("Answer by Private method = "); System.out.println(a - b); } private static void div(int a, int b) { System.out.print("Answer by Private static method = "); System.out.println(a / b); }} class Temp implements TempI { @Override public void mul(int a, int b) { System.out.print("Answer by Abstract method = "); System.out.println(a * b); } public static void main(String[] args) { TempI in = new Temp(); in.mul(2, 3); in.add(6, 2); TempI.mod(5, 3); }}
OUTPUT : Answer by Abstract method = 6 // mul(2, 3) = 2*3 = 6
Answer by Private method = 4 // sub(6, 2) = 6-2 = 4
Answer by Private static method = 3 // div(6, 2) = 6/2 = 3
Answer by Default method = 8 // add(6, 2) = 6+2 = 8
Answer by Private static method = 1 // div(5, 3) = 5/3 = 1
Answer by Static method = 2 // mod(5, 3) = 5%3 = 2
Rules For using Private Methods in Interfaces
Private interface method cannot be abstract and no private and abstract modifiers together.
Private method can be used only inside interface and other static and non-static interface methods.
Private non-static methods cannot be used inside private static methods.
We should use private modifier to define these methods and no lesser accessibility than private modifier.
So, from above it can be conlcuded that java 9 private interface methods can be static or instance. In both cases, the private method is not inherited by sub-interfaces or implementations. They are mainly there to improve code re-usability within interface only – thus improving encapsulation.
java-interfaces
Java
Technical Scripter
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Stream In Java
Introduction to Java
Constructors in Java
Exceptions in Java
Generics in Java
Functional Interfaces in Java
Strings in Java
Java Programming Examples
HashSet in Java
Abstraction in Java | [
{
"code": null,
"e": 54,
"s": 26,
"text": "\n26 Apr, 2018"
},
{
"code": null,
"e": 152,
"s": 54,
"text": "Java 9 onwards, you can include private methods in interfaces. Before Java 9 it was not possible."
},
{
"code": null,
"e": 175,
"s": 152,
"text": "Interfaces till Java 7"
},
{
"code": null,
"e": 389,
"s": 175,
"text": "In Java SE 7 or earlier versions, an interface can have only two things i.e. Constant variables and Abstract methods. These interface methods MUST be implemented by classes which choose to implement the interface."
},
{
"code": "// Java 7 program to illustrate// private methods in interfacespublic interface TempI { public abstract void method(int n);} class Temp implements TempI { @Override public void method(int n) { if (n % 2 == 0) System.out.println(\"geeksforgeeks\"); else System.out.println(\"GEEKSFORGEEKS\"); } public static void main(String[] args) { TempI in1 = new Temp(); TempI in2 = new Temp(); in1.method(4); in2.method(3); }}",
"e": 892,
"s": 389,
"text": null
},
{
"code": null,
"e": 939,
"s": 892,
"text": "OUTPUT : geeksforgeeks\n GEEKSFORGEEKS\n"
},
{
"code": null,
"e": 964,
"s": 939,
"text": "Java 8 Interface Changes"
},
{
"code": null,
"e": 1120,
"s": 964,
"text": "Some new features to interface were introduced in Java 8 i.e. Default methods and Static methods feature. In Java 8, an interface can have only four types:"
},
{
"code": null,
"e": 1184,
"s": 1120,
"text": "Constant variablesAbstract methodsDefault methodsStatic methods"
},
{
"code": null,
"e": 1203,
"s": 1184,
"text": "Constant variables"
},
{
"code": null,
"e": 1220,
"s": 1203,
"text": "Abstract methods"
},
{
"code": null,
"e": 1236,
"s": 1220,
"text": "Default methods"
},
{
"code": null,
"e": 1251,
"s": 1236,
"text": "Static methods"
},
{
"code": null,
"e": 1259,
"s": 1251,
"text": "Example"
},
{
"code": "// Java 8 program to illustrate// static, default and abstract methods in interfacespublic interface TempI { public abstract void div(int a, int b); public default void add(int a, int b) { System.out.print(\"Answer by Default method = \"); System.out.println(a + b); } public static void mul(int a, int b) { System.out.print(\"Answer by Static method = \"); System.out.println(a * b); }} class Temp implements TempI { @Override public void div(int a, int b) { System.out.print(\"Answer by Abstract method = \"); System.out.println(a / b); } public static void main(String[] args) { TempI in = new Temp(); in.div(8, 2); in.add(3, 1); TempI.mul(4, 1); }}",
"e": 2028,
"s": 1259,
"text": null
},
{
"code": null,
"e": 2143,
"s": 2028,
"text": "OUTPUT : Answer by Abstract method = 4\n Answer by Default method = 4\n Answer by Static method = 4\n"
},
{
"code": null,
"e": 2168,
"s": 2143,
"text": "Java 9 Interface Changes"
},
{
"code": null,
"e": 2317,
"s": 2168,
"text": "Java 9 introduced private methods and private static method in interfaces. In Java 9 and later versions, an interface can have six different things:"
},
{
"code": null,
"e": 5134,
"s": 2317,
"text": "Constant variablesAbstract methodsDefault methodsStatic methodsPrivate methodsPrivate Static methodsThese private methods will improve code re-usability inside interfaces and will provide choice to expose only our intended methods implementations to users.These methods are only accessible within that interface only and cannot be accessed or inherited from an interface to another interface or class.// Java 9 program to illustrate// private methods in interfacespublic interface TempI { public abstract void mul(int a, int b); public default void add(int a, int b) {// private method inside default method sub(a, b); // static method inside other non-static method div(a, b); System.out.print(\"Answer by Default method = \"); System.out.println(a + b); } public static void mod(int a, int b) { div(a, b); // static method inside other static method System.out.print(\"Answer by Static method = \"); System.out.println(a % b); } private void sub(int a, int b) { System.out.print(\"Answer by Private method = \"); System.out.println(a - b); } private static void div(int a, int b) { System.out.print(\"Answer by Private static method = \"); System.out.println(a / b); }} class Temp implements TempI { @Override public void mul(int a, int b) { System.out.print(\"Answer by Abstract method = \"); System.out.println(a * b); } public static void main(String[] args) { TempI in = new Temp(); in.mul(2, 3); in.add(6, 2); TempI.mod(5, 3); }}OUTPUT : Answer by Abstract method = 6 // mul(2, 3) = 2*3 = 6\n Answer by Private method = 4 // sub(6, 2) = 6-2 = 4 \n Answer by Private static method = 3 // div(6, 2) = 6/2 = 3\n Answer by Default method = 8 // add(6, 2) = 6+2 = 8\n Answer by Private static method = 1 // div(5, 3) = 5/3 = 1 \n Answer by Static method = 2 // mod(5, 3) = 5%3 = 2\n Rules For using Private Methods in InterfacesPrivate interface method cannot be abstract and no private and abstract modifiers together.Private method can be used only inside interface and other static and non-static interface methods.Private non-static methods cannot be used inside private static methods.We should use private modifier to define these methods and no lesser accessibility than private modifier. So, from above it can be conlcuded that java 9 private interface methods can be static or instance. In both cases, the private method is not inherited by sub-interfaces or implementations. They are mainly there to improve code re-usability within interface only – thus improving encapsulation.My Personal Notes\narrow_drop_upSave"
},
{
"code": null,
"e": 5153,
"s": 5134,
"text": "Constant variables"
},
{
"code": null,
"e": 5170,
"s": 5153,
"text": "Abstract methods"
},
{
"code": null,
"e": 5186,
"s": 5170,
"text": "Default methods"
},
{
"code": null,
"e": 5201,
"s": 5186,
"text": "Static methods"
},
{
"code": null,
"e": 5217,
"s": 5201,
"text": "Private methods"
},
{
"code": null,
"e": 5240,
"s": 5217,
"text": "Private Static methods"
},
{
"code": null,
"e": 5542,
"s": 5240,
"text": "These private methods will improve code re-usability inside interfaces and will provide choice to expose only our intended methods implementations to users.These methods are only accessible within that interface only and cannot be accessed or inherited from an interface to another interface or class."
},
{
"code": "// Java 9 program to illustrate// private methods in interfacespublic interface TempI { public abstract void mul(int a, int b); public default void add(int a, int b) {// private method inside default method sub(a, b); // static method inside other non-static method div(a, b); System.out.print(\"Answer by Default method = \"); System.out.println(a + b); } public static void mod(int a, int b) { div(a, b); // static method inside other static method System.out.print(\"Answer by Static method = \"); System.out.println(a % b); } private void sub(int a, int b) { System.out.print(\"Answer by Private method = \"); System.out.println(a - b); } private static void div(int a, int b) { System.out.print(\"Answer by Private static method = \"); System.out.println(a / b); }} class Temp implements TempI { @Override public void mul(int a, int b) { System.out.print(\"Answer by Abstract method = \"); System.out.println(a * b); } public static void main(String[] args) { TempI in = new Temp(); in.mul(2, 3); in.add(6, 2); TempI.mod(5, 3); }}",
"e": 6764,
"s": 5542,
"text": null
},
{
"code": null,
"e": 7217,
"s": 6764,
"text": "OUTPUT : Answer by Abstract method = 6 // mul(2, 3) = 2*3 = 6\n Answer by Private method = 4 // sub(6, 2) = 6-2 = 4 \n Answer by Private static method = 3 // div(6, 2) = 6/2 = 3\n Answer by Default method = 8 // add(6, 2) = 6+2 = 8\n Answer by Private static method = 1 // div(5, 3) = 5/3 = 1 \n Answer by Static method = 2 // mod(5, 3) = 5%3 = 2\n"
},
{
"code": null,
"e": 7264,
"s": 7217,
"text": " Rules For using Private Methods in Interfaces"
},
{
"code": null,
"e": 7356,
"s": 7264,
"text": "Private interface method cannot be abstract and no private and abstract modifiers together."
},
{
"code": null,
"e": 7456,
"s": 7356,
"text": "Private method can be used only inside interface and other static and non-static interface methods."
},
{
"code": null,
"e": 7529,
"s": 7456,
"text": "Private non-static methods cannot be used inside private static methods."
},
{
"code": null,
"e": 7635,
"s": 7529,
"text": "We should use private modifier to define these methods and no lesser accessibility than private modifier."
},
{
"code": null,
"e": 7930,
"s": 7635,
"text": " So, from above it can be conlcuded that java 9 private interface methods can be static or instance. In both cases, the private method is not inherited by sub-interfaces or implementations. They are mainly there to improve code re-usability within interface only – thus improving encapsulation."
},
{
"code": null,
"e": 7946,
"s": 7930,
"text": "java-interfaces"
},
{
"code": null,
"e": 7951,
"s": 7946,
"text": "Java"
},
{
"code": null,
"e": 7970,
"s": 7951,
"text": "Technical Scripter"
},
{
"code": null,
"e": 7975,
"s": 7970,
"text": "Java"
},
{
"code": null,
"e": 8073,
"s": 7975,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 8088,
"s": 8073,
"text": "Stream In Java"
},
{
"code": null,
"e": 8109,
"s": 8088,
"text": "Introduction to Java"
},
{
"code": null,
"e": 8130,
"s": 8109,
"text": "Constructors in Java"
},
{
"code": null,
"e": 8149,
"s": 8130,
"text": "Exceptions in Java"
},
{
"code": null,
"e": 8166,
"s": 8149,
"text": "Generics in Java"
},
{
"code": null,
"e": 8196,
"s": 8166,
"text": "Functional Interfaces in Java"
},
{
"code": null,
"e": 8212,
"s": 8196,
"text": "Strings in Java"
},
{
"code": null,
"e": 8238,
"s": 8212,
"text": "Java Programming Examples"
},
{
"code": null,
"e": 8254,
"s": 8238,
"text": "HashSet in Java"
}
] |
Sort 1 to N by swapping adjacent elements | 09 Jun, 2022
Given an array, A of size N consisting of elements 1 to N. A boolean array B consisting of N-1 elements indicates that if B[i] is 1, then A[i] can be swapped with A[i+1]. Find out if A can be sorted by swapping elements.Examples:
Input : A[] = {1, 2, 5, 3, 4, 6}
B[] = {0, 1, 1, 1, 0}
Output : A can be sorted
We can swap A[2] with A[3] and then A[3] with A[4].
Input : A[] = {2, 3, 1, 4, 5, 6}
B[] = {0, 1, 1, 1, 1}
Output : A can not be sorted
We can not sort A by swapping elements as 1 can never be swapped with A[0]=2.
Here we can swap only A[i] with A[i+1]. So to find whether array can be sorted or not. Using boolean array B we can sort array for a continuous sequence of 1 for B. At last, we can check, if A is sorted or not.
C++
Java
Python3
C#
PHP
Javascript
// CPP program to test whether array// can be sorted by swapping adjacent// elements using boolean array#include <bits/stdc++.h>using namespace std; // Return true if array can be// sorted otherwise falsebool sortedAfterSwap(int A[], bool B[], int n){ int i, j; // Check bool array B and sorts // elements for continuous sequence of 1 for (i = 0; i < n - 1; i++) { if (B[i]) { j = i; while (B[j]) j++; // Sort array A from i to j sort(A + i, A + 1 + j); i = j; } } // Check if array is sorted or not for (i = 0; i < n; i++) { if (A[i] != i + 1) return false; } return true;} // Driver program to test sortedAfterSwap()int main(){ int A[] = { 1, 2, 5, 3, 4, 6 }; bool B[] = { 0, 1, 1, 1, 0 }; int n = sizeof(A) / sizeof(A[0]); if (sortedAfterSwap(A, B, n)) cout << "A can be sorted\n"; else cout << "A can not be sorted\n"; return 0;}
import java.util.Arrays; // Java program to test whether an array// can be sorted by swapping adjacent// elements using boolean array class GFG { // Return true if array can be // sorted otherwise false static boolean sortedAfterSwap(int A[], boolean B[], int n) { int i, j; // Check bool array B and sorts // elements for continuous sequence of 1 for (i = 0; i < n - 1; i++) { if (B[i]) { j = i; while (B[j]) { j++; } // Sort array A from i to j Arrays.sort(A, i, 1 + j); i = j; } } // Check if array is sorted or not for (i = 0; i < n; i++) { if (A[i] != i + 1) { return false; } } return true; } // Driver program to test sortedAfterSwap() public static void main(String[] args) { int A[] = { 1, 2, 5, 3, 4, 6 }; boolean B[] = { false, true, true, true, false }; int n = A.length; if (sortedAfterSwap(A, B, n)) { System.out.println("A can be sorted"); } else { System.out.println("A can not be sorted"); } }}
# Python 3 program to test whether an array# can be sorted by swapping adjacent# elements using a boolean array # Return true if array can be# sorted otherwise falsedef sortedAfterSwap(A, B, n) : # Check bool array B and sorts # elements for continuous sequence of 1 for i in range(0, n - 1) : if (B[i]== 1) : j = i while (B[j]== 1) : j = j + 1 # Sort array A from i to j A = A[0:i] + sorted(A[i:j + 1]) + A[j + 1:] i = j # Check if array is sorted or not for i in range(0, n) : if (A[i] != i + 1) : return False return True # Driver program to test sortedAfterSwap()A = [ 1, 2, 5, 3, 4, 6 ]B = [ 0, 1, 1, 1, 0 ]n = len(A) if (sortedAfterSwap(A, B, n)) : print("A can be sorted")else : print("A can not be sorted") # This code is contributed# by Nikita Tiwari.
// C# program to test whether array// can be sorted by swapping adjacent// elements using boolean arrayusing System;class GFG { // Return true if array can be // sorted otherwise false static bool sortedAfterSwap(int[] A, bool[] B, int n) { int i, j; // Check bool array B and sorts // elements for continuous sequence of 1 for (i = 0; i < n - 1; i++) { if (B[i]) { j = i; while (B[j]) { j++; } // Sort array A from i to j Array.Sort(A, i, 1 + j); i = j; } } // Check if array is sorted or not for (i = 0; i < n; i++) { if (A[i] != i + 1) { return false; } } return true; } // Driver Code public static void Main() { int[] A = { 1, 2, 5, 3, 4, 6 }; bool[] B = { false, true, true, true, false }; int n = A.Length; if (sortedAfterSwap(A, B, n)) { Console.WriteLine("A can be sorted"); } else { Console.WriteLine("A can not be sorted"); } }} // This code is contributed by Sam007
<?php// PHP program to test whether array// can be sorted by swapping adjacent// elements using boolean array // Return true if array can be// sorted otherwise falsefunction sortedAfterSwap($A, $B, $n){ // Check bool array B and sorts // elements for continuous sequence of 1 for ($i = 0; $i < $n - 1; $i++) { if ($B[$i]) { $j = $i; while ($B[$j]) $j++; // Sort array A from i to j sort($A); $i = $j; } } // Check if array is sorted or not for ($i = 0; $i < $n; $i++) { if ($A[$i] != $i + 1) return false; } return true;} // Driver Code $A = array(1, 2, 5, 3, 4, 6); $B = array(0, 1, 1, 1, 0); $n = count($A); if (sortedAfterSwap($A, $B, $n)) echo "A can be sorted\n"; else echo "A can not be sorted\n"; // This code is contributed by Sam007?>
<script>// JavaScript program to test whether an array// can be sorted by swapping adjacent// elements using boolean array // Return true if array can be // sorted otherwise false function sortedAfterSwap(A, B, n) { let i, j; // Check bool array B and sorts // elements for continuous sequence of 1 for (i = 0; i < n - 1; i++) { if (B[i]) { j = i; while (B[j]) { j++; } // Sort array A from i to j A.sort(); i = j; } } // Check if array is sorted or not for (i = 0; i < n; i++) { if (A[i] != i + 1) { return false; } } return true; } // Driver Code let A = [ 1, 2, 5, 3, 4, 6 ]; let B = [ false, true, true, true, false ]; let n = A.length; if (sortedAfterSwap(A, B, n)) { document.write("A can be sorted"); } else { document.write("A can not be sorted"); } // This code is contributed by code_hunt.</script>
A can be sorted
Time Complexity: O(n*n*logn), where n time is used for iterating and n*logn for sorting inside the arrayAuxiliary Space: O(1), as no extra space is required
Alternative Approach Here we discuss a very intuitive approach which too gives the answer in O(n) time for all cases. The idea here is that whenever the binary array has 1, we check if that index in array A has i+1 or not. If it does not contain i+1, we simply swap a[i] with a[i+1]. The reason for this is that the array should have i+1 stored at index i. And if at all the array is sortable, then the only operation allowed is swapping. Hence, if the required condition is not satisfied, we simply swap. If the array is sortable, swapping will take us one step closer to the correct answer. And as expected, if the array is not sortable, then swapping would lead to just another unsorted version of the same array.
C++
Java
Python3
C#
PHP
Javascript
// CPP program to test whether array// can be sorted by swapping adjacent// elements using boolean array#include <bits/stdc++.h>using namespace std; // Return true if array can be// sorted otherwise falsebool sortedAfterSwap(int A[], bool B[], int n){ for (int i = 0; i < n - 1; i++) { if (B[i]) { if (A[i] != i + 1) swap(A[i], A[i + 1]); } } // Check if array is sorted or not for (int i = 0; i < n; i++) { if (A[i] != i + 1) return false; } return true;} // Driver program to test sortedAfterSwap()int main(){ int A[] = { 1, 2, 5, 3, 4, 6 }; bool B[] = { 0, 1, 1, 1, 0 }; int n = sizeof(A) / sizeof(A[0]); if (sortedAfterSwap(A, B, n)) cout << "A can be sorted\n"; else cout << "A can not be sorted\n"; return 0;}
// Java program to test whether an array// can be sorted by swapping adjacent// elements using boolean arrayclass GFG{ // Return true if array can be // sorted otherwise false static int sortedAfterSwap(int[] A, int[] B, int n) { int t = 0; for (int i = 0; i < n - 1; i++) { if (B[i] != 0) { if (A[i] != i + 1) t = A[i]; A[i] = A[i + 1]; A[i + 1] = t; } } // Check if array is sorted or not for (int i = 0; i < n; i++) { if (A[i] != i + 1) return 0; } return 1; } // Driver Code public static void main(String[] args) { int[] A = { 1, 2, 5, 3, 4, 6 }; int[] B = { 0, 1, 1, 1, 0 }; int n = A.length; if (sortedAfterSwap(A, B, n) == 0) System.out.println("A can be sorted"); else System.out.println("A can not be sorted"); }} // This code is contributed// by Mukul Singh.
# Python3 program to test whether array# can be sorted by swapping adjacent# elements using boolean array # Return true if array can be# sorted otherwise falsedef sortedAfterSwap(A,B,n): for i in range(0,n-1): if B[i]: if A[i]!=i+1: A[i], A[i+1] = A[i+1], A[i] # Check if array is sorted or not for i in range(n): if A[i]!=i+1: return False return True # Driver programif __name__=='__main__': A = [1, 2, 5, 3, 4, 6] B = [0, 1, 1, 1, 0] n =len(A) if (sortedAfterSwap(A, B, n)) : print("A can be sorted") else : print("A can not be sorted") # This code is contributed by# Shrikant13
// C# program to test whether array// can be sorted by swapping adjacent// elements using boolean arrayusing System; class GFG{ // Return true if array can be // sorted otherwise false static int sortedAfterSwap(int[] A, int[] B, int n) { int t = 0; for (int i = 0; i < n - 1; i++) { if (B[i] != 0) { if (A[i] != i + 1) t = A[i]; A[i] = A[i + 1]; A[i + 1] = t; } } // Check if array is sorted or not for (int i = 0; i < n; i++) { if (A[i] != i + 1) return 0; } return 1; } // Driver Code public static void Main() { int[] A = { 1, 2, 5, 3, 4, 6 }; int[] B = { 0, 1, 1, 1, 0 }; int n = A.Length; if (sortedAfterSwap(A, B, n) == 0) Console.WriteLine("A can be sorted"); else Console.WriteLine("A can not be sorted"); }} // This code is contributed// by Akanksha Rai
<?php// PHP program to test whether array// can be sorted by swapping adjacent// elements using boolean array // Return true if array can be// sorted otherwise falsefunction sortedAfterSwap(&$A, &$B, $n){ for ($i = 0; $i < $n - 1; $i++) { if ($B[$i]) { if ($A[$i] != $i + 1) { $t = $A[$i]; $A[$i] = $A[$i + 1]; $A[$i + 1] = $t; } } } // Check if array is sorted or not for ($i = 0; $i < $n; $i++) { if ($A[$i] != $i + 1) return false; } return true;} // Driver Code$A = array( 1, 2, 5, 3, 4, 6 );$B = array( 0, 1, 1, 1, 0 );$n = sizeof($A); if (sortedAfterSwap($A, $B, $n)) echo "A can be sorted\n";else echo "A can not be sorted\n"; // This code is contributed by ita_c?>
<script> // JavaScript program to test whether an array// can be sorted by swapping adjacent// elements using boolean array // Return true if array can be // sorted otherwise false function sortedAfterSwap(A,B,n) { let t = 0; for (let i = 0; i < n - 1; i++) { if (B[i] != 0) { if (A[i] != i + 1) t = A[i]; A[i] = A[i + 1]; A[i + 1] = t; } } // Check if array is sorted or not for (let i = 0; i < n; i++) { if (A[i] != i + 1) return 0; } return 1; } // Driver Code let A = [ 1, 2, 5, 3, 4, 6 ]; let B = [ 0, 1, 1, 1, 0 ]; let n = A.length; if (sortedAfterSwap(A, B, n) == 0) document.write("A can be sorted"); else document.write("A can not be sorted"); // This code is contributed// by sravan kumar Gottumukkala </script>
A can be sorted
Time Complexity: O(n)Auxiliary Space: O(1)
Sam007
02DCE
shrikanth13
ukasp
Akanksha_Rai
Code_Mech
nidhi_biet
aut0b0t
code_hunt
sravankumar8128
singhh3010
binary-string
Arrays
Sorting
Arrays
Sorting
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here. | [
{
"code": null,
"e": 52,
"s": 24,
"text": "\n09 Jun, 2022"
},
{
"code": null,
"e": 284,
"s": 52,
"text": "Given an array, A of size N consisting of elements 1 to N. A boolean array B consisting of N-1 elements indicates that if B[i] is 1, then A[i] can be swapped with A[i+1]. Find out if A can be sorted by swapping elements.Examples: "
},
{
"code": null,
"e": 595,
"s": 284,
"text": "Input : A[] = {1, 2, 5, 3, 4, 6}\n B[] = {0, 1, 1, 1, 0}\nOutput : A can be sorted\nWe can swap A[2] with A[3] and then A[3] with A[4].\n\nInput : A[] = {2, 3, 1, 4, 5, 6}\n B[] = {0, 1, 1, 1, 1}\nOutput : A can not be sorted\nWe can not sort A by swapping elements as 1 can never be swapped with A[0]=2."
},
{
"code": null,
"e": 810,
"s": 597,
"text": "Here we can swap only A[i] with A[i+1]. So to find whether array can be sorted or not. Using boolean array B we can sort array for a continuous sequence of 1 for B. At last, we can check, if A is sorted or not. "
},
{
"code": null,
"e": 814,
"s": 810,
"text": "C++"
},
{
"code": null,
"e": 819,
"s": 814,
"text": "Java"
},
{
"code": null,
"e": 827,
"s": 819,
"text": "Python3"
},
{
"code": null,
"e": 830,
"s": 827,
"text": "C#"
},
{
"code": null,
"e": 834,
"s": 830,
"text": "PHP"
},
{
"code": null,
"e": 845,
"s": 834,
"text": "Javascript"
},
{
"code": "// CPP program to test whether array// can be sorted by swapping adjacent// elements using boolean array#include <bits/stdc++.h>using namespace std; // Return true if array can be// sorted otherwise falsebool sortedAfterSwap(int A[], bool B[], int n){ int i, j; // Check bool array B and sorts // elements for continuous sequence of 1 for (i = 0; i < n - 1; i++) { if (B[i]) { j = i; while (B[j]) j++; // Sort array A from i to j sort(A + i, A + 1 + j); i = j; } } // Check if array is sorted or not for (i = 0; i < n; i++) { if (A[i] != i + 1) return false; } return true;} // Driver program to test sortedAfterSwap()int main(){ int A[] = { 1, 2, 5, 3, 4, 6 }; bool B[] = { 0, 1, 1, 1, 0 }; int n = sizeof(A) / sizeof(A[0]); if (sortedAfterSwap(A, B, n)) cout << \"A can be sorted\\n\"; else cout << \"A can not be sorted\\n\"; return 0;}",
"e": 1846,
"s": 845,
"text": null
},
{
"code": "import java.util.Arrays; // Java program to test whether an array// can be sorted by swapping adjacent// elements using boolean array class GFG { // Return true if array can be // sorted otherwise false static boolean sortedAfterSwap(int A[], boolean B[], int n) { int i, j; // Check bool array B and sorts // elements for continuous sequence of 1 for (i = 0; i < n - 1; i++) { if (B[i]) { j = i; while (B[j]) { j++; } // Sort array A from i to j Arrays.sort(A, i, 1 + j); i = j; } } // Check if array is sorted or not for (i = 0; i < n; i++) { if (A[i] != i + 1) { return false; } } return true; } // Driver program to test sortedAfterSwap() public static void main(String[] args) { int A[] = { 1, 2, 5, 3, 4, 6 }; boolean B[] = { false, true, true, true, false }; int n = A.length; if (sortedAfterSwap(A, B, n)) { System.out.println(\"A can be sorted\"); } else { System.out.println(\"A can not be sorted\"); } }}",
"e": 3127,
"s": 1846,
"text": null
},
{
"code": "# Python 3 program to test whether an array# can be sorted by swapping adjacent# elements using a boolean array # Return true if array can be# sorted otherwise falsedef sortedAfterSwap(A, B, n) : # Check bool array B and sorts # elements for continuous sequence of 1 for i in range(0, n - 1) : if (B[i]== 1) : j = i while (B[j]== 1) : j = j + 1 # Sort array A from i to j A = A[0:i] + sorted(A[i:j + 1]) + A[j + 1:] i = j # Check if array is sorted or not for i in range(0, n) : if (A[i] != i + 1) : return False return True # Driver program to test sortedAfterSwap()A = [ 1, 2, 5, 3, 4, 6 ]B = [ 0, 1, 1, 1, 0 ]n = len(A) if (sortedAfterSwap(A, B, n)) : print(\"A can be sorted\")else : print(\"A can not be sorted\") # This code is contributed# by Nikita Tiwari.",
"e": 4043,
"s": 3127,
"text": null
},
{
"code": "// C# program to test whether array// can be sorted by swapping adjacent// elements using boolean arrayusing System;class GFG { // Return true if array can be // sorted otherwise false static bool sortedAfterSwap(int[] A, bool[] B, int n) { int i, j; // Check bool array B and sorts // elements for continuous sequence of 1 for (i = 0; i < n - 1; i++) { if (B[i]) { j = i; while (B[j]) { j++; } // Sort array A from i to j Array.Sort(A, i, 1 + j); i = j; } } // Check if array is sorted or not for (i = 0; i < n; i++) { if (A[i] != i + 1) { return false; } } return true; } // Driver Code public static void Main() { int[] A = { 1, 2, 5, 3, 4, 6 }; bool[] B = { false, true, true, true, false }; int n = A.Length; if (sortedAfterSwap(A, B, n)) { Console.WriteLine(\"A can be sorted\"); } else { Console.WriteLine(\"A can not be sorted\"); } }} // This code is contributed by Sam007",
"e": 5319,
"s": 4043,
"text": null
},
{
"code": "<?php// PHP program to test whether array// can be sorted by swapping adjacent// elements using boolean array // Return true if array can be// sorted otherwise falsefunction sortedAfterSwap($A, $B, $n){ // Check bool array B and sorts // elements for continuous sequence of 1 for ($i = 0; $i < $n - 1; $i++) { if ($B[$i]) { $j = $i; while ($B[$j]) $j++; // Sort array A from i to j sort($A); $i = $j; } } // Check if array is sorted or not for ($i = 0; $i < $n; $i++) { if ($A[$i] != $i + 1) return false; } return true;} // Driver Code $A = array(1, 2, 5, 3, 4, 6); $B = array(0, 1, 1, 1, 0); $n = count($A); if (sortedAfterSwap($A, $B, $n)) echo \"A can be sorted\\n\"; else echo \"A can not be sorted\\n\"; // This code is contributed by Sam007?>",
"e": 6240,
"s": 5319,
"text": null
},
{
"code": "<script>// JavaScript program to test whether an array// can be sorted by swapping adjacent// elements using boolean array // Return true if array can be // sorted otherwise false function sortedAfterSwap(A, B, n) { let i, j; // Check bool array B and sorts // elements for continuous sequence of 1 for (i = 0; i < n - 1; i++) { if (B[i]) { j = i; while (B[j]) { j++; } // Sort array A from i to j A.sort(); i = j; } } // Check if array is sorted or not for (i = 0; i < n; i++) { if (A[i] != i + 1) { return false; } } return true; } // Driver Code let A = [ 1, 2, 5, 3, 4, 6 ]; let B = [ false, true, true, true, false ]; let n = A.length; if (sortedAfterSwap(A, B, n)) { document.write(\"A can be sorted\"); } else { document.write(\"A can not be sorted\"); } // This code is contributed by code_hunt.</script>",
"e": 7376,
"s": 6240,
"text": null
},
{
"code": null,
"e": 7392,
"s": 7376,
"text": "A can be sorted"
},
{
"code": null,
"e": 7551,
"s": 7394,
"text": "Time Complexity: O(n*n*logn), where n time is used for iterating and n*logn for sorting inside the arrayAuxiliary Space: O(1), as no extra space is required"
},
{
"code": null,
"e": 8269,
"s": 7551,
"text": "Alternative Approach Here we discuss a very intuitive approach which too gives the answer in O(n) time for all cases. The idea here is that whenever the binary array has 1, we check if that index in array A has i+1 or not. If it does not contain i+1, we simply swap a[i] with a[i+1]. The reason for this is that the array should have i+1 stored at index i. And if at all the array is sortable, then the only operation allowed is swapping. Hence, if the required condition is not satisfied, we simply swap. If the array is sortable, swapping will take us one step closer to the correct answer. And as expected, if the array is not sortable, then swapping would lead to just another unsorted version of the same array. "
},
{
"code": null,
"e": 8273,
"s": 8269,
"text": "C++"
},
{
"code": null,
"e": 8278,
"s": 8273,
"text": "Java"
},
{
"code": null,
"e": 8286,
"s": 8278,
"text": "Python3"
},
{
"code": null,
"e": 8289,
"s": 8286,
"text": "C#"
},
{
"code": null,
"e": 8293,
"s": 8289,
"text": "PHP"
},
{
"code": null,
"e": 8304,
"s": 8293,
"text": "Javascript"
},
{
"code": "// CPP program to test whether array// can be sorted by swapping adjacent// elements using boolean array#include <bits/stdc++.h>using namespace std; // Return true if array can be// sorted otherwise falsebool sortedAfterSwap(int A[], bool B[], int n){ for (int i = 0; i < n - 1; i++) { if (B[i]) { if (A[i] != i + 1) swap(A[i], A[i + 1]); } } // Check if array is sorted or not for (int i = 0; i < n; i++) { if (A[i] != i + 1) return false; } return true;} // Driver program to test sortedAfterSwap()int main(){ int A[] = { 1, 2, 5, 3, 4, 6 }; bool B[] = { 0, 1, 1, 1, 0 }; int n = sizeof(A) / sizeof(A[0]); if (sortedAfterSwap(A, B, n)) cout << \"A can be sorted\\n\"; else cout << \"A can not be sorted\\n\"; return 0;}",
"e": 9132,
"s": 8304,
"text": null
},
{
"code": "// Java program to test whether an array// can be sorted by swapping adjacent// elements using boolean arrayclass GFG{ // Return true if array can be // sorted otherwise false static int sortedAfterSwap(int[] A, int[] B, int n) { int t = 0; for (int i = 0; i < n - 1; i++) { if (B[i] != 0) { if (A[i] != i + 1) t = A[i]; A[i] = A[i + 1]; A[i + 1] = t; } } // Check if array is sorted or not for (int i = 0; i < n; i++) { if (A[i] != i + 1) return 0; } return 1; } // Driver Code public static void main(String[] args) { int[] A = { 1, 2, 5, 3, 4, 6 }; int[] B = { 0, 1, 1, 1, 0 }; int n = A.length; if (sortedAfterSwap(A, B, n) == 0) System.out.println(\"A can be sorted\"); else System.out.println(\"A can not be sorted\"); }} // This code is contributed// by Mukul Singh.",
"e": 10227,
"s": 9132,
"text": null
},
{
"code": "# Python3 program to test whether array# can be sorted by swapping adjacent# elements using boolean array # Return true if array can be# sorted otherwise falsedef sortedAfterSwap(A,B,n): for i in range(0,n-1): if B[i]: if A[i]!=i+1: A[i], A[i+1] = A[i+1], A[i] # Check if array is sorted or not for i in range(n): if A[i]!=i+1: return False return True # Driver programif __name__=='__main__': A = [1, 2, 5, 3, 4, 6] B = [0, 1, 1, 1, 0] n =len(A) if (sortedAfterSwap(A, B, n)) : print(\"A can be sorted\") else : print(\"A can not be sorted\") # This code is contributed by# Shrikant13",
"e": 10902,
"s": 10227,
"text": null
},
{
"code": "// C# program to test whether array// can be sorted by swapping adjacent// elements using boolean arrayusing System; class GFG{ // Return true if array can be // sorted otherwise false static int sortedAfterSwap(int[] A, int[] B, int n) { int t = 0; for (int i = 0; i < n - 1; i++) { if (B[i] != 0) { if (A[i] != i + 1) t = A[i]; A[i] = A[i + 1]; A[i + 1] = t; } } // Check if array is sorted or not for (int i = 0; i < n; i++) { if (A[i] != i + 1) return 0; } return 1; } // Driver Code public static void Main() { int[] A = { 1, 2, 5, 3, 4, 6 }; int[] B = { 0, 1, 1, 1, 0 }; int n = A.Length; if (sortedAfterSwap(A, B, n) == 0) Console.WriteLine(\"A can be sorted\"); else Console.WriteLine(\"A can not be sorted\"); }} // This code is contributed// by Akanksha Rai",
"e": 11994,
"s": 10902,
"text": null
},
{
"code": "<?php// PHP program to test whether array// can be sorted by swapping adjacent// elements using boolean array // Return true if array can be// sorted otherwise falsefunction sortedAfterSwap(&$A, &$B, $n){ for ($i = 0; $i < $n - 1; $i++) { if ($B[$i]) { if ($A[$i] != $i + 1) { $t = $A[$i]; $A[$i] = $A[$i + 1]; $A[$i + 1] = $t; } } } // Check if array is sorted or not for ($i = 0; $i < $n; $i++) { if ($A[$i] != $i + 1) return false; } return true;} // Driver Code$A = array( 1, 2, 5, 3, 4, 6 );$B = array( 0, 1, 1, 1, 0 );$n = sizeof($A); if (sortedAfterSwap($A, $B, $n)) echo \"A can be sorted\\n\";else echo \"A can not be sorted\\n\"; // This code is contributed by ita_c?>",
"e": 12816,
"s": 11994,
"text": null
},
{
"code": "<script> // JavaScript program to test whether an array// can be sorted by swapping adjacent// elements using boolean array // Return true if array can be // sorted otherwise false function sortedAfterSwap(A,B,n) { let t = 0; for (let i = 0; i < n - 1; i++) { if (B[i] != 0) { if (A[i] != i + 1) t = A[i]; A[i] = A[i + 1]; A[i + 1] = t; } } // Check if array is sorted or not for (let i = 0; i < n; i++) { if (A[i] != i + 1) return 0; } return 1; } // Driver Code let A = [ 1, 2, 5, 3, 4, 6 ]; let B = [ 0, 1, 1, 1, 0 ]; let n = A.length; if (sortedAfterSwap(A, B, n) == 0) document.write(\"A can be sorted\"); else document.write(\"A can not be sorted\"); // This code is contributed// by sravan kumar Gottumukkala </script>",
"e": 13838,
"s": 12816,
"text": null
},
{
"code": null,
"e": 13855,
"s": 13838,
"text": "A can be sorted\n"
},
{
"code": null,
"e": 13898,
"s": 13855,
"text": "Time Complexity: O(n)Auxiliary Space: O(1)"
},
{
"code": null,
"e": 13905,
"s": 13898,
"text": "Sam007"
},
{
"code": null,
"e": 13911,
"s": 13905,
"text": "02DCE"
},
{
"code": null,
"e": 13923,
"s": 13911,
"text": "shrikanth13"
},
{
"code": null,
"e": 13929,
"s": 13923,
"text": "ukasp"
},
{
"code": null,
"e": 13942,
"s": 13929,
"text": "Akanksha_Rai"
},
{
"code": null,
"e": 13952,
"s": 13942,
"text": "Code_Mech"
},
{
"code": null,
"e": 13963,
"s": 13952,
"text": "nidhi_biet"
},
{
"code": null,
"e": 13971,
"s": 13963,
"text": "aut0b0t"
},
{
"code": null,
"e": 13981,
"s": 13971,
"text": "code_hunt"
},
{
"code": null,
"e": 13997,
"s": 13981,
"text": "sravankumar8128"
},
{
"code": null,
"e": 14008,
"s": 13997,
"text": "singhh3010"
},
{
"code": null,
"e": 14022,
"s": 14008,
"text": "binary-string"
},
{
"code": null,
"e": 14029,
"s": 14022,
"text": "Arrays"
},
{
"code": null,
"e": 14037,
"s": 14029,
"text": "Sorting"
},
{
"code": null,
"e": 14044,
"s": 14037,
"text": "Arrays"
},
{
"code": null,
"e": 14052,
"s": 14044,
"text": "Sorting"
}
] |
Java Program to Compute the Sum of Numbers in a List Using For-Loop | 22 Dec, 2020
Given a list of numbers, write a Java program to find the sum of all the elements in the List using for loop. For performing the given task, complete List traversal is necessary which makes the Time Complexity of the complete program to O(n), where n is the length of the List.
Example:
Input : List = [1, 2, 3]
Output: Sum = 6
Input : List = [5, 1, 2, 3]
Output: Sum = 11
Approach 1:
Create the sum variable of an integer data type.Initialize sum with 0.Start iterating the List using for-loop.During iteration add each element with the sum variable.After execution of the loop, print the sum.
Create the sum variable of an integer data type.
Initialize sum with 0.
Start iterating the List using for-loop.
During iteration add each element with the sum variable.
After execution of the loop, print the sum.
Below is the implementation of the above approach:
Java
// Java Program to Compute the Sum of// Numbers in a List Using For-Loopimport java.util.*;import java.io.*; class GFG { public static void main(String[] args) { List<Integer> list = new ArrayList<>(); list.add(5); list.add(6); list.add(7); list.add(10); list.add(9); int sum = 0; for (int i = 0; i < list.size(); i++) sum += list.get(i); System.out.println("sum-> " + sum); }}
sum-> 37
Time Complexity: O(n)
Approach 2:
Create the sum variable of an integer data type.Initialize sum with 0.Start iterating the List using enhanced for-loop.During iteration add each element with the sum variable.After execution of the loop, print the sum.
Create the sum variable of an integer data type.
Initialize sum with 0.
Start iterating the List using enhanced for-loop.
During iteration add each element with the sum variable.
After execution of the loop, print the sum.
Below is the implementation of the above approach:
Java
// Java Program to Compute the Sum of// Numbers in a List Using Enhanced For-Loopimport java.util.*;import java.io.*; class GFG { public static void main(String[] args) { List<Integer> list = new ArrayList<>(); list.add(5); list.add(6); list.add(7); list.add(10); list.add(9); int sum = 0; for (Integer i : list) sum += i; System.out.println("sum-> " + sum); }}
sum-> 37
Time Complexity: O(n)
java-list
Picked
Technical Scripter 2020
Java
Java Programs
Technical Scripter
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here. | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n22 Dec, 2020"
},
{
"code": null,
"e": 306,
"s": 28,
"text": "Given a list of numbers, write a Java program to find the sum of all the elements in the List using for loop. For performing the given task, complete List traversal is necessary which makes the Time Complexity of the complete program to O(n), where n is the length of the List."
},
{
"code": null,
"e": 315,
"s": 306,
"text": "Example:"
},
{
"code": null,
"e": 402,
"s": 315,
"text": "Input : List = [1, 2, 3]\nOutput: Sum = 6\n\nInput : List = [5, 1, 2, 3]\nOutput: Sum = 11"
},
{
"code": null,
"e": 414,
"s": 402,
"text": "Approach 1:"
},
{
"code": null,
"e": 624,
"s": 414,
"text": "Create the sum variable of an integer data type.Initialize sum with 0.Start iterating the List using for-loop.During iteration add each element with the sum variable.After execution of the loop, print the sum."
},
{
"code": null,
"e": 673,
"s": 624,
"text": "Create the sum variable of an integer data type."
},
{
"code": null,
"e": 696,
"s": 673,
"text": "Initialize sum with 0."
},
{
"code": null,
"e": 737,
"s": 696,
"text": "Start iterating the List using for-loop."
},
{
"code": null,
"e": 794,
"s": 737,
"text": "During iteration add each element with the sum variable."
},
{
"code": null,
"e": 838,
"s": 794,
"text": "After execution of the loop, print the sum."
},
{
"code": null,
"e": 889,
"s": 838,
"text": "Below is the implementation of the above approach:"
},
{
"code": null,
"e": 894,
"s": 889,
"text": "Java"
},
{
"code": "// Java Program to Compute the Sum of// Numbers in a List Using For-Loopimport java.util.*;import java.io.*; class GFG { public static void main(String[] args) { List<Integer> list = new ArrayList<>(); list.add(5); list.add(6); list.add(7); list.add(10); list.add(9); int sum = 0; for (int i = 0; i < list.size(); i++) sum += list.get(i); System.out.println(\"sum-> \" + sum); }}",
"e": 1358,
"s": 894,
"text": null
},
{
"code": null,
"e": 1367,
"s": 1358,
"text": "sum-> 37"
},
{
"code": null,
"e": 1389,
"s": 1367,
"text": "Time Complexity: O(n)"
},
{
"code": null,
"e": 1401,
"s": 1389,
"text": "Approach 2:"
},
{
"code": null,
"e": 1620,
"s": 1401,
"text": "Create the sum variable of an integer data type.Initialize sum with 0.Start iterating the List using enhanced for-loop.During iteration add each element with the sum variable.After execution of the loop, print the sum."
},
{
"code": null,
"e": 1669,
"s": 1620,
"text": "Create the sum variable of an integer data type."
},
{
"code": null,
"e": 1692,
"s": 1669,
"text": "Initialize sum with 0."
},
{
"code": null,
"e": 1742,
"s": 1692,
"text": "Start iterating the List using enhanced for-loop."
},
{
"code": null,
"e": 1799,
"s": 1742,
"text": "During iteration add each element with the sum variable."
},
{
"code": null,
"e": 1843,
"s": 1799,
"text": "After execution of the loop, print the sum."
},
{
"code": null,
"e": 1894,
"s": 1843,
"text": "Below is the implementation of the above approach:"
},
{
"code": null,
"e": 1899,
"s": 1894,
"text": "Java"
},
{
"code": "// Java Program to Compute the Sum of// Numbers in a List Using Enhanced For-Loopimport java.util.*;import java.io.*; class GFG { public static void main(String[] args) { List<Integer> list = new ArrayList<>(); list.add(5); list.add(6); list.add(7); list.add(10); list.add(9); int sum = 0; for (Integer i : list) sum += i; System.out.println(\"sum-> \" + sum); }}",
"e": 2347,
"s": 1899,
"text": null
},
{
"code": null,
"e": 2356,
"s": 2347,
"text": "sum-> 37"
},
{
"code": null,
"e": 2378,
"s": 2356,
"text": "Time Complexity: O(n)"
},
{
"code": null,
"e": 2388,
"s": 2378,
"text": "java-list"
},
{
"code": null,
"e": 2395,
"s": 2388,
"text": "Picked"
},
{
"code": null,
"e": 2419,
"s": 2395,
"text": "Technical Scripter 2020"
},
{
"code": null,
"e": 2424,
"s": 2419,
"text": "Java"
},
{
"code": null,
"e": 2438,
"s": 2424,
"text": "Java Programs"
},
{
"code": null,
"e": 2457,
"s": 2438,
"text": "Technical Scripter"
},
{
"code": null,
"e": 2462,
"s": 2457,
"text": "Java"
}
] |
Java Program to Convert String to Boolean | 16 Apr, 2022
To convert String to boolean in Java, you can use Boolean.parseBoolean(string). But if you want to convert String to Boolean object then use the method Boolean.valueOf(string) method.
Boolean data type consists of only two values i.e true and false. If the string is true (ignoring case), the Boolean equivalent will be true, else false.
Tip: In Java, only true and false are returned as boolean not 0 and 1.
Example:
Input: str = "true"
Output: true
Explanation: The boolean equivalent of true is true itself.
Input: str = "false"
Output: false
Explanation: The boolean equivalent of false is false itself.
Input: str = "yes"
Output: false
Explanation: The boolean equivalent of yes is false since the given value is not equal to true.
This is the most common method to convert String to boolean. This method is used to convert a given string to its primitive boolean value. If the given string contains the value true ( ignoring cases), then this method returns true. If the string contains any other value other than true, then the method returns false.
Syntax:
boolean boolValue = Boolean.parseBoolean(String str)
Example :
Java
// Java Program to Convert a String to Boolean// Using parseBoolean() Method of Boolean Class // Main classclass GFG { // Method 1 // To convert a string to its boolean value public static boolean stringToBoolean(String str) { // Converting a given string to its primitive // boolean value using parseBoolean() method boolean b1 = Boolean.parseBoolean(str); // Return primitive boolean value return b1; } // Method 2 // Main driver method public static void main(String args[]) { // Given String str String str = "yes"; // Printing the desired boolean value System.out.println(stringToBoolean(str)); // Given String str str = "true"; // Printing the desired boolean value System.out.println(stringToBoolean(str)); // Given String str str = "false"; // Printing the desired boolean value System.out.println(stringToBoolean(str)); }}
false
true
false
It is similar to the above method as discussed just a little difference lies as it returns a boolean object instead of a primitive boolean value.
Syntax:
boolean boolValue = Boolean.valueOf(String str)
Example:
Java
// Java Program to Convert a String to Boolean Object// Using valueOf() Method of Boolean Class // Main classclass GFG { // Method 1 // To convert a string to its boolean object public static boolean stringToBoolean(String str) { // Converting a given string // to its boolean object // using valueOf() method boolean b1 = Boolean.valueOf(str); // Returning boolean object return b1; } // Method 2 // Main driver method public static void main(String args[]) { // Given input string 1 String str = "yes"; // Printing the desired boolean System.out.println(stringToBoolean(str)); // Given input string 2 str = "true"; // Printing the desired boolean System.out.println(stringToBoolean(str)); // Given input string 3 str = "false"; // Printing the desired boolean System.out.println(stringToBoolean(str)); }}
false
true
false
nishkarshgandhi
solankimayank
Java-Boolean
Java-String-Programs
Java
Java Programs
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here. | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n16 Apr, 2022"
},
{
"code": null,
"e": 212,
"s": 28,
"text": "To convert String to boolean in Java, you can use Boolean.parseBoolean(string). But if you want to convert String to Boolean object then use the method Boolean.valueOf(string) method."
},
{
"code": null,
"e": 366,
"s": 212,
"text": "Boolean data type consists of only two values i.e true and false. If the string is true (ignoring case), the Boolean equivalent will be true, else false."
},
{
"code": null,
"e": 437,
"s": 366,
"text": "Tip: In Java, only true and false are returned as boolean not 0 and 1."
},
{
"code": null,
"e": 447,
"s": 437,
"text": "Example: "
},
{
"code": null,
"e": 540,
"s": 447,
"text": "Input: str = \"true\"\nOutput: true\nExplanation: The boolean equivalent of true is true itself."
},
{
"code": null,
"e": 639,
"s": 540,
"text": "Input: str = \"false\" \nOutput: false \nExplanation: The boolean equivalent of false is false itself."
},
{
"code": null,
"e": 769,
"s": 639,
"text": "Input: str = \"yes\" \nOutput: false\nExplanation: The boolean equivalent of yes is false since the given value is not equal to true."
},
{
"code": null,
"e": 1089,
"s": 769,
"text": "This is the most common method to convert String to boolean. This method is used to convert a given string to its primitive boolean value. If the given string contains the value true ( ignoring cases), then this method returns true. If the string contains any other value other than true, then the method returns false."
},
{
"code": null,
"e": 1097,
"s": 1089,
"text": "Syntax:"
},
{
"code": null,
"e": 1151,
"s": 1097,
"text": "boolean boolValue = Boolean.parseBoolean(String str) "
},
{
"code": null,
"e": 1161,
"s": 1151,
"text": "Example :"
},
{
"code": null,
"e": 1166,
"s": 1161,
"text": "Java"
},
{
"code": "// Java Program to Convert a String to Boolean// Using parseBoolean() Method of Boolean Class // Main classclass GFG { // Method 1 // To convert a string to its boolean value public static boolean stringToBoolean(String str) { // Converting a given string to its primitive // boolean value using parseBoolean() method boolean b1 = Boolean.parseBoolean(str); // Return primitive boolean value return b1; } // Method 2 // Main driver method public static void main(String args[]) { // Given String str String str = \"yes\"; // Printing the desired boolean value System.out.println(stringToBoolean(str)); // Given String str str = \"true\"; // Printing the desired boolean value System.out.println(stringToBoolean(str)); // Given String str str = \"false\"; // Printing the desired boolean value System.out.println(stringToBoolean(str)); }}",
"e": 2157,
"s": 1166,
"text": null
},
{
"code": null,
"e": 2174,
"s": 2157,
"text": "false\ntrue\nfalse"
},
{
"code": null,
"e": 2320,
"s": 2174,
"text": "It is similar to the above method as discussed just a little difference lies as it returns a boolean object instead of a primitive boolean value."
},
{
"code": null,
"e": 2329,
"s": 2320,
"text": "Syntax: "
},
{
"code": null,
"e": 2378,
"s": 2329,
"text": "boolean boolValue = Boolean.valueOf(String str) "
},
{
"code": null,
"e": 2387,
"s": 2378,
"text": "Example:"
},
{
"code": null,
"e": 2392,
"s": 2387,
"text": "Java"
},
{
"code": "// Java Program to Convert a String to Boolean Object// Using valueOf() Method of Boolean Class // Main classclass GFG { // Method 1 // To convert a string to its boolean object public static boolean stringToBoolean(String str) { // Converting a given string // to its boolean object // using valueOf() method boolean b1 = Boolean.valueOf(str); // Returning boolean object return b1; } // Method 2 // Main driver method public static void main(String args[]) { // Given input string 1 String str = \"yes\"; // Printing the desired boolean System.out.println(stringToBoolean(str)); // Given input string 2 str = \"true\"; // Printing the desired boolean System.out.println(stringToBoolean(str)); // Given input string 3 str = \"false\"; // Printing the desired boolean System.out.println(stringToBoolean(str)); }}",
"e": 3364,
"s": 2392,
"text": null
},
{
"code": null,
"e": 3381,
"s": 3364,
"text": "false\ntrue\nfalse"
},
{
"code": null,
"e": 3397,
"s": 3381,
"text": "nishkarshgandhi"
},
{
"code": null,
"e": 3411,
"s": 3397,
"text": "solankimayank"
},
{
"code": null,
"e": 3424,
"s": 3411,
"text": "Java-Boolean"
},
{
"code": null,
"e": 3445,
"s": 3424,
"text": "Java-String-Programs"
},
{
"code": null,
"e": 3450,
"s": 3445,
"text": "Java"
},
{
"code": null,
"e": 3464,
"s": 3450,
"text": "Java Programs"
},
{
"code": null,
"e": 3469,
"s": 3464,
"text": "Java"
}
] |
Python | Categorizing input Data in Lists | 10 Mar, 2022
Lists in Python are linear containers used for storing data of various Data Types. The ability to store a variety of data is what makes Lists a very unique and vital Data Structure in Python. Once created, lists can be modified further depending on one’s needs. Hence, they are ‘mutable.’Lists, when created and by defining the values in the code-section, generates an output similar to this: Code :
Python3
List =['GeeksForGeeks', 'VenD', 5, 9.2]print('\n List: ', List)
Output:
List: ['GeeksForGeeks', 'VenD', 5, 9.2]
In the above picture, the defined list is a combination of integer and string values. The interpreter implicitly interprets ‘GeeksForGeeks’ and ‘VenD’ as string values whereas 5 and 9.2 are interpreted as integer and float values respectively. We can perform the usual arithmetic operations on integer and float values as follows. Code :
Python3
# Usual Arithmetic Operations on 5 and 9.2:List =['GeeksForGeeks', 'VenD', 5, 9.2]print('\n List[2]+2, Answer: ', end ='')print(List[List.index(5)]+2) print('\n\n List[3]+8.2, Answer: ', end ='')print(List[List.index(9.2)]+8.2)
Output:
List[2]+2, Answer: 7
List[3]+8.2, Answer: 17.4
Also, the string-specific operations like string concatenation can be performed on the respective strings: Code :
Python3
# String Concatenation Operation# List: ['GeeksForGeeks', 'VenD', 5, 9.2]# Concatenating List[0] and List[1]List = ['GeeksForGeeks', 'VenD', 5, 9.2]print(List[0]+' '+List[1])
However, since we know that lists contain items of various data types those which might be of type: string, integer, float, tuple, dictionaries, or maybe even list themselves (a list of lists), the same is not valid if you are generating a list as a result of user input. For instance, consider the example below: Code :
Python3
# All Resultant Elements of List2 will be of string type list2 =[] # This is the list which will contain elements as an input from the user element_count = int(input('\n Enter Number of Elements you wish to enter: ')) for i in range(element_count): element = input(f'\n Enter Element {i + 1} : ') list2.append(element) print("\n List 2 : ", list2)
Output:
Enter Number of Elements you wish to enter: 4
Enter Element 1 : GeeksForGeeks
Enter Element 2 : VenD
Enter Element 3 : 5
Enter Element 4 : 9.2
List 2 : ['GeeksForGeeks', 'VenD', '5', '9.2']
You may notice that List2 generated as a result of User Input, now contains values of string data-type only. Also, the numerical elements have now lost the ability to undergo arithmetic operations since they are of string data-type. This behaviour straightaway contradicts the versatile behavior of Lists. It becomes necessary for us as programmers to process the user data and store it in the appropriate format so that operations and manipulations on the target data set become efficient. In this approach, we shall distinguish data obtained from the user into three sections, namely integer, string, and float. For this, we use a small code to carry out the respective typecasting operations.A technique to Overcome the proposed Limitation:
Code :
Python3
import re def checkInt(string): string_to_integer = re.compile(r'\d+') if len(string_to_integer.findall(string)) != 0: if len(string_to_integer.findall(string)[0])== len(string): return 1 else: return 0 else: return 0 def checkFloat(string): string_to_float = re.compile(r'\d*.\d*') if len(string_to_float.findall(string)) != 0: if len(string_to_float.findall(string)[0])== len(string): return 1 else: return 0 else: return 0 List2 =[]element_count = int(input('\n Enter number of elements : ')) for i in range(element_count): input_element = input(f'\n Enter Element {i + 1}: ') if checkInt(input_element): input_element = int(input_element) List2.append(input_element) elif checkFloat(input_element): input_element = float(input_element) List2.append(input_element) else: List2.append(input_element) print(List2)
Output:
Enter number of elements : 4
Enter Element 1: GeeksForGeeks
Enter Element 2: VenD
Enter Element 3: 5
Enter Element 4: 9.2
['GeeksForGeeks', 'VenD', 5, 9.2]
The above technique is essentially an algorithm which uses the Regular Expression library along with an algorithm to analyze the data-types of elements being inserted. After successfully analyzing the pattern of data, we then proceed to perform the type conversion.For example, consider the following cases:
Case1: All values in the string are numeric. The user input is 7834, the Regular Expression function analyzes the given data and identifies that all values are digits between 0 to 9 hence the string ‘7834’ is typecasted to the equivalent integer value and then appended to the list as an integer.Expression Used for Integer identification : r’\d+’
Case1: All values in the string are numeric. The user input is 7834, the Regular Expression function analyzes the given data and identifies that all values are digits between 0 to 9 hence the string ‘7834’ is typecasted to the equivalent integer value and then appended to the list as an integer.Expression Used for Integer identification : r’\d+’
Case2: The String expression contains elements which represent a floating point number. A floating point value is identified over a pattern of digits preceding or succeeding a full stop(‘.’). Ex: 567., .056, 6.7, etc. Expression used for float value identification: r’\d*.\d*’Case3: String Input contains characters, special characters and numerical values as well. In this case, the data element is generalized as a string value. No special Regular Expression needed since the given expression will return false when being categorised as Integer or Float Values. Ex: ‘155B, Baker Street ! ‘, ’12B72C_?’, ‘I am Agent 007’, ‘_GeeksForGeeks_’, etc.
Case2: The String expression contains elements which represent a floating point number. A floating point value is identified over a pattern of digits preceding or succeeding a full stop(‘.’). Ex: 567., .056, 6.7, etc. Expression used for float value identification: r’\d*.\d*’
Case3: String Input contains characters, special characters and numerical values as well. In this case, the data element is generalized as a string value. No special Regular Expression needed since the given expression will return false when being categorised as Integer or Float Values. Ex: ‘155B, Baker Street ! ‘, ’12B72C_?’, ‘I am Agent 007’, ‘_GeeksForGeeks_’, etc.
Conclusion: This method, however, is just a small prototype of typecasting values and processing raw data before storing it in the list. It definitely offers a fruitful outcome which overcomes the proposed limitations on list inputs. Further, with the advanced applications of regular expressions and some improvements in the algorithm, more forms of data such as tuples, dictionaries, etc. can be analysed and stored accordingly.
Advantages of the Dynamic TypeCasting:
Since data is stored in the appropriate format, various ‘type-specific’ operations can be performed on it. Ex: Concatenation in case of strings, Addition, Subtraction, Multiplication in case of numerical values and various other operations on the respective data types.
Typecasting phase takes place while storing the data. Hence, the programmer does not have to worry about Type Errors which occur while performing operations on the data set.
Limitations of Dynamic TypeCasting:
Some data elements which do not necessarily require typecasting undergo the process, resulting in unnecessary computing.
Multiple condition-checks and function calls result in memory wastage when each time a new element is inserted.
The flexibility of processing numerous types of data might require several new additions to the existing code as per the developer’s needs.
rkbhola5
Python
Python Programs
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here. | [
{
"code": null,
"e": 54,
"s": 26,
"text": "\n10 Mar, 2022"
},
{
"code": null,
"e": 456,
"s": 54,
"text": "Lists in Python are linear containers used for storing data of various Data Types. The ability to store a variety of data is what makes Lists a very unique and vital Data Structure in Python. Once created, lists can be modified further depending on one’s needs. Hence, they are ‘mutable.’Lists, when created and by defining the values in the code-section, generates an output similar to this: Code : "
},
{
"code": null,
"e": 464,
"s": 456,
"text": "Python3"
},
{
"code": "List =['GeeksForGeeks', 'VenD', 5, 9.2]print('\\n List: ', List)",
"e": 528,
"s": 464,
"text": null
},
{
"code": null,
"e": 538,
"s": 528,
"text": "Output: "
},
{
"code": null,
"e": 580,
"s": 538,
"text": " List: ['GeeksForGeeks', 'VenD', 5, 9.2]"
},
{
"code": null,
"e": 920,
"s": 580,
"text": "In the above picture, the defined list is a combination of integer and string values. The interpreter implicitly interprets ‘GeeksForGeeks’ and ‘VenD’ as string values whereas 5 and 9.2 are interpreted as integer and float values respectively. We can perform the usual arithmetic operations on integer and float values as follows. Code : "
},
{
"code": null,
"e": 928,
"s": 920,
"text": "Python3"
},
{
"code": "# Usual Arithmetic Operations on 5 and 9.2:List =['GeeksForGeeks', 'VenD', 5, 9.2]print('\\n List[2]+2, Answer: ', end ='')print(List[List.index(5)]+2) print('\\n\\n List[3]+8.2, Answer: ', end ='')print(List[List.index(9.2)]+8.2)",
"e": 1156,
"s": 928,
"text": null
},
{
"code": null,
"e": 1166,
"s": 1156,
"text": "Output: "
},
{
"code": null,
"e": 1215,
"s": 1166,
"text": " List[2]+2, Answer: 7\n List[3]+8.2, Answer: 17.4"
},
{
"code": null,
"e": 1331,
"s": 1215,
"text": "Also, the string-specific operations like string concatenation can be performed on the respective strings: Code : "
},
{
"code": null,
"e": 1339,
"s": 1331,
"text": "Python3"
},
{
"code": "# String Concatenation Operation# List: ['GeeksForGeeks', 'VenD', 5, 9.2]# Concatenating List[0] and List[1]List = ['GeeksForGeeks', 'VenD', 5, 9.2]print(List[0]+' '+List[1])",
"e": 1516,
"s": 1339,
"text": null
},
{
"code": null,
"e": 1839,
"s": 1516,
"text": "However, since we know that lists contain items of various data types those which might be of type: string, integer, float, tuple, dictionaries, or maybe even list themselves (a list of lists), the same is not valid if you are generating a list as a result of user input. For instance, consider the example below: Code : "
},
{
"code": null,
"e": 1847,
"s": 1839,
"text": "Python3"
},
{
"code": "# All Resultant Elements of List2 will be of string type list2 =[] # This is the list which will contain elements as an input from the user element_count = int(input('\\n Enter Number of Elements you wish to enter: ')) for i in range(element_count): element = input(f'\\n Enter Element {i + 1} : ') list2.append(element) print(\"\\n List 2 : \", list2)",
"e": 2206,
"s": 1847,
"text": null
},
{
"code": null,
"e": 2216,
"s": 2206,
"text": "Output: "
},
{
"code": null,
"e": 2418,
"s": 2216,
"text": " Enter Number of Elements you wish to enter: 4\n\n Enter Element 1 : GeeksForGeeks\n\n Enter Element 2 : VenD\n\n Enter Element 3 : 5\n\n Enter Element 4 : 9.2\n\n List 2 : ['GeeksForGeeks', 'VenD', '5', '9.2']"
},
{
"code": null,
"e": 3163,
"s": 2418,
"text": "You may notice that List2 generated as a result of User Input, now contains values of string data-type only. Also, the numerical elements have now lost the ability to undergo arithmetic operations since they are of string data-type. This behaviour straightaway contradicts the versatile behavior of Lists. It becomes necessary for us as programmers to process the user data and store it in the appropriate format so that operations and manipulations on the target data set become efficient. In this approach, we shall distinguish data obtained from the user into three sections, namely integer, string, and float. For this, we use a small code to carry out the respective typecasting operations.A technique to Overcome the proposed Limitation: "
},
{
"code": null,
"e": 3172,
"s": 3163,
"text": "Code : "
},
{
"code": null,
"e": 3180,
"s": 3172,
"text": "Python3"
},
{
"code": "import re def checkInt(string): string_to_integer = re.compile(r'\\d+') if len(string_to_integer.findall(string)) != 0: if len(string_to_integer.findall(string)[0])== len(string): return 1 else: return 0 else: return 0 def checkFloat(string): string_to_float = re.compile(r'\\d*.\\d*') if len(string_to_float.findall(string)) != 0: if len(string_to_float.findall(string)[0])== len(string): return 1 else: return 0 else: return 0 List2 =[]element_count = int(input('\\n Enter number of elements : ')) for i in range(element_count): input_element = input(f'\\n Enter Element {i + 1}: ') if checkInt(input_element): input_element = int(input_element) List2.append(input_element) elif checkFloat(input_element): input_element = float(input_element) List2.append(input_element) else: List2.append(input_element) print(List2)",
"e": 4181,
"s": 3180,
"text": null
},
{
"code": null,
"e": 4191,
"s": 4181,
"text": "Output: "
},
{
"code": null,
"e": 4356,
"s": 4191,
"text": " Enter number of elements : 4\n\n Enter Element 1: GeeksForGeeks\n\n Enter Element 2: VenD\n\n Enter Element 3: 5\n\n Enter Element 4: 9.2\n['GeeksForGeeks', 'VenD', 5, 9.2]"
},
{
"code": null,
"e": 4666,
"s": 4356,
"text": "The above technique is essentially an algorithm which uses the Regular Expression library along with an algorithm to analyze the data-types of elements being inserted. After successfully analyzing the pattern of data, we then proceed to perform the type conversion.For example, consider the following cases: "
},
{
"code": null,
"e": 5015,
"s": 4666,
"text": "Case1: All values in the string are numeric. The user input is 7834, the Regular Expression function analyzes the given data and identifies that all values are digits between 0 to 9 hence the string ‘7834’ is typecasted to the equivalent integer value and then appended to the list as an integer.Expression Used for Integer identification : r’\\d+’ "
},
{
"code": null,
"e": 5364,
"s": 5015,
"text": "Case1: All values in the string are numeric. The user input is 7834, the Regular Expression function analyzes the given data and identifies that all values are digits between 0 to 9 hence the string ‘7834’ is typecasted to the equivalent integer value and then appended to the list as an integer.Expression Used for Integer identification : r’\\d+’ "
},
{
"code": null,
"e": 6011,
"s": 5364,
"text": "Case2: The String expression contains elements which represent a floating point number. A floating point value is identified over a pattern of digits preceding or succeeding a full stop(‘.’). Ex: 567., .056, 6.7, etc. Expression used for float value identification: r’\\d*.\\d*’Case3: String Input contains characters, special characters and numerical values as well. In this case, the data element is generalized as a string value. No special Regular Expression needed since the given expression will return false when being categorised as Integer or Float Values. Ex: ‘155B, Baker Street ! ‘, ’12B72C_?’, ‘I am Agent 007’, ‘_GeeksForGeeks_’, etc."
},
{
"code": null,
"e": 6288,
"s": 6011,
"text": "Case2: The String expression contains elements which represent a floating point number. A floating point value is identified over a pattern of digits preceding or succeeding a full stop(‘.’). Ex: 567., .056, 6.7, etc. Expression used for float value identification: r’\\d*.\\d*’"
},
{
"code": null,
"e": 6659,
"s": 6288,
"text": "Case3: String Input contains characters, special characters and numerical values as well. In this case, the data element is generalized as a string value. No special Regular Expression needed since the given expression will return false when being categorised as Integer or Float Values. Ex: ‘155B, Baker Street ! ‘, ’12B72C_?’, ‘I am Agent 007’, ‘_GeeksForGeeks_’, etc."
},
{
"code": null,
"e": 7092,
"s": 6659,
"text": "Conclusion: This method, however, is just a small prototype of typecasting values and processing raw data before storing it in the list. It definitely offers a fruitful outcome which overcomes the proposed limitations on list inputs. Further, with the advanced applications of regular expressions and some improvements in the algorithm, more forms of data such as tuples, dictionaries, etc. can be analysed and stored accordingly. "
},
{
"code": null,
"e": 7133,
"s": 7092,
"text": "Advantages of the Dynamic TypeCasting: "
},
{
"code": null,
"e": 7403,
"s": 7133,
"text": "Since data is stored in the appropriate format, various ‘type-specific’ operations can be performed on it. Ex: Concatenation in case of strings, Addition, Subtraction, Multiplication in case of numerical values and various other operations on the respective data types."
},
{
"code": null,
"e": 7577,
"s": 7403,
"text": "Typecasting phase takes place while storing the data. Hence, the programmer does not have to worry about Type Errors which occur while performing operations on the data set."
},
{
"code": null,
"e": 7615,
"s": 7577,
"text": "Limitations of Dynamic TypeCasting: "
},
{
"code": null,
"e": 7736,
"s": 7615,
"text": "Some data elements which do not necessarily require typecasting undergo the process, resulting in unnecessary computing."
},
{
"code": null,
"e": 7848,
"s": 7736,
"text": "Multiple condition-checks and function calls result in memory wastage when each time a new element is inserted."
},
{
"code": null,
"e": 7988,
"s": 7848,
"text": "The flexibility of processing numerous types of data might require several new additions to the existing code as per the developer’s needs."
},
{
"code": null,
"e": 7999,
"s": 7990,
"text": "rkbhola5"
},
{
"code": null,
"e": 8006,
"s": 7999,
"text": "Python"
},
{
"code": null,
"e": 8022,
"s": 8006,
"text": "Python Programs"
}
] |
How to Drop Columns with NaN Values in Pandas DataFrame? | 24 Oct, 2020
Nan(Not a number) is a floating-point value which can’t be converted into other data type expect to float. In data analysis, Nan is the unnecessary value which must be removed in order to analyze the data set properly. In this article, we will discuss how to remove/drop columns having Nan values in the pandas Dataframe. We have a function known as Pandas.DataFrame.dropna() to drop columns having Nan values.
Syntax: DataFrame.dropna(axis=0, how=’any’, thresh=None, subset=None, inplace=False)
Example 1: Dropping all Columns with any NaN/NaT Values.
Python3
# Importing librariesimport pandas as pdimport numpy as np # Creating a dictionarydit = {'August': [pd.NaT, 25, 34, np.nan, 1.1, 10], 'September': [4.8, pd.NaT, 68, 9.25, np.nan, 0.9], 'October': [78, 5.8, 8.52, 12, 1.6, 11], } # Converting it to data framedf = pd.DataFrame(data=dit) # DataFramedf
Output:
Python3
# Dropping the columns having NaN/NaT valuesdf = df.dropna(axis=1) df
Output:
In the above example, we drop the columns ‘August’ and ‘September’ as they hold Nan and NaT values.
Example 2: Dropping all Columns with any NaN/NaT Values and then reset the indices using the df.reset_index() function.
Python3
# Importing librariesimport pandas as pdimport numpy as np # Initializing the nested list with Data setplayer_list = [['M.S.Dhoni', 36, 75, 5428000], [np.nan, 36, 74, np.nan], ['V.Kholi', 31, 70, 8428000], ['S.Smith', 34, 80, 4428000], [pd.NaT, 39, 100, np.nan], [np.nan, 33, 90.5, 7028000], ['K.Peterson', 42, 85, pd.NaT]] # creating a pandas dataframedf = pd.DataFrame(player_list, columns=['Name', 'Age', 'Weight', 'Salary']) df
Output:
Python3
# Dropping the columns having NaN/NaT valuesdf = df.dropna(axis=1) # Resetting the indices using df.reset_index()df = df.reset_index(drop=True) df
Output:
In the above example, we drop the columns ‘Name’ and ‘Salary’ and then reset the indices.
Example 3:
Python3
# Importing librariesimport pandas as pdimport numpy as np # creating and initializing a nested listage_list = [[np.nan, 1952, 8425333, np.nan, 28.35], ['Australia', 1957, 9712569, 'Oceania', 24.26], ['Brazil', 1962, 76039390, np.nan, 30.24], [pd.NaT, 1957, 637408000, 'Asia', 28.32], ['France', 1957, 44310863, pd.NaT, 25.21], ['India', 1952, 3.72e+08, pd.NaT, 27.36], ['United States', 1957, 171984000, 'Americas', 28.98]] # creating a pandas dataframedf = pd.DataFrame(age_list, columns=[ 'Country', 'Year', 'Population', 'Continent', 'lifeExp']) df
Output:
Python3
# Dropping the columns having NaN/NaT valuesdf = df.dropna(axis=1) # Resetting the indices using df.reset_index()df = df.reset_index(drop=True) df
Output:
In the above example, we drop the columns ‘Country’ and ‘Continent’ as they hold Nan and NaT values.
Example 4: Dropping all Columns with any NaN/NaT Values under a certain label index using ‘subset‘ attribute.
Python3
# Importing libraries import pandas as pd import numpy as np # Creating a dictionary dit = {'August': [10, np.nan, 34, 4.85, 71.2, 1.1], 'September': [np.nan, 54, 68, 9.25, pd.NaT, 0.9], 'October': [np.nan, 5.8, 8.52, np.nan, 1.6, 11], 'November': [pd.NaT, 5.8, 50, 8.9, 77, pd.NaT] } # Converting it to data framedf = pd.DataFrame(data=dit) # data framedf
Output:
Python3
# Dropping the columns having NaN/NaT values# under certain label index using 'subset' attributedf = df.dropna(subset=[3], axis=1) # Resetting the indices using df.reset_index()df = df.reset_index(drop=True) df
Output:
In the above example, we drop the column having index 3 i.e ‘October’ using subset attribute.
Python pandas-dataFrame
Python Pandas-exercise
Python-pandas
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here. | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n24 Oct, 2020"
},
{
"code": null,
"e": 439,
"s": 28,
"text": "Nan(Not a number) is a floating-point value which can’t be converted into other data type expect to float. In data analysis, Nan is the unnecessary value which must be removed in order to analyze the data set properly. In this article, we will discuss how to remove/drop columns having Nan values in the pandas Dataframe. We have a function known as Pandas.DataFrame.dropna() to drop columns having Nan values."
},
{
"code": null,
"e": 524,
"s": 439,
"text": "Syntax: DataFrame.dropna(axis=0, how=’any’, thresh=None, subset=None, inplace=False)"
},
{
"code": null,
"e": 581,
"s": 524,
"text": "Example 1: Dropping all Columns with any NaN/NaT Values."
},
{
"code": null,
"e": 589,
"s": 581,
"text": "Python3"
},
{
"code": "# Importing librariesimport pandas as pdimport numpy as np # Creating a dictionarydit = {'August': [pd.NaT, 25, 34, np.nan, 1.1, 10], 'September': [4.8, pd.NaT, 68, 9.25, np.nan, 0.9], 'October': [78, 5.8, 8.52, 12, 1.6, 11], } # Converting it to data framedf = pd.DataFrame(data=dit) # DataFramedf",
"e": 903,
"s": 589,
"text": null
},
{
"code": null,
"e": 911,
"s": 903,
"text": "Output:"
},
{
"code": null,
"e": 919,
"s": 911,
"text": "Python3"
},
{
"code": "# Dropping the columns having NaN/NaT valuesdf = df.dropna(axis=1) df",
"e": 990,
"s": 919,
"text": null
},
{
"code": null,
"e": 998,
"s": 990,
"text": "Output:"
},
{
"code": null,
"e": 1098,
"s": 998,
"text": "In the above example, we drop the columns ‘August’ and ‘September’ as they hold Nan and NaT values."
},
{
"code": null,
"e": 1218,
"s": 1098,
"text": "Example 2: Dropping all Columns with any NaN/NaT Values and then reset the indices using the df.reset_index() function."
},
{
"code": null,
"e": 1226,
"s": 1218,
"text": "Python3"
},
{
"code": "# Importing librariesimport pandas as pdimport numpy as np # Initializing the nested list with Data setplayer_list = [['M.S.Dhoni', 36, 75, 5428000], [np.nan, 36, 74, np.nan], ['V.Kholi', 31, 70, 8428000], ['S.Smith', 34, 80, 4428000], [pd.NaT, 39, 100, np.nan], [np.nan, 33, 90.5, 7028000], ['K.Peterson', 42, 85, pd.NaT]] # creating a pandas dataframedf = pd.DataFrame(player_list, columns=['Name', 'Age', 'Weight', 'Salary']) df",
"e": 1787,
"s": 1226,
"text": null
},
{
"code": null,
"e": 1795,
"s": 1787,
"text": "Output:"
},
{
"code": null,
"e": 1803,
"s": 1795,
"text": "Python3"
},
{
"code": "# Dropping the columns having NaN/NaT valuesdf = df.dropna(axis=1) # Resetting the indices using df.reset_index()df = df.reset_index(drop=True) df",
"e": 1952,
"s": 1803,
"text": null
},
{
"code": null,
"e": 1960,
"s": 1952,
"text": "Output:"
},
{
"code": null,
"e": 2050,
"s": 1960,
"text": "In the above example, we drop the columns ‘Name’ and ‘Salary’ and then reset the indices."
},
{
"code": null,
"e": 2062,
"s": 2050,
"text": "Example 3: "
},
{
"code": null,
"e": 2070,
"s": 2062,
"text": "Python3"
},
{
"code": "# Importing librariesimport pandas as pdimport numpy as np # creating and initializing a nested listage_list = [[np.nan, 1952, 8425333, np.nan, 28.35], ['Australia', 1957, 9712569, 'Oceania', 24.26], ['Brazil', 1962, 76039390, np.nan, 30.24], [pd.NaT, 1957, 637408000, 'Asia', 28.32], ['France', 1957, 44310863, pd.NaT, 25.21], ['India', 1952, 3.72e+08, pd.NaT, 27.36], ['United States', 1957, 171984000, 'Americas', 28.98]] # creating a pandas dataframedf = pd.DataFrame(age_list, columns=[ 'Country', 'Year', 'Population', 'Continent', 'lifeExp']) df",
"e": 2712,
"s": 2070,
"text": null
},
{
"code": null,
"e": 2720,
"s": 2712,
"text": "Output:"
},
{
"code": null,
"e": 2728,
"s": 2720,
"text": "Python3"
},
{
"code": "# Dropping the columns having NaN/NaT valuesdf = df.dropna(axis=1) # Resetting the indices using df.reset_index()df = df.reset_index(drop=True) df",
"e": 2877,
"s": 2728,
"text": null
},
{
"code": null,
"e": 2885,
"s": 2877,
"text": "Output:"
},
{
"code": null,
"e": 2986,
"s": 2885,
"text": "In the above example, we drop the columns ‘Country’ and ‘Continent’ as they hold Nan and NaT values."
},
{
"code": null,
"e": 3096,
"s": 2986,
"text": "Example 4: Dropping all Columns with any NaN/NaT Values under a certain label index using ‘subset‘ attribute."
},
{
"code": null,
"e": 3104,
"s": 3096,
"text": "Python3"
},
{
"code": "# Importing libraries import pandas as pd import numpy as np # Creating a dictionary dit = {'August': [10, np.nan, 34, 4.85, 71.2, 1.1], 'September': [np.nan, 54, 68, 9.25, pd.NaT, 0.9], 'October': [np.nan, 5.8, 8.52, np.nan, 1.6, 11], 'November': [pd.NaT, 5.8, 50, 8.9, 77, pd.NaT] } # Converting it to data framedf = pd.DataFrame(data=dit) # data framedf",
"e": 3486,
"s": 3104,
"text": null
},
{
"code": null,
"e": 3494,
"s": 3486,
"text": "Output:"
},
{
"code": null,
"e": 3502,
"s": 3494,
"text": "Python3"
},
{
"code": "# Dropping the columns having NaN/NaT values# under certain label index using 'subset' attributedf = df.dropna(subset=[3], axis=1) # Resetting the indices using df.reset_index()df = df.reset_index(drop=True) df",
"e": 3716,
"s": 3502,
"text": null
},
{
"code": null,
"e": 3724,
"s": 3716,
"text": "Output:"
},
{
"code": null,
"e": 3819,
"s": 3724,
"text": "In the above example, we drop the column having index 3 i.e ‘October’ using subset attribute. "
},
{
"code": null,
"e": 3843,
"s": 3819,
"text": "Python pandas-dataFrame"
},
{
"code": null,
"e": 3866,
"s": 3843,
"text": "Python Pandas-exercise"
},
{
"code": null,
"e": 3880,
"s": 3866,
"text": "Python-pandas"
},
{
"code": null,
"e": 3887,
"s": 3880,
"text": "Python"
}
] |
MongoDB – Multikey Indexes | 17 Feb, 2021
Indexes are special data structures that store some information related to the documents such that it becomes easy for MongoDB to find the right data file. They also store the value of a specific field or set of fields, ordered by the value of the field as specified in the index. MongoDB allows to index a field that holds an array value by creating an index key for each element in the array, such type of indexing is called Multikey indexes. It supports efficient queries against array fields. It can be constructed over arrays that hold both scalar values(like strings, numbers, etc) and nested documents.
In MongoDB, we can create Multikey indexes using the createIndex() method
Syntax:
db.Collection_name.createIndex({filed_name: 1/ -1})
Important Points:
If an indexed field is an array, then MongoDB will automatically create a multikey index for that field.
You are not allowed to specify a multikey index as the sherd key index.
In MongoDB, hashed indexes are not multikey index.
The multikey index cannot support the $expr operator.
In MongoDB, if a filter query specifies the exact match for an array as a whole, then MongoDB scans the multikey index to look for the first element of the quarry array. After scanning the multikey index to look for the first element of the quarry array, MongoDB retrieves those documents that contain the first element and then filter them for the document whose array matches the given query. Rather than scanning the multikey index to find the whole array.
Examples:
In the following example, we are working with:
Database: gfg
Collections: student
Document: Three documents contains the details of the students
Creating a multikey index:
Now we create multi-index with the help of createIndex() method on the field language:
db.student.createIndex({language:1})
After indexing, we will check the index using the getIndexes() method:
Indexing an array with the embedded document:
You are allowed to create a multikey index on an array field that contains nested documents/objects.
db.student.createIndex({"details.age":1, "details.branch":1})
Here, we create the multikey index on the “details.age” and “details.branch” fields.
After indexing, we will check the index using the getIndexes() method:
When you are creating a compound multikey index then each indexed document must contain at most one indexed field whose value is an array.
You are not allowed to create a compound multikey index if more than one to be indexed field of a document is an array.
When the compound multikey index already exists, then you are not allowed to insert a document that will break the restrictions.
When a field is an array of documents, you are allowed to index an embedded document to create a compound index but at most one indexed field can be an array.
MongoDB
Picked
MongoDB
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to connect MongoDB with ReactJS ?
MongoDB - limit() Method
Create user and add role in MongoDB
MongoDB - Compound Indexes
MongoDB - sort() Method
MongoDB - FindOne() Method
MongoDB updateOne() Method - db.Collection.updateOne()
MongoDB updateMany() Method - db.Collection.updateMany()
Indexing in MongoDB
Spring Boot - CRUD Operations using MongoDB | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n17 Feb, 2021"
},
{
"code": null,
"e": 638,
"s": 28,
"text": "Indexes are special data structures that store some information related to the documents such that it becomes easy for MongoDB to find the right data file. They also store the value of a specific field or set of fields, ordered by the value of the field as specified in the index. MongoDB allows to index a field that holds an array value by creating an index key for each element in the array, such type of indexing is called Multikey indexes. It supports efficient queries against array fields. It can be constructed over arrays that hold both scalar values(like strings, numbers, etc) and nested documents."
},
{
"code": null,
"e": 712,
"s": 638,
"text": "In MongoDB, we can create Multikey indexes using the createIndex() method"
},
{
"code": null,
"e": 720,
"s": 712,
"text": "Syntax:"
},
{
"code": null,
"e": 772,
"s": 720,
"text": "db.Collection_name.createIndex({filed_name: 1/ -1})"
},
{
"code": null,
"e": 790,
"s": 772,
"text": "Important Points:"
},
{
"code": null,
"e": 895,
"s": 790,
"text": "If an indexed field is an array, then MongoDB will automatically create a multikey index for that field."
},
{
"code": null,
"e": 967,
"s": 895,
"text": "You are not allowed to specify a multikey index as the sherd key index."
},
{
"code": null,
"e": 1018,
"s": 967,
"text": "In MongoDB, hashed indexes are not multikey index."
},
{
"code": null,
"e": 1072,
"s": 1018,
"text": "The multikey index cannot support the $expr operator."
},
{
"code": null,
"e": 1532,
"s": 1072,
"text": "In MongoDB, if a filter query specifies the exact match for an array as a whole, then MongoDB scans the multikey index to look for the first element of the quarry array. After scanning the multikey index to look for the first element of the quarry array, MongoDB retrieves those documents that contain the first element and then filter them for the document whose array matches the given query. Rather than scanning the multikey index to find the whole array."
},
{
"code": null,
"e": 1542,
"s": 1532,
"text": "Examples:"
},
{
"code": null,
"e": 1589,
"s": 1542,
"text": "In the following example, we are working with:"
},
{
"code": null,
"e": 1603,
"s": 1589,
"text": "Database: gfg"
},
{
"code": null,
"e": 1624,
"s": 1603,
"text": "Collections: student"
},
{
"code": null,
"e": 1687,
"s": 1624,
"text": "Document: Three documents contains the details of the students"
},
{
"code": null,
"e": 1714,
"s": 1687,
"text": "Creating a multikey index:"
},
{
"code": null,
"e": 1801,
"s": 1714,
"text": "Now we create multi-index with the help of createIndex() method on the field language:"
},
{
"code": null,
"e": 1838,
"s": 1801,
"text": "db.student.createIndex({language:1})"
},
{
"code": null,
"e": 1909,
"s": 1838,
"text": "After indexing, we will check the index using the getIndexes() method:"
},
{
"code": null,
"e": 1955,
"s": 1909,
"text": "Indexing an array with the embedded document:"
},
{
"code": null,
"e": 2056,
"s": 1955,
"text": "You are allowed to create a multikey index on an array field that contains nested documents/objects."
},
{
"code": null,
"e": 2118,
"s": 2056,
"text": "db.student.createIndex({\"details.age\":1, \"details.branch\":1})"
},
{
"code": null,
"e": 2203,
"s": 2118,
"text": "Here, we create the multikey index on the “details.age” and “details.branch” fields."
},
{
"code": null,
"e": 2274,
"s": 2203,
"text": "After indexing, we will check the index using the getIndexes() method:"
},
{
"code": null,
"e": 2413,
"s": 2274,
"text": "When you are creating a compound multikey index then each indexed document must contain at most one indexed field whose value is an array."
},
{
"code": null,
"e": 2533,
"s": 2413,
"text": "You are not allowed to create a compound multikey index if more than one to be indexed field of a document is an array."
},
{
"code": null,
"e": 2662,
"s": 2533,
"text": "When the compound multikey index already exists, then you are not allowed to insert a document that will break the restrictions."
},
{
"code": null,
"e": 2821,
"s": 2662,
"text": "When a field is an array of documents, you are allowed to index an embedded document to create a compound index but at most one indexed field can be an array."
},
{
"code": null,
"e": 2829,
"s": 2821,
"text": "MongoDB"
},
{
"code": null,
"e": 2836,
"s": 2829,
"text": "Picked"
},
{
"code": null,
"e": 2844,
"s": 2836,
"text": "MongoDB"
},
{
"code": null,
"e": 2942,
"s": 2844,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 2980,
"s": 2942,
"text": "How to connect MongoDB with ReactJS ?"
},
{
"code": null,
"e": 3005,
"s": 2980,
"text": "MongoDB - limit() Method"
},
{
"code": null,
"e": 3041,
"s": 3005,
"text": "Create user and add role in MongoDB"
},
{
"code": null,
"e": 3068,
"s": 3041,
"text": "MongoDB - Compound Indexes"
},
{
"code": null,
"e": 3092,
"s": 3068,
"text": "MongoDB - sort() Method"
},
{
"code": null,
"e": 3119,
"s": 3092,
"text": "MongoDB - FindOne() Method"
},
{
"code": null,
"e": 3174,
"s": 3119,
"text": "MongoDB updateOne() Method - db.Collection.updateOne()"
},
{
"code": null,
"e": 3231,
"s": 3174,
"text": "MongoDB updateMany() Method - db.Collection.updateMany()"
},
{
"code": null,
"e": 3251,
"s": 3231,
"text": "Indexing in MongoDB"
}
] |
Measuring the Document Similarity in Python | 27 Feb, 2020
Document similarity, as the name suggests determines how similar are the two given documents. By “documents”, we mean a collection of strings. For example, an essay or a .txt file. Many organizations use this principle of document similarity to check plagiarism. It is also used by many exams conducting institutions to check if a student cheated from the other. Therefore, it is very important as well as interesting to know how all of this works.
Document similarity is calculated by calculating document distance. Document distance is a concept where words(documents) are treated as vectors and is calculated as the angle between two given document vectors. Document vectors are the frequency of occurrences of words in a given document. Let’s see an example:
Say that we are given two documents D1 and D2 as:
D1: “This is a geek”D2: “This was a geek thing”
The similar words in both these documents then become:
"This a geek"
If we make a 3-D representation of this as vectors by taking D1, D2 and similar words in 3 axis geometry, then we get:
Now if we take dot product of D1 and D2,
D1.D2 = "This"."This"+"is"."was"+"a"."a"+"geek"."geek"+"thing".0
D1.D2 = 1+0+1+1+0
D1.D2 = 3
Now that we know how to calculate the dot product of these documents, we can now calculate the angle between the document vectors:
cos d = D1.D2/|D1||D2|
Here d is the document distance. It’s value ranges from 0 degree to 90 degrees. Where 0 degree means the two documents are exactly identical and 90 degrees indicate that the two documents are very different.
Now that we know about document similarity and document distance, let’s look at a Python program to calculate the same:
Document similarity program :
Our algorithm to confirm document similarity will consist of three fundamental steps:
Split the documents in words.
Compute the word frequencies.
Calculate the dot product of the document vectors.
For the first step, we will first use the .read() method to open and read the content of the files. As we read the contents, we will split them into a list. Next, we will calculate the word frequency list of the read in the file. Therefore, the occurrence of each word is counted and the list is sorted alphabetically.
import mathimport stringimport sys # reading the text file# This functio will return a # list of the lines of text # in the file.def read_file(filename): try: with open(filename, 'r') as f: data = f.read() return data except IOError: print("Error opening or reading input file: ", filename) sys.exit() # splitting the text lines into words# translation table is a global variable# mapping upper case to lower case and# punctuation to spacestranslation_table = str.maketrans(string.punctuation+string.ascii_uppercase, " "*len(string.punctuation)+string.ascii_lowercase) # returns a list of the words# in the filedef get_words_from_line_list(text): text = text.translate(translation_table) word_list = text.split() return word_list
Now that we have the word list, we will now calculate the frequency of occurrences of the words.
# counts frequency of each word# returns a dictionary which maps# the words to their frequency.def count_frequency(word_list): D = {} for new_word in word_list: if new_word in D: D[new_word] = D[new_word] + 1 else: D[new_word] = 1 return D # returns dictionary of (word, frequency)# pairs from the previous dictionary.def word_frequencies_for_file(filename): line_list = read_file(filename) word_list = get_words_from_line_list(line_list) freq_mapping = count_frequency(word_list) print("File", filename, ":", ) print(len(line_list), "lines, ", ) print(len(word_list), "words, ", ) print(len(freq_mapping), "distinct words") return freq_mapping
Lastly, we will calculate the dot product to give the document distance.
# returns the dot product of two documentsdef dotProduct(D1, D2): Sum = 0.0 for key in D1: if key in D2: Sum += (D1[key] * D2[key]) return Sum # returns the angle in radians # between document vectorsdef vector_angle(D1, D2): numerator = dotProduct(D1, D2) denominator = math.sqrt(dotProduct(D1, D1)*dotProduct(D2, D2)) return math.acos(numerator / denominator)
That’s all! Time to see the document similarity function:
def documentSimilarity(filename_1, filename_2): # filename_1 = sys.argv[1] # filename_2 = sys.argv[2] sorted_word_list_1 = word_frequencies_for_file(filename_1) sorted_word_list_2 = word_frequencies_for_file(filename_2) distance = vector_angle(sorted_word_list_1, sorted_word_list_2) print("The distance between the documents is: % 0.6f (radians)"% distance)
Here is the full sourcecode.
import mathimport stringimport sys # reading the text file# This functio will return a # list of the lines of text # in the file.def read_file(filename): try: with open(filename, 'r') as f: data = f.read() return data except IOError: print("Error opening or reading input file: ", filename) sys.exit() # splitting the text lines into words# translation table is a global variable# mapping upper case to lower case and# punctuation to spacestranslation_table = str.maketrans(string.punctuation+string.ascii_uppercase, " "*len(string.punctuation)+string.ascii_lowercase) # returns a list of the words# in the filedef get_words_from_line_list(text): text = text.translate(translation_table) word_list = text.split() return word_list # counts frequency of each word# returns a dictionary which maps# the words to their frequency.def count_frequency(word_list): D = {} for new_word in word_list: if new_word in D: D[new_word] = D[new_word] + 1 else: D[new_word] = 1 return D # returns dictionary of (word, frequency)# pairs from the previous dictionary.def word_frequencies_for_file(filename): line_list = read_file(filename) word_list = get_words_from_line_list(line_list) freq_mapping = count_frequency(word_list) print("File", filename, ":", ) print(len(line_list), "lines, ", ) print(len(word_list), "words, ", ) print(len(freq_mapping), "distinct words") return freq_mapping # returns the dot product of two documentsdef dotProduct(D1, D2): Sum = 0.0 for key in D1: if key in D2: Sum += (D1[key] * D2[key]) return Sum # returns the angle in radians # between document vectorsdef vector_angle(D1, D2): numerator = dotProduct(D1, D2) denominator = math.sqrt(dotProduct(D1, D1)*dotProduct(D2, D2)) return math.acos(numerator / denominator) def documentSimilarity(filename_1, filename_2): # filename_1 = sys.argv[1] # filename_2 = sys.argv[2] sorted_word_list_1 = word_frequencies_for_file(filename_1) sorted_word_list_2 = word_frequencies_for_file(filename_2) distance = vector_angle(sorted_word_list_1, sorted_word_list_2) print("The distance between the documents is: % 0.6f (radians)"% distance) # Driver codedocumentSimilarity('GFG.txt', 'file.txt')
Output:
File GFG.txt :
15 lines,
4 words,
4 distinct words
File file.txt :
22 lines,
5 words,
5 distinct words
The distance between the documents is: 0.835482 (radians)
Python-Miscellaneous
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here. | [
{
"code": null,
"e": 54,
"s": 26,
"text": "\n27 Feb, 2020"
},
{
"code": null,
"e": 503,
"s": 54,
"text": "Document similarity, as the name suggests determines how similar are the two given documents. By “documents”, we mean a collection of strings. For example, an essay or a .txt file. Many organizations use this principle of document similarity to check plagiarism. It is also used by many exams conducting institutions to check if a student cheated from the other. Therefore, it is very important as well as interesting to know how all of this works."
},
{
"code": null,
"e": 817,
"s": 503,
"text": "Document similarity is calculated by calculating document distance. Document distance is a concept where words(documents) are treated as vectors and is calculated as the angle between two given document vectors. Document vectors are the frequency of occurrences of words in a given document. Let’s see an example:"
},
{
"code": null,
"e": 867,
"s": 817,
"text": "Say that we are given two documents D1 and D2 as:"
},
{
"code": null,
"e": 915,
"s": 867,
"text": "D1: “This is a geek”D2: “This was a geek thing”"
},
{
"code": null,
"e": 970,
"s": 915,
"text": "The similar words in both these documents then become:"
},
{
"code": null,
"e": 984,
"s": 970,
"text": "\"This a geek\""
},
{
"code": null,
"e": 1103,
"s": 984,
"text": "If we make a 3-D representation of this as vectors by taking D1, D2 and similar words in 3 axis geometry, then we get:"
},
{
"code": null,
"e": 1144,
"s": 1103,
"text": "Now if we take dot product of D1 and D2,"
},
{
"code": null,
"e": 1209,
"s": 1144,
"text": "D1.D2 = \"This\".\"This\"+\"is\".\"was\"+\"a\".\"a\"+\"geek\".\"geek\"+\"thing\".0"
},
{
"code": null,
"e": 1227,
"s": 1209,
"text": "D1.D2 = 1+0+1+1+0"
},
{
"code": null,
"e": 1237,
"s": 1227,
"text": "D1.D2 = 3"
},
{
"code": null,
"e": 1368,
"s": 1237,
"text": "Now that we know how to calculate the dot product of these documents, we can now calculate the angle between the document vectors:"
},
{
"code": null,
"e": 1391,
"s": 1368,
"text": "cos d = D1.D2/|D1||D2|"
},
{
"code": null,
"e": 1599,
"s": 1391,
"text": "Here d is the document distance. It’s value ranges from 0 degree to 90 degrees. Where 0 degree means the two documents are exactly identical and 90 degrees indicate that the two documents are very different."
},
{
"code": null,
"e": 1719,
"s": 1599,
"text": "Now that we know about document similarity and document distance, let’s look at a Python program to calculate the same:"
},
{
"code": null,
"e": 1749,
"s": 1719,
"text": "Document similarity program :"
},
{
"code": null,
"e": 1835,
"s": 1749,
"text": "Our algorithm to confirm document similarity will consist of three fundamental steps:"
},
{
"code": null,
"e": 1865,
"s": 1835,
"text": "Split the documents in words."
},
{
"code": null,
"e": 1895,
"s": 1865,
"text": "Compute the word frequencies."
},
{
"code": null,
"e": 1946,
"s": 1895,
"text": "Calculate the dot product of the document vectors."
},
{
"code": null,
"e": 2265,
"s": 1946,
"text": "For the first step, we will first use the .read() method to open and read the content of the files. As we read the contents, we will split them into a list. Next, we will calculate the word frequency list of the read in the file. Therefore, the occurrence of each word is counted and the list is sorted alphabetically."
},
{
"code": "import mathimport stringimport sys # reading the text file# This functio will return a # list of the lines of text # in the file.def read_file(filename): try: with open(filename, 'r') as f: data = f.read() return data except IOError: print(\"Error opening or reading input file: \", filename) sys.exit() # splitting the text lines into words# translation table is a global variable# mapping upper case to lower case and# punctuation to spacestranslation_table = str.maketrans(string.punctuation+string.ascii_uppercase, \" \"*len(string.punctuation)+string.ascii_lowercase) # returns a list of the words# in the filedef get_words_from_line_list(text): text = text.translate(translation_table) word_list = text.split() return word_list",
"e": 3119,
"s": 2265,
"text": null
},
{
"code": null,
"e": 3216,
"s": 3119,
"text": "Now that we have the word list, we will now calculate the frequency of occurrences of the words."
},
{
"code": "# counts frequency of each word# returns a dictionary which maps# the words to their frequency.def count_frequency(word_list): D = {} for new_word in word_list: if new_word in D: D[new_word] = D[new_word] + 1 else: D[new_word] = 1 return D # returns dictionary of (word, frequency)# pairs from the previous dictionary.def word_frequencies_for_file(filename): line_list = read_file(filename) word_list = get_words_from_line_list(line_list) freq_mapping = count_frequency(word_list) print(\"File\", filename, \":\", ) print(len(line_list), \"lines, \", ) print(len(word_list), \"words, \", ) print(len(freq_mapping), \"distinct words\") return freq_mapping",
"e": 3994,
"s": 3216,
"text": null
},
{
"code": null,
"e": 4067,
"s": 3994,
"text": "Lastly, we will calculate the dot product to give the document distance."
},
{
"code": "# returns the dot product of two documentsdef dotProduct(D1, D2): Sum = 0.0 for key in D1: if key in D2: Sum += (D1[key] * D2[key]) return Sum # returns the angle in radians # between document vectorsdef vector_angle(D1, D2): numerator = dotProduct(D1, D2) denominator = math.sqrt(dotProduct(D1, D1)*dotProduct(D2, D2)) return math.acos(numerator / denominator)",
"e": 4504,
"s": 4067,
"text": null
},
{
"code": null,
"e": 4562,
"s": 4504,
"text": "That’s all! Time to see the document similarity function:"
},
{
"code": "def documentSimilarity(filename_1, filename_2): # filename_1 = sys.argv[1] # filename_2 = sys.argv[2] sorted_word_list_1 = word_frequencies_for_file(filename_1) sorted_word_list_2 = word_frequencies_for_file(filename_2) distance = vector_angle(sorted_word_list_1, sorted_word_list_2) print(\"The distance between the documents is: % 0.6f (radians)\"% distance)",
"e": 4949,
"s": 4562,
"text": null
},
{
"code": null,
"e": 4978,
"s": 4949,
"text": "Here is the full sourcecode."
},
{
"code": "import mathimport stringimport sys # reading the text file# This functio will return a # list of the lines of text # in the file.def read_file(filename): try: with open(filename, 'r') as f: data = f.read() return data except IOError: print(\"Error opening or reading input file: \", filename) sys.exit() # splitting the text lines into words# translation table is a global variable# mapping upper case to lower case and# punctuation to spacestranslation_table = str.maketrans(string.punctuation+string.ascii_uppercase, \" \"*len(string.punctuation)+string.ascii_lowercase) # returns a list of the words# in the filedef get_words_from_line_list(text): text = text.translate(translation_table) word_list = text.split() return word_list # counts frequency of each word# returns a dictionary which maps# the words to their frequency.def count_frequency(word_list): D = {} for new_word in word_list: if new_word in D: D[new_word] = D[new_word] + 1 else: D[new_word] = 1 return D # returns dictionary of (word, frequency)# pairs from the previous dictionary.def word_frequencies_for_file(filename): line_list = read_file(filename) word_list = get_words_from_line_list(line_list) freq_mapping = count_frequency(word_list) print(\"File\", filename, \":\", ) print(len(line_list), \"lines, \", ) print(len(word_list), \"words, \", ) print(len(freq_mapping), \"distinct words\") return freq_mapping # returns the dot product of two documentsdef dotProduct(D1, D2): Sum = 0.0 for key in D1: if key in D2: Sum += (D1[key] * D2[key]) return Sum # returns the angle in radians # between document vectorsdef vector_angle(D1, D2): numerator = dotProduct(D1, D2) denominator = math.sqrt(dotProduct(D1, D1)*dotProduct(D2, D2)) return math.acos(numerator / denominator) def documentSimilarity(filename_1, filename_2): # filename_1 = sys.argv[1] # filename_2 = sys.argv[2] sorted_word_list_1 = word_frequencies_for_file(filename_1) sorted_word_list_2 = word_frequencies_for_file(filename_2) distance = vector_angle(sorted_word_list_1, sorted_word_list_2) print(\"The distance between the documents is: % 0.6f (radians)\"% distance) # Driver codedocumentSimilarity('GFG.txt', 'file.txt')",
"e": 7503,
"s": 4978,
"text": null
},
{
"code": null,
"e": 7511,
"s": 7503,
"text": "Output:"
},
{
"code": null,
"e": 7678,
"s": 7511,
"text": "File GFG.txt :\n15 lines, \n4 words, \n4 distinct words\nFile file.txt :\n22 lines, \n5 words, \n5 distinct words\nThe distance between the documents is: 0.835482 (radians)\n"
},
{
"code": null,
"e": 7699,
"s": 7678,
"text": "Python-Miscellaneous"
},
{
"code": null,
"e": 7706,
"s": 7699,
"text": "Python"
}
] |
LocalDate minusYears() method in Java with Examples | 07 May, 2019
The minusYears() method of a LocalDate class is used to subtract the number of specified years from this LocalDate and return a copy of LocalDate.
This method subtracts the years field in the following steps:
Firstly, it subtracts the years from the year field in this LocalDate.
Check if the date after subtracting years is valid or not.
If the date is invalid then method adjusts the day-of-month to the last valid day.
For example, 2016-02-29 (leap year) minus one year gives date 2015-02-29 but this is an invalid result, so the last valid day of the month, 2015-02-28, is returned. This instance is immutable and unaffected by this method call.
Syntax:
public LocalDate minusYears(long yearsToSubtract)
Parameters: This method accepts a single parameter yearsToSubtract which represents the years to subtract, may be negative.
Return Value: This method returns a LocalDate based on this date with the years subtracted, not null.
Exception: This method throws DateTimeException if the result exceeds the supported date range.
Below programs illustrate the minusYears() method:
Program 1:
// Java program to demonstrate// LocalDate.minusYears() method import java.time.*; public class GFG { public static void main(String[] args) { // create a LocalDate object LocalDate date = LocalDate.parse("2020-10-22"); // print instance System.out.println("LocalDate before" + " subtracting years:" + date); // subtract 30 years LocalDate returnvalue = date.minusYears(30); // print result System.out.println("LocalDate after " + " subtracting years:" + returnvalue); }}
LocalDate before subtracting years:2020-10-22
LocalDate after subtracting years:1990-10-22
Program 2:
// Java program to demonstrate// LocalDate.minusYears() method import java.time.*; public class GFG { public static void main(String[] args) { // create a LocalDate object LocalDate date = LocalDate.parse("2020-02-29"); // print instance System.out.println("LocalDate before" + " subtracting years: " + date); // subtract -21 years LocalDate returnvalue = date.minusYears(-21); // print result System.out.println("LocalDate after " + " subtracting years: " + returnvalue); }}
LocalDate before subtracting years: 2020-02-29
LocalDate after subtracting years: 2041-02-28
Reference:https://docs.oracle.com/javase/10/docs/api/java/time/LocalDate.html#minusYears(long)
Akanksha_Rai
Java-Functions
Java-LocalDate
Java-time package
Java
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here. | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n07 May, 2019"
},
{
"code": null,
"e": 175,
"s": 28,
"text": "The minusYears() method of a LocalDate class is used to subtract the number of specified years from this LocalDate and return a copy of LocalDate."
},
{
"code": null,
"e": 237,
"s": 175,
"text": "This method subtracts the years field in the following steps:"
},
{
"code": null,
"e": 308,
"s": 237,
"text": "Firstly, it subtracts the years from the year field in this LocalDate."
},
{
"code": null,
"e": 367,
"s": 308,
"text": "Check if the date after subtracting years is valid or not."
},
{
"code": null,
"e": 450,
"s": 367,
"text": "If the date is invalid then method adjusts the day-of-month to the last valid day."
},
{
"code": null,
"e": 678,
"s": 450,
"text": "For example, 2016-02-29 (leap year) minus one year gives date 2015-02-29 but this is an invalid result, so the last valid day of the month, 2015-02-28, is returned. This instance is immutable and unaffected by this method call."
},
{
"code": null,
"e": 686,
"s": 678,
"text": "Syntax:"
},
{
"code": null,
"e": 737,
"s": 686,
"text": "public LocalDate minusYears(long yearsToSubtract)\n"
},
{
"code": null,
"e": 861,
"s": 737,
"text": "Parameters: This method accepts a single parameter yearsToSubtract which represents the years to subtract, may be negative."
},
{
"code": null,
"e": 963,
"s": 861,
"text": "Return Value: This method returns a LocalDate based on this date with the years subtracted, not null."
},
{
"code": null,
"e": 1059,
"s": 963,
"text": "Exception: This method throws DateTimeException if the result exceeds the supported date range."
},
{
"code": null,
"e": 1110,
"s": 1059,
"text": "Below programs illustrate the minusYears() method:"
},
{
"code": null,
"e": 1121,
"s": 1110,
"text": "Program 1:"
},
{
"code": "// Java program to demonstrate// LocalDate.minusYears() method import java.time.*; public class GFG { public static void main(String[] args) { // create a LocalDate object LocalDate date = LocalDate.parse(\"2020-10-22\"); // print instance System.out.println(\"LocalDate before\" + \" subtracting years:\" + date); // subtract 30 years LocalDate returnvalue = date.minusYears(30); // print result System.out.println(\"LocalDate after \" + \" subtracting years:\" + returnvalue); }}",
"e": 1742,
"s": 1121,
"text": null
},
{
"code": null,
"e": 1835,
"s": 1742,
"text": "LocalDate before subtracting years:2020-10-22\nLocalDate after subtracting years:1990-10-22\n"
},
{
"code": null,
"e": 1846,
"s": 1835,
"text": "Program 2:"
},
{
"code": "// Java program to demonstrate// LocalDate.minusYears() method import java.time.*; public class GFG { public static void main(String[] args) { // create a LocalDate object LocalDate date = LocalDate.parse(\"2020-02-29\"); // print instance System.out.println(\"LocalDate before\" + \" subtracting years: \" + date); // subtract -21 years LocalDate returnvalue = date.minusYears(-21); // print result System.out.println(\"LocalDate after \" + \" subtracting years: \" + returnvalue); }}",
"e": 2471,
"s": 1846,
"text": null
},
{
"code": null,
"e": 2566,
"s": 2471,
"text": "LocalDate before subtracting years: 2020-02-29\nLocalDate after subtracting years: 2041-02-28\n"
},
{
"code": null,
"e": 2661,
"s": 2566,
"text": "Reference:https://docs.oracle.com/javase/10/docs/api/java/time/LocalDate.html#minusYears(long)"
},
{
"code": null,
"e": 2674,
"s": 2661,
"text": "Akanksha_Rai"
},
{
"code": null,
"e": 2689,
"s": 2674,
"text": "Java-Functions"
},
{
"code": null,
"e": 2704,
"s": 2689,
"text": "Java-LocalDate"
},
{
"code": null,
"e": 2722,
"s": 2704,
"text": "Java-time package"
},
{
"code": null,
"e": 2727,
"s": 2722,
"text": "Java"
},
{
"code": null,
"e": 2732,
"s": 2727,
"text": "Java"
}
] |
Fast Doubling method to find the Nth Fibonacci number | 23 Jun, 2022
Given an integer N, the task is to find the N-th Fibonacci numbers.Examples:
Input: N = 3 Output: 2 Explanation: F(1) = 1, F(2) = 1 F(3) = F(1) + F(2) = 2 Input: N = 6 Output: 8
Approach:
The Matrix Exponentiation Method is already discussed before. The Doubling Method can be seen as an improvement to the matrix exponentiation method to find the N-th Fibonacci number although it doesn’t use matrix multiplication itself.
The Fibonacci recursive sequence is given by
F(n+1) = F(n) + F(n-1)
The Matrix Exponentiation method uses the following formula
The method involves costly matrix multiplication and moreover Fn is redundantly computed twice.On the other hand, Fast Doubling Method is based on two basic formulas:
F(2n) = F(n)[2F(n+1) – F(n)]
F(2n + 1) = F(n)2 + F(n+1)2
Here is a short explanation of the above results:
Start with: F(n+1) = F(n) + F(n-1) & F(n) = F(n) It can be rewritten in the matrix form as:
For doubling, we just plug in “2n” into the formula:
Substituting F(n-1) = F(n+1)- F(n) and after simplification we get,
Below is the implementation of the above approach:
C++
Java
Python3
C#
Javascript
// C++ program to find the Nth Fibonacci// number using Fast Doubling Method#include <bits/stdc++.h>using namespace std; int a, b, c, d;#define MOD 1000000007 // Function calculate the N-th fibonacci// number using fast doubling methodvoid FastDoubling(int n, int res[]){ // Base Condition if (n == 0) { res[0] = 0; res[1] = 1; return; } FastDoubling((n / 2), res); // Here a = F(n) a = res[0]; // Here b = F(n+1) b = res[1]; c = 2 * b - a; if (c < 0) c += MOD; // As F(2n) = F(n)[2F(n+1) – F(n)] // Here c = F(2n) c = (a * c) % MOD; // As F(2n + 1) = F(n)^2 + F(n+1)^2 // Here d = F(2n + 1) d = (a * a + b * b) % MOD; // Check if N is odd // or even if (n % 2 == 0) { res[0] = c; res[1] = d; } else { res[0] = d; res[1] = c + d; }} // Driver codeint main(){ int N = 6; int res[2] = { 0 }; FastDoubling(N, res); cout << res[0] << "\n"; return 0;}
// Java program to find the Nth Fibonacci// number using Fast Doubling Methodclass GFG{ // Function calculate the N-th fibonacci// number using fast doubling methodstatic void FastDoubling(int n, int []res){ int a, b, c, d; int MOD = 1000000007; // Base Condition if (n == 0) { res[0] = 0; res[1] = 1; return; } FastDoubling((n / 2), res); // Here a = F(n) a = res[0]; // Here b = F(n+1) b = res[1]; c = 2 * b - a; if (c < 0) c += MOD; // As F(2n) = F(n)[2F(n+1) – F(n)] // Here c = F(2n) c = (a * c) % MOD; // As F(2n + 1) = F(n)^2 + F(n+1)^2 // Here d = F(2n + 1) d = (a * a + b * b) % MOD; // Check if N is odd // or even if (n % 2 == 0) { res[0] = c; res[1] = d; } else { res[0] = d; res[1] = c + d; }} // Driver codepublic static void main(String []args){ int N = 6; int res[] = new int[2]; FastDoubling(N, res); System.out.print(res[0]);}} // This code is contributed by rock_cool
# Python3 program to find the Nth Fibonacci# number using Fast Doubling MethodMOD = 1000000007 # Function calculate the N-th fibonacci# number using fast doubling methoddef FastDoubling(n, res): # Base Condition if (n == 0): res[0] = 0 res[1] = 1 return FastDoubling((n // 2), res) # Here a = F(n) a = res[0] # Here b = F(n+1) b = res[1] c = 2 * b - a if (c < 0): c += MOD # As F(2n) = F(n)[2F(n+1) – F(n)] # Here c = F(2n) c = (a * c) % MOD # As F(2n + 1) = F(n)^2 + F(n+1)^2 # Here d = F(2n + 1) d = (a * a + b * b) % MOD # Check if N is odd # or even if (n % 2 == 0): res[0] = c res[1] = d else : res[0] = d res[1] = c + d # Driver codeN = 6res = [0] * 2 FastDoubling(N, res) print(res[0]) # This code is contributed by divyamohan123
// C# program to find the Nth Fibonacci// number using Fast Doubling Methodusing System;class GFG{ // Function calculate the N-th fibonacci// number using fast doubling methodstatic void FastDoubling(int n, int []res){ int a, b, c, d; int MOD = 1000000007; // Base Condition if (n == 0) { res[0] = 0; res[1] = 1; return; } FastDoubling((n / 2), res); // Here a = F(n) a = res[0]; // Here b = F(n+1) b = res[1]; c = 2 * b - a; if (c < 0) c += MOD; // As F(2n) = F(n)[2F(n+1) – F(n)] // Here c = F(2n) c = (a * c) % MOD; // As F(2n + 1) = F(n)^2 + F(n+1)^2 // Here d = F(2n + 1) d = (a * a + b * b) % MOD; // Check if N is odd // or even if (n % 2 == 0) { res[0] = c; res[1] = d; } else { res[0] = d; res[1] = c + d; }} // Driver codepublic static void Main(){ int N = 6; int []res = new int[2]; FastDoubling(N, res); Console.Write(res[0]);}} // This code is contributed by Code_Mech
<script> // Javascript program to find the Nth Fibonacci // number using Fast Doubling Method let a, b, c, d; let MOD = 1000000007; // Function calculate the N-th fibonacci // number using fast doubling method function FastDoubling(n, res) { // Base Condition if (n == 0) { res[0] = 0; res[1] = 1; return; } FastDoubling(parseInt(n / 2, 10), res); // Here a = F(n) a = res[0]; // Here b = F(n+1) b = res[1]; c = 2 * b - a; if (c < 0) c += MOD; // As F(2n) = F(n)[2F(n+1) – F(n)] // Here c = F(2n) c = (a * c) % MOD; // As F(2n + 1) = F(n)^2 + F(n+1)^2 // Here d = F(2n + 1) d = (a * a + b * b) % MOD; // Check if N is odd // or even if (n % 2 == 0) { res[0] = c; res[1] = d; } else { res[0] = d; res[1] = c + d; } } let N = 6; let res = new Array(2); res.fill(0); FastDoubling(N, res); document.write(res[0]); </script>
8
Time Complexity: Repeated squaring reduces time from linear to logarithmic . Hence, with constant time arithmetic, the time complexity is O(log n).Auxiliary Space: O(n).
Iterative Version
We can implement iterative version of above method, by initializing array with two elements f = [F(0), F(1)] = [0, 1] and iteratively constructing F(n), on every step we will transform f into [F(2i), F(2i+1)] or [F(2i+1), F(2i+2)] , where i corresponds to the current value of i stored in f = [F(i), F(i+1)].
Approach:
Create array with two elements f = [0, 1] , which represents [F(0), F(1)] .
For finding F(n), iterate over binary representation of n from left to right, let kth bit from left be bk .
Iteratively apply the below steps for all bits in n .
Using bk we will decide whether to transform f = [F(i), F(i+1)] into [F(2i), F(2i+1)] or [F(2i+1), F(2i+2)] .
if bk == 0:
f = [F(2i), F(2i+1)] = [F(i){2F(i+1)-F(i)}, F(i+1)2+F(i)2]
if bk == 1:
f = [F(2i+1), F(2i+2)] = [F(i+1)2+F(i)2, F(i+1){2F(i)+F(i+1)}]
where,
F(i) and F(i+1) are current values stored in f.
return f[0] .
Example:
for n = 13 = (1101)2
b = 1 1 0 1
[F(0), F(1)] -> [F(1), F(2)] -> [F(3), F(4)] -> [F(6), F(7)] -> [F(13), F(14)]
[0, 1] -> [1, 1] -> [2, 3] -> [8, 13] -> [233, 377]
Below is the implementation of the above approach:
C++
Python3
Javascript
// C++ program to find the Nth Fibonacci// number using Fast Doubling Method iteratively #include <bitset>#include <iostream>#include <string> using namespace std; // helper function to get binary stringstring decimal_to_bin(int n){ // use bitset to get binary string string bin = bitset<sizeof(int) * 8>(n).to_string(); auto loc = bin.find('1'); // remove leading zeros if (loc != string::npos) return bin.substr(loc); return "0";} // computes fib(n) iteratively using fast doubling methodlong long fastfib(int n){ string bin_of_n = decimal_to_bin(n); // binary string of n long long f[] = { 0, 1 }; // [F(i), F(i+1)] => i=0 for (auto b : bin_of_n) { long long f2i1 = f[1] * f[1] + f[0] * f[0]; // F(2i+1) long long f2i = f[0] * (2 * f[1] - f[0]); // F(2i) if (b == '0') { f[0] = f2i; // F(2i) f[1] = f2i1; // F(2i+1) } else { f[0] = f2i1; // F(2i+1) f[1] = f2i1 + f2i; // F(2i+2) } } return f[0];} int main(){ int n = 13; long long fib = fastfib(n); cout << "F(" << n << ") = " << fib << "\n";}
# Python3 program to find the Nth Fibonacci# number using Fast Doubling Method iteratively def fastfib(n): """computes fib(n) iteratively using fast doubling method""" bin_of_n = bin(n)[2:] # binary string of n f = [0, 1] # [F(i), F(i+1)] => i=0 for b in bin_of_n: f2i1 = f[1]**2 + f[0]**2 # F(2i+1) f2i = f[0]*(2*f[1]-f[0]) # F(2i) if b == '0': f[0], f[1] = f2i, f2i1 # [F(2i), F(2i+1)] else: f[0], f[1] = f2i1, f2i1+f2i # [F(2i+1), F(2i+2)] return f[0] n = 13fib = fastfib(n)print(f'F({n}) =', fib)
// JavaScript program to find the Nth Fibonacci// number using Fast Doubling Method iteratively // Helper function to convert decimal to binary.function convertToBinary(x) { let bin = 0; let rem, i = 1, step = 1; while (x != 0) { rem = x % 2; x = parseInt(x / 2); bin = bin + rem * i; i = i * 10; } // let myArr = Array.from(String(bin).split("")); return bin.toString();} // helper function to get binary stringfunction decimal_to_bin(n){ // use bitset to get binary string let bin = convertToBinary(n); let loc = bin.indexOf('1'); // remove leading zeros if (loc != -1) return bin.substring(loc); return "0";} // computes fib(n) iteratively using fast doubling methodfunction fastfib(n){ let bin_of_n = decimal_to_bin(n); // binary string of n let f = [0, 1]; // [F(i), F(i+1)] => i=0 for(let i = 0; i < bin_of_n.length; i++){ let b = bin_of_n[i]; let f2i1 = f[1] * f[1] + f[0] * f[0]; // F(2i+1) let f2i = f[0] * (2 * f[1] - f[0]); // F(2i) if (b == '0') { f[0] = f2i; // F(2i) f[1] = f2i1; // F(2i+1) } else { f[0] = f2i1; // F(2i+1) f[1] = f2i1 + f2i; // F(2i+2) } } return f[0];} let n = 13;let fib = fastfib(n);console.log("F(",n,") =", fib); // The code is contributed by Gautam goel (gautamgoel962)
F(13) = 233
Time Complexity: We are iterating over the binary string of number n which has length of log(n) and doing constant time arithmetic operations, so the time complexity is O(log n).
Auxiliary Space: We are storing two elements in f and binary string of n has length log(n), so space complexity is O(log n).
divyamohan123
rock_cool
Code_Mech
divyeshrabadiya07
pankajsharmagfg
2019029
anikakapoor
simmytarika5
gautamgoel962
Fibonacci
matrix-exponentiation
Algorithms
Articles
Competitive Programming
Divide and Conquer
Matrix
Divide and Conquer
Matrix
Fibonacci
Algorithms
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here. | [
{
"code": null,
"e": 52,
"s": 24,
"text": "\n23 Jun, 2022"
},
{
"code": null,
"e": 131,
"s": 52,
"text": "Given an integer N, the task is to find the N-th Fibonacci numbers.Examples: "
},
{
"code": null,
"e": 234,
"s": 131,
"text": "Input: N = 3 Output: 2 Explanation: F(1) = 1, F(2) = 1 F(3) = F(1) + F(2) = 2 Input: N = 6 Output: 8 "
},
{
"code": null,
"e": 248,
"s": 236,
"text": "Approach: "
},
{
"code": null,
"e": 485,
"s": 248,
"text": "The Matrix Exponentiation Method is already discussed before. The Doubling Method can be seen as an improvement to the matrix exponentiation method to find the N-th Fibonacci number although it doesn’t use matrix multiplication itself. "
},
{
"code": null,
"e": 532,
"s": 485,
"text": "The Fibonacci recursive sequence is given by "
},
{
"code": null,
"e": 555,
"s": 532,
"text": "F(n+1) = F(n) + F(n-1)"
},
{
"code": null,
"e": 620,
"s": 555,
"text": "The Matrix Exponentiation method uses the following formula "
},
{
"code": null,
"e": 796,
"s": 627,
"text": "The method involves costly matrix multiplication and moreover Fn is redundantly computed twice.On the other hand, Fast Doubling Method is based on two basic formulas: "
},
{
"code": null,
"e": 853,
"s": 796,
"text": "F(2n) = F(n)[2F(n+1) – F(n)]\nF(2n + 1) = F(n)2 + F(n+1)2"
},
{
"code": null,
"e": 904,
"s": 853,
"text": "Here is a short explanation of the above results: "
},
{
"code": null,
"e": 997,
"s": 904,
"text": "Start with: F(n+1) = F(n) + F(n-1) & F(n) = F(n) It can be rewritten in the matrix form as: "
},
{
"code": null,
"e": 1055,
"s": 1002,
"text": "For doubling, we just plug in “2n” into the formula:"
},
{
"code": null,
"e": 1129,
"s": 1060,
"text": "Substituting F(n-1) = F(n+1)- F(n) and after simplification we get, "
},
{
"code": null,
"e": 1188,
"s": 1136,
"text": "Below is the implementation of the above approach: "
},
{
"code": null,
"e": 1192,
"s": 1188,
"text": "C++"
},
{
"code": null,
"e": 1197,
"s": 1192,
"text": "Java"
},
{
"code": null,
"e": 1205,
"s": 1197,
"text": "Python3"
},
{
"code": null,
"e": 1208,
"s": 1205,
"text": "C#"
},
{
"code": null,
"e": 1219,
"s": 1208,
"text": "Javascript"
},
{
"code": "// C++ program to find the Nth Fibonacci// number using Fast Doubling Method#include <bits/stdc++.h>using namespace std; int a, b, c, d;#define MOD 1000000007 // Function calculate the N-th fibonacci// number using fast doubling methodvoid FastDoubling(int n, int res[]){ // Base Condition if (n == 0) { res[0] = 0; res[1] = 1; return; } FastDoubling((n / 2), res); // Here a = F(n) a = res[0]; // Here b = F(n+1) b = res[1]; c = 2 * b - a; if (c < 0) c += MOD; // As F(2n) = F(n)[2F(n+1) – F(n)] // Here c = F(2n) c = (a * c) % MOD; // As F(2n + 1) = F(n)^2 + F(n+1)^2 // Here d = F(2n + 1) d = (a * a + b * b) % MOD; // Check if N is odd // or even if (n % 2 == 0) { res[0] = c; res[1] = d; } else { res[0] = d; res[1] = c + d; }} // Driver codeint main(){ int N = 6; int res[2] = { 0 }; FastDoubling(N, res); cout << res[0] << \"\\n\"; return 0;}",
"e": 2213,
"s": 1219,
"text": null
},
{
"code": "// Java program to find the Nth Fibonacci// number using Fast Doubling Methodclass GFG{ // Function calculate the N-th fibonacci// number using fast doubling methodstatic void FastDoubling(int n, int []res){ int a, b, c, d; int MOD = 1000000007; // Base Condition if (n == 0) { res[0] = 0; res[1] = 1; return; } FastDoubling((n / 2), res); // Here a = F(n) a = res[0]; // Here b = F(n+1) b = res[1]; c = 2 * b - a; if (c < 0) c += MOD; // As F(2n) = F(n)[2F(n+1) – F(n)] // Here c = F(2n) c = (a * c) % MOD; // As F(2n + 1) = F(n)^2 + F(n+1)^2 // Here d = F(2n + 1) d = (a * a + b * b) % MOD; // Check if N is odd // or even if (n % 2 == 0) { res[0] = c; res[1] = d; } else { res[0] = d; res[1] = c + d; }} // Driver codepublic static void main(String []args){ int N = 6; int res[] = new int[2]; FastDoubling(N, res); System.out.print(res[0]);}} // This code is contributed by rock_cool",
"e": 3263,
"s": 2213,
"text": null
},
{
"code": "# Python3 program to find the Nth Fibonacci# number using Fast Doubling MethodMOD = 1000000007 # Function calculate the N-th fibonacci# number using fast doubling methoddef FastDoubling(n, res): # Base Condition if (n == 0): res[0] = 0 res[1] = 1 return FastDoubling((n // 2), res) # Here a = F(n) a = res[0] # Here b = F(n+1) b = res[1] c = 2 * b - a if (c < 0): c += MOD # As F(2n) = F(n)[2F(n+1) – F(n)] # Here c = F(2n) c = (a * c) % MOD # As F(2n + 1) = F(n)^2 + F(n+1)^2 # Here d = F(2n + 1) d = (a * a + b * b) % MOD # Check if N is odd # or even if (n % 2 == 0): res[0] = c res[1] = d else : res[0] = d res[1] = c + d # Driver codeN = 6res = [0] * 2 FastDoubling(N, res) print(res[0]) # This code is contributed by divyamohan123",
"e": 4142,
"s": 3263,
"text": null
},
{
"code": "// C# program to find the Nth Fibonacci// number using Fast Doubling Methodusing System;class GFG{ // Function calculate the N-th fibonacci// number using fast doubling methodstatic void FastDoubling(int n, int []res){ int a, b, c, d; int MOD = 1000000007; // Base Condition if (n == 0) { res[0] = 0; res[1] = 1; return; } FastDoubling((n / 2), res); // Here a = F(n) a = res[0]; // Here b = F(n+1) b = res[1]; c = 2 * b - a; if (c < 0) c += MOD; // As F(2n) = F(n)[2F(n+1) – F(n)] // Here c = F(2n) c = (a * c) % MOD; // As F(2n + 1) = F(n)^2 + F(n+1)^2 // Here d = F(2n + 1) d = (a * a + b * b) % MOD; // Check if N is odd // or even if (n % 2 == 0) { res[0] = c; res[1] = d; } else { res[0] = d; res[1] = c + d; }} // Driver codepublic static void Main(){ int N = 6; int []res = new int[2]; FastDoubling(N, res); Console.Write(res[0]);}} // This code is contributed by Code_Mech",
"e": 5187,
"s": 4142,
"text": null
},
{
"code": "<script> // Javascript program to find the Nth Fibonacci // number using Fast Doubling Method let a, b, c, d; let MOD = 1000000007; // Function calculate the N-th fibonacci // number using fast doubling method function FastDoubling(n, res) { // Base Condition if (n == 0) { res[0] = 0; res[1] = 1; return; } FastDoubling(parseInt(n / 2, 10), res); // Here a = F(n) a = res[0]; // Here b = F(n+1) b = res[1]; c = 2 * b - a; if (c < 0) c += MOD; // As F(2n) = F(n)[2F(n+1) – F(n)] // Here c = F(2n) c = (a * c) % MOD; // As F(2n + 1) = F(n)^2 + F(n+1)^2 // Here d = F(2n + 1) d = (a * a + b * b) % MOD; // Check if N is odd // or even if (n % 2 == 0) { res[0] = c; res[1] = d; } else { res[0] = d; res[1] = c + d; } } let N = 6; let res = new Array(2); res.fill(0); FastDoubling(N, res); document.write(res[0]); </script>",
"e": 6319,
"s": 5187,
"text": null
},
{
"code": null,
"e": 6321,
"s": 6319,
"text": "8"
},
{
"code": null,
"e": 6491,
"s": 6321,
"text": "Time Complexity: Repeated squaring reduces time from linear to logarithmic . Hence, with constant time arithmetic, the time complexity is O(log n).Auxiliary Space: O(n)."
},
{
"code": null,
"e": 6509,
"s": 6491,
"text": "Iterative Version"
},
{
"code": null,
"e": 6818,
"s": 6509,
"text": "We can implement iterative version of above method, by initializing array with two elements f = [F(0), F(1)] = [0, 1] and iteratively constructing F(n), on every step we will transform f into [F(2i), F(2i+1)] or [F(2i+1), F(2i+2)] , where i corresponds to the current value of i stored in f = [F(i), F(i+1)]."
},
{
"code": null,
"e": 6828,
"s": 6818,
"text": "Approach:"
},
{
"code": null,
"e": 6904,
"s": 6828,
"text": "Create array with two elements f = [0, 1] , which represents [F(0), F(1)] ."
},
{
"code": null,
"e": 7012,
"s": 6904,
"text": "For finding F(n), iterate over binary representation of n from left to right, let kth bit from left be bk ."
},
{
"code": null,
"e": 7066,
"s": 7012,
"text": "Iteratively apply the below steps for all bits in n ."
},
{
"code": null,
"e": 7176,
"s": 7066,
"text": "Using bk we will decide whether to transform f = [F(i), F(i+1)] into [F(2i), F(2i+1)] or [F(2i+1), F(2i+2)] ."
},
{
"code": null,
"e": 7380,
"s": 7176,
"text": "if bk == 0:\n f = [F(2i), F(2i+1)] = [F(i){2F(i+1)-F(i)}, F(i+1)2+F(i)2]\nif bk == 1:\n f = [F(2i+1), F(2i+2)] = [F(i+1)2+F(i)2, F(i+1){2F(i)+F(i+1)}]\n\nwhere,\nF(i) and F(i+1) are current values stored in f."
},
{
"code": null,
"e": 7394,
"s": 7380,
"text": "return f[0] ."
},
{
"code": null,
"e": 7641,
"s": 7394,
"text": "Example:\nfor n = 13 = (1101)2\nb = 1 1 0 1\n[F(0), F(1)] -> [F(1), F(2)] -> [F(3), F(4)] -> [F(6), F(7)] -> [F(13), F(14)]\n[0, 1] -> [1, 1] -> [2, 3] -> [8, 13] -> [233, 377]"
},
{
"code": null,
"e": 7692,
"s": 7641,
"text": "Below is the implementation of the above approach:"
},
{
"code": null,
"e": 7696,
"s": 7692,
"text": "C++"
},
{
"code": null,
"e": 7704,
"s": 7696,
"text": "Python3"
},
{
"code": null,
"e": 7715,
"s": 7704,
"text": "Javascript"
},
{
"code": "// C++ program to find the Nth Fibonacci// number using Fast Doubling Method iteratively #include <bitset>#include <iostream>#include <string> using namespace std; // helper function to get binary stringstring decimal_to_bin(int n){ // use bitset to get binary string string bin = bitset<sizeof(int) * 8>(n).to_string(); auto loc = bin.find('1'); // remove leading zeros if (loc != string::npos) return bin.substr(loc); return \"0\";} // computes fib(n) iteratively using fast doubling methodlong long fastfib(int n){ string bin_of_n = decimal_to_bin(n); // binary string of n long long f[] = { 0, 1 }; // [F(i), F(i+1)] => i=0 for (auto b : bin_of_n) { long long f2i1 = f[1] * f[1] + f[0] * f[0]; // F(2i+1) long long f2i = f[0] * (2 * f[1] - f[0]); // F(2i) if (b == '0') { f[0] = f2i; // F(2i) f[1] = f2i1; // F(2i+1) } else { f[0] = f2i1; // F(2i+1) f[1] = f2i1 + f2i; // F(2i+2) } } return f[0];} int main(){ int n = 13; long long fib = fastfib(n); cout << \"F(\" << n << \") = \" << fib << \"\\n\";}",
"e": 8869,
"s": 7715,
"text": null
},
{
"code": "# Python3 program to find the Nth Fibonacci# number using Fast Doubling Method iteratively def fastfib(n): \"\"\"computes fib(n) iteratively using fast doubling method\"\"\" bin_of_n = bin(n)[2:] # binary string of n f = [0, 1] # [F(i), F(i+1)] => i=0 for b in bin_of_n: f2i1 = f[1]**2 + f[0]**2 # F(2i+1) f2i = f[0]*(2*f[1]-f[0]) # F(2i) if b == '0': f[0], f[1] = f2i, f2i1 # [F(2i), F(2i+1)] else: f[0], f[1] = f2i1, f2i1+f2i # [F(2i+1), F(2i+2)] return f[0] n = 13fib = fastfib(n)print(f'F({n}) =', fib)",
"e": 9446,
"s": 8869,
"text": null
},
{
"code": "// JavaScript program to find the Nth Fibonacci// number using Fast Doubling Method iteratively // Helper function to convert decimal to binary.function convertToBinary(x) { let bin = 0; let rem, i = 1, step = 1; while (x != 0) { rem = x % 2; x = parseInt(x / 2); bin = bin + rem * i; i = i * 10; } // let myArr = Array.from(String(bin).split(\"\")); return bin.toString();} // helper function to get binary stringfunction decimal_to_bin(n){ // use bitset to get binary string let bin = convertToBinary(n); let loc = bin.indexOf('1'); // remove leading zeros if (loc != -1) return bin.substring(loc); return \"0\";} // computes fib(n) iteratively using fast doubling methodfunction fastfib(n){ let bin_of_n = decimal_to_bin(n); // binary string of n let f = [0, 1]; // [F(i), F(i+1)] => i=0 for(let i = 0; i < bin_of_n.length; i++){ let b = bin_of_n[i]; let f2i1 = f[1] * f[1] + f[0] * f[0]; // F(2i+1) let f2i = f[0] * (2 * f[1] - f[0]); // F(2i) if (b == '0') { f[0] = f2i; // F(2i) f[1] = f2i1; // F(2i+1) } else { f[0] = f2i1; // F(2i+1) f[1] = f2i1 + f2i; // F(2i+2) } } return f[0];} let n = 13;let fib = fastfib(n);console.log(\"F(\",n,\") =\", fib); // The code is contributed by Gautam goel (gautamgoel962)",
"e": 10837,
"s": 9446,
"text": null
},
{
"code": null,
"e": 10849,
"s": 10837,
"text": "F(13) = 233"
},
{
"code": null,
"e": 11028,
"s": 10849,
"text": "Time Complexity: We are iterating over the binary string of number n which has length of log(n) and doing constant time arithmetic operations, so the time complexity is O(log n)."
},
{
"code": null,
"e": 11153,
"s": 11028,
"text": "Auxiliary Space: We are storing two elements in f and binary string of n has length log(n), so space complexity is O(log n)."
},
{
"code": null,
"e": 11167,
"s": 11153,
"text": "divyamohan123"
},
{
"code": null,
"e": 11177,
"s": 11167,
"text": "rock_cool"
},
{
"code": null,
"e": 11187,
"s": 11177,
"text": "Code_Mech"
},
{
"code": null,
"e": 11205,
"s": 11187,
"text": "divyeshrabadiya07"
},
{
"code": null,
"e": 11221,
"s": 11205,
"text": "pankajsharmagfg"
},
{
"code": null,
"e": 11229,
"s": 11221,
"text": "2019029"
},
{
"code": null,
"e": 11241,
"s": 11229,
"text": "anikakapoor"
},
{
"code": null,
"e": 11254,
"s": 11241,
"text": "simmytarika5"
},
{
"code": null,
"e": 11268,
"s": 11254,
"text": "gautamgoel962"
},
{
"code": null,
"e": 11278,
"s": 11268,
"text": "Fibonacci"
},
{
"code": null,
"e": 11300,
"s": 11278,
"text": "matrix-exponentiation"
},
{
"code": null,
"e": 11311,
"s": 11300,
"text": "Algorithms"
},
{
"code": null,
"e": 11320,
"s": 11311,
"text": "Articles"
},
{
"code": null,
"e": 11344,
"s": 11320,
"text": "Competitive Programming"
},
{
"code": null,
"e": 11363,
"s": 11344,
"text": "Divide and Conquer"
},
{
"code": null,
"e": 11370,
"s": 11363,
"text": "Matrix"
},
{
"code": null,
"e": 11389,
"s": 11370,
"text": "Divide and Conquer"
},
{
"code": null,
"e": 11396,
"s": 11389,
"text": "Matrix"
},
{
"code": null,
"e": 11406,
"s": 11396,
"text": "Fibonacci"
},
{
"code": null,
"e": 11417,
"s": 11406,
"text": "Algorithms"
}
] |
Print all possible ways to write N as sum of two or more positive integers | 02 Feb, 2022
Given an integer N, the task is to print all the possible ways in which N can be written as the sum of two or more positive integers.Examples:
Input: N = 4 Output: 1 1 1 1 1 1 2 1 3 2 2 Input: N = 3 Output: 1 1 1 1 2
Approach: The idea is to use recursion to solve this problem. The idea is to consider every integer from 1 to N such that the sum N can be reduced by this number at each recursive call and if at any recursive call N reduces to zero then we will print the answer stored in the vector. Below are the steps for recursion:
Get the number N whose sum has to be broken into two or more positive integers.Recursively iterate from value 1 to N as index i:
Get the number N whose sum has to be broken into two or more positive integers.
Recursively iterate from value 1 to N as index i:
Base Case: If the value called recursively is 0, then print the current vector as this is one of the ways to broke N into two or more positive integers.
if (n == 0)
printVector(arr);
Recursive Call: If the base case is not met, then Recursively iterate from [i, N – i]. Push the current element j into vector(say arr) and recursively iterate for the next index and after this recursion ends then pop the element j inserted previously:
for j in range[i, N]:
arr.push_back(j);
recursive_function(arr, j + 1, N - j);
arr.pop_back(j);
Below is the implementation of the above approach:
C++
Java
Python3
C#
Javascript
// C++ program for the above approach#include <bits/stdc++.h>using namespace std; // Function to print the values stored// in vector arrvoid printVector(vector<int>& arr){ if (arr.size() != 1) { // Traverse the vector arr for (int i = 0; i < arr.size(); i++) { cout << arr[i] << " "; } cout << endl; }} // Recursive function to print different// ways in which N can be written as// a sum of at 2 or more positive integersvoid findWays(vector<int>& arr, int i, int n){ // If n is zero then print this // ways of breaking numbers if (n == 0) printVector(arr); // Start from previous element // in the representation till n for (int j = i; j <= n; j++) { // Include current element // from representation arr.push_back(j); // Call function again // with reduced sum findWays(arr, j, n - j); // Backtrack to remove current // element from representation arr.pop_back(); }} // Driver Codeint main(){ // Given sum N int n = 4; // To store the representation // of breaking N vector<int> arr; // Function Call findWays(arr, 1, n); return 0;}
// Java program for the above approachimport java.util.*; class GFG{ // Function to print the values stored// in vector arrstatic void printVector(ArrayList<Integer> arr){ if (arr.size() != 1) { // Traverse the vector arr for(int i = 0; i < arr.size(); i++) { System.out.print(arr.get(i) + " "); } System.out.println(); }} // Recursive function to print different// ways in which N can be written as// a sum of at 2 or more positive integersstatic void findWays(ArrayList<Integer> arr, int i, int n){ // If n is zero then print this // ways of breaking numbers if (n == 0) printVector(arr); // Start from previous element // in the representation till n for(int j = i; j <= n; j++) { // Include current element // from representation arr.add(j); // Call function again // with reduced sum findWays(arr, j, n - j); // Backtrack to remove current // element from representation arr.remove(arr.size() - 1); }} // Driver codepublic static void main(String[] args){ // Given sum N int n = 4; // To store the representation // of breaking N ArrayList<Integer> arr = new ArrayList<Integer>(); // Function call findWays(arr, 1, n);}} // This code is contributed by offbeat
# Python3 program for the above approach # Function to print the values stored# in vector arrdef printVector(arr): if (len(arr) != 1): # Traverse the vector arr for i in range(len(arr)): print(arr[i], end = " ") print() # Recursive function to print different# ways in which N can be written as# a sum of at 2 or more positive integersdef findWays(arr, i, n): # If n is zero then print this # ways of breaking numbers if (n == 0): printVector(arr) # Start from previous element # in the representation till n for j in range(i, n + 1): # Include current element # from representation arr.append(j) # Call function again # with reduced sum findWays(arr, j, n - j) # Backtrack to remove current # element from representation del arr[-1] # Driver Codeif __name__ == '__main__': # Given sum N n = 4 # To store the representation # of breaking N arr = [] # Function Call findWays(arr, 1, n) # This code is contributed by mohit kumar 29
// C# program for the above approachusing System;using System.Collections.Generic; class GFG{ // Function to print the values stored// in vector arrstatic void printList(List<int> arr){ if (arr.Count != 1) { // Traverse the vector arr for(int i = 0; i < arr.Count; i++) { Console.Write(arr[i] + " "); } Console.WriteLine(); }} // Recursive function to print different// ways in which N can be written as// a sum of at 2 or more positive integersstatic void findWays(List<int> arr, int i, int n){ // If n is zero then print this // ways of breaking numbers if (n == 0) printList(arr); // Start from previous element // in the representation till n for(int j = i; j <= n; j++) { // Include current element // from representation arr.Add(j); // Call function again // with reduced sum findWays(arr, j, n - j); // Backtrack to remove current // element from representation arr.RemoveAt(arr.Count - 1); }} // Driver codepublic static void Main(String[] args){ // Given sum N int n = 4; // To store the representation // of breaking N List<int> arr = new List<int>(); // Function call findWays(arr, 1, n);}} // This code is contributed by 29AjayKumar
<script> // Javascript program for the above approach // Function to print the values stored// in vector arrfunction printVector(arr){ if (arr.length != 1) { // Traverse the vector arr for (var i = 0; i < arr.length; i++) { document.write( arr[i] + " "); } document.write("<br>"); }} // Recursive function to print different// ways in which N can be written as// a sum of at 2 or more positive integersfunction findWays(arr, i, n){ // If n is zero then print this // ways of breaking numbers if (n == 0) printVector(arr); // Start from previous element // in the representation till n for (var j = i; j <= n; j++) { // Include current element // from representation arr.push(j); // Call function again // with reduced sum findWays(arr, j, n - j); // Backtrack to remove current // element from representation arr.pop(); }} // Driver Code// Given sum Nvar n = 4;// To store the representation// of breaking Nvar arr = [];// Function CallfindWays(arr, 1, n); </script>
1 1 1 1
1 1 2
1 3
2 2
Time Complexity: O(2N) Auxiliary Space: O(N2)
mohit kumar 29
offbeat
29AjayKumar
Code_Mech
itsok
simmytarika5
surinderdawra388
Algorithms-Backtracking
Algorithms-Recursion
Arrays
Backtracking
Greedy
Mathematical
Recursion
Arrays
Greedy
Mathematical
Recursion
Backtracking
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here. | [
{
"code": null,
"e": 54,
"s": 26,
"text": "\n02 Feb, 2022"
},
{
"code": null,
"e": 199,
"s": 54,
"text": "Given an integer N, the task is to print all the possible ways in which N can be written as the sum of two or more positive integers.Examples: "
},
{
"code": null,
"e": 275,
"s": 199,
"text": "Input: N = 4 Output: 1 1 1 1 1 1 2 1 3 2 2 Input: N = 3 Output: 1 1 1 1 2 "
},
{
"code": null,
"e": 598,
"s": 277,
"text": "Approach: The idea is to use recursion to solve this problem. The idea is to consider every integer from 1 to N such that the sum N can be reduced by this number at each recursive call and if at any recursive call N reduces to zero then we will print the answer stored in the vector. Below are the steps for recursion: "
},
{
"code": null,
"e": 727,
"s": 598,
"text": "Get the number N whose sum has to be broken into two or more positive integers.Recursively iterate from value 1 to N as index i:"
},
{
"code": null,
"e": 807,
"s": 727,
"text": "Get the number N whose sum has to be broken into two or more positive integers."
},
{
"code": null,
"e": 857,
"s": 807,
"text": "Recursively iterate from value 1 to N as index i:"
},
{
"code": null,
"e": 1012,
"s": 857,
"text": "Base Case: If the value called recursively is 0, then print the current vector as this is one of the ways to broke N into two or more positive integers. "
},
{
"code": null,
"e": 1046,
"s": 1012,
"text": "if (n == 0)\n printVector(arr);"
},
{
"code": null,
"e": 1300,
"s": 1046,
"text": "Recursive Call: If the base case is not met, then Recursively iterate from [i, N – i]. Push the current element j into vector(say arr) and recursively iterate for the next index and after this recursion ends then pop the element j inserted previously: "
},
{
"code": null,
"e": 1411,
"s": 1300,
"text": "for j in range[i, N]:\n arr.push_back(j);\n recursive_function(arr, j + 1, N - j);\n arr.pop_back(j); "
},
{
"code": null,
"e": 1463,
"s": 1411,
"text": "Below is the implementation of the above approach: "
},
{
"code": null,
"e": 1467,
"s": 1463,
"text": "C++"
},
{
"code": null,
"e": 1472,
"s": 1467,
"text": "Java"
},
{
"code": null,
"e": 1480,
"s": 1472,
"text": "Python3"
},
{
"code": null,
"e": 1483,
"s": 1480,
"text": "C#"
},
{
"code": null,
"e": 1494,
"s": 1483,
"text": "Javascript"
},
{
"code": "// C++ program for the above approach#include <bits/stdc++.h>using namespace std; // Function to print the values stored// in vector arrvoid printVector(vector<int>& arr){ if (arr.size() != 1) { // Traverse the vector arr for (int i = 0; i < arr.size(); i++) { cout << arr[i] << \" \"; } cout << endl; }} // Recursive function to print different// ways in which N can be written as// a sum of at 2 or more positive integersvoid findWays(vector<int>& arr, int i, int n){ // If n is zero then print this // ways of breaking numbers if (n == 0) printVector(arr); // Start from previous element // in the representation till n for (int j = i; j <= n; j++) { // Include current element // from representation arr.push_back(j); // Call function again // with reduced sum findWays(arr, j, n - j); // Backtrack to remove current // element from representation arr.pop_back(); }} // Driver Codeint main(){ // Given sum N int n = 4; // To store the representation // of breaking N vector<int> arr; // Function Call findWays(arr, 1, n); return 0;}",
"e": 2697,
"s": 1494,
"text": null
},
{
"code": "// Java program for the above approachimport java.util.*; class GFG{ // Function to print the values stored// in vector arrstatic void printVector(ArrayList<Integer> arr){ if (arr.size() != 1) { // Traverse the vector arr for(int i = 0; i < arr.size(); i++) { System.out.print(arr.get(i) + \" \"); } System.out.println(); }} // Recursive function to print different// ways in which N can be written as// a sum of at 2 or more positive integersstatic void findWays(ArrayList<Integer> arr, int i, int n){ // If n is zero then print this // ways of breaking numbers if (n == 0) printVector(arr); // Start from previous element // in the representation till n for(int j = i; j <= n; j++) { // Include current element // from representation arr.add(j); // Call function again // with reduced sum findWays(arr, j, n - j); // Backtrack to remove current // element from representation arr.remove(arr.size() - 1); }} // Driver codepublic static void main(String[] args){ // Given sum N int n = 4; // To store the representation // of breaking N ArrayList<Integer> arr = new ArrayList<Integer>(); // Function call findWays(arr, 1, n);}} // This code is contributed by offbeat",
"e": 4093,
"s": 2697,
"text": null
},
{
"code": "# Python3 program for the above approach # Function to print the values stored# in vector arrdef printVector(arr): if (len(arr) != 1): # Traverse the vector arr for i in range(len(arr)): print(arr[i], end = \" \") print() # Recursive function to print different# ways in which N can be written as# a sum of at 2 or more positive integersdef findWays(arr, i, n): # If n is zero then print this # ways of breaking numbers if (n == 0): printVector(arr) # Start from previous element # in the representation till n for j in range(i, n + 1): # Include current element # from representation arr.append(j) # Call function again # with reduced sum findWays(arr, j, n - j) # Backtrack to remove current # element from representation del arr[-1] # Driver Codeif __name__ == '__main__': # Given sum N n = 4 # To store the representation # of breaking N arr = [] # Function Call findWays(arr, 1, n) # This code is contributed by mohit kumar 29",
"e": 5188,
"s": 4093,
"text": null
},
{
"code": "// C# program for the above approachusing System;using System.Collections.Generic; class GFG{ // Function to print the values stored// in vector arrstatic void printList(List<int> arr){ if (arr.Count != 1) { // Traverse the vector arr for(int i = 0; i < arr.Count; i++) { Console.Write(arr[i] + \" \"); } Console.WriteLine(); }} // Recursive function to print different// ways in which N can be written as// a sum of at 2 or more positive integersstatic void findWays(List<int> arr, int i, int n){ // If n is zero then print this // ways of breaking numbers if (n == 0) printList(arr); // Start from previous element // in the representation till n for(int j = i; j <= n; j++) { // Include current element // from representation arr.Add(j); // Call function again // with reduced sum findWays(arr, j, n - j); // Backtrack to remove current // element from representation arr.RemoveAt(arr.Count - 1); }} // Driver codepublic static void Main(String[] args){ // Given sum N int n = 4; // To store the representation // of breaking N List<int> arr = new List<int>(); // Function call findWays(arr, 1, n);}} // This code is contributed by 29AjayKumar",
"e": 6564,
"s": 5188,
"text": null
},
{
"code": "<script> // Javascript program for the above approach // Function to print the values stored// in vector arrfunction printVector(arr){ if (arr.length != 1) { // Traverse the vector arr for (var i = 0; i < arr.length; i++) { document.write( arr[i] + \" \"); } document.write(\"<br>\"); }} // Recursive function to print different// ways in which N can be written as// a sum of at 2 or more positive integersfunction findWays(arr, i, n){ // If n is zero then print this // ways of breaking numbers if (n == 0) printVector(arr); // Start from previous element // in the representation till n for (var j = i; j <= n; j++) { // Include current element // from representation arr.push(j); // Call function again // with reduced sum findWays(arr, j, n - j); // Backtrack to remove current // element from representation arr.pop(); }} // Driver Code// Given sum Nvar n = 4;// To store the representation// of breaking Nvar arr = [];// Function CallfindWays(arr, 1, n); </script>",
"e": 7672,
"s": 6564,
"text": null
},
{
"code": null,
"e": 7697,
"s": 7672,
"text": "1 1 1 1 \n1 1 2 \n1 3 \n2 2"
},
{
"code": null,
"e": 7746,
"s": 7699,
"text": "Time Complexity: O(2N) Auxiliary Space: O(N2) "
},
{
"code": null,
"e": 7761,
"s": 7746,
"text": "mohit kumar 29"
},
{
"code": null,
"e": 7769,
"s": 7761,
"text": "offbeat"
},
{
"code": null,
"e": 7781,
"s": 7769,
"text": "29AjayKumar"
},
{
"code": null,
"e": 7791,
"s": 7781,
"text": "Code_Mech"
},
{
"code": null,
"e": 7797,
"s": 7791,
"text": "itsok"
},
{
"code": null,
"e": 7810,
"s": 7797,
"text": "simmytarika5"
},
{
"code": null,
"e": 7827,
"s": 7810,
"text": "surinderdawra388"
},
{
"code": null,
"e": 7851,
"s": 7827,
"text": "Algorithms-Backtracking"
},
{
"code": null,
"e": 7872,
"s": 7851,
"text": "Algorithms-Recursion"
},
{
"code": null,
"e": 7879,
"s": 7872,
"text": "Arrays"
},
{
"code": null,
"e": 7892,
"s": 7879,
"text": "Backtracking"
},
{
"code": null,
"e": 7899,
"s": 7892,
"text": "Greedy"
},
{
"code": null,
"e": 7912,
"s": 7899,
"text": "Mathematical"
},
{
"code": null,
"e": 7922,
"s": 7912,
"text": "Recursion"
},
{
"code": null,
"e": 7929,
"s": 7922,
"text": "Arrays"
},
{
"code": null,
"e": 7936,
"s": 7929,
"text": "Greedy"
},
{
"code": null,
"e": 7949,
"s": 7936,
"text": "Mathematical"
},
{
"code": null,
"e": 7959,
"s": 7949,
"text": "Recursion"
},
{
"code": null,
"e": 7972,
"s": 7959,
"text": "Backtracking"
}
] |
Convert a Binary Tree to Threaded binary tree | Set 2 (Efficient) | 07 Jul, 2022
Idea of Threaded Binary Tree is to make inorder traversal faster and do it without stack and without recursion. In a simple threaded binary tree, the NULL right pointers are used to store inorder successor. Where-ever a right pointer is NULL, it is used to store inorder successor.
Chapters
descriptions off, selected
captions settings, opens captions settings dialog
captions off, selected
English
This is a modal window.
Beginning of dialog window. Escape will cancel and close the window.
End of dialog window.
Following diagram shows an example Single Threaded Binary Tree. The dotted lines represent threads.
Following is structure of a single-threaded binary tree.
C
Java
Python3
C#
Javascript
struct Node{ int key; Node *left, *right; // Used to indicate whether the right pointer is a normal right // pointer or a pointer to inorder successor. bool isThreaded; };
static class Node{ int key; Node left, right; // Used to indicate whether the right pointer is a normal right // pointer or a pointer to inorder successor. boolean isThreaded; }; // This code is contributed by umadevi9616
class Node: def __init__(self, data): self.key = data; self.left = none; self.right = none; self.isThreaded = false; # Used to indicate whether the right pointer is a normal right # pointer or a pointer to inorder successor. # This code is contributed by umadevi9616
public class Node { public int key; public Node left, right; // Used to indicate whether the right pointer is a normal right // pointer or a pointer to inorder successor. public bool isThreaded;}; // This code is contributed by umadevi9616
/* structure of a node in threaded binary tree */ class Node { constructor(val) { this.data = val; this.left = null; this.right = null; // Used to indicate whether the right pointer // is a normal right pointer or a pointer // to inorder successor. this.isThreaded = false; } } // This code is contributed by famously.
How to convert a Given Binary Tree to Threaded Binary Tree?
We have discussed a Queue-based solution here. In this post, space-efficient solution is discussed that doesn’t require a queue.The idea is based on the fact that we link from inorder predecessor to a node. We link those inorder predecessor which lie in subtree of node. So we find inorder predecessor of a node if its left is not NULL. Inorder predecessor of a node (whose left is NULL) is a rightmost node in the left child. Once we find the predecessor, we link a thread from it to the current node.
Following is the implementation of the above idea.
C++
Java
Python3
C#
Javascript
/* C++ program to convert a Binary Tree to Threaded Tree */#include <bits/stdc++.h>using namespace std; /* Structure of a node in threaded binary tree */struct Node{ int key; Node *left, *right; // Used to indicate whether the right pointer // is a normal right pointer or a pointer // to inorder successor. bool isThreaded;}; // Converts tree with given root to threaded// binary tree.// This function returns rightmost child of// root.Node *createThreaded(Node *root){ // Base cases : Tree is empty or has single // node if (root == NULL) return NULL; if (root->left == NULL && root->right == NULL) return root; // Find predecessor if it exists if (root->left != NULL) { // Find predecessor of root (Rightmost // child in left subtree) Node* l = createThreaded(root->left); // Link a thread from predecessor to // root. l->right = root; l->isThreaded = true; } // If current node is rightmost child if (root->right == NULL) return root; // Recur for right subtree. return createThreaded(root->right);} // A utility function to find leftmost node// in a binary tree rooted with 'root'.// This function is used in inOrder()Node *leftMost(Node *root){ while (root != NULL && root->left != NULL) root = root->left; return root;} // Function to do inorder traversal of a threadded// binary treevoid inOrder(Node *root){ if (root == NULL) return; // Find the leftmost node in Binary Tree Node *cur = leftMost(root); while (cur != NULL) { cout << cur->key << " "; // If this Node is a thread Node, then go to // inorder successor if (cur->isThreaded) cur = cur->right; else // Else go to the leftmost child in right subtree cur = leftMost(cur->right); }} // A utility function to create a new nodeNode *newNode(int key){ Node *temp = new Node; temp->left = temp->right = NULL; temp->key = key; return temp;} // Driver program to test above functionsint main(){ /* 1 / \ 2 3 / \ / \ 4 5 6 7 */ Node *root = newNode(1); root->left = newNode(2); root->right = newNode(3); root->left->left = newNode(4); root->left->right = newNode(5); root->right->left = newNode(6); root->right->right = newNode(7); createThreaded(root); cout << "Inorder traversal of created " "threaded tree is\n"; inOrder(root); return 0;}
/* Java program to convert a Binary Tree to Threaded Tree */import java.util.*;class solution{ /* structure of a node in threaded binary tree */static class Node { int key; Node left, right; // Used to indicate whether the right pointer // is a normal right pointer or a pointer // to inorder successor. boolean isThreaded; }; // Converts tree with given root to threaded // binary tree. // This function returns rightmost child of // root. static Node createThreaded(Node root) { // Base cases : Tree is empty or has single // node if (root == null) return null; if (root.left == null && root.right == null) return root; // Find predecessor if it exists if (root.left != null) { // Find predecessor of root (Rightmost // child in left subtree) Node l = createThreaded(root.left); // Link a thread from predecessor to // root. l.right = root; l.isThreaded = true; } // If current node is rightmost child if (root.right == null) return root; // Recur for right subtree. return createThreaded(root.right); } // A utility function to find leftmost node // in a binary tree rooted with 'root'. // This function is used in inOrder() static Node leftMost(Node root) { while (root != null && root.left != null) root = root.left; return root; } // Function to do inorder traversal of a threadded // binary tree static void inOrder(Node root) { if (root == null) return; // Find the leftmost node in Binary Tree Node cur = leftMost(root); while (cur != null) { System.out.print(cur.key + " "); // If this Node is a thread Node, then go to // inorder successor if (cur.isThreaded) cur = cur.right; else // Else go to the leftmost child in right subtree cur = leftMost(cur.right); } } // A utility function to create a new node static Node newNode(int key) { Node temp = new Node(); temp.left = temp.right = null; temp.key = key; return temp; } // Driver program to test above functions public static void main(String args[]){ /* 1 / \ 2 3 / \ / \ 4 5 6 7 */ Node root = newNode(1); root.left = newNode(2); root.right = newNode(3); root.left.left = newNode(4); root.left.right = newNode(5); root.right.left = newNode(6); root.right.right = newNode(7); createThreaded(root); System.out.println("Inorder traversal of created "+"threaded tree is\n"); inOrder(root); } }//contributed by Arnab Kundu
# Python3 program to convert a Binary Tree to # Threaded Tree # A utility function to create a new node class newNode: def __init__(self, key): self.left = self.right = None self.key = key self.isThreaded = None # Converts tree with given root to threaded # binary tree. # This function returns rightmost child of # root. def createThreaded(root): # Base cases : Tree is empty or has # single node if root == None: return None if root.left == None and root.right == None: return root # Find predecessor if it exists if root.left != None: # Find predecessor of root (Rightmost # child in left subtree) l = createThreaded(root.left) # Link a thread from predecessor # to root. l.right = root l.isThreaded = True # If current node is rightmost child if root.right == None: return root # Recur for right subtree. return createThreaded(root.right) # A utility function to find leftmost node # in a binary tree rooted with 'root'. # This function is used in inOrder() def leftMost(root): while root != None and root.left != None: root = root.left return root # Function to do inorder traversal of a # threaded binary tree def inOrder(root): if root == None: return # Find the leftmost node in Binary Tree cur = leftMost(root) while cur != None: print(cur.key, end = " ") # If this Node is a thread Node, then # go to inorder successor if cur.isThreaded: cur = cur.right else: # Else go to the leftmost child # in right subtree cur = leftMost(cur.right) # Driver Codeif __name__ == '__main__': # 1 # / \ # 2 3 # / \ / \ # 4 5 6 7 root = newNode(1) root.left = newNode(2) root.right = newNode(3) root.left.left = newNode(4) root.left.right = newNode(5) root.right.left = newNode(6) root.right.right = newNode(7) createThreaded(root) print("Inorder traversal of created", "threaded tree is") inOrder(root) # This code is contributed by PranchalK
using System; /* C# program to convert a Binary Tree to Threaded Tree */public class solution{ /* structure of a node in threaded binary tree */public class Node{ public int key; public Node left, right; // Used to indicate whether the right pointer // is a normal right pointer or a pointer // to inorder successor. public bool isThreaded;} // Converts tree with given root to threaded // binary tree. // This function returns rightmost child of // root. public static Node createThreaded(Node root){ // Base cases : Tree is empty or has single // node if (root == null) { return null; } if (root.left == null && root.right == null) { return root; } // Find predecessor if it exists if (root.left != null) { // Find predecessor of root (Rightmost // child in left subtree) Node l = createThreaded(root.left); // Link a thread from predecessor to // root. l.right = root; l.isThreaded = true; } // If current node is rightmost child if (root.right == null) { return root; } // Recur for right subtree. return createThreaded(root.right);} // A utility function to find leftmost node // in a binary tree rooted with 'root'. // This function is used in inOrder() public static Node leftMost(Node root){ while (root != null && root.left != null) { root = root.left; } return root;} // Function to do inorder traversal of a threadded // binary tree public static void inOrder(Node root){ if (root == null) { return; } // Find the leftmost node in Binary Tree Node cur = leftMost(root); while (cur != null) { Console.Write(cur.key + " "); // If this Node is a thread Node, then go to // inorder successor if (cur.isThreaded) { cur = cur.right; } else // Else go to the leftmost child in right subtree { cur = leftMost(cur.right); } }} // A utility function to create a new node public static Node newNode(int key){ Node temp = new Node(); temp.left = temp.right = null; temp.key = key; return temp;} // Driver program to test above functions public static void Main(string[] args){ /* 1 / \ 2 3 / \ / \ 4 5 6 7 */ Node root = newNode(1); root.left = newNode(2); root.right = newNode(3); root.left.left = newNode(4); root.left.right = newNode(5); root.right.left = newNode(6); root.right.right = newNode(7); createThreaded(root); Console.WriteLine("Inorder traversal of created " + "threaded tree is\n"); inOrder(root);}} // This code is contributed by Shrikant13
<script>/* javascript program to convert a Binary Tree to Threaded Tree */ /* structure of a node in threaded binary tree */ class Node { constructor(val) { this.data = val; this.left = null; this.right = null; // Used to indicate whether the right pointer // is a normal right pointer or a pointer // to inorder successor. this.isThreaded = false; } } // Converts tree with given root to threaded // binary tree. // This function returns rightmost child of // root. function createThreaded(root) { // Base cases : Tree is empty or has single // node if (root == null) return null; if (root.left == null && root.right == null) return root; // Find predecessor if it exists if (root.left != null) { // Find predecessor of root (Rightmost // child in left subtree) var l = createThreaded(root.left); // Link a thread from predecessor to // root. l.right = root; l.isThreaded = true; } // If current node is rightmost child if (root.right == null) return root; // Recur for right subtree. return createThreaded(root.right); } // A utility function to find leftmost node // in a binary tree rooted with 'root'. // This function is used in inOrder() function leftMost(root) { while (root != null && root.left != null) root = root.left; return root; } // Function to do inorder traversal of a threadded // binary tree function inOrder(root) { if (root == null) return; // Find the leftmost node in Binary Tree var cur = leftMost(root); while (cur != null) { document.write(cur.key + " "); // If this Node is a thread Node, then go to // inorder successor if (cur.isThreaded) cur = cur.right; else // Else go to the leftmost child in right subtree cur = leftMost(cur.right); } } // A utility function to create a new node function newNode(key) { var temp = new Node(); temp.left = temp.right = null; temp.key = key; return temp; } // Driver program to test above functions /* 1 / \ 2 3 / \ / \ 4 5 6 7 */ var root = newNode(1); root.left = newNode(2); root.right = newNode(3); root.left.left = newNode(4); root.left.right = newNode(5); root.right.left = newNode(6); root.right.right = newNode(7); createThreaded(root); document.write("Inorder traversal of created "+"threaded tree is<br/>"); inOrder(root); // This code contributed by aashish1995</script>
Inorder traversal of created threaded tree is
4 2 5 1 6 3 7
Time complexity: O(n).space complexity: O(1).
This article is contributed by Gopal Agarwal. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks.
andrew1234
shrikanth13
PranchalKatiyar
Akanksha_Rai
aashish1995
famously
umadevi9616
hardikkoriintern
threaded-binary-tree
Tree
Tree
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Introduction to Data Structures
Introduction to Tree Data Structure
Inorder Tree Traversal without Recursion
What is Data Structure: Types, Classifications and Applications
Binary Tree | Set 3 (Types of Binary Tree)
A program to check if a binary tree is BST or not
Lowest Common Ancestor in a Binary Tree | Set 1
Binary Tree | Set 2 (Properties)
Diameter of a Binary Tree | [
{
"code": null,
"e": 54,
"s": 26,
"text": "\n07 Jul, 2022"
},
{
"code": null,
"e": 336,
"s": 54,
"text": "Idea of Threaded Binary Tree is to make inorder traversal faster and do it without stack and without recursion. In a simple threaded binary tree, the NULL right pointers are used to store inorder successor. Where-ever a right pointer is NULL, it is used to store inorder successor."
},
{
"code": null,
"e": 345,
"s": 336,
"text": "Chapters"
},
{
"code": null,
"e": 372,
"s": 345,
"text": "descriptions off, selected"
},
{
"code": null,
"e": 422,
"s": 372,
"text": "captions settings, opens captions settings dialog"
},
{
"code": null,
"e": 445,
"s": 422,
"text": "captions off, selected"
},
{
"code": null,
"e": 453,
"s": 445,
"text": "English"
},
{
"code": null,
"e": 477,
"s": 453,
"text": "This is a modal window."
},
{
"code": null,
"e": 546,
"s": 477,
"text": "Beginning of dialog window. Escape will cancel and close the window."
},
{
"code": null,
"e": 568,
"s": 546,
"text": "End of dialog window."
},
{
"code": null,
"e": 669,
"s": 568,
"text": "Following diagram shows an example Single Threaded Binary Tree. The dotted lines represent threads. "
},
{
"code": null,
"e": 727,
"s": 669,
"text": "Following is structure of a single-threaded binary tree. "
},
{
"code": null,
"e": 729,
"s": 727,
"text": "C"
},
{
"code": null,
"e": 734,
"s": 729,
"text": "Java"
},
{
"code": null,
"e": 742,
"s": 734,
"text": "Python3"
},
{
"code": null,
"e": 745,
"s": 742,
"text": "C#"
},
{
"code": null,
"e": 756,
"s": 745,
"text": "Javascript"
},
{
"code": "struct Node{ int key; Node *left, *right; // Used to indicate whether the right pointer is a normal right // pointer or a pointer to inorder successor. bool isThreaded; };",
"e": 946,
"s": 756,
"text": null
},
{
"code": "static class Node{ int key; Node left, right; // Used to indicate whether the right pointer is a normal right // pointer or a pointer to inorder successor. boolean isThreaded; }; // This code is contributed by umadevi9616",
"e": 1187,
"s": 946,
"text": null
},
{
"code": "class Node: def __init__(self, data): self.key = data; self.left = none; self.right = none; self.isThreaded = false; # Used to indicate whether the right pointer is a normal right # pointer or a pointer to inorder successor. # This code is contributed by umadevi9616 ",
"e": 1495,
"s": 1187,
"text": null
},
{
"code": "public class Node { public int key; public Node left, right; // Used to indicate whether the right pointer is a normal right // pointer or a pointer to inorder successor. public bool isThreaded;}; // This code is contributed by umadevi9616 ",
"e": 1756,
"s": 1495,
"text": null
},
{
"code": " /* structure of a node in threaded binary tree */ class Node { constructor(val) { this.data = val; this.left = null; this.right = null; // Used to indicate whether the right pointer // is a normal right pointer or a pointer // to inorder successor. this.isThreaded = false; } } // This code is contributed by famously.",
"e": 2159,
"s": 1756,
"text": null
},
{
"code": null,
"e": 2220,
"s": 2159,
"text": "How to convert a Given Binary Tree to Threaded Binary Tree? "
},
{
"code": null,
"e": 2724,
"s": 2220,
"text": "We have discussed a Queue-based solution here. In this post, space-efficient solution is discussed that doesn’t require a queue.The idea is based on the fact that we link from inorder predecessor to a node. We link those inorder predecessor which lie in subtree of node. So we find inorder predecessor of a node if its left is not NULL. Inorder predecessor of a node (whose left is NULL) is a rightmost node in the left child. Once we find the predecessor, we link a thread from it to the current node. "
},
{
"code": null,
"e": 2776,
"s": 2724,
"text": "Following is the implementation of the above idea. "
},
{
"code": null,
"e": 2780,
"s": 2776,
"text": "C++"
},
{
"code": null,
"e": 2785,
"s": 2780,
"text": "Java"
},
{
"code": null,
"e": 2793,
"s": 2785,
"text": "Python3"
},
{
"code": null,
"e": 2796,
"s": 2793,
"text": "C#"
},
{
"code": null,
"e": 2807,
"s": 2796,
"text": "Javascript"
},
{
"code": "/* C++ program to convert a Binary Tree to Threaded Tree */#include <bits/stdc++.h>using namespace std; /* Structure of a node in threaded binary tree */struct Node{ int key; Node *left, *right; // Used to indicate whether the right pointer // is a normal right pointer or a pointer // to inorder successor. bool isThreaded;}; // Converts tree with given root to threaded// binary tree.// This function returns rightmost child of// root.Node *createThreaded(Node *root){ // Base cases : Tree is empty or has single // node if (root == NULL) return NULL; if (root->left == NULL && root->right == NULL) return root; // Find predecessor if it exists if (root->left != NULL) { // Find predecessor of root (Rightmost // child in left subtree) Node* l = createThreaded(root->left); // Link a thread from predecessor to // root. l->right = root; l->isThreaded = true; } // If current node is rightmost child if (root->right == NULL) return root; // Recur for right subtree. return createThreaded(root->right);} // A utility function to find leftmost node// in a binary tree rooted with 'root'.// This function is used in inOrder()Node *leftMost(Node *root){ while (root != NULL && root->left != NULL) root = root->left; return root;} // Function to do inorder traversal of a threadded// binary treevoid inOrder(Node *root){ if (root == NULL) return; // Find the leftmost node in Binary Tree Node *cur = leftMost(root); while (cur != NULL) { cout << cur->key << \" \"; // If this Node is a thread Node, then go to // inorder successor if (cur->isThreaded) cur = cur->right; else // Else go to the leftmost child in right subtree cur = leftMost(cur->right); }} // A utility function to create a new nodeNode *newNode(int key){ Node *temp = new Node; temp->left = temp->right = NULL; temp->key = key; return temp;} // Driver program to test above functionsint main(){ /* 1 / \\ 2 3 / \\ / \\ 4 5 6 7 */ Node *root = newNode(1); root->left = newNode(2); root->right = newNode(3); root->left->left = newNode(4); root->left->right = newNode(5); root->right->left = newNode(6); root->right->right = newNode(7); createThreaded(root); cout << \"Inorder traversal of created \" \"threaded tree is\\n\"; inOrder(root); return 0;}",
"e": 5381,
"s": 2807,
"text": null
},
{
"code": "/* Java program to convert a Binary Tree to Threaded Tree */import java.util.*;class solution{ /* structure of a node in threaded binary tree */static class Node { int key; Node left, right; // Used to indicate whether the right pointer // is a normal right pointer or a pointer // to inorder successor. boolean isThreaded; }; // Converts tree with given root to threaded // binary tree. // This function returns rightmost child of // root. static Node createThreaded(Node root) { // Base cases : Tree is empty or has single // node if (root == null) return null; if (root.left == null && root.right == null) return root; // Find predecessor if it exists if (root.left != null) { // Find predecessor of root (Rightmost // child in left subtree) Node l = createThreaded(root.left); // Link a thread from predecessor to // root. l.right = root; l.isThreaded = true; } // If current node is rightmost child if (root.right == null) return root; // Recur for right subtree. return createThreaded(root.right); } // A utility function to find leftmost node // in a binary tree rooted with 'root'. // This function is used in inOrder() static Node leftMost(Node root) { while (root != null && root.left != null) root = root.left; return root; } // Function to do inorder traversal of a threadded // binary tree static void inOrder(Node root) { if (root == null) return; // Find the leftmost node in Binary Tree Node cur = leftMost(root); while (cur != null) { System.out.print(cur.key + \" \"); // If this Node is a thread Node, then go to // inorder successor if (cur.isThreaded) cur = cur.right; else // Else go to the leftmost child in right subtree cur = leftMost(cur.right); } } // A utility function to create a new node static Node newNode(int key) { Node temp = new Node(); temp.left = temp.right = null; temp.key = key; return temp; } // Driver program to test above functions public static void main(String args[]){ /* 1 / \\ 2 3 / \\ / \\ 4 5 6 7 */ Node root = newNode(1); root.left = newNode(2); root.right = newNode(3); root.left.left = newNode(4); root.left.right = newNode(5); root.right.left = newNode(6); root.right.right = newNode(7); createThreaded(root); System.out.println(\"Inorder traversal of created \"+\"threaded tree is\\n\"); inOrder(root); } }//contributed by Arnab Kundu",
"e": 8129,
"s": 5381,
"text": null
},
{
"code": "# Python3 program to convert a Binary Tree to # Threaded Tree # A utility function to create a new node class newNode: def __init__(self, key): self.left = self.right = None self.key = key self.isThreaded = None # Converts tree with given root to threaded # binary tree. # This function returns rightmost child of # root. def createThreaded(root): # Base cases : Tree is empty or has # single node if root == None: return None if root.left == None and root.right == None: return root # Find predecessor if it exists if root.left != None: # Find predecessor of root (Rightmost # child in left subtree) l = createThreaded(root.left) # Link a thread from predecessor # to root. l.right = root l.isThreaded = True # If current node is rightmost child if root.right == None: return root # Recur for right subtree. return createThreaded(root.right) # A utility function to find leftmost node # in a binary tree rooted with 'root'. # This function is used in inOrder() def leftMost(root): while root != None and root.left != None: root = root.left return root # Function to do inorder traversal of a # threaded binary tree def inOrder(root): if root == None: return # Find the leftmost node in Binary Tree cur = leftMost(root) while cur != None: print(cur.key, end = \" \") # If this Node is a thread Node, then # go to inorder successor if cur.isThreaded: cur = cur.right else: # Else go to the leftmost child # in right subtree cur = leftMost(cur.right) # Driver Codeif __name__ == '__main__': # 1 # / \\ # 2 3 # / \\ / \\ # 4 5 6 7 root = newNode(1) root.left = newNode(2) root.right = newNode(3) root.left.left = newNode(4) root.left.right = newNode(5) root.right.left = newNode(6) root.right.right = newNode(7) createThreaded(root) print(\"Inorder traversal of created\", \"threaded tree is\") inOrder(root) # This code is contributed by PranchalK",
"e": 10394,
"s": 8129,
"text": null
},
{
"code": "using System; /* C# program to convert a Binary Tree to Threaded Tree */public class solution{ /* structure of a node in threaded binary tree */public class Node{ public int key; public Node left, right; // Used to indicate whether the right pointer // is a normal right pointer or a pointer // to inorder successor. public bool isThreaded;} // Converts tree with given root to threaded // binary tree. // This function returns rightmost child of // root. public static Node createThreaded(Node root){ // Base cases : Tree is empty or has single // node if (root == null) { return null; } if (root.left == null && root.right == null) { return root; } // Find predecessor if it exists if (root.left != null) { // Find predecessor of root (Rightmost // child in left subtree) Node l = createThreaded(root.left); // Link a thread from predecessor to // root. l.right = root; l.isThreaded = true; } // If current node is rightmost child if (root.right == null) { return root; } // Recur for right subtree. return createThreaded(root.right);} // A utility function to find leftmost node // in a binary tree rooted with 'root'. // This function is used in inOrder() public static Node leftMost(Node root){ while (root != null && root.left != null) { root = root.left; } return root;} // Function to do inorder traversal of a threadded // binary tree public static void inOrder(Node root){ if (root == null) { return; } // Find the leftmost node in Binary Tree Node cur = leftMost(root); while (cur != null) { Console.Write(cur.key + \" \"); // If this Node is a thread Node, then go to // inorder successor if (cur.isThreaded) { cur = cur.right; } else // Else go to the leftmost child in right subtree { cur = leftMost(cur.right); } }} // A utility function to create a new node public static Node newNode(int key){ Node temp = new Node(); temp.left = temp.right = null; temp.key = key; return temp;} // Driver program to test above functions public static void Main(string[] args){ /* 1 / \\ 2 3 / \\ / \\ 4 5 6 7 */ Node root = newNode(1); root.left = newNode(2); root.right = newNode(3); root.left.left = newNode(4); root.left.right = newNode(5); root.right.left = newNode(6); root.right.right = newNode(7); createThreaded(root); Console.WriteLine(\"Inorder traversal of created \" + \"threaded tree is\\n\"); inOrder(root);}} // This code is contributed by Shrikant13",
"e": 13223,
"s": 10394,
"text": null
},
{
"code": "<script>/* javascript program to convert a Binary Tree to Threaded Tree */ /* structure of a node in threaded binary tree */ class Node { constructor(val) { this.data = val; this.left = null; this.right = null; // Used to indicate whether the right pointer // is a normal right pointer or a pointer // to inorder successor. this.isThreaded = false; } } // Converts tree with given root to threaded // binary tree. // This function returns rightmost child of // root. function createThreaded(root) { // Base cases : Tree is empty or has single // node if (root == null) return null; if (root.left == null && root.right == null) return root; // Find predecessor if it exists if (root.left != null) { // Find predecessor of root (Rightmost // child in left subtree) var l = createThreaded(root.left); // Link a thread from predecessor to // root. l.right = root; l.isThreaded = true; } // If current node is rightmost child if (root.right == null) return root; // Recur for right subtree. return createThreaded(root.right); } // A utility function to find leftmost node // in a binary tree rooted with 'root'. // This function is used in inOrder() function leftMost(root) { while (root != null && root.left != null) root = root.left; return root; } // Function to do inorder traversal of a threadded // binary tree function inOrder(root) { if (root == null) return; // Find the leftmost node in Binary Tree var cur = leftMost(root); while (cur != null) { document.write(cur.key + \" \"); // If this Node is a thread Node, then go to // inorder successor if (cur.isThreaded) cur = cur.right; else // Else go to the leftmost child in right subtree cur = leftMost(cur.right); } } // A utility function to create a new node function newNode(key) { var temp = new Node(); temp.left = temp.right = null; temp.key = key; return temp; } // Driver program to test above functions /* 1 / \\ 2 3 / \\ / \\ 4 5 6 7 */ var root = newNode(1); root.left = newNode(2); root.right = newNode(3); root.left.left = newNode(4); root.left.right = newNode(5); root.right.left = newNode(6); root.right.right = newNode(7); createThreaded(root); document.write(\"Inorder traversal of created \"+\"threaded tree is<br/>\"); inOrder(root); // This code contributed by aashish1995</script>",
"e": 15982,
"s": 13223,
"text": null
},
{
"code": null,
"e": 16043,
"s": 15982,
"text": "Inorder traversal of created threaded tree is\n4 2 5 1 6 3 7 "
},
{
"code": null,
"e": 16089,
"s": 16043,
"text": "Time complexity: O(n).space complexity: O(1)."
},
{
"code": null,
"e": 16387,
"s": 16089,
"text": "This article is contributed by Gopal Agarwal. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks. "
},
{
"code": null,
"e": 16398,
"s": 16387,
"text": "andrew1234"
},
{
"code": null,
"e": 16410,
"s": 16398,
"text": "shrikanth13"
},
{
"code": null,
"e": 16426,
"s": 16410,
"text": "PranchalKatiyar"
},
{
"code": null,
"e": 16439,
"s": 16426,
"text": "Akanksha_Rai"
},
{
"code": null,
"e": 16451,
"s": 16439,
"text": "aashish1995"
},
{
"code": null,
"e": 16460,
"s": 16451,
"text": "famously"
},
{
"code": null,
"e": 16472,
"s": 16460,
"text": "umadevi9616"
},
{
"code": null,
"e": 16489,
"s": 16472,
"text": "hardikkoriintern"
},
{
"code": null,
"e": 16510,
"s": 16489,
"text": "threaded-binary-tree"
},
{
"code": null,
"e": 16515,
"s": 16510,
"text": "Tree"
},
{
"code": null,
"e": 16520,
"s": 16515,
"text": "Tree"
},
{
"code": null,
"e": 16618,
"s": 16520,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 16650,
"s": 16618,
"text": "Introduction to Data Structures"
},
{
"code": null,
"e": 16686,
"s": 16650,
"text": "Introduction to Tree Data Structure"
},
{
"code": null,
"e": 16727,
"s": 16686,
"text": "Inorder Tree Traversal without Recursion"
},
{
"code": null,
"e": 16791,
"s": 16727,
"text": "What is Data Structure: Types, Classifications and Applications"
},
{
"code": null,
"e": 16834,
"s": 16791,
"text": "Binary Tree | Set 3 (Types of Binary Tree)"
},
{
"code": null,
"e": 16884,
"s": 16834,
"text": "A program to check if a binary tree is BST or not"
},
{
"code": null,
"e": 16932,
"s": 16884,
"text": "Lowest Common Ancestor in a Binary Tree | Set 1"
},
{
"code": null,
"e": 16965,
"s": 16932,
"text": "Binary Tree | Set 2 (Properties)"
}
] |
SVG Path Element | 15 Jul, 2020
SVG stands for Scalable Vector Graphic. The SVG element path is used to define a path that starts from a position and ends to a particular position. SVG path can be used to create any basic shapes.
Syntax:
<path d="Shape of path using keyword like M, L, C etc."
pathLength="Length of path"
stroke="stroke color name"
fill="color name">
</path>
Attributes: This element accepts four attributes as mentioned above and described below:
d: It is used to define the shape of the path.M: It is used for moving a point to a certain location.L: It is used for making a line to a point.C: It is used for making a curve to a point.
M: It is used for moving a point to a certain location.
L: It is used for making a line to a point.
C: It is used for making a curve to a point.
pathLength: It is used to define the total length of the path.
stroke: It is used to define the stroke color.
fill: It is used to define the filling color of the SVG.
Few examples are given below for better understanding of the <path> SVG element.
Example 1:
HTML
<!DOCTYPE html><html lang="en"><head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Document</title></head><body> <svg viewBox="500 500 "> <!--Moving point to M10 10 200 200 making a line to 10 200 200 10 --> <path d="M 10 10 200 200 L 10 200 L200 10"> </path> </svg></body></html>
Output:
Example 2:
HTML
<!DOCTYPE html><html lang="en"><head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Document</title></head><body> <h1 style="color:green">GeeksforGeeks SVG Path</h1> <svg viewBox="500 500"> // Creating a rectangle starting point is 10, 10 // Making a line to 10 100 // Moving point to 10 100 // Making line to 100 100 // Moving point to 100 100 // Making line to 100 10 // Moving point to 100 10 // Making line to 10 10 --> <path d="M 10 10 L10 100 M10 100 L100 100 M100 100 L100 10 M100 10 L10 10" stroke="black"> </path> </svg></body></html>
Output:
HTML-Misc
HTML
Web Technologies
HTML
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
REST API (Introduction)
Design a Tribute Page using HTML & CSS
Build a Survey Form using HTML and CSS
Design a web page using HTML and CSS
Angular File Upload
Installation of Node.js on Linux
Difference between var, let and const keywords in JavaScript
How to fetch data from an API in ReactJS ?
Differences between Functional Components and Class Components in React
Remove elements from a JavaScript Array | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n15 Jul, 2020"
},
{
"code": null,
"e": 226,
"s": 28,
"text": "SVG stands for Scalable Vector Graphic. The SVG element path is used to define a path that starts from a position and ends to a particular position. SVG path can be used to create any basic shapes."
},
{
"code": null,
"e": 234,
"s": 226,
"text": "Syntax:"
},
{
"code": null,
"e": 391,
"s": 234,
"text": "<path d=\"Shape of path using keyword like M, L, C etc.\"\n pathLength=\"Length of path\"\n stroke=\"stroke color name\"\n fill=\"color name\">\n</path>\n"
},
{
"code": null,
"e": 480,
"s": 391,
"text": "Attributes: This element accepts four attributes as mentioned above and described below:"
},
{
"code": null,
"e": 669,
"s": 480,
"text": "d: It is used to define the shape of the path.M: It is used for moving a point to a certain location.L: It is used for making a line to a point.C: It is used for making a curve to a point."
},
{
"code": null,
"e": 725,
"s": 669,
"text": "M: It is used for moving a point to a certain location."
},
{
"code": null,
"e": 769,
"s": 725,
"text": "L: It is used for making a line to a point."
},
{
"code": null,
"e": 814,
"s": 769,
"text": "C: It is used for making a curve to a point."
},
{
"code": null,
"e": 877,
"s": 814,
"text": "pathLength: It is used to define the total length of the path."
},
{
"code": null,
"e": 924,
"s": 877,
"text": "stroke: It is used to define the stroke color."
},
{
"code": null,
"e": 981,
"s": 924,
"text": "fill: It is used to define the filling color of the SVG."
},
{
"code": null,
"e": 1062,
"s": 981,
"text": "Few examples are given below for better understanding of the <path> SVG element."
},
{
"code": null,
"e": 1073,
"s": 1062,
"text": "Example 1:"
},
{
"code": null,
"e": 1078,
"s": 1073,
"text": "HTML"
},
{
"code": "<!DOCTYPE html><html lang=\"en\"><head> <meta charset=\"UTF-8\"> <meta name=\"viewport\" content=\"width=device-width, initial-scale=1.0\"> <title>Document</title></head><body> <svg viewBox=\"500 500 \"> <!--Moving point to M10 10 200 200 making a line to 10 200 200 10 --> <path d=\"M 10 10 200 200 L 10 200 L200 10\"> </path> </svg></body></html>",
"e": 1440,
"s": 1078,
"text": null
},
{
"code": null,
"e": 1448,
"s": 1440,
"text": "Output:"
},
{
"code": null,
"e": 1459,
"s": 1448,
"text": "Example 2:"
},
{
"code": null,
"e": 1464,
"s": 1459,
"text": "HTML"
},
{
"code": "<!DOCTYPE html><html lang=\"en\"><head> <meta charset=\"UTF-8\"> <meta name=\"viewport\" content=\"width=device-width, initial-scale=1.0\"> <title>Document</title></head><body> <h1 style=\"color:green\">GeeksforGeeks SVG Path</h1> <svg viewBox=\"500 500\"> // Creating a rectangle starting point is 10, 10 // Making a line to 10 100 // Moving point to 10 100 // Making line to 100 100 // Moving point to 100 100 // Making line to 100 10 // Moving point to 100 10 // Making line to 10 10 --> <path d=\"M 10 10 L10 100 M10 100 L100 100 M100 100 L100 10 M100 10 L10 10\" stroke=\"black\"> </path> </svg></body></html>",
"e": 2119,
"s": 1464,
"text": null
},
{
"code": null,
"e": 2127,
"s": 2119,
"text": "Output:"
},
{
"code": null,
"e": 2137,
"s": 2127,
"text": "HTML-Misc"
},
{
"code": null,
"e": 2142,
"s": 2137,
"text": "HTML"
},
{
"code": null,
"e": 2159,
"s": 2142,
"text": "Web Technologies"
},
{
"code": null,
"e": 2164,
"s": 2159,
"text": "HTML"
},
{
"code": null,
"e": 2262,
"s": 2164,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 2286,
"s": 2262,
"text": "REST API (Introduction)"
},
{
"code": null,
"e": 2325,
"s": 2286,
"text": "Design a Tribute Page using HTML & CSS"
},
{
"code": null,
"e": 2364,
"s": 2325,
"text": "Build a Survey Form using HTML and CSS"
},
{
"code": null,
"e": 2401,
"s": 2364,
"text": "Design a web page using HTML and CSS"
},
{
"code": null,
"e": 2421,
"s": 2401,
"text": "Angular File Upload"
},
{
"code": null,
"e": 2454,
"s": 2421,
"text": "Installation of Node.js on Linux"
},
{
"code": null,
"e": 2515,
"s": 2454,
"text": "Difference between var, let and const keywords in JavaScript"
},
{
"code": null,
"e": 2558,
"s": 2515,
"text": "How to fetch data from an API in ReactJS ?"
},
{
"code": null,
"e": 2630,
"s": 2558,
"text": "Differences between Functional Components and Class Components in React"
}
] |
Queries to check whether a given digit is present in the given Range in C++ | In this problem, we have given an array arr[] and some queries each consisting of three values, L and R, and val. Our task is to create a program to solve Queries to check whether a given digit is present in the given Range in C++.
To solve each query, we need to check if the given element val is present in the given Range between L and R or not.
Let’s take an example to understand the problem,
Input:arr[] = {4, 8, 1, 7, 2, 9, 3, 5, 1}
Q = 3
query = {{1, 4, 3}, {0, 2, 1}, {4, 7, 2 }}
Output: Not Present
Present
Present
Query 1: range is [1, 4], subarray = {8, 1, 7, 2}. 3 is not present in this subarray.
Query 2: range is [0, 2], subarray = {4, 8, 1}. 1 is present in this subarray.
Query 1: range is [4, 7], subarray = {2, 9, 3, 5, 1}. 2 is present in this subarray.
A simple way to solve the problem is by traversing the subarray and checking whether the given element is present in the range.
Live Demo
#include <iostream>
using namespace std;
bool isElementPresent(int arr[], int L, int R, int val){
for(int i = L; i <= R; i++ ){
if(arr[i] == val){
return true;
}
}
return false;
}
int main(){
int arr[] = {4, 8, 1, 7, 2, 9, 3, 5, 1};
int Q = 3;
int query[Q][3] = {{1, 4, 3}, {0, 2, 1}, {4, 7, 2 }};
for(int i = 0; i < Q; i++){
cout<<"For Query "<<(i+1);
if(isElementPresent(arr, query[i][0], query[i][1], query[i][2]))
cout<<": The given digit "<<query[i][2]<<" is present in the given range\n";
else
cout<<": The given digit "<<query[i][2]<<" is not present in the given range\n";
}
return 0;
}
For Query 1: The given digit 3 is not present in the given range
For Query 2: The given digit 1 is present in the given range
For Query 3: The given digit 2 is present in the given range
This is approach uses a loop, hence has a time complexity of the order O(Q * N). Where Q is the number of queries.
A better solution approach could be using a segment Tree to store all possible digits (0 - 9). To avoid duplicate elements in the node we will be using the set data structure (it has a property to eliminate duplicate elements). This will help us reduce the total number of elements in each node to a maximum of 10.
Then, for the query, we will check if the element is present or not in the given range.
Live Demo
#include <bits/stdc++.h>
using namespace std;
set<int> SegTree[36];
void buildSegmentTree(int* arr, int index, int start, int end) {
if (start == end) {
SegTree[index].insert(arr[start]);
return;
}
int middleEle = (start + end) >> 1;
buildSegmentTree(arr, 2 * index, start, middleEle);
buildSegmentTree(arr, 2 * index + 1, middleEle + 1, end);
for (auto it : SegTree[2 * index])
SegTree[index].insert(it);
for (auto it : SegTree[2 * index + 1])
SegTree[index].insert(it);
}
bool isElementPresent(int index, int start, int end, int L, int R, int val){
if (L <= start && end <= R) {
if (SegTree[index].count(val) != 0) {
return true;
}
else
return false;
}
if (R < start || end < L) {
return false;
}
int middleEle = (start + end) >> 1;
bool isPresentInLeftSubArray = isElementPresent((2 * index), start,middleEle, L, R, val);
bool isPresentInRightSubArray = isElementPresent((2 * index + 1),(middleEle + 1), end, L, R, val);
return isPresentInLeftSubArray or isPresentInRightSubArray;
}
int main(){
int arr[] = {4, 8, 1, 7, 2, 9, 3, 5, 1};
int n = sizeof(arr)/sizeof(arr[0]);
int Q = 3;
int query[Q][3] = {{1, 4, 3}, {0, 2, 1}, {4, 7, 2 }};
buildSegmentTree(arr, 1, 0, (n - 1));
for(int i = 0; i < Q; i++){
cout<<"For Query "<<(i+1);
if(isElementPresent(1, 0, (n - 1), query[i][0], query[i][1], query[i][2]))
cout<<": The given digit "<<query[i][2]<<" is present in the given
range\n";
else
cout<<": The given digit "<<query[i][2]<<" is not present in the given range\n";
}
return 0;
}
For Query 1: The given digit 3 is not present in the given range
For Query 2: The given digit 1 is present in the given range
For Query 3: The given digit 2 is present in the given range | [
{
"code": null,
"e": 1419,
"s": 1187,
"text": "In this problem, we have given an array arr[] and some queries each consisting of three values, L and R, and val. Our task is to create a program to solve Queries to check whether a given digit is present in the given Range in C++."
},
{
"code": null,
"e": 1536,
"s": 1419,
"text": "To solve each query, we need to check if the given element val is present in the given Range between L and R or not."
},
{
"code": null,
"e": 1585,
"s": 1536,
"text": "Let’s take an example to understand the problem,"
},
{
"code": null,
"e": 1627,
"s": 1585,
"text": "Input:arr[] = {4, 8, 1, 7, 2, 9, 3, 5, 1}"
},
{
"code": null,
"e": 1633,
"s": 1627,
"text": "Q = 3"
},
{
"code": null,
"e": 1676,
"s": 1633,
"text": "query = {{1, 4, 3}, {0, 2, 1}, {4, 7, 2 }}"
},
{
"code": null,
"e": 1696,
"s": 1676,
"text": "Output: Not Present"
},
{
"code": null,
"e": 1704,
"s": 1696,
"text": "Present"
},
{
"code": null,
"e": 1712,
"s": 1704,
"text": "Present"
},
{
"code": null,
"e": 1798,
"s": 1712,
"text": "Query 1: range is [1, 4], subarray = {8, 1, 7, 2}. 3 is not present in this subarray."
},
{
"code": null,
"e": 1877,
"s": 1798,
"text": "Query 2: range is [0, 2], subarray = {4, 8, 1}. 1 is present in this subarray."
},
{
"code": null,
"e": 1962,
"s": 1877,
"text": "Query 1: range is [4, 7], subarray = {2, 9, 3, 5, 1}. 2 is present in this subarray."
},
{
"code": null,
"e": 2090,
"s": 1962,
"text": "A simple way to solve the problem is by traversing the subarray and checking whether the given element is present in the range."
},
{
"code": null,
"e": 2101,
"s": 2090,
"text": " Live Demo"
},
{
"code": null,
"e": 2780,
"s": 2101,
"text": "#include <iostream>\nusing namespace std;\nbool isElementPresent(int arr[], int L, int R, int val){\n for(int i = L; i <= R; i++ ){\n if(arr[i] == val){\n return true;\n }\n }\n return false;\n}\nint main(){\n int arr[] = {4, 8, 1, 7, 2, 9, 3, 5, 1};\n int Q = 3;\n int query[Q][3] = {{1, 4, 3}, {0, 2, 1}, {4, 7, 2 }};\n for(int i = 0; i < Q; i++){\n cout<<\"For Query \"<<(i+1);\n if(isElementPresent(arr, query[i][0], query[i][1], query[i][2]))\n cout<<\": The given digit \"<<query[i][2]<<\" is present in the given range\\n\";\n else\n cout<<\": The given digit \"<<query[i][2]<<\" is not present in the given range\\n\";\n }\n return 0;\n}"
},
{
"code": null,
"e": 2967,
"s": 2780,
"text": "For Query 1: The given digit 3 is not present in the given range\nFor Query 2: The given digit 1 is present in the given range\nFor Query 3: The given digit 2 is present in the given range"
},
{
"code": null,
"e": 3082,
"s": 2967,
"text": "This is approach uses a loop, hence has a time complexity of the order O(Q * N). Where Q is the number of queries."
},
{
"code": null,
"e": 3397,
"s": 3082,
"text": "A better solution approach could be using a segment Tree to store all possible digits (0 - 9). To avoid duplicate elements in the node we will be using the set data structure (it has a property to eliminate duplicate elements). This will help us reduce the total number of elements in each node to a maximum of 10."
},
{
"code": null,
"e": 3485,
"s": 3397,
"text": "Then, for the query, we will check if the element is present or not in the given range."
},
{
"code": null,
"e": 3496,
"s": 3485,
"text": " Live Demo"
},
{
"code": null,
"e": 5164,
"s": 3496,
"text": "#include <bits/stdc++.h>\nusing namespace std;\nset<int> SegTree[36];\nvoid buildSegmentTree(int* arr, int index, int start, int end) {\n if (start == end) {\n SegTree[index].insert(arr[start]);\n return;\n }\n int middleEle = (start + end) >> 1;\n buildSegmentTree(arr, 2 * index, start, middleEle);\n buildSegmentTree(arr, 2 * index + 1, middleEle + 1, end);\n for (auto it : SegTree[2 * index])\n SegTree[index].insert(it);\n for (auto it : SegTree[2 * index + 1])\n SegTree[index].insert(it);\n}\nbool isElementPresent(int index, int start, int end, int L, int R, int val){\n if (L <= start && end <= R) {\n if (SegTree[index].count(val) != 0) {\n return true;\n }\n else\n return false;\n }\n if (R < start || end < L) {\n return false;\n }\n int middleEle = (start + end) >> 1;\n bool isPresentInLeftSubArray = isElementPresent((2 * index), start,middleEle, L, R, val);\n bool isPresentInRightSubArray = isElementPresent((2 * index + 1),(middleEle + 1), end, L, R, val);\n return isPresentInLeftSubArray or isPresentInRightSubArray;\n}\nint main(){\n int arr[] = {4, 8, 1, 7, 2, 9, 3, 5, 1};\n int n = sizeof(arr)/sizeof(arr[0]);\n int Q = 3;\n int query[Q][3] = {{1, 4, 3}, {0, 2, 1}, {4, 7, 2 }};\n buildSegmentTree(arr, 1, 0, (n - 1));\n for(int i = 0; i < Q; i++){\n cout<<\"For Query \"<<(i+1);\n if(isElementPresent(1, 0, (n - 1), query[i][0], query[i][1], query[i][2]))\n cout<<\": The given digit \"<<query[i][2]<<\" is present in the given\n range\\n\";\n else\n cout<<\": The given digit \"<<query[i][2]<<\" is not present in the given range\\n\";\n }\n return 0;\n}"
},
{
"code": null,
"e": 5351,
"s": 5164,
"text": "For Query 1: The given digit 3 is not present in the given range\nFor Query 2: The given digit 1 is present in the given range\nFor Query 3: The given digit 2 is present in the given range"
}
] |
How to convert CSV string file to a 2D array of objects using JavaScript ? | 11 Apr, 2022
A CSV is a comma-separated values file with a .csv extension, which allows data to be saved in a tabular format.
In this article, we will learn to convert the data of a CSV string to a 2D array of objects, where the first row of the string is the title row using JavaScript.
Given a comma-separated values (CSV) string to a 2D array, using JS.f
Input: 'Name,Roll Number\nRohan,01\nAryan,02'
Output: [
{Name: "Rohan", Roll Number: "01"},
{Name: "Aryan", Roll Number: "02"}
]
// With delimiter ;
Input: 'Name;Roll Number\nRohan;01\nAryan;02'
Output: [
{Name: "Rohan", Roll Number: "01"},
{Name: "Aryan", Roll Number: "02"}
]
We must know some array and string prototype functions that will be helpful in this regard.
indexOf function: The String.prototype.indexOf() function finds the index of the first occurrence of the argument string in the given string and the value returned is in 0 based index.
Example:
str = 'How\nare\nyou?'
str.indexOf('\n');
Output:
3
Slice function: The Array.prototype.slice() method returns a new array containing a portion of the array on which it is implemented and the original array remains the same.
Example:
['a','b','c','d'].slice(1)
Output:
['b','c','d']
Map function: The Array.prototype.map() method returns a new array with the results of calling a provided function on every element.
Example:
arr = [2, 4, 8, 16]
// Dividing each element of the array by 2
newArr = arr.map( item => item/2)
Output:
[1, 2, 4, 8]
Split function: The String.prototype.split() method is used to split the given string into an array of strings by separating it into substrings using a specified separator provided in the argument.
Example:
str = "Geeks for Geeks"
// Split the array when ' ' is located
arr = str.split(' ');
Output:
[ 'Geeks', 'for', 'Geeks' ]
Reduce function: The Array.prototype.reduce() method in JavaScript is used to reduce the array to a single value and executes a provided function for each element of the array from left to right and the return value of the function is stored in an accumulator.
Example:
arr = [2,4,6,8]
// Here 0 is the initial value of the accumulator
// while traversing, currentValue has been added
arr.reduce(function(accumulator,currentValue){
return accumulator+currentValue;
},0)
Output:
20
Approach:
The JavaScript string slice() method extracts parts of a string and returns the extracted parts in a new string taking ‘\n’ as the first occurrence.
Data Values are stored using “\n” as the delimiter.
JavaScript map() function will iterate over all values of title values array and append each object at the end of the array
The “storeKeyValue” variable is used to store each key with its respective values.
Example:
Javascript
<script> function CSVstring_to_Array(data, delimiter = ',') { /* This variable will collect all the titles from the data variable ["Name", "Roll Number"] */ const titles = data.slice(0, data .indexOf('\n')).split(delimiter); /* This variable will store the values from the data [ 'Rohan,01', 'Aryan,02' ] */ const titleValues = data.slice(data .indexOf('\n') + 1).split('\n'); /* Map function will iterate over all values of title values array and append each object at the end of the array */ const ansArray = titleValues.map(function (v) { /* Values variable will store individual title values [ 'Rohan', '01' ] */ const values = v.split(delimiter); /* storeKeyValue variable will store object containing each title with their respective values i.e { Name: 'Rohan', 'Roll Number': '01' } */ const storeKeyValue = titles.reduce( function (obj, title, index) { obj[title] = values[index]; return obj; }, {}); return storeKeyValue; }); return ansArray; }; var inputString1 = "Name,Roll Number\nRohan,01\nAryan,02"; console.log(CSVstring_to_Array(inputString1)); var inputString2 = "Name;Roll Number\nRohan;01\nAryan;02"; console.log(CSVstring_to_Array(inputString2,';'));</script>
Output:
saurabh1990aror
arorakashish0911
CSV
javascript-array
JavaScript-Methods
JavaScript-Questions
Picked
JavaScript
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Difference between var, let and const keywords in JavaScript
Remove elements from a JavaScript Array
JavaScript String includes() Method
Implementation of LinkedList in Javascript
DOM (Document Object Model)
Installation of Node.js on Linux
How to insert spaces/tabs in text using HTML/CSS?
Top 10 Projects For Beginners To Practice HTML and CSS Skills
How to create footer to stay at the bottom of a Web page?
How to set the default value for an HTML <select> element ? | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n11 Apr, 2022"
},
{
"code": null,
"e": 142,
"s": 28,
"text": "A CSV is a comma-separated values file with a .csv extension, which allows data to be saved in a tabular format. "
},
{
"code": null,
"e": 304,
"s": 142,
"text": "In this article, we will learn to convert the data of a CSV string to a 2D array of objects, where the first row of the string is the title row using JavaScript."
},
{
"code": null,
"e": 374,
"s": 304,
"text": "Given a comma-separated values (CSV) string to a 2D array, using JS.f"
},
{
"code": null,
"e": 749,
"s": 374,
"text": "Input: 'Name,Roll Number\\nRohan,01\\nAryan,02' \n\nOutput: [\n {Name: \"Rohan\", Roll Number: \"01\"},\n {Name: \"Aryan\", Roll Number: \"02\"}\n ]\n// With delimiter ; \n \nInput: 'Name;Roll Number\\nRohan;01\\nAryan;02' \n \nOutput: [\n {Name: \"Rohan\", Roll Number: \"01\"},\n {Name: \"Aryan\", Roll Number: \"02\"}\n ] "
},
{
"code": null,
"e": 841,
"s": 749,
"text": "We must know some array and string prototype functions that will be helpful in this regard."
},
{
"code": null,
"e": 1026,
"s": 841,
"text": "indexOf function: The String.prototype.indexOf() function finds the index of the first occurrence of the argument string in the given string and the value returned is in 0 based index."
},
{
"code": null,
"e": 1035,
"s": 1026,
"text": "Example:"
},
{
"code": null,
"e": 1079,
"s": 1035,
"text": "str = 'How\\nare\\nyou?' \n\nstr.indexOf('\\n');"
},
{
"code": null,
"e": 1087,
"s": 1079,
"text": "Output:"
},
{
"code": null,
"e": 1089,
"s": 1087,
"text": "3"
},
{
"code": null,
"e": 1262,
"s": 1089,
"text": "Slice function: The Array.prototype.slice() method returns a new array containing a portion of the array on which it is implemented and the original array remains the same."
},
{
"code": null,
"e": 1272,
"s": 1262,
"text": "Example: "
},
{
"code": null,
"e": 1299,
"s": 1272,
"text": "['a','b','c','d'].slice(1)"
},
{
"code": null,
"e": 1307,
"s": 1299,
"text": "Output:"
},
{
"code": null,
"e": 1322,
"s": 1307,
"text": " ['b','c','d']"
},
{
"code": null,
"e": 1455,
"s": 1322,
"text": "Map function: The Array.prototype.map() method returns a new array with the results of calling a provided function on every element."
},
{
"code": null,
"e": 1464,
"s": 1455,
"text": "Example:"
},
{
"code": null,
"e": 1563,
"s": 1464,
"text": "arr = [2, 4, 8, 16]\n\n// Dividing each element of the array by 2\nnewArr = arr.map( item => item/2) "
},
{
"code": null,
"e": 1571,
"s": 1563,
"text": "Output:"
},
{
"code": null,
"e": 1584,
"s": 1571,
"text": "[1, 2, 4, 8]"
},
{
"code": null,
"e": 1782,
"s": 1584,
"text": "Split function: The String.prototype.split() method is used to split the given string into an array of strings by separating it into substrings using a specified separator provided in the argument."
},
{
"code": null,
"e": 1791,
"s": 1782,
"text": "Example:"
},
{
"code": null,
"e": 1877,
"s": 1791,
"text": "str = \"Geeks for Geeks\"\n\n// Split the array when ' ' is located\narr = str.split(' ');"
},
{
"code": null,
"e": 1885,
"s": 1877,
"text": "Output:"
},
{
"code": null,
"e": 1913,
"s": 1885,
"text": "[ 'Geeks', 'for', 'Geeks' ]"
},
{
"code": null,
"e": 2174,
"s": 1913,
"text": "Reduce function: The Array.prototype.reduce() method in JavaScript is used to reduce the array to a single value and executes a provided function for each element of the array from left to right and the return value of the function is stored in an accumulator."
},
{
"code": null,
"e": 2183,
"s": 2174,
"text": "Example:"
},
{
"code": null,
"e": 2397,
"s": 2183,
"text": " arr = [2,4,6,8]\n \n // Here 0 is the initial value of the accumulator\n // while traversing, currentValue has been added\n \n arr.reduce(function(accumulator,currentValue){\n return accumulator+currentValue;\n },0)"
},
{
"code": null,
"e": 2405,
"s": 2397,
"text": "Output:"
},
{
"code": null,
"e": 2408,
"s": 2405,
"text": "20"
},
{
"code": null,
"e": 2418,
"s": 2408,
"text": "Approach:"
},
{
"code": null,
"e": 2567,
"s": 2418,
"text": "The JavaScript string slice() method extracts parts of a string and returns the extracted parts in a new string taking ‘\\n’ as the first occurrence."
},
{
"code": null,
"e": 2619,
"s": 2567,
"text": "Data Values are stored using “\\n” as the delimiter."
},
{
"code": null,
"e": 2743,
"s": 2619,
"text": "JavaScript map() function will iterate over all values of title values array and append each object at the end of the array"
},
{
"code": null,
"e": 2826,
"s": 2743,
"text": "The “storeKeyValue” variable is used to store each key with its respective values."
},
{
"code": null,
"e": 2835,
"s": 2826,
"text": "Example:"
},
{
"code": null,
"e": 2846,
"s": 2835,
"text": "Javascript"
},
{
"code": "<script> function CSVstring_to_Array(data, delimiter = ',') { /* This variable will collect all the titles from the data variable [\"Name\", \"Roll Number\"] */ const titles = data.slice(0, data .indexOf('\\n')).split(delimiter); /* This variable will store the values from the data [ 'Rohan,01', 'Aryan,02' ] */ const titleValues = data.slice(data .indexOf('\\n') + 1).split('\\n'); /* Map function will iterate over all values of title values array and append each object at the end of the array */ const ansArray = titleValues.map(function (v) { /* Values variable will store individual title values [ 'Rohan', '01' ] */ const values = v.split(delimiter); /* storeKeyValue variable will store object containing each title with their respective values i.e { Name: 'Rohan', 'Roll Number': '01' } */ const storeKeyValue = titles.reduce( function (obj, title, index) { obj[title] = values[index]; return obj; }, {}); return storeKeyValue; }); return ansArray; }; var inputString1 = \"Name,Roll Number\\nRohan,01\\nAryan,02\"; console.log(CSVstring_to_Array(inputString1)); var inputString2 = \"Name;Roll Number\\nRohan;01\\nAryan;02\"; console.log(CSVstring_to_Array(inputString2,';'));</script>",
"e": 4412,
"s": 2846,
"text": null
},
{
"code": null,
"e": 4420,
"s": 4412,
"text": "Output:"
},
{
"code": null,
"e": 4436,
"s": 4420,
"text": "saurabh1990aror"
},
{
"code": null,
"e": 4453,
"s": 4436,
"text": "arorakashish0911"
},
{
"code": null,
"e": 4457,
"s": 4453,
"text": "CSV"
},
{
"code": null,
"e": 4474,
"s": 4457,
"text": "javascript-array"
},
{
"code": null,
"e": 4493,
"s": 4474,
"text": "JavaScript-Methods"
},
{
"code": null,
"e": 4514,
"s": 4493,
"text": "JavaScript-Questions"
},
{
"code": null,
"e": 4521,
"s": 4514,
"text": "Picked"
},
{
"code": null,
"e": 4532,
"s": 4521,
"text": "JavaScript"
},
{
"code": null,
"e": 4549,
"s": 4532,
"text": "Web Technologies"
},
{
"code": null,
"e": 4647,
"s": 4549,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 4708,
"s": 4647,
"text": "Difference between var, let and const keywords in JavaScript"
},
{
"code": null,
"e": 4748,
"s": 4708,
"text": "Remove elements from a JavaScript Array"
},
{
"code": null,
"e": 4784,
"s": 4748,
"text": "JavaScript String includes() Method"
},
{
"code": null,
"e": 4827,
"s": 4784,
"text": "Implementation of LinkedList in Javascript"
},
{
"code": null,
"e": 4855,
"s": 4827,
"text": "DOM (Document Object Model)"
},
{
"code": null,
"e": 4888,
"s": 4855,
"text": "Installation of Node.js on Linux"
},
{
"code": null,
"e": 4938,
"s": 4888,
"text": "How to insert spaces/tabs in text using HTML/CSS?"
},
{
"code": null,
"e": 5000,
"s": 4938,
"text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills"
},
{
"code": null,
"e": 5058,
"s": 5000,
"text": "How to create footer to stay at the bottom of a Web page?"
}
] |
LocalDate getDayOfMonth() method in Java | 28 Nov, 2018
The getDayOfMonth() method of LocalDate class in Java gets the day-of-month field.
Syntax:
public int getDayOfMonth()
Parameter: This method does not accepts any parameter.
Return Value: The function returns the day of the month which is in range 1-31.
Below programs illustrate the getDayOfMonth() method of LocalDate in Java:
Program 1:
// Program to illustrate the getDayOfMonth() method import java.util.*;import java.time.*; public class GfG { public static void main(String[] args) { LocalDate dt = LocalDate.parse("2018-11-27"); System.out.println(dt.getDayOfMonth()); }}
27
Program 2:
// Program to illustrate the getDayOfMonth() method import java.util.*;import java.time.*; public class GfG { public static void main(String[] args) { LocalDate dt = LocalDate.parse("2018-01-01"); System.out.println(dt.getDayOfMonth()); }}
1
Reference: https://docs.oracle.com/javase/10/docs/api/java/time/LocalDate.html#getDayOfMonth()
Java-Functions
Java-LocalDate
Java-time package
Java
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Object Oriented Programming (OOPs) Concept in Java
How to iterate any Map in Java
Interfaces in Java
HashMap in Java with Examples
ArrayList in Java
Collections in Java
Stream In Java
Multidimensional Arrays in Java
Stack Class in Java
Singleton Class in Java | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n28 Nov, 2018"
},
{
"code": null,
"e": 111,
"s": 28,
"text": "The getDayOfMonth() method of LocalDate class in Java gets the day-of-month field."
},
{
"code": null,
"e": 119,
"s": 111,
"text": "Syntax:"
},
{
"code": null,
"e": 147,
"s": 119,
"text": "public int getDayOfMonth()\n"
},
{
"code": null,
"e": 202,
"s": 147,
"text": "Parameter: This method does not accepts any parameter."
},
{
"code": null,
"e": 282,
"s": 202,
"text": "Return Value: The function returns the day of the month which is in range 1-31."
},
{
"code": null,
"e": 357,
"s": 282,
"text": "Below programs illustrate the getDayOfMonth() method of LocalDate in Java:"
},
{
"code": null,
"e": 368,
"s": 357,
"text": "Program 1:"
},
{
"code": "// Program to illustrate the getDayOfMonth() method import java.util.*;import java.time.*; public class GfG { public static void main(String[] args) { LocalDate dt = LocalDate.parse(\"2018-11-27\"); System.out.println(dt.getDayOfMonth()); }}",
"e": 635,
"s": 368,
"text": null
},
{
"code": null,
"e": 639,
"s": 635,
"text": "27\n"
},
{
"code": null,
"e": 650,
"s": 639,
"text": "Program 2:"
},
{
"code": "// Program to illustrate the getDayOfMonth() method import java.util.*;import java.time.*; public class GfG { public static void main(String[] args) { LocalDate dt = LocalDate.parse(\"2018-01-01\"); System.out.println(dt.getDayOfMonth()); }}",
"e": 917,
"s": 650,
"text": null
},
{
"code": null,
"e": 920,
"s": 917,
"text": "1\n"
},
{
"code": null,
"e": 1015,
"s": 920,
"text": "Reference: https://docs.oracle.com/javase/10/docs/api/java/time/LocalDate.html#getDayOfMonth()"
},
{
"code": null,
"e": 1030,
"s": 1015,
"text": "Java-Functions"
},
{
"code": null,
"e": 1045,
"s": 1030,
"text": "Java-LocalDate"
},
{
"code": null,
"e": 1063,
"s": 1045,
"text": "Java-time package"
},
{
"code": null,
"e": 1068,
"s": 1063,
"text": "Java"
},
{
"code": null,
"e": 1073,
"s": 1068,
"text": "Java"
},
{
"code": null,
"e": 1171,
"s": 1073,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 1222,
"s": 1171,
"text": "Object Oriented Programming (OOPs) Concept in Java"
},
{
"code": null,
"e": 1253,
"s": 1222,
"text": "How to iterate any Map in Java"
},
{
"code": null,
"e": 1272,
"s": 1253,
"text": "Interfaces in Java"
},
{
"code": null,
"e": 1302,
"s": 1272,
"text": "HashMap in Java with Examples"
},
{
"code": null,
"e": 1320,
"s": 1302,
"text": "ArrayList in Java"
},
{
"code": null,
"e": 1340,
"s": 1320,
"text": "Collections in Java"
},
{
"code": null,
"e": 1355,
"s": 1340,
"text": "Stream In Java"
},
{
"code": null,
"e": 1387,
"s": 1355,
"text": "Multidimensional Arrays in Java"
},
{
"code": null,
"e": 1407,
"s": 1387,
"text": "Stack Class in Java"
}
] |
Manchester Encoding in Computer Network | 30 Jun, 2022
Prerequisite – Difference between Unipolar, Polar and Bipolar Line Coding Schemes
Manchester encoding is a synchronous clock encoding technique used by the physical layer of the Open System Interconnection [OSI] to encode the clock and data of a synchronous bit stream. The idea of RZ and the idea of-L are combined in manchester
Different encoding techniques are used in data communication to ensure data security and transmission speed. Manchester encoding is an example of digital encoding. Because each data bit length is defined by default, it differs from other digital encoding schemes. The bit state is defined by the direction of the transition. Bit status is represented in various ways by different systems, although most systems use 1 bit for low to high transitions and 0 bit for high to low transitions.
In manchester duration of a bit is divided into two halves. The voltage remains the same at one level during the first half & moves to the other level.The transition at the middle of the bit provides synchronization.Differential Manchester,on the other hand,combines the idea of RZ and NRZ-I. There is always a transition at the middle of the bit, but the bit values are determined at the beginning of the bit. if next bit is zero there is transition if next bit is 1 there is none.
Note: Manchester encoding’s main advantage is signal synchronization.
The binary data to be transmitted over the cable are not sent as NRZ [Non-return-to-zero].
Non-return-to-zero [NRZ] – NRZ code’s voltage level is constant during a bit interval. When there is a long sequence of 0s and 1s, there is a problem at the receiving end. The problem is that the synchronization is lost due to a lack of transmissions. It is of 2 types:
NRZ-level encoding – The polarity of signals changes when the incoming signal changes from ‘1’ to ‘0’ or from ‘0’ to ‘1’. It considers the first bit of data as polarity change.NRZ-Inverted/ Differential encoding – In this, the transitions at the beginning of the bit interval are equal to 1 and if there is no transition at the beginning of the bit interval is equal to 0.
NRZ-level encoding – The polarity of signals changes when the incoming signal changes from ‘1’ to ‘0’ or from ‘0’ to ‘1’. It considers the first bit of data as polarity change.
NRZ-Inverted/ Differential encoding – In this, the transitions at the beginning of the bit interval are equal to 1 and if there is no transition at the beginning of the bit interval is equal to 0.
Characteristics of Manchester Encoding –
A logic 0 is indicated by a 0 to 1 transition at the center of the bit and logic 1 by 1 to 0 transition.
The signal transitions do not always occur at the ‘bit boundary’ but there is always a transition at the center of each bit.
The Differential Physical Layer Transmission does not employ an inverting line driver to convert the binary digits into an electrical signal. And therefore the signal on the wire is not opposite the output by the encoder.
The following are the properties of Manchester encoding:
Each bit is sent at a predetermined rate.
When a high to low transition happens, a ‘1’ is recorded; when a low to high transition occurs, a ‘0’ is recorded.
At the mid-point of a period, the transition that is utilized to precisely note 1 or 0 happens.The Manchester Encoding is also called Biphase code as each bit is encoded by a positive 90 degrees phase transition or by negative 90 degrees phase transition.
The Digital Phase Locked Loop (DPLL) extracts the clock signal and deallocates the value and timing of each bit. The transmitted bitstream must contain a high density of bit transitions.
The Manchester Encoding consumes twice the bandwidth of the original signal.
The advantage of the Manchester code is that the DC component of the signal carries no information. This makes it possible that standards that usually do not carry power can transmit this information.
Only drawback is the signal rate.The signal rate is manchester and differential is double that for NRZ. The reason is that there is always one transition at the middle of the bit and maybe one transition at the end of each bit.
Eg: For 10Mbps LAN the signal spectrum lies between 5 and 20
Another example to find out the bits by seeing the transitions.
GATE-CS-2007 | Question 85GATE IT 2007 | Question 59ISRO CS 2007 | Question 22
GATE-CS-2007 | Question 85
GATE IT 2007 | Question 59
ISRO CS 2007 | Question 22
Reference :Book – Computer Networks by Tanenbaum
mvasam
rohanpa9876632
Pushpender007
akashmomale
pratimaasopa
sagartomar9927
bhawnachelani123
Data Link Layer
Computer Networks
Computer Networks
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here. | [
{
"code": null,
"e": 52,
"s": 24,
"text": "\n30 Jun, 2022"
},
{
"code": null,
"e": 135,
"s": 52,
"text": "Prerequisite – Difference between Unipolar, Polar and Bipolar Line Coding Schemes "
},
{
"code": null,
"e": 384,
"s": 135,
"text": "Manchester encoding is a synchronous clock encoding technique used by the physical layer of the Open System Interconnection [OSI] to encode the clock and data of a synchronous bit stream. The idea of RZ and the idea of-L are combined in manchester"
},
{
"code": null,
"e": 872,
"s": 384,
"text": "Different encoding techniques are used in data communication to ensure data security and transmission speed. Manchester encoding is an example of digital encoding. Because each data bit length is defined by default, it differs from other digital encoding schemes. The bit state is defined by the direction of the transition. Bit status is represented in various ways by different systems, although most systems use 1 bit for low to high transitions and 0 bit for high to low transitions."
},
{
"code": null,
"e": 1356,
"s": 872,
"text": "In manchester duration of a bit is divided into two halves. The voltage remains the same at one level during the first half & moves to the other level.The transition at the middle of the bit provides synchronization.Differential Manchester,on the other hand,combines the idea of RZ and NRZ-I. There is always a transition at the middle of the bit, but the bit values are determined at the beginning of the bit. if next bit is zero there is transition if next bit is 1 there is none. "
},
{
"code": null,
"e": 1426,
"s": 1356,
"text": "Note: Manchester encoding’s main advantage is signal synchronization."
},
{
"code": null,
"e": 1520,
"s": 1428,
"text": "The binary data to be transmitted over the cable are not sent as NRZ [Non-return-to-zero]. "
},
{
"code": null,
"e": 1791,
"s": 1520,
"text": "Non-return-to-zero [NRZ] – NRZ code’s voltage level is constant during a bit interval. When there is a long sequence of 0s and 1s, there is a problem at the receiving end. The problem is that the synchronization is lost due to a lack of transmissions. It is of 2 types: "
},
{
"code": null,
"e": 2164,
"s": 1791,
"text": "NRZ-level encoding – The polarity of signals changes when the incoming signal changes from ‘1’ to ‘0’ or from ‘0’ to ‘1’. It considers the first bit of data as polarity change.NRZ-Inverted/ Differential encoding – In this, the transitions at the beginning of the bit interval are equal to 1 and if there is no transition at the beginning of the bit interval is equal to 0."
},
{
"code": null,
"e": 2341,
"s": 2164,
"text": "NRZ-level encoding – The polarity of signals changes when the incoming signal changes from ‘1’ to ‘0’ or from ‘0’ to ‘1’. It considers the first bit of data as polarity change."
},
{
"code": null,
"e": 2538,
"s": 2341,
"text": "NRZ-Inverted/ Differential encoding – In this, the transitions at the beginning of the bit interval are equal to 1 and if there is no transition at the beginning of the bit interval is equal to 0."
},
{
"code": null,
"e": 2579,
"s": 2538,
"text": "Characteristics of Manchester Encoding –"
},
{
"code": null,
"e": 2684,
"s": 2579,
"text": "A logic 0 is indicated by a 0 to 1 transition at the center of the bit and logic 1 by 1 to 0 transition."
},
{
"code": null,
"e": 2809,
"s": 2684,
"text": "The signal transitions do not always occur at the ‘bit boundary’ but there is always a transition at the center of each bit."
},
{
"code": null,
"e": 3031,
"s": 2809,
"text": "The Differential Physical Layer Transmission does not employ an inverting line driver to convert the binary digits into an electrical signal. And therefore the signal on the wire is not opposite the output by the encoder."
},
{
"code": null,
"e": 3088,
"s": 3031,
"text": "The following are the properties of Manchester encoding:"
},
{
"code": null,
"e": 3130,
"s": 3088,
"text": "Each bit is sent at a predetermined rate."
},
{
"code": null,
"e": 3245,
"s": 3130,
"text": "When a high to low transition happens, a ‘1’ is recorded; when a low to high transition occurs, a ‘0’ is recorded."
},
{
"code": null,
"e": 3501,
"s": 3245,
"text": "At the mid-point of a period, the transition that is utilized to precisely note 1 or 0 happens.The Manchester Encoding is also called Biphase code as each bit is encoded by a positive 90 degrees phase transition or by negative 90 degrees phase transition."
},
{
"code": null,
"e": 3688,
"s": 3501,
"text": "The Digital Phase Locked Loop (DPLL) extracts the clock signal and deallocates the value and timing of each bit. The transmitted bitstream must contain a high density of bit transitions."
},
{
"code": null,
"e": 3765,
"s": 3688,
"text": "The Manchester Encoding consumes twice the bandwidth of the original signal."
},
{
"code": null,
"e": 3966,
"s": 3765,
"text": "The advantage of the Manchester code is that the DC component of the signal carries no information. This makes it possible that standards that usually do not carry power can transmit this information."
},
{
"code": null,
"e": 4195,
"s": 3966,
"text": "Only drawback is the signal rate.The signal rate is manchester and differential is double that for NRZ. The reason is that there is always one transition at the middle of the bit and maybe one transition at the end of each bit. "
},
{
"code": null,
"e": 4256,
"s": 4195,
"text": "Eg: For 10Mbps LAN the signal spectrum lies between 5 and 20"
},
{
"code": null,
"e": 4322,
"s": 4256,
"text": "Another example to find out the bits by seeing the transitions. "
},
{
"code": null,
"e": 4401,
"s": 4322,
"text": "GATE-CS-2007 | Question 85GATE IT 2007 | Question 59ISRO CS 2007 | Question 22"
},
{
"code": null,
"e": 4428,
"s": 4401,
"text": "GATE-CS-2007 | Question 85"
},
{
"code": null,
"e": 4455,
"s": 4428,
"text": "GATE IT 2007 | Question 59"
},
{
"code": null,
"e": 4482,
"s": 4455,
"text": "ISRO CS 2007 | Question 22"
},
{
"code": null,
"e": 4531,
"s": 4482,
"text": "Reference :Book – Computer Networks by Tanenbaum"
},
{
"code": null,
"e": 4538,
"s": 4531,
"text": "mvasam"
},
{
"code": null,
"e": 4553,
"s": 4538,
"text": "rohanpa9876632"
},
{
"code": null,
"e": 4567,
"s": 4553,
"text": "Pushpender007"
},
{
"code": null,
"e": 4579,
"s": 4567,
"text": "akashmomale"
},
{
"code": null,
"e": 4592,
"s": 4579,
"text": "pratimaasopa"
},
{
"code": null,
"e": 4607,
"s": 4592,
"text": "sagartomar9927"
},
{
"code": null,
"e": 4624,
"s": 4607,
"text": "bhawnachelani123"
},
{
"code": null,
"e": 4640,
"s": 4624,
"text": "Data Link Layer"
},
{
"code": null,
"e": 4658,
"s": 4640,
"text": "Computer Networks"
},
{
"code": null,
"e": 4676,
"s": 4658,
"text": "Computer Networks"
}
] |
Construct MEX array from the given array | 13 Jan, 2022
Given an array arr[] having N distinct positive elements, the task is to generate another array B[] such that, for every ith index in the array, arr[], B[i] is the minimum positive number missing from arr[] excluding arr[i].
Examples:
Input: arr[] = {2, 1, 5, 3}Output: B[] = {2, 1, 4, 3} Explanation: After excluding the arr[0], the array is {1, 5, 3}, and the minimum positive number which is not present in this array is 2. Therefore, B[0] = 2. Similarly, after excluding arr[1], arr[2], arr[3], the minimum positive numbers which are not present in the array are 1, 4 and 3, respectively. Hence, B[1] = 1, B[2] = 4, B[3] = 3.
Input: arr[] = {1, 9, 2, 4}Output: B[] = {1, 3, 2, 3}
Naive Approach: The simplest approach to solve this problem is to traverse the array arr[] and for every index i, initialize an array hash[] and for every index j ( where j ≠ i), update hash[arr[j]] =1. Now traverse array hash[] from index 1 and find the minimum index k for which hash[k] = 0 and update B[i] = k. Finally, print the array B[] after completing the above step.
Time Complexity: O(N2) where N is the length of the given array.Auxiliary Space: O(N)
Efficient Approach: To optimize the above approach, the idea is to calculate MEX of the array arr[] and traverse the array arr[]. If arr[i] is less than MEX of the array arr[] then MEX excluding this element will be arr[i] itself, and if arr[i] is greater than MEX of array A[] then MEX of the array will not change after excluding this element.
Follow the steps below to solve the problem:
Initialize an array, say hash[], to store whether the value i is present in the array arr[] or not. If i is present hash[i] = 1 else hash[i] = 0.Initialize a variable MexOfArr to store MEX of array arr[] and traverse array hash[] from 1 to find the minimum index j for which hash[j] = 0, which implies that the value j is not present in the array arr[] and store MexOfArr = j.Now traverse the array, arr[] and if arr[i] is less than MexOfArr, then store B[i] = arr[i] else B[i] = MexOfArr.After completing the above steps, print elements of the array B[] as the required answer.
Initialize an array, say hash[], to store whether the value i is present in the array arr[] or not. If i is present hash[i] = 1 else hash[i] = 0.
Initialize a variable MexOfArr to store MEX of array arr[] and traverse array hash[] from 1 to find the minimum index j for which hash[j] = 0, which implies that the value j is not present in the array arr[] and store MexOfArr = j.
Now traverse the array, arr[] and if arr[i] is less than MexOfArr, then store B[i] = arr[i] else B[i] = MexOfArr.
After completing the above steps, print elements of the array B[] as the required answer.
Below is the implementation of the above approach:
C++
Java
Python3
C#
Javascript
// C++ program for the above approach #include <bits/stdc++.h>using namespace std; #define MAXN 100001 // Function to construct array B[] that// stores MEX of array A[] excluding A[i]void constructMEX(int arr[], int N){ // Stores elements present in arr[] int hash[MAXN] = { 0 }; // Mark all values 1, if present for (int i = 0; i < N; i++) { hash[arr[i]] = 1; } // Initialize variable to store MEX int MexOfArr; // Find MEX of arr[] for (int i = 1; i < MAXN; i++) { if (hash[i] == 0) { MexOfArr = i; break; } } // Stores MEX for all indices int B[N]; // Traverse the given array for (int i = 0; i < N; i++) { // Update MEX if (arr[i] < MexOfArr) B[i] = arr[i]; // MEX default else B[i] = MexOfArr; } // Print the array B for (int i = 0; i < N; i++) cout << B[i] << ' ';} // Driver Codeint main(){ // Given array int arr[] = { 2, 1, 5, 3 }; // Given size int N = sizeof(arr) / sizeof(arr[0]); // Function call constructMEX(arr, N); return 0;}
// Java program for the above approachimport java.util.*;class GFG{ static int MAXN = 100001; // Function to construct array// B[] that stores MEX of array// A[] excluding A[i]static void constructMEX(int arr[], int N){ // Stores elements present // in arr[] int hash[] = new int[MAXN]; for (int i = 0; i < N; i++) { hash[i] = 0; } // Mark all values 1, if // present for (int i = 0; i < N; i++) { hash[arr[i]] = 1; } // Initialize variable to // store MEX int MexOfArr = 0 ; // Find MEX of arr[] for (int i = 1; i < MAXN; i++) { if (hash[i] == 0) { MexOfArr = i; break; } } // Stores MEX for all // indices int B[] = new int[N]; // Traverse the given array for (int i = 0; i < N; i++) { // Update MEX if (arr[i] < MexOfArr) B[i] = arr[i]; // MEX default else B[i] = MexOfArr; } // Print the array B for (int i = 0; i < N; i++) System.out.print(B[i] + " ");} // Driver Codepublic static void main(String[] args){ // Given array arr[] int arr[] = {2, 1, 5, 3}; // Size of array int N = arr.length; // Function call constructMEX(arr, N);}} // This code is contributed by sanjoy_62
# Python3 program for the# above approach MAXN = 100001 # Function to construct# array B[] that stores# MEX of array A[] excluding# A[i]def constructMEX(arr, N): # Stores elements present # in arr[] hash = [0] * MAXN # Mark all values 1, # if present for i in range(N): hash[arr[i]] = 1 # Initialize variable to # store MEX MexOfArr = 0 # Find MEX of arr[] for i in range(1, MAXN): if (hash[i] == 0): MexOfArr = i break # Stores MEX for all # indices B = [0] * N # Traverse the given array for i in range(N): # Update MEX if (arr[i] < MexOfArr): B[i] = arr[i] # MEX default else: B[i] = MexOfArr # Print array B for i in range(N): print(B[i], end = " ") # Driver Codeif __name__ == '__main__': # Given array arr = [2, 1, 5, 3] # Given size N = len(arr) # Function call constructMEX(arr, N) # This code is contributed by Mohit Kumar 29
// C# program for the above approachusing System; class GFG{ static int MAXN = 100001; // Function to construct array// B[] that stores MEX of array// A[] excluding A[i]static void constructMEX(int[] arr, int N){ // Stores elements present // in arr[] int[] hash = new int[MAXN]; for(int i = 0; i < N; i++) { hash[i] = 0; } // Mark all values 1, if // present for(int i = 0; i < N; i++) { hash[arr[i]] = 1; } // Initialize variable to // store MEX int MexOfArr = 0; // Find MEX of arr[] for(int i = 1; i < MAXN; i++) { if (hash[i] == 0) { MexOfArr = i; break; } } // Stores MEX for all // indices int[] B = new int[N]; // Traverse the given array for(int i = 0; i < N; i++) { // Update MEX if (arr[i] < MexOfArr) B[i] = arr[i]; // MEX default else B[i] = MexOfArr; } // Print the array B for(int i = 0; i < N; i++) Console.Write(B[i] + " ");} // Driver Codepublic static void Main(){ // Given array arr[] int[] arr = { 2, 1, 5, 3 }; // Size of array int N = arr.Length; // Function call constructMEX(arr, N);}} // This code is contributed by code_hunt
<script>// Javascript program for the above approach var MAXN = 100001; // Function to construct array B[] that// stores MEX of array A[] excluding A[i]function constructMEX(arr, N){ // Stores elements present in arr[] var hash = Array(MAXN).fill(0); // Mark all values 1, if present for (var i = 0; i < N; i++) { hash[arr[i]] = 1; } // Initialize variable to store MEX var MexOfArr; // Find MEX of arr[] for (var i = 1; i < MAXN; i++) { if (hash[i] == 0) { MexOfArr = i; break; } } // Stores MEX for all indices var B = Array(N); // Traverse the given array for (var i = 0; i < N; i++) { // Update MEX if (arr[i] < MexOfArr) B[i] = arr[i]; // MEX default else B[i] = MexOfArr; } // Print the array B for (var i = 0; i < N; i++) document.write( B[i] + ' ');} // Driver Code// Given arrayvar arr = [2, 1, 5, 3];// Given sizevar N = arr.length;// Function callconstructMEX(arr, N); </script>
2 1 4 3
Time Complexity: O(N)Auxiliary Space: O(N)
mohit kumar 29
sanjoy_62
code_hunt
rutvik_56
khushboogoyal499
counting-sort
frequency-counting
Arrays
Greedy
Hash
Mathematical
Arrays
Hash
Greedy
Mathematical
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here. | [
{
"code": null,
"e": 54,
"s": 26,
"text": "\n13 Jan, 2022"
},
{
"code": null,
"e": 279,
"s": 54,
"text": "Given an array arr[] having N distinct positive elements, the task is to generate another array B[] such that, for every ith index in the array, arr[], B[i] is the minimum positive number missing from arr[] excluding arr[i]."
},
{
"code": null,
"e": 289,
"s": 279,
"text": "Examples:"
},
{
"code": null,
"e": 684,
"s": 289,
"text": "Input: arr[] = {2, 1, 5, 3}Output: B[] = {2, 1, 4, 3} Explanation: After excluding the arr[0], the array is {1, 5, 3}, and the minimum positive number which is not present in this array is 2. Therefore, B[0] = 2. Similarly, after excluding arr[1], arr[2], arr[3], the minimum positive numbers which are not present in the array are 1, 4 and 3, respectively. Hence, B[1] = 1, B[2] = 4, B[3] = 3."
},
{
"code": null,
"e": 738,
"s": 684,
"text": "Input: arr[] = {1, 9, 2, 4}Output: B[] = {1, 3, 2, 3}"
},
{
"code": null,
"e": 1115,
"s": 738,
"text": "Naive Approach: The simplest approach to solve this problem is to traverse the array arr[] and for every index i, initialize an array hash[] and for every index j ( where j ≠ i), update hash[arr[j]] =1. Now traverse array hash[] from index 1 and find the minimum index k for which hash[k] = 0 and update B[i] = k. Finally, print the array B[] after completing the above step."
},
{
"code": null,
"e": 1201,
"s": 1115,
"text": "Time Complexity: O(N2) where N is the length of the given array.Auxiliary Space: O(N)"
},
{
"code": null,
"e": 1547,
"s": 1201,
"text": "Efficient Approach: To optimize the above approach, the idea is to calculate MEX of the array arr[] and traverse the array arr[]. If arr[i] is less than MEX of the array arr[] then MEX excluding this element will be arr[i] itself, and if arr[i] is greater than MEX of array A[] then MEX of the array will not change after excluding this element."
},
{
"code": null,
"e": 1592,
"s": 1547,
"text": "Follow the steps below to solve the problem:"
},
{
"code": null,
"e": 2171,
"s": 1592,
"text": "Initialize an array, say hash[], to store whether the value i is present in the array arr[] or not. If i is present hash[i] = 1 else hash[i] = 0.Initialize a variable MexOfArr to store MEX of array arr[] and traverse array hash[] from 1 to find the minimum index j for which hash[j] = 0, which implies that the value j is not present in the array arr[] and store MexOfArr = j.Now traverse the array, arr[] and if arr[i] is less than MexOfArr, then store B[i] = arr[i] else B[i] = MexOfArr.After completing the above steps, print elements of the array B[] as the required answer."
},
{
"code": null,
"e": 2317,
"s": 2171,
"text": "Initialize an array, say hash[], to store whether the value i is present in the array arr[] or not. If i is present hash[i] = 1 else hash[i] = 0."
},
{
"code": null,
"e": 2549,
"s": 2317,
"text": "Initialize a variable MexOfArr to store MEX of array arr[] and traverse array hash[] from 1 to find the minimum index j for which hash[j] = 0, which implies that the value j is not present in the array arr[] and store MexOfArr = j."
},
{
"code": null,
"e": 2663,
"s": 2549,
"text": "Now traverse the array, arr[] and if arr[i] is less than MexOfArr, then store B[i] = arr[i] else B[i] = MexOfArr."
},
{
"code": null,
"e": 2753,
"s": 2663,
"text": "After completing the above steps, print elements of the array B[] as the required answer."
},
{
"code": null,
"e": 2804,
"s": 2753,
"text": "Below is the implementation of the above approach:"
},
{
"code": null,
"e": 2808,
"s": 2804,
"text": "C++"
},
{
"code": null,
"e": 2813,
"s": 2808,
"text": "Java"
},
{
"code": null,
"e": 2821,
"s": 2813,
"text": "Python3"
},
{
"code": null,
"e": 2824,
"s": 2821,
"text": "C#"
},
{
"code": null,
"e": 2835,
"s": 2824,
"text": "Javascript"
},
{
"code": "// C++ program for the above approach #include <bits/stdc++.h>using namespace std; #define MAXN 100001 // Function to construct array B[] that// stores MEX of array A[] excluding A[i]void constructMEX(int arr[], int N){ // Stores elements present in arr[] int hash[MAXN] = { 0 }; // Mark all values 1, if present for (int i = 0; i < N; i++) { hash[arr[i]] = 1; } // Initialize variable to store MEX int MexOfArr; // Find MEX of arr[] for (int i = 1; i < MAXN; i++) { if (hash[i] == 0) { MexOfArr = i; break; } } // Stores MEX for all indices int B[N]; // Traverse the given array for (int i = 0; i < N; i++) { // Update MEX if (arr[i] < MexOfArr) B[i] = arr[i]; // MEX default else B[i] = MexOfArr; } // Print the array B for (int i = 0; i < N; i++) cout << B[i] << ' ';} // Driver Codeint main(){ // Given array int arr[] = { 2, 1, 5, 3 }; // Given size int N = sizeof(arr) / sizeof(arr[0]); // Function call constructMEX(arr, N); return 0;}",
"e": 3972,
"s": 2835,
"text": null
},
{
"code": "// Java program for the above approachimport java.util.*;class GFG{ static int MAXN = 100001; // Function to construct array// B[] that stores MEX of array// A[] excluding A[i]static void constructMEX(int arr[], int N){ // Stores elements present // in arr[] int hash[] = new int[MAXN]; for (int i = 0; i < N; i++) { hash[i] = 0; } // Mark all values 1, if // present for (int i = 0; i < N; i++) { hash[arr[i]] = 1; } // Initialize variable to // store MEX int MexOfArr = 0 ; // Find MEX of arr[] for (int i = 1; i < MAXN; i++) { if (hash[i] == 0) { MexOfArr = i; break; } } // Stores MEX for all // indices int B[] = new int[N]; // Traverse the given array for (int i = 0; i < N; i++) { // Update MEX if (arr[i] < MexOfArr) B[i] = arr[i]; // MEX default else B[i] = MexOfArr; } // Print the array B for (int i = 0; i < N; i++) System.out.print(B[i] + \" \");} // Driver Codepublic static void main(String[] args){ // Given array arr[] int arr[] = {2, 1, 5, 3}; // Size of array int N = arr.length; // Function call constructMEX(arr, N);}} // This code is contributed by sanjoy_62",
"e": 5173,
"s": 3972,
"text": null
},
{
"code": "# Python3 program for the# above approach MAXN = 100001 # Function to construct# array B[] that stores# MEX of array A[] excluding# A[i]def constructMEX(arr, N): # Stores elements present # in arr[] hash = [0] * MAXN # Mark all values 1, # if present for i in range(N): hash[arr[i]] = 1 # Initialize variable to # store MEX MexOfArr = 0 # Find MEX of arr[] for i in range(1, MAXN): if (hash[i] == 0): MexOfArr = i break # Stores MEX for all # indices B = [0] * N # Traverse the given array for i in range(N): # Update MEX if (arr[i] < MexOfArr): B[i] = arr[i] # MEX default else: B[i] = MexOfArr # Print array B for i in range(N): print(B[i], end = \" \") # Driver Codeif __name__ == '__main__': # Given array arr = [2, 1, 5, 3] # Given size N = len(arr) # Function call constructMEX(arr, N) # This code is contributed by Mohit Kumar 29",
"e": 6189,
"s": 5173,
"text": null
},
{
"code": "// C# program for the above approachusing System; class GFG{ static int MAXN = 100001; // Function to construct array// B[] that stores MEX of array// A[] excluding A[i]static void constructMEX(int[] arr, int N){ // Stores elements present // in arr[] int[] hash = new int[MAXN]; for(int i = 0; i < N; i++) { hash[i] = 0; } // Mark all values 1, if // present for(int i = 0; i < N; i++) { hash[arr[i]] = 1; } // Initialize variable to // store MEX int MexOfArr = 0; // Find MEX of arr[] for(int i = 1; i < MAXN; i++) { if (hash[i] == 0) { MexOfArr = i; break; } } // Stores MEX for all // indices int[] B = new int[N]; // Traverse the given array for(int i = 0; i < N; i++) { // Update MEX if (arr[i] < MexOfArr) B[i] = arr[i]; // MEX default else B[i] = MexOfArr; } // Print the array B for(int i = 0; i < N; i++) Console.Write(B[i] + \" \");} // Driver Codepublic static void Main(){ // Given array arr[] int[] arr = { 2, 1, 5, 3 }; // Size of array int N = arr.Length; // Function call constructMEX(arr, N);}} // This code is contributed by code_hunt",
"e": 7376,
"s": 6189,
"text": null
},
{
"code": "<script>// Javascript program for the above approach var MAXN = 100001; // Function to construct array B[] that// stores MEX of array A[] excluding A[i]function constructMEX(arr, N){ // Stores elements present in arr[] var hash = Array(MAXN).fill(0); // Mark all values 1, if present for (var i = 0; i < N; i++) { hash[arr[i]] = 1; } // Initialize variable to store MEX var MexOfArr; // Find MEX of arr[] for (var i = 1; i < MAXN; i++) { if (hash[i] == 0) { MexOfArr = i; break; } } // Stores MEX for all indices var B = Array(N); // Traverse the given array for (var i = 0; i < N; i++) { // Update MEX if (arr[i] < MexOfArr) B[i] = arr[i]; // MEX default else B[i] = MexOfArr; } // Print the array B for (var i = 0; i < N; i++) document.write( B[i] + ' ');} // Driver Code// Given arrayvar arr = [2, 1, 5, 3];// Given sizevar N = arr.length;// Function callconstructMEX(arr, N); </script>",
"e": 8426,
"s": 7376,
"text": null
},
{
"code": null,
"e": 8434,
"s": 8426,
"text": "2 1 4 3"
},
{
"code": null,
"e": 8479,
"s": 8436,
"text": "Time Complexity: O(N)Auxiliary Space: O(N)"
},
{
"code": null,
"e": 8494,
"s": 8479,
"text": "mohit kumar 29"
},
{
"code": null,
"e": 8504,
"s": 8494,
"text": "sanjoy_62"
},
{
"code": null,
"e": 8514,
"s": 8504,
"text": "code_hunt"
},
{
"code": null,
"e": 8524,
"s": 8514,
"text": "rutvik_56"
},
{
"code": null,
"e": 8541,
"s": 8524,
"text": "khushboogoyal499"
},
{
"code": null,
"e": 8555,
"s": 8541,
"text": "counting-sort"
},
{
"code": null,
"e": 8574,
"s": 8555,
"text": "frequency-counting"
},
{
"code": null,
"e": 8581,
"s": 8574,
"text": "Arrays"
},
{
"code": null,
"e": 8588,
"s": 8581,
"text": "Greedy"
},
{
"code": null,
"e": 8593,
"s": 8588,
"text": "Hash"
},
{
"code": null,
"e": 8606,
"s": 8593,
"text": "Mathematical"
},
{
"code": null,
"e": 8613,
"s": 8606,
"text": "Arrays"
},
{
"code": null,
"e": 8618,
"s": 8613,
"text": "Hash"
},
{
"code": null,
"e": 8625,
"s": 8618,
"text": "Greedy"
},
{
"code": null,
"e": 8638,
"s": 8625,
"text": "Mathematical"
}
] |
How to create a seaborn correlation heatmap in Python? | 12 Nov, 2020
Seaborn is a Python library that is based on matplotlib and is used for data visualization. It provides a medium to present data in a statistical graph format as an informative and attractive medium to impart some information. A heatmap is one of the components supported by seaborn where variation in related data is portrayed using a color palette. This article centrally focuses on a correlation heatmap and how seaborn in combination with pandas and matplotlib can be used to generate one for a dataframe.
Like any another Python library, seaborn can be easily installed using pip:
pip install seaborn
This library is a part of Anaconda distribution and usually works just by import if your IDE is supported by Anaconda, but it can be installed too by the following command:
conda install seaborn
A correlation heatmap is a heatmap that shows a 2D correlation matrix between two discrete dimensions, using colored cells to represent data from usually a monochromatic scale. The values of the first dimension appear as the rows of the table while of the second dimension as a column. The color of the cell is proportional to the number of measurements that match the dimensional value. This makes correlation heatmaps ideal for data analysis since it makes patterns easily readable and highlights the differences and variation in the same data. A correlation heatmap, like a regular heatmap, is assisted by a colorbar making data easily readable and comprehensible.
The following steps show how a correlation heatmap can be produced:
Import all required modules first
Import the file where your data is stored
Plot a heatmap
Display it using matplotlib
For plotting heatmap method of the seaborn module will be used.
Syntax: heatmap(data, vmin, vmax, center, cmap,............................................................)
Except for data all other attributes are optional and data obviously will be the data to be plotted. The data here has to be passed with corr() method to generate a correlation heatmap. Also, corr() itself eliminates columns which will be of no use while generating a correlation heatmap and selects those which can be used.
Example 1:
For the example given below, here a dataset downloaded from kaggle.com is being used. The plot shows data related to bestseller novels on amazon.
Dataset used – Bestsellers
Python3
# import modulesimport matplotlib.pyplot as mpimport pandas as pdimport seaborn as sb # import file with datadata = pd.read_csv("C:\\Users\\Vanshi\\Desktop\\bestsellers.csv") # prints data that will be plotted# columns shown here are selected by corr() since# they are ideal for the plotprint(data.corr()) # plotting correlation heatmapdataplot = sb.heatmap(data.corr(), cmap="YlGnBu", annot=True) # displaying heatmapmp.show()
Output:
The above example deals with small data. The following example depicts how the output will look like for a large dataset,
Example 2:
The dataset used in this example is an exoplanet space research dataset compiled by NASA.
Dataset used – cumulative
Python3
# import modulesimport matplotlib.pyplot as mpimport pandas as pdimport seaborn as sb # import file with datadata=pd.read_csv("C:\\Users\\Vanshi\\Desktop\\cumulative.csv") # plotting correlation heatmapdataplot=sb.heatmap(data.corr()) # displaying heatmapmp.show()
Output:
Python-Seaborn
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Read JSON file using Python
Adding new column to existing DataFrame in Pandas
Python map() function
How to get column names in Pandas dataframe
Python Dictionary
Different ways to create Pandas Dataframe
Taking input in Python
Enumerate() in Python
Read a file line by line in Python
Python String | replace() | [
{
"code": null,
"e": 54,
"s": 26,
"text": "\n12 Nov, 2020"
},
{
"code": null,
"e": 564,
"s": 54,
"text": "Seaborn is a Python library that is based on matplotlib and is used for data visualization. It provides a medium to present data in a statistical graph format as an informative and attractive medium to impart some information. A heatmap is one of the components supported by seaborn where variation in related data is portrayed using a color palette. This article centrally focuses on a correlation heatmap and how seaborn in combination with pandas and matplotlib can be used to generate one for a dataframe."
},
{
"code": null,
"e": 640,
"s": 564,
"text": "Like any another Python library, seaborn can be easily installed using pip:"
},
{
"code": null,
"e": 661,
"s": 640,
"text": "pip install seaborn\n"
},
{
"code": null,
"e": 834,
"s": 661,
"text": "This library is a part of Anaconda distribution and usually works just by import if your IDE is supported by Anaconda, but it can be installed too by the following command:"
},
{
"code": null,
"e": 857,
"s": 834,
"text": "conda install seaborn\n"
},
{
"code": null,
"e": 1525,
"s": 857,
"text": "A correlation heatmap is a heatmap that shows a 2D correlation matrix between two discrete dimensions, using colored cells to represent data from usually a monochromatic scale. The values of the first dimension appear as the rows of the table while of the second dimension as a column. The color of the cell is proportional to the number of measurements that match the dimensional value. This makes correlation heatmaps ideal for data analysis since it makes patterns easily readable and highlights the differences and variation in the same data. A correlation heatmap, like a regular heatmap, is assisted by a colorbar making data easily readable and comprehensible."
},
{
"code": null,
"e": 1593,
"s": 1525,
"text": "The following steps show how a correlation heatmap can be produced:"
},
{
"code": null,
"e": 1627,
"s": 1593,
"text": "Import all required modules first"
},
{
"code": null,
"e": 1669,
"s": 1627,
"text": "Import the file where your data is stored"
},
{
"code": null,
"e": 1684,
"s": 1669,
"text": "Plot a heatmap"
},
{
"code": null,
"e": 1712,
"s": 1684,
"text": "Display it using matplotlib"
},
{
"code": null,
"e": 1776,
"s": 1712,
"text": "For plotting heatmap method of the seaborn module will be used."
},
{
"code": null,
"e": 1885,
"s": 1776,
"text": "Syntax: heatmap(data, vmin, vmax, center, cmap,............................................................)"
},
{
"code": null,
"e": 2210,
"s": 1885,
"text": "Except for data all other attributes are optional and data obviously will be the data to be plotted. The data here has to be passed with corr() method to generate a correlation heatmap. Also, corr() itself eliminates columns which will be of no use while generating a correlation heatmap and selects those which can be used."
},
{
"code": null,
"e": 2221,
"s": 2210,
"text": "Example 1:"
},
{
"code": null,
"e": 2367,
"s": 2221,
"text": "For the example given below, here a dataset downloaded from kaggle.com is being used. The plot shows data related to bestseller novels on amazon."
},
{
"code": null,
"e": 2394,
"s": 2367,
"text": "Dataset used – Bestsellers"
},
{
"code": null,
"e": 2402,
"s": 2394,
"text": "Python3"
},
{
"code": "# import modulesimport matplotlib.pyplot as mpimport pandas as pdimport seaborn as sb # import file with datadata = pd.read_csv(\"C:\\\\Users\\\\Vanshi\\\\Desktop\\\\bestsellers.csv\") # prints data that will be plotted# columns shown here are selected by corr() since# they are ideal for the plotprint(data.corr()) # plotting correlation heatmapdataplot = sb.heatmap(data.corr(), cmap=\"YlGnBu\", annot=True) # displaying heatmapmp.show()",
"e": 2834,
"s": 2402,
"text": null
},
{
"code": null,
"e": 2842,
"s": 2834,
"text": "Output:"
},
{
"code": null,
"e": 2964,
"s": 2842,
"text": "The above example deals with small data. The following example depicts how the output will look like for a large dataset,"
},
{
"code": null,
"e": 2975,
"s": 2964,
"text": "Example 2:"
},
{
"code": null,
"e": 3065,
"s": 2975,
"text": "The dataset used in this example is an exoplanet space research dataset compiled by NASA."
},
{
"code": null,
"e": 3091,
"s": 3065,
"text": "Dataset used – cumulative"
},
{
"code": null,
"e": 3099,
"s": 3091,
"text": "Python3"
},
{
"code": "# import modulesimport matplotlib.pyplot as mpimport pandas as pdimport seaborn as sb # import file with datadata=pd.read_csv(\"C:\\\\Users\\\\Vanshi\\\\Desktop\\\\cumulative.csv\") # plotting correlation heatmapdataplot=sb.heatmap(data.corr()) # displaying heatmapmp.show()",
"e": 3367,
"s": 3099,
"text": null
},
{
"code": null,
"e": 3375,
"s": 3367,
"text": "Output:"
},
{
"code": null,
"e": 3390,
"s": 3375,
"text": "Python-Seaborn"
},
{
"code": null,
"e": 3397,
"s": 3390,
"text": "Python"
},
{
"code": null,
"e": 3495,
"s": 3397,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 3523,
"s": 3495,
"text": "Read JSON file using Python"
},
{
"code": null,
"e": 3573,
"s": 3523,
"text": "Adding new column to existing DataFrame in Pandas"
},
{
"code": null,
"e": 3595,
"s": 3573,
"text": "Python map() function"
},
{
"code": null,
"e": 3639,
"s": 3595,
"text": "How to get column names in Pandas dataframe"
},
{
"code": null,
"e": 3657,
"s": 3639,
"text": "Python Dictionary"
},
{
"code": null,
"e": 3699,
"s": 3657,
"text": "Different ways to create Pandas Dataframe"
},
{
"code": null,
"e": 3722,
"s": 3699,
"text": "Taking input in Python"
},
{
"code": null,
"e": 3744,
"s": 3722,
"text": "Enumerate() in Python"
},
{
"code": null,
"e": 3779,
"s": 3744,
"text": "Read a file line by line in Python"
}
] |
Python | Pandas Series.add() | 01 Oct, 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.
Python Series.add() is used to add series or list like objects with same length to the caller series.
Syntax: Series.add(other, level=None, fill_value=None, axis=0)
Parameters:other: other series or list type to be added into caller seriesfill_value: Value to be replaced by NaN in series/list before addinglevel: integer value of level in case of multi index
Return type: Caller series with added values
To download the data set used in following example, 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 #1: Adding List
In this example, the top 5 rows are stored in new variable using .head() method. After that a list of same length is created and added to the salary column using .add() 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") # creating short data of 5 rowsshort_data = data.head() # creating list with 5 valueslist =[1, 2, 3, 4, 5] # adding list data# creating new columnshort_data["Added values"]= short_data["Salary"].add(list) # displayshort_data
Output:As shown in the output image, it can be compared that the Added value column is having the added values of Salary column + list. Example #2: Adding series to series with null values
In this example, the Age column is added to the Salary column. Since the salary column contains null values too, by default it returns NaN no matter what is added. In this example, 5 is passed to replace null values with 5.
# 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") # age seriesage = data["Age"] # na replacementna = 5 # adding values# storing to new columndata["Added values"]= data["Salary"].add(other = age, fill_value = na) # displaydata
Output:As shown in the output image, the Added value column has added age column with 5 in case of Null values.
Python pandas-selection
Python pandas-series-methods
Python-pandas
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python Dictionary
Different ways to create Pandas Dataframe
Enumerate() in Python
How to Install PIP on Windows ?
*args and **kwargs in Python
Python Classes and Objects
Python OOPs Concepts
Convert integer to string in Python
Introduction To PYTHON
How to drop one or multiple columns in Pandas Dataframe | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n01 Oct, 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": 344,
"s": 242,
"text": "Python Series.add() is used to add series or list like objects with same length to the caller series."
},
{
"code": null,
"e": 407,
"s": 344,
"text": "Syntax: Series.add(other, level=None, fill_value=None, axis=0)"
},
{
"code": null,
"e": 602,
"s": 407,
"text": "Parameters:other: other series or list type to be added into caller seriesfill_value: Value to be replaced by NaN in series/list before addinglevel: integer value of level in case of multi index"
},
{
"code": null,
"e": 647,
"s": 602,
"text": "Return type: Caller series with added values"
},
{
"code": null,
"e": 857,
"s": 647,
"text": "To download the data set used in following example, 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."
},
{
"code": null,
"e": 881,
"s": 857,
"text": "Example #1: Adding List"
},
{
"code": null,
"e": 1057,
"s": 881,
"text": "In this example, the top 5 rows are stored in new variable using .head() method. After that a list of same length is created and added to the salary column using .add() 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\") # creating short data of 5 rowsshort_data = data.head() # creating list with 5 valueslist =[1, 2, 3, 4, 5] # adding list data# creating new columnshort_data[\"Added values\"]= short_data[\"Salary\"].add(list) # displayshort_data",
"e": 1442,
"s": 1057,
"text": null
},
{
"code": null,
"e": 1631,
"s": 1442,
"text": "Output:As shown in the output image, it can be compared that the Added value column is having the added values of Salary column + list. Example #2: Adding series to series with null values"
},
{
"code": null,
"e": 1855,
"s": 1631,
"text": "In this example, the Age column is added to the Salary column. Since the salary column contains null values too, by default it returns NaN no matter what is added. In this example, 5 is passed to replace null values with 5."
},
{
"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\") # age seriesage = data[\"Age\"] # na replacementna = 5 # adding values# storing to new columndata[\"Added values\"]= data[\"Salary\"].add(other = age, fill_value = na) # displaydata",
"e": 2191,
"s": 1855,
"text": null
},
{
"code": null,
"e": 2303,
"s": 2191,
"text": "Output:As shown in the output image, the Added value column has added age column with 5 in case of Null values."
},
{
"code": null,
"e": 2327,
"s": 2303,
"text": "Python pandas-selection"
},
{
"code": null,
"e": 2356,
"s": 2327,
"text": "Python pandas-series-methods"
},
{
"code": null,
"e": 2370,
"s": 2356,
"text": "Python-pandas"
},
{
"code": null,
"e": 2377,
"s": 2370,
"text": "Python"
},
{
"code": null,
"e": 2475,
"s": 2377,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 2493,
"s": 2475,
"text": "Python Dictionary"
},
{
"code": null,
"e": 2535,
"s": 2493,
"text": "Different ways to create Pandas Dataframe"
},
{
"code": null,
"e": 2557,
"s": 2535,
"text": "Enumerate() in Python"
},
{
"code": null,
"e": 2589,
"s": 2557,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 2618,
"s": 2589,
"text": "*args and **kwargs in Python"
},
{
"code": null,
"e": 2645,
"s": 2618,
"text": "Python Classes and Objects"
},
{
"code": null,
"e": 2666,
"s": 2645,
"text": "Python OOPs Concepts"
},
{
"code": null,
"e": 2702,
"s": 2666,
"text": "Convert integer to string in Python"
},
{
"code": null,
"e": 2725,
"s": 2702,
"text": "Introduction To PYTHON"
}
] |
Type Assertions in Golang | 22 Jun, 2020
Type assertions in Golang provide access to the exact type of variable of an interface. If already the data type is present in the interface, then it will retrieve the actual data type value held by the interface. A type assertion takes an interface value and extracts from it a value of the specified explicit type. Basically, it is used to remove the ambiguity from the interface variables.
Syntax:
t := value.(typeName)
where value is a variable whose type must be an interface, typeName is the concrete type we want to check and underlying typeName value is assigned to variable t.
Example 1:
// Golang program to illustrate // the concept of type assertionspackage main import ( "fmt") // main functionfunc main() { // an interface that has // a string value var value interface{} = "GeeksforGeeks" // retrieving a value // of type string and assigning // it to value1 variable var value1 string = value.(string) // printing the concrete value fmt.Println(value1) // this will panic as interface // does not have int type var value2 int = value.(int) fmt.Println(value2)}
Output:
GeeksforGeeks
panic: interface conversion: interface {} is string, not int
In the above code, since the value interface does not hold an int type, the statement triggered panic and the type assertion fails. To check whether an interface value holds a specific type, it is possible for type assertion to return two values, the variable with typeName value and a boolean value that reports whether the assertion was successful or not. This is shown in the following example:
Example 2:
// Golang program to show type// assertions with error checkingpackage main import ( "fmt") // main functionfunc main() { // an interface that has // an int value var value interface{} = 20024 // retrieving a value // of type int and assigning // it to value1 variable var value1 int = value.(int) // printing the concrete value fmt.Println(value1) // this will test if interface // has string type and // return true if found or // false otherwise value2, test := value.(string) if test { fmt.Println("String Value found!") fmt.Println(value2) } else { fmt.Println("String value not found!") }}
Output:
20024
String value not found!
Golang-Misc
Go Language
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Parse JSON in Golang?
Constants- Go Language
Time Durations in Golang
How to iterate over an Array using for loop in Golang?
Structures in Golang
Loops in Go Language
Go Variables
Strings in Golang
time.Parse() Function in Golang With Examples
Class and Object in Golang | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n22 Jun, 2020"
},
{
"code": null,
"e": 421,
"s": 28,
"text": "Type assertions in Golang provide access to the exact type of variable of an interface. If already the data type is present in the interface, then it will retrieve the actual data type value held by the interface. A type assertion takes an interface value and extracts from it a value of the specified explicit type. Basically, it is used to remove the ambiguity from the interface variables."
},
{
"code": null,
"e": 429,
"s": 421,
"text": "Syntax:"
},
{
"code": null,
"e": 452,
"s": 429,
"text": "t := value.(typeName)\n"
},
{
"code": null,
"e": 615,
"s": 452,
"text": "where value is a variable whose type must be an interface, typeName is the concrete type we want to check and underlying typeName value is assigned to variable t."
},
{
"code": null,
"e": 626,
"s": 615,
"text": "Example 1:"
},
{
"code": "// Golang program to illustrate // the concept of type assertionspackage main import ( \"fmt\") // main functionfunc main() { // an interface that has // a string value var value interface{} = \"GeeksforGeeks\" // retrieving a value // of type string and assigning // it to value1 variable var value1 string = value.(string) // printing the concrete value fmt.Println(value1) // this will panic as interface // does not have int type var value2 int = value.(int) fmt.Println(value2)}",
"e": 1181,
"s": 626,
"text": null
},
{
"code": null,
"e": 1189,
"s": 1181,
"text": "Output:"
},
{
"code": null,
"e": 1265,
"s": 1189,
"text": "GeeksforGeeks\npanic: interface conversion: interface {} is string, not int\n"
},
{
"code": null,
"e": 1663,
"s": 1265,
"text": "In the above code, since the value interface does not hold an int type, the statement triggered panic and the type assertion fails. To check whether an interface value holds a specific type, it is possible for type assertion to return two values, the variable with typeName value and a boolean value that reports whether the assertion was successful or not. This is shown in the following example:"
},
{
"code": null,
"e": 1674,
"s": 1663,
"text": "Example 2:"
},
{
"code": "// Golang program to show type// assertions with error checkingpackage main import ( \"fmt\") // main functionfunc main() { // an interface that has // an int value var value interface{} = 20024 // retrieving a value // of type int and assigning // it to value1 variable var value1 int = value.(int) // printing the concrete value fmt.Println(value1) // this will test if interface // has string type and // return true if found or // false otherwise value2, test := value.(string) if test { fmt.Println(\"String Value found!\") fmt.Println(value2) } else { fmt.Println(\"String value not found!\") }}",
"e": 2384,
"s": 1674,
"text": null
},
{
"code": null,
"e": 2392,
"s": 2384,
"text": "Output:"
},
{
"code": null,
"e": 2423,
"s": 2392,
"text": "20024\nString value not found!\n"
},
{
"code": null,
"e": 2435,
"s": 2423,
"text": "Golang-Misc"
},
{
"code": null,
"e": 2447,
"s": 2435,
"text": "Go Language"
},
{
"code": null,
"e": 2545,
"s": 2447,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 2574,
"s": 2545,
"text": "How to Parse JSON in Golang?"
},
{
"code": null,
"e": 2597,
"s": 2574,
"text": "Constants- Go Language"
},
{
"code": null,
"e": 2622,
"s": 2597,
"text": "Time Durations in Golang"
},
{
"code": null,
"e": 2677,
"s": 2622,
"text": "How to iterate over an Array using for loop in Golang?"
},
{
"code": null,
"e": 2698,
"s": 2677,
"text": "Structures in Golang"
},
{
"code": null,
"e": 2719,
"s": 2698,
"text": "Loops in Go Language"
},
{
"code": null,
"e": 2732,
"s": 2719,
"text": "Go Variables"
},
{
"code": null,
"e": 2750,
"s": 2732,
"text": "Strings in Golang"
},
{
"code": null,
"e": 2796,
"s": 2750,
"text": "time.Parse() Function in Golang With Examples"
}
] |
Sierpinski triangle | 15 Nov, 2021
Sierpinski triangle is a fractal and attractive fixed set with the overall shape of an equilateral triangle. It subdivides recursively into smaller triangles.
Examples :
Input : n = 4
Output :
*
* *
* *
* * * *
Input : n = 8
Output :
*
* *
* *
* * * *
* *
* * * *
* * * *
* * * * * * * *
Approach :
Sierpinski Triangle will be constructed from an equilateral triangle by repeated removal of triangular subsets. Steps for Construction : 1 . Take any equilateral triangle . 2 . Divide it into 4 smaller congruent triangle and remove the central triangle . 3 . Repeat step 2 for each of the remaining smaller triangles forever.
Below is the program to implement sierpinski triangle
C++
Java
Python3
C#
PHP
Javascript
// C++ program to print sierpinski triangle.#include <bits/stdc++.h>using namespace std; void printSierpinski(int n){ for (int y = n - 1; y >= 0; y--) { // printing space till // the value of y for (int i = 0; i < y; i++) { cout<<" "; } // printing '*' for (int x = 0; x + y < n; x++) { // printing '*' at the appropriate position // is done by the and value of x and y // wherever value is 0 we have printed '*' if(x & y) cout<<" "<<" "; else cout<<"* "; } cout<<endl; }} // Driver codeint main(){ int n = 16; // Function calling printSierpinski(n); return 0;}
// Java program to print// sierpinski triangle.import java.util.*;import java.io.*; class GFG{ static void printSierpinski(int n) { for (int y = n - 1; y >= 0; y--) { // printing space till // the value of y for (int i = 0; i < y; i++) { System.out.print(" "); } // printing '*' for (int x = 0; x + y < n; x++) { // printing '*' at the appropriate // position is done by the and // value of x and y wherever value // is 0 we have printed '*' if ((x & y) != 0) System.out.print(" " + " "); else System.out.print("* "); } System.out.print("\n"); } } // Driver code public static void main(String args[]) { int n = 16; // Function calling printSierpinski(n); }} // This code is contributed by Sahil_Bansall
# Python 3 program to print# sierpinski triangle. def printSierpinski( n) : y = n - 1 while(y >= 0) : # printing space till # the value of y i = 0 while(i < y ): print(" ",end="") i = i + 1 # printing '*' x = 0 while(x + y < n ): # printing '*' at the appropriate # position is done by the and # value of x and y wherever value # is 0 we have printed '*' if ((x & y) != 0) : print(" ", end = " ") else : print("* ", end = "") x =x + 1 print() y = y - 1 # Driver coden = 16 # Function callingprintSierpinski(n) # This code is contributed by Nikita Tiwari.
// C# program to print// sierpinski triangle.using System; class GFG { static void printSierpinski(int n) { for (int y = n - 1; y >= 0; y--) { // printing space till // the value of y for (int i = 0; i < y; i++) { Console.Write(" "); } // printing '*' for (int x = 0; x + y < n; x++) { // printing '*' at the appropriate // position is done by the and // value of x and y wherever value // is 0 we have printed '*' if ((x & y) != 0) Console.Write(" " + " "); else Console.Write("* "); } Console.WriteLine(); } } // Driver code public static void Main() { int n = 16; // Function calling printSierpinski(n); }} // This code is contributed by vt_m
<?php// PHP implementation to// print sierpinski triangle. function printSierpinski($n){ for ($y = $n - 1; $y >= 0; $y--) { // printing space till // the value of y for ($i = 0; $i < $y; $i++) { echo " "; } // printing '*' for ($x = 0; $x + $y < $n; $x++) { // printing '*' at the appropriate // position is done by the and value // of x and y wherever value is 0 we // have printed '*' if($x & $y) echo" "; else echo"* "; } echo "\n"; }} // Driver code$n = 16;printSierpinski($n); // This code is contributed by Mithun Kumar?>
<script> // javascript program to print// sierpinski triangle. function printSierpinski(n){ for (var y = n - 1; y >= 0; y--) { // printing space till // the value of y for (var i = 0; i < y; i++) { document.write(" "); } // printing '*' for (var x = 0; x + y < n; x++) { // printing '*' at the appropriate // position is done by the and // value of x and y wherever value // is 0 we have printed '*' if ((x & y) != 0) document.write(" "); else document.write("* "); } document.write("<br>"); }} // Driver codevar n = 16; // Function callingprintSierpinski(n); // This code contributed by Princi Singh</script>
Output :
*
* *
* *
* * * *
* *
* * * *
* * * *
* * * * * * * *
* *
* * * *
* * * *
* * * * * * * *
* * * *
* * * * * * * *
* * * * * * * *
* * * * * * * * * * * * * * * *
References : Wiki
Mithun Kumar
princi singh
ankita_saini
Fractal
pattern-printing
triangle
School Programming
pattern-printing
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Introduction To PYTHON
Interfaces in Java
C++ Classes and Objects
C++ Data Types
Operator Overloading in C++
Polymorphism in C++
Types of Operating Systems
Constructors in C++
Constructors in Java
Exceptions in Java | [
{
"code": null,
"e": 52,
"s": 24,
"text": "\n15 Nov, 2021"
},
{
"code": null,
"e": 213,
"s": 52,
"text": "Sierpinski triangle is a fractal and attractive fixed set with the overall shape of an equilateral triangle. It subdivides recursively into smaller triangles. "
},
{
"code": null,
"e": 226,
"s": 213,
"text": "Examples : "
},
{
"code": null,
"e": 411,
"s": 226,
"text": "Input : n = 4\nOutput :\n * \n * * \n * * \n* * * * \n\nInput : n = 8\nOutput :\n * \n * * \n * * \n * * * * \n * * \n * * * * \n * * * * \n* * * * * * * * "
},
{
"code": null,
"e": 426,
"s": 413,
"text": "Approach : "
},
{
"code": null,
"e": 754,
"s": 426,
"text": "Sierpinski Triangle will be constructed from an equilateral triangle by repeated removal of triangular subsets. Steps for Construction : 1 . Take any equilateral triangle . 2 . Divide it into 4 smaller congruent triangle and remove the central triangle . 3 . Repeat step 2 for each of the remaining smaller triangles forever. "
},
{
"code": null,
"e": 810,
"s": 754,
"text": "Below is the program to implement sierpinski triangle "
},
{
"code": null,
"e": 814,
"s": 810,
"text": "C++"
},
{
"code": null,
"e": 819,
"s": 814,
"text": "Java"
},
{
"code": null,
"e": 827,
"s": 819,
"text": "Python3"
},
{
"code": null,
"e": 830,
"s": 827,
"text": "C#"
},
{
"code": null,
"e": 834,
"s": 830,
"text": "PHP"
},
{
"code": null,
"e": 845,
"s": 834,
"text": "Javascript"
},
{
"code": "// C++ program to print sierpinski triangle.#include <bits/stdc++.h>using namespace std; void printSierpinski(int n){ for (int y = n - 1; y >= 0; y--) { // printing space till // the value of y for (int i = 0; i < y; i++) { cout<<\" \"; } // printing '*' for (int x = 0; x + y < n; x++) { // printing '*' at the appropriate position // is done by the and value of x and y // wherever value is 0 we have printed '*' if(x & y) cout<<\" \"<<\" \"; else cout<<\"* \"; } cout<<endl; }} // Driver codeint main(){ int n = 16; // Function calling printSierpinski(n); return 0;}",
"e": 1555,
"s": 845,
"text": null
},
{
"code": "// Java program to print// sierpinski triangle.import java.util.*;import java.io.*; class GFG{ static void printSierpinski(int n) { for (int y = n - 1; y >= 0; y--) { // printing space till // the value of y for (int i = 0; i < y; i++) { System.out.print(\" \"); } // printing '*' for (int x = 0; x + y < n; x++) { // printing '*' at the appropriate // position is done by the and // value of x and y wherever value // is 0 we have printed '*' if ((x & y) != 0) System.out.print(\" \" + \" \"); else System.out.print(\"* \"); } System.out.print(\"\\n\"); } } // Driver code public static void main(String args[]) { int n = 16; // Function calling printSierpinski(n); }} // This code is contributed by Sahil_Bansall",
"e": 2587,
"s": 1555,
"text": null
},
{
"code": "# Python 3 program to print# sierpinski triangle. def printSierpinski( n) : y = n - 1 while(y >= 0) : # printing space till # the value of y i = 0 while(i < y ): print(\" \",end=\"\") i = i + 1 # printing '*' x = 0 while(x + y < n ): # printing '*' at the appropriate # position is done by the and # value of x and y wherever value # is 0 we have printed '*' if ((x & y) != 0) : print(\" \", end = \" \") else : print(\"* \", end = \"\") x =x + 1 print() y = y - 1 # Driver coden = 16 # Function callingprintSierpinski(n) # This code is contributed by Nikita Tiwari.",
"e": 3374,
"s": 2587,
"text": null
},
{
"code": "// C# program to print// sierpinski triangle.using System; class GFG { static void printSierpinski(int n) { for (int y = n - 1; y >= 0; y--) { // printing space till // the value of y for (int i = 0; i < y; i++) { Console.Write(\" \"); } // printing '*' for (int x = 0; x + y < n; x++) { // printing '*' at the appropriate // position is done by the and // value of x and y wherever value // is 0 we have printed '*' if ((x & y) != 0) Console.Write(\" \" + \" \"); else Console.Write(\"* \"); } Console.WriteLine(); } } // Driver code public static void Main() { int n = 16; // Function calling printSierpinski(n); }} // This code is contributed by vt_m",
"e": 4313,
"s": 3374,
"text": null
},
{
"code": "<?php// PHP implementation to// print sierpinski triangle. function printSierpinski($n){ for ($y = $n - 1; $y >= 0; $y--) { // printing space till // the value of y for ($i = 0; $i < $y; $i++) { echo \" \"; } // printing '*' for ($x = 0; $x + $y < $n; $x++) { // printing '*' at the appropriate // position is done by the and value // of x and y wherever value is 0 we // have printed '*' if($x & $y) echo\" \"; else echo\"* \"; } echo \"\\n\"; }} // Driver code$n = 16;printSierpinski($n); // This code is contributed by Mithun Kumar?>",
"e": 5000,
"s": 4313,
"text": null
},
{
"code": "<script> // javascript program to print// sierpinski triangle. function printSierpinski(n){ for (var y = n - 1; y >= 0; y--) { // printing space till // the value of y for (var i = 0; i < y; i++) { document.write(\" \"); } // printing '*' for (var x = 0; x + y < n; x++) { // printing '*' at the appropriate // position is done by the and // value of x and y wherever value // is 0 we have printed '*' if ((x & y) != 0) document.write(\" \"); else document.write(\"* \"); } document.write(\"<br>\"); }} // Driver codevar n = 16; // Function callingprintSierpinski(n); // This code contributed by Princi Singh</script>",
"e": 5786,
"s": 5000,
"text": null
},
{
"code": null,
"e": 5797,
"s": 5786,
"text": "Output : "
},
{
"code": null,
"e": 6205,
"s": 5797,
"text": " * \n * * \n * * \n * * * * \n * * \n * * * * \n * * * * \n * * * * * * * * \n * * \n * * * * \n * * * * \n * * * * * * * * \n * * * * \n * * * * * * * * \n * * * * * * * * \n* * * * * * * * * * * * * * * * "
},
{
"code": null,
"e": 6224,
"s": 6205,
"text": "References : Wiki "
},
{
"code": null,
"e": 6237,
"s": 6224,
"text": "Mithun Kumar"
},
{
"code": null,
"e": 6250,
"s": 6237,
"text": "princi singh"
},
{
"code": null,
"e": 6263,
"s": 6250,
"text": "ankita_saini"
},
{
"code": null,
"e": 6271,
"s": 6263,
"text": "Fractal"
},
{
"code": null,
"e": 6288,
"s": 6271,
"text": "pattern-printing"
},
{
"code": null,
"e": 6297,
"s": 6288,
"text": "triangle"
},
{
"code": null,
"e": 6316,
"s": 6297,
"text": "School Programming"
},
{
"code": null,
"e": 6333,
"s": 6316,
"text": "pattern-printing"
},
{
"code": null,
"e": 6431,
"s": 6333,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 6454,
"s": 6431,
"text": "Introduction To PYTHON"
},
{
"code": null,
"e": 6473,
"s": 6454,
"text": "Interfaces in Java"
},
{
"code": null,
"e": 6497,
"s": 6473,
"text": "C++ Classes and Objects"
},
{
"code": null,
"e": 6512,
"s": 6497,
"text": "C++ Data Types"
},
{
"code": null,
"e": 6540,
"s": 6512,
"text": "Operator Overloading in C++"
},
{
"code": null,
"e": 6560,
"s": 6540,
"text": "Polymorphism in C++"
},
{
"code": null,
"e": 6587,
"s": 6560,
"text": "Types of Operating Systems"
},
{
"code": null,
"e": 6607,
"s": 6587,
"text": "Constructors in C++"
},
{
"code": null,
"e": 6628,
"s": 6607,
"text": "Constructors in Java"
}
] |
Python | Blackman in numpy | 22 Jul, 2021
Blackman window : It is a taper formed by using the first three terms of a summation of cosines. It was designed to have close to the minimal leakage possible. It is close to optimal, only slightly worse than a Kaiser window.
Parameters(numpy.blackman):
M : int Number of points in the output window.
If zero or less, an empty array is returned.
Returns:
out : array
The window, with the maximum value normalized to one (the value one appears only if the number of samples is odd).
Example:
import numpy as np print(np.blackman(12))
Output:
[ -1.38777878e-17 3.26064346e-02 1.59903635e-01 4.14397981e-01
7.36045180e-01 9.67046769e-01 9.67046769e-01 7.36045180e-01
4.14397981e-01 1.59903635e-01 3.26064346e-02 -1.38777878e-17]
Plotting the window and its frequency response (requires SciPy and matplotlib):
Code : For Window:
import numpy as np import matplotlib.pyplot as plt from numpy.fft import fft, fftshift window = np.blackman(51) plt.plot(window) plt.title("Blackman window")plt.ylabel("Amplitude") plt.xlabel("Sample") plt.show()
Output:
Code : For frequency:
import numpy as np import matplotlib.pyplot as plt from numpy.fft import fft, fftshift window = np.blackman(51) plt.figure() A = fft(window, 2048) / 25.5mag = np.abs(fftshift(A))freq = np.linspace(-0.5, 0.5, len(A))response = 20 * np.log10(mag)response = np.clip(response, -100, 100) plt.plot(freq, response)plt.title("Frequency response of Blackman window")plt.ylabel("Magnitude [dB]")plt.xlabel("Normalized frequency [cycles per sample]")plt.axis('tight')plt.show()
Output:
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 ?
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": "\n22 Jul, 2021"
},
{
"code": null,
"e": 254,
"s": 28,
"text": "Blackman window : It is a taper formed by using the first three terms of a summation of cosines. It was designed to have close to the minimal leakage possible. It is close to optimal, only slightly worse than a Kaiser window."
},
{
"code": null,
"e": 402,
"s": 254,
"text": "Parameters(numpy.blackman): \nM : int Number of points in the output window.\n If zero or less, an empty array is returned.\n\nReturns: \nout : array"
},
{
"code": null,
"e": 517,
"s": 402,
"text": "The window, with the maximum value normalized to one (the value one appears only if the number of samples is odd)."
},
{
"code": null,
"e": 526,
"s": 517,
"text": "Example:"
},
{
"code": "import numpy as np print(np.blackman(12))",
"e": 568,
"s": 526,
"text": null
},
{
"code": null,
"e": 576,
"s": 568,
"text": "Output:"
},
{
"code": null,
"e": 785,
"s": 576,
"text": "[ -1.38777878e-17 3.26064346e-02 1.59903635e-01 4.14397981e-01\n 7.36045180e-01 9.67046769e-01 9.67046769e-01 7.36045180e-01\n 4.14397981e-01 1.59903635e-01 3.26064346e-02 -1.38777878e-17]\n"
},
{
"code": null,
"e": 865,
"s": 785,
"text": "Plotting the window and its frequency response (requires SciPy and matplotlib):"
},
{
"code": null,
"e": 884,
"s": 865,
"text": "Code : For Window:"
},
{
"code": "import numpy as np import matplotlib.pyplot as plt from numpy.fft import fft, fftshift window = np.blackman(51) plt.plot(window) plt.title(\"Blackman window\")plt.ylabel(\"Amplitude\") plt.xlabel(\"Sample\") plt.show() ",
"e": 1101,
"s": 884,
"text": null
},
{
"code": null,
"e": 1109,
"s": 1101,
"text": "Output:"
},
{
"code": null,
"e": 1131,
"s": 1109,
"text": "Code : For frequency:"
},
{
"code": "import numpy as np import matplotlib.pyplot as plt from numpy.fft import fft, fftshift window = np.blackman(51) plt.figure() A = fft(window, 2048) / 25.5mag = np.abs(fftshift(A))freq = np.linspace(-0.5, 0.5, len(A))response = 20 * np.log10(mag)response = np.clip(response, -100, 100) plt.plot(freq, response)plt.title(\"Frequency response of Blackman window\")plt.ylabel(\"Magnitude [dB]\")plt.xlabel(\"Normalized frequency [cycles per sample]\")plt.axis('tight')plt.show()",
"e": 1604,
"s": 1131,
"text": null
},
{
"code": null,
"e": 1612,
"s": 1604,
"text": "Output:"
},
{
"code": null,
"e": 1625,
"s": 1612,
"text": "Python-numpy"
},
{
"code": null,
"e": 1632,
"s": 1625,
"text": "Python"
},
{
"code": null,
"e": 1730,
"s": 1632,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 1762,
"s": 1730,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 1789,
"s": 1762,
"text": "Python Classes and Objects"
},
{
"code": null,
"e": 1810,
"s": 1789,
"text": "Python OOPs Concepts"
},
{
"code": null,
"e": 1833,
"s": 1810,
"text": "Introduction To PYTHON"
},
{
"code": null,
"e": 1864,
"s": 1833,
"text": "Python | os.path.join() method"
},
{
"code": null,
"e": 1920,
"s": 1864,
"text": "How to drop one or multiple columns in Pandas Dataframe"
},
{
"code": null,
"e": 1962,
"s": 1920,
"text": "How To Convert Python Dictionary To JSON?"
},
{
"code": null,
"e": 2004,
"s": 1962,
"text": "Check if element exists in list in Python"
},
{
"code": null,
"e": 2043,
"s": 2004,
"text": "Python | Get unique values from a list"
}
] |
How to Get Volume Mixer in Windows 10 ? | 08 Feb, 2021
Windows 10 was released in 2015 almost everyone liked the new interface. However, it removed the volume mixer shortcut which was available earlier. Using that one could easily adjust the volume for each application directly from the volume level control icon in the taskbar.
Windows 10 moved the volume mixer feature to the settings menu (Shortcut: Windows Key + I).
Settings -> System -> Sound -> Advanced Sound Options -> App volume and device preferences
Settings Menu
Default Volume Mixer in Windows 10
However, opening the settings menu every time to change the volume levels for different applications is quite cumbersome.
So, a better approach is to use the old legacy volume mixer which was available on the older versions.
It can be enabled in Windows 10 in some simple steps. Here we will be editing the Windows Registry and any unintended changes can cause your computer to stop functioning. So, please follow the steps very carefully.
1. Open the Registry Editor
Open the Run window (Windows Key + R). Type regedit there and press Enter to open the Registry Editor.
Run -> regedit
Search for ‘Registry Editor’ in the windows start menu.
Open Registry Editor using the start menu
Select Yes, if any prompt asks for permission then run the application.
2. Navigate to the following directory:
Computer\HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows NT\CurrentVersion
You can just paste it in the address box and press enter.
3. Right-click on CurrentVersion and then go to New -> Key and name it MTCUVC.
Create New Key
Name the Key
4. Right-click on MTCUVC and then click on New -> DWORD(32-bit) Value. Name it as EnableMtcUvc.
Create New DWORD
Name DWORD
5. Open it and ensure the default Value Data is 0.
Ensure Value Data is 0
6. Now just close the Registry Editor window and by clicking on the speaker icon on the taskbar, you get the older volume control.
You get the old volume control
In case you want to revert the changes, simply delete the MTCUVC Key created in the Registry Editor.
An alternative approach is to use the open-source EarTrumpet application available on the Microsoft Store, which gives a better-looking UI for the same task.
EarTrumpet UI
Technical Scripter 2020
How To
Operating Systems
Technical Scripter
TechTips
Operating Systems
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Set Git Username and Password in GitBash?
How to Install Jupyter Notebook on MacOS?
How to Install and Use NVM on Windows?
How to Install Python Packages for AWS Lambda Layers?
How to Permanently Disable Swap in Linux?
Types of Operating Systems
Banker's Algorithm in Operating System
Page Replacement Algorithms in Operating Systems
Disk Scheduling Algorithms
Introduction of Deadlock in Operating System | [
{
"code": null,
"e": 54,
"s": 26,
"text": "\n08 Feb, 2021"
},
{
"code": null,
"e": 329,
"s": 54,
"text": "Windows 10 was released in 2015 almost everyone liked the new interface. However, it removed the volume mixer shortcut which was available earlier. Using that one could easily adjust the volume for each application directly from the volume level control icon in the taskbar."
},
{
"code": null,
"e": 421,
"s": 329,
"text": "Windows 10 moved the volume mixer feature to the settings menu (Shortcut: Windows Key + I)."
},
{
"code": null,
"e": 514,
"s": 421,
"text": "Settings -> System -> Sound -> Advanced Sound Options -> App volume and device preferences "
},
{
"code": null,
"e": 528,
"s": 514,
"text": "Settings Menu"
},
{
"code": null,
"e": 564,
"s": 528,
"text": "Default Volume Mixer in Windows 10 "
},
{
"code": null,
"e": 686,
"s": 564,
"text": "However, opening the settings menu every time to change the volume levels for different applications is quite cumbersome."
},
{
"code": null,
"e": 789,
"s": 686,
"text": "So, a better approach is to use the old legacy volume mixer which was available on the older versions."
},
{
"code": null,
"e": 1004,
"s": 789,
"text": "It can be enabled in Windows 10 in some simple steps. Here we will be editing the Windows Registry and any unintended changes can cause your computer to stop functioning. So, please follow the steps very carefully."
},
{
"code": null,
"e": 1032,
"s": 1004,
"text": "1. Open the Registry Editor"
},
{
"code": null,
"e": 1136,
"s": 1032,
"text": "Open the Run window (Windows Key + R). Type regedit there and press Enter to open the Registry Editor. "
},
{
"code": null,
"e": 1151,
"s": 1136,
"text": "Run -> regedit"
},
{
"code": null,
"e": 1209,
"s": 1151,
"text": " Search for ‘Registry Editor’ in the windows start menu. "
},
{
"code": null,
"e": 1251,
"s": 1209,
"text": "Open Registry Editor using the start menu"
},
{
"code": null,
"e": 1323,
"s": 1251,
"text": "Select Yes, if any prompt asks for permission then run the application."
},
{
"code": null,
"e": 1363,
"s": 1323,
"text": "2. Navigate to the following directory:"
},
{
"code": null,
"e": 1436,
"s": 1363,
"text": "Computer\\HKEY_LOCAL_MACHINE\\SOFTWARE\\Microsoft\\Windows NT\\CurrentVersion"
},
{
"code": null,
"e": 1494,
"s": 1436,
"text": "You can just paste it in the address box and press enter."
},
{
"code": null,
"e": 1573,
"s": 1494,
"text": "3. Right-click on CurrentVersion and then go to New -> Key and name it MTCUVC."
},
{
"code": null,
"e": 1588,
"s": 1573,
"text": "Create New Key"
},
{
"code": null,
"e": 1601,
"s": 1588,
"text": "Name the Key"
},
{
"code": null,
"e": 1697,
"s": 1601,
"text": "4. Right-click on MTCUVC and then click on New -> DWORD(32-bit) Value. Name it as EnableMtcUvc."
},
{
"code": null,
"e": 1714,
"s": 1697,
"text": "Create New DWORD"
},
{
"code": null,
"e": 1725,
"s": 1714,
"text": "Name DWORD"
},
{
"code": null,
"e": 1776,
"s": 1725,
"text": "5. Open it and ensure the default Value Data is 0."
},
{
"code": null,
"e": 1799,
"s": 1776,
"text": "Ensure Value Data is 0"
},
{
"code": null,
"e": 1931,
"s": 1799,
"text": "6. Now just close the Registry Editor window and by clicking on the speaker icon on the taskbar, you get the older volume control. "
},
{
"code": null,
"e": 1962,
"s": 1931,
"text": "You get the old volume control"
},
{
"code": null,
"e": 2063,
"s": 1962,
"text": "In case you want to revert the changes, simply delete the MTCUVC Key created in the Registry Editor."
},
{
"code": null,
"e": 2221,
"s": 2063,
"text": "An alternative approach is to use the open-source EarTrumpet application available on the Microsoft Store, which gives a better-looking UI for the same task."
},
{
"code": null,
"e": 2235,
"s": 2221,
"text": "EarTrumpet UI"
},
{
"code": null,
"e": 2259,
"s": 2235,
"text": "Technical Scripter 2020"
},
{
"code": null,
"e": 2266,
"s": 2259,
"text": "How To"
},
{
"code": null,
"e": 2284,
"s": 2266,
"text": "Operating Systems"
},
{
"code": null,
"e": 2303,
"s": 2284,
"text": "Technical Scripter"
},
{
"code": null,
"e": 2312,
"s": 2303,
"text": "TechTips"
},
{
"code": null,
"e": 2330,
"s": 2312,
"text": "Operating Systems"
},
{
"code": null,
"e": 2428,
"s": 2330,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 2477,
"s": 2428,
"text": "How to Set Git Username and Password in GitBash?"
},
{
"code": null,
"e": 2519,
"s": 2477,
"text": "How to Install Jupyter Notebook on MacOS?"
},
{
"code": null,
"e": 2558,
"s": 2519,
"text": "How to Install and Use NVM on Windows?"
},
{
"code": null,
"e": 2612,
"s": 2558,
"text": "How to Install Python Packages for AWS Lambda Layers?"
},
{
"code": null,
"e": 2654,
"s": 2612,
"text": "How to Permanently Disable Swap in Linux?"
},
{
"code": null,
"e": 2681,
"s": 2654,
"text": "Types of Operating Systems"
},
{
"code": null,
"e": 2720,
"s": 2681,
"text": "Banker's Algorithm in Operating System"
},
{
"code": null,
"e": 2769,
"s": 2720,
"text": "Page Replacement Algorithms in Operating Systems"
},
{
"code": null,
"e": 2796,
"s": 2769,
"text": "Disk Scheduling Algorithms"
}
] |
Matplotlib.pyplot.loglog() function in Python | 06 Jul, 2021
Prerequisites: Matplotlib
Matplotlib is a comprehensive library for creating interactive, static and animated visualizations in python. Using general-purpose GUI toolkits like wxPython, SciPy, Tkinter or SciPy, it provides an object-oriented API for embedding plots into applications. Matplotlib.pyplot is a collection of functions that makes Matplotlib work like MATLAB.
Here, we will be exploring loglog() function of Matplotlib.pyplot. It is used to plot a log scale over both x and y-axis.
Syntax:
loglog(X,Y)
Where,
X and Y refer to x and y coordinates respectively.
Other function used is linespace(). It returns evenly spaced numbers over a specified interval.
Syntax:
np.linspace(start, stop, num, endpoint, retstep, dtype, axis)
Where,
Start : The starting value of sequence from where you want to show the line, or we can say starting point of line
Stop : It is the end value of the sequence at where the line stops, unless ‘endpoint’ is set to False.
Num : Number of samples to generate. Must be non-negative. By default, it is 50.
Endpoint : It works same as stop. If it is True then stop is the last sample else stop is excluded from the sequence.
Retstep : If True, return (‘samples’, ‘step’), where `step` is the spacing between samples.
Dtype : The type of the output array.
Axis : The axis in the result to store the samples and it is relevant only if start or stop are array-like
Example : Without loglog()
Python
# importing required modulesimport matplotlib.pyplot as pltimport numpy as np # inputs to plot using loglog plotx_input = np.linspace(0, 10, 50000) y_input = x_input**8 # plotting the value of x_input and y_input using plot functionplt.plot(x_input, y_input)
Output:
Example : With loglog()
Python3
# importing required modulesimport matplotlib.pyplot as pltimport numpy as np # inputs to plot using loglog plotx_input = np.linspace(0, 10, 50000) y_input = x_input**8 # plotting the value of x_input and y_input using loglog plotplt.loglog(x_input, y_input)
Output:
ruhelaa48
Matplotlib Pyplot-class
Picked
Python-matplotlib
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 | os.path.join() method
Introduction To PYTHON
Python OOPs Concepts
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
Create a directory in Python | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n06 Jul, 2021"
},
{
"code": null,
"e": 54,
"s": 28,
"text": "Prerequisites: Matplotlib"
},
{
"code": null,
"e": 400,
"s": 54,
"text": "Matplotlib is a comprehensive library for creating interactive, static and animated visualizations in python. Using general-purpose GUI toolkits like wxPython, SciPy, Tkinter or SciPy, it provides an object-oriented API for embedding plots into applications. Matplotlib.pyplot is a collection of functions that makes Matplotlib work like MATLAB."
},
{
"code": null,
"e": 522,
"s": 400,
"text": "Here, we will be exploring loglog() function of Matplotlib.pyplot. It is used to plot a log scale over both x and y-axis."
},
{
"code": null,
"e": 530,
"s": 522,
"text": "Syntax:"
},
{
"code": null,
"e": 542,
"s": 530,
"text": "loglog(X,Y)"
},
{
"code": null,
"e": 549,
"s": 542,
"text": "Where,"
},
{
"code": null,
"e": 600,
"s": 549,
"text": "X and Y refer to x and y coordinates respectively."
},
{
"code": null,
"e": 696,
"s": 600,
"text": "Other function used is linespace(). It returns evenly spaced numbers over a specified interval."
},
{
"code": null,
"e": 704,
"s": 696,
"text": "Syntax:"
},
{
"code": null,
"e": 766,
"s": 704,
"text": "np.linspace(start, stop, num, endpoint, retstep, dtype, axis)"
},
{
"code": null,
"e": 773,
"s": 766,
"text": "Where,"
},
{
"code": null,
"e": 887,
"s": 773,
"text": "Start : The starting value of sequence from where you want to show the line, or we can say starting point of line"
},
{
"code": null,
"e": 990,
"s": 887,
"text": "Stop : It is the end value of the sequence at where the line stops, unless ‘endpoint’ is set to False."
},
{
"code": null,
"e": 1071,
"s": 990,
"text": "Num : Number of samples to generate. Must be non-negative. By default, it is 50."
},
{
"code": null,
"e": 1189,
"s": 1071,
"text": "Endpoint : It works same as stop. If it is True then stop is the last sample else stop is excluded from the sequence."
},
{
"code": null,
"e": 1281,
"s": 1189,
"text": "Retstep : If True, return (‘samples’, ‘step’), where `step` is the spacing between samples."
},
{
"code": null,
"e": 1319,
"s": 1281,
"text": "Dtype : The type of the output array."
},
{
"code": null,
"e": 1426,
"s": 1319,
"text": "Axis : The axis in the result to store the samples and it is relevant only if start or stop are array-like"
},
{
"code": null,
"e": 1453,
"s": 1426,
"text": "Example : Without loglog()"
},
{
"code": null,
"e": 1460,
"s": 1453,
"text": "Python"
},
{
"code": "# importing required modulesimport matplotlib.pyplot as pltimport numpy as np # inputs to plot using loglog plotx_input = np.linspace(0, 10, 50000) y_input = x_input**8 # plotting the value of x_input and y_input using plot functionplt.plot(x_input, y_input)",
"e": 1720,
"s": 1460,
"text": null
},
{
"code": null,
"e": 1729,
"s": 1720,
"text": "Output: "
},
{
"code": null,
"e": 1753,
"s": 1729,
"text": "Example : With loglog()"
},
{
"code": null,
"e": 1761,
"s": 1753,
"text": "Python3"
},
{
"code": "# importing required modulesimport matplotlib.pyplot as pltimport numpy as np # inputs to plot using loglog plotx_input = np.linspace(0, 10, 50000) y_input = x_input**8 # plotting the value of x_input and y_input using loglog plotplt.loglog(x_input, y_input)",
"e": 2021,
"s": 1761,
"text": null
},
{
"code": null,
"e": 2029,
"s": 2021,
"text": "Output:"
},
{
"code": null,
"e": 2039,
"s": 2029,
"text": "ruhelaa48"
},
{
"code": null,
"e": 2063,
"s": 2039,
"text": "Matplotlib Pyplot-class"
},
{
"code": null,
"e": 2070,
"s": 2063,
"text": "Picked"
},
{
"code": null,
"e": 2088,
"s": 2070,
"text": "Python-matplotlib"
},
{
"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": 2283,
"s": 2252,
"text": "Python | os.path.join() method"
},
{
"code": null,
"e": 2306,
"s": 2283,
"text": "Introduction To PYTHON"
},
{
"code": null,
"e": 2327,
"s": 2306,
"text": "Python OOPs Concepts"
},
{
"code": null,
"e": 2383,
"s": 2327,
"text": "How to drop one or multiple columns in Pandas Dataframe"
},
{
"code": null,
"e": 2425,
"s": 2383,
"text": "How To Convert Python Dictionary To JSON?"
},
{
"code": null,
"e": 2467,
"s": 2425,
"text": "Check if element exists in list in Python"
},
{
"code": null,
"e": 2506,
"s": 2467,
"text": "Python | Get unique values from a list"
}
] |
ReactJS componentDidMount() Method | 20 Dec, 2020
The componentDidMount() method allows us to execute the React code when the component is already placed in the DOM (Document Object Model). This method is called during the Mounting phase of the React Life-cycle i.e after the component is rendered.
All the AJAX requests and the DOM or state updation should be coded in the componentDidMount() method block. We can also set up all the major subscriptions here but to avoid any performance issues, always remember to unsubscribe them in the componentWillUnmount() method.
Syntax:
componentDidMount()
Creating React Application:
Step 1: Create a React application using the following command:
npx create-react-app functiondemo
Step 2: After creating your project folder i.e. functiondemo, move to it using the following command:
cd functiondemo
Project Structure: It will look like the following.
Project Structure
Example: In this example, we are going to build a name color application that changes the color of the text when the component is rendered in the DOM tree.
App.js: Now write down the following code in the App.js file. Here, App is our default component where we have written our code.
Javascript
import React from 'react';class App extends React.Component { constructor(props) { super(props); // Initializing the state this.state = { color: 'lightgreen' }; } componentDidMount() { // Changing the state after 2 sec // from the time when the component // is rendered setTimeout(() => { this.setState({ color: 'wheat' }); }, 2000); } render() { return ( <div> <p style={{ color: this.state.color, backgroundColor: 'rgba(0,0,0,0.88)', textAlign: 'center', paddingTop: 20, width: 400, height: 80, margin: 'auto' }} > GeeksForGeeks </p> </div> ); }}export default App;
Step to Run Application: Run the application using the following command from the root directory of the project:
npm start
Output:
react-js
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here. | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n20 Dec, 2020"
},
{
"code": null,
"e": 277,
"s": 28,
"text": "The componentDidMount() method allows us to execute the React code when the component is already placed in the DOM (Document Object Model). This method is called during the Mounting phase of the React Life-cycle i.e after the component is rendered."
},
{
"code": null,
"e": 549,
"s": 277,
"text": "All the AJAX requests and the DOM or state updation should be coded in the componentDidMount() method block. We can also set up all the major subscriptions here but to avoid any performance issues, always remember to unsubscribe them in the componentWillUnmount() method."
},
{
"code": null,
"e": 557,
"s": 549,
"text": "Syntax:"
},
{
"code": null,
"e": 577,
"s": 557,
"text": "componentDidMount()"
},
{
"code": null,
"e": 605,
"s": 577,
"text": "Creating React Application:"
},
{
"code": null,
"e": 669,
"s": 605,
"text": "Step 1: Create a React application using the following command:"
},
{
"code": null,
"e": 703,
"s": 669,
"text": "npx create-react-app functiondemo"
},
{
"code": null,
"e": 805,
"s": 703,
"text": "Step 2: After creating your project folder i.e. functiondemo, move to it using the following command:"
},
{
"code": null,
"e": 821,
"s": 805,
"text": "cd functiondemo"
},
{
"code": null,
"e": 873,
"s": 821,
"text": "Project Structure: It will look like the following."
},
{
"code": null,
"e": 891,
"s": 873,
"text": "Project Structure"
},
{
"code": null,
"e": 1048,
"s": 891,
"text": "Example: In this example, we are going to build a name color application that changes the color of the text when the component is rendered in the DOM tree. "
},
{
"code": null,
"e": 1177,
"s": 1048,
"text": "App.js: Now write down the following code in the App.js file. Here, App is our default component where we have written our code."
},
{
"code": null,
"e": 1188,
"s": 1177,
"text": "Javascript"
},
{
"code": "import React from 'react';class App extends React.Component { constructor(props) { super(props); // Initializing the state this.state = { color: 'lightgreen' }; } componentDidMount() { // Changing the state after 2 sec // from the time when the component // is rendered setTimeout(() => { this.setState({ color: 'wheat' }); }, 2000); } render() { return ( <div> <p style={{ color: this.state.color, backgroundColor: 'rgba(0,0,0,0.88)', textAlign: 'center', paddingTop: 20, width: 400, height: 80, margin: 'auto' }} > GeeksForGeeks </p> </div> ); }}export default App;",
"e": 1939,
"s": 1188,
"text": null
},
{
"code": null,
"e": 2052,
"s": 1939,
"text": "Step to Run Application: Run the application using the following command from the root directory of the project:"
},
{
"code": null,
"e": 2062,
"s": 2052,
"text": "npm start"
},
{
"code": null,
"e": 2071,
"s": 2062,
"text": "Output: "
},
{
"code": null,
"e": 2080,
"s": 2071,
"text": "react-js"
},
{
"code": null,
"e": 2097,
"s": 2080,
"text": "Web Technologies"
}
] |
Find subarray with given sum | Set 2 (Handles Negative Numbers) | 24 Jun, 2022
Given an unsorted array of integers, find a subarray that adds to a given number. If there is more than one subarray with the sum of the given number, print any of them.
Examples:
Input: arr[] = {1, 4, 20, 3, 10, 5}, sum = 33
Output: Sum found between indexes 2 and 4
Explanation: Sum of elements between indices
2 and 4 is 20 + 3 + 10 = 33
Input: arr[] = {10, 2, -2, -20, 10}, sum = -10
Output: Sum found between indexes 0 to 3
Explanation: Sum of elements between indices
0 and 3 is 10 + 2 - 2 - 20 = -10
Input: arr[] = {-10, 0, 2, -2, -20, 10}, sum = 20
Output: No subarray with given sum exists
Explanation: There is no subarray with the given sum
Note: We have discussed a solution that does not handle negative integers here. In this post, negative integers are also handled.
Simple Approach: A simple solution is to consider all subarrays one by one and check the sum of every subarray. The following program implements the simple solution. Run two loops: the outer loop picks a starting point I and the inner loop tries all subarrays starting from i.
Algorithm:
Traverse the array from start to end.From every index start another loop from i to the end of the array to get all subarrays starting from i, and keep a variable sum to calculate the sum. For every index in the inner loop update sum = sum + array[j]If the sum is equal to the given sum then print the subarray.For every index in the inner loop update sum = sum + array[j]If the sum is equal to the given sum then print the subarray.
Traverse the array from start to end.
From every index start another loop from i to the end of the array to get all subarrays starting from i, and keep a variable sum to calculate the sum. For every index in the inner loop update sum = sum + array[j]If the sum is equal to the given sum then print the subarray.
For every index in the inner loop update sum = sum + array[j]
If the sum is equal to the given sum then print the subarray.
C++
Java
Python3
C#
Javascript
/* A simple program to print subarraywith sum as given sum */#include <bits/stdc++.h>using namespace std; /* Returns true if the there is a subarrayof arr[] with sum equal to 'sum' otherwisereturns false. Also, prints the result */int subArraySum(int arr[], int n, int sum){ int curr_sum, i, j; // Pick a starting point for (i = 0; i < n; i++) { curr_sum = 0; // try all subarrays starting with 'i' for (j = i ; j < n; j++) { curr_sum = curr_sum + arr[j]; if (curr_sum == sum) { cout << "Sum found between indexes " << i << " and " << j ; return 1; } } } cout << "No subarray found"; return 0;} // Driver Codeint main(){ int arr[] = { 15, 2, 4, 8, 9, 5, 10, 23 }; int n = sizeof(arr) / sizeof(arr[0]); int sum = 23; subArraySum(arr, n, sum); return 0;}
// Java program for the above approachimport java.util.*; class GFG{ /* Returns true if the there is a subarrayof arr[] with sum equal to 'sum' otherwisereturns false. Also, prints the result */static int subArraySum(int arr[], int n, int sum){ int curr_sum, i, j; // Pick a starting point for (i = 0; i < n; i++) { curr_sum = 0; // try all subarrays starting with 'i' for (j = i ; j < n; j++) { curr_sum = curr_sum + arr[j]; if (curr_sum == sum) { System.out.print( "Sum found between indexes " + i + " and " + j); return 1; } } } System.out.print("No subarray found"); return 0;} // Driver Codepublic static void main (String[] args){ int arr[] = { 15, 2, 4, 8, 9, 5, 10, 23 }; int n = arr.length; int sum = 23; subArraySum(arr, n, sum);}} // This code is contributed by code_hunt.
# Python3 program to print subarray# with sum as given sum # Returns true if the there is a subarray# of arr[] with sum equal to 'sum' otherwise# returns false. Also, prints the result */def subArraySum(arr, n, sum): # Pick a starting point for i in range(n): curr_sum = 0 # try all subarrays starting with 'i' for j in range(i, n): curr_sum += arr[j] if (curr_sum == sum): print("Sum found between indexes", i, "and", j) return print("No subarray found") # Driver Codearr = [15, 2, 4, 8, 9, 5, 10, 23]n = len(arr)sum = 23 # Function CallsubArraySum(arr, n, sum) # This code is contributed by phasing17
/* A simple program to print subarraywith sum as given sum */ using System; public static class GFG { /* Returns true if the there is a subarray of arr[] with sum equal to 'sum' otherwise returns false. Also, prints the result */ public static int subArraySum(int[] arr, int n, int sum) { int curr_sum; int i; int j; // Pick a starting point for (i = 0; i < n; i++) { curr_sum = 0; // try all subarrays starting with 'i' for (j = i; j < n; j++) { curr_sum = curr_sum + arr[j]; if (curr_sum == sum) { Console.Write( "Sum found between indexes "); Console.Write(i); Console.Write(" and "); Console.Write(j); return 1; } } } Console.Write("No subarray found"); return 0; } // Driver Code public static void Main() { int[] arr = { 15, 2, 4, 8, 9, 5, 10, 23 }; int n = arr.Length; int sum = 23; subArraySum(arr, n, sum); }} // This code is contributed by Aarti_Rathi
/* JavaScript program to print subarraywith sum as given sum */ /* Returns true if the there is a subarrayof arr[] with sum equal to 'sum' otherwisereturns false. Also, prints the result */function subArraySum(arr, n, sum){ var curr_sum, i, j; // Pick a starting point for (i = 0; i < n; i++) { curr_sum = 0; // try all subarrays starting with 'i' for (j = i ; j < n; j++) { curr_sum = curr_sum + arr[j]; if (curr_sum == sum) { console.log("Sum found between indexes " + i + " and " + j); return; } } } console.log("No subarray found");} // Driver Codevar arr = [ 15, 2, 4, 8, 9, 5, 10, 23 ];var n = arr.length;var sum = 23; //Function CallsubArraySum(arr, n, sum); //This code is contributed by phasing17
Sum found between indexes 1 and 4
Approach: The idea is to store the sum of elements of every prefix of the array in a hashmap, i.e, every index stores the sum of elements up to that index hashmap. So to check if there is a subarray with a sum equal to s, check for every index i, and sum up to that index as x. If there is a prefix with a sum equal to x – s, then the subarray with the given sum is found.
Algorithm:
Create a Hashmap (hm) to store a key-value pair, i.e, key = prefix sum and value = its index, and a variable to store the current sum (sum = 0) and the sum of the subarray as sTraverse through the array from start to end.For every element update the sum, i.e sum = sum + array[i]If the sum is equal to s then print that the subarray with the given sum is from 0 to iIf there is any key in the HashMap which is equal to sum – s then print that the subarray with the given sum is from hm[sum – s] to iPut the sum and index in the hashmap as a key-value pair.
Create a Hashmap (hm) to store a key-value pair, i.e, key = prefix sum and value = its index, and a variable to store the current sum (sum = 0) and the sum of the subarray as s
Traverse through the array from start to end.
For every element update the sum, i.e sum = sum + array[i]
If the sum is equal to s then print that the subarray with the given sum is from 0 to i
If there is any key in the HashMap which is equal to sum – s then print that the subarray with the given sum is from hm[sum – s] to i
Put the sum and index in the hashmap as a key-value pair.
Dry-run of the above approach:
Implementation:
C++
Java
Python3
C#
Javascript
// C++ program to print subarray with sum as given sum#include<bits/stdc++.h>using namespace std; // Function to print subarray with sum as given sumvoid subArraySum(int arr[], int n, int sum){ // create an empty map unordered_map<int, int> map; // Maintains sum of elements so far int curr_sum = 0; for (int i = 0; i < n; i++) { // add current element to curr_sum curr_sum = curr_sum + arr[i]; // if curr_sum is equal to target sum // we found a subarray starting from index 0 // and ending at index i if (curr_sum == sum) { cout << "Sum found between indexes " << 0 << " to " << i << endl; return; } // If curr_sum - sum already exists in map // we have found a subarray with target sum if (map.find(curr_sum - sum) != map.end()) { cout << "Sum found between indexes " << map[curr_sum - sum] + 1 << " to " << i << endl; return; } map[curr_sum] = i; } // If we reach here, then no subarray exists cout << "No subarray with given sum exists";} // Driver program to test above functionint main(){ int arr[] = {10, 2, -2, -20, 10}; int n = sizeof(arr)/sizeof(arr[0]); int sum = -10; subArraySum(arr, n, sum); return 0;}
// Java program to print subarray with sum as given sumimport java.util.*; class GFG { public static void subArraySum(int[] arr, int n, int sum) { //cur_sum to keep track of cumulative sum till that point int cur_sum = 0; int start = 0; int end = -1; HashMap<Integer, Integer> hashMap = new HashMap<>(); for (int i = 0; i < n; i++) { cur_sum = cur_sum + arr[i]; //check whether cur_sum - sum = 0, if 0 it means //the sub array is starting from index 0- so stop if (cur_sum - sum == 0) { start = 0; end = i; break; } //if hashMap already has the value, means we already // have subarray with the sum - so stop if (hashMap.containsKey(cur_sum - sum)) { start = hashMap.get(cur_sum - sum) + 1; end = i; break; } //if value is not present then add to hashmap hashMap.put(cur_sum, i); } // if end is -1 : means we have reached end without the sum if (end == -1) { System.out.println("No subarray with given sum exists"); } else { System.out.println("Sum found between indexes " + start + " to " + end); } } // Driver code public static void main(String[] args) { int[] arr = {10, 2, -2, -20, 10}; int n = arr.length; int sum = -10; subArraySum(arr, n, sum); }}
# Python3 program to print subarray with sum as given sum # Function to print subarray with sum as given sumdef subArraySum(arr, n, Sum): # create an empty map Map = {} # Maintains sum of elements so far curr_sum = 0 for i in range(0,n): # add current element to curr_sum curr_sum = curr_sum + arr[i] # if curr_sum is equal to target sum # we found a subarray starting from index 0 # and ending at index i if curr_sum == Sum: print("Sum found between indexes 0 to", i) return # If curr_sum - sum already exists in map # we have found a subarray with target sum if (curr_sum - Sum) in Map: print("Sum found between indexes", \ Map[curr_sum - Sum] + 1, "to", i) return Map[curr_sum] = i # If we reach here, then no subarray exists print("No subarray with given sum exists") # Driver program to test above functionif __name__ == "__main__": arr = [10, 2, -2, -20, 10] n = len(arr) Sum = -10 subArraySum(arr, n, Sum) # This code is contributed by Rituraj Jain
using System;using System.Collections.Generic; // C# program to print subarray with sum as given sum public class GFG{ public static void subArraySum(int[] arr, int n, int sum) { //cur_sum to keep track of cumulative sum till that point int cur_sum = 0; int start = 0; int end = -1; Dictionary<int, int> hashMap = new Dictionary<int, int>(); for (int i = 0; i < n; i++) { cur_sum = cur_sum + arr[i]; //check whether cur_sum - sum = 0, if 0 it means //the sub array is starting from index 0- so stop if (cur_sum - sum == 0) { start = 0; end = i; break; } //if hashMap already has the value, means we already // have subarray with the sum - so stop if (hashMap.ContainsKey(cur_sum - sum)) { start = hashMap[cur_sum - sum] + 1; end = i; break; } //if value is not present then add to hashmap hashMap[cur_sum] = i; } // if end is -1 : means we have reached end without the sum if (end == -1) { Console.WriteLine("No subarray with given sum exists"); } else { Console.WriteLine("Sum found between indexes " + start + " to " + end); } } // Driver code public static void Main(string[] args) { int[] arr = new int[] {10, 2, -2, -20, 10}; int n = arr.Length; int sum = -10; subArraySum(arr, n, sum); }} // This code is contributed by Shrikant13
<script> // Javascript program to print subarray with sum as given sum function subArraySum(arr, n, sum) { //cur_sum to keep track of cumulative sum till that point let cur_sum = 0; let start = 0; let end = -1; let hashMap = new Map(); for (let i = 0; i < n; i++) { cur_sum = cur_sum + arr[i]; //check whether cur_sum - sum = 0, if 0 it means //the sub array is starting from index 0- so stop if (cur_sum - sum == 0) { start = 0; end = i; break; } //if hashMap already has the value, means we already // have subarray with the sum - so stop if (hashMap.has(cur_sum - sum)) { start = hashMap.get(cur_sum - sum) + 1; end = i; break; } //if value is not present then add to hashmap hashMap.set(cur_sum, i); } // if end is -1 : means we have reached end without the sum if (end == -1) { document.write("No subarray with given sum exists"); } else { document.write("Sum found between indexes " + start + " to " + end); } } // Driver program let arr = [10, 2, -2, -20, 10]; let n = arr.length; let sum = -10; subArraySum(arr, n, sum); </script>
Sum found between indexes 0 to 3
Complexity Analysis:
Time complexity: O(N). If hashing is performed with the help of an array, then this is the time complexity. In case the elements cannot be hashed in an array a hash map can also be used as shown in the above code.
Auxiliary space: O(n). As a HashMap is needed, this takes linear space.
Find subarray with given sum | Set 2 (Handles Negative Numbers) | GeeksforGeeks - YouTubeGeeksforGeeks531K subscribersFind subarray with given sum | Set 2 (Handles Negative Numbers) | GeeksforGeeksWatch laterShareCopy linkInfoShoppingTap to unmuteIf playback doesn't begin shortly, try restarting your device.More videosMore videosYou're signed outVideos you watch may be added to the TV's watch history and influence TV recommendations. To avoid this, cancel and sign in to YouTube on your computer.CancelConfirmSwitch cameraShareInclude playlistAn error occurred while retrieving sharing information. Please try again later.Watch on0:000:000:00 / 2:40•Live•<div class="player-unavailable"><h1 class="message">An error occurred.</h1><div class="submessage"><a href="https://www.youtube.com/watch?v=G0ocgTgW464" target="_blank">Try watching this video on www.youtube.com</a>, or enable JavaScript if it is disabled in your browser.</div></div>
Find subarray with given sum with negatives allowed in constant spaceThis article is contributed by Aditya Goel. 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.
Sravan Reddy
shrikanth13
rituraj_jain
ManasChhabra2
nidhi_biet
umang-jain
andrew1234
avijitmondal1998
manikarora059
khushboogoyal499
prasanna1995
code_hunt
surindertarika1234
phasing17
codewithshinchan
cpp-unordered_map
prefix-sum
STL
subarray
subarray-sum
Arrays
Hash
prefix-sum
Arrays
Hash
STL
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here. | [
{
"code": null,
"e": 54,
"s": 26,
"text": "\n24 Jun, 2022"
},
{
"code": null,
"e": 224,
"s": 54,
"text": "Given an unsorted array of integers, find a subarray that adds to a given number. If there is more than one subarray with the sum of the given number, print any of them."
},
{
"code": null,
"e": 236,
"s": 224,
"text": "Examples: "
},
{
"code": null,
"e": 710,
"s": 236,
"text": "Input: arr[] = {1, 4, 20, 3, 10, 5}, sum = 33\nOutput: Sum found between indexes 2 and 4\nExplanation: Sum of elements between indices\n2 and 4 is 20 + 3 + 10 = 33\n\nInput: arr[] = {10, 2, -2, -20, 10}, sum = -10\nOutput: Sum found between indexes 0 to 3\nExplanation: Sum of elements between indices\n0 and 3 is 10 + 2 - 2 - 20 = -10\n\nInput: arr[] = {-10, 0, 2, -2, -20, 10}, sum = 20\nOutput: No subarray with given sum exists\nExplanation: There is no subarray with the given sum"
},
{
"code": null,
"e": 840,
"s": 710,
"text": "Note: We have discussed a solution that does not handle negative integers here. In this post, negative integers are also handled."
},
{
"code": null,
"e": 1117,
"s": 840,
"text": "Simple Approach: A simple solution is to consider all subarrays one by one and check the sum of every subarray. The following program implements the simple solution. Run two loops: the outer loop picks a starting point I and the inner loop tries all subarrays starting from i."
},
{
"code": null,
"e": 1130,
"s": 1117,
"text": "Algorithm: "
},
{
"code": null,
"e": 1563,
"s": 1130,
"text": "Traverse the array from start to end.From every index start another loop from i to the end of the array to get all subarrays starting from i, and keep a variable sum to calculate the sum. For every index in the inner loop update sum = sum + array[j]If the sum is equal to the given sum then print the subarray.For every index in the inner loop update sum = sum + array[j]If the sum is equal to the given sum then print the subarray."
},
{
"code": null,
"e": 1601,
"s": 1563,
"text": "Traverse the array from start to end."
},
{
"code": null,
"e": 1875,
"s": 1601,
"text": "From every index start another loop from i to the end of the array to get all subarrays starting from i, and keep a variable sum to calculate the sum. For every index in the inner loop update sum = sum + array[j]If the sum is equal to the given sum then print the subarray."
},
{
"code": null,
"e": 1937,
"s": 1875,
"text": "For every index in the inner loop update sum = sum + array[j]"
},
{
"code": null,
"e": 1999,
"s": 1937,
"text": "If the sum is equal to the given sum then print the subarray."
},
{
"code": null,
"e": 2003,
"s": 1999,
"text": "C++"
},
{
"code": null,
"e": 2008,
"s": 2003,
"text": "Java"
},
{
"code": null,
"e": 2016,
"s": 2008,
"text": "Python3"
},
{
"code": null,
"e": 2019,
"s": 2016,
"text": "C#"
},
{
"code": null,
"e": 2030,
"s": 2019,
"text": "Javascript"
},
{
"code": "/* A simple program to print subarraywith sum as given sum */#include <bits/stdc++.h>using namespace std; /* Returns true if the there is a subarrayof arr[] with sum equal to 'sum' otherwisereturns false. Also, prints the result */int subArraySum(int arr[], int n, int sum){ int curr_sum, i, j; // Pick a starting point for (i = 0; i < n; i++) { curr_sum = 0; // try all subarrays starting with 'i' for (j = i ; j < n; j++) { curr_sum = curr_sum + arr[j]; if (curr_sum == sum) { cout << \"Sum found between indexes \" << i << \" and \" << j ; return 1; } } } cout << \"No subarray found\"; return 0;} // Driver Codeint main(){ int arr[] = { 15, 2, 4, 8, 9, 5, 10, 23 }; int n = sizeof(arr) / sizeof(arr[0]); int sum = 23; subArraySum(arr, n, sum); return 0;}",
"e": 2970,
"s": 2030,
"text": null
},
{
"code": "// Java program for the above approachimport java.util.*; class GFG{ /* Returns true if the there is a subarrayof arr[] with sum equal to 'sum' otherwisereturns false. Also, prints the result */static int subArraySum(int arr[], int n, int sum){ int curr_sum, i, j; // Pick a starting point for (i = 0; i < n; i++) { curr_sum = 0; // try all subarrays starting with 'i' for (j = i ; j < n; j++) { curr_sum = curr_sum + arr[j]; if (curr_sum == sum) { System.out.print( \"Sum found between indexes \" + i + \" and \" + j); return 1; } } } System.out.print(\"No subarray found\"); return 0;} // Driver Codepublic static void main (String[] args){ int arr[] = { 15, 2, 4, 8, 9, 5, 10, 23 }; int n = arr.length; int sum = 23; subArraySum(arr, n, sum);}} // This code is contributed by code_hunt.",
"e": 3938,
"s": 2970,
"text": null
},
{
"code": "# Python3 program to print subarray# with sum as given sum # Returns true if the there is a subarray# of arr[] with sum equal to 'sum' otherwise# returns false. Also, prints the result */def subArraySum(arr, n, sum): # Pick a starting point for i in range(n): curr_sum = 0 # try all subarrays starting with 'i' for j in range(i, n): curr_sum += arr[j] if (curr_sum == sum): print(\"Sum found between indexes\", i, \"and\", j) return print(\"No subarray found\") # Driver Codearr = [15, 2, 4, 8, 9, 5, 10, 23]n = len(arr)sum = 23 # Function CallsubArraySum(arr, n, sum) # This code is contributed by phasing17",
"e": 4628,
"s": 3938,
"text": null
},
{
"code": "/* A simple program to print subarraywith sum as given sum */ using System; public static class GFG { /* Returns true if the there is a subarray of arr[] with sum equal to 'sum' otherwise returns false. Also, prints the result */ public static int subArraySum(int[] arr, int n, int sum) { int curr_sum; int i; int j; // Pick a starting point for (i = 0; i < n; i++) { curr_sum = 0; // try all subarrays starting with 'i' for (j = i; j < n; j++) { curr_sum = curr_sum + arr[j]; if (curr_sum == sum) { Console.Write( \"Sum found between indexes \"); Console.Write(i); Console.Write(\" and \"); Console.Write(j); return 1; } } } Console.Write(\"No subarray found\"); return 0; } // Driver Code public static void Main() { int[] arr = { 15, 2, 4, 8, 9, 5, 10, 23 }; int n = arr.Length; int sum = 23; subArraySum(arr, n, sum); }} // This code is contributed by Aarti_Rathi",
"e": 5817,
"s": 4628,
"text": null
},
{
"code": "/* JavaScript program to print subarraywith sum as given sum */ /* Returns true if the there is a subarrayof arr[] with sum equal to 'sum' otherwisereturns false. Also, prints the result */function subArraySum(arr, n, sum){ var curr_sum, i, j; // Pick a starting point for (i = 0; i < n; i++) { curr_sum = 0; // try all subarrays starting with 'i' for (j = i ; j < n; j++) { curr_sum = curr_sum + arr[j]; if (curr_sum == sum) { console.log(\"Sum found between indexes \" + i + \" and \" + j); return; } } } console.log(\"No subarray found\");} // Driver Codevar arr = [ 15, 2, 4, 8, 9, 5, 10, 23 ];var n = arr.length;var sum = 23; //Function CallsubArraySum(arr, n, sum); //This code is contributed by phasing17",
"e": 6649,
"s": 5817,
"text": null
},
{
"code": null,
"e": 6683,
"s": 6649,
"text": "Sum found between indexes 1 and 4"
},
{
"code": null,
"e": 7057,
"s": 6683,
"text": "Approach: The idea is to store the sum of elements of every prefix of the array in a hashmap, i.e, every index stores the sum of elements up to that index hashmap. So to check if there is a subarray with a sum equal to s, check for every index i, and sum up to that index as x. If there is a prefix with a sum equal to x – s, then the subarray with the given sum is found. "
},
{
"code": null,
"e": 7070,
"s": 7057,
"text": "Algorithm: "
},
{
"code": null,
"e": 7627,
"s": 7070,
"text": "Create a Hashmap (hm) to store a key-value pair, i.e, key = prefix sum and value = its index, and a variable to store the current sum (sum = 0) and the sum of the subarray as sTraverse through the array from start to end.For every element update the sum, i.e sum = sum + array[i]If the sum is equal to s then print that the subarray with the given sum is from 0 to iIf there is any key in the HashMap which is equal to sum – s then print that the subarray with the given sum is from hm[sum – s] to iPut the sum and index in the hashmap as a key-value pair."
},
{
"code": null,
"e": 7804,
"s": 7627,
"text": "Create a Hashmap (hm) to store a key-value pair, i.e, key = prefix sum and value = its index, and a variable to store the current sum (sum = 0) and the sum of the subarray as s"
},
{
"code": null,
"e": 7850,
"s": 7804,
"text": "Traverse through the array from start to end."
},
{
"code": null,
"e": 7909,
"s": 7850,
"text": "For every element update the sum, i.e sum = sum + array[i]"
},
{
"code": null,
"e": 7997,
"s": 7909,
"text": "If the sum is equal to s then print that the subarray with the given sum is from 0 to i"
},
{
"code": null,
"e": 8131,
"s": 7997,
"text": "If there is any key in the HashMap which is equal to sum – s then print that the subarray with the given sum is from hm[sum – s] to i"
},
{
"code": null,
"e": 8189,
"s": 8131,
"text": "Put the sum and index in the hashmap as a key-value pair."
},
{
"code": null,
"e": 8221,
"s": 8189,
"text": "Dry-run of the above approach: "
},
{
"code": null,
"e": 8239,
"s": 8221,
"text": "Implementation: "
},
{
"code": null,
"e": 8243,
"s": 8239,
"text": "C++"
},
{
"code": null,
"e": 8248,
"s": 8243,
"text": "Java"
},
{
"code": null,
"e": 8256,
"s": 8248,
"text": "Python3"
},
{
"code": null,
"e": 8259,
"s": 8256,
"text": "C#"
},
{
"code": null,
"e": 8270,
"s": 8259,
"text": "Javascript"
},
{
"code": "// C++ program to print subarray with sum as given sum#include<bits/stdc++.h>using namespace std; // Function to print subarray with sum as given sumvoid subArraySum(int arr[], int n, int sum){ // create an empty map unordered_map<int, int> map; // Maintains sum of elements so far int curr_sum = 0; for (int i = 0; i < n; i++) { // add current element to curr_sum curr_sum = curr_sum + arr[i]; // if curr_sum is equal to target sum // we found a subarray starting from index 0 // and ending at index i if (curr_sum == sum) { cout << \"Sum found between indexes \" << 0 << \" to \" << i << endl; return; } // If curr_sum - sum already exists in map // we have found a subarray with target sum if (map.find(curr_sum - sum) != map.end()) { cout << \"Sum found between indexes \" << map[curr_sum - sum] + 1 << \" to \" << i << endl; return; } map[curr_sum] = i; } // If we reach here, then no subarray exists cout << \"No subarray with given sum exists\";} // Driver program to test above functionint main(){ int arr[] = {10, 2, -2, -20, 10}; int n = sizeof(arr)/sizeof(arr[0]); int sum = -10; subArraySum(arr, n, sum); return 0;}",
"e": 9628,
"s": 8270,
"text": null
},
{
"code": "// Java program to print subarray with sum as given sumimport java.util.*; class GFG { public static void subArraySum(int[] arr, int n, int sum) { //cur_sum to keep track of cumulative sum till that point int cur_sum = 0; int start = 0; int end = -1; HashMap<Integer, Integer> hashMap = new HashMap<>(); for (int i = 0; i < n; i++) { cur_sum = cur_sum + arr[i]; //check whether cur_sum - sum = 0, if 0 it means //the sub array is starting from index 0- so stop if (cur_sum - sum == 0) { start = 0; end = i; break; } //if hashMap already has the value, means we already // have subarray with the sum - so stop if (hashMap.containsKey(cur_sum - sum)) { start = hashMap.get(cur_sum - sum) + 1; end = i; break; } //if value is not present then add to hashmap hashMap.put(cur_sum, i); } // if end is -1 : means we have reached end without the sum if (end == -1) { System.out.println(\"No subarray with given sum exists\"); } else { System.out.println(\"Sum found between indexes \" + start + \" to \" + end); } } // Driver code public static void main(String[] args) { int[] arr = {10, 2, -2, -20, 10}; int n = arr.length; int sum = -10; subArraySum(arr, n, sum); }}",
"e": 11170,
"s": 9628,
"text": null
},
{
"code": "# Python3 program to print subarray with sum as given sum # Function to print subarray with sum as given sumdef subArraySum(arr, n, Sum): # create an empty map Map = {} # Maintains sum of elements so far curr_sum = 0 for i in range(0,n): # add current element to curr_sum curr_sum = curr_sum + arr[i] # if curr_sum is equal to target sum # we found a subarray starting from index 0 # and ending at index i if curr_sum == Sum: print(\"Sum found between indexes 0 to\", i) return # If curr_sum - sum already exists in map # we have found a subarray with target sum if (curr_sum - Sum) in Map: print(\"Sum found between indexes\", \\ Map[curr_sum - Sum] + 1, \"to\", i) return Map[curr_sum] = i # If we reach here, then no subarray exists print(\"No subarray with given sum exists\") # Driver program to test above functionif __name__ == \"__main__\": arr = [10, 2, -2, -20, 10] n = len(arr) Sum = -10 subArraySum(arr, n, Sum) # This code is contributed by Rituraj Jain",
"e": 12371,
"s": 11170,
"text": null
},
{
"code": "using System;using System.Collections.Generic; // C# program to print subarray with sum as given sum public class GFG{ public static void subArraySum(int[] arr, int n, int sum) { //cur_sum to keep track of cumulative sum till that point int cur_sum = 0; int start = 0; int end = -1; Dictionary<int, int> hashMap = new Dictionary<int, int>(); for (int i = 0; i < n; i++) { cur_sum = cur_sum + arr[i]; //check whether cur_sum - sum = 0, if 0 it means //the sub array is starting from index 0- so stop if (cur_sum - sum == 0) { start = 0; end = i; break; } //if hashMap already has the value, means we already // have subarray with the sum - so stop if (hashMap.ContainsKey(cur_sum - sum)) { start = hashMap[cur_sum - sum] + 1; end = i; break; } //if value is not present then add to hashmap hashMap[cur_sum] = i; } // if end is -1 : means we have reached end without the sum if (end == -1) { Console.WriteLine(\"No subarray with given sum exists\"); } else { Console.WriteLine(\"Sum found between indexes \" + start + \" to \" + end); } } // Driver code public static void Main(string[] args) { int[] arr = new int[] {10, 2, -2, -20, 10}; int n = arr.Length; int sum = -10; subArraySum(arr, n, sum); }} // This code is contributed by Shrikant13",
"e": 14024,
"s": 12371,
"text": null
},
{
"code": "<script> // Javascript program to print subarray with sum as given sum function subArraySum(arr, n, sum) { //cur_sum to keep track of cumulative sum till that point let cur_sum = 0; let start = 0; let end = -1; let hashMap = new Map(); for (let i = 0; i < n; i++) { cur_sum = cur_sum + arr[i]; //check whether cur_sum - sum = 0, if 0 it means //the sub array is starting from index 0- so stop if (cur_sum - sum == 0) { start = 0; end = i; break; } //if hashMap already has the value, means we already // have subarray with the sum - so stop if (hashMap.has(cur_sum - sum)) { start = hashMap.get(cur_sum - sum) + 1; end = i; break; } //if value is not present then add to hashmap hashMap.set(cur_sum, i); } // if end is -1 : means we have reached end without the sum if (end == -1) { document.write(\"No subarray with given sum exists\"); } else { document.write(\"Sum found between indexes \" + start + \" to \" + end); } } // Driver program let arr = [10, 2, -2, -20, 10]; let n = arr.length; let sum = -10; subArraySum(arr, n, sum); </script>",
"e": 15459,
"s": 14024,
"text": null
},
{
"code": null,
"e": 15492,
"s": 15459,
"text": "Sum found between indexes 0 to 3"
},
{
"code": null,
"e": 15515,
"s": 15492,
"text": "Complexity Analysis: "
},
{
"code": null,
"e": 15729,
"s": 15515,
"text": "Time complexity: O(N). If hashing is performed with the help of an array, then this is the time complexity. In case the elements cannot be hashed in an array a hash map can also be used as shown in the above code."
},
{
"code": null,
"e": 15801,
"s": 15729,
"text": "Auxiliary space: O(n). As a HashMap is needed, this takes linear space."
},
{
"code": null,
"e": 16745,
"s": 15801,
"text": "Find subarray with given sum | Set 2 (Handles Negative Numbers) | GeeksforGeeks - YouTubeGeeksforGeeks531K subscribersFind subarray with given sum | Set 2 (Handles Negative Numbers) | GeeksforGeeksWatch laterShareCopy linkInfoShoppingTap to unmuteIf playback doesn't begin shortly, try restarting your device.More videosMore videosYou're signed outVideos you watch may be added to the TV's watch history and influence TV recommendations. To avoid this, cancel and sign in to YouTube on your computer.CancelConfirmSwitch cameraShareInclude playlistAn error occurred while retrieving sharing information. Please try again later.Watch on0:000:000:00 / 2:40•Live•<div class=\"player-unavailable\"><h1 class=\"message\">An error occurred.</h1><div class=\"submessage\"><a href=\"https://www.youtube.com/watch?v=G0ocgTgW464\" 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": 17234,
"s": 16745,
"text": "Find subarray with given sum with negatives allowed in constant spaceThis article is contributed by Aditya Goel. 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": 17247,
"s": 17234,
"text": "Sravan Reddy"
},
{
"code": null,
"e": 17259,
"s": 17247,
"text": "shrikanth13"
},
{
"code": null,
"e": 17272,
"s": 17259,
"text": "rituraj_jain"
},
{
"code": null,
"e": 17286,
"s": 17272,
"text": "ManasChhabra2"
},
{
"code": null,
"e": 17297,
"s": 17286,
"text": "nidhi_biet"
},
{
"code": null,
"e": 17308,
"s": 17297,
"text": "umang-jain"
},
{
"code": null,
"e": 17319,
"s": 17308,
"text": "andrew1234"
},
{
"code": null,
"e": 17336,
"s": 17319,
"text": "avijitmondal1998"
},
{
"code": null,
"e": 17350,
"s": 17336,
"text": "manikarora059"
},
{
"code": null,
"e": 17367,
"s": 17350,
"text": "khushboogoyal499"
},
{
"code": null,
"e": 17380,
"s": 17367,
"text": "prasanna1995"
},
{
"code": null,
"e": 17390,
"s": 17380,
"text": "code_hunt"
},
{
"code": null,
"e": 17409,
"s": 17390,
"text": "surindertarika1234"
},
{
"code": null,
"e": 17419,
"s": 17409,
"text": "phasing17"
},
{
"code": null,
"e": 17436,
"s": 17419,
"text": "codewithshinchan"
},
{
"code": null,
"e": 17454,
"s": 17436,
"text": "cpp-unordered_map"
},
{
"code": null,
"e": 17465,
"s": 17454,
"text": "prefix-sum"
},
{
"code": null,
"e": 17469,
"s": 17465,
"text": "STL"
},
{
"code": null,
"e": 17478,
"s": 17469,
"text": "subarray"
},
{
"code": null,
"e": 17491,
"s": 17478,
"text": "subarray-sum"
},
{
"code": null,
"e": 17498,
"s": 17491,
"text": "Arrays"
},
{
"code": null,
"e": 17503,
"s": 17498,
"text": "Hash"
},
{
"code": null,
"e": 17514,
"s": 17503,
"text": "prefix-sum"
},
{
"code": null,
"e": 17521,
"s": 17514,
"text": "Arrays"
},
{
"code": null,
"e": 17526,
"s": 17521,
"text": "Hash"
},
{
"code": null,
"e": 17530,
"s": 17526,
"text": "STL"
}
] |
Difference between Directive and Component in AngularJS | 16 Jun, 2020
Introduction:We will start this topic of finding the differences between Directive and Components, by getting a brief idea about these two terminologies, what they mean, and their behavioral characteristics towards building a crisp, and powerful AnglarJS code. Directives are introduced with the invention of Angular, as a structural framework for building dynamic web applications. Directives were popular in manipulating the DOM i.e. Document Object Model and create new custom elements that were part of the DOM. With the upgrade in technology and various modifications in the later versions of Angular(Angular 2 and higher versions, as Angular 2 is itself dependent on the component-based structure) the use of Components is now seen with great interest among the developers. Also, Components are termed as a more simplified version of Directives.
Basic definitions:Directives are functions that are invoked whenever AngularJs’s HTML compiler($compile) finds it in DOM. It tells to attach a specified behavior to that DOM element (e.g. via event listeners), or even to transform the DOM element and its children.Components are just a simplified version of a directive. More specifically Components can be called a special kind of directives with templates, which are mainly used for component-based architecture.Examples:
Component-Syntax:import {Component, View} from 'angular2/angular2';
@Component ({........
........ })
@View ({............
...........})import {Component, View} from 'angular2/angular2';@Component({ selector: 'message'})@View({ template: ` <h6>Hello GeeksforGeeks</h6> <h6>This is an example of component</h6> `})class Message { constructor(public version: string) {}}Output:Hello GeeksforGeeks
This is an example of component
import {Component, View} from 'angular2/angular2';
@Component ({........
........ })
@View ({............
...........})
import {Component, View} from 'angular2/angular2';@Component({ selector: 'message'})@View({ template: ` <h6>Hello GeeksforGeeks</h6> <h6>This is an example of component</h6> `})class Message { constructor(public version: string) {}}
Output:
Hello GeeksforGeeks
This is an example of component
Directive-Syntax:import {Directive} from 'angular2/angular2';
@Directive({........
........})import {Directive} from 'angular2/angular2'; @Directive({ selector: "[myDirective]", hostListeners: { 'click': 'showMessage()' }})class Message { constructor() {} showMessage() { console.log('This is an example of directive'); }} <button>GeeksforGeeks</button>Output:Geeksforgeeks
This is an example of directive
import {Directive} from 'angular2/angular2';
@Directive({........
........})
import {Directive} from 'angular2/angular2'; @Directive({ selector: "[myDirective]", hostListeners: { 'click': 'showMessage()' }})class Message { constructor() {} showMessage() { console.log('This is an example of directive'); }} <button>GeeksforGeeks</button>
Output:
Geeksforgeeks
This is an example of directive
Explanation:In the above examples, we have seen how to write simple Angular code for printing some messages, both using Component, and Directive. In the Component’s example, we have seen that it is mandatory to write view property, whereas, for Directives, we do not need to use view or templates. Let us now discuss what are the main differences between these two.Differences:
A component is always elements (‘E’) where directive can be an attribute, element name, comment or CSS class (‘E’, ‘A’, ‘C’, ‘M’). Templates are the mandatory property and always required in Component, but Directive doesn’t always require them.Component is used to break up the application into smaller components. But Directive is used to design re-usable components, which is more behavior-oriented. That is why components are widely used in later versions of Angular to make things easy and build a total component-based model.As Component has views, viewEncapsulation can be defined. Whereas Directive doesn’t have views. So you can’t use viewEncapsulation in directive.Although Components make it easier to write simple, effective code, it has a simpler configuration than plain directives, it is optimized for component-based architecture. But when not to use a component? The answer is – a component does not support “compile” and “pre-link” functions. So for manipulating DOM objects, we should use the directives.
A component is always elements (‘E’) where directive can be an attribute, element name, comment or CSS class (‘E’, ‘A’, ‘C’, ‘M’). Templates are the mandatory property and always required in Component, but Directive doesn’t always require them.
Component is used to break up the application into smaller components. But Directive is used to design re-usable components, which is more behavior-oriented. That is why components are widely used in later versions of Angular to make things easy and build a total component-based model.
As Component has views, viewEncapsulation can be defined. Whereas Directive doesn’t have views. So you can’t use viewEncapsulation in directive.
Although Components make it easier to write simple, effective code, it has a simpler configuration than plain directives, it is optimized for component-based architecture. But when not to use a component? The answer is – a component does not support “compile” and “pre-link” functions. So for manipulating DOM objects, we should use the directives.
Components should never modify any data or DOM that is out of their own scope. Directives have isolated scopes, by default the child inherits the scope from its parent.
Only one component can be present per DOM element. There can be more than one directive in a DOM element
To register component we use @Component meta-data annotation. For directive, we use @Directive meta-data annotation. Two simple examples are shown in the point ‘Example’ above.
Conclusion:A basic study on the topic has been given. Whether to use Component or Directive, it totally depends on the purpose of writing a particular code for the usage. With the advent of emerging technologies, most of the web page design architectures are aiming towards obtaining a component-based model and this is when we need Components. On the other hand, directives give us plenty of options as selectors, input, output, providers to write the code creatively.
AngularJS-Directives
Picked
AngularJS
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Auth Guards in Angular 9/10/11
Routing in Angular 9/10
What is AOT and JIT Compiler in Angular ?
Angular PrimeNG Dropdown Component
How to set focus on input field automatically on page load in AngularJS ?
Installation of Node.js on Linux
Top 10 Projects For Beginners To Practice HTML and CSS Skills
Difference between var, let and const keywords in JavaScript
How to insert spaces/tabs in text using HTML/CSS?
How to fetch data from an API in ReactJS ? | [
{
"code": null,
"e": 53,
"s": 25,
"text": "\n16 Jun, 2020"
},
{
"code": null,
"e": 905,
"s": 53,
"text": "Introduction:We will start this topic of finding the differences between Directive and Components, by getting a brief idea about these two terminologies, what they mean, and their behavioral characteristics towards building a crisp, and powerful AnglarJS code. Directives are introduced with the invention of Angular, as a structural framework for building dynamic web applications. Directives were popular in manipulating the DOM i.e. Document Object Model and create new custom elements that were part of the DOM. With the upgrade in technology and various modifications in the later versions of Angular(Angular 2 and higher versions, as Angular 2 is itself dependent on the component-based structure) the use of Components is now seen with great interest among the developers. Also, Components are termed as a more simplified version of Directives."
},
{
"code": null,
"e": 1379,
"s": 905,
"text": "Basic definitions:Directives are functions that are invoked whenever AngularJs’s HTML compiler($compile) finds it in DOM. It tells to attach a specified behavior to that DOM element (e.g. via event listeners), or even to transform the DOM element and its children.Components are just a simplified version of a directive. More specifically Components can be called a special kind of directives with templates, which are mainly used for component-based architecture.Examples:"
},
{
"code": null,
"e": 1840,
"s": 1379,
"text": "Component-Syntax:import {Component, View} from 'angular2/angular2';\n@Component ({........\n ........ })\n@View ({............\n ...........})import {Component, View} from 'angular2/angular2';@Component({ selector: 'message'})@View({ template: ` <h6>Hello GeeksforGeeks</h6> <h6>This is an example of component</h6> `})class Message { constructor(public version: string) {}}Output:Hello GeeksforGeeks\nThis is an example of component"
},
{
"code": null,
"e": 1981,
"s": 1840,
"text": "import {Component, View} from 'angular2/angular2';\n@Component ({........\n ........ })\n@View ({............\n ...........})"
},
{
"code": "import {Component, View} from 'angular2/angular2';@Component({ selector: 'message'})@View({ template: ` <h6>Hello GeeksforGeeks</h6> <h6>This is an example of component</h6> `})class Message { constructor(public version: string) {}}",
"e": 2227,
"s": 1981,
"text": null
},
{
"code": null,
"e": 2235,
"s": 2227,
"text": "Output:"
},
{
"code": null,
"e": 2287,
"s": 2235,
"text": "Hello GeeksforGeeks\nThis is an example of component"
},
{
"code": null,
"e": 2737,
"s": 2287,
"text": "Directive-Syntax:import {Directive} from 'angular2/angular2';\n@Directive({........\n ........})import {Directive} from 'angular2/angular2'; @Directive({ selector: \"[myDirective]\", hostListeners: { 'click': 'showMessage()' }})class Message { constructor() {} showMessage() { console.log('This is an example of directive'); }} <button>GeeksforGeeks</button>Output:Geeksforgeeks\nThis is an example of directive"
},
{
"code": null,
"e": 2826,
"s": 2737,
"text": "import {Directive} from 'angular2/angular2';\n@Directive({........\n ........})"
},
{
"code": "import {Directive} from 'angular2/angular2'; @Directive({ selector: \"[myDirective]\", hostListeners: { 'click': 'showMessage()' }})class Message { constructor() {} showMessage() { console.log('This is an example of directive'); }} <button>GeeksforGeeks</button>",
"e": 3119,
"s": 2826,
"text": null
},
{
"code": null,
"e": 3127,
"s": 3119,
"text": "Output:"
},
{
"code": null,
"e": 3173,
"s": 3127,
"text": "Geeksforgeeks\nThis is an example of directive"
},
{
"code": null,
"e": 3551,
"s": 3173,
"text": "Explanation:In the above examples, we have seen how to write simple Angular code for printing some messages, both using Component, and Directive. In the Component’s example, we have seen that it is mandatory to write view property, whereas, for Directives, we do not need to use view or templates. Let us now discuss what are the main differences between these two.Differences:"
},
{
"code": null,
"e": 4574,
"s": 3551,
"text": "A component is always elements (‘E’) where directive can be an attribute, element name, comment or CSS class (‘E’, ‘A’, ‘C’, ‘M’). Templates are the mandatory property and always required in Component, but Directive doesn’t always require them.Component is used to break up the application into smaller components. But Directive is used to design re-usable components, which is more behavior-oriented. That is why components are widely used in later versions of Angular to make things easy and build a total component-based model.As Component has views, viewEncapsulation can be defined. Whereas Directive doesn’t have views. So you can’t use viewEncapsulation in directive.Although Components make it easier to write simple, effective code, it has a simpler configuration than plain directives, it is optimized for component-based architecture. But when not to use a component? The answer is – a component does not support “compile” and “pre-link” functions. So for manipulating DOM objects, we should use the directives."
},
{
"code": null,
"e": 4819,
"s": 4574,
"text": "A component is always elements (‘E’) where directive can be an attribute, element name, comment or CSS class (‘E’, ‘A’, ‘C’, ‘M’). Templates are the mandatory property and always required in Component, but Directive doesn’t always require them."
},
{
"code": null,
"e": 5106,
"s": 4819,
"text": "Component is used to break up the application into smaller components. But Directive is used to design re-usable components, which is more behavior-oriented. That is why components are widely used in later versions of Angular to make things easy and build a total component-based model."
},
{
"code": null,
"e": 5251,
"s": 5106,
"text": "As Component has views, viewEncapsulation can be defined. Whereas Directive doesn’t have views. So you can’t use viewEncapsulation in directive."
},
{
"code": null,
"e": 5600,
"s": 5251,
"text": "Although Components make it easier to write simple, effective code, it has a simpler configuration than plain directives, it is optimized for component-based architecture. But when not to use a component? The answer is – a component does not support “compile” and “pre-link” functions. So for manipulating DOM objects, we should use the directives."
},
{
"code": null,
"e": 5769,
"s": 5600,
"text": "Components should never modify any data or DOM that is out of their own scope. Directives have isolated scopes, by default the child inherits the scope from its parent."
},
{
"code": null,
"e": 5874,
"s": 5769,
"text": "Only one component can be present per DOM element. There can be more than one directive in a DOM element"
},
{
"code": null,
"e": 6051,
"s": 5874,
"text": "To register component we use @Component meta-data annotation. For directive, we use @Directive meta-data annotation. Two simple examples are shown in the point ‘Example’ above."
},
{
"code": null,
"e": 6521,
"s": 6051,
"text": "Conclusion:A basic study on the topic has been given. Whether to use Component or Directive, it totally depends on the purpose of writing a particular code for the usage. With the advent of emerging technologies, most of the web page design architectures are aiming towards obtaining a component-based model and this is when we need Components. On the other hand, directives give us plenty of options as selectors, input, output, providers to write the code creatively."
},
{
"code": null,
"e": 6542,
"s": 6521,
"text": "AngularJS-Directives"
},
{
"code": null,
"e": 6549,
"s": 6542,
"text": "Picked"
},
{
"code": null,
"e": 6559,
"s": 6549,
"text": "AngularJS"
},
{
"code": null,
"e": 6576,
"s": 6559,
"text": "Web Technologies"
},
{
"code": null,
"e": 6674,
"s": 6576,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 6705,
"s": 6674,
"text": "Auth Guards in Angular 9/10/11"
},
{
"code": null,
"e": 6729,
"s": 6705,
"text": "Routing in Angular 9/10"
},
{
"code": null,
"e": 6771,
"s": 6729,
"text": "What is AOT and JIT Compiler in Angular ?"
},
{
"code": null,
"e": 6806,
"s": 6771,
"text": "Angular PrimeNG Dropdown Component"
},
{
"code": null,
"e": 6880,
"s": 6806,
"text": "How to set focus on input field automatically on page load in AngularJS ?"
},
{
"code": null,
"e": 6913,
"s": 6880,
"text": "Installation of Node.js on Linux"
},
{
"code": null,
"e": 6975,
"s": 6913,
"text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills"
},
{
"code": null,
"e": 7036,
"s": 6975,
"text": "Difference between var, let and const keywords in JavaScript"
},
{
"code": null,
"e": 7086,
"s": 7036,
"text": "How to insert spaces/tabs in text using HTML/CSS?"
}
] |
return statement vs exit() in main() | 28 May, 2017
In C++, what is the difference between exit(0) and return 0 ?
When exit(0) is used to exit from program, destructors for locally scoped non-static objects are not called. But destructors are called if return 0 is used.
Program 1 – – uses exit(0) to exit
#include<iostream>#include<stdio.h>#include<stdlib.h> using namespace std; class Test {public: Test() { printf("Inside Test's Constructor\n"); } ~Test(){ printf("Inside Test's Destructor"); getchar(); }}; int main() { Test t1; // using exit(0) to exit from main exit(0);}
Output:Inside Test’s Constructor
Program 2 – uses return 0 to exit
#include<iostream>#include<stdio.h>#include<stdlib.h> using namespace std; class Test {public: Test() { printf("Inside Test's Constructor\n"); } ~Test(){ printf("Inside Test's Destructor"); }}; int main() { Test t1; // using return 0 to exit from main return 0;}
Output:Inside Test’s ConstructorInside Test’s Destructor
Calling destructors is sometimes important, for example, if destructor has code to release resources like closing files.
Note that static objects will be cleaned up even if we call exit(). For example, see following program.
#include<iostream>#include<stdio.h>#include<stdlib.h> using namespace std; class Test {public: Test() { printf("Inside Test's Constructor\n"); } ~Test(){ printf("Inside Test's Destructor"); getchar(); }}; int main() { static Test t1; // Note that t1 is static exit(0);}
Output:Inside Test’s ConstructorInside Test’s Destructor
Contributed by indiarox. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
C-Functions
exit
main
return
C Language
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Substring in C++
Function Pointer in C
Multidimensional Arrays in C / C++
Left Shift and Right Shift Operators in C/C++
Different Methods to Reverse a String in C++
std::string class in C++
Unordered Sets in C++ Standard Template Library
rand() and srand() in C/C++
Enumeration (or enum) in C
C Language Introduction | [
{
"code": null,
"e": 54,
"s": 26,
"text": "\n28 May, 2017"
},
{
"code": null,
"e": 116,
"s": 54,
"text": "In C++, what is the difference between exit(0) and return 0 ?"
},
{
"code": null,
"e": 273,
"s": 116,
"text": "When exit(0) is used to exit from program, destructors for locally scoped non-static objects are not called. But destructors are called if return 0 is used."
},
{
"code": null,
"e": 308,
"s": 273,
"text": "Program 1 – – uses exit(0) to exit"
},
{
"code": "#include<iostream>#include<stdio.h>#include<stdlib.h> using namespace std; class Test {public: Test() { printf(\"Inside Test's Constructor\\n\"); } ~Test(){ printf(\"Inside Test's Destructor\"); getchar(); }}; int main() { Test t1; // using exit(0) to exit from main exit(0);}",
"e": 603,
"s": 308,
"text": null
},
{
"code": null,
"e": 636,
"s": 603,
"text": "Output:Inside Test’s Constructor"
},
{
"code": null,
"e": 670,
"s": 636,
"text": "Program 2 – uses return 0 to exit"
},
{
"code": "#include<iostream>#include<stdio.h>#include<stdlib.h> using namespace std; class Test {public: Test() { printf(\"Inside Test's Constructor\\n\"); } ~Test(){ printf(\"Inside Test's Destructor\"); }}; int main() { Test t1; // using return 0 to exit from main return 0;}",
"e": 954,
"s": 670,
"text": null
},
{
"code": null,
"e": 1011,
"s": 954,
"text": "Output:Inside Test’s ConstructorInside Test’s Destructor"
},
{
"code": null,
"e": 1132,
"s": 1011,
"text": "Calling destructors is sometimes important, for example, if destructor has code to release resources like closing files."
},
{
"code": null,
"e": 1236,
"s": 1132,
"text": "Note that static objects will be cleaned up even if we call exit(). For example, see following program."
},
{
"code": "#include<iostream>#include<stdio.h>#include<stdlib.h> using namespace std; class Test {public: Test() { printf(\"Inside Test's Constructor\\n\"); } ~Test(){ printf(\"Inside Test's Destructor\"); getchar(); }}; int main() { static Test t1; // Note that t1 is static exit(0);}",
"e": 1529,
"s": 1236,
"text": null
},
{
"code": null,
"e": 1586,
"s": 1529,
"text": "Output:Inside Test’s ConstructorInside Test’s Destructor"
},
{
"code": null,
"e": 1736,
"s": 1586,
"text": "Contributed by indiarox. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above."
},
{
"code": null,
"e": 1748,
"s": 1736,
"text": "C-Functions"
},
{
"code": null,
"e": 1753,
"s": 1748,
"text": "exit"
},
{
"code": null,
"e": 1758,
"s": 1753,
"text": "main"
},
{
"code": null,
"e": 1765,
"s": 1758,
"text": "return"
},
{
"code": null,
"e": 1776,
"s": 1765,
"text": "C Language"
},
{
"code": null,
"e": 1874,
"s": 1776,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 1891,
"s": 1874,
"text": "Substring in C++"
},
{
"code": null,
"e": 1913,
"s": 1891,
"text": "Function Pointer in C"
},
{
"code": null,
"e": 1948,
"s": 1913,
"text": "Multidimensional Arrays in C / C++"
},
{
"code": null,
"e": 1994,
"s": 1948,
"text": "Left Shift and Right Shift Operators in C/C++"
},
{
"code": null,
"e": 2039,
"s": 1994,
"text": "Different Methods to Reverse a String in C++"
},
{
"code": null,
"e": 2064,
"s": 2039,
"text": "std::string class in C++"
},
{
"code": null,
"e": 2112,
"s": 2064,
"text": "Unordered Sets in C++ Standard Template Library"
},
{
"code": null,
"e": 2140,
"s": 2112,
"text": "rand() and srand() in C/C++"
},
{
"code": null,
"e": 2167,
"s": 2140,
"text": "Enumeration (or enum) in C"
}
] |
Flutter – BottomSheet Class | 21 Jun, 2022
Bottom Sheet is one of the popular ways to show various options on the screen. This helps the user to switch to a new screen. You will see this bottom sheet in most of the app to add data or add some information such as address or ticket number. In this article, we are going to see how to implement the Bottom Sheet in our Flutter App.
BottomSheet({Key key,
AnimationController animationController,
bool enableDrag: true,
BottomSheetDragStartHandler onDragStart,
BottomSheetDragEndHandler onDragEnd,
Color backgroundColor,
double elevation,
ShapeBorder shape,
Clip clipBehavior,
@required
VoidCallback onClosing,
@required
WidgetBuilder builder})
backgroundColor: It is used to give background color to the bottom sheet.
elevation: It is used to give elevation to our bottom sheet.
builder: It provides a builder for the contents of the sheet.
clipBehaviour: It is used to clip the content of the sheet as specified.
enableDrag: If true, the bottom sheet can be dragged up and down and dismissed by swiping downwards.
hashCode: It represents the hash code of the object.
key: It is used to handle how one widget replaces another widget in the tree.
onClosing: Used to assign action while the bottom sheet is closing.
onDragEnd: It is called when the user stops dragging the bottom sheet.
onDragStart: It is called when the user starts dragging the bottom sheet.
runTimeType: A representation of the runtime type of the object.
shape: It defines the shape of the bottom sheet.
Now let’s look into the implementation of the Bottom sheet. To Implement the Bottom Sheet in Flutter you have to follow the following steps:
Step 1: Navigate to main.dart() file and return Material App()
First, we have declared MyApp() in runApp in main function. Then we created StatefullWidget for MyApp in which we have returned MaterialApp(). In this MaterialApp() we have given the title of our App and then declared the theme of our App as Dark Theme. Then we have given our first screen or slider app in home: HomePage()
Dart
import 'package:flutter/material.dart'; void main() { runApp(const MyApp());} class MyApp extends StatelessWidget { const MyApp({Key? key}) : super(key: key); // This widget is the root of your application. @override Widget build(BuildContext context) { return MaterialApp( debugShowCheckedModeBanner: false, title: 'Flutter Demo', theme: ThemeData( primarySwatch: Colors.green, ), //First Screen of our App home: HomePage(), ); }}
Create a StatefulWidget that provides a base structure to the application using the below code. In this code firstly we have created StatefulWidget for HomePage(). And in this HomePage() we have returned Scaffold() Widget.
Dart
class HomePage extends StatefulWidget { const HomePage({Key? key}) : super(key: key); @override // ignore: library_private_types_in_public_api _HomePageState createState() => _HomePageState();} class _HomePageState extends State<HomePage> { @override Widget build(BuildContext context) { return const Scaffold(); }}
Step 2: Build the Bottom Sheet
In this Scaffold Widget, we have given appbar in which we have given the title of an Appbar. After that in the body, we have declared a Container() which is wrapped with Center Widget and given a sample text as “Hello”.
Dart
class HomePage extends StatefulWidget { const HomePage({Key? key}) : super(key: key); @override // ignore: library_private_types_in_public_api _HomePageState createState() => _HomePageState();} class _HomePageState extends State<HomePage> { @override Widget build(BuildContext context) { return Scaffold( //Appbar along with Title appBar: AppBar( title: const Text("Bottom Sheet"), ), body:Center( //Sample Text Written in Center of Screen // ignore: avoid_unnecessary_containers child: Container( child: const Text("Hello"), ), ), ); }}
Step 3: Create and add a FloatingAction Button
Now create a Floating Action Button, and then we have assigned floatingactionButton and given addition icon on this button. And in the on Pressed method, we have declared showModalBottomSheet(). In then, we have given Container widget in it which is wrapped in SingleChildScrollView() widget. Which is used to scroll the content in the bottom sheet. Again we have declared a Container() for the bottom sheet in which we have given border-radius to the top Right and top Left corner to make this Container circular.
Dart
//Floating Action Button floatingActionButton: FloatingActionButton( child: const Icon(Icons.add, color: Colors.white), onPressed: () { showModalBottomSheet( context: context, builder: (context) { //Scrolling given for content in Container() return SingleChildScrollView( child: Container( padding: EdgeInsets.only( bottom: MediaQuery.of(context).viewInsets.bottom), child: Container( padding: const EdgeInsets.all(20), decoration: const BoxDecoration( borderRadius: BorderRadius.only( topRight: Radius.circular(20), topLeft: Radius.circular(20), ), ), ))); }); }, ),
In this Container() we have declared Column() widget in which we have given its children’s.First we added text heading in the Container(). And after that we added TextField(). In this TextField() we have given InputDecoration() which is used to declare the hint text. Then we added border as OutLineInputBorder() which is used to to give border side color. Also we can make TextField circular by adding border radius in OutlineInputBorder(). After we have given a RaisedButton() in which we have given text written on the button and color of the button.
Dart
//Create a Column to display it's content padding: const EdgeInsets.all(20), decoration: const BoxDecoration( borderRadius: BorderRadius.only( topRight: Radius.circular(20), topLeft: Radius.circular(20), ), ), //Create a Column to display it's content child: Column( children: [ const Text( "Add Data", style: TextStyle( fontWeight: FontWeight.w600, color: Colors.green, fontSize: 20), ), const SizedBox(height: 10.0), // TextField for giving some Input const TextField( decoration: InputDecoration( border: OutlineInputBorder( borderSide: BorderSide(color: Colors.green), ), hintText: "Add Item", hintStyle: TextStyle(color: Colors.grey), ), ), const SizedBox(height: 10), //Button for adding items ElevatedButton( onPressed: null, style: ButtonStyle( backgroundColor: MaterialStateProperty.all(Colors.red), textStyle: MaterialStateProperty.all( const TextStyle(fontSize: 30))), child: const Text("Add"), ) // RaisedButton is deprecated // Instead Use ElevatedButton // RaisedButton( // color: Colors.grey, // onPressed: null, // child: Text( // "ADD", // style: TextStyle(color: Colors.white), // ), // ) ], ), ),
Full Code
Dart
import 'package:flutter/material.dart'; void main() { runApp(const MyApp());} class MyApp extends StatelessWidget { const MyApp({Key? key}) : super(key: key); // This widget is the root of your application. @override Widget build(BuildContext context) { return MaterialApp( debugShowCheckedModeBanner: false, title: 'Flutter Demo', theme: ThemeData( primarySwatch: Colors.green, ), //First Screen of our App home: const HomePage(), ); }} class HomePage extends StatefulWidget { const HomePage({Key? key}) : super(key: key); @override // ignore: library_private_types_in_public_api _HomePageState createState() => _HomePageState();} class _HomePageState extends State<HomePage> { @override Widget build(BuildContext context) { return Scaffold( //Appbar along with Title appBar: AppBar( title: const Text("Bottom Sheet"), ), body: Center( //Sample Text Written in Center of Screen // ignore: avoid_unnecessary_containers child: Container( child: const Text("Hello"), ), ), //Floating Action Button floatingActionButton: FloatingActionButton( child: const Icon(Icons.add, color: Colors.white), onPressed: () { showModalBottomSheet( context: context, builder: (context) { //Scrolling given for content in Container() return SingleChildScrollView( child: Container( padding: EdgeInsets.only( bottom: MediaQuery.of(context).viewInsets.bottom), child: Container( //Create a Column to display it's content padding: const EdgeInsets.all(20), decoration: const BoxDecoration( borderRadius: BorderRadius.only( topRight: Radius.circular(20), topLeft: Radius.circular(20), ), ), //Create a Column to display it's content child: Column( children: [ const Text( "Add Data", style: TextStyle( fontWeight: FontWeight.w600, color: Colors.green, fontSize: 20), ), const SizedBox(height: 10.0), // TextField for giving some Input const TextField( decoration: InputDecoration( border: OutlineInputBorder( borderSide: BorderSide(color: Colors.green), ), hintText: "Add Item", hintStyle: TextStyle(color: Colors.grey), ), ), const SizedBox(height: 10), //Button for adding items ElevatedButton( onPressed: null, style: ButtonStyle( backgroundColor: MaterialStateProperty.all(Colors.red), textStyle: MaterialStateProperty.all( const TextStyle(fontSize: 30))), child: const Text("Add"), ) // RaisedButton is deprecated // Instead Use ElevatedButton // RaisedButton( // color: Colors.grey, // onPressed: null, // child: Text( // "ADD", // style: TextStyle(color: Colors.white), // ), // ) ], ), ), ), ); }); }, ), ); }}
Output:
ankit_kumar_
android
Flutter
Dart
Flutter
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
ListView Class in Flutter
Flutter - Search Bar
Flutter - Dialogs
Flutter - FutureBuilder Widget
Flutter - Flexible Widget
Flutter Tutorial
Flutter - Search Bar
Flutter - Dialogs
Flutter - FutureBuilder Widget
Flutter - Flexible Widget | [
{
"code": null,
"e": 54,
"s": 26,
"text": "\n21 Jun, 2022"
},
{
"code": null,
"e": 391,
"s": 54,
"text": "Bottom Sheet is one of the popular ways to show various options on the screen. This helps the user to switch to a new screen. You will see this bottom sheet in most of the app to add data or add some information such as address or ticket number. In this article, we are going to see how to implement the Bottom Sheet in our Flutter App."
},
{
"code": null,
"e": 703,
"s": 391,
"text": "BottomSheet({Key key,\nAnimationController animationController,\nbool enableDrag: true,\nBottomSheetDragStartHandler onDragStart,\nBottomSheetDragEndHandler onDragEnd,\nColor backgroundColor,\ndouble elevation,\nShapeBorder shape,\nClip clipBehavior,\n@required\nVoidCallback onClosing,\n@required \nWidgetBuilder builder})"
},
{
"code": null,
"e": 777,
"s": 703,
"text": "backgroundColor: It is used to give background color to the bottom sheet."
},
{
"code": null,
"e": 838,
"s": 777,
"text": "elevation: It is used to give elevation to our bottom sheet."
},
{
"code": null,
"e": 900,
"s": 838,
"text": "builder: It provides a builder for the contents of the sheet."
},
{
"code": null,
"e": 973,
"s": 900,
"text": "clipBehaviour: It is used to clip the content of the sheet as specified."
},
{
"code": null,
"e": 1074,
"s": 973,
"text": "enableDrag: If true, the bottom sheet can be dragged up and down and dismissed by swiping downwards."
},
{
"code": null,
"e": 1127,
"s": 1074,
"text": "hashCode: It represents the hash code of the object."
},
{
"code": null,
"e": 1206,
"s": 1127,
"text": "key: It is used to handle how one widget replaces another widget in the tree. "
},
{
"code": null,
"e": 1274,
"s": 1206,
"text": "onClosing: Used to assign action while the bottom sheet is closing."
},
{
"code": null,
"e": 1345,
"s": 1274,
"text": "onDragEnd: It is called when the user stops dragging the bottom sheet."
},
{
"code": null,
"e": 1419,
"s": 1345,
"text": "onDragStart: It is called when the user starts dragging the bottom sheet."
},
{
"code": null,
"e": 1484,
"s": 1419,
"text": "runTimeType: A representation of the runtime type of the object."
},
{
"code": null,
"e": 1533,
"s": 1484,
"text": "shape: It defines the shape of the bottom sheet."
},
{
"code": null,
"e": 1674,
"s": 1533,
"text": "Now let’s look into the implementation of the Bottom sheet. To Implement the Bottom Sheet in Flutter you have to follow the following steps:"
},
{
"code": null,
"e": 1737,
"s": 1674,
"text": "Step 1: Navigate to main.dart() file and return Material App()"
},
{
"code": null,
"e": 2061,
"s": 1737,
"text": "First, we have declared MyApp() in runApp in main function. Then we created StatefullWidget for MyApp in which we have returned MaterialApp(). In this MaterialApp() we have given the title of our App and then declared the theme of our App as Dark Theme. Then we have given our first screen or slider app in home: HomePage()"
},
{
"code": null,
"e": 2066,
"s": 2061,
"text": "Dart"
},
{
"code": "import 'package:flutter/material.dart'; void main() { runApp(const MyApp());} class MyApp extends StatelessWidget { const MyApp({Key? key}) : super(key: key); // This widget is the root of your application. @override Widget build(BuildContext context) { return MaterialApp( debugShowCheckedModeBanner: false, title: 'Flutter Demo', theme: ThemeData( primarySwatch: Colors.green, ), //First Screen of our App home: HomePage(), ); }}",
"e": 2548,
"s": 2066,
"text": null
},
{
"code": null,
"e": 2771,
"s": 2548,
"text": "Create a StatefulWidget that provides a base structure to the application using the below code. In this code firstly we have created StatefulWidget for HomePage(). And in this HomePage() we have returned Scaffold() Widget."
},
{
"code": null,
"e": 2776,
"s": 2771,
"text": "Dart"
},
{
"code": "class HomePage extends StatefulWidget { const HomePage({Key? key}) : super(key: key); @override // ignore: library_private_types_in_public_api _HomePageState createState() => _HomePageState();} class _HomePageState extends State<HomePage> { @override Widget build(BuildContext context) { return const Scaffold(); }}",
"e": 3103,
"s": 2776,
"text": null
},
{
"code": null,
"e": 3134,
"s": 3103,
"text": "Step 2: Build the Bottom Sheet"
},
{
"code": null,
"e": 3354,
"s": 3134,
"text": "In this Scaffold Widget, we have given appbar in which we have given the title of an Appbar. After that in the body, we have declared a Container() which is wrapped with Center Widget and given a sample text as “Hello”."
},
{
"code": null,
"e": 3359,
"s": 3354,
"text": "Dart"
},
{
"code": "class HomePage extends StatefulWidget { const HomePage({Key? key}) : super(key: key); @override // ignore: library_private_types_in_public_api _HomePageState createState() => _HomePageState();} class _HomePageState extends State<HomePage> { @override Widget build(BuildContext context) { return Scaffold( //Appbar along with Title appBar: AppBar( title: const Text(\"Bottom Sheet\"), ), body:Center( //Sample Text Written in Center of Screen // ignore: avoid_unnecessary_containers child: Container( child: const Text(\"Hello\"), ), ), ); }}",
"e": 3989,
"s": 3359,
"text": null
},
{
"code": null,
"e": 4036,
"s": 3989,
"text": "Step 3: Create and add a FloatingAction Button"
},
{
"code": null,
"e": 4551,
"s": 4036,
"text": "Now create a Floating Action Button, and then we have assigned floatingactionButton and given addition icon on this button. And in the on Pressed method, we have declared showModalBottomSheet(). In then, we have given Container widget in it which is wrapped in SingleChildScrollView() widget. Which is used to scroll the content in the bottom sheet. Again we have declared a Container() for the bottom sheet in which we have given border-radius to the top Right and top Left corner to make this Container circular."
},
{
"code": null,
"e": 4556,
"s": 4551,
"text": "Dart"
},
{
"code": "//Floating Action Button floatingActionButton: FloatingActionButton( child: const Icon(Icons.add, color: Colors.white), onPressed: () { showModalBottomSheet( context: context, builder: (context) { //Scrolling given for content in Container() return SingleChildScrollView( child: Container( padding: EdgeInsets.only( bottom: MediaQuery.of(context).viewInsets.bottom), child: Container( padding: const EdgeInsets.all(20), decoration: const BoxDecoration( borderRadius: BorderRadius.only( topRight: Radius.circular(20), topLeft: Radius.circular(20), ), ), ))); }); }, ),",
"e": 5535,
"s": 4556,
"text": null
},
{
"code": null,
"e": 6089,
"s": 5535,
"text": "In this Container() we have declared Column() widget in which we have given its children’s.First we added text heading in the Container(). And after that we added TextField(). In this TextField() we have given InputDecoration() which is used to declare the hint text. Then we added border as OutLineInputBorder() which is used to to give border side color. Also we can make TextField circular by adding border radius in OutlineInputBorder(). After we have given a RaisedButton() in which we have given text written on the button and color of the button."
},
{
"code": null,
"e": 6094,
"s": 6089,
"text": "Dart"
},
{
"code": "//Create a Column to display it's content padding: const EdgeInsets.all(20), decoration: const BoxDecoration( borderRadius: BorderRadius.only( topRight: Radius.circular(20), topLeft: Radius.circular(20), ), ), //Create a Column to display it's content child: Column( children: [ const Text( \"Add Data\", style: TextStyle( fontWeight: FontWeight.w600, color: Colors.green, fontSize: 20), ), const SizedBox(height: 10.0), // TextField for giving some Input const TextField( decoration: InputDecoration( border: OutlineInputBorder( borderSide: BorderSide(color: Colors.green), ), hintText: \"Add Item\", hintStyle: TextStyle(color: Colors.grey), ), ), const SizedBox(height: 10), //Button for adding items ElevatedButton( onPressed: null, style: ButtonStyle( backgroundColor: MaterialStateProperty.all(Colors.red), textStyle: MaterialStateProperty.all( const TextStyle(fontSize: 30))), child: const Text(\"Add\"), ) // RaisedButton is deprecated // Instead Use ElevatedButton // RaisedButton( // color: Colors.grey, // onPressed: null, // child: Text( // \"ADD\", // style: TextStyle(color: Colors.white), // ), // ) ], ), ),",
"e": 8420,
"s": 6094,
"text": null
},
{
"code": null,
"e": 8430,
"s": 8420,
"text": "Full Code"
},
{
"code": null,
"e": 8435,
"s": 8430,
"text": "Dart"
},
{
"code": "import 'package:flutter/material.dart'; void main() { runApp(const MyApp());} class MyApp extends StatelessWidget { const MyApp({Key? key}) : super(key: key); // This widget is the root of your application. @override Widget build(BuildContext context) { return MaterialApp( debugShowCheckedModeBanner: false, title: 'Flutter Demo', theme: ThemeData( primarySwatch: Colors.green, ), //First Screen of our App home: const HomePage(), ); }} class HomePage extends StatefulWidget { const HomePage({Key? key}) : super(key: key); @override // ignore: library_private_types_in_public_api _HomePageState createState() => _HomePageState();} class _HomePageState extends State<HomePage> { @override Widget build(BuildContext context) { return Scaffold( //Appbar along with Title appBar: AppBar( title: const Text(\"Bottom Sheet\"), ), body: Center( //Sample Text Written in Center of Screen // ignore: avoid_unnecessary_containers child: Container( child: const Text(\"Hello\"), ), ), //Floating Action Button floatingActionButton: FloatingActionButton( child: const Icon(Icons.add, color: Colors.white), onPressed: () { showModalBottomSheet( context: context, builder: (context) { //Scrolling given for content in Container() return SingleChildScrollView( child: Container( padding: EdgeInsets.only( bottom: MediaQuery.of(context).viewInsets.bottom), child: Container( //Create a Column to display it's content padding: const EdgeInsets.all(20), decoration: const BoxDecoration( borderRadius: BorderRadius.only( topRight: Radius.circular(20), topLeft: Radius.circular(20), ), ), //Create a Column to display it's content child: Column( children: [ const Text( \"Add Data\", style: TextStyle( fontWeight: FontWeight.w600, color: Colors.green, fontSize: 20), ), const SizedBox(height: 10.0), // TextField for giving some Input const TextField( decoration: InputDecoration( border: OutlineInputBorder( borderSide: BorderSide(color: Colors.green), ), hintText: \"Add Item\", hintStyle: TextStyle(color: Colors.grey), ), ), const SizedBox(height: 10), //Button for adding items ElevatedButton( onPressed: null, style: ButtonStyle( backgroundColor: MaterialStateProperty.all(Colors.red), textStyle: MaterialStateProperty.all( const TextStyle(fontSize: 30))), child: const Text(\"Add\"), ) // RaisedButton is deprecated // Instead Use ElevatedButton // RaisedButton( // color: Colors.grey, // onPressed: null, // child: Text( // \"ADD\", // style: TextStyle(color: Colors.white), // ), // ) ], ), ), ), ); }); }, ), ); }}",
"e": 12668,
"s": 8435,
"text": null
},
{
"code": null,
"e": 12676,
"s": 12668,
"text": "Output:"
},
{
"code": null,
"e": 12689,
"s": 12676,
"text": "ankit_kumar_"
},
{
"code": null,
"e": 12697,
"s": 12689,
"text": "android"
},
{
"code": null,
"e": 12705,
"s": 12697,
"text": "Flutter"
},
{
"code": null,
"e": 12710,
"s": 12705,
"text": "Dart"
},
{
"code": null,
"e": 12718,
"s": 12710,
"text": "Flutter"
},
{
"code": null,
"e": 12816,
"s": 12718,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 12842,
"s": 12816,
"text": "ListView Class in Flutter"
},
{
"code": null,
"e": 12863,
"s": 12842,
"text": "Flutter - Search Bar"
},
{
"code": null,
"e": 12881,
"s": 12863,
"text": "Flutter - Dialogs"
},
{
"code": null,
"e": 12912,
"s": 12881,
"text": "Flutter - FutureBuilder Widget"
},
{
"code": null,
"e": 12938,
"s": 12912,
"text": "Flutter - Flexible Widget"
},
{
"code": null,
"e": 12955,
"s": 12938,
"text": "Flutter Tutorial"
},
{
"code": null,
"e": 12976,
"s": 12955,
"text": "Flutter - Search Bar"
},
{
"code": null,
"e": 12994,
"s": 12976,
"text": "Flutter - Dialogs"
},
{
"code": null,
"e": 13025,
"s": 12994,
"text": "Flutter - FutureBuilder Widget"
}
] |
Odd Even Transposition Sort / Brick Sort using pthreads | 22 Dec, 2021
Odd-Even Transposition Sort is a parallel sorting algorithm. It is based on the Bubble Sort technique, which compares every 2 consecutive numbers in the array and swap them if first is greater than the second to get an ascending order array. It consists of 2 phases – the odd phase and even phase:
Odd phase: Every odd indexed element is compared with the next even indexed element(considering 1-based indexing).
Even phase: Every even indexed element is compared with the next odd indexed element.
This article uses the concept of multi-threading, specifically pthread. In each iteration, every pair of 2 consecutive elements is compared using individual threads executing in parallel as illustrated below.
Examples:
Input: { 2, 1, 4, 9, 5, 3, 6, 10 }
Output: 1, 2, 3, 4, 5, 6, 9, 10
Input: { 11, 19, 4, 20, 1, 22, 25, 8}
Output: 1, 4, 8, 11, 19, 20, 22, 25
Note: Compile the program using following command on your Linux based system.
g++ program_name.cpp -pthread
Below is the implementation of the above topic:
CPP
// CPP Program for Odd-Even Transposition sort// using pthreads #include <bits/stdc++.h>#include <pthread.h> using namespace std; // size of array#define n 8 // maximum number of threadsint max_threads = (n + 1) / 2; int a[] = { 2, 1, 4, 9, 5, 3, 6, 10 };int tmp; // Function to compare and exchange// the consecutive elements of the arrayvoid* compare(void* arg){ // Each thread compares // two consecutive elements of the array int index = tmp; tmp = tmp + 2; if ((a[index] > a[index + 1]) && (index + 1 < n)) { swap(a[index], a[index + 1]); }} void oddEven(pthread_t threads[]){ int i, j; for (i = 1; i <= n; i++) { // Odd step if (i % 2 == 1) { tmp = 0; // Creating threads for (j = 0; j < max_threads; j++) pthread_create(&threads[j], NULL, compare, NULL); // joining threads i.e. waiting // for all the threads to complete for (j = 0; j < max_threads; j++) pthread_join(threads[j], NULL); } // Even step else { tmp = 1; // Creating threads for (j = 0; j < max_threads - 1; j++) pthread_create(&threads[j], NULL, compare, NULL); // joining threads i.e. waiting // for all the threads to complete for (j = 0; j < max_threads - 1; j++) pthread_join(threads[j], NULL); } }} // Function to print an arrayvoid printArray(){ int i; for (i = 0; i < n; i++) cout << a[i] << " "; cout << endl;} // Driver Codeint main(){ pthread_t threads[max_threads]; cout << "Given array is: "; printArray(); oddEven(threads); cout << "\nSorted array is: "; printArray(); return 0;}
Output:
Given array is: 2 1 4 9 5 3 6 10
Sorted array is: 1 2 3 4 5 6 9 10
Time complexity: The time complexity is reduced to O(N) due to parallel computation using threads.Work complexity: The work complexity of this program is O(N) as N/2 number of threads(resources) are being used to sort the array. So, the work-time complexity of the program is O(N^2).
surindertarika1234
cpp-multithreading
C++
Sorting
Sorting
CPP
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here. | [
{
"code": null,
"e": 52,
"s": 24,
"text": "\n22 Dec, 2021"
},
{
"code": null,
"e": 350,
"s": 52,
"text": "Odd-Even Transposition Sort is a parallel sorting algorithm. It is based on the Bubble Sort technique, which compares every 2 consecutive numbers in the array and swap them if first is greater than the second to get an ascending order array. It consists of 2 phases – the odd phase and even phase:"
},
{
"code": null,
"e": 465,
"s": 350,
"text": "Odd phase: Every odd indexed element is compared with the next even indexed element(considering 1-based indexing)."
},
{
"code": null,
"e": 551,
"s": 465,
"text": "Even phase: Every even indexed element is compared with the next odd indexed element."
},
{
"code": null,
"e": 760,
"s": 551,
"text": "This article uses the concept of multi-threading, specifically pthread. In each iteration, every pair of 2 consecutive elements is compared using individual threads executing in parallel as illustrated below."
},
{
"code": null,
"e": 770,
"s": 760,
"text": "Examples:"
},
{
"code": null,
"e": 913,
"s": 770,
"text": "Input: { 2, 1, 4, 9, 5, 3, 6, 10 }\nOutput: 1, 2, 3, 4, 5, 6, 9, 10\n\nInput: { 11, 19, 4, 20, 1, 22, 25, 8}\nOutput: 1, 4, 8, 11, 19, 20, 22, 25\n"
},
{
"code": null,
"e": 991,
"s": 913,
"text": "Note: Compile the program using following command on your Linux based system."
},
{
"code": null,
"e": 1022,
"s": 991,
"text": "g++ program_name.cpp -pthread\n"
},
{
"code": null,
"e": 1070,
"s": 1022,
"text": "Below is the implementation of the above topic:"
},
{
"code": null,
"e": 1074,
"s": 1070,
"text": "CPP"
},
{
"code": "// CPP Program for Odd-Even Transposition sort// using pthreads #include <bits/stdc++.h>#include <pthread.h> using namespace std; // size of array#define n 8 // maximum number of threadsint max_threads = (n + 1) / 2; int a[] = { 2, 1, 4, 9, 5, 3, 6, 10 };int tmp; // Function to compare and exchange// the consecutive elements of the arrayvoid* compare(void* arg){ // Each thread compares // two consecutive elements of the array int index = tmp; tmp = tmp + 2; if ((a[index] > a[index + 1]) && (index + 1 < n)) { swap(a[index], a[index + 1]); }} void oddEven(pthread_t threads[]){ int i, j; for (i = 1; i <= n; i++) { // Odd step if (i % 2 == 1) { tmp = 0; // Creating threads for (j = 0; j < max_threads; j++) pthread_create(&threads[j], NULL, compare, NULL); // joining threads i.e. waiting // for all the threads to complete for (j = 0; j < max_threads; j++) pthread_join(threads[j], NULL); } // Even step else { tmp = 1; // Creating threads for (j = 0; j < max_threads - 1; j++) pthread_create(&threads[j], NULL, compare, NULL); // joining threads i.e. waiting // for all the threads to complete for (j = 0; j < max_threads - 1; j++) pthread_join(threads[j], NULL); } }} // Function to print an arrayvoid printArray(){ int i; for (i = 0; i < n; i++) cout << a[i] << \" \"; cout << endl;} // Driver Codeint main(){ pthread_t threads[max_threads]; cout << \"Given array is: \"; printArray(); oddEven(threads); cout << \"\\nSorted array is: \"; printArray(); return 0;}",
"e": 2879,
"s": 1074,
"text": null
},
{
"code": null,
"e": 2887,
"s": 2879,
"text": "Output:"
},
{
"code": null,
"e": 2956,
"s": 2887,
"text": "Given array is: 2 1 4 9 5 3 6 10\nSorted array is: 1 2 3 4 5 6 9 10\n"
},
{
"code": null,
"e": 3240,
"s": 2956,
"text": "Time complexity: The time complexity is reduced to O(N) due to parallel computation using threads.Work complexity: The work complexity of this program is O(N) as N/2 number of threads(resources) are being used to sort the array. So, the work-time complexity of the program is O(N^2)."
},
{
"code": null,
"e": 3259,
"s": 3240,
"text": "surindertarika1234"
},
{
"code": null,
"e": 3278,
"s": 3259,
"text": "cpp-multithreading"
},
{
"code": null,
"e": 3282,
"s": 3278,
"text": "C++"
},
{
"code": null,
"e": 3290,
"s": 3282,
"text": "Sorting"
},
{
"code": null,
"e": 3298,
"s": 3290,
"text": "Sorting"
},
{
"code": null,
"e": 3302,
"s": 3298,
"text": "CPP"
}
] |
Google Internship Interview Experience | Off-Campus 2022 | 19 Oct, 2021
Applications for Google Summer Internship 2022 were open and I applied. I did not expect to hear back from them as my application was off-campus, without referrals, from a tier 3 college. But I did hear back from Google with an interview offer around 3 weeks later. We also had an interviews preparation session.
I have undergone 2 rounds of technical interviews 45 min each.
Round 1: Interview 1
Warm-up problem – Given an array, create a new array that will have arr[i] and 2 * arr[i] from I iterating from 0 to array size. Return any shuffled version of this newly created array.
For example – input – >[1,2,3] —- new array -> [1,2,2,4,3,6] —— any shuffled version -> [2,3,4,6,2,1]
The main problem – You are given the output of the previous question as an input in this question, You have to output the array which might have created this input.
For example – input ->[2,3,4,6,2,1] output – [1,2,3]
Round 2: Interview 2
Tree problem – A tree node can either be an internal node or a leaf node.
If it is an internal node then it stores the sum of lengths of strings present in its left and right child.
If it is a leaf node then it stores string as well as its length.
Below is the tree node structure
Case 1)Only 1 node i.e. root node present
Root(length = 5,data = ABCDE)
Case 2)Multiple nodes presents
Root(length = 21)
left child(length = 5, data = ABCDE)
right child(length = 16)
left child of right child(length = 10, data = FGHIJKLMNO )
right child of right child(length = 6, data = PQRSTU )
Given input is above tree and N when You have to return the Nth character present in the tree.
Google
Marketing
Off-Campus
Internship
Interview Experiences
Google
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Samsung R&D Bangalore (SRIB) Interview Experience | On- Campus for Internship 2021
Microsoft Interview Experience for SWE Intern
Zoho Interview Experience (Off-Campus ) 2022
Google STEP Interview Experience Internship 2022
Microsoft Interview Experience for SWE Intern (On-Campus)
Amazon Interview Questions
Google SWE Interview Experience (Google Online Coding Challenge) 2022
TCS Digital Interview Questions
Samsung Interview Experience Research & Institute SRIB (Off-Campus) 2022
Amazon Interview Experience for SDE 1 | [
{
"code": null,
"e": 52,
"s": 24,
"text": "\n19 Oct, 2021"
},
{
"code": null,
"e": 365,
"s": 52,
"text": "Applications for Google Summer Internship 2022 were open and I applied. I did not expect to hear back from them as my application was off-campus, without referrals, from a tier 3 college. But I did hear back from Google with an interview offer around 3 weeks later. We also had an interviews preparation session."
},
{
"code": null,
"e": 428,
"s": 365,
"text": "I have undergone 2 rounds of technical interviews 45 min each."
},
{
"code": null,
"e": 449,
"s": 428,
"text": "Round 1: Interview 1"
},
{
"code": null,
"e": 635,
"s": 449,
"text": "Warm-up problem – Given an array, create a new array that will have arr[i] and 2 * arr[i] from I iterating from 0 to array size. Return any shuffled version of this newly created array."
},
{
"code": null,
"e": 738,
"s": 635,
"text": "For example – input – >[1,2,3] —- new array -> [1,2,2,4,3,6] —— any shuffled version -> [2,3,4,6,2,1] "
},
{
"code": null,
"e": 903,
"s": 738,
"text": "The main problem – You are given the output of the previous question as an input in this question, You have to output the array which might have created this input."
},
{
"code": null,
"e": 957,
"s": 903,
"text": "For example – input ->[2,3,4,6,2,1] output – [1,2,3] "
},
{
"code": null,
"e": 978,
"s": 957,
"text": "Round 2: Interview 2"
},
{
"code": null,
"e": 1052,
"s": 978,
"text": "Tree problem – A tree node can either be an internal node or a leaf node."
},
{
"code": null,
"e": 1160,
"s": 1052,
"text": "If it is an internal node then it stores the sum of lengths of strings present in its left and right child."
},
{
"code": null,
"e": 1226,
"s": 1160,
"text": "If it is a leaf node then it stores string as well as its length."
},
{
"code": null,
"e": 1259,
"s": 1226,
"text": "Below is the tree node structure"
},
{
"code": null,
"e": 1558,
"s": 1259,
"text": "Case 1)Only 1 node i.e. root node present\nRoot(length = 5,data = ABCDE) \nCase 2)Multiple nodes presents\nRoot(length = 21) \nleft child(length = 5, data = ABCDE)\nright child(length = 16)\nleft child of right child(length = 10, data = FGHIJKLMNO )\nright child of right child(length = 6, data = PQRSTU )"
},
{
"code": null,
"e": 1653,
"s": 1558,
"text": "Given input is above tree and N when You have to return the Nth character present in the tree."
},
{
"code": null,
"e": 1662,
"s": 1655,
"text": "Google"
},
{
"code": null,
"e": 1672,
"s": 1662,
"text": "Marketing"
},
{
"code": null,
"e": 1683,
"s": 1672,
"text": "Off-Campus"
},
{
"code": null,
"e": 1694,
"s": 1683,
"text": "Internship"
},
{
"code": null,
"e": 1716,
"s": 1694,
"text": "Interview Experiences"
},
{
"code": null,
"e": 1723,
"s": 1716,
"text": "Google"
},
{
"code": null,
"e": 1821,
"s": 1723,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 1904,
"s": 1821,
"text": "Samsung R&D Bangalore (SRIB) Interview Experience | On- Campus for Internship 2021"
},
{
"code": null,
"e": 1950,
"s": 1904,
"text": "Microsoft Interview Experience for SWE Intern"
},
{
"code": null,
"e": 1995,
"s": 1950,
"text": "Zoho Interview Experience (Off-Campus ) 2022"
},
{
"code": null,
"e": 2044,
"s": 1995,
"text": "Google STEP Interview Experience Internship 2022"
},
{
"code": null,
"e": 2102,
"s": 2044,
"text": "Microsoft Interview Experience for SWE Intern (On-Campus)"
},
{
"code": null,
"e": 2129,
"s": 2102,
"text": "Amazon Interview Questions"
},
{
"code": null,
"e": 2199,
"s": 2129,
"text": "Google SWE Interview Experience (Google Online Coding Challenge) 2022"
},
{
"code": null,
"e": 2231,
"s": 2199,
"text": "TCS Digital Interview Questions"
},
{
"code": null,
"e": 2304,
"s": 2231,
"text": "Samsung Interview Experience Research & Institute SRIB (Off-Campus) 2022"
}
] |
JavaScript | Polyfilling & Transpiling | 09 Apr, 2018
Due to the rapid changes in version of JavaScript, the syntaxial forms and vocabulary are also updated in JavaScript, therefore it is seen that many of the JavaScript features are newer additions and may not necessarily be available in older browsers i.e. browsers running on older versions of JavaScript. Another problem is that some of the Browsers do not consider the newest features of JavaScript as safe due to the extreme power it is capable of showing, and hence they are not included or included as an experimental mode with limitations to restrict the usage. But why should we even discuss this? JavaScript is mainly used to develop client-side applications and the successful execution of the programs partially depend on the client’s machine i.e. the version of JavaScript available on the browser of the client.
Now the naive approach would be to run only those functionalities that can be run in the clients’ browser, though it’s really not a healthy approach. There are two primary techniques that a developer can use to “bring” the newer features of JavaScript to the older browsers namely Polyfilling and Transpiling.
Polyfilling
Polyfilling is an invented term by Remy Sharp. It is one of the methodologies that can be used as a sort of backward compatibility measurement. The definition is best given by Remy himself.
“A polyfill, or polyfiller, is a piece of code (or plugin) that provides the technology that you, the developer, expect the browser to provide natively. Flattening the API landscape if you will.”— Remy Sharp
If we illustrate what he meant to say we will get that A polyfill or polyfiller is a code segment that is supposed to behave identically to a newer feature of JavaScript and still being able to run on older versions. For example, ES2015 provides a new utility Number.isNaN(...) to provide a secure and accurate method to check for NaN or Not a Number values. We can use polyfilling to replicate this behavior and use it on those pre-ES2015 browsers. The following snippet will be helpful in our case.
// Check if Number.isNaN already exists.// If False then proceed.if (!Number.isNaN) { // Define explicitly for older browsers. Number.isNaN = function isNaN(x) { // This is a property of NaN. // No two NaN can be equal to the other. // Because NaN is a concept not a comparable value. return x !== x; };}
We first check if the method is already available and prevent defining the explicit version if so. If not present then we are definitely on an older version of JavaScript so we explicitly define one using the property of NaNs that no two NaN is equal to each-other because NaN is a concept, not a comparable value to be equal to the other. Thus, we return True if they are not equals and otherwise we return False. This can be considered as one of the easiest polyfills.
Note: All the new features are not polyfillable or it is not possible always to create polyfills without any deviation thus while implementing polyfills explicitly it is recommended to have a knowledge of the working on whole. But, many developers prefer using the polyfills that are already available. Some of these are mentioned below.
ES6 Shim
ES5 Shim
Transpiling
New JavaScript versions also bring syntaxial updates as well which is not possible to be polyfilled as it would simply not get executed and instead will throw syntax errors in old JavaScript engines, this is where a transpiler comes into play. It has got its name from the union of two operation it performs Transformation + Compiling. In continuation, we can now define a “Transpiler” to be a tool that transforms code with newer syntax into older code equivalents and this process is called “Transpiling”.
By development practice, while using Transpiling it is essential to write the code maintaining the newer syntax but while deploying the project use a transpiler similar to a minifier or a linter to deploy the transpiled old syntax friendly program. That raises the question why should we even bother writing in the newer syntaxial form while still deploying the older one? This is a very logical question to ask and has a lot of good points to give as answers out of which few are given below.
It goes without saying that the newer syntax was added to the language to make the code more readable and easily maintainable i.e. the newer versions are simply better than The older equivalents. Thus it is recommended towrite newer and cleaner syntax to achieve a better result.
Transpiling only for older browsers, while serving the newer syntax to the updated browsers, we can get the advantage of browser performance optimizations.
Using the newer syntax earlier allows it to be tested more robustly in the real world, which provides earlier feedback and if found early enough, they can be changed/fixed before those language design mistakes become permanent. Thus using the newer syntax makes the syntax much more reliable in the long run.
Let us take some examples of Transpiling. ES2015 added a new syntaxial feature of default parameter value, it can be implemented using the following.
// Default Parameter Value Example.// If no parameter is passed a will be 5.function myFunc(a = 5){ console.log(a);} myFunc(96); // Logs 96.myFunc(); // Logs 5 as default.
As you can see, if the parameter is not supplied we take the default parameter value in account but this syntax will not get recognized in pre-ES2015 engines. Thus after transpiling, we will get the older equivalent as the following.
// Default Parameter Value Example.// If no parameter is passed a will be 5.function myFunc(){ // Using Ternary Operator to assign default // 5 if undefined. var a = (arguments[0] !== undefined) ? arguments[0] : 5; console.log(a);} myFunc(96); // Logs 96.myFunc(); // Logs 5 as default.
As seen in the example above we can use a ternary operator to assign the default value if the argument is found to be undefined this will produce similar results to the ES6 equivalent. For next example let us see the thick arrow methods of ES6.
// Function Defining is now this easy.var myFunc = () => { console.log("This is a function.");} myFunc(); // This is a function.
As you can see in the example above we can define a function without even using the keyword function and that also without hampering the readability, but this will not get recognized in pre-ES6 engines thus the equivalent code will be as following.
// Function Defining is now this easy.var myFunc = function() { console.log("This is a function.");} myFunc(); // This is a function.
After learning about Transpilers it will be very odd to end this article without knowing some of the greatest of Transpilers available. The following is a small list of such tools.
Babel
Traceur
Hopefully, we have covered enough to gain knowledge of what these methodologies are and why the use of both of them is not only important to the developer but also for the development of JavaScript itself.
Reference:https://remysharp.com/2010/10/08/what-is-a-polyfill
javascript-basics
JavaScript
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here. | [
{
"code": null,
"e": 52,
"s": 24,
"text": "\n09 Apr, 2018"
},
{
"code": null,
"e": 876,
"s": 52,
"text": "Due to the rapid changes in version of JavaScript, the syntaxial forms and vocabulary are also updated in JavaScript, therefore it is seen that many of the JavaScript features are newer additions and may not necessarily be available in older browsers i.e. browsers running on older versions of JavaScript. Another problem is that some of the Browsers do not consider the newest features of JavaScript as safe due to the extreme power it is capable of showing, and hence they are not included or included as an experimental mode with limitations to restrict the usage. But why should we even discuss this? JavaScript is mainly used to develop client-side applications and the successful execution of the programs partially depend on the client’s machine i.e. the version of JavaScript available on the browser of the client."
},
{
"code": null,
"e": 1186,
"s": 876,
"text": "Now the naive approach would be to run only those functionalities that can be run in the clients’ browser, though it’s really not a healthy approach. There are two primary techniques that a developer can use to “bring” the newer features of JavaScript to the older browsers namely Polyfilling and Transpiling."
},
{
"code": null,
"e": 1198,
"s": 1186,
"text": "Polyfilling"
},
{
"code": null,
"e": 1388,
"s": 1198,
"text": "Polyfilling is an invented term by Remy Sharp. It is one of the methodologies that can be used as a sort of backward compatibility measurement. The definition is best given by Remy himself."
},
{
"code": null,
"e": 1596,
"s": 1388,
"text": "“A polyfill, or polyfiller, is a piece of code (or plugin) that provides the technology that you, the developer, expect the browser to provide natively. Flattening the API landscape if you will.”— Remy Sharp"
},
{
"code": null,
"e": 2097,
"s": 1596,
"text": "If we illustrate what he meant to say we will get that A polyfill or polyfiller is a code segment that is supposed to behave identically to a newer feature of JavaScript and still being able to run on older versions. For example, ES2015 provides a new utility Number.isNaN(...) to provide a secure and accurate method to check for NaN or Not a Number values. We can use polyfilling to replicate this behavior and use it on those pre-ES2015 browsers. The following snippet will be helpful in our case."
},
{
"code": "// Check if Number.isNaN already exists.// If False then proceed.if (!Number.isNaN) { // Define explicitly for older browsers. Number.isNaN = function isNaN(x) { // This is a property of NaN. // No two NaN can be equal to the other. // Because NaN is a concept not a comparable value. return x !== x; };}",
"e": 2443,
"s": 2097,
"text": null
},
{
"code": null,
"e": 2914,
"s": 2443,
"text": "We first check if the method is already available and prevent defining the explicit version if so. If not present then we are definitely on an older version of JavaScript so we explicitly define one using the property of NaNs that no two NaN is equal to each-other because NaN is a concept, not a comparable value to be equal to the other. Thus, we return True if they are not equals and otherwise we return False. This can be considered as one of the easiest polyfills."
},
{
"code": null,
"e": 3252,
"s": 2914,
"text": "Note: All the new features are not polyfillable or it is not possible always to create polyfills without any deviation thus while implementing polyfills explicitly it is recommended to have a knowledge of the working on whole. But, many developers prefer using the polyfills that are already available. Some of these are mentioned below."
},
{
"code": null,
"e": 3261,
"s": 3252,
"text": "ES6 Shim"
},
{
"code": null,
"e": 3270,
"s": 3261,
"text": "ES5 Shim"
},
{
"code": null,
"e": 3282,
"s": 3270,
"text": "Transpiling"
},
{
"code": null,
"e": 3790,
"s": 3282,
"text": "New JavaScript versions also bring syntaxial updates as well which is not possible to be polyfilled as it would simply not get executed and instead will throw syntax errors in old JavaScript engines, this is where a transpiler comes into play. It has got its name from the union of two operation it performs Transformation + Compiling. In continuation, we can now define a “Transpiler” to be a tool that transforms code with newer syntax into older code equivalents and this process is called “Transpiling”."
},
{
"code": null,
"e": 4284,
"s": 3790,
"text": "By development practice, while using Transpiling it is essential to write the code maintaining the newer syntax but while deploying the project use a transpiler similar to a minifier or a linter to deploy the transpiled old syntax friendly program. That raises the question why should we even bother writing in the newer syntaxial form while still deploying the older one? This is a very logical question to ask and has a lot of good points to give as answers out of which few are given below."
},
{
"code": null,
"e": 4564,
"s": 4284,
"text": "It goes without saying that the newer syntax was added to the language to make the code more readable and easily maintainable i.e. the newer versions are simply better than The older equivalents. Thus it is recommended towrite newer and cleaner syntax to achieve a better result."
},
{
"code": null,
"e": 4720,
"s": 4564,
"text": "Transpiling only for older browsers, while serving the newer syntax to the updated browsers, we can get the advantage of browser performance optimizations."
},
{
"code": null,
"e": 5029,
"s": 4720,
"text": "Using the newer syntax earlier allows it to be tested more robustly in the real world, which provides earlier feedback and if found early enough, they can be changed/fixed before those language design mistakes become permanent. Thus using the newer syntax makes the syntax much more reliable in the long run."
},
{
"code": null,
"e": 5179,
"s": 5029,
"text": "Let us take some examples of Transpiling. ES2015 added a new syntaxial feature of default parameter value, it can be implemented using the following."
},
{
"code": "// Default Parameter Value Example.// If no parameter is passed a will be 5.function myFunc(a = 5){ console.log(a);} myFunc(96); // Logs 96.myFunc(); // Logs 5 as default.",
"e": 5355,
"s": 5179,
"text": null
},
{
"code": null,
"e": 5589,
"s": 5355,
"text": "As you can see, if the parameter is not supplied we take the default parameter value in account but this syntax will not get recognized in pre-ES2015 engines. Thus after transpiling, we will get the older equivalent as the following."
},
{
"code": "// Default Parameter Value Example.// If no parameter is passed a will be 5.function myFunc(){ // Using Ternary Operator to assign default // 5 if undefined. var a = (arguments[0] !== undefined) ? arguments[0] : 5; console.log(a);} myFunc(96); // Logs 96.myFunc(); // Logs 5 as default.",
"e": 5889,
"s": 5589,
"text": null
},
{
"code": null,
"e": 6134,
"s": 5889,
"text": "As seen in the example above we can use a ternary operator to assign the default value if the argument is found to be undefined this will produce similar results to the ES6 equivalent. For next example let us see the thick arrow methods of ES6."
},
{
"code": "// Function Defining is now this easy.var myFunc = () => { console.log(\"This is a function.\");} myFunc(); // This is a function.",
"e": 6267,
"s": 6134,
"text": null
},
{
"code": null,
"e": 6516,
"s": 6267,
"text": "As you can see in the example above we can define a function without even using the keyword function and that also without hampering the readability, but this will not get recognized in pre-ES6 engines thus the equivalent code will be as following."
},
{
"code": "// Function Defining is now this easy.var myFunc = function() { console.log(\"This is a function.\");} myFunc(); // This is a function.",
"e": 6654,
"s": 6516,
"text": null
},
{
"code": null,
"e": 6835,
"s": 6654,
"text": "After learning about Transpilers it will be very odd to end this article without knowing some of the greatest of Transpilers available. The following is a small list of such tools."
},
{
"code": null,
"e": 6841,
"s": 6835,
"text": "Babel"
},
{
"code": null,
"e": 6849,
"s": 6841,
"text": "Traceur"
},
{
"code": null,
"e": 7055,
"s": 6849,
"text": "Hopefully, we have covered enough to gain knowledge of what these methodologies are and why the use of both of them is not only important to the developer but also for the development of JavaScript itself."
},
{
"code": null,
"e": 7117,
"s": 7055,
"text": "Reference:https://remysharp.com/2010/10/08/what-is-a-polyfill"
},
{
"code": null,
"e": 7135,
"s": 7117,
"text": "javascript-basics"
},
{
"code": null,
"e": 7146,
"s": 7135,
"text": "JavaScript"
}
] |
SQL Statement to Remove Part of a String | 22 Oct, 2021
Here we will see SQL statements to remove part of the string.
We will use this method if we want to remove a part of the string whose position is known to us.
1. SUBSTRING(): This function is used to find a sub-string from the string from the given position. It takes three parameters:
String: It is a required parameter. It provides information about the string on which function is applied.
Start: It gives the starting position of the string. It is also the required parameter.
Length: It is an optional parameter. By default, it takes the length of the whole string.
2. LEN(): The syntax is not the standard one. For different server syntax for returning the length of a string may vary. For example, LEN() is in SQL server, LENGTH() is used in oracle database, and so on. It takes only one parameter that is the string whose length you need to find.
Let see these above mention function with an example. Suppose to remove unwanted parts of the string we will extract only the wanted part from string characters from the field, we will use the following query:
Step 1: Create a database
Use the below SQL statement to create database called geeks;
Query:
CREATE DATABASE geeks;
Step 2: Using the database
Use the below SQL statement to switch the database context to geeks:
Query:
USE geeks;
Step 3: Table creation
We have the following demo_table in our geek’s database.
Query:
CREATE TABLE demo_table(
NAME VARCHAR(20),
GENDER VARCHAR(20),
AGE INT,
CITY VARCHAR(20) );
Step 4: Insert data into a table
Query:
INSERT INTO demo_table VALUES
('ROMY KUMARI', 'FEMALE', 22, 'NEW DELHI'),
('PUSHKAR JHA', 'MALE',23, 'NEW DELHI'),
('RINKLE ARORA', 'FEMALE',23, 'PUNJAB'),
('AKASH GUPTA', 'MALE', 23, 'UTTAR PRADESH');
Step 5: View data of the table
Query:
SELECT * FROM demo_table;
Output:
Step 6: Remove part of a string
Suppose if we want to remove the last 4 characters from the string then, we will extract the remaining part using the below statement.
Syntax:
SELECT SUBSTRING(column_name,1,length(column_name)-4) FROM table_name;
Example :
Remove the last 4 characters from the NAME field.
Query:
SELECT SUBSTRING(NAME,1,len(NAME)-4) AS NAME, GENDER, AGE, CITY FROM demo_table;
Output:
We can remove part of the string using REPLACE() function. We can use this function if we know the exact character of the string to remove.
REMOVE(): This function replaces all occurrences of a substring within a new substring. It takes three parameters, all are required parameters.
string Required. The original string
old_string Required. The string to be replaced
new_string Required. The new replacement string
Syntax:
REPLACE(string, old_string, new_string)
We will use the above demo_table for the demonstration. Suppose if we remove ‘New’ from the CITY field in demo_table then query will be:
Query:
SELECT NAME, GENDER, AGE, REPLACE(CITY,'New','') AS CITY FROM demo_table;
We are not replacing it with a new string.
Output:
TRIM(): This function removes the space character or other specified characters from the start or end of a string. By using this function we can not remove part of the string from the middle of the string.
Syntax:
TRIM([characters FROM ]string);
We will use the above demo_table for the demonstration. Suppose if we want to remove ‘New’ from the CITY field in demo_table then the query will be as follows:
Query:
SELECT NAME, GENDER, AGE, TRIM ('NEW' FROM CITY)AS "NEW CITY" FROM demo_table;
Output:
romy421kumari
Picked
SQL-Server
TrueGeek-2021
SQL
TrueGeek
SQL
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here. | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n22 Oct, 2021"
},
{
"code": null,
"e": 90,
"s": 28,
"text": "Here we will see SQL statements to remove part of the string."
},
{
"code": null,
"e": 187,
"s": 90,
"text": "We will use this method if we want to remove a part of the string whose position is known to us."
},
{
"code": null,
"e": 316,
"s": 187,
"text": "1. SUBSTRING(): This function is used to find a sub-string from the string from the given position. It takes three parameters: "
},
{
"code": null,
"e": 423,
"s": 316,
"text": "String: It is a required parameter. It provides information about the string on which function is applied."
},
{
"code": null,
"e": 511,
"s": 423,
"text": "Start: It gives the starting position of the string. It is also the required parameter."
},
{
"code": null,
"e": 601,
"s": 511,
"text": "Length: It is an optional parameter. By default, it takes the length of the whole string."
},
{
"code": null,
"e": 885,
"s": 601,
"text": "2. LEN(): The syntax is not the standard one. For different server syntax for returning the length of a string may vary. For example, LEN() is in SQL server, LENGTH() is used in oracle database, and so on. It takes only one parameter that is the string whose length you need to find."
},
{
"code": null,
"e": 1095,
"s": 885,
"text": "Let see these above mention function with an example. Suppose to remove unwanted parts of the string we will extract only the wanted part from string characters from the field, we will use the following query:"
},
{
"code": null,
"e": 1121,
"s": 1095,
"text": "Step 1: Create a database"
},
{
"code": null,
"e": 1182,
"s": 1121,
"text": "Use the below SQL statement to create database called geeks;"
},
{
"code": null,
"e": 1189,
"s": 1182,
"text": "Query:"
},
{
"code": null,
"e": 1212,
"s": 1189,
"text": "CREATE DATABASE geeks;"
},
{
"code": null,
"e": 1239,
"s": 1212,
"text": "Step 2: Using the database"
},
{
"code": null,
"e": 1308,
"s": 1239,
"text": "Use the below SQL statement to switch the database context to geeks:"
},
{
"code": null,
"e": 1315,
"s": 1308,
"text": "Query:"
},
{
"code": null,
"e": 1326,
"s": 1315,
"text": "USE geeks;"
},
{
"code": null,
"e": 1349,
"s": 1326,
"text": "Step 3: Table creation"
},
{
"code": null,
"e": 1406,
"s": 1349,
"text": "We have the following demo_table in our geek’s database."
},
{
"code": null,
"e": 1413,
"s": 1406,
"text": "Query:"
},
{
"code": null,
"e": 1505,
"s": 1413,
"text": "CREATE TABLE demo_table(\nNAME VARCHAR(20),\nGENDER VARCHAR(20),\nAGE INT,\nCITY VARCHAR(20) );"
},
{
"code": null,
"e": 1538,
"s": 1505,
"text": "Step 4: Insert data into a table"
},
{
"code": null,
"e": 1545,
"s": 1538,
"text": "Query:"
},
{
"code": null,
"e": 1747,
"s": 1545,
"text": "INSERT INTO demo_table VALUES\n('ROMY KUMARI', 'FEMALE', 22, 'NEW DELHI'),\n('PUSHKAR JHA', 'MALE',23, 'NEW DELHI'),\n('RINKLE ARORA', 'FEMALE',23, 'PUNJAB'),\n('AKASH GUPTA', 'MALE', 23, 'UTTAR PRADESH');"
},
{
"code": null,
"e": 1779,
"s": 1747,
"text": "Step 5: View data of the table "
},
{
"code": null,
"e": 1786,
"s": 1779,
"text": "Query:"
},
{
"code": null,
"e": 1812,
"s": 1786,
"text": "SELECT * FROM demo_table;"
},
{
"code": null,
"e": 1820,
"s": 1812,
"text": "Output:"
},
{
"code": null,
"e": 1852,
"s": 1820,
"text": "Step 6: Remove part of a string"
},
{
"code": null,
"e": 1987,
"s": 1852,
"text": "Suppose if we want to remove the last 4 characters from the string then, we will extract the remaining part using the below statement."
},
{
"code": null,
"e": 1995,
"s": 1987,
"text": "Syntax:"
},
{
"code": null,
"e": 2066,
"s": 1995,
"text": "SELECT SUBSTRING(column_name,1,length(column_name)-4) FROM table_name;"
},
{
"code": null,
"e": 2076,
"s": 2066,
"text": "Example :"
},
{
"code": null,
"e": 2126,
"s": 2076,
"text": "Remove the last 4 characters from the NAME field."
},
{
"code": null,
"e": 2133,
"s": 2126,
"text": "Query:"
},
{
"code": null,
"e": 2214,
"s": 2133,
"text": "SELECT SUBSTRING(NAME,1,len(NAME)-4) AS NAME, GENDER, AGE, CITY FROM demo_table;"
},
{
"code": null,
"e": 2222,
"s": 2214,
"text": "Output:"
},
{
"code": null,
"e": 2362,
"s": 2222,
"text": "We can remove part of the string using REPLACE() function. We can use this function if we know the exact character of the string to remove."
},
{
"code": null,
"e": 2507,
"s": 2362,
"text": "REMOVE(): This function replaces all occurrences of a substring within a new substring. It takes three parameters, all are required parameters."
},
{
"code": null,
"e": 2544,
"s": 2507,
"text": "string Required. The original string"
},
{
"code": null,
"e": 2591,
"s": 2544,
"text": "old_string Required. The string to be replaced"
},
{
"code": null,
"e": 2639,
"s": 2591,
"text": "new_string Required. The new replacement string"
},
{
"code": null,
"e": 2647,
"s": 2639,
"text": "Syntax:"
},
{
"code": null,
"e": 2687,
"s": 2647,
"text": "REPLACE(string, old_string, new_string)"
},
{
"code": null,
"e": 2824,
"s": 2687,
"text": "We will use the above demo_table for the demonstration. Suppose if we remove ‘New’ from the CITY field in demo_table then query will be:"
},
{
"code": null,
"e": 2831,
"s": 2824,
"text": "Query:"
},
{
"code": null,
"e": 2905,
"s": 2831,
"text": "SELECT NAME, GENDER, AGE, REPLACE(CITY,'New','') AS CITY FROM demo_table;"
},
{
"code": null,
"e": 2948,
"s": 2905,
"text": "We are not replacing it with a new string."
},
{
"code": null,
"e": 2956,
"s": 2948,
"text": "Output:"
},
{
"code": null,
"e": 3162,
"s": 2956,
"text": "TRIM(): This function removes the space character or other specified characters from the start or end of a string. By using this function we can not remove part of the string from the middle of the string."
},
{
"code": null,
"e": 3170,
"s": 3162,
"text": "Syntax:"
},
{
"code": null,
"e": 3202,
"s": 3170,
"text": "TRIM([characters FROM ]string);"
},
{
"code": null,
"e": 3362,
"s": 3202,
"text": "We will use the above demo_table for the demonstration. Suppose if we want to remove ‘New’ from the CITY field in demo_table then the query will be as follows:"
},
{
"code": null,
"e": 3369,
"s": 3362,
"text": "Query:"
},
{
"code": null,
"e": 3449,
"s": 3369,
"text": "SELECT NAME, GENDER, AGE, TRIM ('NEW' FROM CITY)AS \"NEW CITY\" FROM demo_table;"
},
{
"code": null,
"e": 3457,
"s": 3449,
"text": "Output:"
},
{
"code": null,
"e": 3471,
"s": 3457,
"text": "romy421kumari"
},
{
"code": null,
"e": 3478,
"s": 3471,
"text": "Picked"
},
{
"code": null,
"e": 3489,
"s": 3478,
"text": "SQL-Server"
},
{
"code": null,
"e": 3503,
"s": 3489,
"text": "TrueGeek-2021"
},
{
"code": null,
"e": 3507,
"s": 3503,
"text": "SQL"
},
{
"code": null,
"e": 3516,
"s": 3507,
"text": "TrueGeek"
},
{
"code": null,
"e": 3520,
"s": 3516,
"text": "SQL"
}
] |
SQL Query to Add Email Validation Using Only One Query | 19 May, 2021
In this article let us see how can we check for the validation of mails in the student database using MSSQL as the database server. For example, if the email is like [email protected] this is the valid form of an email if it is other than this then that is said to Invalid. So, now we will discuss this concept in detail step-by-step:
Step 1: Creating a database college by using the following SQL query as follows.
CREATE DATABASE college;
Step 2: Using the database student using the following SQL query as follows.
USE college;
Step 3: Creating a table student with 4 columns using the following SQL query as follows.
CREATE TABLE student
(
s_id varchar(20),
s_name varchar(20),
s_branch varchar(20),
s_email varchar(100)
);
Step 4: To view the description of the table in the database using the following SQL query as follows.
EXEC sp_columns student;
Step 5: Inserting rows into student_details table using the following SQL query as follows.
INSERT INTO student VALUES
('19102001','JOHNSON','E.C.E','[email protected]'),
('19102002','VIVEK','E.C.E','VIVEK2252gmail.com'),
('19102003','DINESH','E.C.E','[email protected]'),
('19102004','HARSHA','E.C.E','[email protected]'),
('19102005','DAVID','E.C.E','[email protected]'),
('19102006','NAVIN','E.C.E','navin00'),
('19102007','VINAY','E.C.E','Vinay24mail.com');
Step 6: Viewing the table student_details after inserting rows by using the following SQL query as follows.
SELECT * FROM student;
Query: Now we are querying to display all the student details with valid emails. So, the email validation is done by using pattern matching which can be done by using LIKE operator in MSSQL. It checks for the fixed pattern set by the database designer in the data and displays the data that matches the fixed pattern.
Syntax:
SELECT * FROM table_name
WHERE attribute LIKE 'pattern';
SELECT * FROM student
WHERE s_email LIKE '%@gmail.com';
Only the students with valid emails are displayed in the tables.
Picked
SQL-Query
SQL
SQL
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
CTE in SQL
How to Update Multiple Columns in Single Update Statement in SQL?
SQL Trigger | Student Database
SQL Interview Questions
SQL | Views
Difference between DELETE, DROP and TRUNCATE
MySQL | Group_CONCAT() Function
Difference between DDL and DML in DBMS
SQL | GROUP BY
Window functions in SQL | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n19 May, 2021"
},
{
"code": null,
"e": 379,
"s": 28,
"text": "In this article let us see how can we check for the validation of mails in the student database using MSSQL as the database server. For example, if the email is like [email protected] this is the valid form of an email if it is other than this then that is said to Invalid. So, now we will discuss this concept in detail step-by-step:"
},
{
"code": null,
"e": 460,
"s": 379,
"text": "Step 1: Creating a database college by using the following SQL query as follows."
},
{
"code": null,
"e": 485,
"s": 460,
"text": "CREATE DATABASE college;"
},
{
"code": null,
"e": 562,
"s": 485,
"text": "Step 2: Using the database student using the following SQL query as follows."
},
{
"code": null,
"e": 575,
"s": 562,
"text": "USE college;"
},
{
"code": null,
"e": 665,
"s": 575,
"text": "Step 3: Creating a table student with 4 columns using the following SQL query as follows."
},
{
"code": null,
"e": 788,
"s": 665,
"text": "CREATE TABLE student\n(\n s_id varchar(20),\n s_name varchar(20),\n s_branch varchar(20),\n s_email varchar(100)\n);"
},
{
"code": null,
"e": 891,
"s": 788,
"text": "Step 4: To view the description of the table in the database using the following SQL query as follows."
},
{
"code": null,
"e": 916,
"s": 891,
"text": "EXEC sp_columns student;"
},
{
"code": null,
"e": 1008,
"s": 916,
"text": "Step 5: Inserting rows into student_details table using the following SQL query as follows."
},
{
"code": null,
"e": 1382,
"s": 1008,
"text": "INSERT INTO student VALUES\n('19102001','JOHNSON','E.C.E','[email protected]'),\n('19102002','VIVEK','E.C.E','VIVEK2252gmail.com'),\n('19102003','DINESH','E.C.E','[email protected]'),\n('19102004','HARSHA','E.C.E','[email protected]'),\n('19102005','DAVID','E.C.E','[email protected]'),\n('19102006','NAVIN','E.C.E','navin00'),\n('19102007','VINAY','E.C.E','Vinay24mail.com');"
},
{
"code": null,
"e": 1490,
"s": 1382,
"text": "Step 6: Viewing the table student_details after inserting rows by using the following SQL query as follows."
},
{
"code": null,
"e": 1513,
"s": 1490,
"text": "SELECT * FROM student;"
},
{
"code": null,
"e": 1831,
"s": 1513,
"text": "Query: Now we are querying to display all the student details with valid emails. So, the email validation is done by using pattern matching which can be done by using LIKE operator in MSSQL. It checks for the fixed pattern set by the database designer in the data and displays the data that matches the fixed pattern."
},
{
"code": null,
"e": 1839,
"s": 1831,
"text": "Syntax:"
},
{
"code": null,
"e": 1896,
"s": 1839,
"text": "SELECT * FROM table_name\nWHERE attribute LIKE 'pattern';"
},
{
"code": null,
"e": 1952,
"s": 1896,
"text": "SELECT * FROM student\nWHERE s_email LIKE '%@gmail.com';"
},
{
"code": null,
"e": 2017,
"s": 1952,
"text": "Only the students with valid emails are displayed in the tables."
},
{
"code": null,
"e": 2024,
"s": 2017,
"text": "Picked"
},
{
"code": null,
"e": 2034,
"s": 2024,
"text": "SQL-Query"
},
{
"code": null,
"e": 2038,
"s": 2034,
"text": "SQL"
},
{
"code": null,
"e": 2042,
"s": 2038,
"text": "SQL"
},
{
"code": null,
"e": 2140,
"s": 2042,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 2151,
"s": 2140,
"text": "CTE in SQL"
},
{
"code": null,
"e": 2217,
"s": 2151,
"text": "How to Update Multiple Columns in Single Update Statement in SQL?"
},
{
"code": null,
"e": 2248,
"s": 2217,
"text": "SQL Trigger | Student Database"
},
{
"code": null,
"e": 2272,
"s": 2248,
"text": "SQL Interview Questions"
},
{
"code": null,
"e": 2284,
"s": 2272,
"text": "SQL | Views"
},
{
"code": null,
"e": 2329,
"s": 2284,
"text": "Difference between DELETE, DROP and TRUNCATE"
},
{
"code": null,
"e": 2361,
"s": 2329,
"text": "MySQL | Group_CONCAT() Function"
},
{
"code": null,
"e": 2400,
"s": 2361,
"text": "Difference between DDL and DML in DBMS"
},
{
"code": null,
"e": 2415,
"s": 2400,
"text": "SQL | GROUP BY"
}
] |
JavaScript toLocaleString() function | The toLocaleString() method of JavaScript is used to convert a Date object to a string using locale settings.
The syntax is as follows −
Date.toLocaleString(locales, options)
Above, the locales parameter is the language specific format to be used −
ar-SA Arabic (Saudi Arabia)
bn-BD Bangla (Bangladesh)
bn-IN Bangla (India)
cs-CZ Czech (Czech Republic)
da-DK Danish (Denmark)
de-AT Austrian German
de-CH "Swiss" German
de-DE Standard German (as spoken in Germany)
el-GR Modern Greek
en-AU Australian English
en-CA Canadian English
en-GB British English
en-IE Irish English
en-IN Indian English
en-NZ New Zealand English
en-US US English
en-ZA English (South Africa)
es-AR Argentine Spanish
es-CL Chilean Spanish
es-CO Colombian Spanish
es-ES Castilian Spanish (as spoken in Central-Northern Spain)
es-MX Mexican Spanish
es-US American Spanish
fi-FI Finnish (Finland)
fr-BE Belgian French
Let us now implement the array. toLocaleString() method in JavaScript −
Live Demo
<!DOCTYPE html>
<html>
<body>
<h2>Products</h2>
<p>Click to display the updated product list...</p>
<button onclick="display()">Result</button>
<p id="test"></p>
<script>
var products = ["Electronics", "Books", "Accessories"];
document.getElementById("test").innerHTML = products;
function display() {
var d = new Date();
products.splice(3, 1, "Pet Supplies", "Footwear", "Home Appliances");
document.getElementById("test").innerHTML = products +" on "+d.toLocaleString();
}
</script>
</body>
</html>
Click on the “Result” button above −
Live Demo
<!DOCTYPE html>
<html>
<body>
<h2>Displaying Date</h2>
<button onclick="display()">Result</button>
<p id="test"></p>
<script>
document.getElementById("test").innerHTML = "Display the current date...";
function display() {
var d = new Date();
document.getElementById("test").innerHTML = d.toLocaleString();
}
</script>
</body>
</html>
Click “Result” button − | [
{
"code": null,
"e": 1297,
"s": 1187,
"text": "The toLocaleString() method of JavaScript is used to convert a Date object to a string using locale settings."
},
{
"code": null,
"e": 1324,
"s": 1297,
"text": "The syntax is as follows −"
},
{
"code": null,
"e": 1362,
"s": 1324,
"text": "Date.toLocaleString(locales, options)"
},
{
"code": null,
"e": 1436,
"s": 1362,
"text": "Above, the locales parameter is the language specific format to be used −"
},
{
"code": null,
"e": 2075,
"s": 1436,
"text": "ar-SA Arabic (Saudi Arabia)\nbn-BD Bangla (Bangladesh)\nbn-IN Bangla (India)\ncs-CZ Czech (Czech Republic)\nda-DK Danish (Denmark)\nde-AT Austrian German\nde-CH \"Swiss\" German\nde-DE Standard German (as spoken in Germany)\nel-GR Modern Greek\nen-AU Australian English\nen-CA Canadian English\nen-GB British English\nen-IE Irish English\nen-IN Indian English\nen-NZ New Zealand English\nen-US US English\nen-ZA English (South Africa)\nes-AR Argentine Spanish\nes-CL Chilean Spanish\nes-CO Colombian Spanish\nes-ES Castilian Spanish (as spoken in Central-Northern Spain)\nes-MX Mexican Spanish\nes-US American Spanish\nfi-FI Finnish (Finland)\nfr-BE Belgian French"
},
{
"code": null,
"e": 2147,
"s": 2075,
"text": "Let us now implement the array. toLocaleString() method in JavaScript −"
},
{
"code": null,
"e": 2158,
"s": 2147,
"text": " Live Demo"
},
{
"code": null,
"e": 2689,
"s": 2158,
"text": "<!DOCTYPE html>\n<html>\n<body>\n<h2>Products</h2>\n<p>Click to display the updated product list...</p>\n<button onclick=\"display()\">Result</button>\n<p id=\"test\"></p>\n<script>\n var products = [\"Electronics\", \"Books\", \"Accessories\"];\n document.getElementById(\"test\").innerHTML = products;\n function display() {\n var d = new Date();\n products.splice(3, 1, \"Pet Supplies\", \"Footwear\", \"Home Appliances\");\n document.getElementById(\"test\").innerHTML = products +\" on \"+d.toLocaleString();\n }\n</script>\n</body>\n</html>"
},
{
"code": null,
"e": 2726,
"s": 2689,
"text": "Click on the “Result” button above −"
},
{
"code": null,
"e": 2737,
"s": 2726,
"text": " Live Demo"
},
{
"code": null,
"e": 3092,
"s": 2737,
"text": "<!DOCTYPE html>\n<html>\n<body>\n<h2>Displaying Date</h2>\n<button onclick=\"display()\">Result</button>\n<p id=\"test\"></p>\n<script>\n document.getElementById(\"test\").innerHTML = \"Display the current date...\";\n function display() {\n var d = new Date();\n document.getElementById(\"test\").innerHTML = d.toLocaleString();\n }\n</script>\n</body>\n</html>"
},
{
"code": null,
"e": 3116,
"s": 3092,
"text": "Click “Result” button −"
}
] |
HTML acronym Tag | 24 Mar, 2022
The <acronym> tag in HTML is used to define the acronym. The <acronym> tag is used to spell out another word. It is used to give useful information to browsers, translation systems, and search-engines. This tag is not supported in HTML 5 otherwise use <abbr> Tag.
Syntax:
<acronym title=""> Short Form </acronym>
Attribute: This tag accepts an optional attribute as mentioned above and described below:
title: It is used to specify extra information about the element. When the mouse moves over the element then it shows the information.
Example:
html
<!DOCTYPE html><html> <body> <h1>GeeksforGeeks</h1> <h2>This is HTML <acronym> Tag</h2> <acronym title="GeeksforGeeks">GFG</acronym> <br> <acronym title="Operating System">OS</acronym></body> </html>
Output:
Supported Browser:
Google Chrome
Internet Explorer
Firefox
Opera
Safari
shubhamyadav4
hritikbhatnagar2182
HTML-Tags
HTML
Web Technologies
HTML
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to update Node.js and NPM to next version ?
Top 10 Projects For Beginners To Practice HTML and CSS Skills
How to insert spaces/tabs in text using HTML/CSS?
REST API (Introduction)
Hide or show elements in HTML using display property
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": 52,
"s": 24,
"text": "\n24 Mar, 2022"
},
{
"code": null,
"e": 316,
"s": 52,
"text": "The <acronym> tag in HTML is used to define the acronym. The <acronym> tag is used to spell out another word. It is used to give useful information to browsers, translation systems, and search-engines. This tag is not supported in HTML 5 otherwise use <abbr> Tag."
},
{
"code": null,
"e": 325,
"s": 316,
"text": "Syntax: "
},
{
"code": null,
"e": 366,
"s": 325,
"text": "<acronym title=\"\"> Short Form </acronym>"
},
{
"code": null,
"e": 456,
"s": 366,
"text": "Attribute: This tag accepts an optional attribute as mentioned above and described below:"
},
{
"code": null,
"e": 591,
"s": 456,
"text": "title: It is used to specify extra information about the element. When the mouse moves over the element then it shows the information."
},
{
"code": null,
"e": 601,
"s": 591,
"text": "Example: "
},
{
"code": null,
"e": 606,
"s": 601,
"text": "html"
},
{
"code": "<!DOCTYPE html><html> <body> <h1>GeeksforGeeks</h1> <h2>This is HTML <acronym> Tag</h2> <acronym title=\"GeeksforGeeks\">GFG</acronym> <br> <acronym title=\"Operating System\">OS</acronym></body> </html>",
"e": 827,
"s": 606,
"text": null
},
{
"code": null,
"e": 836,
"s": 827,
"text": "Output: "
},
{
"code": null,
"e": 856,
"s": 836,
"text": "Supported Browser: "
},
{
"code": null,
"e": 870,
"s": 856,
"text": "Google Chrome"
},
{
"code": null,
"e": 888,
"s": 870,
"text": "Internet Explorer"
},
{
"code": null,
"e": 896,
"s": 888,
"text": "Firefox"
},
{
"code": null,
"e": 902,
"s": 896,
"text": "Opera"
},
{
"code": null,
"e": 909,
"s": 902,
"text": "Safari"
},
{
"code": null,
"e": 923,
"s": 909,
"text": "shubhamyadav4"
},
{
"code": null,
"e": 943,
"s": 923,
"text": "hritikbhatnagar2182"
},
{
"code": null,
"e": 953,
"s": 943,
"text": "HTML-Tags"
},
{
"code": null,
"e": 958,
"s": 953,
"text": "HTML"
},
{
"code": null,
"e": 975,
"s": 958,
"text": "Web Technologies"
},
{
"code": null,
"e": 980,
"s": 975,
"text": "HTML"
},
{
"code": null,
"e": 1078,
"s": 980,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 1126,
"s": 1078,
"text": "How to update Node.js and NPM to next version ?"
},
{
"code": null,
"e": 1188,
"s": 1126,
"text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills"
},
{
"code": null,
"e": 1238,
"s": 1188,
"text": "How to insert spaces/tabs in text using HTML/CSS?"
},
{
"code": null,
"e": 1262,
"s": 1238,
"text": "REST API (Introduction)"
},
{
"code": null,
"e": 1315,
"s": 1262,
"text": "Hide or show elements in HTML using display property"
},
{
"code": null,
"e": 1377,
"s": 1315,
"text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills"
},
{
"code": null,
"e": 1410,
"s": 1377,
"text": "Installation of Node.js on Linux"
},
{
"code": null,
"e": 1471,
"s": 1410,
"text": "Difference between var, let and const keywords in JavaScript"
},
{
"code": null,
"e": 1521,
"s": 1471,
"text": "How to insert spaces/tabs in text using HTML/CSS?"
}
] |
How to schedule background tasks (jobs) in ASP.NET Core? | Background tasks, also called as jobs, are essentially services that aren’t meant to execute during a normal flow of the application, such as sending email confirmations or periodically cleaning up the database to purge the inactive accounts. These jobs are not meant to interact with the customers or process user input. Rather, they run in the background, handling items from a queue or executing a long-running process.
A primary advantage of performing these tasks in a background job or service, you can keep the application responsive. For example, when a user signs up, instead of sending them an email in the same request, you can schedule a background job that will send the email to the user.
ASP.NET Core supports background tasks, by providing an abstraction for running a task in the background when the application starts. In ASP.NET Core, these types of background tasks are called Hosted Services, because you host them within your application.
You can use the IHostedService interface to run tasks in the background. The hosted service simply indicates a class that contains background task logic. When the application starts, you register multiple background tasks that run in the background while the application is running. When the application stops, the services are stopped as well. Even Kestrel, the ASP.NET Core server, runs as an IHostedService.
The IHostedService interface contains two methods:
StartAsync(CancellationToken): provides the logic to start the background task.
StartAsync(CancellationToken): provides the logic to start the background task.
StopAsync(CancellationToken): called before the application stops. It provides the logic to end the background task.
StopAsync(CancellationToken): called before the application stops. It provides the logic to end the background task.
Here is an example that illustrates the configuration of a hosted service.
public class Program{
public static void Main(string[] args){
CreateHostBuilder(args).Build().Run();
}
public static IHostBuilder CreateHostBuilder(string[] args) =>
Host.CreateDefaultBuilder(args)
.ConfigureWebHostDefaults(webBuilder =>{
webBuilder.UseStartup<Startup>();
})
.ConfigureServices(services =>{
services.AddHostedService<VideosWatcher>();
});
}
You can implement the IHostedService interface using the BackgroundService class as the base class. It contains an ExecuteAsync(CancellationToken) that is called to run the background service. The method returns a Task object that represents the background service lifetime. | [
{
"code": null,
"e": 1610,
"s": 1187,
"text": "Background tasks, also called as jobs, are essentially services that aren’t meant to execute during a normal flow of the application, such as sending email confirmations or periodically cleaning up the database to purge the inactive accounts. These jobs are not meant to interact with the customers or process user input. Rather, they run in the background, handling items from a queue or executing a long-running process."
},
{
"code": null,
"e": 1890,
"s": 1610,
"text": "A primary advantage of performing these tasks in a background job or service, you can keep the application responsive. For example, when a user signs up, instead of sending them an email in the same request, you can schedule a background job that will send the email to the user."
},
{
"code": null,
"e": 2148,
"s": 1890,
"text": "ASP.NET Core supports background tasks, by providing an abstraction for running a task in the background when the application starts. In ASP.NET Core, these types of background tasks are called Hosted Services, because you host them within your application."
},
{
"code": null,
"e": 2559,
"s": 2148,
"text": "You can use the IHostedService interface to run tasks in the background. The hosted service simply indicates a class that contains background task logic. When the application starts, you register multiple background tasks that run in the background while the application is running. When the application stops, the services are stopped as well. Even Kestrel, the ASP.NET Core server, runs as an IHostedService."
},
{
"code": null,
"e": 2610,
"s": 2559,
"text": "The IHostedService interface contains two methods:"
},
{
"code": null,
"e": 2690,
"s": 2610,
"text": "StartAsync(CancellationToken): provides the logic to start the background task."
},
{
"code": null,
"e": 2770,
"s": 2690,
"text": "StartAsync(CancellationToken): provides the logic to start the background task."
},
{
"code": null,
"e": 2887,
"s": 2770,
"text": "StopAsync(CancellationToken): called before the application stops. It provides the logic to end the background task."
},
{
"code": null,
"e": 3004,
"s": 2887,
"text": "StopAsync(CancellationToken): called before the application stops. It provides the logic to end the background task."
},
{
"code": null,
"e": 3079,
"s": 3004,
"text": "Here is an example that illustrates the configuration of a hosted service."
},
{
"code": null,
"e": 3498,
"s": 3079,
"text": "public class Program{\n public static void Main(string[] args){\n CreateHostBuilder(args).Build().Run();\n }\n\n public static IHostBuilder CreateHostBuilder(string[] args) =>\n Host.CreateDefaultBuilder(args)\n .ConfigureWebHostDefaults(webBuilder =>{\n webBuilder.UseStartup<Startup>();\n })\n .ConfigureServices(services =>{\n services.AddHostedService<VideosWatcher>();\n });\n}"
},
{
"code": null,
"e": 3773,
"s": 3498,
"text": "You can implement the IHostedService interface using the BackgroundService class as the base class. It contains an ExecuteAsync(CancellationToken) that is called to run the background service. The method returns a Task object that represents the background service lifetime."
}
] |
NumPy | Vector Multiplication | 05 May, 2020
Vector multiplication is of three types:
Scalar Product
Dot Product
Cross Product
Scalar Multiplication:Scalar multiplication can be represented by multiplying a scalar quantity by all the elements in the vector matrix.
Code: Python code explaining Scalar Multiplication
# importing libraries import numpy as npimport matplotlib.pyplot as pltimport math v = np.array([4, 1])w = 5 * vprint("w = ", w) # Plot worigin =[0], [0]plt.grid()plt.ticklabel_format(style ='sci', axis ='both', scilimits =(0, 0))plt.quiver(*origin, *w, scale = 10)plt.show()
Output :
w = [20 5]
Dot Product multiplication:
Code: Python code to explain Dot Product Multiplication
import numpy as npimport math v = np.array([2, 1])s = np.array([3, -2])d = np.dot(v, s)print(d)
Here, dot product can also be received using the ‘@’ operator.
d = v@s
Output :
4
Cross Product:
Code: Python code explaining Cross Product
import numpy as npimport math v = np.array([4, 9, 12])s = np.array([21, 32, 44])r = np.cross(v, s)print(r)
Output:
[ 12 76 -61]
Python-numpy
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here. | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n05 May, 2020"
},
{
"code": null,
"e": 69,
"s": 28,
"text": "Vector multiplication is of three types:"
},
{
"code": null,
"e": 84,
"s": 69,
"text": "Scalar Product"
},
{
"code": null,
"e": 96,
"s": 84,
"text": "Dot Product"
},
{
"code": null,
"e": 110,
"s": 96,
"text": "Cross Product"
},
{
"code": null,
"e": 248,
"s": 110,
"text": "Scalar Multiplication:Scalar multiplication can be represented by multiplying a scalar quantity by all the elements in the vector matrix."
},
{
"code": null,
"e": 299,
"s": 248,
"text": "Code: Python code explaining Scalar Multiplication"
},
{
"code": " # importing libraries import numpy as npimport matplotlib.pyplot as pltimport math v = np.array([4, 1])w = 5 * vprint(\"w = \", w) # Plot worigin =[0], [0]plt.grid()plt.ticklabel_format(style ='sci', axis ='both', scilimits =(0, 0))plt.quiver(*origin, *w, scale = 10)plt.show()",
"e": 606,
"s": 299,
"text": null
},
{
"code": null,
"e": 615,
"s": 606,
"text": "Output :"
},
{
"code": null,
"e": 628,
"s": 615,
"text": "w = [20 5]"
},
{
"code": null,
"e": 656,
"s": 628,
"text": "Dot Product multiplication:"
},
{
"code": null,
"e": 712,
"s": 656,
"text": "Code: Python code to explain Dot Product Multiplication"
},
{
"code": "import numpy as npimport math v = np.array([2, 1])s = np.array([3, -2])d = np.dot(v, s)print(d)",
"e": 809,
"s": 712,
"text": null
},
{
"code": null,
"e": 872,
"s": 809,
"text": "Here, dot product can also be received using the ‘@’ operator."
},
{
"code": null,
"e": 880,
"s": 872,
"text": "d = v@s"
},
{
"code": null,
"e": 889,
"s": 880,
"text": "Output :"
},
{
"code": null,
"e": 891,
"s": 889,
"text": "4"
},
{
"code": null,
"e": 906,
"s": 891,
"text": "Cross Product:"
},
{
"code": null,
"e": 949,
"s": 906,
"text": "Code: Python code explaining Cross Product"
},
{
"code": "import numpy as npimport math v = np.array([4, 9, 12])s = np.array([21, 32, 44])r = np.cross(v, s)print(r)",
"e": 1057,
"s": 949,
"text": null
},
{
"code": null,
"e": 1065,
"s": 1057,
"text": "Output:"
},
{
"code": null,
"e": 1079,
"s": 1065,
"text": "[ 12 76 -61]"
},
{
"code": null,
"e": 1092,
"s": 1079,
"text": "Python-numpy"
},
{
"code": null,
"e": 1099,
"s": 1092,
"text": "Python"
}
] |
Matplotlib.pyplot.xlim() in Python | 27 Apr, 2020
Matplotlib is a library in Python and it is numerical – mathematical extension for NumPy library. Pyplot is a state-based interface to a Matplotlib module which provides a MATLAB-like interface. There are various plots which can be used in Pyplot are Line Plot, Contour, Histogram, Scatter, 3D Plot, etc.#Sample Code
# sample codeimport matplotlib.pyplot as plt plt.plot([1, 2, 3, 4], [16, 4, 1, 8]) plt.show()
Output:
The xlim() function in pyplot module of matplotlib library is used to get or set the x-limits of the current axes.Syntax:
matplotlib.pyplot.xlim(*args, **kwargs)
Parameters: This method accept the following parameters that are described below:
left: This parameter is used to set the xlim to left.
right: This parameter is used to set the xlim to right.
**kwargs: This parameter is Text properties that is used to control the appearance of the labels.
Returns: This returns the following:
left, right: This returns the tuple of the new x-axis limits.
Below examples illustrate the matplotlib.pyplot.ylim() function in matplotlib.pyplot:
Example-1:
# Implementation of matplotlib functionimport matplotlib.pyplot as pltimport numpy as np h = plt.plot(np.arange(0, 10), np.arange(0, 10))plt.xlim([-5, 20])l1 = np.array((1, 1))angle = 65 th1 = plt.text(l1[0], l1[1], 'Line_angle', fontsize = 10, rotation = angle, rotation_mode ='anchor') plt.title(" matplotlib.pyplot.xlim() Example")plt.show()
Output:
Example-2:
# Implementation of matplotlib functionimport matplotlib.pyplot as pltimport numpy as np np.random.seed(9680801) mu, sigma = 50, 13x = mu + sigma * np.random.randn(10000) # the histogram of the datan, bins, patches = plt.hist(x, 50, density = True, facecolor ='g', alpha = 0.75) plt.xlabel('No of Users in K')plt.title('Histogram of IQ')plt.text(50, .035, r'$\mu = 50, \ \ \sigma = 13$') plt.xlim(-10, 110)plt.ylim(0, 0.04) plt.grid(True)plt.title(" matplotlib.pyplot.xlim() Example")plt.show()
Output:
Matplotlib Pyplot-class
Python-matplotlib
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
Convert integer to string in Python
Python OOPs Concepts
Introduction To PYTHON
Python | os.path.join() method
How to drop one or multiple columns in Pandas Dataframe | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n27 Apr, 2020"
},
{
"code": null,
"e": 345,
"s": 28,
"text": "Matplotlib is a library in Python and it is numerical – mathematical extension for NumPy library. Pyplot is a state-based interface to a Matplotlib module which provides a MATLAB-like interface. There are various plots which can be used in Pyplot are Line Plot, Contour, Histogram, Scatter, 3D Plot, etc.#Sample Code"
},
{
"code": "# sample codeimport matplotlib.pyplot as plt plt.plot([1, 2, 3, 4], [16, 4, 1, 8]) plt.show() ",
"e": 444,
"s": 345,
"text": null
},
{
"code": null,
"e": 452,
"s": 444,
"text": "Output:"
},
{
"code": null,
"e": 574,
"s": 452,
"text": "The xlim() function in pyplot module of matplotlib library is used to get or set the x-limits of the current axes.Syntax:"
},
{
"code": null,
"e": 614,
"s": 574,
"text": "matplotlib.pyplot.xlim(*args, **kwargs)"
},
{
"code": null,
"e": 696,
"s": 614,
"text": "Parameters: This method accept the following parameters that are described below:"
},
{
"code": null,
"e": 750,
"s": 696,
"text": "left: This parameter is used to set the xlim to left."
},
{
"code": null,
"e": 806,
"s": 750,
"text": "right: This parameter is used to set the xlim to right."
},
{
"code": null,
"e": 904,
"s": 806,
"text": "**kwargs: This parameter is Text properties that is used to control the appearance of the labels."
},
{
"code": null,
"e": 941,
"s": 904,
"text": "Returns: This returns the following:"
},
{
"code": null,
"e": 1003,
"s": 941,
"text": "left, right: This returns the tuple of the new x-axis limits."
},
{
"code": null,
"e": 1089,
"s": 1003,
"text": "Below examples illustrate the matplotlib.pyplot.ylim() function in matplotlib.pyplot:"
},
{
"code": null,
"e": 1100,
"s": 1089,
"text": "Example-1:"
},
{
"code": "# Implementation of matplotlib functionimport matplotlib.pyplot as pltimport numpy as np h = plt.plot(np.arange(0, 10), np.arange(0, 10))plt.xlim([-5, 20])l1 = np.array((1, 1))angle = 65 th1 = plt.text(l1[0], l1[1], 'Line_angle', fontsize = 10, rotation = angle, rotation_mode ='anchor') plt.title(\" matplotlib.pyplot.xlim() Example\")plt.show()",
"e": 1476,
"s": 1100,
"text": null
},
{
"code": null,
"e": 1484,
"s": 1476,
"text": "Output:"
},
{
"code": null,
"e": 1495,
"s": 1484,
"text": "Example-2:"
},
{
"code": "# Implementation of matplotlib functionimport matplotlib.pyplot as pltimport numpy as np np.random.seed(9680801) mu, sigma = 50, 13x = mu + sigma * np.random.randn(10000) # the histogram of the datan, bins, patches = plt.hist(x, 50, density = True, facecolor ='g', alpha = 0.75) plt.xlabel('No of Users in K')plt.title('Histogram of IQ')plt.text(50, .035, r'$\\mu = 50, \\ \\ \\sigma = 13$') plt.xlim(-10, 110)plt.ylim(0, 0.04) plt.grid(True)plt.title(\" matplotlib.pyplot.xlim() Example\")plt.show()",
"e": 2089,
"s": 1495,
"text": null
},
{
"code": null,
"e": 2097,
"s": 2089,
"text": "Output:"
},
{
"code": null,
"e": 2121,
"s": 2097,
"text": "Matplotlib Pyplot-class"
},
{
"code": null,
"e": 2139,
"s": 2121,
"text": "Python-matplotlib"
},
{
"code": null,
"e": 2146,
"s": 2139,
"text": "Python"
},
{
"code": null,
"e": 2244,
"s": 2146,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 2286,
"s": 2244,
"text": "Different ways to create Pandas Dataframe"
},
{
"code": null,
"e": 2308,
"s": 2286,
"text": "Enumerate() in Python"
},
{
"code": null,
"e": 2340,
"s": 2308,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 2369,
"s": 2340,
"text": "*args and **kwargs in Python"
},
{
"code": null,
"e": 2396,
"s": 2369,
"text": "Python Classes and Objects"
},
{
"code": null,
"e": 2432,
"s": 2396,
"text": "Convert integer to string in Python"
},
{
"code": null,
"e": 2453,
"s": 2432,
"text": "Python OOPs Concepts"
},
{
"code": null,
"e": 2476,
"s": 2453,
"text": "Introduction To PYTHON"
},
{
"code": null,
"e": 2507,
"s": 2476,
"text": "Python | os.path.join() method"
}
] |
Check if the given array is mirror-inverse | 01 Apr, 2021
Given an array arr[], the task is to find whether the array is mirror inverse. Inverse of an array means if the array elements are swapped with their corresponding indices and the array is called mirror-inverse if it’s inverse is equal to itself. If array is mirror-inverse then print Yes else print No.Examples:
Input: arr[] = [3, 4, 2, 0, 1} Output: Yes In the given array: index(0) -> value(3) index(1) -> value(4) index(2) -> value(2) index(3) -> value(0) index(4) -> value(1) To find the inverse of the array, swap the index and the value of the array. index(3) -> value(0) index(4) -> value(1) index(2) -> value(2) index(0) -> value(3) index(1) -> value(4)Inverse arr[] = {3, 4, 2, 0, 1} So, the inverse array is equal to the given array.Input: arr[] = {1, 2, 3, 0} Output: No
A simple approach is to create a new array by swapping the value and index of the given array and check whether the new array is equal to the original array or not.A better approach is to traverse the array and for all the indices, if arr[arr[index]] = index is satisfied then the given array is mirror inverse.Below is the implementation of the above approach:
C++
Java
Python3
C#
PHP
Javascript
// C++ implementation of the approach#include<bits/stdc++.h>using namespace std; // Function that returns true if// the array is mirror-inversebool isMirrorInverse(int arr[], int n){ for (int i = 0; i < n; i++) { // If condition fails for any element if (arr[arr[i]] != i) return false; } // Given array is mirror-inverse return true;} // Driver codeint main(){ int arr[] = { 1, 2, 3, 0 }; int n = sizeof(arr)/sizeof(arr[0]); if (isMirrorInverse(arr,n)) cout << "Yes"; else cout << "No"; return 0;} // This code is contributed by Rajput-Ji
// Java implementation of the approachpublic class GFG { // Function that returns true if // the array is mirror-inverse static boolean isMirrorInverse(int arr[]) { for (int i = 0; i < arr.length; i++) { // If condition fails for any element if (arr[arr[i]] != i) return false; } // Given array is mirror-inverse return true; } // Driver code public static void main(String[] args) { int arr[] = { 1, 2, 3, 0 }; if (isMirrorInverse(arr)) System.out.println("Yes"); else System.out.println("No"); }}
# Python 3 implementation of the approach # Function that returns true if# the array is mirror-inversedef isMirrorInverse(arr, n) : for i in range(n) : # If condition fails for any element if (arr[arr[i]] != i) : return False; # Given array is mirror-inverse return true; # Driver codeif __name__ == "__main__" : arr = [ 1, 2, 3, 0 ]; n = len(arr) ; if (isMirrorInverse(arr,n)) : print("Yes"); else : print("No"); # This code is contributed by Ryuga
// C# implementation of the approachusing System; class GFG{ // Function that returns true if // the array is mirror-inverse static bool isMirrorInverse(int []arr) { for (int i = 0; i < arr.Length; i++) { // If condition fails for any element if (arr[arr[i]] != i) return false; } // Given array is mirror-inverse return true; } // Driver code static public void Main () { int []arr = { 1, 2, 3, 0 }; if (isMirrorInverse(arr)) Console.WriteLine("Yes"); else Console.WriteLine("No"); }} // This code is contributed by ajit...
<?php// PHP implementation of the approach // Function that returns true if// the array is mirror-inversefunction isMirrorInverse($arr){ for ($i = 0; $i < sizeof($arr); $i++) { // If condition fails for any element if ($arr[$arr[$i]] != $i) return false; } // Given array is mirror-inverse return true;} // Driver code$arr = array(1, 2, 3, 0);if (isMirrorInverse($arr)) echo("Yes");else echo("No"); // These code is contributed by Code_Mech.?>
<script> // JavaScript implementation of the approach // Function that returns true if // the array is mirror-inverse function isMirrorInverse(arr) { for (i = 0; i < arr.length; i++) { // If condition fails for any element if (arr[arr[i]] != i) return false; } // Given array is mirror-inverse return true; } // Driver code var arr = [ 1, 2, 3, 0 ]; if (isMirrorInverse(arr)) document.write("Yes"); else document.write("No"); // This code contributed by Rajput-Ji </script>
No
jit_t
Rajput-Ji
ankthon
Code_Mech
Arrays
Java Programs
School Programming
Arrays
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Maximum and minimum of an array using minimum number of comparisons
Top 50 Array Coding Problems for Interviews
Multidimensional Arrays in Java
Stack Data Structure (Introduction and Program)
Linear Search
Initializing a List in Java
Java Programming Examples
Convert a String to Character Array in Java
Convert Double to Integer in Java
Implementing a Linked List in Java using Class | [
{
"code": null,
"e": 52,
"s": 24,
"text": "\n01 Apr, 2021"
},
{
"code": null,
"e": 367,
"s": 52,
"text": "Given an array arr[], the task is to find whether the array is mirror inverse. Inverse of an array means if the array elements are swapped with their corresponding indices and the array is called mirror-inverse if it’s inverse is equal to itself. If array is mirror-inverse then print Yes else print No.Examples: "
},
{
"code": null,
"e": 839,
"s": 367,
"text": "Input: arr[] = [3, 4, 2, 0, 1} Output: Yes In the given array: index(0) -> value(3) index(1) -> value(4) index(2) -> value(2) index(3) -> value(0) index(4) -> value(1) To find the inverse of the array, swap the index and the value of the array. index(3) -> value(0) index(4) -> value(1) index(2) -> value(2) index(0) -> value(3) index(1) -> value(4)Inverse arr[] = {3, 4, 2, 0, 1} So, the inverse array is equal to the given array.Input: arr[] = {1, 2, 3, 0} Output: No "
},
{
"code": null,
"e": 1205,
"s": 841,
"text": "A simple approach is to create a new array by swapping the value and index of the given array and check whether the new array is equal to the original array or not.A better approach is to traverse the array and for all the indices, if arr[arr[index]] = index is satisfied then the given array is mirror inverse.Below is the implementation of the above approach: "
},
{
"code": null,
"e": 1209,
"s": 1205,
"text": "C++"
},
{
"code": null,
"e": 1214,
"s": 1209,
"text": "Java"
},
{
"code": null,
"e": 1222,
"s": 1214,
"text": "Python3"
},
{
"code": null,
"e": 1225,
"s": 1222,
"text": "C#"
},
{
"code": null,
"e": 1229,
"s": 1225,
"text": "PHP"
},
{
"code": null,
"e": 1240,
"s": 1229,
"text": "Javascript"
},
{
"code": "// C++ implementation of the approach#include<bits/stdc++.h>using namespace std; // Function that returns true if// the array is mirror-inversebool isMirrorInverse(int arr[], int n){ for (int i = 0; i < n; i++) { // If condition fails for any element if (arr[arr[i]] != i) return false; } // Given array is mirror-inverse return true;} // Driver codeint main(){ int arr[] = { 1, 2, 3, 0 }; int n = sizeof(arr)/sizeof(arr[0]); if (isMirrorInverse(arr,n)) cout << \"Yes\"; else cout << \"No\"; return 0;} // This code is contributed by Rajput-Ji",
"e": 1879,
"s": 1240,
"text": null
},
{
"code": "// Java implementation of the approachpublic class GFG { // Function that returns true if // the array is mirror-inverse static boolean isMirrorInverse(int arr[]) { for (int i = 0; i < arr.length; i++) { // If condition fails for any element if (arr[arr[i]] != i) return false; } // Given array is mirror-inverse return true; } // Driver code public static void main(String[] args) { int arr[] = { 1, 2, 3, 0 }; if (isMirrorInverse(arr)) System.out.println(\"Yes\"); else System.out.println(\"No\"); }}",
"e": 2517,
"s": 1879,
"text": null
},
{
"code": "# Python 3 implementation of the approach # Function that returns true if# the array is mirror-inversedef isMirrorInverse(arr, n) : for i in range(n) : # If condition fails for any element if (arr[arr[i]] != i) : return False; # Given array is mirror-inverse return true; # Driver codeif __name__ == \"__main__\" : arr = [ 1, 2, 3, 0 ]; n = len(arr) ; if (isMirrorInverse(arr,n)) : print(\"Yes\"); else : print(\"No\"); # This code is contributed by Ryuga",
"e": 3044,
"s": 2517,
"text": null
},
{
"code": "// C# implementation of the approachusing System; class GFG{ // Function that returns true if // the array is mirror-inverse static bool isMirrorInverse(int []arr) { for (int i = 0; i < arr.Length; i++) { // If condition fails for any element if (arr[arr[i]] != i) return false; } // Given array is mirror-inverse return true; } // Driver code static public void Main () { int []arr = { 1, 2, 3, 0 }; if (isMirrorInverse(arr)) Console.WriteLine(\"Yes\"); else Console.WriteLine(\"No\"); }} // This code is contributed by ajit...",
"e": 3719,
"s": 3044,
"text": null
},
{
"code": "<?php// PHP implementation of the approach // Function that returns true if// the array is mirror-inversefunction isMirrorInverse($arr){ for ($i = 0; $i < sizeof($arr); $i++) { // If condition fails for any element if ($arr[$arr[$i]] != $i) return false; } // Given array is mirror-inverse return true;} // Driver code$arr = array(1, 2, 3, 0);if (isMirrorInverse($arr)) echo(\"Yes\");else echo(\"No\"); // These code is contributed by Code_Mech.?>",
"e": 4211,
"s": 3719,
"text": null
},
{
"code": "<script> // JavaScript implementation of the approach // Function that returns true if // the array is mirror-inverse function isMirrorInverse(arr) { for (i = 0; i < arr.length; i++) { // If condition fails for any element if (arr[arr[i]] != i) return false; } // Given array is mirror-inverse return true; } // Driver code var arr = [ 1, 2, 3, 0 ]; if (isMirrorInverse(arr)) document.write(\"Yes\"); else document.write(\"No\"); // This code contributed by Rajput-Ji </script>",
"e": 4818,
"s": 4211,
"text": null
},
{
"code": null,
"e": 4821,
"s": 4818,
"text": "No"
},
{
"code": null,
"e": 4829,
"s": 4823,
"text": "jit_t"
},
{
"code": null,
"e": 4839,
"s": 4829,
"text": "Rajput-Ji"
},
{
"code": null,
"e": 4847,
"s": 4839,
"text": "ankthon"
},
{
"code": null,
"e": 4857,
"s": 4847,
"text": "Code_Mech"
},
{
"code": null,
"e": 4864,
"s": 4857,
"text": "Arrays"
},
{
"code": null,
"e": 4878,
"s": 4864,
"text": "Java Programs"
},
{
"code": null,
"e": 4897,
"s": 4878,
"text": "School Programming"
},
{
"code": null,
"e": 4904,
"s": 4897,
"text": "Arrays"
},
{
"code": null,
"e": 5002,
"s": 4904,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 5070,
"s": 5002,
"text": "Maximum and minimum of an array using minimum number of comparisons"
},
{
"code": null,
"e": 5114,
"s": 5070,
"text": "Top 50 Array Coding Problems for Interviews"
},
{
"code": null,
"e": 5146,
"s": 5114,
"text": "Multidimensional Arrays in Java"
},
{
"code": null,
"e": 5194,
"s": 5146,
"text": "Stack Data Structure (Introduction and Program)"
},
{
"code": null,
"e": 5208,
"s": 5194,
"text": "Linear Search"
},
{
"code": null,
"e": 5236,
"s": 5208,
"text": "Initializing a List in Java"
},
{
"code": null,
"e": 5262,
"s": 5236,
"text": "Java Programming Examples"
},
{
"code": null,
"e": 5306,
"s": 5262,
"text": "Convert a String to Character Array in Java"
},
{
"code": null,
"e": 5340,
"s": 5306,
"text": "Convert Double to Integer in Java"
}
] |
with statement in Python | 15 Feb, 2019
with statement in Python is used in exception handling to make the code cleaner and much more readable. It simplifies the management of common resources like file streams. Observe the following code example on how the use of with statement makes code cleaner.
# file handling # 1) without using with statementfile = open('file_path', 'w')file.write('hello world !')file.close() # 2) without using with statementfile = open('file_path', 'w')try: file.write('hello world')finally: file.close()
# using with statementwith open('file_path', 'w') as file: file.write('hello world !')
Notice that unlike the first two implementations, there is no need to call file.close() when using with statement. The with statement itself ensures proper acquisition and release of resources. An exception during the file.write() call in the first implementation can prevent the file from closing properly which may introduce several bugs in the code, i.e. many changes in files do not go into effect until the file is properly closed.
The second approach in the above example takes care of all the exceptions but using the with statement makes the code compact and much more readable. Thus, with statement helps avoiding bugs and leaks by ensuring that a resource is properly released when the code using the resource is completely executed. The with statement is popularly used with file streams, as shown above and with Locks, sockets, subprocesses and telnets etc.
There is nothing special in open() which makes it usable with the with statement and the same functionality can be provided in user defined objects. Supporting with statement in your objects will ensure that you never leave any resource open.To use with statement in user defined objects you only need to add the methods __enter__() and __exit__() in the object methods. Consider the following example for further clarification.
# a simple file writer object class MessageWriter(object): def __init__(self, file_name): self.file_name = file_name def __enter__(self): self.file = open(self.file_name, 'w') return self.file def __exit__(self): self.file.close() # using with statement with MessageWriter with MessageWriter('my_file.txt') as xfile: xfile.write('hello world')
Let’s examine the above code. If you notice, what follows the with keyword is the constructor of MessageWriter. As soon as the execution enters the context of the with statement a MessageWriter object is created and python then calls the __enter__() method. In this __enter__() method, initialize the resource you wish to use in the object. This __enter__() method should always return a descriptor of the acquired resource.
What are resource descriptors?These are the handles provided by the operating system to access the requested resources. In the following code block, file is a descriptor of the file stream resource.
file = open('hello.txt')
In the MessageWriter example provided above, the __enter__() method creates a file descriptor and returns it. The name xfile here is used to refer to the file descriptor returned by the __enter__() method. The block of code which uses the acquired resource is placed inside the block of the with statement. As soon as the code inside the with block is executed, the __exit__() method is called. All the acquired resources are released in the __exit__() method. This is how we use the with statement with user defined objects.
This interface of __enter__() and __exit__() methods which provides the support of with statement in user defined objects is called Context Manager.
A class based context manager as shown above is not the only way to support the with statement in user defined objects. The contextlib module provides a few more abstractions built upon the basic context manager interface. Here is how we can rewrite the context manager for the MessageWriter object using the contextlib module.
from contextlib import contextmanager class MessageWriter(object): def __init__(self, filename): self.file_name = filename @contextmanager def open_file(self): try: file = open(self.file_name, 'w') yield file finally: file.close() # usagemessage_writer = MessageWriter('hello.txt')with message_writer.open_file() as my_file: my_file.write('hello world')
In this code example, because of the yield statement in its definition, the function open_file() is a generator function.When this open_file() function is called, it creates a resource descriptor named file. This resource descriptor is then passed to the caller and is represented here by the variable my_file. After the code inside the with block is executed the program control returns back to the open_file() function. The open_file() function resumes its execution and executes the code following the yield statement. This part of code which appears after the yield statement releases the acquired resources. The @contextmanager here is a decorator.
The previous class-based implementation and this generator-based implementation of context managers is internally the same. While the later seems more readable, it requires the knowledge of generators, decorators and yield.
Python-exceptions
python-object
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python Dictionary
Different ways to create Pandas Dataframe
Python String | replace()
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 | [
{
"code": null,
"e": 54,
"s": 26,
"text": "\n15 Feb, 2019"
},
{
"code": null,
"e": 314,
"s": 54,
"text": "with statement in Python is used in exception handling to make the code cleaner and much more readable. It simplifies the management of common resources like file streams. Observe the following code example on how the use of with statement makes code cleaner."
},
{
"code": "# file handling # 1) without using with statementfile = open('file_path', 'w')file.write('hello world !')file.close() # 2) without using with statementfile = open('file_path', 'w')try: file.write('hello world')finally: file.close()",
"e": 554,
"s": 314,
"text": null
},
{
"code": "# using with statementwith open('file_path', 'w') as file: file.write('hello world !')",
"e": 646,
"s": 556,
"text": null
},
{
"code": null,
"e": 1083,
"s": 646,
"text": "Notice that unlike the first two implementations, there is no need to call file.close() when using with statement. The with statement itself ensures proper acquisition and release of resources. An exception during the file.write() call in the first implementation can prevent the file from closing properly which may introduce several bugs in the code, i.e. many changes in files do not go into effect until the file is properly closed."
},
{
"code": null,
"e": 1516,
"s": 1083,
"text": "The second approach in the above example takes care of all the exceptions but using the with statement makes the code compact and much more readable. Thus, with statement helps avoiding bugs and leaks by ensuring that a resource is properly released when the code using the resource is completely executed. The with statement is popularly used with file streams, as shown above and with Locks, sockets, subprocesses and telnets etc."
},
{
"code": null,
"e": 1945,
"s": 1516,
"text": "There is nothing special in open() which makes it usable with the with statement and the same functionality can be provided in user defined objects. Supporting with statement in your objects will ensure that you never leave any resource open.To use with statement in user defined objects you only need to add the methods __enter__() and __exit__() in the object methods. Consider the following example for further clarification."
},
{
"code": "# a simple file writer object class MessageWriter(object): def __init__(self, file_name): self.file_name = file_name def __enter__(self): self.file = open(self.file_name, 'w') return self.file def __exit__(self): self.file.close() # using with statement with MessageWriter with MessageWriter('my_file.txt') as xfile: xfile.write('hello world')",
"e": 2340,
"s": 1945,
"text": null
},
{
"code": null,
"e": 2765,
"s": 2340,
"text": "Let’s examine the above code. If you notice, what follows the with keyword is the constructor of MessageWriter. As soon as the execution enters the context of the with statement a MessageWriter object is created and python then calls the __enter__() method. In this __enter__() method, initialize the resource you wish to use in the object. This __enter__() method should always return a descriptor of the acquired resource."
},
{
"code": null,
"e": 2964,
"s": 2765,
"text": "What are resource descriptors?These are the handles provided by the operating system to access the requested resources. In the following code block, file is a descriptor of the file stream resource."
},
{
"code": "file = open('hello.txt')",
"e": 2989,
"s": 2964,
"text": null
},
{
"code": null,
"e": 3515,
"s": 2989,
"text": "In the MessageWriter example provided above, the __enter__() method creates a file descriptor and returns it. The name xfile here is used to refer to the file descriptor returned by the __enter__() method. The block of code which uses the acquired resource is placed inside the block of the with statement. As soon as the code inside the with block is executed, the __exit__() method is called. All the acquired resources are released in the __exit__() method. This is how we use the with statement with user defined objects."
},
{
"code": null,
"e": 3664,
"s": 3515,
"text": "This interface of __enter__() and __exit__() methods which provides the support of with statement in user defined objects is called Context Manager."
},
{
"code": null,
"e": 3992,
"s": 3664,
"text": "A class based context manager as shown above is not the only way to support the with statement in user defined objects. The contextlib module provides a few more abstractions built upon the basic context manager interface. Here is how we can rewrite the context manager for the MessageWriter object using the contextlib module."
},
{
"code": "from contextlib import contextmanager class MessageWriter(object): def __init__(self, filename): self.file_name = filename @contextmanager def open_file(self): try: file = open(self.file_name, 'w') yield file finally: file.close() # usagemessage_writer = MessageWriter('hello.txt')with message_writer.open_file() as my_file: my_file.write('hello world')",
"e": 4416,
"s": 3992,
"text": null
},
{
"code": null,
"e": 5070,
"s": 4416,
"text": "In this code example, because of the yield statement in its definition, the function open_file() is a generator function.When this open_file() function is called, it creates a resource descriptor named file. This resource descriptor is then passed to the caller and is represented here by the variable my_file. After the code inside the with block is executed the program control returns back to the open_file() function. The open_file() function resumes its execution and executes the code following the yield statement. This part of code which appears after the yield statement releases the acquired resources. The @contextmanager here is a decorator."
},
{
"code": null,
"e": 5294,
"s": 5070,
"text": "The previous class-based implementation and this generator-based implementation of context managers is internally the same. While the later seems more readable, it requires the knowledge of generators, decorators and yield."
},
{
"code": null,
"e": 5312,
"s": 5294,
"text": "Python-exceptions"
},
{
"code": null,
"e": 5326,
"s": 5312,
"text": "python-object"
},
{
"code": null,
"e": 5333,
"s": 5326,
"text": "Python"
},
{
"code": null,
"e": 5431,
"s": 5333,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 5449,
"s": 5431,
"text": "Python Dictionary"
},
{
"code": null,
"e": 5491,
"s": 5449,
"text": "Different ways to create Pandas Dataframe"
},
{
"code": null,
"e": 5517,
"s": 5491,
"text": "Python String | replace()"
},
{
"code": null,
"e": 5549,
"s": 5517,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 5578,
"s": 5549,
"text": "*args and **kwargs in Python"
},
{
"code": null,
"e": 5605,
"s": 5578,
"text": "Python Classes and Objects"
},
{
"code": null,
"e": 5626,
"s": 5605,
"text": "Python OOPs Concepts"
},
{
"code": null,
"e": 5649,
"s": 5626,
"text": "Introduction To PYTHON"
},
{
"code": null,
"e": 5685,
"s": 5649,
"text": "Convert integer to string in Python"
}
] |
How to pass argument to an Exception in Python? | 07 Oct, 2021
There might arise a situation where there is a need for additional information from an exception raised by Python. Python has two types of exceptions namely, Built-In Exceptions and User-Defined Exceptions.Why use Argument in Exceptions? Using arguments for Exceptions in Python is useful for the following reasons:
It can be used to gain additional information about the error encountered.
As contents of an Argument can vary depending upon different types of Exceptions in Python, Variables can be supplied to the Exceptions to capture the essence of the encountered errors. Same error can occur of different causes, Arguments helps us identify the specific cause for an error using the except clause.
It can also be used to trap multiple exceptions, by using a variable to follow the tuple of Exceptions.
Arguments in Built-in Exceptions:
The below codes demonstrates use of Argument with Built-in Exceptions:Example 1:
Python3
try: b = float(100 + 50 / 0)except Exception as Argument: print( 'This is the Argument\n', Argument)
Output:
This is the Argument
division by zero
Example 2:
Python3
my_string = "GeeksForGeeks" try: b = float(my_string / 20)except Exception as Argument: print( 'This is the Argument\n', Argument)
Output:
This is the Argument
unsupported operand type(s) for /: 'str' and 'int'
Arguments in User-defined Exceptions:
The below codes demonstrates use of Argument with User-defined Exceptions:Example 1:
Python3
# create user-defined exception # derived from super class Exceptionclass MyError(Exception): # Constructor or Initializer def __init__(self, value): self.value = value # __str__ is to print() the value def __str__(self): return(repr(self.value)) try: raise(MyError("Some Error Data")) # Value of Exception is stored in errorexcept MyError as Argument: print('This is the Argument\n', Argument)
Output:
This is the Argument
'Some Error Data'
Example 2:
Python3
# class Error is derived from super class Exceptionclass Error(Exception): # Error is derived class for Exception, but # Base class for exceptions in this module pass class TransitionError(Error): # Raised when an operation attempts a state # transition that's not allowed. def __init__(self, prev, nex, msg): self.prev = prev self.next = nex try: raise(TransitionError(2, 3 * 2, "Not Allowed")) # Value of Exception is stored in errorexcept TransitionError as Argument: print('Exception occurred: ', Argument)
Output:
Exception occurred: (2, 6, 'Not Allowed')
anikaseth98
Python-exceptions
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here. | [
{
"code": null,
"e": 54,
"s": 26,
"text": "\n07 Oct, 2021"
},
{
"code": null,
"e": 371,
"s": 54,
"text": "There might arise a situation where there is a need for additional information from an exception raised by Python. Python has two types of exceptions namely, Built-In Exceptions and User-Defined Exceptions.Why use Argument in Exceptions? Using arguments for Exceptions in Python is useful for the following reasons: "
},
{
"code": null,
"e": 447,
"s": 371,
"text": "It can be used to gain additional information about the error encountered. "
},
{
"code": null,
"e": 761,
"s": 447,
"text": "As contents of an Argument can vary depending upon different types of Exceptions in Python, Variables can be supplied to the Exceptions to capture the essence of the encountered errors. Same error can occur of different causes, Arguments helps us identify the specific cause for an error using the except clause. "
},
{
"code": null,
"e": 867,
"s": 761,
"text": "It can also be used to trap multiple exceptions, by using a variable to follow the tuple of Exceptions. "
},
{
"code": null,
"e": 901,
"s": 867,
"text": "Arguments in Built-in Exceptions:"
},
{
"code": null,
"e": 983,
"s": 901,
"text": "The below codes demonstrates use of Argument with Built-in Exceptions:Example 1: "
},
{
"code": null,
"e": 991,
"s": 983,
"text": "Python3"
},
{
"code": "try: b = float(100 + 50 / 0)except Exception as Argument: print( 'This is the Argument\\n', Argument)",
"e": 1098,
"s": 991,
"text": null
},
{
"code": null,
"e": 1108,
"s": 1098,
"text": "Output: "
},
{
"code": null,
"e": 1147,
"s": 1108,
"text": "This is the Argument\n division by zero"
},
{
"code": null,
"e": 1159,
"s": 1147,
"text": "Example 2: "
},
{
"code": null,
"e": 1167,
"s": 1159,
"text": "Python3"
},
{
"code": "my_string = \"GeeksForGeeks\" try: b = float(my_string / 20)except Exception as Argument: print( 'This is the Argument\\n', Argument)",
"e": 1304,
"s": 1167,
"text": null
},
{
"code": null,
"e": 1314,
"s": 1304,
"text": "Output: "
},
{
"code": null,
"e": 1387,
"s": 1314,
"text": "This is the Argument\n unsupported operand type(s) for /: 'str' and 'int'"
},
{
"code": null,
"e": 1425,
"s": 1387,
"text": "Arguments in User-defined Exceptions:"
},
{
"code": null,
"e": 1511,
"s": 1425,
"text": "The below codes demonstrates use of Argument with User-defined Exceptions:Example 1: "
},
{
"code": null,
"e": 1519,
"s": 1511,
"text": "Python3"
},
{
"code": "# create user-defined exception # derived from super class Exceptionclass MyError(Exception): # Constructor or Initializer def __init__(self, value): self.value = value # __str__ is to print() the value def __str__(self): return(repr(self.value)) try: raise(MyError(\"Some Error Data\")) # Value of Exception is stored in errorexcept MyError as Argument: print('This is the Argument\\n', Argument)",
"e": 1956,
"s": 1519,
"text": null
},
{
"code": null,
"e": 1966,
"s": 1956,
"text": "Output: "
},
{
"code": null,
"e": 2006,
"s": 1966,
"text": "This is the Argument\n 'Some Error Data'"
},
{
"code": null,
"e": 2018,
"s": 2006,
"text": "Example 2: "
},
{
"code": null,
"e": 2026,
"s": 2018,
"text": "Python3"
},
{
"code": "# class Error is derived from super class Exceptionclass Error(Exception): # Error is derived class for Exception, but # Base class for exceptions in this module pass class TransitionError(Error): # Raised when an operation attempts a state # transition that's not allowed. def __init__(self, prev, nex, msg): self.prev = prev self.next = nex try: raise(TransitionError(2, 3 * 2, \"Not Allowed\")) # Value of Exception is stored in errorexcept TransitionError as Argument: print('Exception occurred: ', Argument)",
"e": 2577,
"s": 2026,
"text": null
},
{
"code": null,
"e": 2586,
"s": 2577,
"text": "Output: "
},
{
"code": null,
"e": 2629,
"s": 2586,
"text": "Exception occurred: (2, 6, 'Not Allowed')"
},
{
"code": null,
"e": 2641,
"s": 2629,
"text": "anikaseth98"
},
{
"code": null,
"e": 2659,
"s": 2641,
"text": "Python-exceptions"
},
{
"code": null,
"e": 2666,
"s": 2659,
"text": "Python"
}
] |
Multi-Character Literal in C/C++ | 08 Mar, 2021
Character literals for C and C++ are char, string, and their Unicode and Raw type. Also, there is a multi-character literal that contains more than one c-char. A single c-char literal has type char and a multi-character literal is conditionally-supported, has type int, and has an implementation-defined value.
Example:
'a' is a character literal.
"abcd" is a string literal.
'abcd' is a multicharacter literal.
Most C/C++ compilers support multi-character literals. Below is the example to demonstrate the concept of Multi-character Literal.
Example 1:
C
// C program to demonstrate // Multicharacter literal#pragma GCC diagnostic ignored "-Wmultichar" // This disables the // multi-character warning#include <stdio.h> // Driver codeint main(){ printf("%d", 'abcd'); return 0;}
1633837924
Example 2:
C++
// C++ program to demonstrate// multi-character literal#include <iostream> // Due to a bug we can't disable// multi-character warning in C++// using #pragma GCC diagnostic// ignored "-Wmultichar"using namespace std; // Driver codeint main(){ cout << 'abcd' << endl; return 0;}
Output:
This compiles and runs fine and the multi-character literal stores as an integer value (from where the number comes you will find below). As pedantic compiler flag generally passed it gives a warning on all multi-character literals. This warning helps to point out if we mistakenly use ‘ instead of “. The warning is:
warning: multi-character character constant [-Wmultichar]
You can disable the warning using the #pragma GCC diagnostic ignored “-Wmultichar” directly from the source code.
Below are some important information about Multi-character Literals:
1. Multi-character Literals are different from the string: Multi character literals are not the same as string or character array, they are totally different. Multi character literals are integer type’s not character types.
C++
#include <iostream>#include <typeinfo>using namespace std; int main(){ auto a = 10; auto b = 'a'; auto c = 'abcd'; auto d = "abcd"; // 10 is of type i or int cout << "type of 10 is " << typeid(a).name() << endl; // 'a' is of type c or char cout << "type of \'a\' is " << typeid(b).name() << endl; // Multicharacter literals // 'abcd' is of type i or int cout << "type of \'abcd\' is " << typeid(c).name() << endl; // "abcd" is of type string cout << "type of \"abcd\" is " << typeid(d).name() << endl; return 0;}
Output:
Though typeid() should not be used to tell the type as it’s sometimes guaranteed by the standard to give you the wrong answer. But here typeid() is sufficient to point out that Multi-character stores as an integer type and different from char and string.
2. Multi-character literals are implementation-defined and not a bug:
An aspect of C++’s semantics that is defined for each implementation rather than specified in the standard for every implementation. An example is the size of an int (which must be at least 16 bits but can be longer). Avoid implementation-defined behavior whenever possible.
Any code that relies on implementation-defined behavior is only guaranteed to work under a specific platform and/or compiler. Example:
sizeof(int); It may be 4 bytes or 8 bytes depend on the compiler.
int *p = malloc(0 * sizeof *o); It may result in p either being NULL or a unique pointer (as specified in 7.20.3 of the C99 Standard).
C++ inherited the multi-character literals from C and C inherited it from the B programming language. Most compilers (except MSVC) implement multi-character literals as specified in B.
It is not that the creators of C or C++ didn’t know about this, they just leave it in hands of compilers to deal with it.
3. Multi-character literals stores as int rather than char (C standard): Now the question is from where the integer value is coming. On compilers where int is 4 bytes, Multi-characters stores as 4 bytes as it depends on the compiler. For 4 bytes Multi-character literal each char initialize successive bytes of the resulting integer(big-endian, zero-padded, right-adjusted order). For Example, The value converted in 4 bytes int for ASCII char as,
Here, integers have 4 bytes of storage:
Now the ASCII of the first character from the left gets stored at last. Basically, “Big-endian” byte ordering:
Then for the next character, the integer value shifted 1 byte left:
And so on,
Now, these 4 bytes represent a single integer number and calculated as:
'abcd' = (('a'*256 + 'b')*256 + `c`)*256 + 'd' = 1633837924 = 0x61626364 = '0xa0xb0xc0xd'
C++
#include <iostream>using namespace std; // Driver codeint main(){ cout << "\'abcd\' = " << 'abcd' << " = " << hex << 'abcd' << endl; cout << "\'a' = " << dec << (int)'a' << " = " << hex << (int)'a'; return 0;}
Output:
If there are more than 4 characters in the Multi-character literal then only the last 4 characters stored and therefore, ‘abcdefgh’ == ‘efgh’, although the compiler will issue a warning on the literal that overflows.
C++
#include <iostream>using namespace std; // Driver codeint main(){ cout << "\'abcd\' = " << 'abcd' << endl; cout << "\'efgh\' = " << 'efgh' << endl; cout << "\'abcdefgh\' = " << 'abcdefgh' << endl; return 0;}
Output:
And like above if we try to store Multi-character literal as char then only the last character gets stored.
C++
#include <iostream>using namespace std; // Driver codeint main(){ char c = 'abcd'; // stores as, c = ' d ' cout << c << endl; return 0;}
Output:
Here we can see that the Multi-character literal which is a 4-byte integer is converting to 1-byte char and only stored the last character.
Good thing about multi-character literals: As multi-character literals are store as int, it can be used for comparison and in switch-case where strings are not used normally.
C++
#include <iostream>using namespace std; // Driver codeint main(){ int s = 'abcd'; switch (s) { case 'abcd': cout << ('abcd' == 'abcd'); // s = 1633837924 and 'abcd' // = 1633837924 so, value of // s is equal to 'abcd' } return 0;}
Output:
Problems with multi-character literals:
In C++, multi-character literals are conditionally-supported. Thus, your code may fail to compile.
They are supported, but they have implementation-defined value. If the code runs on your machine fine that does not guarantee it will run on other machines.
Also, it is possible that the implementation chooses to assign all multi-character literals the value 0, breaking your code.
C Language
C++
CPP
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Unordered Sets in C++ Standard Template Library
Operators in C / C++
Exception Handling in C++
What is the purpose of a function prototype?
Sorting Vector of Pairs in C++ | Set 1 (Sort by first and second)
Vector in C++ STL
Map in C++ Standard Template Library (STL)
Initialize a vector in C++ (7 different ways)
Set in C++ Standard Template Library (STL)
Priority Queue in C++ Standard Template Library (STL) | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n08 Mar, 2021"
},
{
"code": null,
"e": 340,
"s": 28,
"text": "Character literals for C and C++ are char, string, and their Unicode and Raw type. Also, there is a multi-character literal that contains more than one c-char. A single c-char literal has type char and a multi-character literal is conditionally-supported, has type int, and has an implementation-defined value. "
},
{
"code": null,
"e": 350,
"s": 340,
"text": "Example: "
},
{
"code": null,
"e": 442,
"s": 350,
"text": "'a' is a character literal.\n\"abcd\" is a string literal.\n'abcd' is a multicharacter literal."
},
{
"code": null,
"e": 573,
"s": 442,
"text": "Most C/C++ compilers support multi-character literals. Below is the example to demonstrate the concept of Multi-character Literal."
},
{
"code": null,
"e": 584,
"s": 573,
"text": "Example 1:"
},
{
"code": null,
"e": 586,
"s": 584,
"text": "C"
},
{
"code": "// C program to demonstrate // Multicharacter literal#pragma GCC diagnostic ignored \"-Wmultichar\" // This disables the // multi-character warning#include <stdio.h> // Driver codeint main(){ printf(\"%d\", 'abcd'); return 0;}",
"e": 813,
"s": 586,
"text": null
},
{
"code": null,
"e": 824,
"s": 813,
"text": "1633837924"
},
{
"code": null,
"e": 835,
"s": 824,
"text": "Example 2:"
},
{
"code": null,
"e": 839,
"s": 835,
"text": "C++"
},
{
"code": "// C++ program to demonstrate// multi-character literal#include <iostream> // Due to a bug we can't disable// multi-character warning in C++// using #pragma GCC diagnostic// ignored \"-Wmultichar\"using namespace std; // Driver codeint main(){ cout << 'abcd' << endl; return 0;}",
"e": 1124,
"s": 839,
"text": null
},
{
"code": null,
"e": 1132,
"s": 1124,
"text": "Output:"
},
{
"code": null,
"e": 1451,
"s": 1132,
"text": "This compiles and runs fine and the multi-character literal stores as an integer value (from where the number comes you will find below). As pedantic compiler flag generally passed it gives a warning on all multi-character literals. This warning helps to point out if we mistakenly use ‘ instead of “. The warning is:"
},
{
"code": null,
"e": 1509,
"s": 1451,
"text": "warning: multi-character character constant [-Wmultichar]"
},
{
"code": null,
"e": 1623,
"s": 1509,
"text": "You can disable the warning using the #pragma GCC diagnostic ignored “-Wmultichar” directly from the source code."
},
{
"code": null,
"e": 1692,
"s": 1623,
"text": "Below are some important information about Multi-character Literals:"
},
{
"code": null,
"e": 1916,
"s": 1692,
"text": "1. Multi-character Literals are different from the string: Multi character literals are not the same as string or character array, they are totally different. Multi character literals are integer type’s not character types."
},
{
"code": null,
"e": 1920,
"s": 1916,
"text": "C++"
},
{
"code": "#include <iostream>#include <typeinfo>using namespace std; int main(){ auto a = 10; auto b = 'a'; auto c = 'abcd'; auto d = \"abcd\"; // 10 is of type i or int cout << \"type of 10 is \" << typeid(a).name() << endl; // 'a' is of type c or char cout << \"type of \\'a\\' is \" << typeid(b).name() << endl; // Multicharacter literals // 'abcd' is of type i or int cout << \"type of \\'abcd\\' is \" << typeid(c).name() << endl; // \"abcd\" is of type string cout << \"type of \\\"abcd\\\" is \" << typeid(d).name() << endl; return 0;}",
"e": 2506,
"s": 1920,
"text": null
},
{
"code": null,
"e": 2514,
"s": 2506,
"text": "Output:"
},
{
"code": null,
"e": 2769,
"s": 2514,
"text": "Though typeid() should not be used to tell the type as it’s sometimes guaranteed by the standard to give you the wrong answer. But here typeid() is sufficient to point out that Multi-character stores as an integer type and different from char and string."
},
{
"code": null,
"e": 2839,
"s": 2769,
"text": "2. Multi-character literals are implementation-defined and not a bug:"
},
{
"code": null,
"e": 3114,
"s": 2839,
"text": "An aspect of C++’s semantics that is defined for each implementation rather than specified in the standard for every implementation. An example is the size of an int (which must be at least 16 bits but can be longer). Avoid implementation-defined behavior whenever possible."
},
{
"code": null,
"e": 3250,
"s": 3114,
"text": "Any code that relies on implementation-defined behavior is only guaranteed to work under a specific platform and/or compiler. Example: "
},
{
"code": null,
"e": 3316,
"s": 3250,
"text": "sizeof(int); It may be 4 bytes or 8 bytes depend on the compiler."
},
{
"code": null,
"e": 3451,
"s": 3316,
"text": "int *p = malloc(0 * sizeof *o); It may result in p either being NULL or a unique pointer (as specified in 7.20.3 of the C99 Standard)."
},
{
"code": null,
"e": 3637,
"s": 3451,
"text": "C++ inherited the multi-character literals from C and C inherited it from the B programming language. Most compilers (except MSVC) implement multi-character literals as specified in B. "
},
{
"code": null,
"e": 3760,
"s": 3637,
"text": "It is not that the creators of C or C++ didn’t know about this, they just leave it in hands of compilers to deal with it. "
},
{
"code": null,
"e": 4209,
"s": 3760,
"text": "3. Multi-character literals stores as int rather than char (C standard): Now the question is from where the integer value is coming. On compilers where int is 4 bytes, Multi-characters stores as 4 bytes as it depends on the compiler. For 4 bytes Multi-character literal each char initialize successive bytes of the resulting integer(big-endian, zero-padded, right-adjusted order). For Example, The value converted in 4 bytes int for ASCII char as,"
},
{
"code": null,
"e": 4249,
"s": 4209,
"text": "Here, integers have 4 bytes of storage:"
},
{
"code": null,
"e": 4360,
"s": 4249,
"text": "Now the ASCII of the first character from the left gets stored at last. Basically, “Big-endian” byte ordering:"
},
{
"code": null,
"e": 4428,
"s": 4360,
"text": "Then for the next character, the integer value shifted 1 byte left:"
},
{
"code": null,
"e": 4439,
"s": 4428,
"text": "And so on,"
},
{
"code": null,
"e": 4511,
"s": 4439,
"text": "Now, these 4 bytes represent a single integer number and calculated as:"
},
{
"code": null,
"e": 4601,
"s": 4511,
"text": "'abcd' = (('a'*256 + 'b')*256 + `c`)*256 + 'd' = 1633837924 = 0x61626364 = '0xa0xb0xc0xd'"
},
{
"code": null,
"e": 4605,
"s": 4601,
"text": "C++"
},
{
"code": "#include <iostream>using namespace std; // Driver codeint main(){ cout << \"\\'abcd\\' = \" << 'abcd' << \" = \" << hex << 'abcd' << endl; cout << \"\\'a' = \" << dec << (int)'a' << \" = \" << hex << (int)'a'; return 0;}",
"e": 4845,
"s": 4605,
"text": null
},
{
"code": null,
"e": 4853,
"s": 4845,
"text": "Output:"
},
{
"code": null,
"e": 5070,
"s": 4853,
"text": "If there are more than 4 characters in the Multi-character literal then only the last 4 characters stored and therefore, ‘abcdefgh’ == ‘efgh’, although the compiler will issue a warning on the literal that overflows."
},
{
"code": null,
"e": 5074,
"s": 5070,
"text": "C++"
},
{
"code": "#include <iostream>using namespace std; // Driver codeint main(){ cout << \"\\'abcd\\' = \" << 'abcd' << endl; cout << \"\\'efgh\\' = \" << 'efgh' << endl; cout << \"\\'abcdefgh\\' = \" << 'abcdefgh' << endl; return 0;}",
"e": 5295,
"s": 5074,
"text": null
},
{
"code": null,
"e": 5303,
"s": 5295,
"text": "Output:"
},
{
"code": null,
"e": 5411,
"s": 5303,
"text": "And like above if we try to store Multi-character literal as char then only the last character gets stored."
},
{
"code": null,
"e": 5415,
"s": 5411,
"text": "C++"
},
{
"code": "#include <iostream>using namespace std; // Driver codeint main(){ char c = 'abcd'; // stores as, c = ' d ' cout << c << endl; return 0;}",
"e": 5569,
"s": 5415,
"text": null
},
{
"code": null,
"e": 5577,
"s": 5569,
"text": "Output:"
},
{
"code": null,
"e": 5717,
"s": 5577,
"text": "Here we can see that the Multi-character literal which is a 4-byte integer is converting to 1-byte char and only stored the last character."
},
{
"code": null,
"e": 5892,
"s": 5717,
"text": "Good thing about multi-character literals: As multi-character literals are store as int, it can be used for comparison and in switch-case where strings are not used normally."
},
{
"code": null,
"e": 5896,
"s": 5892,
"text": "C++"
},
{
"code": "#include <iostream>using namespace std; // Driver codeint main(){ int s = 'abcd'; switch (s) { case 'abcd': cout << ('abcd' == 'abcd'); // s = 1633837924 and 'abcd' // = 1633837924 so, value of // s is equal to 'abcd' } return 0;}",
"e": 6177,
"s": 5896,
"text": null
},
{
"code": null,
"e": 6185,
"s": 6177,
"text": "Output:"
},
{
"code": null,
"e": 6225,
"s": 6185,
"text": "Problems with multi-character literals:"
},
{
"code": null,
"e": 6324,
"s": 6225,
"text": "In C++, multi-character literals are conditionally-supported. Thus, your code may fail to compile."
},
{
"code": null,
"e": 6481,
"s": 6324,
"text": "They are supported, but they have implementation-defined value. If the code runs on your machine fine that does not guarantee it will run on other machines."
},
{
"code": null,
"e": 6606,
"s": 6481,
"text": "Also, it is possible that the implementation chooses to assign all multi-character literals the value 0, breaking your code."
},
{
"code": null,
"e": 6617,
"s": 6606,
"text": "C Language"
},
{
"code": null,
"e": 6621,
"s": 6617,
"text": "C++"
},
{
"code": null,
"e": 6625,
"s": 6621,
"text": "CPP"
},
{
"code": null,
"e": 6723,
"s": 6625,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 6771,
"s": 6723,
"text": "Unordered Sets in C++ Standard Template Library"
},
{
"code": null,
"e": 6792,
"s": 6771,
"text": "Operators in C / C++"
},
{
"code": null,
"e": 6818,
"s": 6792,
"text": "Exception Handling in C++"
},
{
"code": null,
"e": 6863,
"s": 6818,
"text": "What is the purpose of a function prototype?"
},
{
"code": null,
"e": 6929,
"s": 6863,
"text": "Sorting Vector of Pairs in C++ | Set 1 (Sort by first and second)"
},
{
"code": null,
"e": 6947,
"s": 6929,
"text": "Vector in C++ STL"
},
{
"code": null,
"e": 6990,
"s": 6947,
"text": "Map in C++ Standard Template Library (STL)"
},
{
"code": null,
"e": 7036,
"s": 6990,
"text": "Initialize a vector in C++ (7 different ways)"
},
{
"code": null,
"e": 7079,
"s": 7036,
"text": "Set in C++ Standard Template Library (STL)"
}
] |
Stack in Python | 08 Jul, 2022
A stack is a linear data structure that stores items in a Last-In/First-Out (LIFO) or First-In/Last-Out (FILO) manner. In stack, a new element is added at one end and an element is removed from that end only. The insert and delete operations are often called push and pop.
The functions associated with stack are:
empty() – Returns whether the stack is empty – Time Complexity: O(1)
size() – Returns the size of the stack – Time Complexity: O(1)
top() / peek() – Returns a reference to the topmost element of the stack – Time Complexity: O(1)
push(a) – Inserts the element ‘a’ at the top of the stack – Time Complexity: O(1)
pop() – Deletes the topmost element of the stack – Time Complexity: O(1)
There are various ways from which a stack can be implemented in Python. This article covers the implementation of a stack using data structures and modules from the Python library. Stack in Python can be implemented using the following ways:
list
Collections.deque
queue.LifoQueue
Python’s built-in data structure list can be used as a stack. Instead of push(), append() is used to add elements to the top of the stack while pop() removes the element in LIFO order. Unfortunately, the list has a few shortcomings. The biggest issue is that it can run into speed issues as it grows. The items in the list are stored next to each other in memory, if the stack grows bigger than the block of memory that currently holds it, then Python needs to do some memory allocations. This can lead to some append() calls taking much longer than other ones.
Python3
# Python program to# demonstrate stack implementation# using list stack = [] # append() function to push# element in the stackstack.append('a')stack.append('b')stack.append('c') print('Initial stack')print(stack) # pop() function to pop# element from stack in# LIFO orderprint('\nElements popped from stack:')print(stack.pop())print(stack.pop())print(stack.pop()) print('\nStack after elements are popped:')print(stack) # uncommenting print(stack.pop())# will cause an IndexError# as the stack is now empty
Output:
Initial stack
['a', 'b', 'c']
Elements popped from stack:
c
b
a
Stack after elements are popped:
[]
Traceback (most recent call last):
File "/home/2426bc32be6a59881fde0eec91247623.py", line 25, in <module>
print(stack.pop())
IndexError: pop from empty list
Python stack can be implemented using the deque class from the collections module. Deque is preferred over the list in the cases where we need quicker append and pop operations from both the ends of the container, as deque provides an O(1) time complexity for append and pop operations as compared to list which provides O(n) time complexity.
The same methods on deque as seen in the list are used, append() and pop().
Python3
# Python program to# demonstrate stack implementation# using collections.deque from collections import deque stack = deque() # append() function to push# element in the stackstack.append('a')stack.append('b')stack.append('c') print('Initial stack:')print(stack) # pop() function to pop# element from stack in# LIFO orderprint('\nElements popped from stack:')print(stack.pop())print(stack.pop())print(stack.pop()) print('\nStack after elements are popped:')print(stack) # uncommenting print(stack.pop())# will cause an IndexError# as the stack is now empty
Output:
Initial stack:
deque(['a', 'b', 'c'])
Elements popped from stack:
c
b
a
Stack after elements are popped:
deque([])
Traceback (most recent call last):
File "/home/97171a8f6fead6988ea96f86e4b01c32.py", line 29, in <module>
print(stack.pop())
IndexError: pop from an empty deque
Queue module also has a LIFO Queue, which is basically a Stack. Data is inserted into Queue using the put() function and get() takes data out from the Queue.
There are various functions available in this module:
maxsize – Number of items allowed in the queue.
empty() – Return True if the queue is empty, False otherwise.
full() – Return True if there are maxsize items in the queue. If the queue was initialized with maxsize=0 (the default), then full() never returns True.
get() – Remove and return an item from the queue. If the queue is empty, wait until an item is available.
get_nowait() – Return an item if one is immediately available, else raise QueueEmpty.
put(item) – Put an item into the queue. If the queue is full, wait until a free slot is available before adding the item.
put_nowait(item) – Put an item into the queue without blocking. If no free slot is immediately available, raise QueueFull.
qsize() – Return the number of items in the queue.
Python3
# Python program to# demonstrate stack implementation# using queue module from queue import LifoQueue # Initializing a stackstack = LifoQueue(maxsize=3) # qsize() show the number of elements# in the stackprint(stack.qsize()) # put() function to push# element in the stackstack.put('a')stack.put('b')stack.put('c') print("Full: ", stack.full())print("Size: ", stack.qsize()) # get() function to pop# element from stack in# LIFO orderprint('\nElements popped from the stack')print(stack.get())print(stack.get())print(stack.get()) print("\nEmpty: ", stack.empty())
Output:
0
Full: True
Size: 3
Elements popped from the stack
c
b
a
Empty: True
The linked list has two methods addHead(item) and removeHead() that run in constant time. These two methods are suitable to implement a stack.
getSize()– Get the number of items in the stack.
isEmpty() – Return True if the stack is empty, False otherwise.
peek() – Return the top item in the stack. If the stack is empty, raise an exception.
push(value) – Push a value into the head of the stack.
pop() – Remove and return a value in the head of the stack. If the stack is empty, raise an exception.
Below is the implementation of the above approach:
Python3
# Python program to demonstrate# stack implementation using a linked list.# node class class Node: def __init__(self, value): self.value = value self.next = None class Stack: # Initializing a stack. # Use a dummy node, which is # easier for handling edge cases. def __init__(self): self.head = Node("head") self.size = 0 # String representation of the stack def __str__(self): cur = self.head.next out = "" while cur: out += str(cur.value) + "->" cur = cur.next return out[:-3] # Get the current size of the stack def getSize(self): return self.size # Check if the stack is empty def isEmpty(self): return self.size == 0 # Get the top item of the stack def peek(self): # Sanitary check to see if we # are peeking an empty stack. if self.isEmpty(): raise Exception("Peeking from an empty stack") return self.head.next.value # Push a value into the stack. def push(self, value): node = Node(value) node.next = self.head.next self.head.next = node self.size += 1 # Remove a value from the stack and return. def pop(self): if self.isEmpty(): raise Exception("Popping from an empty stack") remove = self.head.next self.head.next = self.head.next.next self.size -= 1 return remove.value # Driver Codeif __name__ == "__main__": stack = Stack() for i in range(1, 11): stack.push(i) print(f"Stack: {stack}") for _ in range(1, 6): remove = stack.pop() print(f"Pop: {remove}") print(f"Stack: {stack}")
Output:
Stack: 10 -> 9 -> 8 -> 7 -> 6 -> 5 -> 4 -> 3 -> 2 -> 1
Pop: 10
Pop: 9
Pop: 8
Pop: 7
Pop: 6
Stack: 5 -> 4 -> 3 -> 2 -> 1
nidhi_biet
duybao200300
saransh_codes
arorakashish0911
noonecares907
abhinav8970
harsh khanna
Python-Data-Structures
Python
Stack
Stack
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python Dictionary
Different ways to create Pandas Dataframe
Enumerate() in Python
Read a file line by line in Python
Python String | replace()
Stack Data Structure (Introduction and Program)
Stack Class in Java
Check for Balanced Brackets in an expression (well-formedness) using Stack
Introduction to Data Structures
Queue using Stacks | [
{
"code": null,
"e": 52,
"s": 24,
"text": "\n08 Jul, 2022"
},
{
"code": null,
"e": 325,
"s": 52,
"text": "A stack is a linear data structure that stores items in a Last-In/First-Out (LIFO) or First-In/Last-Out (FILO) manner. In stack, a new element is added at one end and an element is removed from that end only. The insert and delete operations are often called push and pop."
},
{
"code": null,
"e": 366,
"s": 325,
"text": "The functions associated with stack are:"
},
{
"code": null,
"e": 435,
"s": 366,
"text": "empty() – Returns whether the stack is empty – Time Complexity: O(1)"
},
{
"code": null,
"e": 498,
"s": 435,
"text": "size() – Returns the size of the stack – Time Complexity: O(1)"
},
{
"code": null,
"e": 595,
"s": 498,
"text": "top() / peek() – Returns a reference to the topmost element of the stack – Time Complexity: O(1)"
},
{
"code": null,
"e": 677,
"s": 595,
"text": "push(a) – Inserts the element ‘a’ at the top of the stack – Time Complexity: O(1)"
},
{
"code": null,
"e": 750,
"s": 677,
"text": "pop() – Deletes the topmost element of the stack – Time Complexity: O(1)"
},
{
"code": null,
"e": 993,
"s": 750,
"text": "There are various ways from which a stack can be implemented in Python. This article covers the implementation of a stack using data structures and modules from the Python library. Stack in Python can be implemented using the following ways: "
},
{
"code": null,
"e": 998,
"s": 993,
"text": "list"
},
{
"code": null,
"e": 1016,
"s": 998,
"text": "Collections.deque"
},
{
"code": null,
"e": 1032,
"s": 1016,
"text": "queue.LifoQueue"
},
{
"code": null,
"e": 1594,
"s": 1032,
"text": "Python’s built-in data structure list can be used as a stack. Instead of push(), append() is used to add elements to the top of the stack while pop() removes the element in LIFO order. Unfortunately, the list has a few shortcomings. The biggest issue is that it can run into speed issues as it grows. The items in the list are stored next to each other in memory, if the stack grows bigger than the block of memory that currently holds it, then Python needs to do some memory allocations. This can lead to some append() calls taking much longer than other ones."
},
{
"code": null,
"e": 1602,
"s": 1594,
"text": "Python3"
},
{
"code": "# Python program to# demonstrate stack implementation# using list stack = [] # append() function to push# element in the stackstack.append('a')stack.append('b')stack.append('c') print('Initial stack')print(stack) # pop() function to pop# element from stack in# LIFO orderprint('\\nElements popped from stack:')print(stack.pop())print(stack.pop())print(stack.pop()) print('\\nStack after elements are popped:')print(stack) # uncommenting print(stack.pop())# will cause an IndexError# as the stack is now empty",
"e": 2115,
"s": 1602,
"text": null
},
{
"code": null,
"e": 2124,
"s": 2115,
"text": "Output: "
},
{
"code": null,
"e": 2226,
"s": 2124,
"text": "Initial stack\n['a', 'b', 'c']\n\nElements popped from stack:\nc\nb\na\n\nStack after elements are popped:\n[]"
},
{
"code": null,
"e": 2391,
"s": 2226,
"text": "Traceback (most recent call last):\n File \"/home/2426bc32be6a59881fde0eec91247623.py\", line 25, in <module>\n print(stack.pop()) \nIndexError: pop from empty list"
},
{
"code": null,
"e": 2735,
"s": 2391,
"text": "Python stack can be implemented using the deque class from the collections module. Deque is preferred over the list in the cases where we need quicker append and pop operations from both the ends of the container, as deque provides an O(1) time complexity for append and pop operations as compared to list which provides O(n) time complexity. "
},
{
"code": null,
"e": 2811,
"s": 2735,
"text": "The same methods on deque as seen in the list are used, append() and pop()."
},
{
"code": null,
"e": 2819,
"s": 2811,
"text": "Python3"
},
{
"code": "# Python program to# demonstrate stack implementation# using collections.deque from collections import deque stack = deque() # append() function to push# element in the stackstack.append('a')stack.append('b')stack.append('c') print('Initial stack:')print(stack) # pop() function to pop# element from stack in# LIFO orderprint('\\nElements popped from stack:')print(stack.pop())print(stack.pop())print(stack.pop()) print('\\nStack after elements are popped:')print(stack) # uncommenting print(stack.pop())# will cause an IndexError# as the stack is now empty",
"e": 3382,
"s": 2819,
"text": null
},
{
"code": null,
"e": 3391,
"s": 3382,
"text": "Output: "
},
{
"code": null,
"e": 3508,
"s": 3391,
"text": "Initial stack:\ndeque(['a', 'b', 'c'])\n\nElements popped from stack:\nc\nb\na\n\nStack after elements are popped:\ndeque([])"
},
{
"code": null,
"e": 3677,
"s": 3508,
"text": "Traceback (most recent call last):\n File \"/home/97171a8f6fead6988ea96f86e4b01c32.py\", line 29, in <module>\n print(stack.pop()) \nIndexError: pop from an empty deque"
},
{
"code": null,
"e": 3836,
"s": 3677,
"text": "Queue module also has a LIFO Queue, which is basically a Stack. Data is inserted into Queue using the put() function and get() takes data out from the Queue. "
},
{
"code": null,
"e": 3891,
"s": 3836,
"text": "There are various functions available in this module: "
},
{
"code": null,
"e": 3939,
"s": 3891,
"text": "maxsize – Number of items allowed in the queue."
},
{
"code": null,
"e": 4001,
"s": 3939,
"text": "empty() – Return True if the queue is empty, False otherwise."
},
{
"code": null,
"e": 4154,
"s": 4001,
"text": "full() – Return True if there are maxsize items in the queue. If the queue was initialized with maxsize=0 (the default), then full() never returns True."
},
{
"code": null,
"e": 4260,
"s": 4154,
"text": "get() – Remove and return an item from the queue. If the queue is empty, wait until an item is available."
},
{
"code": null,
"e": 4346,
"s": 4260,
"text": "get_nowait() – Return an item if one is immediately available, else raise QueueEmpty."
},
{
"code": null,
"e": 4468,
"s": 4346,
"text": "put(item) – Put an item into the queue. If the queue is full, wait until a free slot is available before adding the item."
},
{
"code": null,
"e": 4591,
"s": 4468,
"text": "put_nowait(item) – Put an item into the queue without blocking. If no free slot is immediately available, raise QueueFull."
},
{
"code": null,
"e": 4642,
"s": 4591,
"text": "qsize() – Return the number of items in the queue."
},
{
"code": null,
"e": 4650,
"s": 4642,
"text": "Python3"
},
{
"code": "# Python program to# demonstrate stack implementation# using queue module from queue import LifoQueue # Initializing a stackstack = LifoQueue(maxsize=3) # qsize() show the number of elements# in the stackprint(stack.qsize()) # put() function to push# element in the stackstack.put('a')stack.put('b')stack.put('c') print(\"Full: \", stack.full())print(\"Size: \", stack.qsize()) # get() function to pop# element from stack in# LIFO orderprint('\\nElements popped from the stack')print(stack.get())print(stack.get())print(stack.get()) print(\"\\nEmpty: \", stack.empty())",
"e": 5219,
"s": 4650,
"text": null
},
{
"code": null,
"e": 5228,
"s": 5219,
"text": "Output: "
},
{
"code": null,
"e": 5303,
"s": 5228,
"text": "0\nFull: True\nSize: 3\n\nElements popped from the stack\nc\nb\na\n\nEmpty: True"
},
{
"code": null,
"e": 5447,
"s": 5303,
"text": "The linked list has two methods addHead(item) and removeHead() that run in constant time. These two methods are suitable to implement a stack. "
},
{
"code": null,
"e": 5496,
"s": 5447,
"text": "getSize()– Get the number of items in the stack."
},
{
"code": null,
"e": 5560,
"s": 5496,
"text": "isEmpty() – Return True if the stack is empty, False otherwise."
},
{
"code": null,
"e": 5646,
"s": 5560,
"text": "peek() – Return the top item in the stack. If the stack is empty, raise an exception."
},
{
"code": null,
"e": 5701,
"s": 5646,
"text": "push(value) – Push a value into the head of the stack."
},
{
"code": null,
"e": 5804,
"s": 5701,
"text": "pop() – Remove and return a value in the head of the stack. If the stack is empty, raise an exception."
},
{
"code": null,
"e": 5855,
"s": 5804,
"text": "Below is the implementation of the above approach:"
},
{
"code": null,
"e": 5863,
"s": 5855,
"text": "Python3"
},
{
"code": "# Python program to demonstrate# stack implementation using a linked list.# node class class Node: def __init__(self, value): self.value = value self.next = None class Stack: # Initializing a stack. # Use a dummy node, which is # easier for handling edge cases. def __init__(self): self.head = Node(\"head\") self.size = 0 # String representation of the stack def __str__(self): cur = self.head.next out = \"\" while cur: out += str(cur.value) + \"->\" cur = cur.next return out[:-3] # Get the current size of the stack def getSize(self): return self.size # Check if the stack is empty def isEmpty(self): return self.size == 0 # Get the top item of the stack def peek(self): # Sanitary check to see if we # are peeking an empty stack. if self.isEmpty(): raise Exception(\"Peeking from an empty stack\") return self.head.next.value # Push a value into the stack. def push(self, value): node = Node(value) node.next = self.head.next self.head.next = node self.size += 1 # Remove a value from the stack and return. def pop(self): if self.isEmpty(): raise Exception(\"Popping from an empty stack\") remove = self.head.next self.head.next = self.head.next.next self.size -= 1 return remove.value # Driver Codeif __name__ == \"__main__\": stack = Stack() for i in range(1, 11): stack.push(i) print(f\"Stack: {stack}\") for _ in range(1, 6): remove = stack.pop() print(f\"Pop: {remove}\") print(f\"Stack: {stack}\")",
"e": 7571,
"s": 5863,
"text": null
},
{
"code": null,
"e": 7580,
"s": 7571,
"text": "Output: "
},
{
"code": null,
"e": 7702,
"s": 7580,
"text": "Stack: 10 -> 9 -> 8 -> 7 -> 6 -> 5 -> 4 -> 3 -> 2 -> 1\n\nPop: 10\nPop: 9\nPop: 8\nPop: 7\nPop: 6\n\nStack: 5 -> 4 -> 3 -> 2 -> 1"
},
{
"code": null,
"e": 7713,
"s": 7702,
"text": "nidhi_biet"
},
{
"code": null,
"e": 7726,
"s": 7713,
"text": "duybao200300"
},
{
"code": null,
"e": 7740,
"s": 7726,
"text": "saransh_codes"
},
{
"code": null,
"e": 7757,
"s": 7740,
"text": "arorakashish0911"
},
{
"code": null,
"e": 7771,
"s": 7757,
"text": "noonecares907"
},
{
"code": null,
"e": 7783,
"s": 7771,
"text": "abhinav8970"
},
{
"code": null,
"e": 7796,
"s": 7783,
"text": "harsh khanna"
},
{
"code": null,
"e": 7819,
"s": 7796,
"text": "Python-Data-Structures"
},
{
"code": null,
"e": 7826,
"s": 7819,
"text": "Python"
},
{
"code": null,
"e": 7832,
"s": 7826,
"text": "Stack"
},
{
"code": null,
"e": 7838,
"s": 7832,
"text": "Stack"
},
{
"code": null,
"e": 7936,
"s": 7838,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 7954,
"s": 7936,
"text": "Python Dictionary"
},
{
"code": null,
"e": 7996,
"s": 7954,
"text": "Different ways to create Pandas Dataframe"
},
{
"code": null,
"e": 8018,
"s": 7996,
"text": "Enumerate() in Python"
},
{
"code": null,
"e": 8053,
"s": 8018,
"text": "Read a file line by line in Python"
},
{
"code": null,
"e": 8079,
"s": 8053,
"text": "Python String | replace()"
},
{
"code": null,
"e": 8127,
"s": 8079,
"text": "Stack Data Structure (Introduction and Program)"
},
{
"code": null,
"e": 8147,
"s": 8127,
"text": "Stack Class in Java"
},
{
"code": null,
"e": 8222,
"s": 8147,
"text": "Check for Balanced Brackets in an expression (well-formedness) using Stack"
},
{
"code": null,
"e": 8254,
"s": 8222,
"text": "Introduction to Data Structures"
}
] |
Python – Extract values of Particular Key in Nested Values | 01 Aug, 2020
Given a dictionary with nested dictionaries as values, extract all the values with of particular key.
Input : test_dict = {‘Gfg’ : {“a” : 7, “b” : 9, “c” : 12}, ‘is’ : {“a” : 15, “b” : 19, “c” : 20}, ‘best’ :{“a” : 5, “b” : 10, “c” : 2}}, temp = “b”Output : [9, 10, 19]Explanation : All values of “b” key are extracted.
Input : test_dict = {‘Gfg’ : {“a” : 7, “b” : 9, “c” : 12}, ‘is’ : {“a” : 15, “b” : 19, “c” : 20}, ‘best’ :{“a” : 5, “b” : 10, “c” : 2}}, temp = “a”Output : [7, 15, 5]Explanation : All values of “a” key are extracted.
Method #1 : Using list comprehension + items()
This is one of the ways in which this task can be performed. In this, we use list comprehension to perform the task of extracting particular key and items() is used to get all the items().
Python3
# Python3 code to demonstrate working of # Extract values of Particular Key in Nested Values# Using list comprehension # initializing dictionarytest_dict = {'Gfg' : {"a" : 7, "b" : 9, "c" : 12}, 'is' : {"a" : 15, "b" : 19, "c" : 20}, 'best' :{"a" : 5, "b" : 10, "c" : 2}} # printing original dictionaryprint("The original dictionary is : " + str(test_dict)) # initializing keytemp = "c" # using item() to extract key value pair as wholeres = [val[temp] for key, val in test_dict.items() if temp in val] # printing result print("The extracted values : " + str(res))
The original dictionary is : {'Gfg': {'a': 7, 'b': 9, 'c': 12}, 'is': {'a': 15, 'b': 19, 'c': 20}, 'best': {'a': 5, 'b': 10, 'c': 2}}
The extracted values : [12, 20, 2]
Method #2 : Using list comprehension + values() + keys()
The combination of above functions can be used to solve this problem. In this, we use values() and keys() to get values and keys separately rather than at once extracted using items().
Python3
# Python3 code to demonstrate working of # Extract values of Particular Key in Nested Values# Using list comprehension + values() + keys() # initializing dictionarytest_dict = {'Gfg' : {"a" : 7, "b" : 9, "c" : 12}, 'is' : {"a" : 15, "b" : 19, "c" : 20}, 'best' :{"a" : 5, "b" : 10, "c" : 2}} # printing original dictionaryprint("The original dictionary is : " + str(test_dict)) # initializing keytemp = "c" # using keys() and values() to extract valuesres = [sub[temp] for sub in test_dict.values() if temp in sub.keys()] # printing result print("The extracted values : " + str(res))
The original dictionary is : {'Gfg': {'a': 7, 'b': 9, 'c': 12}, 'is': {'a': 15, 'b': 19, 'c': 20}, 'best': {'a': 5, 'b': 10, 'c': 2}}
The extracted values : [12, 20, 2]
Python dictionary-programs
Python list-programs
Python
Python Programs
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python Dictionary
Different ways to create Pandas Dataframe
Enumerate() in Python
Read a file line by line in Python
Python String | replace()
Python program to convert a list to string
Defaultdict in Python
Python | Convert a list to dictionary
Python | Convert string dictionary to dictionary
Python Program for Fibonacci numbers | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n01 Aug, 2020"
},
{
"code": null,
"e": 130,
"s": 28,
"text": "Given a dictionary with nested dictionaries as values, extract all the values with of particular key."
},
{
"code": null,
"e": 348,
"s": 130,
"text": "Input : test_dict = {‘Gfg’ : {“a” : 7, “b” : 9, “c” : 12}, ‘is’ : {“a” : 15, “b” : 19, “c” : 20}, ‘best’ :{“a” : 5, “b” : 10, “c” : 2}}, temp = “b”Output : [9, 10, 19]Explanation : All values of “b” key are extracted."
},
{
"code": null,
"e": 565,
"s": 348,
"text": "Input : test_dict = {‘Gfg’ : {“a” : 7, “b” : 9, “c” : 12}, ‘is’ : {“a” : 15, “b” : 19, “c” : 20}, ‘best’ :{“a” : 5, “b” : 10, “c” : 2}}, temp = “a”Output : [7, 15, 5]Explanation : All values of “a” key are extracted."
},
{
"code": null,
"e": 612,
"s": 565,
"text": "Method #1 : Using list comprehension + items()"
},
{
"code": null,
"e": 801,
"s": 612,
"text": "This is one of the ways in which this task can be performed. In this, we use list comprehension to perform the task of extracting particular key and items() is used to get all the items()."
},
{
"code": null,
"e": 809,
"s": 801,
"text": "Python3"
},
{
"code": "# Python3 code to demonstrate working of # Extract values of Particular Key in Nested Values# Using list comprehension # initializing dictionarytest_dict = {'Gfg' : {\"a\" : 7, \"b\" : 9, \"c\" : 12}, 'is' : {\"a\" : 15, \"b\" : 19, \"c\" : 20}, 'best' :{\"a\" : 5, \"b\" : 10, \"c\" : 2}} # printing original dictionaryprint(\"The original dictionary is : \" + str(test_dict)) # initializing keytemp = \"c\" # using item() to extract key value pair as wholeres = [val[temp] for key, val in test_dict.items() if temp in val] # printing result print(\"The extracted values : \" + str(res)) ",
"e": 1405,
"s": 809,
"text": null
},
{
"code": null,
"e": 1575,
"s": 1405,
"text": "The original dictionary is : {'Gfg': {'a': 7, 'b': 9, 'c': 12}, 'is': {'a': 15, 'b': 19, 'c': 20}, 'best': {'a': 5, 'b': 10, 'c': 2}}\nThe extracted values : [12, 20, 2]\n"
},
{
"code": null,
"e": 1633,
"s": 1575,
"text": "Method #2 : Using list comprehension + values() + keys() "
},
{
"code": null,
"e": 1818,
"s": 1633,
"text": "The combination of above functions can be used to solve this problem. In this, we use values() and keys() to get values and keys separately rather than at once extracted using items()."
},
{
"code": null,
"e": 1826,
"s": 1818,
"text": "Python3"
},
{
"code": "# Python3 code to demonstrate working of # Extract values of Particular Key in Nested Values# Using list comprehension + values() + keys() # initializing dictionarytest_dict = {'Gfg' : {\"a\" : 7, \"b\" : 9, \"c\" : 12}, 'is' : {\"a\" : 15, \"b\" : 19, \"c\" : 20}, 'best' :{\"a\" : 5, \"b\" : 10, \"c\" : 2}} # printing original dictionaryprint(\"The original dictionary is : \" + str(test_dict)) # initializing keytemp = \"c\" # using keys() and values() to extract valuesres = [sub[temp] for sub in test_dict.values() if temp in sub.keys()] # printing result print(\"The extracted values : \" + str(res)) ",
"e": 2442,
"s": 1826,
"text": null
},
{
"code": null,
"e": 2612,
"s": 2442,
"text": "The original dictionary is : {'Gfg': {'a': 7, 'b': 9, 'c': 12}, 'is': {'a': 15, 'b': 19, 'c': 20}, 'best': {'a': 5, 'b': 10, 'c': 2}}\nThe extracted values : [12, 20, 2]\n"
},
{
"code": null,
"e": 2639,
"s": 2612,
"text": "Python dictionary-programs"
},
{
"code": null,
"e": 2660,
"s": 2639,
"text": "Python list-programs"
},
{
"code": null,
"e": 2667,
"s": 2660,
"text": "Python"
},
{
"code": null,
"e": 2683,
"s": 2667,
"text": "Python Programs"
},
{
"code": null,
"e": 2781,
"s": 2683,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 2799,
"s": 2781,
"text": "Python Dictionary"
},
{
"code": null,
"e": 2841,
"s": 2799,
"text": "Different ways to create Pandas Dataframe"
},
{
"code": null,
"e": 2863,
"s": 2841,
"text": "Enumerate() in Python"
},
{
"code": null,
"e": 2898,
"s": 2863,
"text": "Read a file line by line in Python"
},
{
"code": null,
"e": 2924,
"s": 2898,
"text": "Python String | replace()"
},
{
"code": null,
"e": 2967,
"s": 2924,
"text": "Python program to convert a list to string"
},
{
"code": null,
"e": 2989,
"s": 2967,
"text": "Defaultdict in Python"
},
{
"code": null,
"e": 3027,
"s": 2989,
"text": "Python | Convert a list to dictionary"
},
{
"code": null,
"e": 3076,
"s": 3027,
"text": "Python | Convert string dictionary to dictionary"
}
] |
Python EasyGUI module – Introduction | 09 Jun, 2021
EasyGUI is a module for very simple, very easy GUI programming in Python. EasyGUI is different from other GUI generators in that EasyGUI is NOT event-driven. Instead, all GUI interactions are invoked by simple function calls. Unlike other complicated GUI’s EasyGUI is the simplest GUI till now.
Install using this command:
pip install easygui
Note : It is not recommended to run EasyGui on IDLE as EasyGui runs on Tkinter and has its own event loop, and IDLE is also an application written by Tkinter module and also it has its own event loop. So when both are run at the same time, conflicts can occur and unpredictable results can occur. So it is preferred to run EasyGui out side the IDLE.
Importing EasyGUI
from easygui import *
It is the best way to use all the widgets without extra reference.
Example : In this we will create a window having a short message and a press button which when pressed closes our message box, below is the implementation
Python3
# importing easygui modulefrom easygui import * # title of our windowtitle = "GfG-EasyGUI" # message for our windowmsg = "GeeksforGeeks, Hello World from EasyGUI" # button message by default it is "OK"button = "Let's Go" # creating a message boxmsgbox(msg, title, button )
Output :
"Let's Go"
Another Example: In this we will allow user to choose the “geek form” and when ans is selected it will get printed, below is the implementation
Python3
# importing easygui modulefrom easygui import * # choices which user can selectchoices = ["Geek", "Super Geek", "Super Geek 2", "Super Geek God"] # message / question to be askedmsg = "Select any one option" # opening a choice box using our msg and choicesreply = choicebox(msg, choices = choices) # printing the selected optionprint("You selected : ", end = "")print(reply)
Output :
You selected : Super Geek God
saurabh1990aror
Python-EasyGUI
Python-gui
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python Dictionary
Different ways to create Pandas Dataframe
Enumerate() in Python
Read a file line by line in Python
Python String | replace()
How to Install PIP on Windows ?
*args and **kwargs in Python
Python Classes and Objects
Iterate over a list in Python
Convert integer to string in Python | [
{
"code": null,
"e": 54,
"s": 26,
"text": "\n09 Jun, 2021"
},
{
"code": null,
"e": 349,
"s": 54,
"text": "EasyGUI is a module for very simple, very easy GUI programming in Python. EasyGUI is different from other GUI generators in that EasyGUI is NOT event-driven. Instead, all GUI interactions are invoked by simple function calls. Unlike other complicated GUI’s EasyGUI is the simplest GUI till now."
},
{
"code": null,
"e": 378,
"s": 349,
"text": "Install using this command: "
},
{
"code": null,
"e": 398,
"s": 378,
"text": "pip install easygui"
},
{
"code": null,
"e": 748,
"s": 398,
"text": "Note : It is not recommended to run EasyGui on IDLE as EasyGui runs on Tkinter and has its own event loop, and IDLE is also an application written by Tkinter module and also it has its own event loop. So when both are run at the same time, conflicts can occur and unpredictable results can occur. So it is preferred to run EasyGui out side the IDLE."
},
{
"code": null,
"e": 768,
"s": 748,
"text": "Importing EasyGUI "
},
{
"code": null,
"e": 790,
"s": 768,
"text": "from easygui import *"
},
{
"code": null,
"e": 857,
"s": 790,
"text": "It is the best way to use all the widgets without extra reference."
},
{
"code": null,
"e": 1013,
"s": 857,
"text": "Example : In this we will create a window having a short message and a press button which when pressed closes our message box, below is the implementation "
},
{
"code": null,
"e": 1021,
"s": 1013,
"text": "Python3"
},
{
"code": "# importing easygui modulefrom easygui import * # title of our windowtitle = \"GfG-EasyGUI\" # message for our windowmsg = \"GeeksforGeeks, Hello World from EasyGUI\" # button message by default it is \"OK\"button = \"Let's Go\" # creating a message boxmsgbox(msg, title, button )",
"e": 1294,
"s": 1021,
"text": null
},
{
"code": null,
"e": 1304,
"s": 1294,
"text": "Output : "
},
{
"code": null,
"e": 1315,
"s": 1304,
"text": "\"Let's Go\""
},
{
"code": null,
"e": 1460,
"s": 1315,
"text": "Another Example: In this we will allow user to choose the “geek form” and when ans is selected it will get printed, below is the implementation "
},
{
"code": null,
"e": 1468,
"s": 1460,
"text": "Python3"
},
{
"code": "# importing easygui modulefrom easygui import * # choices which user can selectchoices = [\"Geek\", \"Super Geek\", \"Super Geek 2\", \"Super Geek God\"] # message / question to be askedmsg = \"Select any one option\" # opening a choice box using our msg and choicesreply = choicebox(msg, choices = choices) # printing the selected optionprint(\"You selected : \", end = \"\")print(reply)",
"e": 1843,
"s": 1468,
"text": null
},
{
"code": null,
"e": 1854,
"s": 1843,
"text": "Output : "
},
{
"code": null,
"e": 1884,
"s": 1854,
"text": "You selected : Super Geek God"
},
{
"code": null,
"e": 1902,
"s": 1886,
"text": "saurabh1990aror"
},
{
"code": null,
"e": 1917,
"s": 1902,
"text": "Python-EasyGUI"
},
{
"code": null,
"e": 1928,
"s": 1917,
"text": "Python-gui"
},
{
"code": null,
"e": 1935,
"s": 1928,
"text": "Python"
},
{
"code": null,
"e": 2033,
"s": 1935,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 2051,
"s": 2033,
"text": "Python Dictionary"
},
{
"code": null,
"e": 2093,
"s": 2051,
"text": "Different ways to create Pandas Dataframe"
},
{
"code": null,
"e": 2115,
"s": 2093,
"text": "Enumerate() in Python"
},
{
"code": null,
"e": 2150,
"s": 2115,
"text": "Read a file line by line in Python"
},
{
"code": null,
"e": 2176,
"s": 2150,
"text": "Python String | replace()"
},
{
"code": null,
"e": 2208,
"s": 2176,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 2237,
"s": 2208,
"text": "*args and **kwargs in Python"
},
{
"code": null,
"e": 2264,
"s": 2237,
"text": "Python Classes and Objects"
},
{
"code": null,
"e": 2294,
"s": 2264,
"text": "Iterate over a list in Python"
}
] |
Object-Oriented Machine Learning Pipeline with mlflow for Pandas and Koalas DataFrames | by Yuefeng Zhang, PhD | Towards Data Science | In the article Python Data Preprocessing Using Pandas DataFrame, Spark DataFrame, and Koalas DataFrame, I used a public dataset to evaluate and compare the basic functionality of Pandas, Spark, and Koalas DataFrames in typical data preprocessing steps for machine learning. The main advantage of Koalas is that it supports an easy-to-use API similar to Pandas on Spark.
In this article, I use a more challenging dataset, the Interview Attendance Problem for Kaggle competition to demonstrate an end-to-end process of developing an Object-Oriented machine learning pipeline in Python for both Pandas and Koalas DataFrames using Pandas, Koalas, scikit-learn, and mlflow. This is achieved by:
Developing a data preprocessing pipeline using Pandas DataFrame with scikit-learn pipeline API
Developing a data preprocessing pipeline for Spark by combining scikit-learn pipeline API with Koalas DataFrame
Developing a machine learning pipeline by combining scikit-learn with mlflow
The end-to-end development process is based on the Cross-industry standard process for data mining. As shown in the diagram below, it consists of six major phases:
Business Understanding
Data Understanding
Data Preparation
Modeling
Evaluation
Deployment
Figure 1: CRISP-DM process diagram (refer to source in Wikipedia)
For convenience of discussion, it is assumed that the following Python libraries have been installed on a local machine such as Mac:
Anaconda (conda 4.7.10) with Python 3.6, Numpy, Pandas, Matplotlib, and Scikit-Learn
pyspark 2.4.4
Koalas
mlflow
The reason of using Python 3.6 is that certain functionality (e.g., deployment) of the current release of mlflow does not work with Python 3.7.
The first phase is business understanding. The key point in this phase is to understand the business problem to be solved. As an example, the following is a brief description of the Kaggle interview attendance problem:
Given a set of questions that are asked by a recruiter while scheduling an interview with a candidate, how to use the answers to those questions from the candidate to predict whether the expected attendance will attend a scheduled interview (yes, no, or uncertain).
Once the business problem is understood, the next step is to identify where (i.e., data sources) and how we should collect data from which a machine learning solution to the problem can be built.
The dataset for the Kaggle interview attendance problem has been collected from the recruitment industry in India by the researchers over a period of more than 2 years between September 2014 and January 2017.
This dataset is collected with labels (the column of Observed Attendance holds the labels) and thus it is suitable for supervised machine learning.
The following code imports the necessary Python libraries for all the source code in this article, and loads the dataset into a Koalas DataFrame and displays the first five rows of the DataFrame as shown in the table above.
import numpy as npimport pandas as pdimport databricks.koalas as ksimport matplotlib.pyplot as pltimport matplotlib as mplfrom datetime import datetimeimport osfrom sklearn.base import BaseEstimator, TransformerMixinfrom sklearn.pipeline import Pipelinefrom sklearn.externals import joblibimport mlflowimport mlflow.sklearnfrom sklearn.model_selection import train_test_splitfrom sklearn.ensemble import RandomForestClassifierfrom sklearn.model_selection import GridSearchCVfrom sklearn.metrics import make_scorerfrom sklearn.metrics import accuracy_scorefrom sklearn.metrics import f1_scorefrom sklearn.metrics import mean_squared_error, mean_absolute_error, r2_score%matplotlib inlineks_df = ks.read_csv('Interview_Attendance_Data.csv')ks_df.head()
The main goal of data preparation is to clean and transform a collected raw dataset into appropriate format so that the transformed data can be effectively consumed by a target machine learning model.
In the interview attendance raw dataset, the column of Name(Cand ID) contains candidate unique identifiers, which do not have much prediction power and thus can be dropped. In addition, all of the columns (i.e., columns from _c22 to _c26 for Koalas DataFrame, or columns from Unnamed: 22 to Unnamed: 26 for Pandas DataFrame) have no data and thus can safely be dropped as well.
Except for the date of interview, all of the other columns in the dataset have categorical (textual) values. In order to use machine learning to solve the problem, those categorical values must be transformed into numeric values because a machine learning model can only consume numeric data.
The column of Date of Interview should be split into day, month, and year to increase prediction power since the information of individual day, month, and year tends to be more strongly correlated with seasonable jobs compared with a string of date as a whole.
The columns of Nature of Skillset and Candidate Native location have a large number of unique entries. These will introduce a large number of new derived features after one-hot encoding. Too many features can lead to a curse of dimensionality problem in the case the size of dataset is not large enough. To alleviate such problem, the values of these two columns are redivided into a smaller number of buckets.
The above data preprocessing/transformation can be summarized as following steps:
Bucketing skillset
Bucketing candidate native location
Parsing interview date
Changing categorical values to uppercase and dropping less useful features
One-Hot Encoding categorical values
These steps are implemented by developing an Object-Oriented data preprocessing pipeline for both Pandas and Koalas DataFrames by combining Pandas and Koalas DataFrames with scikit-learn pipeline API (i.e., BaseEstimator, TransformerMixin, and Pipeline).
Several data preprocessing steps share a common operation of transforming the values of a particular column in a DataFrame. But, as described in Koalas Series, a Koalas Series does not support some of the common Pandas DataFrame and Series indexing mechanisms such as df.iloc[0]. Because of this, there is no simple method of traversing and changing the values of a column in a Koalas DataFrame.
The other difficulty is that Koalas does not allow to build a new Koalas Series object from scratch and then add it as a new column in an existing Koalas DataFrame. It only allows a new Koalas Series object that is built from the existing columns of a Koalas DataFrame.
The difficulties above are avoided by defining a global function to call the apply() method of a Koalas Series object.
def transformColumn(column_values, func, func_type): def transform_column(column_element) -> func_type: return func(column_element) cvalues = column_values cvalues = cvalues.apply(transform_column) return cvalues
To alleviate the curse of dimensionality issue, the transform() method of the BucketSkillset transformer class divides the unique values of the skillset column into smaller number of buckets by changing those values that appear less than 9 times as one same string value of Others.
class BucketSkillset(BaseEstimator, TransformerMixin): def __init__(self): self.skillset = ['JAVA/J2EE/Struts/Hibernate', 'Fresher', 'Accounting Operations', 'CDD KYC', 'Routine', 'Oracle', 'JAVA/SPRING/HIBERNATE/JSF', 'Java J2EE', 'SAS', 'Oracle Plsql', 'Java Developer', 'Lending and Liabilities', 'Banking Operations', 'Java', 'Core Java', 'Java J2ee', 'T-24 developer', 'Senior software engineer-Mednet', 'ALS Testing', 'SCCM', 'COTS Developer', 'Analytical R & D', 'Sr Automation Testing', 'Regulatory', 'Hadoop', 'testing', 'Java', 'ETL', 'Publishing'] def fit(self, X, y=None): return self def transform(self, X, y=None): func = lambda x: x if x in self.skillset else 'Others' X1 = X.copy() cname = 'Nature of Skillset' cvalue = X1[cname] if type(X1) == ks.DataFrame: cvalue = transformColumn(cvalue, func, str) X1[cname] = cvalue elif type(X1) == pd.DataFrame: X2 = map(func, cvalue) X1[cname] = pd.Series(X2) else: print('BucketSkillset: unsupported dataframe: {}'.format(type(X1))) pass return X1
Similarly to bucketing skillset, to alleviate the curse of dimensionality issue, the transform() method of the BucketLocation transformer class divides the unique values of the candidate native location column into smaller number of buckets by changing those values that appear less than 12 times into one same value of Others.
class BucketLocation(BaseEstimator, TransformerMixin): def __init__(self): self.candidate_locations = ['Chennai', 'Hyderabad', 'Bangalore', 'Gurgaon', 'Cuttack', 'Cochin', 'Pune', 'Coimbatore', 'Allahabad', 'Noida', 'Visakapatinam', 'Nagercoil', 'Trivandrum', 'Kolkata', 'Trichy', 'Vellore'] def fit(self, X, y=None): return self def transform(self, X, y=None): X1 = X.copy() func = lambda x: x if x in self.candidate_locations else 'Others' cname = 'Candidate Native location' cvalue = X1[cname] if type(X1) == ks.DataFrame: cvalue = transformColumn(cvalue, func, str) X1[cname] = cvalue elif type(X1) == pd.DataFrame: X2 = map(func, cvalue) X1[cname] = pd.Series(X2) else: print('BucketLocation: unsupported dataframe: {}'.format(type(X1))) pass return X1
The values of the column of Date of Interview are messy in that various formats are used. For instance not only different delimits are used to separate day, month, and year, but also different orders of day, month, and year are followed. This is handled by the _parseDate() and transform_date() methods of the ParseInterviewDate transformer class. The overall functionality of the transform() method is to separate the interview date string into values of individual day, month, and year.
class ParseInterviewDate(BaseEstimator, TransformerMixin): def __init__(self): pass def __parseDate(self, string, delimit): try: if ('&' in string): subs = tuple(string.split('&')) string = subs[0] except: print ('TypeError: {}'.format(string)) return None string = string.strip() try: d = datetime.strptime(string, '%d{0}%m{0}%Y'.format(delimit)) except: try: d = datetime.strptime(string, '%d{0}%m{0}%y'.format(delimit)) except: try: d = datetime.strptime(string, '%d{0}%b{0}%Y'.format(delimit)) except: try: d = datetime.strptime(string, '%d{0}%b{0}%y'.format(delimit)) except: try: d = datetime.strptime(string, '%b{0}%d{0}%Y'.format(delimit)) except: try: d = datetime.strptime(string, '%b{0}%d{0}%y'.format(delimit)) except: d = None return d def fit(self, X, y=None): return self def transform(self, X, y=None): def transform_date(ditem): if (isinstance(ditem, str) and len(ditem) > 0): if ('.' in ditem): d = self.__parseDate(ditem, '.') elif ('/' in ditem): d = self.__parseDate(ditem, '/') elif ('-' in ditem): d = self.__parseDate(ditem, '-') elif (' ' in ditem): d = self.__parseDate(ditem, ' ') else: d = None if (d is None): return 0, 0, 0 else: return d.day, d.month, d.year def get_day(column_element) -> int: try: day, month, year = transform_date(column_element) return int(day) except: return 0 def get_month(column_element) -> int: try: day, month, year = transform_date(column_element) return int(month) except: return 0 def get_year(column_element) -> int: try: day, month, year = transform_date(column_element) return int(year) except: return 0 def pandas_transform_date(X1): days = [] months = [] years = [] ditems = X1['Date of Interview'].values for ditem in ditems: if (isinstance(ditem, str) and len(ditem) > 0): if ('.' in ditem): d = self.__parseDate(ditem, '.') elif ('/' in ditem): d = self.__parseDate(ditem, '/') elif ('-' in ditem): d = self.__parseDate(ditem, '-') elif (' ' in ditem): d = self.__parseDate(ditem, ' ') else: d = None if (d is None): # print("{}, invalid format of interview date!".format(ditem)) days.append(0) # 0 - NaN months.append(0) years.append(0) else: days.append(d.day) months.append(d.month) years.append(d.year) else: days.append(0) months.append(0) years.append(0) X1['Year'] = years X1['Month'] = months X1['Day'] = days return X1 X1 = X.copy() if type(X1) == ks.DataFrame: X1['Year'] = X1['Date of Interview'] X1['Month'] = X1['Date of Interview'] X1['Day'] = X1['Date of Interview'] func_map = {'Year' : get_year, 'Month' : get_month, 'Day' : get_day} for cname in func_map: cvalue = X1[cname] cvalue = cvalue.apply(func_map[cname]) X1[cname] = cvalue elif type(X1) == pd.DataFrame: X1 = pandas_transform_date(X1) else: print('ParseInterviewDate: unsupported dataframe: {}'.format(type(X1))) pass return X1
The transform() method of the FeaturesUppercase transformer class is to change the values of categorical features to uppercase and at the same time drop less useful features.
class FeaturesUppercase(BaseEstimator, TransformerMixin): def __init__(self, feature_names, drop_feature_names): self.feature_names = feature_names self.drop_feature_names = drop_feature_names def fit(self, X, y=None): return self def transform(self, X, y=None): func = lambda x: x.strip().upper() X1 = X.copy() for fname in self.feature_names: values = X1[fname] values = values.fillna('NaN') if type(X1) == ks.DataFrame: values = transformColumn(values, func, str) elif type(X1) == pd.DataFrame: values = map(lambda x: x.strip().upper(), values) else: print('FeaturesUppercase: unsupported dataframe: {}'.format(type(X1))) X1[fname] = values # drop less important features X1 = X1.drop(self.drop_feature_names, axis=1) return X1
The transform() method of the OneHotEncodeData transformer class calls the get_dummies() method of DataFrame to one-hot encode the values of categorical values.
class OneHotEncodeData(BaseEstimator, TransformerMixin): def __init__(self): self.one_hot_feature_names = ['Client name', 'Industry', 'Location', 'Position to be closed', 'Nature of Skillset', 'Interview Type', 'Gender', 'Candidate Current Location', 'Candidate Job Location', 'Interview Venue', 'Candidate Native location', 'Have you obtained the necessary permission to start at the required time', 'Hope there will be no unscheduled meetings', 'Can I Call you three hours before the interview and follow up on your attendance for the interview', 'Can I have an alternative number/ desk number. I assure you that I will not trouble you too much', 'Have you taken a printout of your updated resume. Have you read the JD and understood the same', 'Are you clear with the venue details and the landmark.', 'Has the call letter been shared', 'Marital Status'] self.label_encoders = None self.one_hot_encoders = None def fit(self, X, y=None): return self def transform(self, X, y=None): X1 = X.copy() if type(X1) == ks.DataFrame: X1 = ks.get_dummies(X1) elif type(X1) == pd.DataFrame: X1 = pd.get_dummies(X1) else: print('OneHotEncodeData: unsupported dataframe: {}'.format(type(X1))) pass return X1
All of the data preprocessing transformers are combined into a scikit-learn pipeline as follows in the PreprocessData() method of the PredictInterview class (see Section 4.3 for details). The fit() and transform() methods of these transformers will be executed sequentially once the fit_transform() method of the pipeline object is called.
self.pipeline = Pipeline([ ('bucket_skillset', BucketSkillset()), ('bucket_location', BucketLocation()), ('parse_interview_date', ParseInterviewDate()), ('features_to_uppercase', FeaturesUppercase(self.feature_names, self.drop_feature_names)), ('one_hot_encoder', self.oneHotEncoder) ])
Once the dataset has been prepared, the next step is modeling. The main goals of modeling include:
Identify machine learning model
Train machine learning model
Tune the hyper-parameters of machine learning model
There are three major high-level types of machine learning and deep learning algorithms/models:
supervised machine learning and deep learning
unsupervised machine learning and deep learning
reinforcement learning
Supervised machine learning and deep learning can be divided into subtypes such as regression and classification. Each subtype includes various machine learning and deep learning algorithms/models. For instance, supervised machine learning classification models include Decision Tree classifier, Random Forest classifier, GBM classifier, etc.
Generally speaking, given a business problem, there are many different types of models that can be used as possible solutions. These different models need to be compared to identify the most promising one as the solution to the target business problem. Thus model identification can not be done in isolation. It depends on model training and evaluation/comparison of model performance metrics.
In this article we simply select the scikit-learn RandomForestClassifier model for demonstration purpose.
Once a model (e.g., RandomForestClassifier) is identified, typically there are multiple hyper-parameters to be tuned. A hyper-parameter is a parameter that needs to be set before a model training can begin and such hyper-parameter value does not change during model training. For example, the Random Forest Classifier has multiple hyper-parameters such as number of estimators, max depth, etc.
The sciket-learn GridSearchCV is a popular library for searching the best combination of hyper-parameters of a given model by automatically executing an instance of the model many times. Each execution corresponds to a unique combination of the selected hyper-parameter values. The GridSearch class is to use this library to find the best combination of number of estimators and max depth:
class GridSearch(object): def __init__(self, cv=10): self.grid_param = [ {'n_estimators': range(68,69), # range(60, 70) 'max_depth' : range(8,9)} # range(5, 10)} ] self.cv = cv self.scoring_function = make_scorer(f1_score, greater_is_better=True) self.gridSearch = None def fit(self, X, y): rfc = RandomForestClassifier() self.gridSearchCV = GridSearchCV(rfc, self.grid_param, cv=self.cv, scoring=self.scoring_function) self.gridSearchCV.fit(X, y) return self.gridSearchCV.best_estimator_
One designed functionality of mlflow is to track and compare the hyper-parameters and performance metrics of different model executions.
The method of mlFlow() of the PredictInterview class is to train a model, use the trained model to predict results, obtain various model performance metrics, and then call the mlflow API to track both the hyper-parameters and performance metrics, and at the same time log a trained model into a file for later usage such as deployment.
def mlFlow(self): np.random.seed(40) with mlflow.start_run(): self.loadData() self.PreprocessData() self.trainModel() self.predictClasses() accuracy_score, f1_score, rmse_score, mae_score, r2_score = self.getModelMetrics() best_params = self.gridSearch.gridSearchCV.best_params_ mlflow.log_param("n_estimators", best_params["n_estimators"]) mlflow.log_param("max_depth", best_params["max_depth"]) mlflow.log_metric("rmse", rmse_score) mlflow.log_metric("r2", r2_score) mlflow.log_metric("mae", mae_score) mlflow.log_metric("accuracy", accuracy_score) mlflow.log_metric("f1", f1_score) mlflow.sklearn.log_model(self.rfc, "random_forest_model")
A Jupyter notebook of the PredictInterview class below and all the other pieces of source code in this article are available in Github [6].
class PredictInterview(object): def __init__(self, use_koalas=True): self.use_koalas = use_koalas self.dataset_file_name = 'Interview_Attendance_Data.csv' self.feature_names = ['Date of Interview', 'Client name', 'Industry', 'Location', 'Position to be closed', 'Nature of Skillset', 'Interview Type', 'Gender', 'Candidate Current Location', 'Candidate Job Location', 'Interview Venue', 'Candidate Native location', 'Have you obtained the necessary permission to start at the required time', 'Hope there will be no unscheduled meetings', 'Can I Call you three hours before the interview and follow up on your attendance for the interview', 'Can I have an alternative number/ desk number. I assure you that I will not trouble you too much', 'Have you taken a printout of your updated resume. Have you read the JD and understood the same', 'Are you clear with the venue details and the landmark.', 'Has the call letter been shared', 'Marital Status'] if self.use_koalas: self.drop_feature_names = [ 'Name(Cand ID)', 'Date of Interview', '_c22', '_c23', '_c24', '_c25', '_c26'] else: # use Pandas self.drop_feature_names = [ 'Unnamed: 22', 'Unnamed: 23', 'Unnamed: 24', 'Unnamed: 25', 'Unnamed: 26'] self.dataset = None self.rfc = None self.gridSearch = None self.X_train = None self.y_train = None self.X_test = None self.y_test = None self.y_pred = None self.X_clean = None self.y_clean = None self.X_train_encoded = None self.X_test_encoded = None self.y_train_encoded = None self.accuracy_score = None self.f1_score = None self.oneHotEncoder = None self.X_test_name_ids = None self.pipeline = None def loadData(self, path=None): if (path != None): path = os.path.join(path, self.dataset_file_name) else: path = self.dataset_file_name if self.use_koalas: dataset = ks.read_csv(path) else: dataset = pd.read_csv(path) # shuffle data self.dataset = dataset.sample(frac=1.0) return self.dataset def PreprocessData(self): y = self.dataset['Observed Attendance'] # extract labels y if self.use_koalas: X = self.dataset.drop('Observed Attendance') # extract features X else: X = self.dataset.drop(['Observed Attendance'], axis=1) self.oneHotEncoder = OneHotEncodeData() self.pipeline = Pipeline([ ('bucket_skillset', BucketSkillset()), ('bucket_location', BucketLocation()), ('parse_interview_date', ParseInterviewDate()), ('features_to_uppercase', FeaturesUppercase(self.feature_names, self.drop_feature_names)), ('one_hot_encoder', self.oneHotEncoder) ]) X_1hot = self.pipeline.fit_transform(X) # fill up missing labels and then change labels to uppercase y = y.fillna('NaN') if self.use_koalas: func = lambda x: x.strip().upper() y_uppercase = transformColumn(y, func, str) else: y_uppercase = map(lambda x: x.strip().upper(), y.values) y_uppercase = pd.Series(y_uppercase) # separate labeled records from unlabeled records self.X_train_encoded = X_1hot[y_uppercase != 'NAN'] self.X_test_encoded = X_1hot[y_uppercase == 'NAN'] # save Names/ID for reporting later one self.X_test_name_ids = self.dataset['Name(Cand ID)'].loc[y_uppercase == 'NAN'] y_train = y_uppercase.loc[y_uppercase != 'NAN'] # encode labels as follows: 0 - NO, 1 - YES, NAN - NAN if self.use_koalas: func = lambda x: 1 if x == 'YES' else 0 y = transformColumn(y_train, func, int) else: y = map(lambda x: 1 if x == 'YES' else 0, y_train) y = pd.Series(y) self.y_train_encoded = y self.X_clean = X_1hot self.y_clean = y_uppercase return None def __splitData(self): if self.use_koalas: X_train_encoded = self.X_train_encoded.to_numpy() y_train_encoded = self.y_train_encoded.to_numpy() else: X_train_encoded = self.X_train_encoded.values y_train_encoded = self.y_train_encoded.values self.X_train, self.X_test, self.y_train, self.y_test = train_test_split(X_train_encoded, y_train_encoded, test_size = 0.25, random_state = 0) return (self.X_train, self.X_test, self.y_train, self.y_test) def trainModel(self): X_train, X_test, y_train, y_test = self.__splitData() self.gridSearch = GridSearch() self.rfc = self.gridSearch.fit(X_train, y_train) return self.rfc def predictClasses(self): if (self.rfc is None): print("No trained model available, please train a model first!") return None self.y_pred = self.rfc.predict(self.X_test) return self.y_pred def getModelMetrics(self): if (self.y_test is None or self.y_pred is None): print('Failed to get model performance metrics because y_test is null or y_pred is null!') return None self.accuracy_score = accuracy_score(self.y_test, self.y_pred) self.f1_score = f1_score(self.y_test, self.y_pred) pred = self.predictAttendanceProbability(self.X_test)[:, 1] actual = self.y_test.astype(float) self.rmse_score = np.sqrt(mean_squared_error(actual, pred)) self.mae_score = mean_absolute_error(actual, pred) self.r2_score = r2_score(actual, pred) return (self.accuracy_score, self.f1_score, self.rmse_score, self.mae_score, self.r2_score) def predictNullAttendanceProbability(self): y_pred = self.rfc.predict_proba(self.X_test_encoded.to_numpy()) return y_pred def predictNullAttendanceClasses(self): y_pred = self.rfc.predict(self.X_test_encoded.to_numpy()) return y_pred def predictAttendanceProbability(self, X): y_pred = self.rfc.predict_proba(X) return y_pred def predictAttendanceClass(self, X): y_pred = self.rfc.predict(X) return y_pred def mlFlow(self): np.random.seed(40) with mlflow.start_run(): self.loadData() self.PreprocessData() self.trainModel() self.predictClasses() accuracy_score, f1_score, rmse_score, mae_score, r2_score = self.getModelMetrics() best_params = self.gridSearch.gridSearchCV.best_params_ mlflow.log_param("n_estimators", best_params["n_estimators"]) mlflow.log_param("max_depth", best_params["max_depth"]) mlflow.log_metric("rmse", rmse_score) mlflow.log_metric("r2", r2_score) mlflow.log_metric("mae", mae_score) mlflow.log_metric("accuracy", accuracy_score) mlflow.log_metric("f1", f1_score) mlflow.sklearn.log_model(self.rfc, "random_forest_model")
The code below shows how to instantiate an object of the PredictInterview class and then call its mlFlow() method.
predictInterview = PredictInterview(use_koalas=True)predictInterview.mlFlow()
Once the hyper-parameters and performance metrics of a model have been tracked in mlflow, we can use a terminal or Jupyter notebook to start the mlflow UI (User Interface) as follows to view the history of model executions:
!mlflow ui # for jupyter notebook
Assuming that the mlflow UI starts on a local machine, the following IP address and port number can be used to view the results in a Web browser:
http://127.0.0.1:5000
The following picture is a snapshot of a model execution history in the mlflow UI:
Figure 2: Tracking hyper-parameters and metrics in mlflow UI
Once a machine learning model has been trained with expected performance, the next step is to assess the prediction results of the model in a controlled close-to-real settings to gain confidence that the model is valid, reliable, and meets business requirements of deployment.
As an example, for the Kaggle interview attendance project, one possible method of evaluation is to use mlflow to deploy the model as a Web service and then develop a client program to call the model Web service to get the prediction results of a testing dataset after going through data preparation. These prediction results can then be used to generate a report (e.g., a table or csv file) for recruitment industry domain experts to review.
As demonstration purpose, the following code uses the prediction results with a threshold of 0.5 to generate both a probability and a prediction for each of the candidates where the value in the “Observed Attendance” column is missing, and forms the results as a Pandas DataFrame.
pred_probs = predictInterview.predictNullAttendanceProbability()pred_classes = predictInterview.predictNullAttendanceClasses()x = predictInterview.X_test_name_ids.to_numpy() z = zip(x, pred_probs, pred_classes)answers = ('no', 'yes')result = [[x1, p1[1], answers[c]] for x1, p1, c in z]result_df = pd.DataFrame(np.array(result), columns=['Names/ID', 'Probability', 'Yes/No'])result_df.to_csv('interview_prediction.csv')result_df.head(15)
The following are the first 15 rows of the DataFrame:
Once the model evaluation concludes that the model is ready for deployment, the final step is to deploy an evaluated model into a production system. As described in the book Data Science for Business, the specifics of deployment depend on the target production system.
Taking the Kaggle interview attendance project as an example, one possible scenario is to deploy the model as a Web service on a server, which can be called by other components in a target production system to get prediction results for assisting job interview arrangement. In a more complicated scenario that the development of the target production system is based on a programming language (e.g., Java) that is different from the modeling language (e.g., Python), then the chance is that the model needs to be reimplemented in the target programming language as a component of the production system.
As described before, a trained model has been logged into a file during the process of tracking model executions in mlflow. The following screen snapshot shows the information of a logged model:
Figure 3: Logging trained model in mlflow UI
Similarly to the mlflow tutorial, the following code is to use the mlflow built-in functionality to start a logged model as a Web service:
mlflow models serve -m /Users/xyz/machine-learning-spark/mlruns/0/258301f3ac5f42fb99e885968ff17c2a/artifacts/random_forest_model -p 1234
For simplicity, in this section, it is assumed that the test_df is a Pandas DataFrame with only one row of testing data (an interview attendance feature vector):
test_df.head()
The following code can be used to send the row of testing data to the model Web service to obtain the predicted interview attendance (1 - Yes, 0 - No):
import requestsimport jsonheaders = {'Content-Type': 'application/json', 'Format': 'pandas-split'}url = 'http://127.0.0.1:1234/invocations'headers_json_str = json.dumps(headers)headers_json_obj = json.loads(headers_json_str)data_json_obj = test_df.to_json(orient='split')response = requests.post(url, data=data_json_obj, headers = headers_json_obj)response.text
In this article, I used a close-to-real challenging dataset, the Interview Attendance Problem for Kaggle competition, to demonstrate an end-to-end process of developing an Object-Oriented machine learning pipeline in Python for both Pandas and Koalas DataFrames by combining Pandas and Koalas DataFrame with scikit-learn pipeline API and mlflow. This end-to-end development process follows the Cross-industry standard process for data mining. A brief description and sample implementation code are provided for each of the phases (except for the first phase) of the standard process. A Jupyter notebook and corresponding Python source code file are available in Github [6].
[1] Provost, F., Fawcett, T. (2013). Data Science for Business, O’Reilly, July 2013
[2] Geron, A. (2017). Hands-On Machine Learning with Scikit-Learn & TensorFlow, O’Reilly, March 2017
[3] mlflow 1.3.0 tutorial: https://www.mlflow.org/docs/latest/tutorial.html
[4] The Interview Attendance Problem: https://www.kaggle.com/vishnusraghavan/the-interview-attendance-problem/data
[5] Zhang, Y. (2019). Python Data Preprocessing Using Pandas DataFrame, Spark DataFrame, and Koalas DataFrame: https://towardsdatascience.com/python-data-preprocessing-using-pandas-dataframe-spark-dataframe-and-koalas-dataframe-e44c42258a8f
[6] Zhang, Y. (2019). Jupyter notebook in Github
DISCLOSURE STATEMENT: © 2019 Capital One. Opinions are those of the individual author. Unless noted otherwise in this post, Capital One is not affiliated with, nor endorsed by, any of the companies mentioned. All trademarks and other intellectual property used or displayed are property of their respective owners. | [
{
"code": null,
"e": 542,
"s": 172,
"text": "In the article Python Data Preprocessing Using Pandas DataFrame, Spark DataFrame, and Koalas DataFrame, I used a public dataset to evaluate and compare the basic functionality of Pandas, Spark, and Koalas DataFrames in typical data preprocessing steps for machine learning. The main advantage of Koalas is that it supports an easy-to-use API similar to Pandas on Spark."
},
{
"code": null,
"e": 862,
"s": 542,
"text": "In this article, I use a more challenging dataset, the Interview Attendance Problem for Kaggle competition to demonstrate an end-to-end process of developing an Object-Oriented machine learning pipeline in Python for both Pandas and Koalas DataFrames using Pandas, Koalas, scikit-learn, and mlflow. This is achieved by:"
},
{
"code": null,
"e": 957,
"s": 862,
"text": "Developing a data preprocessing pipeline using Pandas DataFrame with scikit-learn pipeline API"
},
{
"code": null,
"e": 1069,
"s": 957,
"text": "Developing a data preprocessing pipeline for Spark by combining scikit-learn pipeline API with Koalas DataFrame"
},
{
"code": null,
"e": 1146,
"s": 1069,
"text": "Developing a machine learning pipeline by combining scikit-learn with mlflow"
},
{
"code": null,
"e": 1310,
"s": 1146,
"text": "The end-to-end development process is based on the Cross-industry standard process for data mining. As shown in the diagram below, it consists of six major phases:"
},
{
"code": null,
"e": 1333,
"s": 1310,
"text": "Business Understanding"
},
{
"code": null,
"e": 1352,
"s": 1333,
"text": "Data Understanding"
},
{
"code": null,
"e": 1369,
"s": 1352,
"text": "Data Preparation"
},
{
"code": null,
"e": 1378,
"s": 1369,
"text": "Modeling"
},
{
"code": null,
"e": 1389,
"s": 1378,
"text": "Evaluation"
},
{
"code": null,
"e": 1400,
"s": 1389,
"text": "Deployment"
},
{
"code": null,
"e": 1466,
"s": 1400,
"text": "Figure 1: CRISP-DM process diagram (refer to source in Wikipedia)"
},
{
"code": null,
"e": 1599,
"s": 1466,
"text": "For convenience of discussion, it is assumed that the following Python libraries have been installed on a local machine such as Mac:"
},
{
"code": null,
"e": 1684,
"s": 1599,
"text": "Anaconda (conda 4.7.10) with Python 3.6, Numpy, Pandas, Matplotlib, and Scikit-Learn"
},
{
"code": null,
"e": 1698,
"s": 1684,
"text": "pyspark 2.4.4"
},
{
"code": null,
"e": 1705,
"s": 1698,
"text": "Koalas"
},
{
"code": null,
"e": 1712,
"s": 1705,
"text": "mlflow"
},
{
"code": null,
"e": 1856,
"s": 1712,
"text": "The reason of using Python 3.6 is that certain functionality (e.g., deployment) of the current release of mlflow does not work with Python 3.7."
},
{
"code": null,
"e": 2075,
"s": 1856,
"text": "The first phase is business understanding. The key point in this phase is to understand the business problem to be solved. As an example, the following is a brief description of the Kaggle interview attendance problem:"
},
{
"code": null,
"e": 2341,
"s": 2075,
"text": "Given a set of questions that are asked by a recruiter while scheduling an interview with a candidate, how to use the answers to those questions from the candidate to predict whether the expected attendance will attend a scheduled interview (yes, no, or uncertain)."
},
{
"code": null,
"e": 2537,
"s": 2341,
"text": "Once the business problem is understood, the next step is to identify where (i.e., data sources) and how we should collect data from which a machine learning solution to the problem can be built."
},
{
"code": null,
"e": 2746,
"s": 2537,
"text": "The dataset for the Kaggle interview attendance problem has been collected from the recruitment industry in India by the researchers over a period of more than 2 years between September 2014 and January 2017."
},
{
"code": null,
"e": 2894,
"s": 2746,
"text": "This dataset is collected with labels (the column of Observed Attendance holds the labels) and thus it is suitable for supervised machine learning."
},
{
"code": null,
"e": 3118,
"s": 2894,
"text": "The following code imports the necessary Python libraries for all the source code in this article, and loads the dataset into a Koalas DataFrame and displays the first five rows of the DataFrame as shown in the table above."
},
{
"code": null,
"e": 3871,
"s": 3118,
"text": "import numpy as npimport pandas as pdimport databricks.koalas as ksimport matplotlib.pyplot as pltimport matplotlib as mplfrom datetime import datetimeimport osfrom sklearn.base import BaseEstimator, TransformerMixinfrom sklearn.pipeline import Pipelinefrom sklearn.externals import joblibimport mlflowimport mlflow.sklearnfrom sklearn.model_selection import train_test_splitfrom sklearn.ensemble import RandomForestClassifierfrom sklearn.model_selection import GridSearchCVfrom sklearn.metrics import make_scorerfrom sklearn.metrics import accuracy_scorefrom sklearn.metrics import f1_scorefrom sklearn.metrics import mean_squared_error, mean_absolute_error, r2_score%matplotlib inlineks_df = ks.read_csv('Interview_Attendance_Data.csv')ks_df.head()"
},
{
"code": null,
"e": 4072,
"s": 3871,
"text": "The main goal of data preparation is to clean and transform a collected raw dataset into appropriate format so that the transformed data can be effectively consumed by a target machine learning model."
},
{
"code": null,
"e": 4450,
"s": 4072,
"text": "In the interview attendance raw dataset, the column of Name(Cand ID) contains candidate unique identifiers, which do not have much prediction power and thus can be dropped. In addition, all of the columns (i.e., columns from _c22 to _c26 for Koalas DataFrame, or columns from Unnamed: 22 to Unnamed: 26 for Pandas DataFrame) have no data and thus can safely be dropped as well."
},
{
"code": null,
"e": 4743,
"s": 4450,
"text": "Except for the date of interview, all of the other columns in the dataset have categorical (textual) values. In order to use machine learning to solve the problem, those categorical values must be transformed into numeric values because a machine learning model can only consume numeric data."
},
{
"code": null,
"e": 5004,
"s": 4743,
"text": "The column of Date of Interview should be split into day, month, and year to increase prediction power since the information of individual day, month, and year tends to be more strongly correlated with seasonable jobs compared with a string of date as a whole."
},
{
"code": null,
"e": 5415,
"s": 5004,
"text": "The columns of Nature of Skillset and Candidate Native location have a large number of unique entries. These will introduce a large number of new derived features after one-hot encoding. Too many features can lead to a curse of dimensionality problem in the case the size of dataset is not large enough. To alleviate such problem, the values of these two columns are redivided into a smaller number of buckets."
},
{
"code": null,
"e": 5497,
"s": 5415,
"text": "The above data preprocessing/transformation can be summarized as following steps:"
},
{
"code": null,
"e": 5516,
"s": 5497,
"text": "Bucketing skillset"
},
{
"code": null,
"e": 5552,
"s": 5516,
"text": "Bucketing candidate native location"
},
{
"code": null,
"e": 5575,
"s": 5552,
"text": "Parsing interview date"
},
{
"code": null,
"e": 5650,
"s": 5575,
"text": "Changing categorical values to uppercase and dropping less useful features"
},
{
"code": null,
"e": 5686,
"s": 5650,
"text": "One-Hot Encoding categorical values"
},
{
"code": null,
"e": 5941,
"s": 5686,
"text": "These steps are implemented by developing an Object-Oriented data preprocessing pipeline for both Pandas and Koalas DataFrames by combining Pandas and Koalas DataFrames with scikit-learn pipeline API (i.e., BaseEstimator, TransformerMixin, and Pipeline)."
},
{
"code": null,
"e": 6337,
"s": 5941,
"text": "Several data preprocessing steps share a common operation of transforming the values of a particular column in a DataFrame. But, as described in Koalas Series, a Koalas Series does not support some of the common Pandas DataFrame and Series indexing mechanisms such as df.iloc[0]. Because of this, there is no simple method of traversing and changing the values of a column in a Koalas DataFrame."
},
{
"code": null,
"e": 6607,
"s": 6337,
"text": "The other difficulty is that Koalas does not allow to build a new Koalas Series object from scratch and then add it as a new column in an existing Koalas DataFrame. It only allows a new Koalas Series object that is built from the existing columns of a Koalas DataFrame."
},
{
"code": null,
"e": 6726,
"s": 6607,
"text": "The difficulties above are avoided by defining a global function to call the apply() method of a Koalas Series object."
},
{
"code": null,
"e": 6962,
"s": 6726,
"text": "def transformColumn(column_values, func, func_type): def transform_column(column_element) -> func_type: return func(column_element) cvalues = column_values cvalues = cvalues.apply(transform_column) return cvalues"
},
{
"code": null,
"e": 7244,
"s": 6962,
"text": "To alleviate the curse of dimensionality issue, the transform() method of the BucketSkillset transformer class divides the unique values of the skillset column into smaller number of buckets by changing those values that appear less than 9 times as one same string value of Others."
},
{
"code": null,
"e": 8496,
"s": 7244,
"text": "class BucketSkillset(BaseEstimator, TransformerMixin): def __init__(self): self.skillset = ['JAVA/J2EE/Struts/Hibernate', 'Fresher', 'Accounting Operations', 'CDD KYC', 'Routine', 'Oracle', 'JAVA/SPRING/HIBERNATE/JSF', 'Java J2EE', 'SAS', 'Oracle Plsql', 'Java Developer', 'Lending and Liabilities', 'Banking Operations', 'Java', 'Core Java', 'Java J2ee', 'T-24 developer', 'Senior software engineer-Mednet', 'ALS Testing', 'SCCM', 'COTS Developer', 'Analytical R & D', 'Sr Automation Testing', 'Regulatory', 'Hadoop', 'testing', 'Java', 'ETL', 'Publishing'] def fit(self, X, y=None): return self def transform(self, X, y=None): func = lambda x: x if x in self.skillset else 'Others' X1 = X.copy() cname = 'Nature of Skillset' cvalue = X1[cname] if type(X1) == ks.DataFrame: cvalue = transformColumn(cvalue, func, str) X1[cname] = cvalue elif type(X1) == pd.DataFrame: X2 = map(func, cvalue) X1[cname] = pd.Series(X2) else: print('BucketSkillset: unsupported dataframe: {}'.format(type(X1))) pass return X1"
},
{
"code": null,
"e": 8824,
"s": 8496,
"text": "Similarly to bucketing skillset, to alleviate the curse of dimensionality issue, the transform() method of the BucketLocation transformer class divides the unique values of the candidate native location column into smaller number of buckets by changing those values that appear less than 12 times into one same value of Others."
},
{
"code": null,
"e": 9835,
"s": 8824,
"text": "class BucketLocation(BaseEstimator, TransformerMixin): def __init__(self): self.candidate_locations = ['Chennai', 'Hyderabad', 'Bangalore', 'Gurgaon', 'Cuttack', 'Cochin', 'Pune', 'Coimbatore', 'Allahabad', 'Noida', 'Visakapatinam', 'Nagercoil', 'Trivandrum', 'Kolkata', 'Trichy', 'Vellore'] def fit(self, X, y=None): return self def transform(self, X, y=None): X1 = X.copy() func = lambda x: x if x in self.candidate_locations else 'Others' cname = 'Candidate Native location' cvalue = X1[cname] if type(X1) == ks.DataFrame: cvalue = transformColumn(cvalue, func, str) X1[cname] = cvalue elif type(X1) == pd.DataFrame: X2 = map(func, cvalue) X1[cname] = pd.Series(X2) else: print('BucketLocation: unsupported dataframe: {}'.format(type(X1))) pass return X1"
},
{
"code": null,
"e": 10324,
"s": 9835,
"text": "The values of the column of Date of Interview are messy in that various formats are used. For instance not only different delimits are used to separate day, month, and year, but also different orders of day, month, and year are followed. This is handled by the _parseDate() and transform_date() methods of the ParseInterviewDate transformer class. The overall functionality of the transform() method is to separate the interview date string into values of individual day, month, and year."
},
{
"code": null,
"e": 15002,
"s": 10324,
"text": "class ParseInterviewDate(BaseEstimator, TransformerMixin): def __init__(self): pass def __parseDate(self, string, delimit): try: if ('&' in string): subs = tuple(string.split('&')) string = subs[0] except: print ('TypeError: {}'.format(string)) return None string = string.strip() try: d = datetime.strptime(string, '%d{0}%m{0}%Y'.format(delimit)) except: try: d = datetime.strptime(string, '%d{0}%m{0}%y'.format(delimit)) except: try: d = datetime.strptime(string, '%d{0}%b{0}%Y'.format(delimit)) except: try: d = datetime.strptime(string, '%d{0}%b{0}%y'.format(delimit)) except: try: d = datetime.strptime(string, '%b{0}%d{0}%Y'.format(delimit)) except: try: d = datetime.strptime(string, '%b{0}%d{0}%y'.format(delimit)) except: d = None return d def fit(self, X, y=None): return self def transform(self, X, y=None): def transform_date(ditem): if (isinstance(ditem, str) and len(ditem) > 0): if ('.' in ditem): d = self.__parseDate(ditem, '.') elif ('/' in ditem): d = self.__parseDate(ditem, '/') elif ('-' in ditem): d = self.__parseDate(ditem, '-') elif (' ' in ditem): d = self.__parseDate(ditem, ' ') else: d = None if (d is None): return 0, 0, 0 else: return d.day, d.month, d.year def get_day(column_element) -> int: try: day, month, year = transform_date(column_element) return int(day) except: return 0 def get_month(column_element) -> int: try: day, month, year = transform_date(column_element) return int(month) except: return 0 def get_year(column_element) -> int: try: day, month, year = transform_date(column_element) return int(year) except: return 0 def pandas_transform_date(X1): days = [] months = [] years = [] ditems = X1['Date of Interview'].values for ditem in ditems: if (isinstance(ditem, str) and len(ditem) > 0): if ('.' in ditem): d = self.__parseDate(ditem, '.') elif ('/' in ditem): d = self.__parseDate(ditem, '/') elif ('-' in ditem): d = self.__parseDate(ditem, '-') elif (' ' in ditem): d = self.__parseDate(ditem, ' ') else: d = None if (d is None): # print(\"{}, invalid format of interview date!\".format(ditem)) days.append(0) # 0 - NaN months.append(0) years.append(0) else: days.append(d.day) months.append(d.month) years.append(d.year) else: days.append(0) months.append(0) years.append(0) X1['Year'] = years X1['Month'] = months X1['Day'] = days return X1 X1 = X.copy() if type(X1) == ks.DataFrame: X1['Year'] = X1['Date of Interview'] X1['Month'] = X1['Date of Interview'] X1['Day'] = X1['Date of Interview'] func_map = {'Year' : get_year, 'Month' : get_month, 'Day' : get_day} for cname in func_map: cvalue = X1[cname] cvalue = cvalue.apply(func_map[cname]) X1[cname] = cvalue elif type(X1) == pd.DataFrame: X1 = pandas_transform_date(X1) else: print('ParseInterviewDate: unsupported dataframe: {}'.format(type(X1))) pass return X1"
},
{
"code": null,
"e": 15177,
"s": 15002,
"text": "The transform() method of the FeaturesUppercase transformer class is to change the values of categorical features to uppercase and at the same time drop less useful features."
},
{
"code": null,
"e": 16160,
"s": 15177,
"text": "class FeaturesUppercase(BaseEstimator, TransformerMixin): def __init__(self, feature_names, drop_feature_names): self.feature_names = feature_names self.drop_feature_names = drop_feature_names def fit(self, X, y=None): return self def transform(self, X, y=None): func = lambda x: x.strip().upper() X1 = X.copy() for fname in self.feature_names: values = X1[fname] values = values.fillna('NaN') if type(X1) == ks.DataFrame: values = transformColumn(values, func, str) elif type(X1) == pd.DataFrame: values = map(lambda x: x.strip().upper(), values) else: print('FeaturesUppercase: unsupported dataframe: {}'.format(type(X1))) X1[fname] = values # drop less important features X1 = X1.drop(self.drop_feature_names, axis=1) return X1"
},
{
"code": null,
"e": 16321,
"s": 16160,
"text": "The transform() method of the OneHotEncodeData transformer class calls the get_dummies() method of DataFrame to one-hot encode the values of categorical values."
},
{
"code": null,
"e": 18089,
"s": 16321,
"text": "class OneHotEncodeData(BaseEstimator, TransformerMixin): def __init__(self): self.one_hot_feature_names = ['Client name', 'Industry', 'Location', 'Position to be closed', 'Nature of Skillset', 'Interview Type', 'Gender', 'Candidate Current Location', 'Candidate Job Location', 'Interview Venue', 'Candidate Native location', 'Have you obtained the necessary permission to start at the required time', 'Hope there will be no unscheduled meetings', 'Can I Call you three hours before the interview and follow up on your attendance for the interview', 'Can I have an alternative number/ desk number. I assure you that I will not trouble you too much', 'Have you taken a printout of your updated resume. Have you read the JD and understood the same', 'Are you clear with the venue details and the landmark.', 'Has the call letter been shared', 'Marital Status'] self.label_encoders = None self.one_hot_encoders = None def fit(self, X, y=None): return self def transform(self, X, y=None): X1 = X.copy() if type(X1) == ks.DataFrame: X1 = ks.get_dummies(X1) elif type(X1) == pd.DataFrame: X1 = pd.get_dummies(X1) else: print('OneHotEncodeData: unsupported dataframe: {}'.format(type(X1))) pass return X1"
},
{
"code": null,
"e": 18429,
"s": 18089,
"text": "All of the data preprocessing transformers are combined into a scikit-learn pipeline as follows in the PreprocessData() method of the PredictInterview class (see Section 4.3 for details). The fit() and transform() methods of these transformers will be executed sequentially once the fit_transform() method of the pipeline object is called."
},
{
"code": null,
"e": 18778,
"s": 18429,
"text": "self.pipeline = Pipeline([ ('bucket_skillset', BucketSkillset()), ('bucket_location', BucketLocation()), ('parse_interview_date', ParseInterviewDate()), ('features_to_uppercase', FeaturesUppercase(self.feature_names, self.drop_feature_names)), ('one_hot_encoder', self.oneHotEncoder) ])"
},
{
"code": null,
"e": 18877,
"s": 18778,
"text": "Once the dataset has been prepared, the next step is modeling. The main goals of modeling include:"
},
{
"code": null,
"e": 18909,
"s": 18877,
"text": "Identify machine learning model"
},
{
"code": null,
"e": 18938,
"s": 18909,
"text": "Train machine learning model"
},
{
"code": null,
"e": 18990,
"s": 18938,
"text": "Tune the hyper-parameters of machine learning model"
},
{
"code": null,
"e": 19086,
"s": 18990,
"text": "There are three major high-level types of machine learning and deep learning algorithms/models:"
},
{
"code": null,
"e": 19132,
"s": 19086,
"text": "supervised machine learning and deep learning"
},
{
"code": null,
"e": 19180,
"s": 19132,
"text": "unsupervised machine learning and deep learning"
},
{
"code": null,
"e": 19203,
"s": 19180,
"text": "reinforcement learning"
},
{
"code": null,
"e": 19546,
"s": 19203,
"text": "Supervised machine learning and deep learning can be divided into subtypes such as regression and classification. Each subtype includes various machine learning and deep learning algorithms/models. For instance, supervised machine learning classification models include Decision Tree classifier, Random Forest classifier, GBM classifier, etc."
},
{
"code": null,
"e": 19940,
"s": 19546,
"text": "Generally speaking, given a business problem, there are many different types of models that can be used as possible solutions. These different models need to be compared to identify the most promising one as the solution to the target business problem. Thus model identification can not be done in isolation. It depends on model training and evaluation/comparison of model performance metrics."
},
{
"code": null,
"e": 20046,
"s": 19940,
"text": "In this article we simply select the scikit-learn RandomForestClassifier model for demonstration purpose."
},
{
"code": null,
"e": 20440,
"s": 20046,
"text": "Once a model (e.g., RandomForestClassifier) is identified, typically there are multiple hyper-parameters to be tuned. A hyper-parameter is a parameter that needs to be set before a model training can begin and such hyper-parameter value does not change during model training. For example, the Random Forest Classifier has multiple hyper-parameters such as number of estimators, max depth, etc."
},
{
"code": null,
"e": 20830,
"s": 20440,
"text": "The sciket-learn GridSearchCV is a popular library for searching the best combination of hyper-parameters of a given model by automatically executing an instance of the model many times. Each execution corresponds to a unique combination of the selected hyper-parameter values. The GridSearch class is to use this library to find the best combination of number of estimators and max depth:"
},
{
"code": null,
"e": 21426,
"s": 20830,
"text": "class GridSearch(object): def __init__(self, cv=10): self.grid_param = [ {'n_estimators': range(68,69), # range(60, 70) 'max_depth' : range(8,9)} # range(5, 10)} ] self.cv = cv self.scoring_function = make_scorer(f1_score, greater_is_better=True) self.gridSearch = None def fit(self, X, y): rfc = RandomForestClassifier() self.gridSearchCV = GridSearchCV(rfc, self.grid_param, cv=self.cv, scoring=self.scoring_function) self.gridSearchCV.fit(X, y) return self.gridSearchCV.best_estimator_"
},
{
"code": null,
"e": 21563,
"s": 21426,
"text": "One designed functionality of mlflow is to track and compare the hyper-parameters and performance metrics of different model executions."
},
{
"code": null,
"e": 21899,
"s": 21563,
"text": "The method of mlFlow() of the PredictInterview class is to train a model, use the trained model to predict results, obtain various model performance metrics, and then call the mlflow API to track both the hyper-parameters and performance metrics, and at the same time log a trained model into a file for later usage such as deployment."
},
{
"code": null,
"e": 22722,
"s": 21899,
"text": "def mlFlow(self): np.random.seed(40) with mlflow.start_run(): self.loadData() self.PreprocessData() self.trainModel() self.predictClasses() accuracy_score, f1_score, rmse_score, mae_score, r2_score = self.getModelMetrics() best_params = self.gridSearch.gridSearchCV.best_params_ mlflow.log_param(\"n_estimators\", best_params[\"n_estimators\"]) mlflow.log_param(\"max_depth\", best_params[\"max_depth\"]) mlflow.log_metric(\"rmse\", rmse_score) mlflow.log_metric(\"r2\", r2_score) mlflow.log_metric(\"mae\", mae_score) mlflow.log_metric(\"accuracy\", accuracy_score) mlflow.log_metric(\"f1\", f1_score) mlflow.sklearn.log_model(self.rfc, \"random_forest_model\")"
},
{
"code": null,
"e": 22862,
"s": 22722,
"text": "A Jupyter notebook of the PredictInterview class below and all the other pieces of source code in this article are available in Github [6]."
},
{
"code": null,
"e": 30889,
"s": 22862,
"text": "class PredictInterview(object): def __init__(self, use_koalas=True): self.use_koalas = use_koalas self.dataset_file_name = 'Interview_Attendance_Data.csv' self.feature_names = ['Date of Interview', 'Client name', 'Industry', 'Location', 'Position to be closed', 'Nature of Skillset', 'Interview Type', 'Gender', 'Candidate Current Location', 'Candidate Job Location', 'Interview Venue', 'Candidate Native location', 'Have you obtained the necessary permission to start at the required time', 'Hope there will be no unscheduled meetings', 'Can I Call you three hours before the interview and follow up on your attendance for the interview', 'Can I have an alternative number/ desk number. I assure you that I will not trouble you too much', 'Have you taken a printout of your updated resume. Have you read the JD and understood the same', 'Are you clear with the venue details and the landmark.', 'Has the call letter been shared', 'Marital Status'] if self.use_koalas: self.drop_feature_names = [ 'Name(Cand ID)', 'Date of Interview', '_c22', '_c23', '_c24', '_c25', '_c26'] else: # use Pandas self.drop_feature_names = [ 'Unnamed: 22', 'Unnamed: 23', 'Unnamed: 24', 'Unnamed: 25', 'Unnamed: 26'] self.dataset = None self.rfc = None self.gridSearch = None self.X_train = None self.y_train = None self.X_test = None self.y_test = None self.y_pred = None self.X_clean = None self.y_clean = None self.X_train_encoded = None self.X_test_encoded = None self.y_train_encoded = None self.accuracy_score = None self.f1_score = None self.oneHotEncoder = None self.X_test_name_ids = None self.pipeline = None def loadData(self, path=None): if (path != None): path = os.path.join(path, self.dataset_file_name) else: path = self.dataset_file_name if self.use_koalas: dataset = ks.read_csv(path) else: dataset = pd.read_csv(path) # shuffle data self.dataset = dataset.sample(frac=1.0) return self.dataset def PreprocessData(self): y = self.dataset['Observed Attendance'] # extract labels y if self.use_koalas: X = self.dataset.drop('Observed Attendance') # extract features X else: X = self.dataset.drop(['Observed Attendance'], axis=1) self.oneHotEncoder = OneHotEncodeData() self.pipeline = Pipeline([ ('bucket_skillset', BucketSkillset()), ('bucket_location', BucketLocation()), ('parse_interview_date', ParseInterviewDate()), ('features_to_uppercase', FeaturesUppercase(self.feature_names, self.drop_feature_names)), ('one_hot_encoder', self.oneHotEncoder) ]) X_1hot = self.pipeline.fit_transform(X) # fill up missing labels and then change labels to uppercase y = y.fillna('NaN') if self.use_koalas: func = lambda x: x.strip().upper() y_uppercase = transformColumn(y, func, str) else: y_uppercase = map(lambda x: x.strip().upper(), y.values) y_uppercase = pd.Series(y_uppercase) # separate labeled records from unlabeled records self.X_train_encoded = X_1hot[y_uppercase != 'NAN'] self.X_test_encoded = X_1hot[y_uppercase == 'NAN'] # save Names/ID for reporting later one self.X_test_name_ids = self.dataset['Name(Cand ID)'].loc[y_uppercase == 'NAN'] y_train = y_uppercase.loc[y_uppercase != 'NAN'] # encode labels as follows: 0 - NO, 1 - YES, NAN - NAN if self.use_koalas: func = lambda x: 1 if x == 'YES' else 0 y = transformColumn(y_train, func, int) else: y = map(lambda x: 1 if x == 'YES' else 0, y_train) y = pd.Series(y) self.y_train_encoded = y self.X_clean = X_1hot self.y_clean = y_uppercase return None def __splitData(self): if self.use_koalas: X_train_encoded = self.X_train_encoded.to_numpy() y_train_encoded = self.y_train_encoded.to_numpy() else: X_train_encoded = self.X_train_encoded.values y_train_encoded = self.y_train_encoded.values self.X_train, self.X_test, self.y_train, self.y_test = train_test_split(X_train_encoded, y_train_encoded, test_size = 0.25, random_state = 0) return (self.X_train, self.X_test, self.y_train, self.y_test) def trainModel(self): X_train, X_test, y_train, y_test = self.__splitData() self.gridSearch = GridSearch() self.rfc = self.gridSearch.fit(X_train, y_train) return self.rfc def predictClasses(self): if (self.rfc is None): print(\"No trained model available, please train a model first!\") return None self.y_pred = self.rfc.predict(self.X_test) return self.y_pred def getModelMetrics(self): if (self.y_test is None or self.y_pred is None): print('Failed to get model performance metrics because y_test is null or y_pred is null!') return None self.accuracy_score = accuracy_score(self.y_test, self.y_pred) self.f1_score = f1_score(self.y_test, self.y_pred) pred = self.predictAttendanceProbability(self.X_test)[:, 1] actual = self.y_test.astype(float) self.rmse_score = np.sqrt(mean_squared_error(actual, pred)) self.mae_score = mean_absolute_error(actual, pred) self.r2_score = r2_score(actual, pred) return (self.accuracy_score, self.f1_score, self.rmse_score, self.mae_score, self.r2_score) def predictNullAttendanceProbability(self): y_pred = self.rfc.predict_proba(self.X_test_encoded.to_numpy()) return y_pred def predictNullAttendanceClasses(self): y_pred = self.rfc.predict(self.X_test_encoded.to_numpy()) return y_pred def predictAttendanceProbability(self, X): y_pred = self.rfc.predict_proba(X) return y_pred def predictAttendanceClass(self, X): y_pred = self.rfc.predict(X) return y_pred def mlFlow(self): np.random.seed(40) with mlflow.start_run(): self.loadData() self.PreprocessData() self.trainModel() self.predictClasses() accuracy_score, f1_score, rmse_score, mae_score, r2_score = self.getModelMetrics() best_params = self.gridSearch.gridSearchCV.best_params_ mlflow.log_param(\"n_estimators\", best_params[\"n_estimators\"]) mlflow.log_param(\"max_depth\", best_params[\"max_depth\"]) mlflow.log_metric(\"rmse\", rmse_score) mlflow.log_metric(\"r2\", r2_score) mlflow.log_metric(\"mae\", mae_score) mlflow.log_metric(\"accuracy\", accuracy_score) mlflow.log_metric(\"f1\", f1_score) mlflow.sklearn.log_model(self.rfc, \"random_forest_model\")"
},
{
"code": null,
"e": 31004,
"s": 30889,
"text": "The code below shows how to instantiate an object of the PredictInterview class and then call its mlFlow() method."
},
{
"code": null,
"e": 31082,
"s": 31004,
"text": "predictInterview = PredictInterview(use_koalas=True)predictInterview.mlFlow()"
},
{
"code": null,
"e": 31306,
"s": 31082,
"text": "Once the hyper-parameters and performance metrics of a model have been tracked in mlflow, we can use a terminal or Jupyter notebook to start the mlflow UI (User Interface) as follows to view the history of model executions:"
},
{
"code": null,
"e": 31340,
"s": 31306,
"text": "!mlflow ui # for jupyter notebook"
},
{
"code": null,
"e": 31486,
"s": 31340,
"text": "Assuming that the mlflow UI starts on a local machine, the following IP address and port number can be used to view the results in a Web browser:"
},
{
"code": null,
"e": 31508,
"s": 31486,
"text": "http://127.0.0.1:5000"
},
{
"code": null,
"e": 31591,
"s": 31508,
"text": "The following picture is a snapshot of a model execution history in the mlflow UI:"
},
{
"code": null,
"e": 31652,
"s": 31591,
"text": "Figure 2: Tracking hyper-parameters and metrics in mlflow UI"
},
{
"code": null,
"e": 31929,
"s": 31652,
"text": "Once a machine learning model has been trained with expected performance, the next step is to assess the prediction results of the model in a controlled close-to-real settings to gain confidence that the model is valid, reliable, and meets business requirements of deployment."
},
{
"code": null,
"e": 32372,
"s": 31929,
"text": "As an example, for the Kaggle interview attendance project, one possible method of evaluation is to use mlflow to deploy the model as a Web service and then develop a client program to call the model Web service to get the prediction results of a testing dataset after going through data preparation. These prediction results can then be used to generate a report (e.g., a table or csv file) for recruitment industry domain experts to review."
},
{
"code": null,
"e": 32653,
"s": 32372,
"text": "As demonstration purpose, the following code uses the prediction results with a threshold of 0.5 to generate both a probability and a prediction for each of the candidates where the value in the “Observed Attendance” column is missing, and forms the results as a Pandas DataFrame."
},
{
"code": null,
"e": 33093,
"s": 32653,
"text": "pred_probs = predictInterview.predictNullAttendanceProbability()pred_classes = predictInterview.predictNullAttendanceClasses()x = predictInterview.X_test_name_ids.to_numpy() z = zip(x, pred_probs, pred_classes)answers = ('no', 'yes')result = [[x1, p1[1], answers[c]] for x1, p1, c in z]result_df = pd.DataFrame(np.array(result), columns=['Names/ID', 'Probability', 'Yes/No'])result_df.to_csv('interview_prediction.csv')result_df.head(15)"
},
{
"code": null,
"e": 33147,
"s": 33093,
"text": "The following are the first 15 rows of the DataFrame:"
},
{
"code": null,
"e": 33416,
"s": 33147,
"text": "Once the model evaluation concludes that the model is ready for deployment, the final step is to deploy an evaluated model into a production system. As described in the book Data Science for Business, the specifics of deployment depend on the target production system."
},
{
"code": null,
"e": 34019,
"s": 33416,
"text": "Taking the Kaggle interview attendance project as an example, one possible scenario is to deploy the model as a Web service on a server, which can be called by other components in a target production system to get prediction results for assisting job interview arrangement. In a more complicated scenario that the development of the target production system is based on a programming language (e.g., Java) that is different from the modeling language (e.g., Python), then the chance is that the model needs to be reimplemented in the target programming language as a component of the production system."
},
{
"code": null,
"e": 34214,
"s": 34019,
"text": "As described before, a trained model has been logged into a file during the process of tracking model executions in mlflow. The following screen snapshot shows the information of a logged model:"
},
{
"code": null,
"e": 34259,
"s": 34214,
"text": "Figure 3: Logging trained model in mlflow UI"
},
{
"code": null,
"e": 34398,
"s": 34259,
"text": "Similarly to the mlflow tutorial, the following code is to use the mlflow built-in functionality to start a logged model as a Web service:"
},
{
"code": null,
"e": 34535,
"s": 34398,
"text": "mlflow models serve -m /Users/xyz/machine-learning-spark/mlruns/0/258301f3ac5f42fb99e885968ff17c2a/artifacts/random_forest_model -p 1234"
},
{
"code": null,
"e": 34697,
"s": 34535,
"text": "For simplicity, in this section, it is assumed that the test_df is a Pandas DataFrame with only one row of testing data (an interview attendance feature vector):"
},
{
"code": null,
"e": 34713,
"s": 34697,
"text": "test_df.head() "
},
{
"code": null,
"e": 34865,
"s": 34713,
"text": "The following code can be used to send the row of testing data to the model Web service to obtain the predicted interview attendance (1 - Yes, 0 - No):"
},
{
"code": null,
"e": 35237,
"s": 34865,
"text": "import requestsimport jsonheaders = {'Content-Type': 'application/json', 'Format': 'pandas-split'}url = 'http://127.0.0.1:1234/invocations'headers_json_str = json.dumps(headers)headers_json_obj = json.loads(headers_json_str)data_json_obj = test_df.to_json(orient='split')response = requests.post(url, data=data_json_obj, headers = headers_json_obj)response.text"
},
{
"code": null,
"e": 35911,
"s": 35237,
"text": "In this article, I used a close-to-real challenging dataset, the Interview Attendance Problem for Kaggle competition, to demonstrate an end-to-end process of developing an Object-Oriented machine learning pipeline in Python for both Pandas and Koalas DataFrames by combining Pandas and Koalas DataFrame with scikit-learn pipeline API and mlflow. This end-to-end development process follows the Cross-industry standard process for data mining. A brief description and sample implementation code are provided for each of the phases (except for the first phase) of the standard process. A Jupyter notebook and corresponding Python source code file are available in Github [6]."
},
{
"code": null,
"e": 35995,
"s": 35911,
"text": "[1] Provost, F., Fawcett, T. (2013). Data Science for Business, O’Reilly, July 2013"
},
{
"code": null,
"e": 36096,
"s": 35995,
"text": "[2] Geron, A. (2017). Hands-On Machine Learning with Scikit-Learn & TensorFlow, O’Reilly, March 2017"
},
{
"code": null,
"e": 36172,
"s": 36096,
"text": "[3] mlflow 1.3.0 tutorial: https://www.mlflow.org/docs/latest/tutorial.html"
},
{
"code": null,
"e": 36287,
"s": 36172,
"text": "[4] The Interview Attendance Problem: https://www.kaggle.com/vishnusraghavan/the-interview-attendance-problem/data"
},
{
"code": null,
"e": 36528,
"s": 36287,
"text": "[5] Zhang, Y. (2019). Python Data Preprocessing Using Pandas DataFrame, Spark DataFrame, and Koalas DataFrame: https://towardsdatascience.com/python-data-preprocessing-using-pandas-dataframe-spark-dataframe-and-koalas-dataframe-e44c42258a8f"
},
{
"code": null,
"e": 36577,
"s": 36528,
"text": "[6] Zhang, Y. (2019). Jupyter notebook in Github"
}
] |
How to get values from html input array using JavaScript ? - GeeksforGeeks | 30 Jul, 2021
This problem can be solved by using input tags having the same “name” attribute value that can group multiple values stored under one name which could later be accessed by using that name. To access all the values entered in input fields use the following method:
var input = document.getElementsByName('array[]');
The document.getElementsByName() method is used to return all the values stored under a particular name and thus making input variable an array indexed from 0 to number of inputs. The method document.getElementById().innerHTML is used to change the inner HTML of selected Id. So in this way, we can access the input values and convert them into the array and access it as you like. We have used form tag because it is generally a good practice to group all the input elements together inside a form otherwise in the present scenario it is completely optional.
Example:
<!DOCTYPE html><html lang="en" dir="ltr"> <head> <meta charset="utf-8"> <title> How to get values from html input array using JavaScript ? </title></head> <body style="text-align: center;"> <h1 style="color: green;"> GeeksforGeeks </h1> <h3 id="po">Input Array Elements</h3> <form class="" action="index.html" method="post"> <input type="text" name="array[]" value="" /><br> <input type="text" name="array[]" value="" /><br> <input type="text" name="array[]" value="" /><br> <input type="text" name="array[]" value="" /><br> <input type="text" name="array[]" value="" /><br> <button type="button" name="button" onclick="Geeks()"> Submit </button> </form> <br> <p id="par"></p> <script type="text/javascript"> var k = "The respective values are :"; function Geeks() { var input = document.getElementsByName('array[]'); for (var i = 0; i < input.length; i++) { var a = input[i]; k = k + "array[" + i + "].value= " + a.value + " "; } document.getElementById("par").innerHTML = k; document.getElementById("po").innerHTML = "Output"; } </script></body> </html>
Output:
Input Array Elements:
Output Array Elements:
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.
HTML is the foundation of webpages, is used for webpage development by structuring websites and web apps.You can learn HTML from the ground up by following this HTML Tutorial and HTML Examples.
CSS is the foundation of webpages, is used for webpage development by styling websites and web apps.You can learn CSS from the ground up by following this CSS Tutorial and CSS Examples.
CSS-Misc
HTML-Misc
Picked
CSS
HTML
JavaScript
Web Technologies
Web technologies Questions
HTML
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Create a Responsive Navbar using ReactJS
Design a web page using HTML and CSS
Form validation using jQuery
How to place text on image using HTML and CSS?
How to auto-resize an image to fit a div container using CSS?
How to set the default value for an HTML <select> element ?
Hide or show elements in HTML using display property
How to Insert Form Data into Database using PHP ?
REST API (Introduction)
Design a web page using HTML and CSS | [
{
"code": null,
"e": 24691,
"s": 24663,
"text": "\n30 Jul, 2021"
},
{
"code": null,
"e": 24955,
"s": 24691,
"text": "This problem can be solved by using input tags having the same “name” attribute value that can group multiple values stored under one name which could later be accessed by using that name. To access all the values entered in input fields use the following method:"
},
{
"code": null,
"e": 25006,
"s": 24955,
"text": "var input = document.getElementsByName('array[]');"
},
{
"code": null,
"e": 25566,
"s": 25006,
"text": "The document.getElementsByName() method is used to return all the values stored under a particular name and thus making input variable an array indexed from 0 to number of inputs. The method document.getElementById().innerHTML is used to change the inner HTML of selected Id. So in this way, we can access the input values and convert them into the array and access it as you like. We have used form tag because it is generally a good practice to group all the input elements together inside a form otherwise in the present scenario it is completely optional."
},
{
"code": null,
"e": 25575,
"s": 25566,
"text": "Example:"
},
{
"code": "<!DOCTYPE html><html lang=\"en\" dir=\"ltr\"> <head> <meta charset=\"utf-8\"> <title> How to get values from html input array using JavaScript ? </title></head> <body style=\"text-align: center;\"> <h1 style=\"color: green;\"> GeeksforGeeks </h1> <h3 id=\"po\">Input Array Elements</h3> <form class=\"\" action=\"index.html\" method=\"post\"> <input type=\"text\" name=\"array[]\" value=\"\" /><br> <input type=\"text\" name=\"array[]\" value=\"\" /><br> <input type=\"text\" name=\"array[]\" value=\"\" /><br> <input type=\"text\" name=\"array[]\" value=\"\" /><br> <input type=\"text\" name=\"array[]\" value=\"\" /><br> <button type=\"button\" name=\"button\" onclick=\"Geeks()\"> Submit </button> </form> <br> <p id=\"par\"></p> <script type=\"text/javascript\"> var k = \"The respective values are :\"; function Geeks() { var input = document.getElementsByName('array[]'); for (var i = 0; i < input.length; i++) { var a = input[i]; k = k + \"array[\" + i + \"].value= \" + a.value + \" \"; } document.getElementById(\"par\").innerHTML = k; document.getElementById(\"po\").innerHTML = \"Output\"; } </script></body> </html>",
"e": 26907,
"s": 25575,
"text": null
},
{
"code": null,
"e": 26915,
"s": 26907,
"text": "Output:"
},
{
"code": null,
"e": 26937,
"s": 26915,
"text": "Input Array Elements:"
},
{
"code": null,
"e": 26960,
"s": 26937,
"text": "Output Array Elements:"
},
{
"code": null,
"e": 27179,
"s": 26960,
"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": 27373,
"s": 27179,
"text": "HTML is the foundation of webpages, is used for webpage development by structuring websites and web apps.You can learn HTML from the ground up by following this HTML Tutorial and HTML Examples."
},
{
"code": null,
"e": 27559,
"s": 27373,
"text": "CSS is the foundation of webpages, is used for webpage development by styling websites and web apps.You can learn CSS from the ground up by following this CSS Tutorial and CSS Examples."
},
{
"code": null,
"e": 27568,
"s": 27559,
"text": "CSS-Misc"
},
{
"code": null,
"e": 27578,
"s": 27568,
"text": "HTML-Misc"
},
{
"code": null,
"e": 27585,
"s": 27578,
"text": "Picked"
},
{
"code": null,
"e": 27589,
"s": 27585,
"text": "CSS"
},
{
"code": null,
"e": 27594,
"s": 27589,
"text": "HTML"
},
{
"code": null,
"e": 27605,
"s": 27594,
"text": "JavaScript"
},
{
"code": null,
"e": 27622,
"s": 27605,
"text": "Web Technologies"
},
{
"code": null,
"e": 27649,
"s": 27622,
"text": "Web technologies Questions"
},
{
"code": null,
"e": 27654,
"s": 27649,
"text": "HTML"
},
{
"code": null,
"e": 27752,
"s": 27654,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 27761,
"s": 27752,
"text": "Comments"
},
{
"code": null,
"e": 27774,
"s": 27761,
"text": "Old Comments"
},
{
"code": null,
"e": 27815,
"s": 27774,
"text": "Create a Responsive Navbar using ReactJS"
},
{
"code": null,
"e": 27852,
"s": 27815,
"text": "Design a web page using HTML and CSS"
},
{
"code": null,
"e": 27881,
"s": 27852,
"text": "Form validation using jQuery"
},
{
"code": null,
"e": 27928,
"s": 27881,
"text": "How to place text on image using HTML and CSS?"
},
{
"code": null,
"e": 27990,
"s": 27928,
"text": "How to auto-resize an image to fit a div container using CSS?"
},
{
"code": null,
"e": 28050,
"s": 27990,
"text": "How to set the default value for an HTML <select> element ?"
},
{
"code": null,
"e": 28103,
"s": 28050,
"text": "Hide or show elements in HTML using display property"
},
{
"code": null,
"e": 28153,
"s": 28103,
"text": "How to Insert Form Data into Database using PHP ?"
},
{
"code": null,
"e": 28177,
"s": 28153,
"text": "REST API (Introduction)"
}
] |
Transform a BST to greater sum tree - GeeksforGeeks | 22 Jun, 2021
Given a BST, transform it into a greater sum tree where each node contains sum of all nodes greater than that node.
We strongly recommend to minimize the browser and try this yourself first.Method 1 (Naïve): This method doesn’t require the tree to be a BST. Following are the steps. 1. Traverse node by node(Inorder, preorder, etc.) 2. For each node find all the nodes greater than that of the current node, sum the values. Store all these sums. 3. Replace each node value with their corresponding sum by traversing in the same order as in Step 1. This takes O(n^2) Time Complexity.
Method 2 (Using only one traversal) By leveraging the fact that the tree is a BST, we can find an O(n) solution. The idea is to traverse BST in reverse inorder. Reverse inorder traversal of a BST gives us keys in decreasing order. Before visiting a node, we visit all greater nodes of that node. While traversing we keep track of the sum of keys which is the sum of all the keys greater than the key of the current node.
C++
Java
Python3
C#
Javascript
// C++ program to transform a BST to sum tree#include<iostream>using namespace std; // A BST nodestruct Node{ int data; struct Node *left, *right;}; // A utility function to create a new Binary Tree Nodestruct Node *newNode(int item){ struct Node *temp = new Node; temp->data = item; temp->left = temp->right = NULL; return temp;} // Recursive function to transform a BST to sum tree.// This function traverses the tree in reverse inorder so// that we have visited all greater key nodes of the currently// visited nodevoid transformTreeUtil(struct Node *root, int *sum){ // Base case if (root == NULL) return; // Recur for right subtree transformTreeUtil(root->right, sum); // Update sum *sum = *sum + root->data; // Store old sum in current node root->data = *sum - root->data; // Recur for left subtree transformTreeUtil(root->left, sum);} // A wrapper over transformTreeUtil()void transformTree(struct Node *root){ int sum = 0; // Initialize sum transformTreeUtil(root, &sum);} // A utility function to print indorder traversal of a// binary treevoid printInorder(struct Node *root){ if (root == NULL) return; printInorder(root->left); cout << root->data << " "; printInorder(root->right);} // Driver Program to test above functionsint main(){ struct Node *root = newNode(11); root->left = newNode(2); root->right = newNode(29); root->left->left = newNode(1); root->left->right = newNode(7); root->right->left = newNode(15); root->right->right = newNode(40); root->right->right->left = newNode(35); cout << "Inorder Traversal of given tree\n"; printInorder(root); transformTree(root); cout << "\n\nInorder Traversal of transformed tree\n"; printInorder(root); return 0;}
// Java program to transform a BST to sum treeimport java.io.*;class Node{ int data; Node left, right; // A utility function to create a new Binary Tree Node Node(int item) { data = item; left = right = null; }} class GFG{ static int sum = 0; static Node Root; // Recursive function to transform a BST to sum tree. // This function traverses the tree in reverse inorder so // that we have visited all greater key nodes of the currently // visited node static void transformTreeUtil(Node root) { // Base case if (root == null) return; // Recur for right subtree transformTreeUtil(root.right); // Update sum sum = sum + root.data; // Store old sum in current node root.data = sum - root.data; // Recur for left subtree transformTreeUtil(root.left); } // A wrapper over transformTreeUtil() static void transformTree(Node root) { transformTreeUtil(root); } // A utility function to print indorder traversal of a // binary tree static void printInorder(Node root) { if (root == null) return; printInorder(root.left); System.out.print(root.data + " "); printInorder(root.right); } // Driver Program to test above functions public static void main (String[] args) { GFG.Root = new Node(11); GFG.Root.left = new Node(2); GFG.Root.right = new Node(29); GFG.Root.left.left = new Node(1); GFG.Root.left.right = new Node(7); GFG.Root.right.left = new Node(15); GFG.Root.right.right = new Node(40); GFG.Root.right.right.left = new Node(35); System.out.println("Inorder Traversal of given tree"); printInorder(Root); transformTree(Root); System.out.println("\n\nInorder Traversal of transformed tree"); printInorder(Root); }} // This code is contributed by avanitrachhadiya2155
# Python3 program to transform a BST to sum tree class Node: def __init__(self, x): self.data = x self.left = None self.right = None # Recursive function to transform a BST to sum tree.# This function traverses the tree in reverse inorder so# that we have visited all greater key nodes of the currently# visited nodedef transformTreeUtil(root): # Base case if (root == None): return # Recur for right subtree transformTreeUtil(root.right) # Update sum global sum sum = sum + root.data # Store old sum in current node root.data = sum - root.data # Recur for left subtree transformTreeUtil(root.left) # A wrapper over transformTreeUtil()def transformTree(root): # sum = 0 #Initialize sum transformTreeUtil(root) # A utility function to prindorder traversal of a# binary treedef printInorder(root): if (root == None): return printInorder(root.left) print(root.data, end = " ") printInorder(root.right) # Driver Program to test above functionsif __name__ == '__main__': sum=0 root = Node(11) root.left = Node(2) root.right = Node(29) root.left.left = Node(1) root.left.right = Node(7) root.right.left = Node(15) root.right.right = Node(40) root.right.right.left = Node(35) print("Inorder Traversal of given tree") printInorder(root) transformTree(root) print("\nInorder Traversal of transformed tree") printInorder(root) # This code is contributed by mohit kumar 29
// C# program to transform a BST to sum treeusing System; public class Node{ public int data; public Node left, right; // A utility function to create a new Binary Tree Node public Node(int item) { data = item; left = right = null; }} public class GFG{ static int sum = 0; static Node Root; // Recursive function to transform a BST to sum tree. // This function traverses the tree in reverse inorder so // that we have visited all greater key nodes of the currently // visited node static void transformTreeUtil(Node root) { // Base case if (root == null) return; // Recur for right subtree transformTreeUtil(root.right); // Update sum sum = sum + root.data; // Store old sum in current node root.data = sum - root.data; // Recur for left subtree transformTreeUtil(root.left); } // A wrapper over transformTreeUtil() static void transformTree(Node root) { transformTreeUtil(root); } // A utility function to print indorder traversal of a // binary tree static void printInorder(Node root) { if (root == null) return; printInorder(root.left); Console.Write(root.data + " "); printInorder(root.right); } // Driver Program to test above functions static public void Main (){ GFG.Root = new Node(11); GFG.Root.left = new Node(2); GFG.Root.right = new Node(29); GFG.Root.left.left = new Node(1); GFG.Root.left.right = new Node(7); GFG.Root.right.left = new Node(15); GFG.Root.right.right = new Node(40); GFG.Root.right.right.left = new Node(35); Console.WriteLine("Inorder Traversal of given tree"); printInorder(Root); transformTree(Root); Console.WriteLine("\n\nInorder Traversal of transformed tree"); printInorder(Root); }} // This code is contributed by ab2127
<script> // Javascript program to transform// a BST to sum tree // A utility function to create a// new Binary Tree Nodeclass Node{ constructor(item) { this.data = item; this.left=null; this.right=null; }} let sum = 0;let Root; // Recursive function to transform a BST// to sum tree. This function traverses// the tree in reverse inorder so that// we have visited all greater key nodes// of the currently visited nodefunction transformTreeUtil(root){ // Base case if (root == null) return; // Recur for right subtree transformTreeUtil(root.right); // Update sum sum = sum + root.data; // Store old sum in current node root.data = sum - root.data; // Recur for left subtree transformTreeUtil(root.left);} // A wrapper over transformTreeUtil()function transformTree(root){ transformTreeUtil(root);} // A utility function to print indorder// traversal of a binary treefunction printInorder(root){ if (root == null) return; printInorder(root.left); document.write(root.data + " "); printInorder(root.right);} // Driver codeRoot = new Node(11);Root.left = new Node(2);Root.right = new Node(29);Root.left.left = new Node(1);Root.left.right = new Node(7);Root.right.left = new Node(15);Root.right.right = new Node(40);Root.right.right.left = new Node(35); document.write("Inorder Traversal of given tree<br>");printInorder(Root); transformTree(Root);document.write("<br><br>Inorder Traversal of " + "transformed tree<br>");printInorder(Root); // This code is contributed by unknown2108 </script>
Output:
Inorder Traversal of given tree
1 2 7 11 15 29 35 40
Inorder Traversal of transformed tree
139 137 130 119 104 75 40 0
The time complexity of this method is O(n) as it does a simple traversal of the tree.https://youtu.be/hx8IADDBqb0?list=PLqM7alHXFySHCXD7r1J0ky9Zg_GBB1dbk
This article is contributed by Bhavana. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above
mohit kumar 29
uchiha1101
avanitrachhadiya2155
unknown2108
ab2127
Binary Search Tree
Binary Search Tree
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
set vs unordered_set in C++ STL
Red Black Tree vs AVL Tree
Print BST keys in the given range
Implementing Forward Iterator in BST
Construct BST from given preorder traversal | Set 2
Construct all possible BSTs for keys 1 to N
Find the largest BST subtree in a given Binary Tree | Set 1
Check if a given Binary Tree is Heap
Find median of BST in O(n) time and O(1) space | [
{
"code": null,
"e": 24835,
"s": 24807,
"text": "\n22 Jun, 2021"
},
{
"code": null,
"e": 24951,
"s": 24835,
"text": "Given a BST, transform it into a greater sum tree where each node contains sum of all nodes greater than that node."
},
{
"code": null,
"e": 25419,
"s": 24951,
"text": "We strongly recommend to minimize the browser and try this yourself first.Method 1 (Naïve): This method doesn’t require the tree to be a BST. Following are the steps. 1. Traverse node by node(Inorder, preorder, etc.) 2. For each node find all the nodes greater than that of the current node, sum the values. Store all these sums. 3. Replace each node value with their corresponding sum by traversing in the same order as in Step 1. This takes O(n^2) Time Complexity."
},
{
"code": null,
"e": 25841,
"s": 25419,
"text": "Method 2 (Using only one traversal) By leveraging the fact that the tree is a BST, we can find an O(n) solution. The idea is to traverse BST in reverse inorder. Reverse inorder traversal of a BST gives us keys in decreasing order. Before visiting a node, we visit all greater nodes of that node. While traversing we keep track of the sum of keys which is the sum of all the keys greater than the key of the current node. "
},
{
"code": null,
"e": 25845,
"s": 25841,
"text": "C++"
},
{
"code": null,
"e": 25850,
"s": 25845,
"text": "Java"
},
{
"code": null,
"e": 25858,
"s": 25850,
"text": "Python3"
},
{
"code": null,
"e": 25861,
"s": 25858,
"text": "C#"
},
{
"code": null,
"e": 25872,
"s": 25861,
"text": "Javascript"
},
{
"code": "// C++ program to transform a BST to sum tree#include<iostream>using namespace std; // A BST nodestruct Node{ int data; struct Node *left, *right;}; // A utility function to create a new Binary Tree Nodestruct Node *newNode(int item){ struct Node *temp = new Node; temp->data = item; temp->left = temp->right = NULL; return temp;} // Recursive function to transform a BST to sum tree.// This function traverses the tree in reverse inorder so// that we have visited all greater key nodes of the currently// visited nodevoid transformTreeUtil(struct Node *root, int *sum){ // Base case if (root == NULL) return; // Recur for right subtree transformTreeUtil(root->right, sum); // Update sum *sum = *sum + root->data; // Store old sum in current node root->data = *sum - root->data; // Recur for left subtree transformTreeUtil(root->left, sum);} // A wrapper over transformTreeUtil()void transformTree(struct Node *root){ int sum = 0; // Initialize sum transformTreeUtil(root, &sum);} // A utility function to print indorder traversal of a// binary treevoid printInorder(struct Node *root){ if (root == NULL) return; printInorder(root->left); cout << root->data << \" \"; printInorder(root->right);} // Driver Program to test above functionsint main(){ struct Node *root = newNode(11); root->left = newNode(2); root->right = newNode(29); root->left->left = newNode(1); root->left->right = newNode(7); root->right->left = newNode(15); root->right->right = newNode(40); root->right->right->left = newNode(35); cout << \"Inorder Traversal of given tree\\n\"; printInorder(root); transformTree(root); cout << \"\\n\\nInorder Traversal of transformed tree\\n\"; printInorder(root); return 0;}",
"e": 27655,
"s": 25872,
"text": null
},
{
"code": "// Java program to transform a BST to sum treeimport java.io.*;class Node{ int data; Node left, right; // A utility function to create a new Binary Tree Node Node(int item) { data = item; left = right = null; }} class GFG{ static int sum = 0; static Node Root; // Recursive function to transform a BST to sum tree. // This function traverses the tree in reverse inorder so // that we have visited all greater key nodes of the currently // visited node static void transformTreeUtil(Node root) { // Base case if (root == null) return; // Recur for right subtree transformTreeUtil(root.right); // Update sum sum = sum + root.data; // Store old sum in current node root.data = sum - root.data; // Recur for left subtree transformTreeUtil(root.left); } // A wrapper over transformTreeUtil() static void transformTree(Node root) { transformTreeUtil(root); } // A utility function to print indorder traversal of a // binary tree static void printInorder(Node root) { if (root == null) return; printInorder(root.left); System.out.print(root.data + \" \"); printInorder(root.right); } // Driver Program to test above functions public static void main (String[] args) { GFG.Root = new Node(11); GFG.Root.left = new Node(2); GFG.Root.right = new Node(29); GFG.Root.left.left = new Node(1); GFG.Root.left.right = new Node(7); GFG.Root.right.left = new Node(15); GFG.Root.right.right = new Node(40); GFG.Root.right.right.left = new Node(35); System.out.println(\"Inorder Traversal of given tree\"); printInorder(Root); transformTree(Root); System.out.println(\"\\n\\nInorder Traversal of transformed tree\"); printInorder(Root); }} // This code is contributed by avanitrachhadiya2155",
"e": 29462,
"s": 27655,
"text": null
},
{
"code": "# Python3 program to transform a BST to sum tree class Node: def __init__(self, x): self.data = x self.left = None self.right = None # Recursive function to transform a BST to sum tree.# This function traverses the tree in reverse inorder so# that we have visited all greater key nodes of the currently# visited nodedef transformTreeUtil(root): # Base case if (root == None): return # Recur for right subtree transformTreeUtil(root.right) # Update sum global sum sum = sum + root.data # Store old sum in current node root.data = sum - root.data # Recur for left subtree transformTreeUtil(root.left) # A wrapper over transformTreeUtil()def transformTree(root): # sum = 0 #Initialize sum transformTreeUtil(root) # A utility function to prindorder traversal of a# binary treedef printInorder(root): if (root == None): return printInorder(root.left) print(root.data, end = \" \") printInorder(root.right) # Driver Program to test above functionsif __name__ == '__main__': sum=0 root = Node(11) root.left = Node(2) root.right = Node(29) root.left.left = Node(1) root.left.right = Node(7) root.right.left = Node(15) root.right.right = Node(40) root.right.right.left = Node(35) print(\"Inorder Traversal of given tree\") printInorder(root) transformTree(root) print(\"\\nInorder Traversal of transformed tree\") printInorder(root) # This code is contributed by mohit kumar 29",
"e": 30961,
"s": 29462,
"text": null
},
{
"code": "// C# program to transform a BST to sum treeusing System; public class Node{ public int data; public Node left, right; // A utility function to create a new Binary Tree Node public Node(int item) { data = item; left = right = null; }} public class GFG{ static int sum = 0; static Node Root; // Recursive function to transform a BST to sum tree. // This function traverses the tree in reverse inorder so // that we have visited all greater key nodes of the currently // visited node static void transformTreeUtil(Node root) { // Base case if (root == null) return; // Recur for right subtree transformTreeUtil(root.right); // Update sum sum = sum + root.data; // Store old sum in current node root.data = sum - root.data; // Recur for left subtree transformTreeUtil(root.left); } // A wrapper over transformTreeUtil() static void transformTree(Node root) { transformTreeUtil(root); } // A utility function to print indorder traversal of a // binary tree static void printInorder(Node root) { if (root == null) return; printInorder(root.left); Console.Write(root.data + \" \"); printInorder(root.right); } // Driver Program to test above functions static public void Main (){ GFG.Root = new Node(11); GFG.Root.left = new Node(2); GFG.Root.right = new Node(29); GFG.Root.left.left = new Node(1); GFG.Root.left.right = new Node(7); GFG.Root.right.left = new Node(15); GFG.Root.right.right = new Node(40); GFG.Root.right.right.left = new Node(35); Console.WriteLine(\"Inorder Traversal of given tree\"); printInorder(Root); transformTree(Root); Console.WriteLine(\"\\n\\nInorder Traversal of transformed tree\"); printInorder(Root); }} // This code is contributed by ab2127",
"e": 32764,
"s": 30961,
"text": null
},
{
"code": "<script> // Javascript program to transform// a BST to sum tree // A utility function to create a// new Binary Tree Nodeclass Node{ constructor(item) { this.data = item; this.left=null; this.right=null; }} let sum = 0;let Root; // Recursive function to transform a BST// to sum tree. This function traverses// the tree in reverse inorder so that// we have visited all greater key nodes// of the currently visited nodefunction transformTreeUtil(root){ // Base case if (root == null) return; // Recur for right subtree transformTreeUtil(root.right); // Update sum sum = sum + root.data; // Store old sum in current node root.data = sum - root.data; // Recur for left subtree transformTreeUtil(root.left);} // A wrapper over transformTreeUtil()function transformTree(root){ transformTreeUtil(root);} // A utility function to print indorder// traversal of a binary treefunction printInorder(root){ if (root == null) return; printInorder(root.left); document.write(root.data + \" \"); printInorder(root.right);} // Driver codeRoot = new Node(11);Root.left = new Node(2);Root.right = new Node(29);Root.left.left = new Node(1);Root.left.right = new Node(7);Root.right.left = new Node(15);Root.right.right = new Node(40);Root.right.right.left = new Node(35); document.write(\"Inorder Traversal of given tree<br>\");printInorder(Root); transformTree(Root);document.write(\"<br><br>Inorder Traversal of \" + \"transformed tree<br>\");printInorder(Root); // This code is contributed by unknown2108 </script>",
"e": 34405,
"s": 32764,
"text": null
},
{
"code": null,
"e": 34414,
"s": 34405,
"text": "Output: "
},
{
"code": null,
"e": 34534,
"s": 34414,
"text": "Inorder Traversal of given tree\n1 2 7 11 15 29 35 40\n\nInorder Traversal of transformed tree\n139 137 130 119 104 75 40 0"
},
{
"code": null,
"e": 34689,
"s": 34534,
"text": "The time complexity of this method is O(n) as it does a simple traversal of the tree.https://youtu.be/hx8IADDBqb0?list=PLqM7alHXFySHCXD7r1J0ky9Zg_GBB1dbk "
},
{
"code": null,
"e": 34854,
"s": 34689,
"text": "This article is contributed by Bhavana. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above "
},
{
"code": null,
"e": 34869,
"s": 34854,
"text": "mohit kumar 29"
},
{
"code": null,
"e": 34880,
"s": 34869,
"text": "uchiha1101"
},
{
"code": null,
"e": 34901,
"s": 34880,
"text": "avanitrachhadiya2155"
},
{
"code": null,
"e": 34913,
"s": 34901,
"text": "unknown2108"
},
{
"code": null,
"e": 34920,
"s": 34913,
"text": "ab2127"
},
{
"code": null,
"e": 34939,
"s": 34920,
"text": "Binary Search Tree"
},
{
"code": null,
"e": 34958,
"s": 34939,
"text": "Binary Search Tree"
},
{
"code": null,
"e": 35056,
"s": 34958,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 35065,
"s": 35056,
"text": "Comments"
},
{
"code": null,
"e": 35078,
"s": 35065,
"text": "Old Comments"
},
{
"code": null,
"e": 35110,
"s": 35078,
"text": "set vs unordered_set in C++ STL"
},
{
"code": null,
"e": 35137,
"s": 35110,
"text": "Red Black Tree vs AVL Tree"
},
{
"code": null,
"e": 35171,
"s": 35137,
"text": "Print BST keys in the given range"
},
{
"code": null,
"e": 35208,
"s": 35171,
"text": "Implementing Forward Iterator in BST"
},
{
"code": null,
"e": 35260,
"s": 35208,
"text": "Construct BST from given preorder traversal | Set 2"
},
{
"code": null,
"e": 35304,
"s": 35260,
"text": "Construct all possible BSTs for keys 1 to N"
},
{
"code": null,
"e": 35364,
"s": 35304,
"text": "Find the largest BST subtree in a given Binary Tree | Set 1"
},
{
"code": null,
"e": 35401,
"s": 35364,
"text": "Check if a given Binary Tree is Heap"
}
] |
GATE | GATE-CS-2015 (Set 2) | Question 47 - GeeksforGeeks | 27 Sep, 2021
The number of min-terms after minimizing the following Boolean expression is _________.
[D′ + AB′ + A′C + AC′D + A′C′D]′
(A) 1(B) 2(C) 3(D) 4Answer: (A)Explanation:
Given Boolean expression is:
[D′ + AB′ + A′C + AC′D + A′C′D]′
Step 1 : [D′ + AB′ + A′C + C′D ( A + A')]′
( taking C'D as common )
Step 2 : [D′ + AB′ + A′C + C′D]′
( as, A + A' = 1 )
: [D' + DC' + AB' + A'C]' (Rearrange)
Step 3 : [D' + C' + AB' + A'C]'
( Rule of Duality, A + A'B = A + B )
: [D' + C' + CA' + AB']' (Rearrange)
Step 4 : [D' + C' + A' + AB']'
(Rule of Duality)
: [D' + C' + A' + AB']' (Rearrange)
Step 5 : [D' + C' + A' + B']'
(Rule of Duality)
:[( D' + C' )'.( A' + B')']
(Demorgan's law, (A + B)'=(A'. B'))
:[(D''.C'').( A''.B'')] (Demorgan's law)
:[(D.C).(A.B)] (Idempotent law, A'' = A)
: ABCD
Hence only 1 minterm after minimization.
YouTubeGeeksforGeeks GATE Computer Science16.1K subscribersBoolean Functions and Canonical Forms with Rishabh Setiya | GeeksforGeeks GATEWatch 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:0017:51 / 21:51•Live•<div class="player-unavailable"><h1 class="message">An error occurred.</h1><div class="submessage"><a href="https://www.youtube.com/watch?v=irOK71KSqR0" target="_blank">Try watching this video on www.youtube.com</a>, or enable JavaScript if it is disabled in your browser.</div></div>Quiz of this Question
GATE-CS-2015 (Set 2)
GATE-GATE-CS-2015 (Set 2)
GATE
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
GATE | GATE-IT-2004 | Question 66
GATE | GATE-CS-2014-(Set-3) | Question 65
GATE | GATE-CS-2006 | Question 49
GATE | GATE-CS-2004 | Question 3
GATE | GATE CS 2010 | Question 24
GATE | GATE CS 2011 | Question 65
GATE | GATE CS 2019 | Question 27
GATE | GATE CS 2021 | Set 1 | Question 47
GATE | GATE CS 2011 | Question 7
GATE | GATE-CS-2017 (Set 2) | Question 42 | [
{
"code": null,
"e": 24514,
"s": 24486,
"text": "\n27 Sep, 2021"
},
{
"code": null,
"e": 24602,
"s": 24514,
"text": "The number of min-terms after minimizing the following Boolean expression is _________."
},
{
"code": null,
"e": 24641,
"s": 24602,
"text": " [D′ + AB′ + A′C + AC′D + A′C′D]′"
},
{
"code": null,
"e": 24685,
"s": 24641,
"text": "(A) 1(B) 2(C) 3(D) 4Answer: (A)Explanation:"
},
{
"code": null,
"e": 25373,
"s": 24685,
"text": "Given Boolean expression is: \n [D′ + AB′ + A′C + AC′D + A′C′D]′\n\nStep 1 : [D′ + AB′ + A′C + C′D ( A + A')]′ \n( taking C'D as common )\n\nStep 2 : [D′ + AB′ + A′C + C′D]′ \n( as, A + A' = 1 )\n\n: [D' + DC' + AB' + A'C]' (Rearrange)\n\nStep 3 : [D' + C' + AB' + A'C]' \n( Rule of Duality, A + A'B = A + B )\n\n: [D' + C' + CA' + AB']' (Rearrange)\n\nStep 4 : [D' + C' + A' + AB']' \n(Rule of Duality)\n\n: [D' + C' + A' + AB']' (Rearrange)\n\nStep 5 : [D' + C' + A' + B']' \n(Rule of Duality)\n\n:[( D' + C' )'.( A' + B')'] \n(Demorgan's law, (A + B)'=(A'. B'))\n\n:[(D''.C'').( A''.B'')] (Demorgan's law)\n\n:[(D.C).(A.B)] (Idempotent law, A'' = A)\n\n: ABCD\n\nHence only 1 minterm after minimization. "
},
{
"code": null,
"e": 26280,
"s": 25373,
"text": "YouTubeGeeksforGeeks GATE Computer Science16.1K subscribersBoolean Functions and Canonical Forms with Rishabh Setiya | GeeksforGeeks GATEWatch 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:0017:51 / 21:51•Live•<div class=\"player-unavailable\"><h1 class=\"message\">An error occurred.</h1><div class=\"submessage\"><a href=\"https://www.youtube.com/watch?v=irOK71KSqR0\" target=\"_blank\">Try watching this video on www.youtube.com</a>, or enable JavaScript if it is disabled in your browser.</div></div>Quiz of this Question"
},
{
"code": null,
"e": 26301,
"s": 26280,
"text": "GATE-CS-2015 (Set 2)"
},
{
"code": null,
"e": 26327,
"s": 26301,
"text": "GATE-GATE-CS-2015 (Set 2)"
},
{
"code": null,
"e": 26332,
"s": 26327,
"text": "GATE"
},
{
"code": null,
"e": 26430,
"s": 26332,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 26464,
"s": 26430,
"text": "GATE | GATE-IT-2004 | Question 66"
},
{
"code": null,
"e": 26506,
"s": 26464,
"text": "GATE | GATE-CS-2014-(Set-3) | Question 65"
},
{
"code": null,
"e": 26540,
"s": 26506,
"text": "GATE | GATE-CS-2006 | Question 49"
},
{
"code": null,
"e": 26573,
"s": 26540,
"text": "GATE | GATE-CS-2004 | Question 3"
},
{
"code": null,
"e": 26607,
"s": 26573,
"text": "GATE | GATE CS 2010 | Question 24"
},
{
"code": null,
"e": 26641,
"s": 26607,
"text": "GATE | GATE CS 2011 | Question 65"
},
{
"code": null,
"e": 26675,
"s": 26641,
"text": "GATE | GATE CS 2019 | Question 27"
},
{
"code": null,
"e": 26717,
"s": 26675,
"text": "GATE | GATE CS 2021 | Set 1 | Question 47"
},
{
"code": null,
"e": 26750,
"s": 26717,
"text": "GATE | GATE CS 2011 | Question 7"
}
] |
How to use Remove, RemoveAt, RemoveRange methods in C# list collections? | To implement Remove() and RemoveAt() methods in C#, try the following code −
Firstly, set a list.
List<string> myList = new List<string>() {
"mammals",
"reptiles",
"amphibians",
"vertebrate"
};
Now, use Remove() method to remove an element.
myList.Remove("reptiles");
Now, use RemoveAt() method to remove an element by setting the position.
myList.RemoveAt(2);
The following is the complete code −
using System;
using System.Collections.Generic;
using System.Linq;
class Program {
static void Main() {
List<string> myList = new List<string>() {
"mammals",
"reptiles",
"amphibians",
"vertebrate"
};
Console.Write("Initial list...");
foreach (string list in myList) {
Console.WriteLine(list);
}
Console.Write("Using Remove() method...");
myList.Remove("reptiles");
foreach (string list in myList) {
Console.WriteLine(list);
}
Console.Write("Using RemoveAt() method...");
myList.RemoveAt(2);
foreach (string list in myList) {
Console.WriteLine(list);
}
}
}
Here is an example that implements RemoveRange() method.
using System;
using System.Collections.Generic;
using System.Linq;
class Program {
static void Main() {
List<int> myList = new List<int>();
myList.Add(5);
myList.Add(10);
myList.Add(15);
myList.Add(20);
myList.Add(25);
myList.Add(30);
myList.Add(35);
Console.Write("Initial list...");
foreach (int list in myList) {
Console.WriteLine(list);
}
Console.Write("New list...");
int rem = Math.Max(0, myList.Count - 3);
myList.RemoveRange(0, rem);
foreach (int list in myList) {
Console.Write("\n"+list);
}
}
} | [
{
"code": null,
"e": 1139,
"s": 1062,
"text": "To implement Remove() and RemoveAt() methods in C#, try the following code −"
},
{
"code": null,
"e": 1160,
"s": 1139,
"text": "Firstly, set a list."
},
{
"code": null,
"e": 1268,
"s": 1160,
"text": "List<string> myList = new List<string>() {\n \"mammals\",\n \"reptiles\",\n \"amphibians\",\n \"vertebrate\"\n};"
},
{
"code": null,
"e": 1315,
"s": 1268,
"text": "Now, use Remove() method to remove an element."
},
{
"code": null,
"e": 1342,
"s": 1315,
"text": "myList.Remove(\"reptiles\");"
},
{
"code": null,
"e": 1415,
"s": 1342,
"text": "Now, use RemoveAt() method to remove an element by setting the position."
},
{
"code": null,
"e": 1435,
"s": 1415,
"text": "myList.RemoveAt(2);"
},
{
"code": null,
"e": 1472,
"s": 1435,
"text": "The following is the complete code −"
},
{
"code": null,
"e": 2181,
"s": 1472,
"text": "using System;\nusing System.Collections.Generic;\nusing System.Linq;\n\nclass Program {\n static void Main() {\n List<string> myList = new List<string>() {\n \"mammals\",\n \"reptiles\",\n \"amphibians\",\n \"vertebrate\"\n };\n\n Console.Write(\"Initial list...\");\n foreach (string list in myList) {\n Console.WriteLine(list);\n }\n\n Console.Write(\"Using Remove() method...\");\n myList.Remove(\"reptiles\");\n\n foreach (string list in myList) {\n Console.WriteLine(list);\n }\n\n Console.Write(\"Using RemoveAt() method...\");\n myList.RemoveAt(2);\n\n foreach (string list in myList) {\n Console.WriteLine(list);\n }\n }\n}"
},
{
"code": null,
"e": 2238,
"s": 2181,
"text": "Here is an example that implements RemoveRange() method."
},
{
"code": null,
"e": 2867,
"s": 2238,
"text": "using System;\nusing System.Collections.Generic;\nusing System.Linq;\n\nclass Program {\n static void Main() {\n List<int> myList = new List<int>();\n myList.Add(5);\n myList.Add(10);\n myList.Add(15);\n myList.Add(20);\n myList.Add(25);\n myList.Add(30);\n myList.Add(35);\n\n Console.Write(\"Initial list...\");\n foreach (int list in myList) {\n Console.WriteLine(list);\n }\n\n Console.Write(\"New list...\");\n int rem = Math.Max(0, myList.Count - 3);\n myList.RemoveRange(0, rem);\n\n foreach (int list in myList) {\n Console.Write(\"\\n\"+list);\n }\n }\n}"
}
] |
PostgreSQL - DROP Database | In this chapter, we will discuss how to delete the database in PostgreSQL. There are two options to delete a database −
Using DROP DATABASE, an SQL command.
Using dropdb a command-line executable.
This command drops a database. It removes the catalog entries for the database and deletes the directory containing the data. It can only be executed by the database owner. This command cannot be executed while you or anyone else is connected to the target database (connect to postgres or any other database to issue this command).
The syntax for DROP DATABASE is given below −
DROP DATABASE [ IF EXISTS ] name
The table lists the parameters with their descriptions.
IF EXISTS
Do not throw an error if the database does not exist. A notice is issued in this case.
name
The name of the database to remove.
The following is a simple example, which will delete testdb from your PostgreSQL schema −
postgres=# DROP DATABASE testdb;
postgres-#
PostgresSQL command line executable dropdb is a command-line wrapper around the SQL command DROP DATABASE. There is no effective difference between dropping databases via this utility and via other methods for accessing the server. dropdb destroys an existing PostgreSQL database. The user, who executes this command must be a database super user or the owner of the database.
The syntax for dropdb is as shown below −
dropdb [option...] dbname
The following table lists the parameters with their descriptions
dbname
The name of a database to be deleted.
option
command-line arguments, which dropdb accepts.
The following table lists the command-line arguments dropdb accepts −
-e
Shows the commands being sent to the server.
-i
Issues a verification prompt before doing anything destructive.
-V
Print the dropdb version and exit.
--if-exists
Do not throw an error if the database does not exist. A notice is issued in this case.
--help
Show help about dropdb command-line arguments, and exit.
-h host
Specifies the host name of the machine on which the server is running.
-p port
Specifies the TCP port or the local UNIX domain socket file extension on which the server is listening for connections.
-U username
User name to connect as.
-w
Never issue a password prompt.
-W
Force dropdb to prompt for a password before connecting to a database.
--maintenance-db=dbname
Specifies the name of the database to connect to in order to drop the target database.
The following example demonstrates deleting a database from OS command prompt −
dropdb -h localhost -p 5432 -U postgress testdb
Password for user postgress: ****
The above command drops the database testdb. Here, I have used the postgres (found under the pg_roles of template1) username to drop the database.
23 Lectures
1.5 hours
John Elder
49 Lectures
3.5 hours
Niyazi Erdogan
126 Lectures
10.5 hours
Abhishek And Pukhraj
35 Lectures
5 hours
Karthikeya T
5 Lectures
51 mins
Vinay Kumar
5 Lectures
52 mins
Vinay Kumar
Print
Add Notes
Bookmark this page | [
{
"code": null,
"e": 2945,
"s": 2825,
"text": "In this chapter, we will discuss how to delete the database in PostgreSQL. There are two options to delete a database −"
},
{
"code": null,
"e": 2982,
"s": 2945,
"text": "Using DROP DATABASE, an SQL command."
},
{
"code": null,
"e": 3022,
"s": 2982,
"text": "Using dropdb a command-line executable."
},
{
"code": null,
"e": 3355,
"s": 3022,
"text": "This command drops a database. It removes the catalog entries for the database and deletes the directory containing the data. It can only be executed by the database owner. This command cannot be executed while you or anyone else is connected to the target database (connect to postgres or any other database to issue this command)."
},
{
"code": null,
"e": 3401,
"s": 3355,
"text": "The syntax for DROP DATABASE is given below −"
},
{
"code": null,
"e": 3435,
"s": 3401,
"text": "DROP DATABASE [ IF EXISTS ] name\n"
},
{
"code": null,
"e": 3491,
"s": 3435,
"text": "The table lists the parameters with their descriptions."
},
{
"code": null,
"e": 3501,
"s": 3491,
"text": "IF EXISTS"
},
{
"code": null,
"e": 3588,
"s": 3501,
"text": "Do not throw an error if the database does not exist. A notice is issued in this case."
},
{
"code": null,
"e": 3593,
"s": 3588,
"text": "name"
},
{
"code": null,
"e": 3629,
"s": 3593,
"text": "The name of the database to remove."
},
{
"code": null,
"e": 3719,
"s": 3629,
"text": "The following is a simple example, which will delete testdb from your PostgreSQL schema −"
},
{
"code": null,
"e": 3764,
"s": 3719,
"text": "postgres=# DROP DATABASE testdb;\npostgres-# "
},
{
"code": null,
"e": 4141,
"s": 3764,
"text": "PostgresSQL command line executable dropdb is a command-line wrapper around the SQL command DROP DATABASE. There is no effective difference between dropping databases via this utility and via other methods for accessing the server. dropdb destroys an existing PostgreSQL database. The user, who executes this command must be a database super user or the owner of the database."
},
{
"code": null,
"e": 4183,
"s": 4141,
"text": "The syntax for dropdb is as shown below −"
},
{
"code": null,
"e": 4211,
"s": 4183,
"text": "dropdb [option...] dbname\n"
},
{
"code": null,
"e": 4276,
"s": 4211,
"text": "The following table lists the parameters with their descriptions"
},
{
"code": null,
"e": 4283,
"s": 4276,
"text": "dbname"
},
{
"code": null,
"e": 4321,
"s": 4283,
"text": "The name of a database to be deleted."
},
{
"code": null,
"e": 4328,
"s": 4321,
"text": "option"
},
{
"code": null,
"e": 4374,
"s": 4328,
"text": "command-line arguments, which dropdb accepts."
},
{
"code": null,
"e": 4444,
"s": 4374,
"text": "The following table lists the command-line arguments dropdb accepts −"
},
{
"code": null,
"e": 4447,
"s": 4444,
"text": "-e"
},
{
"code": null,
"e": 4492,
"s": 4447,
"text": "Shows the commands being sent to the server."
},
{
"code": null,
"e": 4495,
"s": 4492,
"text": "-i"
},
{
"code": null,
"e": 4559,
"s": 4495,
"text": "Issues a verification prompt before doing anything destructive."
},
{
"code": null,
"e": 4562,
"s": 4559,
"text": "-V"
},
{
"code": null,
"e": 4597,
"s": 4562,
"text": "Print the dropdb version and exit."
},
{
"code": null,
"e": 4609,
"s": 4597,
"text": "--if-exists"
},
{
"code": null,
"e": 4696,
"s": 4609,
"text": "Do not throw an error if the database does not exist. A notice is issued in this case."
},
{
"code": null,
"e": 4703,
"s": 4696,
"text": "--help"
},
{
"code": null,
"e": 4760,
"s": 4703,
"text": "Show help about dropdb command-line arguments, and exit."
},
{
"code": null,
"e": 4768,
"s": 4760,
"text": "-h host"
},
{
"code": null,
"e": 4839,
"s": 4768,
"text": "Specifies the host name of the machine on which the server is running."
},
{
"code": null,
"e": 4847,
"s": 4839,
"text": "-p port"
},
{
"code": null,
"e": 4967,
"s": 4847,
"text": "Specifies the TCP port or the local UNIX domain socket file extension on which the server is listening for connections."
},
{
"code": null,
"e": 4979,
"s": 4967,
"text": "-U username"
},
{
"code": null,
"e": 5004,
"s": 4979,
"text": "User name to connect as."
},
{
"code": null,
"e": 5007,
"s": 5004,
"text": "-w"
},
{
"code": null,
"e": 5038,
"s": 5007,
"text": "Never issue a password prompt."
},
{
"code": null,
"e": 5041,
"s": 5038,
"text": "-W"
},
{
"code": null,
"e": 5112,
"s": 5041,
"text": "Force dropdb to prompt for a password before connecting to a database."
},
{
"code": null,
"e": 5136,
"s": 5112,
"text": "--maintenance-db=dbname"
},
{
"code": null,
"e": 5223,
"s": 5136,
"text": "Specifies the name of the database to connect to in order to drop the target database."
},
{
"code": null,
"e": 5303,
"s": 5223,
"text": "The following example demonstrates deleting a database from OS command prompt −"
},
{
"code": null,
"e": 5385,
"s": 5303,
"text": "dropdb -h localhost -p 5432 -U postgress testdb\nPassword for user postgress: ****"
},
{
"code": null,
"e": 5532,
"s": 5385,
"text": "The above command drops the database testdb. Here, I have used the postgres (found under the pg_roles of template1) username to drop the database."
},
{
"code": null,
"e": 5567,
"s": 5532,
"text": "\n 23 Lectures \n 1.5 hours \n"
},
{
"code": null,
"e": 5579,
"s": 5567,
"text": " John Elder"
},
{
"code": null,
"e": 5614,
"s": 5579,
"text": "\n 49 Lectures \n 3.5 hours \n"
},
{
"code": null,
"e": 5630,
"s": 5614,
"text": " Niyazi Erdogan"
},
{
"code": null,
"e": 5667,
"s": 5630,
"text": "\n 126 Lectures \n 10.5 hours \n"
},
{
"code": null,
"e": 5689,
"s": 5667,
"text": " Abhishek And Pukhraj"
},
{
"code": null,
"e": 5722,
"s": 5689,
"text": "\n 35 Lectures \n 5 hours \n"
},
{
"code": null,
"e": 5736,
"s": 5722,
"text": " Karthikeya T"
},
{
"code": null,
"e": 5767,
"s": 5736,
"text": "\n 5 Lectures \n 51 mins\n"
},
{
"code": null,
"e": 5780,
"s": 5767,
"text": " Vinay Kumar"
},
{
"code": null,
"e": 5811,
"s": 5780,
"text": "\n 5 Lectures \n 52 mins\n"
},
{
"code": null,
"e": 5824,
"s": 5811,
"text": " Vinay Kumar"
},
{
"code": null,
"e": 5831,
"s": 5824,
"text": " Print"
},
{
"code": null,
"e": 5842,
"s": 5831,
"text": " Add Notes"
}
] |
Count-min sketch in Java with Examples - GeeksforGeeks | 27 Jun, 2021
The Count-min sketch is a probabilistic data structure. The Count-Min sketch is a simple technique to summarize large amounts of frequency data. Count-min sketch algorithm talks about keeping track of the count of things. i.e, How many times an element is present in the set. Finding the count of an item could be easily achieved in Java using HashTable or Map. Trying MultiSet as an alternative to Count-min sketch Let’s try to implement this data structure using MultiSet with the below source code and try to find out issues with this approach.
java
// Java program to try MultiSet as an// alternative to Count-min sketch import com.google.common.collect.HashMultiset;import com.google.common.collect.Multiset; public class MultiSetDemo { public static void main(String[] args) { Multiset<String> blackListedIPs = HashMultiset.create(); blackListedIPs.add("192.170.0.1"); blackListedIPs.add("75.245.10.1"); blackListedIPs.add("10.125.22.20"); blackListedIPs.add("192.170.0.1"); System.out.println(blackListedIPs .count("192.170.0.1")); System.out.println(blackListedIPs .count("10.125.22.20")); }}
Output:
Understanding the problem of using MultiSet Now let’s look at the time and space consumed with this type of approach.
----------------------------------------------
|Number of UUIDs Insertion Time(ms) |
----------------------------------------------
|10 <25 |
|100 <25 |
|1, 000 30 |
|10, 000 257 |
|100, 000 1200 |
|1, 000, 000 4244 |
----------------------------------------------
Let’s have a look at the memory (space) consumed:
----------------------------------------------
|Number of UUIDs JVM heap used(MB) |
----------------------------------------------
|10 <2 |
|100 <2 |
|1, 000 3 |
|10, 000 9 |
|100, 000 39 |
|1, 000, 000 234 |
-----------------------------------------------
We can easily understand that as data grows, the above approach is consuming a lot of memory and time to process the data. This can be optimized if we use count-min sketch algorithm.What is Count-min sketch and how does it work? Count-min sketch approach was proposed by Graham Cormode and S. Muthukrishnan. in the paper approximating data with the count-min sketch published in 2011/12. Count-min sketch is used to count the frequency of the events on the streaming data. Like Bloom filter, Count-min sketch algorithm also works with hash codes. It uses multiple hash functions to map these frequencies on to the matrix (Consider sketch here a two dimensional array or matrix).Let’s look at the below example step by step.
Consider below 2D array with 4 rows and 16 columns, also the number of rows is equal to the number of hash functions. That means we are taking four hash functions for our example. Initialize/mark each cell in the matrix with zero. Note: The more accurate result you want, the more number of hash function to be used.
Consider below 2D array with 4 rows and 16 columns, also the number of rows is equal to the number of hash functions. That means we are taking four hash functions for our example. Initialize/mark each cell in the matrix with zero. Note: The more accurate result you want, the more number of hash function to be used.
Now let’s add some element to it. To do so we have to pass that element with all four hash functions which will may result as follows.
Now let’s add some element to it. To do so we have to pass that element with all four hash functions which will may result as follows.
Input : 192.170.0.1
hashFunction1(192.170.0.1): 1
hashFunction2(192.170.0.1): 6
hashFunction3(192.170.0.1): 3
hashFunction4(192.170.0.1): 1
Now visit to the indexes retrieved above by all four hash function and mark them as 1.
Now visit to the indexes retrieved above by all four hash function and mark them as 1.
Similarly process second input by passing it to all four hash functions.
Similarly process second input by passing it to all four hash functions.
Input : 75.245.10.1
hashFunction1(75.245.10.1): 1
hashFunction2(75.245.10.1): 2
hashFunction3(75.245.10.1): 4
hashFunction4(75.245.10.1): 6
Now, take these indexes and visit the matrix, if the given index has already been marked as 1. This is called collision which means that, the index of that row was already marked by some previous inputs and in this case just increment the index value by 1. In our case, since we have already marked index 1 of row 1 i.e., hashFunction1() as 1 by previous input, so this time it will be incremented by 1 and now this cell entry will be 2, but for rest of the index of rest rows it will be 0, since there was no collision.
Now, take these indexes and visit the matrix, if the given index has already been marked as 1. This is called collision which means that, the index of that row was already marked by some previous inputs and in this case just increment the index value by 1. In our case, since we have already marked index 1 of row 1 i.e., hashFunction1() as 1 by previous input, so this time it will be incremented by 1 and now this cell entry will be 2, but for rest of the index of rest rows it will be 0, since there was no collision.
Let’s process next input
Let’s process next input
Input : 10.125.22.20
hashFunction1(10.125.22.20): 3
hashFunction2(10.125.22.20): 4
hashFunction3(10.125.22.20): 1
hashFunction4(10.125.22.20): 6
Lets, represent it on matrix, do remember to increment the count by 1 if already some entry exist.
Lets, represent it on matrix, do remember to increment the count by 1 if already some entry exist.
Similarly process next input.
Similarly process next input.
Input : 192.170.0.1
hashFunction1(192.170.0.1): 1
hashFunction2(192.170.0.1): 6
hashFunction3(192.170.0.1): 3
hashFunction4(192.170.0.1): 1
Let’s have a look on matrix representation.
Let’s have a look on matrix representation.
Now let’s test some element and check how many time are they present.
Test Input #1: 192.170.0.1
Pass above input to all four hash functions, and take the index numbers generated by hash functions.
Pass above input to all four hash functions, and take the index numbers generated by hash functions.
hashFunction1(192.170.0.1): 1
hashFunction2(192.170.0.1): 6
hashFunction3(192.170.0.1): 3
hashFunction4(192.170.0.1): 1
Now visit to each index and take note down the entry present on that index
Now visit to each index and take note down the entry present on that index
So the final entry on each index was 3, 2, 2, 2. Now take the minimum count among these entries and that is the result. So min(3, 2, 2, 2) is 2, that means the above test input is processed two times in the above list.
So the final entry on each index was 3, 2, 2, 2. Now take the minimum count among these entries and that is the result. So min(3, 2, 2, 2) is 2, that means the above test input is processed two times in the above list.
Test Input #1: 10.125.22.20
Pass above input to all four hash functions, and take the index numbers generated by hash functions.
Pass above input to all four hash functions, and take the index numbers generated by hash functions.
hashFunction1(10.125.22.20): 3
hashFunction2(10.125.22.20): 4
hashFunction3(10.125.22.20): 1
hashFunction4(10.125.22.20): 6
Now visit to each index and take note down the entry present on that index
Now visit to each index and take note down the entry present on that index
So the final entry on each index was 1, 1, 1, 2. Now take the minimum count among these entries and that is the result. So min(1, 1, 1, 2) is 1, that means the above test input is processed only once in the above list.
So the final entry on each index was 1, 1, 1, 2. Now take the minimum count among these entries and that is the result. So min(1, 1, 1, 2) is 1, that means the above test input is processed only once in the above list.
Issue with Count-min sketch and its solution: What if one or more elements got the same hash values and then they all incremented. So, in that case, the value would have been increased because of the hash collision. Thus sometimes (in very rare cases) Count-min sketch overcounts the frequencies because of the hash functions. So the more hash function we take there will be less collision. The fewer hash functions we take there will be a high probability of collision. Hence it always recommended taking more number of hash functions. Applications of Count-min sketch:
Compressed Sensing
Networking
NLP
Stream Processing
Frequency tracking
Extension: Heavy-hitters
Extension: Range-query
Implementation of Count-min sketch using Guava library in Java: We can implement the Count-min sketch using Java library provided by Guava. Below is the step by step implementation:
Use below maven dependency.
Use below maven dependency.
XML
<dependency> <groupId>com.clearspring.analytics</groupId> <artifactId>stream</artifactId> <version>2.9.5</version></dependency>
The detailed Java code is as follows:
The detailed Java code is as follows:
Java
import com.clearspring.analytics .stream.frequency.CountMinSketch; public class CountMinSketchDemo { public static void main(String[] args) { CountMinSketch countMinSketch = new CountMinSketch( // epsilon 0.001, // delta 0.99, // seed 1); countMinSketch.add("75.245.10.1", 1); countMinSketch.add("10.125.22.20", 1); countMinSketch.add("192.170.0.1", 2); System.out.println( countMinSketch .estimateCount( "192.170.0.1")); System.out.println( countMinSketch .estimateCount( "999.999.99.99")); }}
Above example takes three arguments in the constructor which are
Above example takes three arguments in the constructor which are
- 0.001 = the epsilon i.e., error rate
- 0.99 = the delta i.e., confidence or accuracy rate
- 1 = the seed
Now lets have a look at the time and space consumed with this approach.
Now lets have a look at the time and space consumed with this approach.
-----------------------------------------------------------------------------
|Number of UUIDs | Multiset Insertion Time(ms) | CMS Insertion Time(ms) |
-----------------------------------------------------------------------------
|10 <25 35 |
|100 <25 30 |
|1, 000 30 69 |
|10, 000 257 246 |
|100, 000 1200 970 |
|1, 000, 000 4244 4419 |
-----------------------------------------------------------------------------
Now, Let’s have a look of the memory consumed:
Now, Let’s have a look of the memory consumed:
--------------------------------------------------------------------------
|Number of UUIDs | Multiset JVM heap used(MB) | CMS JVM heap used(MB) |
--------------------------------------------------------------------------
|10 <2 N/A |
|100 <2 N/A |
|1, 000 3 N/A |
|10, 000 9 N/A |
|100, 000 39 N/A |
|1, 000, 000 234 N/A |
---------------------------------------------------------------------------
Suggestions:
Suggestions:
-------------------------------------------------------------------------------------
|Epsilon | Delta | width/Row (hash functions)| Depth/column| CMS JVM heap used(MB) |
-------------------------------------------------------------------------------------
|0.1 |0.99 | 7 | 20 | 0.009 |
|0.01 |0.999 | 10 | 100 | 0.02 |
|0.001 |0.9999 | 14 | 2000 | 0.2 |
|0.0001 |0.99999 | 17 | 20000 | 2 |
--------------------------------------------------------------------------------------
Conclusion:We have observed that the Count-min sketch is a good choice in a situation where we have to process a large data set with low memory consumption. We also saw that the more accurate result we want the number of hash functions(rows/width) has to be increased.
anikaseth98
Advanced Data Structure
Algorithms
Data Structures
Java
Data Structures
Java
Algorithms
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Decision Tree Introduction with example
Disjoint Set Data Structures
Red-Black Tree | Set 2 (Insert)
AVL Tree | Set 2 (Deletion)
Insert Operation in B-Tree
SDE SHEET - A Complete Guide for SDE Preparation
Top 50 Array Coding Problems for Interviews
DSA Sheet by Love Babbar
Difference between BFS and DFS
A* Search Algorithm | [
{
"code": null,
"e": 24644,
"s": 24616,
"text": "\n27 Jun, 2021"
},
{
"code": null,
"e": 25194,
"s": 24644,
"text": "The Count-min sketch is a probabilistic data structure. The Count-Min sketch is a simple technique to summarize large amounts of frequency data. Count-min sketch algorithm talks about keeping track of the count of things. i.e, How many times an element is present in the set. Finding the count of an item could be easily achieved in Java using HashTable or Map. Trying MultiSet as an alternative to Count-min sketch Let’s try to implement this data structure using MultiSet with the below source code and try to find out issues with this approach. "
},
{
"code": null,
"e": 25199,
"s": 25194,
"text": "java"
},
{
"code": "// Java program to try MultiSet as an// alternative to Count-min sketch import com.google.common.collect.HashMultiset;import com.google.common.collect.Multiset; public class MultiSetDemo { public static void main(String[] args) { Multiset<String> blackListedIPs = HashMultiset.create(); blackListedIPs.add(\"192.170.0.1\"); blackListedIPs.add(\"75.245.10.1\"); blackListedIPs.add(\"10.125.22.20\"); blackListedIPs.add(\"192.170.0.1\"); System.out.println(blackListedIPs .count(\"192.170.0.1\")); System.out.println(blackListedIPs .count(\"10.125.22.20\")); }}",
"e": 25877,
"s": 25199,
"text": null
},
{
"code": null,
"e": 25887,
"s": 25877,
"text": "Output: "
},
{
"code": null,
"e": 26007,
"s": 25887,
"text": "Understanding the problem of using MultiSet Now let’s look at the time and space consumed with this type of approach. "
},
{
"code": null,
"e": 26487,
"s": 26007,
"text": "----------------------------------------------\n|Number of UUIDs Insertion Time(ms) |\n----------------------------------------------\n|10 <25 | \n|100 <25 |\n|1, 000 30 |\n|10, 000 257 |\n|100, 000 1200 |\n|1, 000, 000 4244 |\n----------------------------------------------"
},
{
"code": null,
"e": 26539,
"s": 26487,
"text": "Let’s have a look at the memory (space) consumed: "
},
{
"code": null,
"e": 27020,
"s": 26539,
"text": "----------------------------------------------\n|Number of UUIDs JVM heap used(MB) |\n----------------------------------------------\n|10 <2 | \n|100 <2 |\n|1, 000 3 |\n|10, 000 9 |\n|100, 000 39 |\n|1, 000, 000 234 |\n-----------------------------------------------"
},
{
"code": null,
"e": 27746,
"s": 27020,
"text": "We can easily understand that as data grows, the above approach is consuming a lot of memory and time to process the data. This can be optimized if we use count-min sketch algorithm.What is Count-min sketch and how does it work? Count-min sketch approach was proposed by Graham Cormode and S. Muthukrishnan. in the paper approximating data with the count-min sketch published in 2011/12. Count-min sketch is used to count the frequency of the events on the streaming data. Like Bloom filter, Count-min sketch algorithm also works with hash codes. It uses multiple hash functions to map these frequencies on to the matrix (Consider sketch here a two dimensional array or matrix).Let’s look at the below example step by step. "
},
{
"code": null,
"e": 28065,
"s": 27746,
"text": "Consider below 2D array with 4 rows and 16 columns, also the number of rows is equal to the number of hash functions. That means we are taking four hash functions for our example. Initialize/mark each cell in the matrix with zero. Note: The more accurate result you want, the more number of hash function to be used. "
},
{
"code": null,
"e": 28384,
"s": 28065,
"text": "Consider below 2D array with 4 rows and 16 columns, also the number of rows is equal to the number of hash functions. That means we are taking four hash functions for our example. Initialize/mark each cell in the matrix with zero. Note: The more accurate result you want, the more number of hash function to be used. "
},
{
"code": null,
"e": 28522,
"s": 28384,
"text": " Now let’s add some element to it. To do so we have to pass that element with all four hash functions which will may result as follows. "
},
{
"code": null,
"e": 28661,
"s": 28524,
"text": "Now let’s add some element to it. To do so we have to pass that element with all four hash functions which will may result as follows. "
},
{
"code": null,
"e": 28682,
"s": 28661,
"text": "Input : 192.170.0.1 "
},
{
"code": null,
"e": 28806,
"s": 28686,
"text": "hashFunction1(192.170.0.1): 1\nhashFunction2(192.170.0.1): 6\nhashFunction3(192.170.0.1): 3\nhashFunction4(192.170.0.1): 1"
},
{
"code": null,
"e": 28895,
"s": 28806,
"text": "Now visit to the indexes retrieved above by all four hash function and mark them as 1. "
},
{
"code": null,
"e": 28984,
"s": 28895,
"text": "Now visit to the indexes retrieved above by all four hash function and mark them as 1. "
},
{
"code": null,
"e": 29060,
"s": 28984,
"text": " Similarly process second input by passing it to all four hash functions. "
},
{
"code": null,
"e": 29137,
"s": 29062,
"text": "Similarly process second input by passing it to all four hash functions. "
},
{
"code": null,
"e": 29158,
"s": 29137,
"text": "Input : 75.245.10.1 "
},
{
"code": null,
"e": 29282,
"s": 29162,
"text": "hashFunction1(75.245.10.1): 1\nhashFunction2(75.245.10.1): 2\nhashFunction3(75.245.10.1): 4\nhashFunction4(75.245.10.1): 6"
},
{
"code": null,
"e": 29805,
"s": 29282,
"text": "Now, take these indexes and visit the matrix, if the given index has already been marked as 1. This is called collision which means that, the index of that row was already marked by some previous inputs and in this case just increment the index value by 1. In our case, since we have already marked index 1 of row 1 i.e., hashFunction1() as 1 by previous input, so this time it will be incremented by 1 and now this cell entry will be 2, but for rest of the index of rest rows it will be 0, since there was no collision. "
},
{
"code": null,
"e": 30328,
"s": 29805,
"text": "Now, take these indexes and visit the matrix, if the given index has already been marked as 1. This is called collision which means that, the index of that row was already marked by some previous inputs and in this case just increment the index value by 1. In our case, since we have already marked index 1 of row 1 i.e., hashFunction1() as 1 by previous input, so this time it will be incremented by 1 and now this cell entry will be 2, but for rest of the index of rest rows it will be 0, since there was no collision. "
},
{
"code": null,
"e": 30356,
"s": 30328,
"text": " Let’s process next input "
},
{
"code": null,
"e": 30385,
"s": 30358,
"text": "Let’s process next input "
},
{
"code": null,
"e": 30407,
"s": 30385,
"text": "Input : 10.125.22.20 "
},
{
"code": null,
"e": 30535,
"s": 30411,
"text": "hashFunction1(10.125.22.20): 3\nhashFunction2(10.125.22.20): 4\nhashFunction3(10.125.22.20): 1\nhashFunction4(10.125.22.20): 6"
},
{
"code": null,
"e": 30635,
"s": 30535,
"text": "Lets, represent it on matrix, do remember to increment the count by 1 if already some entry exist. "
},
{
"code": null,
"e": 30735,
"s": 30635,
"text": "Lets, represent it on matrix, do remember to increment the count by 1 if already some entry exist. "
},
{
"code": null,
"e": 30768,
"s": 30735,
"text": " Similarly process next input. "
},
{
"code": null,
"e": 30802,
"s": 30770,
"text": "Similarly process next input. "
},
{
"code": null,
"e": 30823,
"s": 30802,
"text": "Input : 192.170.0.1 "
},
{
"code": null,
"e": 30947,
"s": 30827,
"text": "hashFunction1(192.170.0.1): 1\nhashFunction2(192.170.0.1): 6\nhashFunction3(192.170.0.1): 3\nhashFunction4(192.170.0.1): 1"
},
{
"code": null,
"e": 30993,
"s": 30947,
"text": "Let’s have a look on matrix representation. "
},
{
"code": null,
"e": 31039,
"s": 30993,
"text": "Let’s have a look on matrix representation. "
},
{
"code": null,
"e": 31115,
"s": 31043,
"text": "Now let’s test some element and check how many time are they present. "
},
{
"code": null,
"e": 31143,
"s": 31115,
"text": "Test Input #1: 192.170.0.1 "
},
{
"code": null,
"e": 31246,
"s": 31143,
"text": "Pass above input to all four hash functions, and take the index numbers generated by hash functions. "
},
{
"code": null,
"e": 31349,
"s": 31246,
"text": "Pass above input to all four hash functions, and take the index numbers generated by hash functions. "
},
{
"code": null,
"e": 31469,
"s": 31349,
"text": "hashFunction1(192.170.0.1): 1\nhashFunction2(192.170.0.1): 6\nhashFunction3(192.170.0.1): 3\nhashFunction4(192.170.0.1): 1"
},
{
"code": null,
"e": 31546,
"s": 31469,
"text": "Now visit to each index and take note down the entry present on that index "
},
{
"code": null,
"e": 31623,
"s": 31546,
"text": "Now visit to each index and take note down the entry present on that index "
},
{
"code": null,
"e": 31844,
"s": 31623,
"text": "So the final entry on each index was 3, 2, 2, 2. Now take the minimum count among these entries and that is the result. So min(3, 2, 2, 2) is 2, that means the above test input is processed two times in the above list. "
},
{
"code": null,
"e": 32065,
"s": 31844,
"text": "So the final entry on each index was 3, 2, 2, 2. Now take the minimum count among these entries and that is the result. So min(3, 2, 2, 2) is 2, that means the above test input is processed two times in the above list. "
},
{
"code": null,
"e": 32094,
"s": 32065,
"text": "Test Input #1: 10.125.22.20 "
},
{
"code": null,
"e": 32197,
"s": 32094,
"text": "Pass above input to all four hash functions, and take the index numbers generated by hash functions. "
},
{
"code": null,
"e": 32300,
"s": 32197,
"text": "Pass above input to all four hash functions, and take the index numbers generated by hash functions. "
},
{
"code": null,
"e": 32424,
"s": 32300,
"text": "hashFunction1(10.125.22.20): 3\nhashFunction2(10.125.22.20): 4\nhashFunction3(10.125.22.20): 1\nhashFunction4(10.125.22.20): 6"
},
{
"code": null,
"e": 32501,
"s": 32424,
"text": "Now visit to each index and take note down the entry present on that index "
},
{
"code": null,
"e": 32578,
"s": 32501,
"text": "Now visit to each index and take note down the entry present on that index "
},
{
"code": null,
"e": 32799,
"s": 32578,
"text": "So the final entry on each index was 1, 1, 1, 2. Now take the minimum count among these entries and that is the result. So min(1, 1, 1, 2) is 1, that means the above test input is processed only once in the above list. "
},
{
"code": null,
"e": 33020,
"s": 32799,
"text": "So the final entry on each index was 1, 1, 1, 2. Now take the minimum count among these entries and that is the result. So min(1, 1, 1, 2) is 1, that means the above test input is processed only once in the above list. "
},
{
"code": null,
"e": 33593,
"s": 33020,
"text": "Issue with Count-min sketch and its solution: What if one or more elements got the same hash values and then they all incremented. So, in that case, the value would have been increased because of the hash collision. Thus sometimes (in very rare cases) Count-min sketch overcounts the frequencies because of the hash functions. So the more hash function we take there will be less collision. The fewer hash functions we take there will be a high probability of collision. Hence it always recommended taking more number of hash functions. Applications of Count-min sketch: "
},
{
"code": null,
"e": 33612,
"s": 33593,
"text": "Compressed Sensing"
},
{
"code": null,
"e": 33623,
"s": 33612,
"text": "Networking"
},
{
"code": null,
"e": 33627,
"s": 33623,
"text": "NLP"
},
{
"code": null,
"e": 33645,
"s": 33627,
"text": "Stream Processing"
},
{
"code": null,
"e": 33664,
"s": 33645,
"text": "Frequency tracking"
},
{
"code": null,
"e": 33689,
"s": 33664,
"text": "Extension: Heavy-hitters"
},
{
"code": null,
"e": 33712,
"s": 33689,
"text": "Extension: Range-query"
},
{
"code": null,
"e": 33896,
"s": 33712,
"text": "Implementation of Count-min sketch using Guava library in Java: We can implement the Count-min sketch using Java library provided by Guava. Below is the step by step implementation: "
},
{
"code": null,
"e": 33925,
"s": 33896,
"text": "Use below maven dependency. "
},
{
"code": null,
"e": 33954,
"s": 33925,
"text": "Use below maven dependency. "
},
{
"code": null,
"e": 33958,
"s": 33954,
"text": "XML"
},
{
"code": "<dependency> <groupId>com.clearspring.analytics</groupId> <artifactId>stream</artifactId> <version>2.9.5</version></dependency>",
"e": 34095,
"s": 33958,
"text": null
},
{
"code": null,
"e": 34136,
"s": 34095,
"text": " The detailed Java code is as follows: "
},
{
"code": null,
"e": 34178,
"s": 34138,
"text": "The detailed Java code is as follows: "
},
{
"code": null,
"e": 34183,
"s": 34178,
"text": "Java"
},
{
"code": "import com.clearspring.analytics .stream.frequency.CountMinSketch; public class CountMinSketchDemo { public static void main(String[] args) { CountMinSketch countMinSketch = new CountMinSketch( // epsilon 0.001, // delta 0.99, // seed 1); countMinSketch.add(\"75.245.10.1\", 1); countMinSketch.add(\"10.125.22.20\", 1); countMinSketch.add(\"192.170.0.1\", 2); System.out.println( countMinSketch .estimateCount( \"192.170.0.1\")); System.out.println( countMinSketch .estimateCount( \"999.999.99.99\")); }}",
"e": 34925,
"s": 34183,
"text": null
},
{
"code": null,
"e": 34997,
"s": 34929,
"text": " Above example takes three arguments in the constructor which are "
},
{
"code": null,
"e": 35066,
"s": 34999,
"text": "Above example takes three arguments in the constructor which are "
},
{
"code": null,
"e": 35173,
"s": 35066,
"text": "- 0.001 = the epsilon i.e., error rate\n- 0.99 = the delta i.e., confidence or accuracy rate\n- 1 = the seed"
},
{
"code": null,
"e": 35248,
"s": 35173,
"text": " Now lets have a look at the time and space consumed with this approach. "
},
{
"code": null,
"e": 35324,
"s": 35250,
"text": "Now lets have a look at the time and space consumed with this approach. "
},
{
"code": null,
"e": 36107,
"s": 35324,
"text": "-----------------------------------------------------------------------------\n|Number of UUIDs | Multiset Insertion Time(ms) | CMS Insertion Time(ms) |\n-----------------------------------------------------------------------------\n|10 <25 35 | \n|100 <25 30 |\n|1, 000 30 69 |\n|10, 000 257 246 |\n|100, 000 1200 970 |\n|1, 000, 000 4244 4419 |\n-----------------------------------------------------------------------------"
},
{
"code": null,
"e": 36157,
"s": 36107,
"text": " Now, Let’s have a look of the memory consumed: "
},
{
"code": null,
"e": 36208,
"s": 36159,
"text": "Now, Let’s have a look of the memory consumed: "
},
{
"code": null,
"e": 36963,
"s": 36208,
"text": "--------------------------------------------------------------------------\n|Number of UUIDs | Multiset JVM heap used(MB) | CMS JVM heap used(MB) | \n--------------------------------------------------------------------------\n|10 <2 N/A | \n|100 <2 N/A |\n|1, 000 3 N/A |\n|10, 000 9 N/A |\n|100, 000 39 N/A |\n|1, 000, 000 234 N/A |\n---------------------------------------------------------------------------"
},
{
"code": null,
"e": 36979,
"s": 36963,
"text": " Suggestions: "
},
{
"code": null,
"e": 36996,
"s": 36981,
"text": "Suggestions: "
},
{
"code": null,
"e": 37691,
"s": 36996,
"text": "-------------------------------------------------------------------------------------\n|Epsilon | Delta | width/Row (hash functions)| Depth/column| CMS JVM heap used(MB) |\n-------------------------------------------------------------------------------------\n|0.1 |0.99 | 7 | 20 | 0.009 |\n|0.01 |0.999 | 10 | 100 | 0.02 |\n|0.001 |0.9999 | 14 | 2000 | 0.2 |\n|0.0001 |0.99999 | 17 | 20000 | 2 | \n--------------------------------------------------------------------------------------"
},
{
"code": null,
"e": 37961,
"s": 37691,
"text": "Conclusion:We have observed that the Count-min sketch is a good choice in a situation where we have to process a large data set with low memory consumption. We also saw that the more accurate result we want the number of hash functions(rows/width) has to be increased. "
},
{
"code": null,
"e": 37973,
"s": 37961,
"text": "anikaseth98"
},
{
"code": null,
"e": 37997,
"s": 37973,
"text": "Advanced Data Structure"
},
{
"code": null,
"e": 38008,
"s": 37997,
"text": "Algorithms"
},
{
"code": null,
"e": 38024,
"s": 38008,
"text": "Data Structures"
},
{
"code": null,
"e": 38029,
"s": 38024,
"text": "Java"
},
{
"code": null,
"e": 38045,
"s": 38029,
"text": "Data Structures"
},
{
"code": null,
"e": 38050,
"s": 38045,
"text": "Java"
},
{
"code": null,
"e": 38061,
"s": 38050,
"text": "Algorithms"
},
{
"code": null,
"e": 38159,
"s": 38061,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 38199,
"s": 38159,
"text": "Decision Tree Introduction with example"
},
{
"code": null,
"e": 38228,
"s": 38199,
"text": "Disjoint Set Data Structures"
},
{
"code": null,
"e": 38260,
"s": 38228,
"text": "Red-Black Tree | Set 2 (Insert)"
},
{
"code": null,
"e": 38288,
"s": 38260,
"text": "AVL Tree | Set 2 (Deletion)"
},
{
"code": null,
"e": 38315,
"s": 38288,
"text": "Insert Operation in B-Tree"
},
{
"code": null,
"e": 38364,
"s": 38315,
"text": "SDE SHEET - A Complete Guide for SDE Preparation"
},
{
"code": null,
"e": 38408,
"s": 38364,
"text": "Top 50 Array Coding Problems for Interviews"
},
{
"code": null,
"e": 38433,
"s": 38408,
"text": "DSA Sheet by Love Babbar"
},
{
"code": null,
"e": 38464,
"s": 38433,
"text": "Difference between BFS and DFS"
}
] |
Passing Information Using POST Method in Python | A generally more reliable method of passing information to a CGI program is the POST method. This packages the information in exactly the same way as GET methods, but instead of sending it as a text string after a ? in the URL it sends it as a separate message. This message comes into the CGI script in the form of the standard input.
Below is same hello_get.py script which handles GET as well as POST method.
#!/usr/bin/python
Import modules for CGI handling
import cgi, cgitb
# Create instance of FieldStorage
form = cgi.FieldStorage()
# Get data from fields
first_name = form.getvalue('first_name')
last_name = form.getvalue('last_name')
print "Content-type:text/html\r\n\r\n"
print "<html>"
print "<head>"
print "<title>Hello - Second CGI Program</title>"
print "</head>"
print "<body>"
print "<h2>Hello %s %s</h2>" % (first_name, last_name)
print "</body>"
print "</html>"
Let us take again same example as above which passes two values using HTML FORM and submit button. We use same CGI script hello_get.py to handle this input.
<form action = "/cgi-bin/hello_get.py" method = "post">
First Name: <input type = "text" name = "first_name"><br />
Last Name: <input type = "text" name = "last_name" />
<input type = "submit" value = "Submit" />
</form>
Here is the actual output of the above form. You enter First and Last Name and then click submit button to see the result. | [
{
"code": null,
"e": 1398,
"s": 1062,
"text": "A generally more reliable method of passing information to a CGI program is the POST method. This packages the information in exactly the same way as GET methods, but instead of sending it as a text string after a ? in the URL it sends it as a separate message. This message comes into the CGI script in the form of the standard input."
},
{
"code": null,
"e": 1474,
"s": 1398,
"text": "Below is same hello_get.py script which handles GET as well as POST method."
},
{
"code": null,
"e": 1942,
"s": 1474,
"text": "#!/usr/bin/python\nImport modules for CGI handling\nimport cgi, cgitb\n# Create instance of FieldStorage\nform = cgi.FieldStorage()\n# Get data from fields\nfirst_name = form.getvalue('first_name')\nlast_name = form.getvalue('last_name')\nprint \"Content-type:text/html\\r\\n\\r\\n\"\nprint \"<html>\"\nprint \"<head>\"\nprint \"<title>Hello - Second CGI Program</title>\"\nprint \"</head>\"\nprint \"<body>\"\nprint \"<h2>Hello %s %s</h2>\" % (first_name, last_name)\nprint \"</body>\"\nprint \"</html>\""
},
{
"code": null,
"e": 2099,
"s": 1942,
"text": "Let us take again same example as above which passes two values using HTML FORM and submit button. We use same CGI script hello_get.py to handle this input."
},
{
"code": null,
"e": 2320,
"s": 2099,
"text": "<form action = \"/cgi-bin/hello_get.py\" method = \"post\">\nFirst Name: <input type = \"text\" name = \"first_name\"><br />\nLast Name: <input type = \"text\" name = \"last_name\" />\n<input type = \"submit\" value = \"Submit\" />\n</form>"
},
{
"code": null,
"e": 2443,
"s": 2320,
"text": "Here is the actual output of the above form. You enter First and Last Name and then click submit button to see the result."
}
] |
What are Closures in JavaScript? | Closures in JavaScript allow us to access outer function scope from inner function even after the outer function has executed and returned. This means that the inner function will always have access to the outer function variable.
Following is the code for closures in JavaScript −
Live Demo
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Document</title>
<style>
body {
font-family: "Segoe UI", Tahoma, Geneva, Verdana, sans-serif;
}
.result {
font-size: 20px;
font-weight: 500;
}
</style>
</head>
<body>
<h1>JavaScript Closures</h1>
<div style="color: green;" class="result"></div>
<button class="Btn">CLICK HERE</button>
<h3>Click on the above button to add two numbers using closure</h3>
<script>
let sampleEle = document.querySelector(".sample");
let resEle = document.querySelector(".result");
function add(num) {
return function add1(num1) {
resEle.innerHTML += `${num}+${num1} = ${num + num1}`;
};
}
document.querySelector(".Btn").addEventListener("click", () => {
let storeadd = add(99);
storeadd(44);
});
</script>
</body>
</html>
On clicking the ‘CLICK HERE’ button − | [
{
"code": null,
"e": 1293,
"s": 1062,
"text": "Closures in JavaScript allow us to access outer function scope from inner function even after the outer function has executed and returned. This means that the inner function will always have access to the outer function variable."
},
{
"code": null,
"e": 1344,
"s": 1293,
"text": "Following is the code for closures in JavaScript −"
},
{
"code": null,
"e": 1355,
"s": 1344,
"text": " Live Demo"
},
{
"code": null,
"e": 2283,
"s": 1355,
"text": "<!DOCTYPE html>\n<html lang=\"en\">\n<head>\n<meta charset=\"UTF-8\" />\n<meta name=\"viewport\" content=\"width=device-width, initial-scale=1.0\" />\n<title>Document</title>\n<style>\n body {\n font-family: \"Segoe UI\", Tahoma, Geneva, Verdana, sans-serif;\n }\n .result {\n font-size: 20px;\n font-weight: 500;\n }\n</style>\n</head>\n<body>\n<h1>JavaScript Closures</h1>\n<div style=\"color: green;\" class=\"result\"></div>\n<button class=\"Btn\">CLICK HERE</button>\n<h3>Click on the above button to add two numbers using closure</h3>\n<script>\n let sampleEle = document.querySelector(\".sample\");\n let resEle = document.querySelector(\".result\");\n function add(num) {\n return function add1(num1) {\n resEle.innerHTML += `${num}+${num1} = ${num + num1}`;\n };\n }\n document.querySelector(\".Btn\").addEventListener(\"click\", () => {\n let storeadd = add(99);\n storeadd(44);\n });\n</script>\n</body>\n</html>"
},
{
"code": null,
"e": 2321,
"s": 2283,
"text": "On clicking the ‘CLICK HERE’ button −"
}
] |
How to remove a common suffix from column names in an R data frame? | To remove a common suffix from column names we can use gsub function. For example, if we have a data frame df that contains column defined as x1df, x2df, x3df, and x4df then we can remove df from all the column names by using the below command:
colnames(df)<-gsub("df","",colnames(df))
Consider the below data frame:
Live Demo
> x1Data<-rnorm(20,25,4)
> x2Data<-rnorm(20,25,1.2)
> x3Data<-runif(20,2,5)
> df1<-data.frame(x1Data,x2Data,x3Data)
> df1
x1Data x2Data x3Data
1 29.26500 26.64124 2.598983
2 21.82170 23.41442 4.134393
3 22.71918 25.21586 4.442823
4 19.88633 25.23487 3.338448
5 20.48989 23.33683 3.829757
6 29.07910 25.54084 3.519393
7 24.28573 23.67258 4.667397
8 27.99849 22.97148 4.100405
9 23.48148 25.36574 2.618030
10 26.39401 23.80191 4.235092
11 29.39867 24.36261 2.782559
12 30.11137 24.62702 4.873779
13 23.56623 25.29017 2.255684
14 24.18464 25.59862 2.247147
15 23.35541 25.38190 4.704027
16 25.02549 25.76776 4.706971
17 18.24187 23.53798 2.411423
18 24.12003 25.27751 2.137409
19 27.58055 24.80092 3.992380
20 23.70832 25.73701 2.577801
Removing the word Data from column names of data frame df1:
> colnames(df1)<-gsub("Data","",colnames(df1))
> df1
x1 x2 x3
1 29.26500 26.64124 2.598983
2 21.82170 23.41442 4.134393
3 22.71918 25.21586 4.442823
4 19.88633 25.23487 3.338448
5 20.48989 23.33683 3.829757
6 29.07910 25.54084 3.519393
7 24.28573 23.67258 4.667397
8 27.99849 22.97148 4.100405
9 23.48148 25.36574 2.618030
10 26.39401 23.80191 4.235092
11 29.39867 24.36261 2.782559
12 30.11137 24.62702 4.873779
13 23.56623 25.29017 2.255684
14 24.18464 25.59862 2.247147
15 23.35541 25.38190 4.704027
16 25.02549 25.76776 4.706971
17 18.24187 23.53798 2.411423
18 24.12003 25.27751 2.137409
19 27.58055 24.80092 3.992380
20 23.70832 25.73701 2.577801
Let’s have a look at another example:
Live Demo
> a_treatment<-rpois(20,5)
> b_treatment<-rpois(20,10)
> c_treatment<-rpois(20,2)
> d_treatment<-rpois(20,8)
> df2<-data.frame(a_treatment,b_treatment,c_treatment,d_treatment)
> df2
a_treatment b_treatment c_treatment d_treatment
1 3 18 3 4
2 1 9 1 5
3 3 13 0 5
4 2 14 0 9
5 4 9 1 10
6 6 8 0 8
7 4 7 5 9
8 2 13 1 8
9 5 4 4 7
10 6 11 1 7
11 4 9 3 12
12 7 6 4 10
13 6 20 3 6
14 4 10 1 4
15 13 11 0 12
16 6 11 1 10
17 6 8 1 16
18 4 8 1 14
19 8 11 2 8
20 3 7 0 9
Removing the word _treatment from column names of data frame df2:
> colnames(df2)<-gsub("_treatment","",colnames(df2))
> df2
a b c d
1 3 18 3 4
2 1 9 1 5
3 3 13 0 5
4 2 14 0 9
5 4 9 1 10
6 6 8 0 8
7 4 7 5 9
8 2 13 1 8
9 5 4 4 7
10 6 11 1 7
11 4 9 3 12
12 7 6 4 10
13 6 20 3 6
14 4 10 1 4
15 13 11 0 12
16 6 11 1 10
17 6 8 1 16
18 4 8 1 14
19 8 11 2 8
20 3 7 0 9 | [
{
"code": null,
"e": 1307,
"s": 1062,
"text": "To remove a common suffix from column names we can use gsub function. For example, if we have a data frame df that contains column defined as x1df, x2df, x3df, and x4df then we can remove df from all the column names by using the below command:"
},
{
"code": null,
"e": 1348,
"s": 1307,
"text": "colnames(df)<-gsub(\"df\",\"\",colnames(df))"
},
{
"code": null,
"e": 1379,
"s": 1348,
"text": "Consider the below data frame:"
},
{
"code": null,
"e": 1389,
"s": 1379,
"text": "Live Demo"
},
{
"code": null,
"e": 1511,
"s": 1389,
"text": "> x1Data<-rnorm(20,25,4)\n> x2Data<-rnorm(20,25,1.2)\n> x3Data<-runif(20,2,5)\n> df1<-data.frame(x1Data,x2Data,x3Data)\n> df1"
},
{
"code": null,
"e": 2123,
"s": 1511,
"text": "x1Data x2Data x3Data\n1 29.26500 26.64124 2.598983\n2 21.82170 23.41442 4.134393\n3 22.71918 25.21586 4.442823\n4 19.88633 25.23487 3.338448\n5 20.48989 23.33683 3.829757\n6 29.07910 25.54084 3.519393\n7 24.28573 23.67258 4.667397\n8 27.99849 22.97148 4.100405\n9 23.48148 25.36574 2.618030\n10 26.39401 23.80191 4.235092\n11 29.39867 24.36261 2.782559\n12 30.11137 24.62702 4.873779\n13 23.56623 25.29017 2.255684\n14 24.18464 25.59862 2.247147\n15 23.35541 25.38190 4.704027\n16 25.02549 25.76776 4.706971\n17 18.24187 23.53798 2.411423\n18 24.12003 25.27751 2.137409\n19 27.58055 24.80092 3.992380\n20 23.70832 25.73701 2.577801"
},
{
"code": null,
"e": 2183,
"s": 2123,
"text": "Removing the word Data from column names of data frame df1:"
},
{
"code": null,
"e": 2236,
"s": 2183,
"text": "> colnames(df1)<-gsub(\"Data\",\"\",colnames(df1))\n> df1"
},
{
"code": null,
"e": 2836,
"s": 2236,
"text": "x1 x2 x3\n1 29.26500 26.64124 2.598983\n2 21.82170 23.41442 4.134393\n3 22.71918 25.21586 4.442823\n4 19.88633 25.23487 3.338448\n5 20.48989 23.33683 3.829757\n6 29.07910 25.54084 3.519393\n7 24.28573 23.67258 4.667397\n8 27.99849 22.97148 4.100405\n9 23.48148 25.36574 2.618030\n10 26.39401 23.80191 4.235092\n11 29.39867 24.36261 2.782559\n12 30.11137 24.62702 4.873779\n13 23.56623 25.29017 2.255684\n14 24.18464 25.59862 2.247147\n15 23.35541 25.38190 4.704027\n16 25.02549 25.76776 4.706971\n17 18.24187 23.53798 2.411423\n18 24.12003 25.27751 2.137409\n19 27.58055 24.80092 3.992380\n20 23.70832 25.73701 2.577801"
},
{
"code": null,
"e": 2874,
"s": 2836,
"text": "Let’s have a look at another example:"
},
{
"code": null,
"e": 2884,
"s": 2874,
"text": "Live Demo"
},
{
"code": null,
"e": 3066,
"s": 2884,
"text": "> a_treatment<-rpois(20,5)\n> b_treatment<-rpois(20,10)\n> c_treatment<-rpois(20,2)\n> d_treatment<-rpois(20,8)\n> df2<-data.frame(a_treatment,b_treatment,c_treatment,d_treatment)\n> df2"
},
{
"code": null,
"e": 3343,
"s": 3066,
"text": "a_treatment b_treatment c_treatment d_treatment\n1 3 18 3 4\n2 1 9 1 5\n3 3 13 0 5\n4 2 14 0 9\n5 4 9 1 10\n6 6 8 0 8\n7 4 7 5 9\n8 2 13 1 8\n9 5 4 4 7\n10 6 11 1 7\n11 4 9 3 12\n12 7 6 4 10\n13 6 20 3 6\n14 4 10 1 4\n15 13 11 0 12\n16 6 11 1 10\n17 6 8 1 16\n18 4 8 1 14\n19 8 11 2 8\n20 3 7 0 9"
},
{
"code": null,
"e": 3409,
"s": 3343,
"text": "Removing the word _treatment from column names of data frame df2:"
},
{
"code": null,
"e": 3468,
"s": 3409,
"text": "> colnames(df2)<-gsub(\"_treatment\",\"\",colnames(df2))\n> df2"
},
{
"code": null,
"e": 3705,
"s": 3468,
"text": "a b c d\n1 3 18 3 4\n2 1 9 1 5\n3 3 13 0 5\n4 2 14 0 9\n5 4 9 1 10\n6 6 8 0 8\n7 4 7 5 9\n8 2 13 1 8\n9 5 4 4 7\n10 6 11 1 7\n11 4 9 3 12\n12 7 6 4 10\n13 6 20 3 6\n14 4 10 1 4\n15 13 11 0 12\n16 6 11 1 10\n17 6 8 1 16\n18 4 8 1 14\n19 8 11 2 8\n20 3 7 0 9"
}
] |
D3.js log.tickFormat() Function - GeeksforGeeks | 03 Sep, 2020
The log.tickFormat() function is used to format the ticks returned by log.ticks() function. This function is similar to pow.tickFormat(), the only difference is that this function is customized for the logarithmic scale. If there are too many ticks, the formatter may return the empty string for some ticks so to avoid this set the count equal to infinity.
Syntax:
log.tickFormat([count[, specifier]]);
Parameters: This function accepts two parameters as mentioned above and described below:
count: It is the number of tick values.
specifier: A specifier is a string of format type “s”.
Return Values: This function does not return anything.
Below given are a few examples of the function given above.
Example 1:
<!DOCTYPE html><html lang="en"> <head> <meta charset="UTF-8" /> <meta name="viewport" path1tent="width=device-width, initial-scale=1.0" /> <script src="https://d3js.org/d3.v4.min.js"> </script> <script src="https://d3js.org/d3-color.v1.min.js"> </script> <script src="https://d3js.org/d3-interpolate.v1.min.js"> </script> <script src="https://d3js.org/d3-scale-chromatic.v1.min.js"> </script></head> <body> <h1 style="color:green;"> Geeks for geeks </h1> <p>log.tickFormat() Function</p> <script> var log = d3.scaleLog() .domain([1, 14]) .range([1, 2, 3, 4]); var ticks = log.ticks(2); var tickFormat = log.tickFormat(2, "$, f"); document.write("<h3>" + ticks.map(tickFormat) + "</h3>"); </script></body> </html>
Output:
Example 2:
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8" /> <meta name="viewport" path1tent="width=device-width, initial-scale=1.0"/> <script src="https://d3js.org/d3.v4.min.js"> </script> <script src="https://d3js.org/d3-color.v1.min.js"> </script> <script src="https://d3js.org/d3-interpolate.v1.min.js"> </script> <script src="https://d3js.org/d3-scale-chromatic.v1.min.js"> </script> </head> <body> <h1 style="color:green;"> Geeks for geeks </h2> <p>log.tickFormat() Function </p> <script> var log = d3.scaleLog() .domain([1, 14]) .range([1, 2, 3, 4]); var ticks = log.ticks(Infinity); var tickFormat = log.tickFormat(Infinity, "$"); document.write("<h3>" + ticks.map(tickFormat) + "</h3>"); </script> </body> </html>
Output:
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
Difference Between PUT and PATCH Request
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": 26199,
"s": 26171,
"text": "\n03 Sep, 2020"
},
{
"code": null,
"e": 26556,
"s": 26199,
"text": "The log.tickFormat() function is used to format the ticks returned by log.ticks() function. This function is similar to pow.tickFormat(), the only difference is that this function is customized for the logarithmic scale. If there are too many ticks, the formatter may return the empty string for some ticks so to avoid this set the count equal to infinity."
},
{
"code": null,
"e": 26564,
"s": 26556,
"text": "Syntax:"
},
{
"code": null,
"e": 26602,
"s": 26564,
"text": "log.tickFormat([count[, specifier]]);"
},
{
"code": null,
"e": 26691,
"s": 26602,
"text": "Parameters: This function accepts two parameters as mentioned above and described below:"
},
{
"code": null,
"e": 26731,
"s": 26691,
"text": "count: It is the number of tick values."
},
{
"code": null,
"e": 26786,
"s": 26731,
"text": "specifier: A specifier is a string of format type “s”."
},
{
"code": null,
"e": 26841,
"s": 26786,
"text": "Return Values: This function does not return anything."
},
{
"code": null,
"e": 26901,
"s": 26841,
"text": "Below given are a few examples of the function given above."
},
{
"code": null,
"e": 26912,
"s": 26901,
"text": "Example 1:"
},
{
"code": "<!DOCTYPE html><html lang=\"en\"> <head> <meta charset=\"UTF-8\" /> <meta name=\"viewport\" path1tent=\"width=device-width, initial-scale=1.0\" /> <script src=\"https://d3js.org/d3.v4.min.js\"> </script> <script src=\"https://d3js.org/d3-color.v1.min.js\"> </script> <script src=\"https://d3js.org/d3-interpolate.v1.min.js\"> </script> <script src=\"https://d3js.org/d3-scale-chromatic.v1.min.js\"> </script></head> <body> <h1 style=\"color:green;\"> Geeks for geeks </h1> <p>log.tickFormat() Function</p> <script> var log = d3.scaleLog() .domain([1, 14]) .range([1, 2, 3, 4]); var ticks = log.ticks(2); var tickFormat = log.tickFormat(2, \"$, f\"); document.write(\"<h3>\" + ticks.map(tickFormat) + \"</h3>\"); </script></body> </html>",
"e": 27753,
"s": 26912,
"text": null
},
{
"code": null,
"e": 27761,
"s": 27753,
"text": "Output:"
},
{
"code": null,
"e": 27772,
"s": 27761,
"text": "Example 2:"
},
{
"code": "<!DOCTYPE html> <html lang=\"en\"> <head> <meta charset=\"UTF-8\" /> <meta name=\"viewport\" path1tent=\"width=device-width, initial-scale=1.0\"/> <script src=\"https://d3js.org/d3.v4.min.js\"> </script> <script src=\"https://d3js.org/d3-color.v1.min.js\"> </script> <script src=\"https://d3js.org/d3-interpolate.v1.min.js\"> </script> <script src=\"https://d3js.org/d3-scale-chromatic.v1.min.js\"> </script> </head> <body> <h1 style=\"color:green;\"> Geeks for geeks </h2> <p>log.tickFormat() Function </p> <script> var log = d3.scaleLog() .domain([1, 14]) .range([1, 2, 3, 4]); var ticks = log.ticks(Infinity); var tickFormat = log.tickFormat(Infinity, \"$\"); document.write(\"<h3>\" + ticks.map(tickFormat) + \"</h3>\"); </script> </body> </html>",
"e": 28648,
"s": 27772,
"text": null
},
{
"code": null,
"e": 28656,
"s": 28648,
"text": "Output:"
},
{
"code": null,
"e": 28662,
"s": 28656,
"text": "D3.js"
},
{
"code": null,
"e": 28673,
"s": 28662,
"text": "JavaScript"
},
{
"code": null,
"e": 28690,
"s": 28673,
"text": "Web Technologies"
},
{
"code": null,
"e": 28788,
"s": 28690,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 28828,
"s": 28788,
"text": "Remove elements from a JavaScript Array"
},
{
"code": null,
"e": 28873,
"s": 28828,
"text": "Convert a string to an integer in JavaScript"
},
{
"code": null,
"e": 28934,
"s": 28873,
"text": "Difference between var, let and const keywords in JavaScript"
},
{
"code": null,
"e": 29006,
"s": 28934,
"text": "Differences between Functional Components and Class Components in React"
},
{
"code": null,
"e": 29047,
"s": 29006,
"text": "Difference Between PUT and PATCH Request"
},
{
"code": null,
"e": 29087,
"s": 29047,
"text": "Remove elements from a JavaScript Array"
},
{
"code": null,
"e": 29120,
"s": 29087,
"text": "Installation of Node.js on Linux"
},
{
"code": null,
"e": 29165,
"s": 29120,
"text": "Convert a string to an integer in JavaScript"
},
{
"code": null,
"e": 29208,
"s": 29165,
"text": "How to fetch data from an API in ReactJS ?"
}
] |
How does Query.prototype.explain() work in Mongoose? - GeeksforGeeks | 17 Mar, 2021
The Query.prototype.explain() function is used to set the explain option thereby making this query return detailed execution stats instead of the actual query result.
Syntax:
Query.prototype.explain()
Parameters: This function has one optional verbose parameter.Return Value: This function returns Query Object.
Installing mongoose :
npm install mongoose
After installing the mongoose module, you can check your mongoose version in command prompt using the command.
npm mongoose --version
Now, create a folder and add a file for example, index.js as shown below.
Database: The sample database used here is shown below:
Project Structure: The project structure will look like this.
Example 1:
index.js
const mongoose = require('mongoose'); // Database connectionmongoose.connect('mongodb://127.0.0.1:27017/geeksforgeeks', { useNewUrlParser: true, useCreateIndex: true, useUnifiedTopology: true}); // User modelconst User = mongoose.model('User', { name: { type: String }, age: { type: Number }}); var query = User.find({age: 5}).explain('queryPlanner')query.exec(function(err, res){ if(err) console.log(err.message) else console.log(res)});
Run index.js file using below command:
node index.js
Output :
[
{
queryPlanner: {
plannerVersion: 1,
namespace: 'geeksforgeeks.users',
indexFilterSet: false,
parsedQuery: [Object],
queryHash: '3838C5A3',
planCacheKey: '38305F3',
winningPlan: [Object],
rejectedPlans: []
},
executionStats: {
executionSuccess: true,
nReturned: 1,
executionTimeMillis: 0,
totalKeysExamined: 0,
totalDocsExamined: 4,
executionStages: [Object],
allPlansExecution: []
},
serverInfo: {
host: 'Lenovo530S',
port: 27017,
version: '4.2.0',
gitVersion: 'a4b751dcf51dd249c58812b390cfd1c0129c30'
},
ok: 1
}
]
Example 2:
index.js
const express = require('express');const mongoose = require('mongoose');const app = express() // Database connectionmongoose.connect('mongodb://127.0.0.1:27017/geeksforgeeks', { useNewUrlParser: true, useCreateIndex: true, useUnifiedTopology: true}); // User modelconst User = mongoose.model('User', { name: { type: String }, age: { type: Number }}); var query = User.find({age: 5}).explain('allPlansExecution')query.exec(function(err, res){ if(err) console.log(err.message) else console.log(res)}); app.listen(3000, function(error ) { if(error) console.log(error) console.log("Server listening on PORT 3000")});
Run index.js file using below command:
node index.js
Output :
Server listening on PORT 3000
[
{
queryPlanner: {
plannerVersion: 1,
namespace: 'geeksforgeeks.users',
indexFilterSet: false,
parsedQuery: [Object],
queryHash: '3838SF3',
planCacheKey: '3238C5F3',
winningPlan: [Object],
rejectedPlans: []
},
executionStats: {
executionSuccess: true,
nReturned: 1,
executionTimeMillis: 0,
totalKeysExamined: 0,
totalDocsExamined: 4,
executionStages: [Object],
allPlansExecution: []
},
serverInfo: {
host: 'Lenovo530S',
port: 27017,
version: '4.2.0',
gitVersion: 'a4b751dcf51sd249c5865812b390cfd1c0129c30'
},
ok: 1
}
]
Reference: https://mongoosejs.com/docs/api/query.html#query_Query-explain
Mongoose
Node.js
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Express.js express.Router() Function
Mongoose Populate() Method
JWT Authentication with Node.js
Node.js Event Loop
How to build a basic CRUD app with Node.js and ReactJS ?
Express.js express.Router() Function
Top 10 Projects For Beginners To Practice HTML and CSS Skills
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 | [
{
"code": null,
"e": 24531,
"s": 24503,
"text": "\n17 Mar, 2021"
},
{
"code": null,
"e": 24698,
"s": 24531,
"text": "The Query.prototype.explain() function is used to set the explain option thereby making this query return detailed execution stats instead of the actual query result."
},
{
"code": null,
"e": 24706,
"s": 24698,
"text": "Syntax:"
},
{
"code": null,
"e": 24732,
"s": 24706,
"text": "Query.prototype.explain()"
},
{
"code": null,
"e": 24844,
"s": 24732,
"text": "Parameters: This function has one optional verbose parameter.Return Value: This function returns Query Object. "
},
{
"code": null,
"e": 24867,
"s": 24844,
"text": "Installing mongoose : "
},
{
"code": null,
"e": 24888,
"s": 24867,
"text": "npm install mongoose"
},
{
"code": null,
"e": 25000,
"s": 24888,
"text": "After installing the mongoose module, you can check your mongoose version in command prompt using the command. "
},
{
"code": null,
"e": 25023,
"s": 25000,
"text": "npm mongoose --version"
},
{
"code": null,
"e": 25097,
"s": 25023,
"text": "Now, create a folder and add a file for example, index.js as shown below."
},
{
"code": null,
"e": 25155,
"s": 25097,
"text": "Database: The sample database used here is shown below: "
},
{
"code": null,
"e": 25217,
"s": 25155,
"text": "Project Structure: The project structure will look like this."
},
{
"code": null,
"e": 25228,
"s": 25217,
"text": "Example 1:"
},
{
"code": null,
"e": 25237,
"s": 25228,
"text": "index.js"
},
{
"code": "const mongoose = require('mongoose'); // Database connectionmongoose.connect('mongodb://127.0.0.1:27017/geeksforgeeks', { useNewUrlParser: true, useCreateIndex: true, useUnifiedTopology: true}); // User modelconst User = mongoose.model('User', { name: { type: String }, age: { type: Number }}); var query = User.find({age: 5}).explain('queryPlanner')query.exec(function(err, res){ if(err) console.log(err.message) else console.log(res)});",
"e": 25701,
"s": 25237,
"text": null
},
{
"code": null,
"e": 25740,
"s": 25701,
"text": "Run index.js file using below command:"
},
{
"code": null,
"e": 25754,
"s": 25740,
"text": "node index.js"
},
{
"code": null,
"e": 25764,
"s": 25754,
"text": "Output : "
},
{
"code": null,
"e": 26428,
"s": 25764,
"text": "[\n {\n queryPlanner: {\n plannerVersion: 1,\n namespace: 'geeksforgeeks.users',\n indexFilterSet: false,\n parsedQuery: [Object],\n queryHash: '3838C5A3',\n planCacheKey: '38305F3',\n winningPlan: [Object],\n rejectedPlans: []\n },\n executionStats: {\n executionSuccess: true,\n nReturned: 1,\n executionTimeMillis: 0,\n totalKeysExamined: 0,\n totalDocsExamined: 4,\n executionStages: [Object],\n allPlansExecution: []\n },\n serverInfo: {\n host: 'Lenovo530S',\n port: 27017,\n version: '4.2.0',\n gitVersion: 'a4b751dcf51dd249c58812b390cfd1c0129c30'\n },\n ok: 1\n }\n]"
},
{
"code": null,
"e": 26439,
"s": 26428,
"text": "Example 2:"
},
{
"code": null,
"e": 26448,
"s": 26439,
"text": "index.js"
},
{
"code": "const express = require('express');const mongoose = require('mongoose');const app = express() // Database connectionmongoose.connect('mongodb://127.0.0.1:27017/geeksforgeeks', { useNewUrlParser: true, useCreateIndex: true, useUnifiedTopology: true}); // User modelconst User = mongoose.model('User', { name: { type: String }, age: { type: Number }}); var query = User.find({age: 5}).explain('allPlansExecution')query.exec(function(err, res){ if(err) console.log(err.message) else console.log(res)}); app.listen(3000, function(error ) { if(error) console.log(error) console.log(\"Server listening on PORT 3000\")});",
"e": 27093,
"s": 26448,
"text": null
},
{
"code": null,
"e": 27132,
"s": 27093,
"text": "Run index.js file using below command:"
},
{
"code": null,
"e": 27146,
"s": 27132,
"text": "node index.js"
},
{
"code": null,
"e": 27156,
"s": 27146,
"text": "Output : "
},
{
"code": null,
"e": 27852,
"s": 27156,
"text": "Server listening on PORT 3000\n[\n {\n queryPlanner: {\n plannerVersion: 1,\n namespace: 'geeksforgeeks.users',\n indexFilterSet: false,\n parsedQuery: [Object],\n queryHash: '3838SF3',\n planCacheKey: '3238C5F3',\n winningPlan: [Object],\n rejectedPlans: []\n },\n executionStats: {\n executionSuccess: true,\n nReturned: 1,\n executionTimeMillis: 0,\n totalKeysExamined: 0,\n totalDocsExamined: 4,\n executionStages: [Object],\n allPlansExecution: []\n },\n serverInfo: {\n host: 'Lenovo530S',\n port: 27017,\n version: '4.2.0',\n gitVersion: 'a4b751dcf51sd249c5865812b390cfd1c0129c30'\n },\n ok: 1\n }\n]"
},
{
"code": null,
"e": 27926,
"s": 27852,
"text": "Reference: https://mongoosejs.com/docs/api/query.html#query_Query-explain"
},
{
"code": null,
"e": 27935,
"s": 27926,
"text": "Mongoose"
},
{
"code": null,
"e": 27943,
"s": 27935,
"text": "Node.js"
},
{
"code": null,
"e": 27960,
"s": 27943,
"text": "Web Technologies"
},
{
"code": null,
"e": 28058,
"s": 27960,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 28067,
"s": 28058,
"text": "Comments"
},
{
"code": null,
"e": 28080,
"s": 28067,
"text": "Old Comments"
},
{
"code": null,
"e": 28117,
"s": 28080,
"text": "Express.js express.Router() Function"
},
{
"code": null,
"e": 28144,
"s": 28117,
"text": "Mongoose Populate() Method"
},
{
"code": null,
"e": 28176,
"s": 28144,
"text": "JWT Authentication with Node.js"
},
{
"code": null,
"e": 28195,
"s": 28176,
"text": "Node.js Event Loop"
},
{
"code": null,
"e": 28252,
"s": 28195,
"text": "How to build a basic CRUD app with Node.js and ReactJS ?"
},
{
"code": null,
"e": 28289,
"s": 28252,
"text": "Express.js express.Router() Function"
},
{
"code": null,
"e": 28351,
"s": 28289,
"text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills"
},
{
"code": null,
"e": 28394,
"s": 28351,
"text": "How to fetch data from an API in ReactJS ?"
},
{
"code": null,
"e": 28455,
"s": 28394,
"text": "Difference between var, let and const keywords in JavaScript"
}
] |
C++ Program to Implement Traveling Salesman Problem using Nearest Neighbour Algorithm | Here is a C++ Program to Implement Traveling Salesman Problem using Nearest Neighbour Algorithm.
Begin
Initialize c = 0, cost = 1000;
Initialize g[][].
function swap() is used to swap two values x and y.
function cal_sum() to calculate the cost which take array a[] and size of array as input.
Initialize sum = 0.
for i = 0 to n
compute s+= g[a[i %3]][a[(i+ 1) %3]];
if (cost >s)
cost = s
function permute() is used to perform permutation:
if there is one element in array
call cal_sum().
else
for j = i to n
swap (a+i) with (a + j)
cal_sum(a+1,n)
swap (a+i) with (a + j)
End
Live Demo
#include<iostream>
using namespace std;
int c = 0, cost = 1000;
int g[3][3 ]={{1, 2, 3}, {4, 5, 8}, {6, 7, 10}};
void swap(int *x, int *y) {
int t;
t = *x;
*x = *y;
*y = t;
}
void cal_sum(int *a, int n) {
int i, s= 0;
for (i = 0; i <= n; i++) {
s+= g[a[i %3]][a[(i+ 1) %3]];
} if (cost >s) {
cost = s;
}
}
void permute(int *a,int i,int n) {
int j, k;
if (i == n) {
cal_sum (a,n);
} else {
for (j = i; j <= n; j++) {
swap((a + i), (a + j));
cal_sum(a+1,n);
swap((a + i), (a + j));
}
}
}
int main() {
int i, j;
int a[] = {1,2,3};
permute(a, 0,2);
cout << "minimum cost:" << cost << endl;
}
Comparing str1 and str2 using ==, Res: 0
Comparing str1 and str3 using ==, Res: 1
Comparing str1 and str2 using compare(), Res: -1024
Comparing str1 and str3 using compare(), Res: 0 | [
{
"code": null,
"e": 1159,
"s": 1062,
"text": "Here is a C++ Program to Implement Traveling Salesman Problem using Nearest Neighbour Algorithm."
},
{
"code": null,
"e": 1716,
"s": 1159,
"text": "Begin\n Initialize c = 0, cost = 1000;\n Initialize g[][].\n function swap() is used to swap two values x and y.\n function cal_sum() to calculate the cost which take array a[] and size of array as input.\n Initialize sum = 0.\n for i = 0 to n\n compute s+= g[a[i %3]][a[(i+ 1) %3]];\n if (cost >s)\n cost = s\n function permute() is used to perform permutation:\n if there is one element in array\n call cal_sum().\n else\n for j = i to n\n swap (a+i) with (a + j)\n cal_sum(a+1,n)\n swap (a+i) with (a + j)\nEnd"
},
{
"code": null,
"e": 1727,
"s": 1716,
"text": " Live Demo"
},
{
"code": null,
"e": 2420,
"s": 1727,
"text": "#include<iostream>\nusing namespace std;\nint c = 0, cost = 1000;\nint g[3][3 ]={{1, 2, 3}, {4, 5, 8}, {6, 7, 10}};\nvoid swap(int *x, int *y) {\n int t;\n t = *x;\n *x = *y;\n *y = t;\n}\nvoid cal_sum(int *a, int n) {\n int i, s= 0;\n for (i = 0; i <= n; i++) {\n s+= g[a[i %3]][a[(i+ 1) %3]];\n } if (cost >s) {\n cost = s;\n }\n}\nvoid permute(int *a,int i,int n) {\n int j, k;\n if (i == n) {\n cal_sum (a,n);\n } else {\n for (j = i; j <= n; j++) {\n swap((a + i), (a + j));\n cal_sum(a+1,n);\n swap((a + i), (a + j));\n }\n }\n}\nint main() {\n int i, j;\n int a[] = {1,2,3};\n permute(a, 0,2);\n cout << \"minimum cost:\" << cost << endl;\n}"
},
{
"code": null,
"e": 2602,
"s": 2420,
"text": "Comparing str1 and str2 using ==, Res: 0\nComparing str1 and str3 using ==, Res: 1\nComparing str1 and str2 using compare(), Res: -1024\nComparing str1 and str3 using compare(), Res: 0"
}
] |
Evaluation of Expression Tree in C++ | In this problem, we are given an expression tree that consist of binary operations like +, - , /, *. We need to do the evaluation of the expression tree and then return the result.
Expression Tree is a special type of binary tree in which each node either consist of an operator or operand which are distributed as−
Leaf nodes of the tree are values on which the operation is to be performed.
Non-leaf nodes consist of the binary operator
denoting the operation to be performed.
Input:
Output: 1
Explanation:
Decoding the expression tree,
Exp = ( (5+9) / (2*7) ) = ( 14 / 14 )
= 1
A simple solution to the problem is by performing one operation each from root, for operends we will solve the subtree. As all operations are binary the nodes of a tree either have two childrens or none.
We will use recursion to solve each node's binary operation.
Live Demo
#include <bits/stdc++.h>
using namespace std;
class node {
public:
string value;
node *left = NULL, *right = NULL;
node(string x)
{
value = x;
}
};
int solveExpressionTree(node* root) {
if (!root)
return 0;
if (!root->left && !root->right)
return stoi(root->value);
int leftSubTreeSol = solveExpressionTree(root->left);
int rightSubTreeSol = solveExpressionTree(root->right);
if (root->value == "+")
return leftSubTreeSol + rightSubTreeSol;
if (root->value == "-")
return leftSubTreeSol - rightSubTreeSol;
if (root->value == "*")
return leftSubTreeSol * rightSubTreeSol;
if (root -> value == "/")
return leftSubTreeSol / rightSubTreeSol;
return -1;
}
int main()
{
node *root = new node("/");
root->left = new node("+");
root->left->left = new node("9");
root->left->right = new node("5");
root->right = new node("*");
root->right->left = new node("2");
root->right->right = new node("7");
cout<<"The evaluation of expression tree is "<<solveExpressionTree(root);
return 0;
}
The evaluation of expression tree is 1 | [
{
"code": null,
"e": 1243,
"s": 1062,
"text": "In this problem, we are given an expression tree that consist of binary operations like +, - , /, *. We need to do the evaluation of the expression tree and then return the result."
},
{
"code": null,
"e": 1378,
"s": 1243,
"text": "Expression Tree is a special type of binary tree in which each node either consist of an operator or operand which are distributed as−"
},
{
"code": null,
"e": 1456,
"s": 1378,
"text": "Leaf nodes of the tree are values on which the operation is to be performed. "
},
{
"code": null,
"e": 1543,
"s": 1456,
"text": "Non-leaf nodes consist of the binary operator\ndenoting the operation to be performed. "
},
{
"code": null,
"e": 1551,
"s": 1543,
"text": "Input: "
},
{
"code": null,
"e": 1561,
"s": 1551,
"text": "Output: 1"
},
{
"code": null,
"e": 1575,
"s": 1561,
"text": "Explanation: "
},
{
"code": null,
"e": 1605,
"s": 1575,
"text": "Decoding the expression tree,"
},
{
"code": null,
"e": 1673,
"s": 1605,
"text": "Exp = ( (5+9) / (2*7) ) = ( 14 / 14 )"
},
{
"code": null,
"e": 1677,
"s": 1673,
"text": "= 1"
},
{
"code": null,
"e": 1881,
"s": 1677,
"text": "A simple solution to the problem is by performing one operation each from root, for operends we will solve the subtree. As all operations are binary the nodes of a tree either have two childrens or none."
},
{
"code": null,
"e": 1942,
"s": 1881,
"text": "We will use recursion to solve each node's binary operation."
},
{
"code": null,
"e": 1952,
"s": 1942,
"text": "Live Demo"
},
{
"code": null,
"e": 3091,
"s": 1952,
"text": "#include <bits/stdc++.h>\nusing namespace std;\n\nclass node {\n \n public:\n string value;\n node *left = NULL, *right = NULL;\n node(string x)\n {\n value = x;\n }\n};\n\nint solveExpressionTree(node* root) {\n \n if (!root)\n return 0;\n\n if (!root->left && !root->right)\n return stoi(root->value);\n\n int leftSubTreeSol = solveExpressionTree(root->left);\n int rightSubTreeSol = solveExpressionTree(root->right);\n\n if (root->value == \"+\")\n return leftSubTreeSol + rightSubTreeSol;\n\n if (root->value == \"-\")\n return leftSubTreeSol - rightSubTreeSol;\n\n if (root->value == \"*\")\n return leftSubTreeSol * rightSubTreeSol;\n \n if (root -> value == \"/\")\n return leftSubTreeSol / rightSubTreeSol;\n \n return -1;\n}\n\nint main()\n{\n node *root = new node(\"/\");\n root->left = new node(\"+\");\n root->left->left = new node(\"9\");\n root->left->right = new node(\"5\");\n root->right = new node(\"*\");\n root->right->left = new node(\"2\");\n root->right->right = new node(\"7\");\n cout<<\"The evaluation of expression tree is \"<<solveExpressionTree(root);\n return 0;\n}"
},
{
"code": null,
"e": 3130,
"s": 3091,
"text": "The evaluation of expression tree is 1"
}
] |
VB.Net - ContextMenuStrip Control | The ContextMenuStrip control represents a shortcut menu that pops up over controls, usually when you right click them. They appear in context of some specific controls, so are called context menus. For example, Cut, Copy or Paste options.
This control associates the context menu with other menu items by setting that menu item's ContextMenuStrip property to the ContextMenuStrip control you designed.
Context menu items can also be disabled, hidden or deleted. You can also show a context menu with the help of the Show method of the ContextMenuStrip control.
The following diagram shows adding a ContextMenuStrip control on the form −
The following are some of the commonly used properties of the ContextMenuStrip control −
SourceControl
Gets the last control that displayed the ContextMenuStrip control.
In this example, let us add a content menu with the menu items Cut, Copy and Paste.
Take the following steps −
Drag and drop or double click on a ControlMenuStrip control to add it to the form.
Drag and drop or double click on a ControlMenuStrip control to add it to the form.
Add the menu items, Cut, Copy and Paste to it.
Add the menu items, Cut, Copy and Paste to it.
Add a RichTextBox control on the form.
Add a RichTextBox control on the form.
Set the ContextMenuStrip property of the rich text box to ContextMenuStrip1 using the properties window.
Set the ContextMenuStrip property of the rich text box to ContextMenuStrip1 using the properties window.
Double the menu items and add following codes in the Click event of these menus −
Double the menu items and add following codes in the Click event of these menus −
Private Sub CutToolStripMenuItem_Click(sender As Object, e As EventArgs) _
Handles CutToolStripMenuItem.Click
RichTextBox1.Cut()
End Sub
Private Sub CopyToolStripMenuItem_Click(sender As Object, e As EventArgs) _
Handles CopyToolStripMenuItem.Click
RichTextBox1.Copy()
End Sub
Private Sub PasteToolStripMenuItem_Click(sender As Object, e As EventArgs) _
Handles PasteToolStripMenuItem.Click
RichTextBox1.Paste()
End Sub
When the above code is executed and run using Start button available at the Microsoft Visual Studio tool bar, it will show the following window −
Enter some text in the rich text box, select it and right-click to get the context menu appear −
Now, you can select any menu items and perform cut, copy or paste on the text box.
63 Lectures
4 hours
Frahaan Hussain
103 Lectures
12 hours
Arnold Higuit
60 Lectures
9.5 hours
Arnold Higuit
97 Lectures
9 hours
Arnold Higuit
Print
Add Notes
Bookmark this page | [
{
"code": null,
"e": 2539,
"s": 2300,
"text": "The ContextMenuStrip control represents a shortcut menu that pops up over controls, usually when you right click them. They appear in context of some specific controls, so are called context menus. For example, Cut, Copy or Paste options."
},
{
"code": null,
"e": 2702,
"s": 2539,
"text": "This control associates the context menu with other menu items by setting that menu item's ContextMenuStrip property to the ContextMenuStrip control you designed."
},
{
"code": null,
"e": 2861,
"s": 2702,
"text": "Context menu items can also be disabled, hidden or deleted. You can also show a context menu with the help of the Show method of the ContextMenuStrip control."
},
{
"code": null,
"e": 2938,
"s": 2861,
"text": "The following diagram shows adding a ContextMenuStrip control on the form −"
},
{
"code": null,
"e": 3027,
"s": 2938,
"text": "The following are some of the commonly used properties of the ContextMenuStrip control −"
},
{
"code": null,
"e": 3041,
"s": 3027,
"text": "SourceControl"
},
{
"code": null,
"e": 3108,
"s": 3041,
"text": "Gets the last control that displayed the ContextMenuStrip control."
},
{
"code": null,
"e": 3192,
"s": 3108,
"text": "In this example, let us add a content menu with the menu items Cut, Copy and Paste."
},
{
"code": null,
"e": 3219,
"s": 3192,
"text": "Take the following steps −"
},
{
"code": null,
"e": 3302,
"s": 3219,
"text": "Drag and drop or double click on a ControlMenuStrip control to add it to the form."
},
{
"code": null,
"e": 3385,
"s": 3302,
"text": "Drag and drop or double click on a ControlMenuStrip control to add it to the form."
},
{
"code": null,
"e": 3432,
"s": 3385,
"text": "Add the menu items, Cut, Copy and Paste to it."
},
{
"code": null,
"e": 3479,
"s": 3432,
"text": "Add the menu items, Cut, Copy and Paste to it."
},
{
"code": null,
"e": 3518,
"s": 3479,
"text": "Add a RichTextBox control on the form."
},
{
"code": null,
"e": 3557,
"s": 3518,
"text": "Add a RichTextBox control on the form."
},
{
"code": null,
"e": 3662,
"s": 3557,
"text": "Set the ContextMenuStrip property of the rich text box to ContextMenuStrip1 using the properties window."
},
{
"code": null,
"e": 3767,
"s": 3662,
"text": "Set the ContextMenuStrip property of the rich text box to ContextMenuStrip1 using the properties window."
},
{
"code": null,
"e": 3849,
"s": 3767,
"text": "Double the menu items and add following codes in the Click event of these menus −"
},
{
"code": null,
"e": 3931,
"s": 3849,
"text": "Double the menu items and add following codes in the Click event of these menus −"
},
{
"code": null,
"e": 4362,
"s": 3931,
"text": "Private Sub CutToolStripMenuItem_Click(sender As Object, e As EventArgs) _\nHandles CutToolStripMenuItem.Click\n RichTextBox1.Cut()\nEnd Sub\n\nPrivate Sub CopyToolStripMenuItem_Click(sender As Object, e As EventArgs) _\nHandles CopyToolStripMenuItem.Click\n RichTextBox1.Copy()\nEnd Sub\n\nPrivate Sub PasteToolStripMenuItem_Click(sender As Object, e As EventArgs) _\nHandles PasteToolStripMenuItem.Click\n RichTextBox1.Paste()\nEnd Sub"
},
{
"code": null,
"e": 4508,
"s": 4362,
"text": "When the above code is executed and run using Start button available at the Microsoft Visual Studio tool bar, it will show the following window −"
},
{
"code": null,
"e": 4605,
"s": 4508,
"text": "Enter some text in the rich text box, select it and right-click to get the context menu appear −"
},
{
"code": null,
"e": 4688,
"s": 4605,
"text": "Now, you can select any menu items and perform cut, copy or paste on the text box."
},
{
"code": null,
"e": 4721,
"s": 4688,
"text": "\n 63 Lectures \n 4 hours \n"
},
{
"code": null,
"e": 4738,
"s": 4721,
"text": " Frahaan Hussain"
},
{
"code": null,
"e": 4773,
"s": 4738,
"text": "\n 103 Lectures \n 12 hours \n"
},
{
"code": null,
"e": 4788,
"s": 4773,
"text": " Arnold Higuit"
},
{
"code": null,
"e": 4823,
"s": 4788,
"text": "\n 60 Lectures \n 9.5 hours \n"
},
{
"code": null,
"e": 4838,
"s": 4823,
"text": " Arnold Higuit"
},
{
"code": null,
"e": 4871,
"s": 4838,
"text": "\n 97 Lectures \n 9 hours \n"
},
{
"code": null,
"e": 4886,
"s": 4871,
"text": " Arnold Higuit"
},
{
"code": null,
"e": 4893,
"s": 4886,
"text": " Print"
},
{
"code": null,
"e": 4904,
"s": 4893,
"text": " Add Notes"
}
] |
Android Progress Bar using ProgressDialog | Progress bars are used to show progress of a task. For example, when you are uploading or downloading something from the internet, it is better to show the progress of download/upload to the user.
In android there is a class called ProgressDialog that allows you to create progress bar. In order to do this, you need to instantiate an object of this class. Its syntax is.
ProgressDialog progress = new ProgressDialog(this);
Now you can set some properties of this dialog. Such as, its style, its text etc.
progress.setMessage("Downloading Music :) ");
progress.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
progress.setIndeterminate(true);
Apart from these methods, there are other methods that are provided by the ProgressDialog class
getMax()
This method returns the maximum value of the progress.
incrementProgressBy(int diff)
This method increments the progress bar by the difference of value passed as a parameter.
setIndeterminate(boolean indeterminate)
This method sets the progress indicator as determinate or indeterminate.
setMax(int max)
This method sets the maximum value of the progress dialog.
setProgress(int value)
This method is used to update the progress dialog with some specific value.
show(Context context, CharSequence title, CharSequence message)
This is a static method, used to display progress dialog.
This example demonstrates the horizontal use of the progress dialog which is in fact a progress bar. It display a progress bar on pressing the button.
To experiment with this example, you need to run this on an actual device after developing the application according to the steps below.
Following is the content of the modified main activity file src/MainActivity.java.
package com.example.sairamkrishna.myapplication;
import android.app.ProgressDialog;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
public class MainActivity extends ActionBarActivity {
Button b1;
private ProgressDialog progress;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
b1 = (Button) findViewById(R.id.button2);
}
public void download(View view){
progress=new ProgressDialog(this);
progress.setMessage("Downloading Music");
progress.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
progress.setIndeterminate(true);
progress.setProgress(0);
progress.show();
final int totalProgressTime = 100;
final Thread t = new Thread() {
@Override
public void run() {
int jumpTime = 0;
while(jumpTime < totalProgressTime) {
try {
sleep(200);
jumpTime += 5;
progress.setProgress(jumpTime);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
};
t.start();
}
}
Modify the content of res/layout/activity_main.xml to the following −
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent"
android:layout_height="match_parent" android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
android:paddingBottom="@dimen/activity_vertical_margin" tools:context=".MainActivity">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/textView"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:textSize="30dp"
android:text="Progress bar" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Tutorials Point"
android:id="@+id/textView2"
android:layout_below="@+id/textView"
android:layout_centerHorizontal="true"
android:textSize="35dp"
android:textColor="#ff16ff01" />
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Download"
android:onClick="download"
android:id="@+id/button2"
android:layout_marginLeft="125dp"
android:layout_marginStart="125dp"
android:layout_centerVertical="true" />
</RelativeLayout>
This is the default AndroidManifest.xml −
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.sairamkrishna.myapplication" >
<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:theme="@style/AppTheme" >
<activity
android:name=".MainActivity"
android:label="@string/app_name" >
<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. We 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. Before starting your application, Android studio will display following window to select an option where you want to run your Android application.
Select your mobile device as an option and then check your mobile device which will display following screen −
Just press the button to start the Progress bar. After pressing, following screen would appear −
It will continuously update itself.
46 Lectures
7.5 hours
Aditya Dua
32 Lectures
3.5 hours
Sharad Kumar
9 Lectures
1 hours
Abhilash Nelson
14 Lectures
1.5 hours
Abhilash Nelson
15 Lectures
1.5 hours
Abhilash Nelson
10 Lectures
1 hours
Abhilash Nelson
Print
Add Notes
Bookmark this page | [
{
"code": null,
"e": 3804,
"s": 3607,
"text": "Progress bars are used to show progress of a task. For example, when you are uploading or downloading something from the internet, it is better to show the progress of download/upload to the user."
},
{
"code": null,
"e": 3979,
"s": 3804,
"text": "In android there is a class called ProgressDialog that allows you to create progress bar. In order to do this, you need to instantiate an object of this class. Its syntax is."
},
{
"code": null,
"e": 4032,
"s": 3979,
"text": "ProgressDialog progress = new ProgressDialog(this);\n"
},
{
"code": null,
"e": 4114,
"s": 4032,
"text": "Now you can set some properties of this dialog. Such as, its style, its text etc."
},
{
"code": null,
"e": 4253,
"s": 4114,
"text": "progress.setMessage(\"Downloading Music :) \");\nprogress.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);\nprogress.setIndeterminate(true);"
},
{
"code": null,
"e": 4349,
"s": 4253,
"text": "Apart from these methods, there are other methods that are provided by the ProgressDialog class"
},
{
"code": null,
"e": 4358,
"s": 4349,
"text": "getMax()"
},
{
"code": null,
"e": 4413,
"s": 4358,
"text": "This method returns the maximum value of the progress."
},
{
"code": null,
"e": 4443,
"s": 4413,
"text": "incrementProgressBy(int diff)"
},
{
"code": null,
"e": 4533,
"s": 4443,
"text": "This method increments the progress bar by the difference of value passed as a parameter."
},
{
"code": null,
"e": 4573,
"s": 4533,
"text": "setIndeterminate(boolean indeterminate)"
},
{
"code": null,
"e": 4646,
"s": 4573,
"text": "This method sets the progress indicator as determinate or indeterminate."
},
{
"code": null,
"e": 4662,
"s": 4646,
"text": "setMax(int max)"
},
{
"code": null,
"e": 4721,
"s": 4662,
"text": "This method sets the maximum value of the progress dialog."
},
{
"code": null,
"e": 4744,
"s": 4721,
"text": "setProgress(int value)"
},
{
"code": null,
"e": 4820,
"s": 4744,
"text": "This method is used to update the progress dialog with some specific value."
},
{
"code": null,
"e": 4884,
"s": 4820,
"text": "show(Context context, CharSequence title, CharSequence message)"
},
{
"code": null,
"e": 4942,
"s": 4884,
"text": "This is a static method, used to display progress dialog."
},
{
"code": null,
"e": 5093,
"s": 4942,
"text": "This example demonstrates the horizontal use of the progress dialog which is in fact a progress bar. It display a progress bar on pressing the button."
},
{
"code": null,
"e": 5230,
"s": 5093,
"text": "To experiment with this example, you need to run this on an actual device after developing the application according to the steps below."
},
{
"code": null,
"e": 5313,
"s": 5230,
"text": "Following is the content of the modified main activity file src/MainActivity.java."
},
{
"code": null,
"e": 6701,
"s": 5313,
"text": "package com.example.sairamkrishna.myapplication;\n\nimport android.app.ProgressDialog;\nimport android.support.v7.app.ActionBarActivity;\nimport android.os.Bundle;\nimport android.view.View;\nimport android.widget.Button;\n\npublic class MainActivity extends ActionBarActivity {\n Button b1;\n private ProgressDialog progress;\n \n protected void onCreate(Bundle savedInstanceState) {\n super.onCreate(savedInstanceState);\n setContentView(R.layout.activity_main);\n b1 = (Button) findViewById(R.id.button2);\n }\n \n public void download(View view){\n progress=new ProgressDialog(this);\n progress.setMessage(\"Downloading Music\");\n progress.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);\n progress.setIndeterminate(true);\n progress.setProgress(0);\n progress.show();\n \n final int totalProgressTime = 100;\n final Thread t = new Thread() {\n @Override\n public void run() {\n int jumpTime = 0;\n \n while(jumpTime < totalProgressTime) {\n try {\n sleep(200);\n jumpTime += 5;\n progress.setProgress(jumpTime);\n } catch (InterruptedException e) {\n // TODO Auto-generated catch block\n e.printStackTrace();\n }\n }\n }\n };\n t.start();\n }\n}"
},
{
"code": null,
"e": 6771,
"s": 6701,
"text": "Modify the content of res/layout/activity_main.xml to the following −"
},
{
"code": null,
"e": 8207,
"s": 6771,
"text": "<RelativeLayout xmlns:android=\"http://schemas.android.com/apk/res/android\"\n xmlns:tools=\"http://schemas.android.com/tools\" android:layout_width=\"match_parent\"\n android:layout_height=\"match_parent\" android:paddingLeft=\"@dimen/activity_horizontal_margin\"\n android:paddingRight=\"@dimen/activity_horizontal_margin\"\n android:paddingTop=\"@dimen/activity_vertical_margin\"\n android:paddingBottom=\"@dimen/activity_vertical_margin\" tools:context=\".MainActivity\">\n \n <TextView\n android:layout_width=\"wrap_content\"\n android:layout_height=\"wrap_content\"\n android:id=\"@+id/textView\"\n android:layout_alignParentTop=\"true\"\n android:layout_centerHorizontal=\"true\"\n android:textSize=\"30dp\"\n android:text=\"Progress bar\" />\n \n <TextView\n android:layout_width=\"wrap_content\"\n android:layout_height=\"wrap_content\"\n android:text=\"Tutorials Point\"\n android:id=\"@+id/textView2\"\n android:layout_below=\"@+id/textView\"\n android:layout_centerHorizontal=\"true\"\n android:textSize=\"35dp\"\n android:textColor=\"#ff16ff01\" />\n \n <Button\n android:layout_width=\"wrap_content\"\n android:layout_height=\"wrap_content\"\n android:text=\"Download\"\n android:onClick=\"download\"\n android:id=\"@+id/button2\"\n android:layout_marginLeft=\"125dp\"\n android:layout_marginStart=\"125dp\"\n android:layout_centerVertical=\"true\" />\n \n</RelativeLayout>"
},
{
"code": null,
"e": 8249,
"s": 8207,
"text": "This is the default AndroidManifest.xml −"
},
{
"code": null,
"e": 8938,
"s": 8249,
"text": "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<manifest xmlns:android=\"http://schemas.android.com/apk/res/android\"\n package=\"com.example.sairamkrishna.myapplication\" >\n <application\n android:allowBackup=\"true\"\n android:icon=\"@mipmap/ic_launcher\"\n android:label=\"@string/app_name\"\n android:theme=\"@style/AppTheme\" >\n \n <activity\n android:name=\".MainActivity\"\n android:label=\"@string/app_name\" >\n \n <intent-filter>\n <action android:name=\"android.intent.action.MAIN\" />\n <category android:name=\"android.intent.category.LAUNCHER\" />\n </intent-filter>\n \n </activity>\n \n </application>\n</manifest>"
},
{
"code": null,
"e": 9320,
"s": 8938,
"text": "Let's try to run your application. We 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. Before starting your application, Android studio will display following window to select an option where you want to run your Android application."
},
{
"code": null,
"e": 9431,
"s": 9320,
"text": "Select your mobile device as an option and then check your mobile device which will display following screen −"
},
{
"code": null,
"e": 9528,
"s": 9431,
"text": "Just press the button to start the Progress bar. After pressing, following screen would appear −"
},
{
"code": null,
"e": 9564,
"s": 9528,
"text": "It will continuously update itself."
},
{
"code": null,
"e": 9599,
"s": 9564,
"text": "\n 46 Lectures \n 7.5 hours \n"
},
{
"code": null,
"e": 9611,
"s": 9599,
"text": " Aditya Dua"
},
{
"code": null,
"e": 9646,
"s": 9611,
"text": "\n 32 Lectures \n 3.5 hours \n"
},
{
"code": null,
"e": 9660,
"s": 9646,
"text": " Sharad Kumar"
},
{
"code": null,
"e": 9692,
"s": 9660,
"text": "\n 9 Lectures \n 1 hours \n"
},
{
"code": null,
"e": 9709,
"s": 9692,
"text": " Abhilash Nelson"
},
{
"code": null,
"e": 9744,
"s": 9709,
"text": "\n 14 Lectures \n 1.5 hours \n"
},
{
"code": null,
"e": 9761,
"s": 9744,
"text": " Abhilash Nelson"
},
{
"code": null,
"e": 9796,
"s": 9761,
"text": "\n 15 Lectures \n 1.5 hours \n"
},
{
"code": null,
"e": 9813,
"s": 9796,
"text": " Abhilash Nelson"
},
{
"code": null,
"e": 9846,
"s": 9813,
"text": "\n 10 Lectures \n 1 hours \n"
},
{
"code": null,
"e": 9863,
"s": 9846,
"text": " Abhilash Nelson"
},
{
"code": null,
"e": 9870,
"s": 9863,
"text": " Print"
},
{
"code": null,
"e": 9881,
"s": 9870,
"text": " Add Notes"
}
] |
Reinforcement Learning — Generalisation in Continuous State Space | by Jeremy Zhang | Towards Data Science | Till now I have introduced most basic ideas and algorithms of reinforcement learning with discrete state, action settings. Recall the examples we have been implemented so far, Grid World, Tic-Tac-Toe, Multi-Arm Bandits, Cliff Walking, Blackjack ... etc, most of which has a basic setting of a board or a grid in order to make the state space countable. However, the power of reinforcement learning does not stop there, and in a real world situation, the states space are mostly continuous, with uncountable states and actions combinations for an agent to explore. In this article, I will extend our previous learnt idea to continuous space and implement a more general Random Walk example by applying function approximation.
From this article, I will introduce:
How to approximate a value function using parametric methodsSemi-gradient TD method(which is an extension of the n-step TD method)Some general functions used for approximationApply the functions on Random Walk example
How to approximate a value function using parametric methods
Semi-gradient TD method(which is an extension of the n-step TD method)
Some general functions used for approximation
Apply the functions on Random Walk example
For discrete state space, theoretically an agent is able to experience every state and explore rewards on each of them. When the case being extended to continuous state space, to generalise the value function, we will need a representation of state.
Consider a supervised learning problem, no matter what algorithms one applies, the model being trained is able to do prediction on data it has never seen before, and the magic is that it learnt a representation of y = f(x) , where x is the input features and y is the target. This approximation or generalisation idea can be exactly copied to reinforcement learning problems, (in fact, most algorithms in machine learning can be applied on function approximation in reinforcement learning settings), where we try to approximate the value function v = v(s, w) (where s is state and w is model weights) and take the state, value as training examples. For example, in its simplest form, we could define value function v = w_0*s + w_1 , using a linear approximation with order 1.
Now here comes the problem, we have a representation of value function, then how are we able to update the weights of parameters in order to make the value approximate the actual value? In fact, the weight update follows the rule in Stochastic Gradient Descent(SGD) :
Where v(S_t) denotes the actual value at step t and v(S_t, w_t) denotes the approximate function with weight parameter w_t . Note that the square difference between actual value and estimated value measures the error of the approximate function, and by taking derivative with respect to w_t , the weight is tuning itself slightly towards the right direction.
Stochastic gradient-descent (SGD) methods do this by adjusting the weight vector after each example by a small amount in the direction that would most reduce the error on that example.
For approximate function with multiple weight parameters, one should update each weights by taking derivative respectively:
Now let’s get to the algorithm applied in continuous state space:
It looks there’s awful lot steps, but if you look closer, you will see it looks super similar with the n-step TD method we learnt here. Have a look at the n-step TD method in discrete space:
The Q function here is substitutable by Value function. By comparing TD method for continuous space and discrete space, it is clear that the only difference lies in the value function update, whereas in discrete space, the value function(or Q function) is directly updated, in continuous space, the value function is implicitly updated through weights update, as the value function here is represented by weights w . Another thing you need to notice is that in continuous space, the target value is taken as G , which in 1 step TD method is the accumulated value of one step ahead and in Monte Carlo simulation(which essentially is infinite TD method as we talked before) is the accumulated value till the end of the episode.
As we mentioned above, in continuous space setting, value function is a representation of states ( V = V(S, w) ) and most machine learning algorithms can be applied here. In this post, I will introduce some most basic approximation functions that can be easily implemented and help you get a sense on how to apply it in reinforcement learning problems.
The simplest form of function approximation. For example, suppose that there are 10 states (1, 2, 3, ..., 10) in the space, we set 1 to 5 has the same value and 6 to 10 has another value, then this is called state aggregation. The mathematical representation could be:
V(S) = w_0 if 1≤S≤5V(S) = w_1 if 5<S≤10
The function is simple but very important, as the idea is critical in Tile Coding, which is a technic of function generalisation that being used a lot in reinforcement learning problems. The advantage of state aggregation is that the derivative for state in each aggregated session is 1 and the value for that state is the corresponding weight.
The polynomial function we will apply here can be written as:
V(S) = w_0*S^0 + w_1*S^1 + ...
In this case the derivative of weight parameters is always the value of its corresponding power to the states.
Similar to polynomial case, the Fourier function applied here is:
V(S) = w_0*cos(0*πs) + w_1*cos(1*πs) + ...
The derivative of weight w_i is cos(i*πs).
Notice that both polynomials and Fourier introduced here are linear in terms of weight parameter, as this guarantees convergence. And also here I only introduced case for one state, for more general form please refer to Sutton’s book.
Enough for theorems, let’s apply what we’ve learned and get our hands on a actual case.
Consider a 1000-state version of the random walk task. The states are numbered from 1 to 1000, left to right, and all episodes begin near the center, in state 500. State transitions are from the current state to one of the 100 neighbouring states to its left, or to one of the 100 neighbouring states to its right, all with equal probability. Of course, if the current state is near an edge, then there may be fewer than 100 neighbours on that side of it. In this case, all the probability that would have gone into those missing neighbours goes into the probability of terminating on that side (thus, state 1 has a 0.5 chance of terminating on the left, and state 950 has a 0.25 chance of terminating on the right). As usual, termination on the left produces a reward of -1, and termination on the right produces a reward of +1. All other transitions have a reward of zero.
Remember the 100-state random walk we talked in the other post, here the rules are mostly the same. Differences are
Each step ranges from 1 to 100When the agent bashes into the boundary, it ends there
Each step ranges from 1 to 100
When the agent bashes into the boundary, it ends there
I previously did the implementation of random walk on discrete state space, and you can check out here. The following implementation, I will be focusing on the difference.
The soul of reinforcement learning in continuous state space. The value function should be able to do
Get the value given a stateUpdate weights given state and temporal difference
Get the value given a state
Update weights given state and temporal difference
Aggregate State Function
For the state aggregation, the 1000 states were partitioned into 10 groups of 100 states each (i.e., states 1–100 were one group, states 101–200 were another, and so on)
The 1000 states are divided into 10 groups, each with a value stored in self.values . The value function just returns the value stored in the corresponding group and update function update the value by adding delta*dev , where here derivative is 1 and delta is G-V(S, w) as introduced above.(Notice that here value is essentially the weight parameter)
Polynomials & Fourier Function
The LinearValueFunction includes both polynomial function and Fourier function. Inside the value function, features is a list of components of the value function representation, and inside the update function, derivative equals the components value as we described above.
Difference from previous random walk, here the agent is able to walk faster(from 1 to 100 steps), and when its position reaches out of the boundary, the episode ends and reward will be received with either -1 or 1.
With all the above prep work, the play function is a lot easier to implement. The structure is very alike with our previous implementation:
If you have been following up my previous posts, you must have seen this structure many times. The only difference here is that the value function is replaced by valueFunction .
Three different value functions are applied and let’s compare the learning result. (full implementation)
For aggregate state function with 1 step, 1000 states are aggregated into 10 groups, each with 100 states, and this is why you see a staircase-like graph.
This is the learning graph with polynomial function of order 5 and 1 step, from which we see a divergence at the lower states and a convergence at higher states. This is because for polynomial function approximation, there is always an intercept, thus making the value for state 0 is non-zero(in general, polynomial functions are not recognised).
This is for now the best approximation, and generally Fourier function has better performance than polynomial function.
We here learned the basic theory of reinforcement learning in continuous space and implement some basic approximate functions. And for sure, the idea dose not limit only on these functions. In more advanced settings, neural network functions can be leveraged which makes a deep reinforcement learning problem.
In the next post, I will introduce tile coding and apply it on Q function learning in continuous state space, which is more general than random walk example. | [
{
"code": null,
"e": 897,
"s": 172,
"text": "Till now I have introduced most basic ideas and algorithms of reinforcement learning with discrete state, action settings. Recall the examples we have been implemented so far, Grid World, Tic-Tac-Toe, Multi-Arm Bandits, Cliff Walking, Blackjack ... etc, most of which has a basic setting of a board or a grid in order to make the state space countable. However, the power of reinforcement learning does not stop there, and in a real world situation, the states space are mostly continuous, with uncountable states and actions combinations for an agent to explore. In this article, I will extend our previous learnt idea to continuous space and implement a more general Random Walk example by applying function approximation."
},
{
"code": null,
"e": 934,
"s": 897,
"text": "From this article, I will introduce:"
},
{
"code": null,
"e": 1152,
"s": 934,
"text": "How to approximate a value function using parametric methodsSemi-gradient TD method(which is an extension of the n-step TD method)Some general functions used for approximationApply the functions on Random Walk example"
},
{
"code": null,
"e": 1213,
"s": 1152,
"text": "How to approximate a value function using parametric methods"
},
{
"code": null,
"e": 1284,
"s": 1213,
"text": "Semi-gradient TD method(which is an extension of the n-step TD method)"
},
{
"code": null,
"e": 1330,
"s": 1284,
"text": "Some general functions used for approximation"
},
{
"code": null,
"e": 1373,
"s": 1330,
"text": "Apply the functions on Random Walk example"
},
{
"code": null,
"e": 1623,
"s": 1373,
"text": "For discrete state space, theoretically an agent is able to experience every state and explore rewards on each of them. When the case being extended to continuous state space, to generalise the value function, we will need a representation of state."
},
{
"code": null,
"e": 2399,
"s": 1623,
"text": "Consider a supervised learning problem, no matter what algorithms one applies, the model being trained is able to do prediction on data it has never seen before, and the magic is that it learnt a representation of y = f(x) , where x is the input features and y is the target. This approximation or generalisation idea can be exactly copied to reinforcement learning problems, (in fact, most algorithms in machine learning can be applied on function approximation in reinforcement learning settings), where we try to approximate the value function v = v(s, w) (where s is state and w is model weights) and take the state, value as training examples. For example, in its simplest form, we could define value function v = w_0*s + w_1 , using a linear approximation with order 1."
},
{
"code": null,
"e": 2667,
"s": 2399,
"text": "Now here comes the problem, we have a representation of value function, then how are we able to update the weights of parameters in order to make the value approximate the actual value? In fact, the weight update follows the rule in Stochastic Gradient Descent(SGD) :"
},
{
"code": null,
"e": 3026,
"s": 2667,
"text": "Where v(S_t) denotes the actual value at step t and v(S_t, w_t) denotes the approximate function with weight parameter w_t . Note that the square difference between actual value and estimated value measures the error of the approximate function, and by taking derivative with respect to w_t , the weight is tuning itself slightly towards the right direction."
},
{
"code": null,
"e": 3211,
"s": 3026,
"text": "Stochastic gradient-descent (SGD) methods do this by adjusting the weight vector after each example by a small amount in the direction that would most reduce the error on that example."
},
{
"code": null,
"e": 3335,
"s": 3211,
"text": "For approximate function with multiple weight parameters, one should update each weights by taking derivative respectively:"
},
{
"code": null,
"e": 3401,
"s": 3335,
"text": "Now let’s get to the algorithm applied in continuous state space:"
},
{
"code": null,
"e": 3592,
"s": 3401,
"text": "It looks there’s awful lot steps, but if you look closer, you will see it looks super similar with the n-step TD method we learnt here. Have a look at the n-step TD method in discrete space:"
},
{
"code": null,
"e": 4318,
"s": 3592,
"text": "The Q function here is substitutable by Value function. By comparing TD method for continuous space and discrete space, it is clear that the only difference lies in the value function update, whereas in discrete space, the value function(or Q function) is directly updated, in continuous space, the value function is implicitly updated through weights update, as the value function here is represented by weights w . Another thing you need to notice is that in continuous space, the target value is taken as G , which in 1 step TD method is the accumulated value of one step ahead and in Monte Carlo simulation(which essentially is infinite TD method as we talked before) is the accumulated value till the end of the episode."
},
{
"code": null,
"e": 4671,
"s": 4318,
"text": "As we mentioned above, in continuous space setting, value function is a representation of states ( V = V(S, w) ) and most machine learning algorithms can be applied here. In this post, I will introduce some most basic approximation functions that can be easily implemented and help you get a sense on how to apply it in reinforcement learning problems."
},
{
"code": null,
"e": 4940,
"s": 4671,
"text": "The simplest form of function approximation. For example, suppose that there are 10 states (1, 2, 3, ..., 10) in the space, we set 1 to 5 has the same value and 6 to 10 has another value, then this is called state aggregation. The mathematical representation could be:"
},
{
"code": null,
"e": 4980,
"s": 4940,
"text": "V(S) = w_0 if 1≤S≤5V(S) = w_1 if 5<S≤10"
},
{
"code": null,
"e": 5325,
"s": 4980,
"text": "The function is simple but very important, as the idea is critical in Tile Coding, which is a technic of function generalisation that being used a lot in reinforcement learning problems. The advantage of state aggregation is that the derivative for state in each aggregated session is 1 and the value for that state is the corresponding weight."
},
{
"code": null,
"e": 5387,
"s": 5325,
"text": "The polynomial function we will apply here can be written as:"
},
{
"code": null,
"e": 5418,
"s": 5387,
"text": "V(S) = w_0*S^0 + w_1*S^1 + ..."
},
{
"code": null,
"e": 5529,
"s": 5418,
"text": "In this case the derivative of weight parameters is always the value of its corresponding power to the states."
},
{
"code": null,
"e": 5595,
"s": 5529,
"text": "Similar to polynomial case, the Fourier function applied here is:"
},
{
"code": null,
"e": 5638,
"s": 5595,
"text": "V(S) = w_0*cos(0*πs) + w_1*cos(1*πs) + ..."
},
{
"code": null,
"e": 5681,
"s": 5638,
"text": "The derivative of weight w_i is cos(i*πs)."
},
{
"code": null,
"e": 5916,
"s": 5681,
"text": "Notice that both polynomials and Fourier introduced here are linear in terms of weight parameter, as this guarantees convergence. And also here I only introduced case for one state, for more general form please refer to Sutton’s book."
},
{
"code": null,
"e": 6004,
"s": 5916,
"text": "Enough for theorems, let’s apply what we’ve learned and get our hands on a actual case."
},
{
"code": null,
"e": 6879,
"s": 6004,
"text": "Consider a 1000-state version of the random walk task. The states are numbered from 1 to 1000, left to right, and all episodes begin near the center, in state 500. State transitions are from the current state to one of the 100 neighbouring states to its left, or to one of the 100 neighbouring states to its right, all with equal probability. Of course, if the current state is near an edge, then there may be fewer than 100 neighbours on that side of it. In this case, all the probability that would have gone into those missing neighbours goes into the probability of terminating on that side (thus, state 1 has a 0.5 chance of terminating on the left, and state 950 has a 0.25 chance of terminating on the right). As usual, termination on the left produces a reward of -1, and termination on the right produces a reward of +1. All other transitions have a reward of zero."
},
{
"code": null,
"e": 6995,
"s": 6879,
"text": "Remember the 100-state random walk we talked in the other post, here the rules are mostly the same. Differences are"
},
{
"code": null,
"e": 7080,
"s": 6995,
"text": "Each step ranges from 1 to 100When the agent bashes into the boundary, it ends there"
},
{
"code": null,
"e": 7111,
"s": 7080,
"text": "Each step ranges from 1 to 100"
},
{
"code": null,
"e": 7166,
"s": 7111,
"text": "When the agent bashes into the boundary, it ends there"
},
{
"code": null,
"e": 7338,
"s": 7166,
"text": "I previously did the implementation of random walk on discrete state space, and you can check out here. The following implementation, I will be focusing on the difference."
},
{
"code": null,
"e": 7440,
"s": 7338,
"text": "The soul of reinforcement learning in continuous state space. The value function should be able to do"
},
{
"code": null,
"e": 7518,
"s": 7440,
"text": "Get the value given a stateUpdate weights given state and temporal difference"
},
{
"code": null,
"e": 7546,
"s": 7518,
"text": "Get the value given a state"
},
{
"code": null,
"e": 7597,
"s": 7546,
"text": "Update weights given state and temporal difference"
},
{
"code": null,
"e": 7622,
"s": 7597,
"text": "Aggregate State Function"
},
{
"code": null,
"e": 7792,
"s": 7622,
"text": "For the state aggregation, the 1000 states were partitioned into 10 groups of 100 states each (i.e., states 1–100 were one group, states 101–200 were another, and so on)"
},
{
"code": null,
"e": 8144,
"s": 7792,
"text": "The 1000 states are divided into 10 groups, each with a value stored in self.values . The value function just returns the value stored in the corresponding group and update function update the value by adding delta*dev , where here derivative is 1 and delta is G-V(S, w) as introduced above.(Notice that here value is essentially the weight parameter)"
},
{
"code": null,
"e": 8175,
"s": 8144,
"text": "Polynomials & Fourier Function"
},
{
"code": null,
"e": 8447,
"s": 8175,
"text": "The LinearValueFunction includes both polynomial function and Fourier function. Inside the value function, features is a list of components of the value function representation, and inside the update function, derivative equals the components value as we described above."
},
{
"code": null,
"e": 8662,
"s": 8447,
"text": "Difference from previous random walk, here the agent is able to walk faster(from 1 to 100 steps), and when its position reaches out of the boundary, the episode ends and reward will be received with either -1 or 1."
},
{
"code": null,
"e": 8802,
"s": 8662,
"text": "With all the above prep work, the play function is a lot easier to implement. The structure is very alike with our previous implementation:"
},
{
"code": null,
"e": 8980,
"s": 8802,
"text": "If you have been following up my previous posts, you must have seen this structure many times. The only difference here is that the value function is replaced by valueFunction ."
},
{
"code": null,
"e": 9085,
"s": 8980,
"text": "Three different value functions are applied and let’s compare the learning result. (full implementation)"
},
{
"code": null,
"e": 9240,
"s": 9085,
"text": "For aggregate state function with 1 step, 1000 states are aggregated into 10 groups, each with 100 states, and this is why you see a staircase-like graph."
},
{
"code": null,
"e": 9587,
"s": 9240,
"text": "This is the learning graph with polynomial function of order 5 and 1 step, from which we see a divergence at the lower states and a convergence at higher states. This is because for polynomial function approximation, there is always an intercept, thus making the value for state 0 is non-zero(in general, polynomial functions are not recognised)."
},
{
"code": null,
"e": 9707,
"s": 9587,
"text": "This is for now the best approximation, and generally Fourier function has better performance than polynomial function."
},
{
"code": null,
"e": 10017,
"s": 9707,
"text": "We here learned the basic theory of reinforcement learning in continuous space and implement some basic approximate functions. And for sure, the idea dose not limit only on these functions. In more advanced settings, neural network functions can be leveraged which makes a deep reinforcement learning problem."
}
] |
3D passwords-Advanced Authentication Systems - GeeksforGeeks | 17 Dec, 2019
The increase in the usage of computer systems has given rise to many security concerns.One of the major security concern is authentication, which is the process of validating who you are to whom you claimed to be.
Current authentication systems suffer from various weaknesses. People usually use textual passwords; however they do not follow their requirements.The issue is that users intend to use meaningful words from the dictionary, which eventually are easier to break and vulnerable to attack.
A major drawback of the textual password is its conflicting requirements-the selection of a password that is easy to remember(for the user), and at the same time, hard to guess(to prevent unauthorized access to private data).
As a solution, many biometric authentications have been proposed. These include:
1. Retinal scans
2. Fingerscanning
3. Iris recognition
4. Facial recognition
5. Finger vein ID
However, users usually tend to resist biometrics because:
because of their effect on privacy and their intrusiveness.
moreover, biometrics cannot be revoked.
3D password is a multi factor authentication scheme, that is, it is a security approach that requires the user to provide more than 1 identity factor before accessing their data.
Some factors include:
what a user KNOWS: that is their password.what a user HAS: that is a smart card/hard token.what a user IS: that is a retinal scan/ finger print.
what a user KNOWS: that is their password.
what a user HAS: that is a smart card/hard token.
what a user IS: that is a retinal scan/ finger print.
To be authenticated into a secure system, we present a 3-D virtual environment where the user navigates and interacts with various objects. The sequence of actions and interactions towards the objects inside the environment.Then the user’s password is constructed. The password can combine most existing authentication schemes, i.e., graphical and textual passwords and various biometrics into a virtual 3D environment.
The design of the 3D virtual environment and the type of objects selected determine the 3D password key space.
Advantages:
easy to remember and is highly secure.
easy to customise.
difficult to share.
3D graphical password has no limit.
Disadvantages:
difficult to use for the blind people.
is costly.
requires complex computer technology.
cryptography
Computer Networks
cryptography
Computer Networks
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Advanced Encryption Standard (AES)
Intrusion Detection System (IDS)
Introduction and IPv4 Datagram Header
Block Cipher modes of Operation
Stop and Wait ARQ
Multiple Access Protocols in Computer Network
Cryptography and its Types
Congestion Control in Computer Networks
Active and Passive attacks in Information Security
Secure Electronic Transaction (SET) Protocol | [
{
"code": null,
"e": 24119,
"s": 24091,
"text": "\n17 Dec, 2019"
},
{
"code": null,
"e": 24333,
"s": 24119,
"text": "The increase in the usage of computer systems has given rise to many security concerns.One of the major security concern is authentication, which is the process of validating who you are to whom you claimed to be."
},
{
"code": null,
"e": 24619,
"s": 24333,
"text": "Current authentication systems suffer from various weaknesses. People usually use textual passwords; however they do not follow their requirements.The issue is that users intend to use meaningful words from the dictionary, which eventually are easier to break and vulnerable to attack."
},
{
"code": null,
"e": 24845,
"s": 24619,
"text": "A major drawback of the textual password is its conflicting requirements-the selection of a password that is easy to remember(for the user), and at the same time, hard to guess(to prevent unauthorized access to private data)."
},
{
"code": null,
"e": 24926,
"s": 24845,
"text": "As a solution, many biometric authentications have been proposed. These include:"
},
{
"code": null,
"e": 25022,
"s": 24926,
"text": "1. Retinal scans\n2. Fingerscanning\n3. Iris recognition\n4. Facial recognition\n5. Finger vein ID "
},
{
"code": null,
"e": 25080,
"s": 25022,
"text": "However, users usually tend to resist biometrics because:"
},
{
"code": null,
"e": 25140,
"s": 25080,
"text": "because of their effect on privacy and their intrusiveness."
},
{
"code": null,
"e": 25180,
"s": 25140,
"text": "moreover, biometrics cannot be revoked."
},
{
"code": null,
"e": 25359,
"s": 25180,
"text": "3D password is a multi factor authentication scheme, that is, it is a security approach that requires the user to provide more than 1 identity factor before accessing their data."
},
{
"code": null,
"e": 25381,
"s": 25359,
"text": "Some factors include:"
},
{
"code": null,
"e": 25526,
"s": 25381,
"text": "what a user KNOWS: that is their password.what a user HAS: that is a smart card/hard token.what a user IS: that is a retinal scan/ finger print."
},
{
"code": null,
"e": 25569,
"s": 25526,
"text": "what a user KNOWS: that is their password."
},
{
"code": null,
"e": 25619,
"s": 25569,
"text": "what a user HAS: that is a smart card/hard token."
},
{
"code": null,
"e": 25673,
"s": 25619,
"text": "what a user IS: that is a retinal scan/ finger print."
},
{
"code": null,
"e": 26093,
"s": 25673,
"text": "To be authenticated into a secure system, we present a 3-D virtual environment where the user navigates and interacts with various objects. The sequence of actions and interactions towards the objects inside the environment.Then the user’s password is constructed. The password can combine most existing authentication schemes, i.e., graphical and textual passwords and various biometrics into a virtual 3D environment."
},
{
"code": null,
"e": 26204,
"s": 26093,
"text": "The design of the 3D virtual environment and the type of objects selected determine the 3D password key space."
},
{
"code": null,
"e": 26216,
"s": 26204,
"text": "Advantages:"
},
{
"code": null,
"e": 26255,
"s": 26216,
"text": "easy to remember and is highly secure."
},
{
"code": null,
"e": 26274,
"s": 26255,
"text": "easy to customise."
},
{
"code": null,
"e": 26294,
"s": 26274,
"text": "difficult to share."
},
{
"code": null,
"e": 26330,
"s": 26294,
"text": "3D graphical password has no limit."
},
{
"code": null,
"e": 26345,
"s": 26330,
"text": "Disadvantages:"
},
{
"code": null,
"e": 26384,
"s": 26345,
"text": "difficult to use for the blind people."
},
{
"code": null,
"e": 26395,
"s": 26384,
"text": "is costly."
},
{
"code": null,
"e": 26433,
"s": 26395,
"text": "requires complex computer technology."
},
{
"code": null,
"e": 26446,
"s": 26433,
"text": "cryptography"
},
{
"code": null,
"e": 26464,
"s": 26446,
"text": "Computer Networks"
},
{
"code": null,
"e": 26477,
"s": 26464,
"text": "cryptography"
},
{
"code": null,
"e": 26495,
"s": 26477,
"text": "Computer Networks"
},
{
"code": null,
"e": 26593,
"s": 26495,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 26602,
"s": 26593,
"text": "Comments"
},
{
"code": null,
"e": 26615,
"s": 26602,
"text": "Old Comments"
},
{
"code": null,
"e": 26650,
"s": 26615,
"text": "Advanced Encryption Standard (AES)"
},
{
"code": null,
"e": 26683,
"s": 26650,
"text": "Intrusion Detection System (IDS)"
},
{
"code": null,
"e": 26721,
"s": 26683,
"text": "Introduction and IPv4 Datagram Header"
},
{
"code": null,
"e": 26753,
"s": 26721,
"text": "Block Cipher modes of Operation"
},
{
"code": null,
"e": 26771,
"s": 26753,
"text": "Stop and Wait ARQ"
},
{
"code": null,
"e": 26817,
"s": 26771,
"text": "Multiple Access Protocols in Computer Network"
},
{
"code": null,
"e": 26844,
"s": 26817,
"text": "Cryptography and its Types"
},
{
"code": null,
"e": 26884,
"s": 26844,
"text": "Congestion Control in Computer Networks"
},
{
"code": null,
"e": 26935,
"s": 26884,
"text": "Active and Passive attacks in Information Security"
}
] |
bokeh.plotting.figure.circle() function in Python | 17 Jun, 2020
Bokeh is a data visualization library in Python that provides high-performance interactive charts and plots and the output can be obtained in various mediums like notebook, html and server. The Figure Class create a new Figure for plotting. It is a subclass of Plot that simplifies plot creation with default axes, grids, tools, etc.
The circle() function in plotting module of bokeh library is used to Configure and add Circle glyphs to this Figure.
Syntax: circle(x, y, *, angle=0.0, angle_units=’rad’, fill_alpha=1.0, fill_color=’gray’, line_alpha=1.0, line_cap=’butt’, line_color=’black’, line_dash=[], line_dash_offset=0, line_join=’bevel’, line_width=1, name=None, radius=None, radius_dimension=’x’, radius_units=’data’, size=4, tags=[], **kwargs)
Parameters: This method accept the following parameters that are described below:
x: This parameter is the x-coordinates for the center of the markers.
y: This parameter is the y-coordinates for the center of the markers.
angle: This parameter is the angles to rotate the markers.
fill_alpha: This parameter is the fill alpha values for the markers.
fill_color: This parameter is the fill color values for the markers.
line_alpha: This parameter is the line alpha values for the markers with default value of 1.0 .
line_cap: This parameter is the line cap values for the markers with default value of butt.
line_color: This parameter is the line color values for the markers with default value of black.
line_dash: This parameter is the line dash values for the markers with default value of [].
line_dash_offset: This parameter is the line dash offset values for the markers with default value of 0.
line_join: This parameter is the line join values for the markers with default value of bevel.
line_width: This parameter is the line width values for the markers with default value of 1.
mode: This parameter can be one of three values : [“before”, “after”, “center”].
name: This parameter is the user-supplied name for this model.
tags: This parameter is the user-supplied values for this model.
radius: This parameter is the radius values for circle markers .
radius_dimension: This parameter is the dimension to measure circle radii along.
size: This parameter is the size (diameter) values for the markers in screen space units.
Other Parameters: These parameters are **kwargs that are described below:
alpha: This parameter is used to set all alpha keyword arguments at once.
color: This parameter is used to to set all color keyword arguments at once.
legend_field: This parameter is the name of a column in the data source that should be used or the grouping.
legend_group: This parameter is the name of a column in the data source that should be used or the grouping.
legend_label: This parameter is the legend entry is labeled with exactly the text supplied here.
muted: This parameter contains the bool value.
name: This parameter is the optional user-supplied name to attach to the renderer.
source: This parameter is the user-supplied data source.
view: This parameter is the view for filtering the data source.
visible: This parameter contains the bool value.
x_range_name: This parameter is the name of an extra range to use for mapping x-coordinates.
y_range_name: This parameter is the name of an extra range to use for mapping y-coordinates.
level: This parameter specify the render level order for this glyph.
Return: This method return the GlyphRenderer value.
Below examples illustrate the bokeh.plotting.figure.circle() function in bokeh.plotting:Example 1:
# Implementation of bokeh function import numpy as np from bokeh.plotting import figure, output_file, show plot = figure(plot_width = 300, plot_height = 300)plot.circle(x = [1, 2, 3], y = [3, 7, 5], size = 20, color ="green", alpha = 0.6) show(plot)
Output:
Example 2:
# Implementation of bokeh function import numpy as np from bokeh.plotting import figure, output_file, show x = [1, 2, 3, 4, 5]y = [6, 7, 8, 7, 3] output_file("geeksforgeeks.html") p = figure(plot_width = 300, plot_height = 300) # add both a line and circles on the # same plotp.line(x, y, line_width = 2)p.circle(x, y, fill_color ="red", line_color ="green", size = 8) show(p)
Output:
Python-Bokeh
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here. | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n17 Jun, 2020"
},
{
"code": null,
"e": 362,
"s": 28,
"text": "Bokeh is a data visualization library in Python that provides high-performance interactive charts and plots and the output can be obtained in various mediums like notebook, html and server. The Figure Class create a new Figure for plotting. It is a subclass of Plot that simplifies plot creation with default axes, grids, tools, etc."
},
{
"code": null,
"e": 479,
"s": 362,
"text": "The circle() function in plotting module of bokeh library is used to Configure and add Circle glyphs to this Figure."
},
{
"code": null,
"e": 782,
"s": 479,
"text": "Syntax: circle(x, y, *, angle=0.0, angle_units=’rad’, fill_alpha=1.0, fill_color=’gray’, line_alpha=1.0, line_cap=’butt’, line_color=’black’, line_dash=[], line_dash_offset=0, line_join=’bevel’, line_width=1, name=None, radius=None, radius_dimension=’x’, radius_units=’data’, size=4, tags=[], **kwargs)"
},
{
"code": null,
"e": 864,
"s": 782,
"text": "Parameters: This method accept the following parameters that are described below:"
},
{
"code": null,
"e": 934,
"s": 864,
"text": "x: This parameter is the x-coordinates for the center of the markers."
},
{
"code": null,
"e": 1004,
"s": 934,
"text": "y: This parameter is the y-coordinates for the center of the markers."
},
{
"code": null,
"e": 1063,
"s": 1004,
"text": "angle: This parameter is the angles to rotate the markers."
},
{
"code": null,
"e": 1132,
"s": 1063,
"text": "fill_alpha: This parameter is the fill alpha values for the markers."
},
{
"code": null,
"e": 1201,
"s": 1132,
"text": "fill_color: This parameter is the fill color values for the markers."
},
{
"code": null,
"e": 1297,
"s": 1201,
"text": "line_alpha: This parameter is the line alpha values for the markers with default value of 1.0 ."
},
{
"code": null,
"e": 1389,
"s": 1297,
"text": "line_cap: This parameter is the line cap values for the markers with default value of butt."
},
{
"code": null,
"e": 1486,
"s": 1389,
"text": "line_color: This parameter is the line color values for the markers with default value of black."
},
{
"code": null,
"e": 1578,
"s": 1486,
"text": "line_dash: This parameter is the line dash values for the markers with default value of []."
},
{
"code": null,
"e": 1683,
"s": 1578,
"text": "line_dash_offset: This parameter is the line dash offset values for the markers with default value of 0."
},
{
"code": null,
"e": 1778,
"s": 1683,
"text": "line_join: This parameter is the line join values for the markers with default value of bevel."
},
{
"code": null,
"e": 1871,
"s": 1778,
"text": "line_width: This parameter is the line width values for the markers with default value of 1."
},
{
"code": null,
"e": 1952,
"s": 1871,
"text": "mode: This parameter can be one of three values : [“before”, “after”, “center”]."
},
{
"code": null,
"e": 2015,
"s": 1952,
"text": "name: This parameter is the user-supplied name for this model."
},
{
"code": null,
"e": 2080,
"s": 2015,
"text": "tags: This parameter is the user-supplied values for this model."
},
{
"code": null,
"e": 2145,
"s": 2080,
"text": "radius: This parameter is the radius values for circle markers ."
},
{
"code": null,
"e": 2226,
"s": 2145,
"text": "radius_dimension: This parameter is the dimension to measure circle radii along."
},
{
"code": null,
"e": 2316,
"s": 2226,
"text": "size: This parameter is the size (diameter) values for the markers in screen space units."
},
{
"code": null,
"e": 2390,
"s": 2316,
"text": "Other Parameters: These parameters are **kwargs that are described below:"
},
{
"code": null,
"e": 2464,
"s": 2390,
"text": "alpha: This parameter is used to set all alpha keyword arguments at once."
},
{
"code": null,
"e": 2541,
"s": 2464,
"text": "color: This parameter is used to to set all color keyword arguments at once."
},
{
"code": null,
"e": 2650,
"s": 2541,
"text": "legend_field: This parameter is the name of a column in the data source that should be used or the grouping."
},
{
"code": null,
"e": 2759,
"s": 2650,
"text": "legend_group: This parameter is the name of a column in the data source that should be used or the grouping."
},
{
"code": null,
"e": 2856,
"s": 2759,
"text": "legend_label: This parameter is the legend entry is labeled with exactly the text supplied here."
},
{
"code": null,
"e": 2903,
"s": 2856,
"text": "muted: This parameter contains the bool value."
},
{
"code": null,
"e": 2986,
"s": 2903,
"text": "name: This parameter is the optional user-supplied name to attach to the renderer."
},
{
"code": null,
"e": 3043,
"s": 2986,
"text": "source: This parameter is the user-supplied data source."
},
{
"code": null,
"e": 3107,
"s": 3043,
"text": "view: This parameter is the view for filtering the data source."
},
{
"code": null,
"e": 3156,
"s": 3107,
"text": "visible: This parameter contains the bool value."
},
{
"code": null,
"e": 3249,
"s": 3156,
"text": "x_range_name: This parameter is the name of an extra range to use for mapping x-coordinates."
},
{
"code": null,
"e": 3342,
"s": 3249,
"text": "y_range_name: This parameter is the name of an extra range to use for mapping y-coordinates."
},
{
"code": null,
"e": 3411,
"s": 3342,
"text": "level: This parameter specify the render level order for this glyph."
},
{
"code": null,
"e": 3463,
"s": 3411,
"text": "Return: This method return the GlyphRenderer value."
},
{
"code": null,
"e": 3562,
"s": 3463,
"text": "Below examples illustrate the bokeh.plotting.figure.circle() function in bokeh.plotting:Example 1:"
},
{
"code": "# Implementation of bokeh function import numpy as np from bokeh.plotting import figure, output_file, show plot = figure(plot_width = 300, plot_height = 300)plot.circle(x = [1, 2, 3], y = [3, 7, 5], size = 20, color =\"green\", alpha = 0.6) show(plot)",
"e": 3830,
"s": 3562,
"text": null
},
{
"code": null,
"e": 3838,
"s": 3830,
"text": "Output:"
},
{
"code": null,
"e": 3849,
"s": 3838,
"text": "Example 2:"
},
{
"code": "# Implementation of bokeh function import numpy as np from bokeh.plotting import figure, output_file, show x = [1, 2, 3, 4, 5]y = [6, 7, 8, 7, 3] output_file(\"geeksforgeeks.html\") p = figure(plot_width = 300, plot_height = 300) # add both a line and circles on the # same plotp.line(x, y, line_width = 2)p.circle(x, y, fill_color =\"red\", line_color =\"green\", size = 8) show(p)",
"e": 4243,
"s": 3849,
"text": null
},
{
"code": null,
"e": 4251,
"s": 4243,
"text": "Output:"
},
{
"code": null,
"e": 4264,
"s": 4251,
"text": "Python-Bokeh"
},
{
"code": null,
"e": 4271,
"s": 4264,
"text": "Python"
}
] |
Python – tensorflow.math.subtract() | 16 Jun, 2020
TensorFlow is open-source Python library designed by Google to develop Machine Learning models and deep learning neural networks.
subtract() is used to compute element wise (x-y).
Syntax: tensorflow.math.subtract(x, y, name)
Parameters:
x: It’s a tensor. Allowed dtypes are bfloat16, half, float32, float64, complex64, complex128.
y: It’s a tensor of same dtype as x.
name(optional): It defines the name for the operation.
Returns: It returns a tensor.
Example 1:
Python3
# importing the libraryimport tensorflow as tf # Initializing the input tensora = tf.constant([ -5, -7, 2, 5, 7], dtype = tf.float64)b = tf.constant([ 1, 3, 9, 4, 7], dtype = tf.float64) # Printing the input tensorprint('a: ', a)print('b: ', b) # Calculating resultres = tf.math.subtract(a, b) # Printing the resultprint('Result: ', res)
Output:
a: tf.Tensor([-5. -7. 2. 5. 7.], shape=(5, ), dtype=float64)
b: tf.Tensor([1. 3. 9. 4. 7.], shape=(5, ), dtype=float64)
Result: tf.Tensor([ -6. -10. -7. 1. 0.], shape=(5, ), dtype=float64)
Example 2: Taking complex input
Python3
# importing the libraryimport tensorflow as tf # Initializing the input tensora = tf.constant([ -5 + 3j, -7-2j, 2 + 1j, 5-7j, 7 + 3j], dtype = tf.complex128)b = tf.constant([ 1 + 5j, 3 + 1j, 9-5j, 4 + 3j, 7-6j], dtype = tf.complex128) # Printing the input tensorprint('a: ', a)print('b: ', b) # Calculating resultres = tf.math.subtract(a, b) # Printing the resultprint('Result: ', res)
Output:
a: tf.Tensor([-5.+3.j -7.-2.j 2.+1.j 5.-7.j 7.+3.j], shape=(5, ), dtype=complex128)
b: tf.Tensor([1.+5.j 3.+1.j 9.-5.j 4.+3.j 7.-6.j], shape=(5, ), dtype=complex128)
Result: tf.Tensor([ -6. -2.j -10. -3.j -7. +6.j 1.-10.j 0. +9.j], shape=(5, ), dtype=complex128)
Python Tensorflow-math-functions
Python-Tensorflow
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 | datetime.timedelta() function
Python | Get unique values from a list | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n16 Jun, 2020"
},
{
"code": null,
"e": 159,
"s": 28,
"text": "TensorFlow is open-source Python library designed by Google to develop Machine Learning models and deep learning neural networks."
},
{
"code": null,
"e": 209,
"s": 159,
"text": "subtract() is used to compute element wise (x-y)."
},
{
"code": null,
"e": 254,
"s": 209,
"text": "Syntax: tensorflow.math.subtract(x, y, name)"
},
{
"code": null,
"e": 266,
"s": 254,
"text": "Parameters:"
},
{
"code": null,
"e": 360,
"s": 266,
"text": "x: It’s a tensor. Allowed dtypes are bfloat16, half, float32, float64, complex64, complex128."
},
{
"code": null,
"e": 397,
"s": 360,
"text": "y: It’s a tensor of same dtype as x."
},
{
"code": null,
"e": 452,
"s": 397,
"text": "name(optional): It defines the name for the operation."
},
{
"code": null,
"e": 482,
"s": 452,
"text": "Returns: It returns a tensor."
},
{
"code": null,
"e": 493,
"s": 482,
"text": "Example 1:"
},
{
"code": null,
"e": 501,
"s": 493,
"text": "Python3"
},
{
"code": "# importing the libraryimport tensorflow as tf # Initializing the input tensora = tf.constant([ -5, -7, 2, 5, 7], dtype = tf.float64)b = tf.constant([ 1, 3, 9, 4, 7], dtype = tf.float64) # Printing the input tensorprint('a: ', a)print('b: ', b) # Calculating resultres = tf.math.subtract(a, b) # Printing the resultprint('Result: ', res)",
"e": 843,
"s": 501,
"text": null
},
{
"code": null,
"e": 851,
"s": 843,
"text": "Output:"
},
{
"code": null,
"e": 1055,
"s": 851,
"text": "a: tf.Tensor([-5. -7. 2. 5. 7.], shape=(5, ), dtype=float64)\nb: tf.Tensor([1. 3. 9. 4. 7.], shape=(5, ), dtype=float64)\nResult: tf.Tensor([ -6. -10. -7. 1. 0.], shape=(5, ), dtype=float64)\n\n\n\n"
},
{
"code": null,
"e": 1087,
"s": 1055,
"text": "Example 2: Taking complex input"
},
{
"code": null,
"e": 1095,
"s": 1087,
"text": "Python3"
},
{
"code": "# importing the libraryimport tensorflow as tf # Initializing the input tensora = tf.constant([ -5 + 3j, -7-2j, 2 + 1j, 5-7j, 7 + 3j], dtype = tf.complex128)b = tf.constant([ 1 + 5j, 3 + 1j, 9-5j, 4 + 3j, 7-6j], dtype = tf.complex128) # Printing the input tensorprint('a: ', a)print('b: ', b) # Calculating resultres = tf.math.subtract(a, b) # Printing the resultprint('Result: ', res)",
"e": 1485,
"s": 1095,
"text": null
},
{
"code": null,
"e": 1493,
"s": 1485,
"text": "Output:"
},
{
"code": null,
"e": 1768,
"s": 1493,
"text": "a: tf.Tensor([-5.+3.j -7.-2.j 2.+1.j 5.-7.j 7.+3.j], shape=(5, ), dtype=complex128)\nb: tf.Tensor([1.+5.j 3.+1.j 9.-5.j 4.+3.j 7.-6.j], shape=(5, ), dtype=complex128)\nResult: tf.Tensor([ -6. -2.j -10. -3.j -7. +6.j 1.-10.j 0. +9.j], shape=(5, ), dtype=complex128)\n"
},
{
"code": null,
"e": 1801,
"s": 1768,
"text": "Python Tensorflow-math-functions"
},
{
"code": null,
"e": 1819,
"s": 1801,
"text": "Python-Tensorflow"
},
{
"code": null,
"e": 1826,
"s": 1819,
"text": "Python"
},
{
"code": null,
"e": 1924,
"s": 1826,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 1956,
"s": 1924,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 1983,
"s": 1956,
"text": "Python Classes and Objects"
},
{
"code": null,
"e": 2004,
"s": 1983,
"text": "Python OOPs Concepts"
},
{
"code": null,
"e": 2027,
"s": 2004,
"text": "Introduction To PYTHON"
},
{
"code": null,
"e": 2058,
"s": 2027,
"text": "Python | os.path.join() method"
},
{
"code": null,
"e": 2114,
"s": 2058,
"text": "How to drop one or multiple columns in Pandas Dataframe"
},
{
"code": null,
"e": 2156,
"s": 2114,
"text": "How To Convert Python Dictionary To JSON?"
},
{
"code": null,
"e": 2198,
"s": 2156,
"text": "Check if element exists in list in Python"
},
{
"code": null,
"e": 2237,
"s": 2198,
"text": "Python | datetime.timedelta() function"
}
] |
How to check if an element is hidden in jQuery? | 28 Mar, 2019
To check if an element is hidden or not, jQuery :hidden selector can be used. .toggle() function is used to toggle the visibility of an element.
Syntax:
$(element).is(":hidden");
Example:
<!DOCTYPE html><html lang="en"> <head> <meta charset="utf-8"> <title> Jquery Hidden element Checking </title> <style> h1 { color: green; } table, th, td { border: 1px solid black; } </style> <script src="https://code.jquery.com/jquery-1.12.4.min.js"> </script> <script type="text/javascript"> $(document).ready(function() { $("button").click(function() { $("table").toggle("slow", function() { if ($("table").is(":hidden")) { alert(" Hidden Element."); } else { alert("Element Visible."); } }); }); }); </script></head> <body> <center> <h1>Geeks for Geeks</h1> <button type="button"> Click! </button> <table style="width:60%"> <tr> <th>Language Index</th> <th>Language Name</th> </tr> <tr> <td>1</td> <td>C</td> </tr> <tr> <td>2</td> <td>C++</td> </tr> <tr> <td>3</td> <td>Java</td> </tr> <tr> <td>4</td> <td>Python</td> </tr> <tr> <td>5</td> <td>HTML</td> </tr> </table> </center></body> </html>
Output:Before Clicking:
After Clicking:
Picked
JQuery
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": "\n28 Mar, 2019"
},
{
"code": null,
"e": 173,
"s": 28,
"text": "To check if an element is hidden or not, jQuery :hidden selector can be used. .toggle() function is used to toggle the visibility of an element."
},
{
"code": null,
"e": 181,
"s": 173,
"text": "Syntax:"
},
{
"code": null,
"e": 207,
"s": 181,
"text": "$(element).is(\":hidden\");"
},
{
"code": null,
"e": 216,
"s": 207,
"text": "Example:"
},
{
"code": "<!DOCTYPE html><html lang=\"en\"> <head> <meta charset=\"utf-8\"> <title> Jquery Hidden element Checking </title> <style> h1 { color: green; } table, th, td { border: 1px solid black; } </style> <script src=\"https://code.jquery.com/jquery-1.12.4.min.js\"> </script> <script type=\"text/javascript\"> $(document).ready(function() { $(\"button\").click(function() { $(\"table\").toggle(\"slow\", function() { if ($(\"table\").is(\":hidden\")) { alert(\" Hidden Element.\"); } else { alert(\"Element Visible.\"); } }); }); }); </script></head> <body> <center> <h1>Geeks for Geeks</h1> <button type=\"button\"> Click! </button> <table style=\"width:60%\"> <tr> <th>Language Index</th> <th>Language Name</th> </tr> <tr> <td>1</td> <td>C</td> </tr> <tr> <td>2</td> <td>C++</td> </tr> <tr> <td>3</td> <td>Java</td> </tr> <tr> <td>4</td> <td>Python</td> </tr> <tr> <td>5</td> <td>HTML</td> </tr> </table> </center></body> </html>",
"e": 1763,
"s": 216,
"text": null
},
{
"code": null,
"e": 1787,
"s": 1763,
"text": "Output:Before Clicking:"
},
{
"code": null,
"e": 1803,
"s": 1787,
"text": "After Clicking:"
},
{
"code": null,
"e": 1810,
"s": 1803,
"text": "Picked"
},
{
"code": null,
"e": 1817,
"s": 1810,
"text": "JQuery"
},
{
"code": null,
"e": 1834,
"s": 1817,
"text": "Web Technologies"
}
] |
Field get() method in Java with Examples | 26 Aug, 2019
The get() method of java.lang.reflect.Field used to get the value of the field object. If Field has a primitive type then the value of the field is automatically wrapped in an object. If the field is a static field, the argument of obj is ignored; it may be null Otherwise, the underlying field is an instance field. This method throws a NullPointerException if the specified obj argument is null and an IllegalArgumentException If the specified object is not an instance of the class or interface declaring the underlying field. If the field is hidden in the type of obj, the field’s value is obtained according to the preceding rules.
Syntax:
public double get(Object obj)
throws IllegalArgumentException,
IllegalAccessException
Parameters: This method accepts a single parameter obj which is the object to extract the field value from.
Return value: This method returns the value of the represented field in object obj; primitive values are wrapped in an appropriate object before being returned.
Exception: This method throws following Exception:
IllegalAccessException– if this Field object is enforcing Java language access control and the underlying field is inaccessible.IllegalArgumentException– if the specified object is not an instance of the class or interface declaring the underlying field (or a subclass or implementor thereof).NullPointerException– if the specified object is null and the field is an instance field.ExceptionInInitializerError– if the initialization provoked by this method fails.
IllegalAccessException– if this Field object is enforcing Java language access control and the underlying field is inaccessible.
IllegalArgumentException– if the specified object is not an instance of the class or interface declaring the underlying field (or a subclass or implementor thereof).
NullPointerException– if the specified object is null and the field is an instance field.
ExceptionInInitializerError– if the initialization provoked by this method fails.
Below programs illustrate get() method:Program 1:
// Java program to demonstrate get() method import java.lang.reflect.Field; public class GFG { public static void main(String[] args) throws Exception { // Create the User class object User user = new User(); // Get the all field objects of User class Field[] fields = User.class.getFields(); for (int i = 0; i < fields.length; i++) { // get value of the fields Object value = fields[i].get(user); // print result System.out.println("Value of Field " + fields[i].getName() + " is " + value); } }} // sample User classclass User { // static double values public static double Marks = 34.13; public static int Fees = 34199; public static String name = "Aman"; public static double getMarks() { return Marks; } public static void setMarks(double marks) { Marks = marks; } public static int getFees() { return Fees; } public static void setFees(int fees) { Fees = fees; } public static String getName() { return name; } public static void setName(String name) { User.name = name; }}
Value of Field Marks is 34.13
Value of Field Fees is 34199
Value of Field name is Aman
Program 2:
// Java program to demonstrate get() method import java.lang.reflect.Field; public class GFG { public static void main(String[] args) throws Exception { // Create the RealNumbers class object Fields field = new Fields(); // Get the all field objects of User class Field[] fieldsOfFieldClass = Fields.class.getFields(); for (int i = 0; i < fieldsOfFieldClass.length; i++) { // get value Object value = fieldsOfFieldClass[i] .get(field); // print result System.out.println( "Value of Field " + fieldsOfFieldClass[i].getName() + " is " + value); } } // RealNumbers class static class Fields { // double field public static final double doubleValue = 9999999.34567; public static final int intValue = 9999999; public static final float floatValue = 9999999.34567f; public static final boolean booleanValue = true; }}
Value of Field doubleValue is 9999999.34567
Value of Field intValue is 9999999
Value of Field floatValue is 9999999.0
Value of Field booleanValue is true
References: https://docs.oracle.com/javase/8/docs/api/java/lang/reflect/Field.html#get-java.lang.Object-
Java-Field
Java-Functions
java-lang-reflect-package
Java
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Object Oriented Programming (OOPs) Concept in Java
How to iterate any Map in Java
HashMap in Java with Examples
ArrayList in Java
Multidimensional Arrays in Java
Collections in Java
Set in Java
Stream In Java
Initializing a List in Java
Singleton Class in Java | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n26 Aug, 2019"
},
{
"code": null,
"e": 665,
"s": 28,
"text": "The get() method of java.lang.reflect.Field used to get the value of the field object. If Field has a primitive type then the value of the field is automatically wrapped in an object. If the field is a static field, the argument of obj is ignored; it may be null Otherwise, the underlying field is an instance field. This method throws a NullPointerException if the specified obj argument is null and an IllegalArgumentException If the specified object is not an instance of the class or interface declaring the underlying field. If the field is hidden in the type of obj, the field’s value is obtained according to the preceding rules."
},
{
"code": null,
"e": 673,
"s": 665,
"text": "Syntax:"
},
{
"code": null,
"e": 793,
"s": 673,
"text": "public double get(Object obj)\n throws IllegalArgumentException,\n IllegalAccessException\n"
},
{
"code": null,
"e": 901,
"s": 793,
"text": "Parameters: This method accepts a single parameter obj which is the object to extract the field value from."
},
{
"code": null,
"e": 1062,
"s": 901,
"text": "Return value: This method returns the value of the represented field in object obj; primitive values are wrapped in an appropriate object before being returned."
},
{
"code": null,
"e": 1113,
"s": 1062,
"text": "Exception: This method throws following Exception:"
},
{
"code": null,
"e": 1577,
"s": 1113,
"text": "IllegalAccessException– if this Field object is enforcing Java language access control and the underlying field is inaccessible.IllegalArgumentException– if the specified object is not an instance of the class or interface declaring the underlying field (or a subclass or implementor thereof).NullPointerException– if the specified object is null and the field is an instance field.ExceptionInInitializerError– if the initialization provoked by this method fails."
},
{
"code": null,
"e": 1706,
"s": 1577,
"text": "IllegalAccessException– if this Field object is enforcing Java language access control and the underlying field is inaccessible."
},
{
"code": null,
"e": 1872,
"s": 1706,
"text": "IllegalArgumentException– if the specified object is not an instance of the class or interface declaring the underlying field (or a subclass or implementor thereof)."
},
{
"code": null,
"e": 1962,
"s": 1872,
"text": "NullPointerException– if the specified object is null and the field is an instance field."
},
{
"code": null,
"e": 2044,
"s": 1962,
"text": "ExceptionInInitializerError– if the initialization provoked by this method fails."
},
{
"code": null,
"e": 2094,
"s": 2044,
"text": "Below programs illustrate get() method:Program 1:"
},
{
"code": "// Java program to demonstrate get() method import java.lang.reflect.Field; public class GFG { public static void main(String[] args) throws Exception { // Create the User class object User user = new User(); // Get the all field objects of User class Field[] fields = User.class.getFields(); for (int i = 0; i < fields.length; i++) { // get value of the fields Object value = fields[i].get(user); // print result System.out.println(\"Value of Field \" + fields[i].getName() + \" is \" + value); } }} // sample User classclass User { // static double values public static double Marks = 34.13; public static int Fees = 34199; public static String name = \"Aman\"; public static double getMarks() { return Marks; } public static void setMarks(double marks) { Marks = marks; } public static int getFees() { return Fees; } public static void setFees(int fees) { Fees = fees; } public static String getName() { return name; } public static void setName(String name) { User.name = name; }}",
"e": 3372,
"s": 2094,
"text": null
},
{
"code": null,
"e": 3460,
"s": 3372,
"text": "Value of Field Marks is 34.13\nValue of Field Fees is 34199\nValue of Field name is Aman\n"
},
{
"code": null,
"e": 3471,
"s": 3460,
"text": "Program 2:"
},
{
"code": "// Java program to demonstrate get() method import java.lang.reflect.Field; public class GFG { public static void main(String[] args) throws Exception { // Create the RealNumbers class object Fields field = new Fields(); // Get the all field objects of User class Field[] fieldsOfFieldClass = Fields.class.getFields(); for (int i = 0; i < fieldsOfFieldClass.length; i++) { // get value Object value = fieldsOfFieldClass[i] .get(field); // print result System.out.println( \"Value of Field \" + fieldsOfFieldClass[i].getName() + \" is \" + value); } } // RealNumbers class static class Fields { // double field public static final double doubleValue = 9999999.34567; public static final int intValue = 9999999; public static final float floatValue = 9999999.34567f; public static final boolean booleanValue = true; }}",
"e": 4601,
"s": 3471,
"text": null
},
{
"code": null,
"e": 4756,
"s": 4601,
"text": "Value of Field doubleValue is 9999999.34567\nValue of Field intValue is 9999999\nValue of Field floatValue is 9999999.0\nValue of Field booleanValue is true\n"
},
{
"code": null,
"e": 4861,
"s": 4756,
"text": "References: https://docs.oracle.com/javase/8/docs/api/java/lang/reflect/Field.html#get-java.lang.Object-"
},
{
"code": null,
"e": 4872,
"s": 4861,
"text": "Java-Field"
},
{
"code": null,
"e": 4887,
"s": 4872,
"text": "Java-Functions"
},
{
"code": null,
"e": 4913,
"s": 4887,
"text": "java-lang-reflect-package"
},
{
"code": null,
"e": 4918,
"s": 4913,
"text": "Java"
},
{
"code": null,
"e": 4923,
"s": 4918,
"text": "Java"
},
{
"code": null,
"e": 5021,
"s": 4923,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 5072,
"s": 5021,
"text": "Object Oriented Programming (OOPs) Concept in Java"
},
{
"code": null,
"e": 5103,
"s": 5072,
"text": "How to iterate any Map in Java"
},
{
"code": null,
"e": 5133,
"s": 5103,
"text": "HashMap in Java with Examples"
},
{
"code": null,
"e": 5151,
"s": 5133,
"text": "ArrayList in Java"
},
{
"code": null,
"e": 5183,
"s": 5151,
"text": "Multidimensional Arrays in Java"
},
{
"code": null,
"e": 5203,
"s": 5183,
"text": "Collections in Java"
},
{
"code": null,
"e": 5215,
"s": 5203,
"text": "Set in Java"
},
{
"code": null,
"e": 5230,
"s": 5215,
"text": "Stream In Java"
},
{
"code": null,
"e": 5258,
"s": 5230,
"text": "Initializing a List in Java"
}
] |
HTML <b> Tag | 17 Mar, 2022
Example: This simple code example illustrates highlighting the text by making it as bold text in HTML.
HTML
<!DOCTYPE html><html><body> <h1>GeeksforGeeks</h1> <h3>HTML b tag</h3> <p> A <b>Computer Science portal</b> for geeks. It contains well written, well thought and well explained <b>computer science and programming articles.</b> </p> </body></html>
Output:
The <b> tag in HTML is used to specify the bold text without any extra importance. The text is written within <b> tag display in bold size. You can do that by using font-weight: bold; property in CSS. It is a container tag that contains an opening tag, content & closing tag. There is a similar tag, <strong> tag that is the parsed tag and used to show the importance of the text & has a similar effect on content.
As per the HTML5 specification, the <b> tag should be used as a last option to resort when no other tag is more appropriate. The HTML5 specification states that for headings, it should be depicted by the <h1> to <h6> tags, for emphasized text, it must be depicted by the <em> tag & similar wise, the important text by the <strong> tag, & for marked/highlighted text, it should be denoted with the <mark> tag.
Syntax:
<b> Contents... </b>
Accepted Attributes: This is a Global attribute, and can be used on any HTML element.
Example 1: In this example, we have used the <b> tag & <p> tag to illustrates the difference in the text appearance & their sizes.
HTML
<!DOCTYPE html><html><body> <h1>GeeksforGeeks</h1> <h3>HTML b tag</h3> <!--paragraph Tag --> <p>This is normal paragraph Tag text</p> <!--bold Tag --> <b>This is bold Tag text</b></body></html>
Output:
Example 2: In this example, we have used the CSS font-weight property whose value is set to bold to make the text bold.
HTML
<!DOCTYPE html><html><body> <h1>GeeksforGeeks</h1> <h3>HTML b tag</h3> <!--paragraph Tag --> <p>This is normal paragraph Tag text</p> <!--Using CSS in paragraph Tag for making text bold --> <p style ="font-weight: bold">This is bold text using CSS</p> </body></html>
Output:
Supported Browsers:
Google Chrome 93.0
Internet Explorer 11.0
Microsoft Edge 93.0
Firefox 92.0
Opera 78.0
Safari 14.1
shubhamyadav4
bhaskargeeksforgeeks
vshylaja
HTML-Tags
HTML
HTML
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here. | [
{
"code": null,
"e": 53,
"s": 25,
"text": "\n17 Mar, 2022"
},
{
"code": null,
"e": 156,
"s": 53,
"text": "Example: This simple code example illustrates highlighting the text by making it as bold text in HTML."
},
{
"code": null,
"e": 161,
"s": 156,
"text": "HTML"
},
{
"code": "<!DOCTYPE html><html><body> <h1>GeeksforGeeks</h1> <h3>HTML b tag</h3> <p> A <b>Computer Science portal</b> for geeks. It contains well written, well thought and well explained <b>computer science and programming articles.</b> </p> </body></html>",
"e": 443,
"s": 161,
"text": null
},
{
"code": null,
"e": 451,
"s": 443,
"text": "Output:"
},
{
"code": null,
"e": 867,
"s": 451,
"text": "The <b> tag in HTML is used to specify the bold text without any extra importance. The text is written within <b> tag display in bold size. You can do that by using font-weight: bold; property in CSS. It is a container tag that contains an opening tag, content & closing tag. There is a similar tag, <strong> tag that is the parsed tag and used to show the importance of the text & has a similar effect on content. "
},
{
"code": null,
"e": 1276,
"s": 867,
"text": "As per the HTML5 specification, the <b> tag should be used as a last option to resort when no other tag is more appropriate. The HTML5 specification states that for headings, it should be depicted by the <h1> to <h6> tags, for emphasized text, it must be depicted by the <em> tag & similar wise, the important text by the <strong> tag, & for marked/highlighted text, it should be denoted with the <mark> tag."
},
{
"code": null,
"e": 1284,
"s": 1276,
"text": "Syntax:"
},
{
"code": null,
"e": 1305,
"s": 1284,
"text": "<b> Contents... </b>"
},
{
"code": null,
"e": 1391,
"s": 1305,
"text": "Accepted Attributes: This is a Global attribute, and can be used on any HTML element."
},
{
"code": null,
"e": 1522,
"s": 1391,
"text": "Example 1: In this example, we have used the <b> tag & <p> tag to illustrates the difference in the text appearance & their sizes."
},
{
"code": null,
"e": 1527,
"s": 1522,
"text": "HTML"
},
{
"code": "<!DOCTYPE html><html><body> <h1>GeeksforGeeks</h1> <h3>HTML b tag</h3> <!--paragraph Tag --> <p>This is normal paragraph Tag text</p> <!--bold Tag --> <b>This is bold Tag text</b></body></html>",
"e": 1749,
"s": 1527,
"text": null
},
{
"code": null,
"e": 1757,
"s": 1749,
"text": "Output:"
},
{
"code": null,
"e": 1877,
"s": 1757,
"text": "Example 2: In this example, we have used the CSS font-weight property whose value is set to bold to make the text bold."
},
{
"code": null,
"e": 1882,
"s": 1877,
"text": "HTML"
},
{
"code": "<!DOCTYPE html><html><body> <h1>GeeksforGeeks</h1> <h3>HTML b tag</h3> <!--paragraph Tag --> <p>This is normal paragraph Tag text</p> <!--Using CSS in paragraph Tag for making text bold --> <p style =\"font-weight: bold\">This is bold text using CSS</p> </body></html>",
"e": 2179,
"s": 1882,
"text": null
},
{
"code": null,
"e": 2187,
"s": 2179,
"text": "Output:"
},
{
"code": null,
"e": 2208,
"s": 2187,
"text": "Supported Browsers: "
},
{
"code": null,
"e": 2227,
"s": 2208,
"text": "Google Chrome 93.0"
},
{
"code": null,
"e": 2250,
"s": 2227,
"text": "Internet Explorer 11.0"
},
{
"code": null,
"e": 2270,
"s": 2250,
"text": "Microsoft Edge 93.0"
},
{
"code": null,
"e": 2283,
"s": 2270,
"text": "Firefox 92.0"
},
{
"code": null,
"e": 2294,
"s": 2283,
"text": "Opera 78.0"
},
{
"code": null,
"e": 2306,
"s": 2294,
"text": "Safari 14.1"
},
{
"code": null,
"e": 2320,
"s": 2306,
"text": "shubhamyadav4"
},
{
"code": null,
"e": 2341,
"s": 2320,
"text": "bhaskargeeksforgeeks"
},
{
"code": null,
"e": 2350,
"s": 2341,
"text": "vshylaja"
},
{
"code": null,
"e": 2360,
"s": 2350,
"text": "HTML-Tags"
},
{
"code": null,
"e": 2365,
"s": 2360,
"text": "HTML"
},
{
"code": null,
"e": 2370,
"s": 2365,
"text": "HTML"
}
] |
Python program for sum of consecutive numbers with overlapping in lists | 01 Oct, 2020
Given a List, perform summation of consecutive elements, by overlapping.
Input : test_list = [4, 7, 3, 2] Output : [11, 10, 5, 6] Explanation : 4 + 7 = 11, 7 + 3 = 10, 3 + 2 = 5, and 2 + 4 = 6.
Input : test_list = [4, 7, 3] Output : [11, 10, 7] Explanation : 4+7=11, 7+3=10, 3+4=7.
Method 1 : Using list comprehension + zip()
In this, we zip list, with consecutive elements’ using zip() and then perform summation using + operator. The iteration part is done using list comprehension.
Python3
# initializing listtest_list = [4, 7, 3, 2, 9, 2, 1] # printing original listprint("The original list is : " + str(test_list)) # using zip() to get pairing.# last element is joined with first for pairingres = [a + b for a, b in zip(test_list, test_list[1:] + [test_list[0]])] # printing resultprint("The Consecutive overlapping Summation : " + str(res))
The original list is : [4, 7, 3, 2, 9, 2, 1]
The Consecutive overlapping Summation : [11, 10, 5, 11, 11, 3, 5]
Method #2 : Using sum() + list comprehension + zip()
In this, we perform the task of getting summation using sum() and rest all functionalities kept similar to the above method.
Python3
# Python3 code to demonstrate working of # Consecutive overlapping Summation# Using sum() + list comprehension + zip() # initializing listtest_list = [4, 7, 3, 2, 9, 2, 1] # printing original listprint("The original list is : " + str(test_list)) # using sum() to compute elements sum# last element is joined with first for pairingres = [sum(sub) for sub in zip(test_list, test_list[1:] + [test_list[0]])] # printing result print("The Consecutive overlapping Summation : " + str(res))
The original list is : [4, 7, 3, 2, 9, 2, 1]
The Consecutive overlapping Summation : [11, 10, 5, 11, 11, 3, 5]
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": "\n01 Oct, 2020"
},
{
"code": null,
"e": 101,
"s": 28,
"text": "Given a List, perform summation of consecutive elements, by overlapping."
},
{
"code": null,
"e": 223,
"s": 101,
"text": "Input : test_list = [4, 7, 3, 2] Output : [11, 10, 5, 6] Explanation : 4 + 7 = 11, 7 + 3 = 10, 3 + 2 = 5, and 2 + 4 = 6. "
},
{
"code": null,
"e": 313,
"s": 223,
"text": "Input : test_list = [4, 7, 3] Output : [11, 10, 7] Explanation : 4+7=11, 7+3=10, 3+4=7. "
},
{
"code": null,
"e": 357,
"s": 313,
"text": "Method 1 : Using list comprehension + zip()"
},
{
"code": null,
"e": 516,
"s": 357,
"text": "In this, we zip list, with consecutive elements’ using zip() and then perform summation using + operator. The iteration part is done using list comprehension."
},
{
"code": null,
"e": 524,
"s": 516,
"text": "Python3"
},
{
"code": "# initializing listtest_list = [4, 7, 3, 2, 9, 2, 1] # printing original listprint(\"The original list is : \" + str(test_list)) # using zip() to get pairing.# last element is joined with first for pairingres = [a + b for a, b in zip(test_list, test_list[1:] + [test_list[0]])] # printing resultprint(\"The Consecutive overlapping Summation : \" + str(res))",
"e": 881,
"s": 524,
"text": null
},
{
"code": null,
"e": 994,
"s": 881,
"text": "The original list is : [4, 7, 3, 2, 9, 2, 1]\nThe Consecutive overlapping Summation : [11, 10, 5, 11, 11, 3, 5]\n\n"
},
{
"code": null,
"e": 1047,
"s": 994,
"text": "Method #2 : Using sum() + list comprehension + zip()"
},
{
"code": null,
"e": 1172,
"s": 1047,
"text": "In this, we perform the task of getting summation using sum() and rest all functionalities kept similar to the above method."
},
{
"code": null,
"e": 1180,
"s": 1172,
"text": "Python3"
},
{
"code": "# Python3 code to demonstrate working of # Consecutive overlapping Summation# Using sum() + list comprehension + zip() # initializing listtest_list = [4, 7, 3, 2, 9, 2, 1] # printing original listprint(\"The original list is : \" + str(test_list)) # using sum() to compute elements sum# last element is joined with first for pairingres = [sum(sub) for sub in zip(test_list, test_list[1:] + [test_list[0]])] # printing result print(\"The Consecutive overlapping Summation : \" + str(res))",
"e": 1670,
"s": 1180,
"text": null
},
{
"code": null,
"e": 1786,
"s": 1673,
"text": "The original list is : [4, 7, 3, 2, 9, 2, 1]\nThe Consecutive overlapping Summation : [11, 10, 5, 11, 11, 3, 5]\n\n"
},
{
"code": null,
"e": 1809,
"s": 1788,
"text": "Python list-programs"
},
{
"code": null,
"e": 1816,
"s": 1809,
"text": "Python"
},
{
"code": null,
"e": 1832,
"s": 1816,
"text": "Python Programs"
}
] |
Python | Introduction to Web development using Flask | 18 May, 2020
What is Flask?Flask is an API of Python that allows us to build up web-applications. It was developed by Armin Ronacher. Flask’s framework is more explicit than Django’s framework and is also easier to learn because it has less base code to implement a simple web-Application. A Web-Application Framework or Web Framework is the collection of modules and libraries that helps the developer to write applications without writing the low-level codes such as protocols, thread management, etc. Flask is based on WSGI(Web Server Gateway Interface) toolkit and Jinja2 template engine.
Getting Started With Flask:Python 2.6 or higher is required for the installation of the Flask. You can start by import Flask from the flask package on any python IDE. For installation on any environment, you can click on the installation link given below.To test that if the installation is working, check out this code given below.
# an object of WSGI applicationfrom flask import Flask app = Flask(__name__) # Flask constructor # A decorator used to tell the application# which URL is associated [email protected]('/') def hello(): return 'HELLO' if __name__=='__main__': app.run()
‘/’ URL is bound with hello() function. When the home page of the webserver is opened in the browser, the output of this function will be rendered accordingly.
The Flask application is started by calling the run() function. The method should be restarted manually for any change in the code. To overcome this, the debug support is enabled so as to track any error.
app.debug = Trueapp.run()app.run(debug = True)
Routing:Nowadays, the web frameworks provide routing technique so that user can remember the URLs. It is useful to access the web page directly without navigating from the Home page. It is done through the following route() decorator, to bind the URL to a function.
# decorator to route [email protected](‘/hello’) # binding to the function of route def hello_world(): return ‘hello world’
If a user visits http://localhost:5000/hello URL, the output of the hello_world() function will be rendered in the browser. The add_url_rule() function of an application object can also be used to bind URL with the function as in above example.
def hello_world(): return ‘hello world’app.add_url_rule(‘/’, ‘hello’, hello_world)
Using Variables in Flask:The Variables in the flask is used to build a URL dynamically by adding the variable parts to the rule parameter. This variable part is marked as. It is passed as keyword argument. See the example below
from flask import Flaskapp = Flask(__name__) # routing the decorator function [email protected]('/hello/<name>') def hello_name(name): return 'Hello %s!' % name if __name__ == '__main__': app.run(debug = True)
Save the above example as hello.py and run from power shell. Next, open the browser and enter the URL http://localhost:5000/hello/GeeksforGeeks.
Output:
Hello GeeksforGeeks!
In the above example, the parameter of route() decorator contains the variable part attached to the URL ‘/hello’ as an argument. Hence, if URL like http://localhost:5000/hello/GeeksforGeeks is entered then ‘GeeksforGeeks’ will be passed to the hello() function as an argument.
In addition to the default string variable part, other data types like int, float, and path(for directory separator channel which can take slash) are also used. The URL rules of Flask are based on Werkzeug’s routing module. This ensures that the URLs formed are unique and based on precedents laid down by Apache.
Examples:
from flask import Flaskapp = Flask(__name__) @app.route('/blog/<postID>')def show_blog(postID): return 'Blog Number %d' % postID @app.route('/rev/<revNo>')def revision(revNo): return 'Revision Number %f' % revNo if __name__ == '__main__': app.run() # say the URL is http://localhost:5000/blog/555
Output :
Blog Number 555
# Enter this URL in the browser ? http://localhost:5000/rev/1.1
Revision Number: 1.100000
Building URL in FLask:Dynamic Building of the URL for a specific function is done using url_for() function. The function accepts the name of the function as first argument, and one or more keyword arguments. See this example
from flask import Flask, redirect, url_forapp = Flask(__name__) @app.route('/admin') #decorator for route(argument) functiondef hello_admin(): #binding to hello_admin call return 'Hello Admin' @app.route('/guest/<guest>')def hello_guest(guest): #binding to hello_guest call return 'Hello %s as Guest' % guest @app.route('/user/<name>')def hello_user(name): if name =='admin': #dynamic binding of URL to function return redirect(url_for('hello_admin')) else: return redirect(url_for('hello_guest', guest = name)) if __name__ == '__main__': app.run(debug = True)
To test this, save the above code and run through python shell and then open browser and enter the following URL:-
Input: http://localhost:5000/user/admin
Output: Hello Admin
Input: http://localhost:5000/user/ABC
Output: Hello ABC as Guest
The above code has a function named user(name), accepts the value through input URL. It checks that the received argument matches the ‘admin’ argument or not. If it matches, then the function hello_admin() is called else the hello_guest() is called.
Flask support various HTTP protocols for data retrieval from the specified URL, these can be defined as:-
Handling Static Files :A web application often requires a static file such as javascript or a CSS file to render the display of the web page in browser. Usually, the web server is configured to set them, but during development, these files are served as static folder in your package or next to the module. See the example in JavaScript given below:
from flask import Flask, render_templateapp = Flask(__name__) @app.route("/")def index(): return render_template("index.html") if __name__ == '__main__': app.run(debug = True)
The following HTML code:This will be inside templates folder which will be sibling of the python file we wrote above
<html> <head> <script type = "text/javascript" src = "{{ url_for('static', filename = 'hello.js') }}" ></script> </head> <body> <input type = "button" onclick = "sayHello()" value = "Say Hello" /> </body> </html>
The JavaScript file for hello.js is:This code will be inside static folder which will be sibling of the templates folder
function sayHello() { alert("Hello World")}
The above hello.js file will be rendered accordingly to the HTML file.Object Request of Data from a client’s web page is send to the server as a global request object. It is then processed by importing the Flask module. These consist of attributes like Form(containing Key-Value Pair), Args(parsed URL after question mark(?)), Cookies(contain Cookie names and Values), Files(data pertaining to uploaded file) and Method(current request). Cookies:A Cookie is a form of text file which is stored on a client’s computer, whose purpose is to remember and track data pertaining to client’s usage in order to improve the website according to the user’s experience and statistic of webpage.The Request object contains cookie’s attribute. It is the dictionary object of all the cookie variables and their corresponding values. It also contains expiry time of itself. In Flask, cookie are set on response object.See the example given below:-
from flask import Flaskapp = Flask(__name__)@app.route('/')def index(): return render_template('index.html')
HTML code for index.html
<html> <body> <form action = "/setcookie" method = "POST"> <p><h3>Enter userID</h3></p> <p><input type = 'text' name = 'nm'/></p> <p><input type = 'submit' value = 'Login'/></p> </form> </body></html>
Add this code to the python file defined above
@app.route('/setcookie', methods = ['POST', 'GET'])def setcookie(): if request.method == 'POST': user = request.form['nm'] resp = make_response(render_template('cookie.html')) resp.set_cookie('userID', user) return resp @app.route('/getcookie')def getcookie(): name = request.cookies.get('userID') return '<h1>welcome '+name+'</h1>'
HTML code for cookie.html
<html> <body> <a href="/getcookie">Click me to get Cookie</a> </body></html>
Run the above application and visit link on Browser http://localhost:5000/The form is set to ‘/setcookie’ and function set contains a Cookie name userID that will be rendered to another webpage. The ‘cookie.html’ contains hyperlink to another view function getcookie(), which displays the value in browser. Sessions in Flask:In Session, the data is stored on Server. It can be defined as a time interval in which the client logs into a server until the user logs out. The data in between them are held in a temporary folder on the Server. Each user is assigned with a specific Session ID. The Session object is a dictionary that contains the key-value pair of the variables associated with the session. A SECRET_KEY is used to store the encrypted data on the cookie.
For example:
Session[key] = value // stores the session value
Session.pop(key, None) // releases a session variable
Other Important Flask Functions:redirect(): It is used to return the response of an object and redirects the user to another target location with specified status code.
Syntax: Flask.redirect(location, statuscode, response)
//location is used to redirect to the desired URL//statuscode sends header value, default 302//response is used to initiate response.
abort: It is used to handle the error in the code.
Syntax: Flask.abort(code)
The code parameter can take the following values to handle the error accordingly:
400 – For Bad Request
401 – For Unauthenticated
403 – For Forbidden request
404 – For Not Found
406 – For Not acceptable
425 – For Unsupported Media
429 – Too many Requests
File-Uploading in Flask:File Uploading in Flask is very easy. It needs an HTML form with enctype attribute and URL handler, that fetches file and saves the object to the desired location. Files are temporary stored on server and then on the desired location.The HTML Syntax that handle the uploading URL is :
form action="http://localhost:5000/uploader" method="POST" enctype="multipart/form-data"
and following python code of Flask is:
from flask import Flask, render_template, requestfrom werkzeug import secure_filenameapp = Flask(__name__) @app.route('/upload')def upload_file(): return render_template('upload.html') @app.route('/uploader', methods = ['GET', 'POST'])def upload_file(): if request.method == 'POST': f = request.files['file'] f.save(secure_filename(f.filename)) return 'file uploaded successfully' if __name__ == '__main__': app.run(debug = True)
Sending Form Data to the HTML File of Server:A Form in HTML is used to collect the information of required entries which are then forwarded and stored on the server. These can be requested to read or modify the form. The flask provides this facility by using the URL rule. In the given example below, the ‘/’ URL renders a web page(student.html) which has a form. The data filled in it is posted to the ‘/result’ URL which triggers the result() function. The results() function collects form data present in request.form in a dictionary object and sends it for rendering to result.html.
from flask import Flask, render_template, requestapp = Flask(__name__)@app.route('/')def student(): return render_template('student.html') @app.route('/result', methods = ['POST', 'GET'])def result(): if request.method == 'POST': result = request.form return render_template("result.html", result = result) if __name__ == '__main__': app.run(debug = True)
<!doctype html><html> <body> <table border = 1> {% for key, value in result.items() %} <tr> <th> {{ key }} </th> <td> {{ value }} </td> </tr> {% endfor %} </table> </body></html>
<html> <body> <form action = "http://localhost:5000/result" method = "POST"> <p>Name <input type = "text" name = "Name" /></p> <p>Physics <input type = "text" name = "Physics" /></p> <p>Chemistry <input type = "text" name = "chemistry" /></p> <p>Maths <input type ="text" name = "Maths" /></p> <p><input type = "submit" value = "submit" /></p> </form> </body></html>
Message Flashing:It can be defined as a pop-up or a dialog box that appears on the web-page or like alert in JavaScript, which are used to inform the user. This in flask can be done by using the method flash() in Flask. It passes the message to the next template.
Syntax: flash(message, category)
message is actual text to be displayed and category is optional which is to render any error or info.
Example :
from flask import Flaskapp = Flask(__name__) # /login display login [email protected]('/login', methods = ['GET', 'POST']) # login function verify username and passworddef login(): error = None if request.method == 'POST': if request.form['username'] != 'admin' or \ request.form['password'] != 'admin': error = 'Invalid username or password. Please try again !' else: # flashes on successful login flash('You were successfully logged in') return redirect(url_for('index')) return render_template('login.html', error = error)
Reference: Flask Documentation
aashray18521
Picked
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here. | [
{
"code": null,
"e": 54,
"s": 26,
"text": "\n18 May, 2020"
},
{
"code": null,
"e": 634,
"s": 54,
"text": "What is Flask?Flask is an API of Python that allows us to build up web-applications. It was developed by Armin Ronacher. Flask’s framework is more explicit than Django’s framework and is also easier to learn because it has less base code to implement a simple web-Application. A Web-Application Framework or Web Framework is the collection of modules and libraries that helps the developer to write applications without writing the low-level codes such as protocols, thread management, etc. Flask is based on WSGI(Web Server Gateway Interface) toolkit and Jinja2 template engine."
},
{
"code": null,
"e": 967,
"s": 634,
"text": "Getting Started With Flask:Python 2.6 or higher is required for the installation of the Flask. You can start by import Flask from the flask package on any python IDE. For installation on any environment, you can click on the installation link given below.To test that if the installation is working, check out this code given below."
},
{
"code": "# an object of WSGI applicationfrom flask import Flask app = Flask(__name__) # Flask constructor # A decorator used to tell the application# which URL is associated [email protected]('/') def hello(): return 'HELLO' if __name__=='__main__': app.run()",
"e": 1236,
"s": 967,
"text": null
},
{
"code": null,
"e": 1396,
"s": 1236,
"text": "‘/’ URL is bound with hello() function. When the home page of the webserver is opened in the browser, the output of this function will be rendered accordingly."
},
{
"code": null,
"e": 1601,
"s": 1396,
"text": "The Flask application is started by calling the run() function. The method should be restarted manually for any change in the code. To overcome this, the debug support is enabled so as to track any error."
},
{
"code": "app.debug = Trueapp.run()app.run(debug = True)",
"e": 1648,
"s": 1601,
"text": null
},
{
"code": null,
"e": 1915,
"s": 1648,
"text": " Routing:Nowadays, the web frameworks provide routing technique so that user can remember the URLs. It is useful to access the web page directly without navigating from the Home page. It is done through the following route() decorator, to bind the URL to a function."
},
{
"code": "# decorator to route [email protected](‘/hello’) # binding to the function of route def hello_world(): return ‘hello world’",
"e": 2045,
"s": 1915,
"text": null
},
{
"code": null,
"e": 2290,
"s": 2045,
"text": "If a user visits http://localhost:5000/hello URL, the output of the hello_world() function will be rendered in the browser. The add_url_rule() function of an application object can also be used to bind URL with the function as in above example."
},
{
"code": "def hello_world(): return ‘hello world’app.add_url_rule(‘/’, ‘hello’, hello_world)",
"e": 2375,
"s": 2290,
"text": null
},
{
"code": null,
"e": 2604,
"s": 2375,
"text": " Using Variables in Flask:The Variables in the flask is used to build a URL dynamically by adding the variable parts to the rule parameter. This variable part is marked as. It is passed as keyword argument. See the example below"
},
{
"code": "from flask import Flaskapp = Flask(__name__) # routing the decorator function [email protected]('/hello/<name>') def hello_name(name): return 'Hello %s!' % name if __name__ == '__main__': app.run(debug = True)",
"e": 2824,
"s": 2604,
"text": null
},
{
"code": null,
"e": 2969,
"s": 2824,
"text": "Save the above example as hello.py and run from power shell. Next, open the browser and enter the URL http://localhost:5000/hello/GeeksforGeeks."
},
{
"code": null,
"e": 2977,
"s": 2969,
"text": "Output:"
},
{
"code": null,
"e": 2998,
"s": 2977,
"text": "Hello GeeksforGeeks!"
},
{
"code": null,
"e": 3275,
"s": 2998,
"text": "In the above example, the parameter of route() decorator contains the variable part attached to the URL ‘/hello’ as an argument. Hence, if URL like http://localhost:5000/hello/GeeksforGeeks is entered then ‘GeeksforGeeks’ will be passed to the hello() function as an argument."
},
{
"code": null,
"e": 3589,
"s": 3275,
"text": "In addition to the default string variable part, other data types like int, float, and path(for directory separator channel which can take slash) are also used. The URL rules of Flask are based on Werkzeug’s routing module. This ensures that the URLs formed are unique and based on precedents laid down by Apache."
},
{
"code": null,
"e": 3599,
"s": 3589,
"text": "Examples:"
},
{
"code": "from flask import Flaskapp = Flask(__name__) @app.route('/blog/<postID>')def show_blog(postID): return 'Blog Number %d' % postID @app.route('/rev/<revNo>')def revision(revNo): return 'Revision Number %f' % revNo if __name__ == '__main__': app.run() # say the URL is http://localhost:5000/blog/555",
"e": 3906,
"s": 3599,
"text": null
},
{
"code": null,
"e": 3915,
"s": 3906,
"text": "Output :"
},
{
"code": null,
"e": 4023,
"s": 3915,
"text": "Blog Number 555\n\n# Enter this URL in the browser ? http://localhost:5000/rev/1.1\nRevision Number: 1.100000\n"
},
{
"code": null,
"e": 4249,
"s": 4023,
"text": " Building URL in FLask:Dynamic Building of the URL for a specific function is done using url_for() function. The function accepts the name of the function as first argument, and one or more keyword arguments. See this example"
},
{
"code": "from flask import Flask, redirect, url_forapp = Flask(__name__) @app.route('/admin') #decorator for route(argument) functiondef hello_admin(): #binding to hello_admin call return 'Hello Admin' @app.route('/guest/<guest>')def hello_guest(guest): #binding to hello_guest call return 'Hello %s as Guest' % guest @app.route('/user/<name>')def hello_user(name): if name =='admin': #dynamic binding of URL to function return redirect(url_for('hello_admin')) else: return redirect(url_for('hello_guest', guest = name)) if __name__ == '__main__': app.run(debug = True)",
"e": 4853,
"s": 4249,
"text": null
},
{
"code": null,
"e": 4968,
"s": 4853,
"text": "To test this, save the above code and run through python shell and then open browser and enter the following URL:-"
},
{
"code": null,
"e": 5095,
"s": 4968,
"text": "Input: http://localhost:5000/user/admin\nOutput: Hello Admin \n\nInput: http://localhost:5000/user/ABC\nOutput: Hello ABC as Guest"
},
{
"code": null,
"e": 5345,
"s": 5095,
"text": "The above code has a function named user(name), accepts the value through input URL. It checks that the received argument matches the ‘admin’ argument or not. If it matches, then the function hello_admin() is called else the hello_guest() is called."
},
{
"code": null,
"e": 5451,
"s": 5345,
"text": "Flask support various HTTP protocols for data retrieval from the specified URL, these can be defined as:-"
},
{
"code": null,
"e": 5802,
"s": 5451,
"text": " Handling Static Files :A web application often requires a static file such as javascript or a CSS file to render the display of the web page in browser. Usually, the web server is configured to set them, but during development, these files are served as static folder in your package or next to the module. See the example in JavaScript given below:"
},
{
"code": "from flask import Flask, render_templateapp = Flask(__name__) @app.route(\"/\")def index(): return render_template(\"index.html\") if __name__ == '__main__': app.run(debug = True)",
"e": 5984,
"s": 5802,
"text": null
},
{
"code": null,
"e": 6101,
"s": 5984,
"text": "The following HTML code:This will be inside templates folder which will be sibling of the python file we wrote above"
},
{
"code": "<html> <head> <script type = \"text/javascript\" src = \"{{ url_for('static', filename = 'hello.js') }}\" ></script> </head> <body> <input type = \"button\" onclick = \"sayHello()\" value = \"Say Hello\" /> </body> </html>",
"e": 6352,
"s": 6101,
"text": null
},
{
"code": null,
"e": 6473,
"s": 6352,
"text": "The JavaScript file for hello.js is:This code will be inside static folder which will be sibling of the templates folder"
},
{
"code": "function sayHello() { alert(\"Hello World\")}",
"e": 6519,
"s": 6473,
"text": null
},
{
"code": null,
"e": 7452,
"s": 6519,
"text": "The above hello.js file will be rendered accordingly to the HTML file.Object Request of Data from a client’s web page is send to the server as a global request object. It is then processed by importing the Flask module. These consist of attributes like Form(containing Key-Value Pair), Args(parsed URL after question mark(?)), Cookies(contain Cookie names and Values), Files(data pertaining to uploaded file) and Method(current request). Cookies:A Cookie is a form of text file which is stored on a client’s computer, whose purpose is to remember and track data pertaining to client’s usage in order to improve the website according to the user’s experience and statistic of webpage.The Request object contains cookie’s attribute. It is the dictionary object of all the cookie variables and their corresponding values. It also contains expiry time of itself. In Flask, cookie are set on response object.See the example given below:-"
},
{
"code": "from flask import Flaskapp = Flask(__name__)@app.route('/')def index(): return render_template('index.html')",
"e": 7563,
"s": 7452,
"text": null
},
{
"code": null,
"e": 7588,
"s": 7563,
"text": "HTML code for index.html"
},
{
"code": "<html> <body> <form action = \"/setcookie\" method = \"POST\"> <p><h3>Enter userID</h3></p> <p><input type = 'text' name = 'nm'/></p> <p><input type = 'submit' value = 'Login'/></p> </form> </body></html>",
"e": 7840,
"s": 7588,
"text": null
},
{
"code": null,
"e": 7887,
"s": 7840,
"text": "Add this code to the python file defined above"
},
{
"code": "@app.route('/setcookie', methods = ['POST', 'GET'])def setcookie(): if request.method == 'POST': user = request.form['nm'] resp = make_response(render_template('cookie.html')) resp.set_cookie('userID', user) return resp @app.route('/getcookie')def getcookie(): name = request.cookies.get('userID') return '<h1>welcome '+name+'</h1>'",
"e": 8248,
"s": 7887,
"text": null
},
{
"code": null,
"e": 8274,
"s": 8248,
"text": "HTML code for cookie.html"
},
{
"code": "<html> <body> <a href=\"/getcookie\">Click me to get Cookie</a> </body></html>",
"e": 8366,
"s": 8274,
"text": null
},
{
"code": null,
"e": 9133,
"s": 8366,
"text": "Run the above application and visit link on Browser http://localhost:5000/The form is set to ‘/setcookie’ and function set contains a Cookie name userID that will be rendered to another webpage. The ‘cookie.html’ contains hyperlink to another view function getcookie(), which displays the value in browser. Sessions in Flask:In Session, the data is stored on Server. It can be defined as a time interval in which the client logs into a server until the user logs out. The data in between them are held in a temporary folder on the Server. Each user is assigned with a specific Session ID. The Session object is a dictionary that contains the key-value pair of the variables associated with the session. A SECRET_KEY is used to store the encrypted data on the cookie."
},
{
"code": null,
"e": 9146,
"s": 9133,
"text": "For example:"
},
{
"code": null,
"e": 9252,
"s": 9146,
"text": "Session[key] = value // stores the session value\nSession.pop(key, None) // releases a session variable"
},
{
"code": null,
"e": 9421,
"s": 9252,
"text": "Other Important Flask Functions:redirect(): It is used to return the response of an object and redirects the user to another target location with specified status code."
},
{
"code": null,
"e": 9476,
"s": 9421,
"text": "Syntax: Flask.redirect(location, statuscode, response)"
},
{
"code": null,
"e": 9610,
"s": 9476,
"text": "//location is used to redirect to the desired URL//statuscode sends header value, default 302//response is used to initiate response."
},
{
"code": null,
"e": 9661,
"s": 9610,
"text": "abort: It is used to handle the error in the code."
},
{
"code": null,
"e": 9688,
"s": 9661,
"text": "Syntax: Flask.abort(code)"
},
{
"code": null,
"e": 9770,
"s": 9688,
"text": "The code parameter can take the following values to handle the error accordingly:"
},
{
"code": null,
"e": 9792,
"s": 9770,
"text": "400 – For Bad Request"
},
{
"code": null,
"e": 9818,
"s": 9792,
"text": "401 – For Unauthenticated"
},
{
"code": null,
"e": 9846,
"s": 9818,
"text": "403 – For Forbidden request"
},
{
"code": null,
"e": 9866,
"s": 9846,
"text": "404 – For Not Found"
},
{
"code": null,
"e": 9891,
"s": 9866,
"text": "406 – For Not acceptable"
},
{
"code": null,
"e": 9919,
"s": 9891,
"text": "425 – For Unsupported Media"
},
{
"code": null,
"e": 9943,
"s": 9919,
"text": "429 – Too many Requests"
},
{
"code": null,
"e": 10253,
"s": 9943,
"text": " File-Uploading in Flask:File Uploading in Flask is very easy. It needs an HTML form with enctype attribute and URL handler, that fetches file and saves the object to the desired location. Files are temporary stored on server and then on the desired location.The HTML Syntax that handle the uploading URL is :"
},
{
"code": null,
"e": 10343,
"s": 10253,
"text": "form action=\"http://localhost:5000/uploader\" method=\"POST\" enctype=\"multipart/form-data\"\n"
},
{
"code": null,
"e": 10382,
"s": 10343,
"text": "and following python code of Flask is:"
},
{
"code": "from flask import Flask, render_template, requestfrom werkzeug import secure_filenameapp = Flask(__name__) @app.route('/upload')def upload_file(): return render_template('upload.html') @app.route('/uploader', methods = ['GET', 'POST'])def upload_file(): if request.method == 'POST': f = request.files['file'] f.save(secure_filename(f.filename)) return 'file uploaded successfully' if __name__ == '__main__': app.run(debug = True)",
"e": 10848,
"s": 10382,
"text": null
},
{
"code": null,
"e": 11436,
"s": 10848,
"text": " Sending Form Data to the HTML File of Server:A Form in HTML is used to collect the information of required entries which are then forwarded and stored on the server. These can be requested to read or modify the form. The flask provides this facility by using the URL rule. In the given example below, the ‘/’ URL renders a web page(student.html) which has a form. The data filled in it is posted to the ‘/result’ URL which triggers the result() function. The results() function collects form data present in request.form in a dictionary object and sends it for rendering to result.html."
},
{
"code": "from flask import Flask, render_template, requestapp = Flask(__name__)@app.route('/')def student(): return render_template('student.html') @app.route('/result', methods = ['POST', 'GET'])def result(): if request.method == 'POST': result = request.form return render_template(\"result.html\", result = result) if __name__ == '__main__': app.run(debug = True)",
"e": 11810,
"s": 11436,
"text": null
},
{
"code": "<!doctype html><html> <body> <table border = 1> {% for key, value in result.items() %} <tr> <th> {{ key }} </th> <td> {{ value }} </td> </tr> {% endfor %} </table> </body></html>",
"e": 12107,
"s": 11810,
"text": null
},
{
"code": "<html> <body> <form action = \"http://localhost:5000/result\" method = \"POST\"> <p>Name <input type = \"text\" name = \"Name\" /></p> <p>Physics <input type = \"text\" name = \"Physics\" /></p> <p>Chemistry <input type = \"text\" name = \"chemistry\" /></p> <p>Maths <input type =\"text\" name = \"Maths\" /></p> <p><input type = \"submit\" value = \"submit\" /></p> </form> </body></html>",
"e": 12533,
"s": 12107,
"text": null
},
{
"code": null,
"e": 12798,
"s": 12533,
"text": " Message Flashing:It can be defined as a pop-up or a dialog box that appears on the web-page or like alert in JavaScript, which are used to inform the user. This in flask can be done by using the method flash() in Flask. It passes the message to the next template."
},
{
"code": null,
"e": 12831,
"s": 12798,
"text": "Syntax: flash(message, category)"
},
{
"code": null,
"e": 12933,
"s": 12831,
"text": "message is actual text to be displayed and category is optional which is to render any error or info."
},
{
"code": null,
"e": 12943,
"s": 12933,
"text": "Example :"
},
{
"code": "from flask import Flaskapp = Flask(__name__) # /login display login [email protected]('/login', methods = ['GET', 'POST']) # login function verify username and passworddef login(): error = None if request.method == 'POST': if request.form['username'] != 'admin' or \\ request.form['password'] != 'admin': error = 'Invalid username or password. Please try again !' else: # flashes on successful login flash('You were successfully logged in') return redirect(url_for('index')) return render_template('login.html', error = error)",
"e": 13538,
"s": 12943,
"text": null
},
{
"code": null,
"e": 13571,
"s": 13540,
"text": "Reference: Flask Documentation"
},
{
"code": null,
"e": 13584,
"s": 13571,
"text": "aashray18521"
},
{
"code": null,
"e": 13591,
"s": 13584,
"text": "Picked"
},
{
"code": null,
"e": 13598,
"s": 13591,
"text": "Python"
}
] |
Thread functions in C/C++ | 23 Jun, 2020
In a Unix/Linux operating system, the C/C++ languages provide the POSIX thread(pthread) standard API(Application program Interface) for all thread related functions. It allows us to create multiple threads for concurrent process flow. It is most effective on multiprocessor or multi-core systems where threads can be implemented on a kernel-level for achieving the speed of execution. Gains can also be found in uni-processor systems by exploiting the latency in IO or other system functions that may halt a process.
We must include the pthread.h header file at the beginning of the script to use all the functions of the pthreads library. To execute the c file, we have to use the -pthread or -lpthread in the command line while compiling the file.
cc -pthread file.c or
cc -lpthread file.c
The functions defined in the pthreads library include:
pthread_create: used to create a new threadSyntax:int pthread_create(pthread_t * thread,
const pthread_attr_t * attr,
void * (*start_routine)(void *),
void *arg);
Parameters:thread: pointer to an unsigned integer value that returns the thread id of the thread created.attr: pointer to a structure that is used to define thread attributes like detached state, scheduling policy, stack address, etc. Set to NULL for default thread attributes.start_routine: pointer to a subroutine that is executed by the thread. The return type and parameter type of the subroutine must be of type void *. The function has a single attribute but if multiple values need to be passed to the function, a struct must be used.arg: pointer to void that contains the arguments to the function defined in the earlier argumentpthread_exit: used to terminate a threadSyntax:void pthread_exit(void *retval);
Parameters: This method accepts a mandatory parameter retval which is the pointer to an integer that stores the return status of the thread terminated. The scope of this variable must be global so that any thread waiting to join this thread may read the return status.pthread_join: used to wait for the termination of a thread.Syntax:int pthread_join(pthread_t th,
void **thread_return);
Parameter: This method accepts following parameters:th: thread id of the thread for which the current thread waits.thread_return: pointer to the location where the exit status of the thread mentioned in th is stored.pthread_self: used to get the thread id of the current thread.Syntax:pthread_t pthread_self(void);
pthread_equal: compares whether two threads are the same or not. If the two threads are equal, the function returns a non-zero value otherwise zero.Syntax:int pthread_equal(pthread_t t1,
pthread_t t2);
Parameters: This method accepts following parameters:t1: the thread id of the first threadt2: the thread id of the second threadpthread_cancel: used to send a cancellation request to a threadSyntax:int pthread_cancel(pthread_t thread);
Parameter: This method accepts a mandatory parameter thread which is the thread id of the thread to which cancel request is sent.pthread_detach: used to detach a thread. A detached thread does not require a thread to join on terminating. The resources of the thread are automatically released after terminating if the thread is detached.Syntax:int pthread_detach(pthread_t thread);
Parameter: This method accepts a mandatory parameter thread which is the thread id of the thread that must be detached.
pthread_create: used to create a new threadSyntax:int pthread_create(pthread_t * thread,
const pthread_attr_t * attr,
void * (*start_routine)(void *),
void *arg);
Parameters:thread: pointer to an unsigned integer value that returns the thread id of the thread created.attr: pointer to a structure that is used to define thread attributes like detached state, scheduling policy, stack address, etc. Set to NULL for default thread attributes.start_routine: pointer to a subroutine that is executed by the thread. The return type and parameter type of the subroutine must be of type void *. The function has a single attribute but if multiple values need to be passed to the function, a struct must be used.arg: pointer to void that contains the arguments to the function defined in the earlier argument
Syntax:
int pthread_create(pthread_t * thread,
const pthread_attr_t * attr,
void * (*start_routine)(void *),
void *arg);
Parameters:
thread: pointer to an unsigned integer value that returns the thread id of the thread created.
attr: pointer to a structure that is used to define thread attributes like detached state, scheduling policy, stack address, etc. Set to NULL for default thread attributes.
start_routine: pointer to a subroutine that is executed by the thread. The return type and parameter type of the subroutine must be of type void *. The function has a single attribute but if multiple values need to be passed to the function, a struct must be used.
arg: pointer to void that contains the arguments to the function defined in the earlier argument
pthread_exit: used to terminate a threadSyntax:void pthread_exit(void *retval);
Parameters: This method accepts a mandatory parameter retval which is the pointer to an integer that stores the return status of the thread terminated. The scope of this variable must be global so that any thread waiting to join this thread may read the return status.
Syntax:
void pthread_exit(void *retval);
Parameters: This method accepts a mandatory parameter retval which is the pointer to an integer that stores the return status of the thread terminated. The scope of this variable must be global so that any thread waiting to join this thread may read the return status.
pthread_join: used to wait for the termination of a thread.Syntax:int pthread_join(pthread_t th,
void **thread_return);
Parameter: This method accepts following parameters:th: thread id of the thread for which the current thread waits.thread_return: pointer to the location where the exit status of the thread mentioned in th is stored.
Syntax:
int pthread_join(pthread_t th,
void **thread_return);
Parameter: This method accepts following parameters:
th: thread id of the thread for which the current thread waits.
thread_return: pointer to the location where the exit status of the thread mentioned in th is stored.
pthread_self: used to get the thread id of the current thread.Syntax:pthread_t pthread_self(void);
Syntax:
pthread_t pthread_self(void);
pthread_equal: compares whether two threads are the same or not. If the two threads are equal, the function returns a non-zero value otherwise zero.Syntax:int pthread_equal(pthread_t t1,
pthread_t t2);
Parameters: This method accepts following parameters:t1: the thread id of the first threadt2: the thread id of the second thread
Syntax:
int pthread_equal(pthread_t t1,
pthread_t t2);
Parameters: This method accepts following parameters:
t1: the thread id of the first thread
t2: the thread id of the second thread
pthread_cancel: used to send a cancellation request to a threadSyntax:int pthread_cancel(pthread_t thread);
Parameter: This method accepts a mandatory parameter thread which is the thread id of the thread to which cancel request is sent.
Syntax:
int pthread_cancel(pthread_t thread);
Parameter: This method accepts a mandatory parameter thread which is the thread id of the thread to which cancel request is sent.
pthread_detach: used to detach a thread. A detached thread does not require a thread to join on terminating. The resources of the thread are automatically released after terminating if the thread is detached.Syntax:int pthread_detach(pthread_t thread);
Parameter: This method accepts a mandatory parameter thread which is the thread id of the thread that must be detached.
Syntax:
int pthread_detach(pthread_t thread);
Parameter: This method accepts a mandatory parameter thread which is the thread id of the thread that must be detached.
Example: A simple implementation of threads may be as follows:
// C program to show thread functions #include <pthread.h>#include <stdio.h>#include <stdlib.h> void* func(void* arg){ // detach the current thread // from the calling thread pthread_detach(pthread_self()); printf("Inside the thread\n"); // exit the current thread pthread_exit(NULL);} void fun(){ pthread_t ptid; // Creating a new thread pthread_create(&ptid, NULL, &func, NULL); printf("This line may be printed" " before thread terminates\n"); // The following line terminates // the thread manually // pthread_cancel(ptid); // Compare the two threads created if(pthread_equal(ptid, pthread_self()) printf("Threads are equal\n"); else printf("Threads are not equal\n"); // Waiting for the created thread to terminate pthread_join(ptid, NULL); printf("This line will be printed" " after thread ends\n"); pthread_exit(NULL);} // Driver codeint main(){ fun(); return 0;}
Output:
This line may be printed before thread terminates
Threads are not equal
Inside the thread
This line will be printed after thread ends
Explanation: Here two threads of execution are created in the code. The order of the lines of output of the two threads may be interchanged depending upon the thread processed earlier. The main thread waits on the newly created thread for exiting. Therefore, the final line of the output is printed only after the new thread exits. The threads can terminate independently of each other by not using the pthread_join function. If we want to terminate the new thread manually, we may use pthread_cancel to do it.
Note: If we use exit() instead of pthread_exit() to end a thread, the whole process with all associated threads will be terminated even if some of the threads may still be running.
Akanksha_Rai
C-Functions
C Language
Linux-Unix
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here. | [
{
"code": null,
"e": 52,
"s": 24,
"text": "\n23 Jun, 2020"
},
{
"code": null,
"e": 569,
"s": 52,
"text": "In a Unix/Linux operating system, the C/C++ languages provide the POSIX thread(pthread) standard API(Application program Interface) for all thread related functions. It allows us to create multiple threads for concurrent process flow. It is most effective on multiprocessor or multi-core systems where threads can be implemented on a kernel-level for achieving the speed of execution. Gains can also be found in uni-processor systems by exploiting the latency in IO or other system functions that may halt a process."
},
{
"code": null,
"e": 802,
"s": 569,
"text": "We must include the pthread.h header file at the beginning of the script to use all the functions of the pthreads library. To execute the c file, we have to use the -pthread or -lpthread in the command line while compiling the file."
},
{
"code": null,
"e": 845,
"s": 802,
"text": "cc -pthread file.c or\ncc -lpthread file.c\n"
},
{
"code": null,
"e": 900,
"s": 845,
"text": "The functions defined in the pthreads library include:"
},
{
"code": null,
"e": 3520,
"s": 900,
"text": "pthread_create: used to create a new threadSyntax:int pthread_create(pthread_t * thread, \n const pthread_attr_t * attr, \n void * (*start_routine)(void *), \n void *arg);\nParameters:thread: pointer to an unsigned integer value that returns the thread id of the thread created.attr: pointer to a structure that is used to define thread attributes like detached state, scheduling policy, stack address, etc. Set to NULL for default thread attributes.start_routine: pointer to a subroutine that is executed by the thread. The return type and parameter type of the subroutine must be of type void *. The function has a single attribute but if multiple values need to be passed to the function, a struct must be used.arg: pointer to void that contains the arguments to the function defined in the earlier argumentpthread_exit: used to terminate a threadSyntax:void pthread_exit(void *retval);\nParameters: This method accepts a mandatory parameter retval which is the pointer to an integer that stores the return status of the thread terminated. The scope of this variable must be global so that any thread waiting to join this thread may read the return status.pthread_join: used to wait for the termination of a thread.Syntax:int pthread_join(pthread_t th, \n void **thread_return);\nParameter: This method accepts following parameters:th: thread id of the thread for which the current thread waits.thread_return: pointer to the location where the exit status of the thread mentioned in th is stored.pthread_self: used to get the thread id of the current thread.Syntax:pthread_t pthread_self(void);\npthread_equal: compares whether two threads are the same or not. If the two threads are equal, the function returns a non-zero value otherwise zero.Syntax:int pthread_equal(pthread_t t1, \n pthread_t t2);\nParameters: This method accepts following parameters:t1: the thread id of the first threadt2: the thread id of the second threadpthread_cancel: used to send a cancellation request to a threadSyntax:int pthread_cancel(pthread_t thread);\nParameter: This method accepts a mandatory parameter thread which is the thread id of the thread to which cancel request is sent.pthread_detach: used to detach a thread. A detached thread does not require a thread to join on terminating. The resources of the thread are automatically released after terminating if the thread is detached.Syntax:int pthread_detach(pthread_t thread);\nParameter: This method accepts a mandatory parameter thread which is the thread id of the thread that must be detached."
},
{
"code": null,
"e": 4381,
"s": 3520,
"text": "pthread_create: used to create a new threadSyntax:int pthread_create(pthread_t * thread, \n const pthread_attr_t * attr, \n void * (*start_routine)(void *), \n void *arg);\nParameters:thread: pointer to an unsigned integer value that returns the thread id of the thread created.attr: pointer to a structure that is used to define thread attributes like detached state, scheduling policy, stack address, etc. Set to NULL for default thread attributes.start_routine: pointer to a subroutine that is executed by the thread. The return type and parameter type of the subroutine must be of type void *. The function has a single attribute but if multiple values need to be passed to the function, a struct must be used.arg: pointer to void that contains the arguments to the function defined in the earlier argument"
},
{
"code": null,
"e": 4389,
"s": 4381,
"text": "Syntax:"
},
{
"code": null,
"e": 4563,
"s": 4389,
"text": "int pthread_create(pthread_t * thread, \n const pthread_attr_t * attr, \n void * (*start_routine)(void *), \n void *arg);\n"
},
{
"code": null,
"e": 4575,
"s": 4563,
"text": "Parameters:"
},
{
"code": null,
"e": 4670,
"s": 4575,
"text": "thread: pointer to an unsigned integer value that returns the thread id of the thread created."
},
{
"code": null,
"e": 4843,
"s": 4670,
"text": "attr: pointer to a structure that is used to define thread attributes like detached state, scheduling policy, stack address, etc. Set to NULL for default thread attributes."
},
{
"code": null,
"e": 5108,
"s": 4843,
"text": "start_routine: pointer to a subroutine that is executed by the thread. The return type and parameter type of the subroutine must be of type void *. The function has a single attribute but if multiple values need to be passed to the function, a struct must be used."
},
{
"code": null,
"e": 5205,
"s": 5108,
"text": "arg: pointer to void that contains the arguments to the function defined in the earlier argument"
},
{
"code": null,
"e": 5554,
"s": 5205,
"text": "pthread_exit: used to terminate a threadSyntax:void pthread_exit(void *retval);\nParameters: This method accepts a mandatory parameter retval which is the pointer to an integer that stores the return status of the thread terminated. The scope of this variable must be global so that any thread waiting to join this thread may read the return status."
},
{
"code": null,
"e": 5562,
"s": 5554,
"text": "Syntax:"
},
{
"code": null,
"e": 5596,
"s": 5562,
"text": "void pthread_exit(void *retval);\n"
},
{
"code": null,
"e": 5865,
"s": 5596,
"text": "Parameters: This method accepts a mandatory parameter retval which is the pointer to an integer that stores the return status of the thread terminated. The scope of this variable must be global so that any thread waiting to join this thread may read the return status."
},
{
"code": null,
"e": 6220,
"s": 5865,
"text": "pthread_join: used to wait for the termination of a thread.Syntax:int pthread_join(pthread_t th, \n void **thread_return);\nParameter: This method accepts following parameters:th: thread id of the thread for which the current thread waits.thread_return: pointer to the location where the exit status of the thread mentioned in th is stored."
},
{
"code": null,
"e": 6228,
"s": 6220,
"text": "Syntax:"
},
{
"code": null,
"e": 6301,
"s": 6228,
"text": "int pthread_join(pthread_t th, \n void **thread_return);\n"
},
{
"code": null,
"e": 6354,
"s": 6301,
"text": "Parameter: This method accepts following parameters:"
},
{
"code": null,
"e": 6418,
"s": 6354,
"text": "th: thread id of the thread for which the current thread waits."
},
{
"code": null,
"e": 6520,
"s": 6418,
"text": "thread_return: pointer to the location where the exit status of the thread mentioned in th is stored."
},
{
"code": null,
"e": 6620,
"s": 6520,
"text": "pthread_self: used to get the thread id of the current thread.Syntax:pthread_t pthread_self(void);\n"
},
{
"code": null,
"e": 6628,
"s": 6620,
"text": "Syntax:"
},
{
"code": null,
"e": 6659,
"s": 6628,
"text": "pthread_t pthread_self(void);\n"
},
{
"code": null,
"e": 7009,
"s": 6659,
"text": "pthread_equal: compares whether two threads are the same or not. If the two threads are equal, the function returns a non-zero value otherwise zero.Syntax:int pthread_equal(pthread_t t1, \n pthread_t t2);\nParameters: This method accepts following parameters:t1: the thread id of the first threadt2: the thread id of the second thread"
},
{
"code": null,
"e": 7017,
"s": 7009,
"text": "Syntax:"
},
{
"code": null,
"e": 7084,
"s": 7017,
"text": "int pthread_equal(pthread_t t1, \n pthread_t t2);\n"
},
{
"code": null,
"e": 7138,
"s": 7084,
"text": "Parameters: This method accepts following parameters:"
},
{
"code": null,
"e": 7176,
"s": 7138,
"text": "t1: the thread id of the first thread"
},
{
"code": null,
"e": 7215,
"s": 7176,
"text": "t2: the thread id of the second thread"
},
{
"code": null,
"e": 7453,
"s": 7215,
"text": "pthread_cancel: used to send a cancellation request to a threadSyntax:int pthread_cancel(pthread_t thread);\nParameter: This method accepts a mandatory parameter thread which is the thread id of the thread to which cancel request is sent."
},
{
"code": null,
"e": 7461,
"s": 7453,
"text": "Syntax:"
},
{
"code": null,
"e": 7500,
"s": 7461,
"text": "int pthread_cancel(pthread_t thread);\n"
},
{
"code": null,
"e": 7630,
"s": 7500,
"text": "Parameter: This method accepts a mandatory parameter thread which is the thread id of the thread to which cancel request is sent."
},
{
"code": null,
"e": 8003,
"s": 7630,
"text": "pthread_detach: used to detach a thread. A detached thread does not require a thread to join on terminating. The resources of the thread are automatically released after terminating if the thread is detached.Syntax:int pthread_detach(pthread_t thread);\nParameter: This method accepts a mandatory parameter thread which is the thread id of the thread that must be detached."
},
{
"code": null,
"e": 8011,
"s": 8003,
"text": "Syntax:"
},
{
"code": null,
"e": 8050,
"s": 8011,
"text": "int pthread_detach(pthread_t thread);\n"
},
{
"code": null,
"e": 8170,
"s": 8050,
"text": "Parameter: This method accepts a mandatory parameter thread which is the thread id of the thread that must be detached."
},
{
"code": null,
"e": 8233,
"s": 8170,
"text": "Example: A simple implementation of threads may be as follows:"
},
{
"code": "// C program to show thread functions #include <pthread.h>#include <stdio.h>#include <stdlib.h> void* func(void* arg){ // detach the current thread // from the calling thread pthread_detach(pthread_self()); printf(\"Inside the thread\\n\"); // exit the current thread pthread_exit(NULL);} void fun(){ pthread_t ptid; // Creating a new thread pthread_create(&ptid, NULL, &func, NULL); printf(\"This line may be printed\" \" before thread terminates\\n\"); // The following line terminates // the thread manually // pthread_cancel(ptid); // Compare the two threads created if(pthread_equal(ptid, pthread_self()) printf(\"Threads are equal\\n\"); else printf(\"Threads are not equal\\n\"); // Waiting for the created thread to terminate pthread_join(ptid, NULL); printf(\"This line will be printed\" \" after thread ends\\n\"); pthread_exit(NULL);} // Driver codeint main(){ fun(); return 0;}",
"e": 9224,
"s": 8233,
"text": null
},
{
"code": null,
"e": 9232,
"s": 9224,
"text": "Output:"
},
{
"code": null,
"e": 9367,
"s": 9232,
"text": "This line may be printed before thread terminates\nThreads are not equal\nInside the thread\nThis line will be printed after thread ends\n"
},
{
"code": null,
"e": 9878,
"s": 9367,
"text": "Explanation: Here two threads of execution are created in the code. The order of the lines of output of the two threads may be interchanged depending upon the thread processed earlier. The main thread waits on the newly created thread for exiting. Therefore, the final line of the output is printed only after the new thread exits. The threads can terminate independently of each other by not using the pthread_join function. If we want to terminate the new thread manually, we may use pthread_cancel to do it."
},
{
"code": null,
"e": 10059,
"s": 9878,
"text": "Note: If we use exit() instead of pthread_exit() to end a thread, the whole process with all associated threads will be terminated even if some of the threads may still be running."
},
{
"code": null,
"e": 10072,
"s": 10059,
"text": "Akanksha_Rai"
},
{
"code": null,
"e": 10084,
"s": 10072,
"text": "C-Functions"
},
{
"code": null,
"e": 10095,
"s": 10084,
"text": "C Language"
},
{
"code": null,
"e": 10106,
"s": 10095,
"text": "Linux-Unix"
}
] |
Least Prime Factor | Practice | GeeksforGeeks | Given a number N, find least prime factors for all numbers from 1 to N. The least prime factor of an integer N is the smallest prime number that divides it.
Note : The least prime factor of all even numbers is 2. A prime number is its own least prime factor (as well as its own greatest prime factor).1 needs to be printed for 1.​
Example 1:
Input: N = 6
Output: [1, 2, 3, 2, 5, 2]
Explanation: least prime factor of 1 = 1,
least prime factor of 2 = 2,
least prime factor of 3 = 3,
least prime factor of 4 = 2,
least prime factor of 5 = 5,
least prime factor of 6 = 2.
So answer is[1, 2, 3, 2, 5, 2].
Example 2:
Input: N = 4
Output: [1, 2, 3, 2]
Explanation: least prime factor of 1 = 1,
least prime factor of 2 = 2,
least prime factor of 3 = 3,
least prime factor of 4 = 2.
So answer is[1, 2, 3, 2].
Your Task:
You dont need to read input or print anything. Complete the function leastPrimeFactor() which takes N as input parameter and returns a list of integers containing all the least prime factor of each numbers from 1 to N.
Expected Time Complexity: O(NlogN)
Expected Auxiliary Space: O(N)
Constraints:
2<= n <=103
0
raunakgiri213 days ago
C++
class Solution { public: bool isPrime(int n) { if(n<=1)return 0; for(int i=2;i<sqrt(n);i++) { if(n%i==0)return 0; }return 1; } int findLPF(int n) { for(int i=2;i*i<=n;i++) { if(isPrime(i) && n%i==0)return i; } return n; } vector<int> leastPrimeFactor(int n) { // code here vector<int> list; list.push_back(1); for(int i=1;i<=n;i++) { list.push_back(findLPF(i)); } return list; }};
0
moaslam8263 weeks ago
c++ seive algo
vector<int> leastPrimeFactor(int n) {
// code here
int X=1e3;
int lp[X]={0};
lp[1]=1;
for(int i=2;i<X;i++){
for(int j=i;j<X;j+=i){
if(lp[j]==0){
lp[j]=i;
}
}
}
vector<int> ans;
ans.push_back(1);
for(int i=1;i<=n;i++){
ans.push_back(lp[i]);
}
return ans;
}
+1
mashhadihossain4 weeks ago
SIMPLEST JAVA SOLUTION (0.5/5.0 SEC)
class Solution{ public int[] leastPrimeFactor(int n) { int a[]=new int[n+1]; a[1]=1; for(int i=2;i<=n;i++) { for(int j=2;j<=i;j++) { if(i%j==0) { a[i]=j; break; } } } return a; }}
0
chhitizgoyal2 months ago
Kindly correct me. (Java).
public static int prime(int num){ int ans = 1; if(num%2==0){ ans = 2; }else if(num%3==0){ ans = 3; } else if(num%5==0){ ans = 5; } else{ ans = num; } return ans; } public int[] leastPrimeFactor(int n) { int[] arr = new int[n+1]; for(int i=0; i<=n; i++){ arr[i] = prime(i); } return arr; }
+1
ayazmrz982 months ago
static boolean isprime(int n)
{
if(n<=1)
{
return false;
}
for(int i=2;i<=Math.sqrt(n);i++)
{
if(n%i==0)
{
return false;
}
}
return true;
}
public int[] leastPrimeFactor(int n)
{
int[] arr = new int[n+1];
arr[1]=1;
for(int i=2;i<=n;i++)
{
if(i%2==0)
{
arr[i]=2;
continue;
}
else
{
for(int j=3;j<=i;j++)
{
if(i%j==0)
{
if(isprime(j))
{
arr[i]=j;
break;
}
}
}
}
}
return arr;
}
+2
akshay014 months ago
no this is called a proper solution the best one execution time 0.0
vector<int> leastPrimeFactor(int n) { // code here vector<int> v; v.push_back(0); v.push_back(1); for(int i=2;i<=n;i++) { for(int j=2;j<=i;j++) { if(i%j == 0) { v.push_back(j); break; } } } return v; }
0
rakeshkumar696 months ago
worst compiler here
its output should be 1
but it is not showing that
0
c1phani1simha6 months ago
class Solution { public: vector<int> leastPrimeFactor(int n) { vector<int> ans(n+1,0); ans[1]=1; for(int i=2;i<=n;i++) { if(ans[i]==0) { ans[i]=i; for(int j=i*i;j<=n;j+=i) { if(ans[j]==0) ans[j]=i; } } } return ans; }};
0
Anjali Jaiswal10 months ago
Anjali Jaiswal
class Solution { public: vector<int> leastPrimeFactor(int n) { vector<int>v; // v.push_back(1); int s[n+1]; for(int i=0;i<=n;i++) { s[i]=i; } for(int i=2;i<=sqrt(n);i++) { if(s[i]==i) { for(int j=i*i;j<=n;j+=i) { if(s[j]==j) s[j]=i; } } } for(int i=0;i<=n;i++) { v.push_back(s[i]); } return v; }};
0
Anjali Jaiswal10 months ago
Anjali Jaiswal
class Solution { public: vector<int> leastPrimeFactor(int n) { vector<int>v; // v.push_back(1); int s[n+1]; for(int i=0;i<=n;i++) { s[i]=i; } for(int i=2;i<=sqrt(n);i++) { if(s[i]==i) { for(int j=i*i;j<=n;j+=i) { if(s[j]==j) s[j]=i; } } } for(int i=0;i<=n;i++) { v.push_back(s[i]); } return v; }};
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": 585,
"s": 238,
"text": "Given a number N, find least prime factors for all numbers from 1 to N. The least prime factor of an integer N is the smallest prime number that divides it.\nNote : The least prime factor of all even numbers is 2. A prime number is its own least prime factor (as well as its own greatest prime factor).1 needs to be printed for 1.​\n\nExample 1:"
},
{
"code": null,
"e": 847,
"s": 585,
"text": "Input: N = 6\nOutput: [1, 2, 3, 2, 5, 2] \nExplanation: least prime factor of 1 = 1,\nleast prime factor of 2 = 2,\nleast prime factor of 3 = 3,\nleast prime factor of 4 = 2,\nleast prime factor of 5 = 5,\nleast prime factor of 6 = 2.\nSo answer is[1, 2, 3, 2, 5, 2]. \n"
},
{
"code": null,
"e": 859,
"s": 847,
"text": "\nExample 2:"
},
{
"code": null,
"e": 1050,
"s": 859,
"text": "Input: N = 4\nOutput: [1, 2, 3, 2]\nExplanation: least prime factor of 1 = 1,\nleast prime factor of 2 = 2,\nleast prime factor of 3 = 3,\nleast prime factor of 4 = 2.\nSo answer is[1, 2, 3, 2]. \n"
},
{
"code": null,
"e": 1376,
"s": 1050,
"text": "\nYour Task: \nYou dont need to read input or print anything. Complete the function leastPrimeFactor() which takes N as input parameter and returns a list of integers containing all the least prime factor of each numbers from 1 to N.\n\nExpected Time Complexity: O(NlogN)\nExpected Auxiliary Space: O(N)\n\nConstraints:\n2<= n <=103"
},
{
"code": null,
"e": 1378,
"s": 1376,
"text": "0"
},
{
"code": null,
"e": 1401,
"s": 1378,
"text": "raunakgiri213 days ago"
},
{
"code": null,
"e": 1405,
"s": 1401,
"text": "C++"
},
{
"code": null,
"e": 1924,
"s": 1407,
"text": "class Solution { public: bool isPrime(int n) { if(n<=1)return 0; for(int i=2;i<sqrt(n);i++) { if(n%i==0)return 0; }return 1; } int findLPF(int n) { for(int i=2;i*i<=n;i++) { if(isPrime(i) && n%i==0)return i; } return n; } vector<int> leastPrimeFactor(int n) { // code here vector<int> list; list.push_back(1); for(int i=1;i<=n;i++) { list.push_back(findLPF(i)); } return list; }};"
},
{
"code": null,
"e": 1926,
"s": 1924,
"text": "0"
},
{
"code": null,
"e": 1948,
"s": 1926,
"text": "moaslam8263 weeks ago"
},
{
"code": null,
"e": 1963,
"s": 1948,
"text": "c++ seive algo"
},
{
"code": null,
"e": 2399,
"s": 1963,
"text": "vector<int> leastPrimeFactor(int n) {\n // code here\n int X=1e3;\n int lp[X]={0};\n lp[1]=1;\n for(int i=2;i<X;i++){\n for(int j=i;j<X;j+=i){\n if(lp[j]==0){\n lp[j]=i;\n }\n }\n }\n vector<int> ans;\n ans.push_back(1);\n for(int i=1;i<=n;i++){\n ans.push_back(lp[i]);\n }\n return ans;\n }"
},
{
"code": null,
"e": 2402,
"s": 2399,
"text": "+1"
},
{
"code": null,
"e": 2429,
"s": 2402,
"text": "mashhadihossain4 weeks ago"
},
{
"code": null,
"e": 2466,
"s": 2429,
"text": "SIMPLEST JAVA SOLUTION (0.5/5.0 SEC)"
},
{
"code": null,
"e": 2796,
"s": 2466,
"text": "class Solution{ public int[] leastPrimeFactor(int n) { int a[]=new int[n+1]; a[1]=1; for(int i=2;i<=n;i++) { for(int j=2;j<=i;j++) { if(i%j==0) { a[i]=j; break; } } } return a; }}"
},
{
"code": null,
"e": 2798,
"s": 2796,
"text": "0"
},
{
"code": null,
"e": 2823,
"s": 2798,
"text": "chhitizgoyal2 months ago"
},
{
"code": null,
"e": 2850,
"s": 2823,
"text": "Kindly correct me. (Java)."
},
{
"code": null,
"e": 3275,
"s": 2850,
"text": "public static int prime(int num){ int ans = 1; if(num%2==0){ ans = 2; }else if(num%3==0){ ans = 3; } else if(num%5==0){ ans = 5; } else{ ans = num; } return ans; } public int[] leastPrimeFactor(int n) { int[] arr = new int[n+1]; for(int i=0; i<=n; i++){ arr[i] = prime(i); } return arr; }"
},
{
"code": null,
"e": 3278,
"s": 3275,
"text": "+1"
},
{
"code": null,
"e": 3300,
"s": 3278,
"text": "ayazmrz982 months ago"
},
{
"code": null,
"e": 4171,
"s": 3300,
"text": " static boolean isprime(int n)\n {\n if(n<=1)\n {\n return false;\n }\n for(int i=2;i<=Math.sqrt(n);i++)\n {\n if(n%i==0)\n {\n return false;\n }\n }\n return true;\n }\n public int[] leastPrimeFactor(int n)\n {\n int[] arr = new int[n+1];\n arr[1]=1;\n for(int i=2;i<=n;i++)\n {\n if(i%2==0)\n {\n arr[i]=2;\n continue;\n }\n else\n {\n for(int j=3;j<=i;j++)\n {\n if(i%j==0)\n {\n if(isprime(j))\n {\n arr[i]=j;\n break;\n }\n }\n }\n }\n }\n \n return arr;\n }"
},
{
"code": null,
"e": 4174,
"s": 4171,
"text": "+2"
},
{
"code": null,
"e": 4195,
"s": 4174,
"text": "akshay014 months ago"
},
{
"code": null,
"e": 4263,
"s": 4195,
"text": "no this is called a proper solution the best one execution time 0.0"
},
{
"code": null,
"e": 4653,
"s": 4263,
"text": "vector<int> leastPrimeFactor(int n) { // code here vector<int> v; v.push_back(0); v.push_back(1); for(int i=2;i<=n;i++) { for(int j=2;j<=i;j++) { if(i%j == 0) { v.push_back(j); break; } } } return v; }"
},
{
"code": null,
"e": 4657,
"s": 4655,
"text": "0"
},
{
"code": null,
"e": 4683,
"s": 4657,
"text": "rakeshkumar696 months ago"
},
{
"code": null,
"e": 4704,
"s": 4683,
"text": "worst compiler here "
},
{
"code": null,
"e": 4728,
"s": 4704,
"text": "its output should be 1 "
},
{
"code": null,
"e": 4756,
"s": 4728,
"text": "but it is not showing that "
},
{
"code": null,
"e": 4760,
"s": 4758,
"text": "0"
},
{
"code": null,
"e": 4786,
"s": 4760,
"text": "c1phani1simha6 months ago"
},
{
"code": null,
"e": 5175,
"s": 4786,
"text": "class Solution { public: vector<int> leastPrimeFactor(int n) { vector<int> ans(n+1,0); ans[1]=1; for(int i=2;i<=n;i++) { if(ans[i]==0) { ans[i]=i; for(int j=i*i;j<=n;j+=i) { if(ans[j]==0) ans[j]=i; } } } return ans; }};"
},
{
"code": null,
"e": 5177,
"s": 5175,
"text": "0"
},
{
"code": null,
"e": 5205,
"s": 5177,
"text": "Anjali Jaiswal10 months ago"
},
{
"code": null,
"e": 5220,
"s": 5205,
"text": "Anjali Jaiswal"
},
{
"code": null,
"e": 5722,
"s": 5220,
"text": "class Solution { public: vector<int> leastPrimeFactor(int n) { vector<int>v; // v.push_back(1); int s[n+1]; for(int i=0;i<=n;i++) { s[i]=i; } for(int i=2;i<=sqrt(n);i++) { if(s[i]==i) { for(int j=i*i;j<=n;j+=i) { if(s[j]==j) s[j]=i; } } } for(int i=0;i<=n;i++) { v.push_back(s[i]); } return v; }};"
},
{
"code": null,
"e": 5724,
"s": 5722,
"text": "0"
},
{
"code": null,
"e": 5752,
"s": 5724,
"text": "Anjali Jaiswal10 months ago"
},
{
"code": null,
"e": 5767,
"s": 5752,
"text": "Anjali Jaiswal"
},
{
"code": null,
"e": 6269,
"s": 5767,
"text": "class Solution { public: vector<int> leastPrimeFactor(int n) { vector<int>v; // v.push_back(1); int s[n+1]; for(int i=0;i<=n;i++) { s[i]=i; } for(int i=2;i<=sqrt(n);i++) { if(s[i]==i) { for(int j=i*i;j<=n;j+=i) { if(s[j]==j) s[j]=i; } } } for(int i=0;i<=n;i++) { v.push_back(s[i]); } return v; }};"
},
{
"code": null,
"e": 6415,
"s": 6269,
"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": 6451,
"s": 6415,
"text": " Login to access your submissions. "
},
{
"code": null,
"e": 6461,
"s": 6451,
"text": "\nProblem\n"
},
{
"code": null,
"e": 6471,
"s": 6461,
"text": "\nContest\n"
},
{
"code": null,
"e": 6534,
"s": 6471,
"text": "Reset the IDE using the second button on the top right corner."
},
{
"code": null,
"e": 6682,
"s": 6534,
"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": 6890,
"s": 6682,
"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": 6996,
"s": 6890,
"text": "You can access the hints to get an idea about what is expected of you as well as the final solution code."
}
] |
Python | sympy.eigenvals() method - GeeksforGeeks | 29 Jun, 2019
With the help of sympy.eigenvals() method, we can find the eigenvalues of a matrix by using sympy.eigenvals() method.
Syntax : sympy.eigenvals()Return : Return eigenvalues of a matrix.
Example #1 :In this example, we can see that by using sympy.eigenvals() method, we are able to find the eigenvalues of a matrix.
# import sympyfrom sympy import * # Use sympy.eigenvals() methodmat = Matrix([[1, 0, 1], [2, -1, 3], [4, 3, 2]])d = mat.eigenvals() print(d)
Output :
{2/3 + 46/(9*(241/54 + sqrt(36807)*I/18)**(1/3)) + (241/54 + sqrt(36807)*I/18)**(1/3): 1, 2/3 + 46/(9*(-1/2 + sqrt(3)*I/2)*(241/54 + sqrt(36807)*I/18)**(1/3)) + (-1/2 + sqrt(3)*I/2)*(241/54 + sqrt(36807)*I/18)**(1/3): 1, 2/3 + (-1/2 – sqrt(3)*I/2)*(241/54 + sqrt(36807)*I/18)**(1/3) + 46/(9*(-1/2 – sqrt(3)*I/2)*(241/54 + sqrt(36807)*I/18)**(1/3)): 1}
Example #2 :
# import sympyfrom sympy import * # Use sympy.eigenvals() methodmat = Matrix([[1, 5, 1], [12, -1, 31], [4, 33, 2]])d = mat.eigenvals() print(d)
Output :
{2/3 + 3268/(9*(16225/54 + sqrt(15482600967)*I/18)**(1/3)) + (16225/54 + sqrt(15482600967)*I/18)**(1/3): 1, 2/3 + 3268/(9*(-1/2 + sqrt(3)*I/2)*(16225/54 + sqrt(15482600967)*I/18)**(1/3)) + (-1/2 + sqrt(3)*I/2)*(16225/54 + sqrt(15482600967)*I/18)**(1/3): 1, 2/3 + (-1/2 – sqrt(3)*I/2)*(16225/54 + sqrt(15482600967)*I/18)**(1/3) + 3268/(9*(-1/2 – sqrt(3)*I/2)*(16225/54 + sqrt(15482600967)*I/18)**(1/3)): 1}
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()
Python | Get unique values from a list
Defaultdict in Python
Python | os.path.join() method
Python Classes and Objects
Create a directory in Python | [
{
"code": null,
"e": 23901,
"s": 23873,
"text": "\n29 Jun, 2019"
},
{
"code": null,
"e": 24019,
"s": 23901,
"text": "With the help of sympy.eigenvals() method, we can find the eigenvalues of a matrix by using sympy.eigenvals() method."
},
{
"code": null,
"e": 24086,
"s": 24019,
"text": "Syntax : sympy.eigenvals()Return : Return eigenvalues of a matrix."
},
{
"code": null,
"e": 24215,
"s": 24086,
"text": "Example #1 :In this example, we can see that by using sympy.eigenvals() method, we are able to find the eigenvalues of a matrix."
},
{
"code": "# import sympyfrom sympy import * # Use sympy.eigenvals() methodmat = Matrix([[1, 0, 1], [2, -1, 3], [4, 3, 2]])d = mat.eigenvals() print(d)",
"e": 24359,
"s": 24215,
"text": null
},
{
"code": null,
"e": 24368,
"s": 24359,
"text": "Output :"
},
{
"code": null,
"e": 24720,
"s": 24368,
"text": "{2/3 + 46/(9*(241/54 + sqrt(36807)*I/18)**(1/3)) + (241/54 + sqrt(36807)*I/18)**(1/3): 1, 2/3 + 46/(9*(-1/2 + sqrt(3)*I/2)*(241/54 + sqrt(36807)*I/18)**(1/3)) + (-1/2 + sqrt(3)*I/2)*(241/54 + sqrt(36807)*I/18)**(1/3): 1, 2/3 + (-1/2 – sqrt(3)*I/2)*(241/54 + sqrt(36807)*I/18)**(1/3) + 46/(9*(-1/2 – sqrt(3)*I/2)*(241/54 + sqrt(36807)*I/18)**(1/3)): 1}"
},
{
"code": null,
"e": 24733,
"s": 24720,
"text": "Example #2 :"
},
{
"code": "# import sympyfrom sympy import * # Use sympy.eigenvals() methodmat = Matrix([[1, 5, 1], [12, -1, 31], [4, 33, 2]])d = mat.eigenvals() print(d)",
"e": 24880,
"s": 24733,
"text": null
},
{
"code": null,
"e": 24889,
"s": 24880,
"text": "Output :"
},
{
"code": null,
"e": 25295,
"s": 24889,
"text": "{2/3 + 3268/(9*(16225/54 + sqrt(15482600967)*I/18)**(1/3)) + (16225/54 + sqrt(15482600967)*I/18)**(1/3): 1, 2/3 + 3268/(9*(-1/2 + sqrt(3)*I/2)*(16225/54 + sqrt(15482600967)*I/18)**(1/3)) + (-1/2 + sqrt(3)*I/2)*(16225/54 + sqrt(15482600967)*I/18)**(1/3): 1, 2/3 + (-1/2 – sqrt(3)*I/2)*(16225/54 + sqrt(15482600967)*I/18)**(1/3) + 3268/(9*(-1/2 – sqrt(3)*I/2)*(16225/54 + sqrt(15482600967)*I/18)**(1/3)): 1}"
},
{
"code": null,
"e": 25302,
"s": 25295,
"text": "Python"
},
{
"code": null,
"e": 25400,
"s": 25302,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 25409,
"s": 25400,
"text": "Comments"
},
{
"code": null,
"e": 25422,
"s": 25409,
"text": "Old Comments"
},
{
"code": null,
"e": 25454,
"s": 25422,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 25510,
"s": 25454,
"text": "How to drop one or multiple columns in Pandas Dataframe"
},
{
"code": null,
"e": 25552,
"s": 25510,
"text": "How To Convert Python Dictionary To JSON?"
},
{
"code": null,
"e": 25594,
"s": 25552,
"text": "Check if element exists in list in Python"
},
{
"code": null,
"e": 25630,
"s": 25594,
"text": "Python | Pandas dataframe.groupby()"
},
{
"code": null,
"e": 25669,
"s": 25630,
"text": "Python | Get unique values from a list"
},
{
"code": null,
"e": 25691,
"s": 25669,
"text": "Defaultdict in Python"
},
{
"code": null,
"e": 25722,
"s": 25691,
"text": "Python | os.path.join() method"
},
{
"code": null,
"e": 25749,
"s": 25722,
"text": "Python Classes and Objects"
}
] |
Solve the MNIST Image Classification Problem | by Rakshit Raj | Towards Data Science | Solving the MNIST is a benchmark for machine learning models. It is also one of the first problems that you’ll encounter as you enter the realm of deep learning.
In this article, we will design a neural network that uses the Python library Keras to learn to classify handwritten digits of the MNIST dataset.
The crazy thing about solving MNIST is that it isn’t resource-intensive at all. You do not need a GPU. The model we build here can be trained quickly on any modern CPU in under a minute.
The MNIST dataset is a set of 60,000 training images plus 10,000 test images, assembled by the National Institute of Standards and Technology (NIST) in the 1980s. These images are encoded as NumPy arrays, and the labels are an array of digits, ranging from 0 to 9. The images and labels have a one-to-one correspondence.
Assuming that you have already installed Anaconda, we shall briefly discuss installing Keras and other dependencies.
While Anaconda bundles a lot of good stuff by default, it does not ship with Keras pre-installed. The good folks over at Anaconda Cloud, however, have a customized Keras package available here.
You could install the same from the conda-forge channel using the command line.
$ conda install --channel conda-forge keras
Draw mappings of training samples and corresponding targets, i.e., load the data.Create network architecture.Select a loss function, an optimizer, and metrics to monitor during testing and training.Pre-process the data as required.Run the network on training samples, i.e., forward pass to get predictions.Compute the loss of the network on the batch.Update all weights of the network, reducing loss on the batch.
Draw mappings of training samples and corresponding targets, i.e., load the data.
Create network architecture.
Select a loss function, an optimizer, and metrics to monitor during testing and training.
Pre-process the data as required.
Run the network on training samples, i.e., forward pass to get predictions.
Compute the loss of the network on the batch.
Update all weights of the network, reducing loss on the batch.
The MNIST Image Classification Problem is a Multiclass Classification problem. Let us implement the pedagogy, as discussed above.
The workflow adopted is simple. We’ll feed the training data to the neural network. The network will then learn to associate images and labels. Finally, the network will produce predictions for testing data and the degree of accuracy achieved.
The MNIST dataset comes preloaded in Keras, in the form of a set of four NumPy arrays. We’ll load the dataset using load_data() function.
We’ll build the network using densely connected (also called fully connected) sequential neural layers*. Layers are the core building block of a neural network. They are basic tensor operations that implement a progressive ‘data distillation.’
(confusing sentence ahead, read carefully**)
A layer takes the output of the layer before it as input.
**Therefore, the ‘shape of the input to a layer’ must match the ‘shape of the output of the previous layer.’
*Sequential layers dynamically adjust the shape of input to a layer based the out of the layer before it, thus reducing effort on the part of the programmer.
To create our network,
Our network consists of two fully connected layers. The second (and last) layer is a 10-way softmax layer, which returns an array of 10 probability scores. Each score is the probability that the current digit image belongs to one of our 10 digit classes.
Now let’s select an optimizer, a loss function & metrics for evaluation of model performance.
We’ll pre-process the image data by reshaping it into the shape that the network expects and by scaling it so that all values are in the [0,1] interval.
Previously our training images were stored in an array of shape (60000, 28, 28) of type uint8 with values in the [0,255] range. We will transform it into a float32 array of shape (60000, 28 * 28) with values between 0 and 1.
We will then categorically encode the labels, using to_categorical function from keras.utils
Now, we are ready to train our network.
Keras trains the network via a call to the network’s fit() method. We fit the model to its training data.
As the network trains, you will see its accuracy increase and loss decrease. The times you see here are training times corresponding to an i7 CPU.
Epoch 1/5469/469 [==============================] - 5s 10ms/step - loss: 0.2596 - accuracy: 0.9255Epoch 2/5469/469 [==============================] - 5s 10ms/step - loss: 0.1047 - accuracy: 0.9693Epoch 3/5469/469 [==============================] - 5s 11ms/step - loss: 0.0684 - accuracy: 0.9791Epoch 4/5469/469 [==============================] - 5s 10ms/step - loss: 0.0496 - accuracy: 0.9851Epoch 5/5469/469 [==============================] - 5s 11ms/step - loss: 0.0379 - accuracy: 0.9887
We have attained a training accuracy of 98.87% This measure tells us that our network correctly classified 98.87% of images in the testing data.
The MNIST dataset reserves 10,000 images as test_images We will evaluate the performance of our network by testing it on this previously unseen dataset.
313/313 [==============================] - 1s 3ms/step - loss: 0.0774 - accuracy: 0.9775Test Loss: 0.07742435485124588Test Accuracy : 97.75000214576721 %
We attain a testing accuracy of 97.75% It is understandably lower compared to training accuracy due to overfitting.
To visualize our Neural network, we will need a couple of extra dependencies. You can install them using
$ $HOME/anaconda/bin/pip install graphviz$ pip3 install ann-visualizer
We’ll use ann-visualizer to visualize our neural network as a graph. This step is optional; you may choose not to visualize your network. However, looking at the graph is undoubtedly more fun.
graphviz is a dependency for ann-visualizer
Here is your neural network;
For more information on Visualizing Neural Networks check out the GitHub Repository of ann-visualizer that you just used.
github.com
Congratulations! You have successfully crossed the threshold of Deep Learning. If this was your first foray into Neural Networks, I hope you enjoyed it.
I recommend that you work along with the article. You can solve the MNIST image classification problem in under ten minutes. Make sure to stress enough on Pedagogy we discussed earlier. That is the basis of solving and implementing Neural Networks across the board.
I assume that the reader has a working understanding of technicalities like optimizer, categorical encoding, loss function, and metrics. You can find my practice notes on these concepts here.
For more, please check out the book Deep Learning with Python by Francois Chollet.
Feel free to check out this article’s implementation and more of my work on GitHub.
Thanks for reading! | [
{
"code": null,
"e": 333,
"s": 171,
"text": "Solving the MNIST is a benchmark for machine learning models. It is also one of the first problems that you’ll encounter as you enter the realm of deep learning."
},
{
"code": null,
"e": 479,
"s": 333,
"text": "In this article, we will design a neural network that uses the Python library Keras to learn to classify handwritten digits of the MNIST dataset."
},
{
"code": null,
"e": 666,
"s": 479,
"text": "The crazy thing about solving MNIST is that it isn’t resource-intensive at all. You do not need a GPU. The model we build here can be trained quickly on any modern CPU in under a minute."
},
{
"code": null,
"e": 987,
"s": 666,
"text": "The MNIST dataset is a set of 60,000 training images plus 10,000 test images, assembled by the National Institute of Standards and Technology (NIST) in the 1980s. These images are encoded as NumPy arrays, and the labels are an array of digits, ranging from 0 to 9. The images and labels have a one-to-one correspondence."
},
{
"code": null,
"e": 1104,
"s": 987,
"text": "Assuming that you have already installed Anaconda, we shall briefly discuss installing Keras and other dependencies."
},
{
"code": null,
"e": 1298,
"s": 1104,
"text": "While Anaconda bundles a lot of good stuff by default, it does not ship with Keras pre-installed. The good folks over at Anaconda Cloud, however, have a customized Keras package available here."
},
{
"code": null,
"e": 1378,
"s": 1298,
"text": "You could install the same from the conda-forge channel using the command line."
},
{
"code": null,
"e": 1422,
"s": 1378,
"text": "$ conda install --channel conda-forge keras"
},
{
"code": null,
"e": 1836,
"s": 1422,
"text": "Draw mappings of training samples and corresponding targets, i.e., load the data.Create network architecture.Select a loss function, an optimizer, and metrics to monitor during testing and training.Pre-process the data as required.Run the network on training samples, i.e., forward pass to get predictions.Compute the loss of the network on the batch.Update all weights of the network, reducing loss on the batch."
},
{
"code": null,
"e": 1918,
"s": 1836,
"text": "Draw mappings of training samples and corresponding targets, i.e., load the data."
},
{
"code": null,
"e": 1947,
"s": 1918,
"text": "Create network architecture."
},
{
"code": null,
"e": 2037,
"s": 1947,
"text": "Select a loss function, an optimizer, and metrics to monitor during testing and training."
},
{
"code": null,
"e": 2071,
"s": 2037,
"text": "Pre-process the data as required."
},
{
"code": null,
"e": 2147,
"s": 2071,
"text": "Run the network on training samples, i.e., forward pass to get predictions."
},
{
"code": null,
"e": 2193,
"s": 2147,
"text": "Compute the loss of the network on the batch."
},
{
"code": null,
"e": 2256,
"s": 2193,
"text": "Update all weights of the network, reducing loss on the batch."
},
{
"code": null,
"e": 2386,
"s": 2256,
"text": "The MNIST Image Classification Problem is a Multiclass Classification problem. Let us implement the pedagogy, as discussed above."
},
{
"code": null,
"e": 2630,
"s": 2386,
"text": "The workflow adopted is simple. We’ll feed the training data to the neural network. The network will then learn to associate images and labels. Finally, the network will produce predictions for testing data and the degree of accuracy achieved."
},
{
"code": null,
"e": 2768,
"s": 2630,
"text": "The MNIST dataset comes preloaded in Keras, in the form of a set of four NumPy arrays. We’ll load the dataset using load_data() function."
},
{
"code": null,
"e": 3012,
"s": 2768,
"text": "We’ll build the network using densely connected (also called fully connected) sequential neural layers*. Layers are the core building block of a neural network. They are basic tensor operations that implement a progressive ‘data distillation.’"
},
{
"code": null,
"e": 3057,
"s": 3012,
"text": "(confusing sentence ahead, read carefully**)"
},
{
"code": null,
"e": 3115,
"s": 3057,
"text": "A layer takes the output of the layer before it as input."
},
{
"code": null,
"e": 3224,
"s": 3115,
"text": "**Therefore, the ‘shape of the input to a layer’ must match the ‘shape of the output of the previous layer.’"
},
{
"code": null,
"e": 3382,
"s": 3224,
"text": "*Sequential layers dynamically adjust the shape of input to a layer based the out of the layer before it, thus reducing effort on the part of the programmer."
},
{
"code": null,
"e": 3405,
"s": 3382,
"text": "To create our network,"
},
{
"code": null,
"e": 3660,
"s": 3405,
"text": "Our network consists of two fully connected layers. The second (and last) layer is a 10-way softmax layer, which returns an array of 10 probability scores. Each score is the probability that the current digit image belongs to one of our 10 digit classes."
},
{
"code": null,
"e": 3754,
"s": 3660,
"text": "Now let’s select an optimizer, a loss function & metrics for evaluation of model performance."
},
{
"code": null,
"e": 3907,
"s": 3754,
"text": "We’ll pre-process the image data by reshaping it into the shape that the network expects and by scaling it so that all values are in the [0,1] interval."
},
{
"code": null,
"e": 4132,
"s": 3907,
"text": "Previously our training images were stored in an array of shape (60000, 28, 28) of type uint8 with values in the [0,255] range. We will transform it into a float32 array of shape (60000, 28 * 28) with values between 0 and 1."
},
{
"code": null,
"e": 4225,
"s": 4132,
"text": "We will then categorically encode the labels, using to_categorical function from keras.utils"
},
{
"code": null,
"e": 4265,
"s": 4225,
"text": "Now, we are ready to train our network."
},
{
"code": null,
"e": 4371,
"s": 4265,
"text": "Keras trains the network via a call to the network’s fit() method. We fit the model to its training data."
},
{
"code": null,
"e": 4518,
"s": 4371,
"text": "As the network trains, you will see its accuracy increase and loss decrease. The times you see here are training times corresponding to an i7 CPU."
},
{
"code": null,
"e": 5009,
"s": 4518,
"text": "Epoch 1/5469/469 [==============================] - 5s 10ms/step - loss: 0.2596 - accuracy: 0.9255Epoch 2/5469/469 [==============================] - 5s 10ms/step - loss: 0.1047 - accuracy: 0.9693Epoch 3/5469/469 [==============================] - 5s 11ms/step - loss: 0.0684 - accuracy: 0.9791Epoch 4/5469/469 [==============================] - 5s 10ms/step - loss: 0.0496 - accuracy: 0.9851Epoch 5/5469/469 [==============================] - 5s 11ms/step - loss: 0.0379 - accuracy: 0.9887"
},
{
"code": null,
"e": 5154,
"s": 5009,
"text": "We have attained a training accuracy of 98.87% This measure tells us that our network correctly classified 98.87% of images in the testing data."
},
{
"code": null,
"e": 5307,
"s": 5154,
"text": "The MNIST dataset reserves 10,000 images as test_images We will evaluate the performance of our network by testing it on this previously unseen dataset."
},
{
"code": null,
"e": 5461,
"s": 5307,
"text": "313/313 [==============================] - 1s 3ms/step - loss: 0.0774 - accuracy: 0.9775Test Loss: 0.07742435485124588Test Accuracy : 97.75000214576721 %"
},
{
"code": null,
"e": 5577,
"s": 5461,
"text": "We attain a testing accuracy of 97.75% It is understandably lower compared to training accuracy due to overfitting."
},
{
"code": null,
"e": 5682,
"s": 5577,
"text": "To visualize our Neural network, we will need a couple of extra dependencies. You can install them using"
},
{
"code": null,
"e": 5753,
"s": 5682,
"text": "$ $HOME/anaconda/bin/pip install graphviz$ pip3 install ann-visualizer"
},
{
"code": null,
"e": 5946,
"s": 5753,
"text": "We’ll use ann-visualizer to visualize our neural network as a graph. This step is optional; you may choose not to visualize your network. However, looking at the graph is undoubtedly more fun."
},
{
"code": null,
"e": 5990,
"s": 5946,
"text": "graphviz is a dependency for ann-visualizer"
},
{
"code": null,
"e": 6019,
"s": 5990,
"text": "Here is your neural network;"
},
{
"code": null,
"e": 6141,
"s": 6019,
"text": "For more information on Visualizing Neural Networks check out the GitHub Repository of ann-visualizer that you just used."
},
{
"code": null,
"e": 6152,
"s": 6141,
"text": "github.com"
},
{
"code": null,
"e": 6305,
"s": 6152,
"text": "Congratulations! You have successfully crossed the threshold of Deep Learning. If this was your first foray into Neural Networks, I hope you enjoyed it."
},
{
"code": null,
"e": 6571,
"s": 6305,
"text": "I recommend that you work along with the article. You can solve the MNIST image classification problem in under ten minutes. Make sure to stress enough on Pedagogy we discussed earlier. That is the basis of solving and implementing Neural Networks across the board."
},
{
"code": null,
"e": 6763,
"s": 6571,
"text": "I assume that the reader has a working understanding of technicalities like optimizer, categorical encoding, loss function, and metrics. You can find my practice notes on these concepts here."
},
{
"code": null,
"e": 6846,
"s": 6763,
"text": "For more, please check out the book Deep Learning with Python by Francois Chollet."
},
{
"code": null,
"e": 6930,
"s": 6846,
"text": "Feel free to check out this article’s implementation and more of my work on GitHub."
}
] |
SLF4J - Parameterized logging | As discussed earlier in this tutorial SLF4J provides support for parameterized log messages.
You can use parameters in the messages and pass values to them later in the same statement.
As shown below, you need to use placeholders ({}) in the message (String) wherever you need and later you can pass value for place holder in object form, separating the message and value with comma.
Integer age;
Logger.info("At the age of {} ramu got his first job", age);
The following example demonstrates parameterized logging (with single parameter) using SLF4J.
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class PlaceHolders {
public static void main(String[] args) {
//Creating the Logger object
Logger logger = LoggerFactory.getLogger(PlaceHolders.class);
Integer age = 23;
//Logging the information
logger.info("At the age of {} ramu got his first job", age);
}
}
Upon execution, the above program generates the following output −
Dec 10, 2018 3:25:45 PM PlaceHolders main
INFO: At the age of 23 Ramu got his first job
In Java, if we need to print values in a statement, we will use concatenation operator as −
System.out.println("At the age of "+23+" ramu got his first job");
This involves the conversion of the integer value 23 to string and concatenation of this value to the strings surrounding it.
And if it is a logging statement, and if that particular log level of your statement is disabled then, all this calculation will be of no use.
In such circumstances, you can use parameterized logging. In this format, initially SLF4J confirms whether the logging for particular level is enabled. If so then, it replaces the placeholders in the messages with the respective values.
For example, if we have a statement as
Integer age;
Logger.debug("At the age of {} ramu got his first job", age);
Only if debugging is enabled then, SLF4J converts the age into integer and concatenates it with the strings otherwise, it does nothing. Thus incurring the cost of parameter constructions when logging level is disabled.
You can also use two parameters in a message as −
logger.info("Old weight is {}. new weight is {}.", oldWeight, newWeight);
The following example demonstrates the usage of two placeholders in parametrized logging.
import java.util.Scanner;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class PlaceHolders {
public static void main(String[] args) {
Integer oldWeight;
Integer newWeight;
Scanner sc = new Scanner(System.in);
System.out.println("Enter old weight:");
oldWeight = sc.nextInt();
System.out.println("Enter new weight:");
newWeight = sc.nextInt();
//Creating the Logger object
Logger logger = LoggerFactory.getLogger(Sample.class);
//Logging the information
logger.info("Old weight is {}. new weight is {}.", oldWeight, newWeight);
//Logging the information
logger.info("After the program weight reduced is: "+(oldWeight-newWeight));
}
}
Upon execution, the above program generates the following output.
Enter old weight:
85
Enter new weight:
74
Dec 10, 2018 4:12:31 PM PlaceHolders main
INFO: Old weight is 85. new weight is 74.
Dec 10, 2018 4:12:31 PM PlaceHolders main
INFO: After the program weight reduced is: 11
You can also use more than two placeholders as shown in the following example −
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class PlaceHolders {
public static void main(String[] args) {
Integer age = 24;
String designation = "Software Engineer";
String company = "Infosys";
//Creating the Logger object
Logger logger = LoggerFactory.getLogger(Sample.class);
//Logging the information
logger.info("At the age of {} ramu got his first job as a {} at {}", age, designation, company);
}
}
Upon execution, the above program generates the following output −
Dec 10, 2018 4:23:52 PM PlaceHolders main
INFO: At the age of 24 ramu got his first job as a Software Engineer at Infosys
Print
Add Notes
Bookmark this page | [
{
"code": null,
"e": 1878,
"s": 1785,
"text": "As discussed earlier in this tutorial SLF4J provides support for parameterized log messages."
},
{
"code": null,
"e": 1970,
"s": 1878,
"text": "You can use parameters in the messages and pass values to them later in the same statement."
},
{
"code": null,
"e": 2169,
"s": 1970,
"text": "As shown below, you need to use placeholders ({}) in the message (String) wherever you need and later you can pass value for place holder in object form, separating the message and value with comma."
},
{
"code": null,
"e": 2244,
"s": 2169,
"text": "Integer age;\nLogger.info(\"At the age of {} ramu got his first job\", age);\n"
},
{
"code": null,
"e": 2338,
"s": 2244,
"text": "The following example demonstrates parameterized logging (with single parameter) using SLF4J."
},
{
"code": null,
"e": 2713,
"s": 2338,
"text": "import org.slf4j.Logger;\nimport org.slf4j.LoggerFactory;\npublic class PlaceHolders {\n public static void main(String[] args) {\n \n //Creating the Logger object\n Logger logger = LoggerFactory.getLogger(PlaceHolders.class);\n Integer age = 23;\n \n //Logging the information\n logger.info(\"At the age of {} ramu got his first job\", age);\n }\n}"
},
{
"code": null,
"e": 2780,
"s": 2713,
"text": "Upon execution, the above program generates the following output −"
},
{
"code": null,
"e": 2869,
"s": 2780,
"text": "Dec 10, 2018 3:25:45 PM PlaceHolders main\nINFO: At the age of 23 Ramu got his first job\n"
},
{
"code": null,
"e": 2961,
"s": 2869,
"text": "In Java, if we need to print values in a statement, we will use concatenation operator as −"
},
{
"code": null,
"e": 3029,
"s": 2961,
"text": "System.out.println(\"At the age of \"+23+\" ramu got his first job\");\n"
},
{
"code": null,
"e": 3155,
"s": 3029,
"text": "This involves the conversion of the integer value 23 to string and concatenation of this value to the strings surrounding it."
},
{
"code": null,
"e": 3298,
"s": 3155,
"text": "And if it is a logging statement, and if that particular log level of your statement is disabled then, all this calculation will be of no use."
},
{
"code": null,
"e": 3535,
"s": 3298,
"text": "In such circumstances, you can use parameterized logging. In this format, initially SLF4J confirms whether the logging for particular level is enabled. If so then, it replaces the placeholders in the messages with the respective values."
},
{
"code": null,
"e": 3574,
"s": 3535,
"text": "For example, if we have a statement as"
},
{
"code": null,
"e": 3650,
"s": 3574,
"text": "Integer age;\nLogger.debug(\"At the age of {} ramu got his first job\", age);\n"
},
{
"code": null,
"e": 3869,
"s": 3650,
"text": "Only if debugging is enabled then, SLF4J converts the age into integer and concatenates it with the strings otherwise, it does nothing. Thus incurring the cost of parameter constructions when logging level is disabled."
},
{
"code": null,
"e": 3919,
"s": 3869,
"text": "You can also use two parameters in a message as −"
},
{
"code": null,
"e": 3994,
"s": 3919,
"text": "logger.info(\"Old weight is {}. new weight is {}.\", oldWeight, newWeight);\n"
},
{
"code": null,
"e": 4084,
"s": 3994,
"text": "The following example demonstrates the usage of two placeholders in parametrized logging."
},
{
"code": null,
"e": 4825,
"s": 4084,
"text": "import java.util.Scanner;\nimport org.slf4j.Logger;\nimport org.slf4j.LoggerFactory;\n\npublic class PlaceHolders {\n public static void main(String[] args) {\n Integer oldWeight;\n Integer newWeight;\n Scanner sc = new Scanner(System.in);\n System.out.println(\"Enter old weight:\");\n oldWeight = sc.nextInt();\n\n System.out.println(\"Enter new weight:\");\n newWeight = sc.nextInt();\n\n //Creating the Logger object\n Logger logger = LoggerFactory.getLogger(Sample.class);\n\n //Logging the information\n logger.info(\"Old weight is {}. new weight is {}.\", oldWeight, newWeight);\n \n //Logging the information\n logger.info(\"After the program weight reduced is: \"+(oldWeight-newWeight));\n }\n}"
},
{
"code": null,
"e": 4891,
"s": 4825,
"text": "Upon execution, the above program generates the following output."
},
{
"code": null,
"e": 5106,
"s": 4891,
"text": "Enter old weight:\n85\nEnter new weight:\n74\nDec 10, 2018 4:12:31 PM PlaceHolders main\nINFO: Old weight is 85. new weight is 74.\nDec 10, 2018 4:12:31 PM PlaceHolders main\nINFO: After the program weight reduced is: 11\n"
},
{
"code": null,
"e": 5186,
"s": 5106,
"text": "You can also use more than two placeholders as shown in the following example −"
},
{
"code": null,
"e": 5661,
"s": 5186,
"text": "import org.slf4j.Logger;\nimport org.slf4j.LoggerFactory;\npublic class PlaceHolders {\n public static void main(String[] args) {\n Integer age = 24;\n String designation = \"Software Engineer\";\n String company = \"Infosys\";\n\n //Creating the Logger object\n Logger logger = LoggerFactory.getLogger(Sample.class);\n\n //Logging the information\n logger.info(\"At the age of {} ramu got his first job as a {} at {}\", age, designation, company);\n }\n}"
},
{
"code": null,
"e": 5728,
"s": 5661,
"text": "Upon execution, the above program generates the following output −"
},
{
"code": null,
"e": 5851,
"s": 5728,
"text": "Dec 10, 2018 4:23:52 PM PlaceHolders main\nINFO: At the age of 24 ramu got his first job as a Software Engineer at Infosys\n"
},
{
"code": null,
"e": 5858,
"s": 5851,
"text": " Print"
},
{
"code": null,
"e": 5869,
"s": 5858,
"text": " Add Notes"
}
] |
How to Use WiFi Direct on Android? | This example demonstrate about How to Use WiFi Direct 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"?>
<LinearLayout xmlns:android = "http://schemas.android.com/apk/res/android"
xmlns:tools = "http://schemas.android.com/tools"
android:layout_width = "match_parent"
android:layout_height = "match_parent"
android:layout_margin = "16dp"
android:orientation = "vertical"
tools:context = ".MainActivity">
<Button
android:text = "Turn on wifi"
android:id = "@+id/button"
android:layout_width = "wrap_content"
android:layout_height = "wrap_content"
android:layout_gravity = "center" />
</LinearLayout>
Step 3 − Add the following code to src/WifiDirectBroadcastReceiver
package com.example.myapplication;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.net.wifi.p2p.WifiP2pManager;
import android.widget.Toast;
public class WifiDirectBroadcastReceiver extends BroadcastReceiver {
WifiP2pManager wifiP2pManager;
WifiP2pManager.Channel channel;
MainActivity activity;
public WifiDirectBroadcastReceiver(WifiP2pManager wifiP2pManager, WifiP2pManager.Channel channel, MainActivity activity) {
this.wifiP2pManager = wifiP2pManager;
this.channel = channel;
this.activity = activity;
}
@Override
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
if (WifiP2pManager.WIFI_P2P_STATE_CHANGED_ACTION.equals(action)) {
int state = intent.getIntExtra(WifiP2pManager.EXTRA_WIFI_STATE, -1);
if (state = = WifiP2pManager.WIFI_P2P_STATE_ENABLED) {
Toast.makeText(activity, "Wifi on", Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(activity, "Wifi off", Toast.LENGTH_SHORT).show();
}
} else if (WifiP2pManager.WIFI_P2P_PEERS_CHANGED_ACTION.equals(action)) {
} else if (WifiP2pManager.WIFI_P2P_CONNECTION_CHANGED_ACTION.equals(action)) {
} else if (WifiP2pManager.WIFI_P2P_THIS_DEVICE_CHANGED_ACTION.equals(action)) {
}
}
}
Step 4 − Add the following code to src/MainActivity.java
package com.example.myapplication;
import android.content.BroadcastReceiver;
import android.content.IntentFilter;
import android.net.wifi.WifiManager;
import android.net.wifi.p2p.WifiP2pManager;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
public class MainActivity extends AppCompatActivity {
TextView text;
Button button;
WifiManager mWifiMgr;
WifiP2pManager mWifiP2pMgr;
WifiP2pManager.Channel mChannel;
BroadcastReceiver mReceiver;
IntentFilter mIntentFilter;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
button = findViewById(R.id.button);
mWifiMgr = (WifiManager) getApplicationContext().getSystemService(WIFI_SERVICE);
mWifiMgr.setWifiEnabled(false);
mWifiP2pMgr = (WifiP2pManager) getApplicationContext().getSystemService(WIFI_P2P_SERVICE);
mChannel = mWifiP2pMgr.initialize(this, getMainLooper(), null);
mReceiver = new WifiDirectBroadcastReceiver(mWifiP2pMgr, mChannel, this);
mIntentFilter = new IntentFilter();
mIntentFilter.addAction(WifiP2pManager.WIFI_P2P_STATE_CHANGED_ACTION);
mIntentFilter.addAction(WifiP2pManager.WIFI_P2P_PEERS_CHANGED_ACTION);
mIntentFilter.addAction(WifiP2pManager.WIFI_P2P_CONNECTION_CHANGED_ACTION);
mIntentFilter.addAction(WifiP2pManager.WIFI_P2P_THIS_DEVICE_CHANGED_ACTION);
button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if (mWifiMgr.isWifiEnabled()) {
mWifiMgr.setWifiEnabled(false);
button.setText("Turn on wifi");
} else {
mWifiMgr.setWifiEnabled(true);
button.setText("Turn off wifi");
}
}
});
}
@Override
protected void onResume() {
super.onResume();
registerReceiver(mReceiver, mIntentFilter);
}
@Override
protected void onPause() {
super.onPause();
unregisterReceiver(mReceiver);
}
}
Step 5 − Add the following code to androidManifest.xml
<?xml version = "1.0" encoding = "utf-8"?>
<manifest xmlns:android = "http://schemas.android.com/apk/res/android"
package = "com.example.myapplication">
<uses-permission android:name = "android.permission.CHANGE_WIFI_STATE" />
<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 = "com.example.myapplication.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 – | [
{
"code": null,
"e": 1127,
"s": 1062,
"text": "This example demonstrate about How to Use WiFi Direct on Android"
},
{
"code": null,
"e": 1256,
"s": 1127,
"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": 1321,
"s": 1256,
"text": "Step 2 − Add the following code to res/layout/activity_main.xml."
},
{
"code": null,
"e": 1908,
"s": 1321,
"text": "<?xml version = \"1.0\" encoding = \"utf-8\"?>\n<LinearLayout xmlns:android = \"http://schemas.android.com/apk/res/android\"\n xmlns:tools = \"http://schemas.android.com/tools\"\n android:layout_width = \"match_parent\"\n android:layout_height = \"match_parent\"\n android:layout_margin = \"16dp\"\n android:orientation = \"vertical\"\n tools:context = \".MainActivity\">\n <Button\n android:text = \"Turn on wifi\"\n android:id = \"@+id/button\"\n android:layout_width = \"wrap_content\"\n android:layout_height = \"wrap_content\"\n android:layout_gravity = \"center\" />\n</LinearLayout>"
},
{
"code": null,
"e": 1975,
"s": 1908,
"text": "Step 3 − Add the following code to src/WifiDirectBroadcastReceiver"
},
{
"code": null,
"e": 3367,
"s": 1975,
"text": "package com.example.myapplication;\nimport android.content.BroadcastReceiver;\nimport android.content.Context;\nimport android.content.Intent;\nimport android.net.wifi.p2p.WifiP2pManager;\nimport android.widget.Toast;\n\npublic class WifiDirectBroadcastReceiver extends BroadcastReceiver {\n WifiP2pManager wifiP2pManager;\n WifiP2pManager.Channel channel;\n MainActivity activity;\n public WifiDirectBroadcastReceiver(WifiP2pManager wifiP2pManager, WifiP2pManager.Channel channel, MainActivity activity) {\n this.wifiP2pManager = wifiP2pManager;\n this.channel = channel;\n this.activity = activity;\n }\n @Override\n public void onReceive(Context context, Intent intent) {\n String action = intent.getAction();\n if (WifiP2pManager.WIFI_P2P_STATE_CHANGED_ACTION.equals(action)) {\n int state = intent.getIntExtra(WifiP2pManager.EXTRA_WIFI_STATE, -1);\n if (state = = WifiP2pManager.WIFI_P2P_STATE_ENABLED) {\n Toast.makeText(activity, \"Wifi on\", Toast.LENGTH_SHORT).show();\n } else {\n Toast.makeText(activity, \"Wifi off\", Toast.LENGTH_SHORT).show();\n }\n } else if (WifiP2pManager.WIFI_P2P_PEERS_CHANGED_ACTION.equals(action)) {\n } else if (WifiP2pManager.WIFI_P2P_CONNECTION_CHANGED_ACTION.equals(action)) {\n } else if (WifiP2pManager.WIFI_P2P_THIS_DEVICE_CHANGED_ACTION.equals(action)) {\n }\n }\n}"
},
{
"code": null,
"e": 3424,
"s": 3367,
"text": "Step 4 − Add the following code to src/MainActivity.java"
},
{
"code": null,
"e": 5605,
"s": 3424,
"text": "package com.example.myapplication;\nimport android.content.BroadcastReceiver;\nimport android.content.IntentFilter;\nimport android.net.wifi.WifiManager;\nimport android.net.wifi.p2p.WifiP2pManager;\nimport android.support.v7.app.AppCompatActivity;\nimport android.os.Bundle;\nimport android.view.View;\nimport android.widget.Button;\nimport android.widget.TextView;\n\npublic class MainActivity extends AppCompatActivity {\n TextView text;\n Button button;\n WifiManager mWifiMgr;\n WifiP2pManager mWifiP2pMgr;\n WifiP2pManager.Channel mChannel;\n BroadcastReceiver mReceiver;\n IntentFilter mIntentFilter;\n @Override\n protected void onCreate(Bundle savedInstanceState) {\n super.onCreate(savedInstanceState);\n setContentView(R.layout.activity_main);\n button = findViewById(R.id.button);\n mWifiMgr = (WifiManager) getApplicationContext().getSystemService(WIFI_SERVICE);\n mWifiMgr.setWifiEnabled(false);\n mWifiP2pMgr = (WifiP2pManager) getApplicationContext().getSystemService(WIFI_P2P_SERVICE);\n mChannel = mWifiP2pMgr.initialize(this, getMainLooper(), null);\n mReceiver = new WifiDirectBroadcastReceiver(mWifiP2pMgr, mChannel, this);\n mIntentFilter = new IntentFilter();\n mIntentFilter.addAction(WifiP2pManager.WIFI_P2P_STATE_CHANGED_ACTION);\n mIntentFilter.addAction(WifiP2pManager.WIFI_P2P_PEERS_CHANGED_ACTION);\n mIntentFilter.addAction(WifiP2pManager.WIFI_P2P_CONNECTION_CHANGED_ACTION);\n mIntentFilter.addAction(WifiP2pManager.WIFI_P2P_THIS_DEVICE_CHANGED_ACTION);\n button.setOnClickListener(new View.OnClickListener() {\n @Override\n public void onClick(View v) {\n if (mWifiMgr.isWifiEnabled()) {\n mWifiMgr.setWifiEnabled(false);\n button.setText(\"Turn on wifi\");\n } else {\n mWifiMgr.setWifiEnabled(true);\n button.setText(\"Turn off wifi\");\n }\n }\n });\n }\n @Override\n protected void onResume() {\n super.onResume();\n registerReceiver(mReceiver, mIntentFilter);\n }\n @Override\n protected void onPause() {\n super.onPause();\n unregisterReceiver(mReceiver);\n }\n}"
},
{
"code": null,
"e": 5660,
"s": 5605,
"text": "Step 5 − Add the following code to androidManifest.xml"
},
{
"code": null,
"e": 6472,
"s": 5660,
"text": "<?xml version = \"1.0\" encoding = \"utf-8\"?>\n<manifest xmlns:android = \"http://schemas.android.com/apk/res/android\"\n package = \"com.example.myapplication\">\n <uses-permission android:name = \"android.permission.CHANGE_WIFI_STATE\" />\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 = \"com.example.myapplication.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": 6821,
"s": 6472,
"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 –"
}
] |
How to remove windows features using PowerShell? | To remove windows features, we can use command Remove-WindowsFeature command is used along with feature name.
Remove-WindowsFeature Search-Service -Verbose
VERBOSE: Uninstallation started...
VERBOSE: Continue with removal?
VERBOSE: Prerequisite processing started...
VERBOSE: Prerequisite processing succeeded.
Success Restart Needed Exit Code Feature Result
------- -------------- --------- --------------
True No Success {Windows Search Service}
VERBOSE: Uninstallation succeeded.
If the windows feature has the management tools like as in Web-Server (IIS) feature, you can add the same in the command line. If the server requires restart then you can add the -Restart parameter. For example,
Remove-WindowsFeature Web-Server -IncludeManagementTools -Restart -Verbose
If we check the -Name parameter, it supports the string array. This means we can remove multiple roles and features together.
help Remove-WindowsFeature -Parameter Name -Name <Feature[]>
Example of removal of multiple features together and with -LogPath parameter to log the output on the local computer.
PS C:\Users\Administrator> Remove-WindowsFeature Windows-Server-Backup, Search-Service -LogPath C:\Temp\Uninstallfeatures.txt -Verbose
VERBOSE: Uninstallation started...
VERBOSE: Continue with removal?
VERBOSE: Prerequisite processing started...
VERBOSE: Prerequisite processing succeeded.
Success Restart Needed Exit Code Feature Result
------- -------------- --------- --------------
True No Success {Windows Search Service, Windows Server Ba...
VERBOSE: Uninstallation succeeded.
To remove windows features on the remote computer, you need to use -ComputerName parameter. For example,
Remove-WindowsFeature Windows-Server-Backup, Search-Service -ComputerName Test1-Win2k16 -Verbose
PS C:\Scripts\IISRestart> Remove-WindowsFeature Windows-Server-Backup, Search-Service -ComputerName Test1-Win2k16 -Verbose
VERBOSE: Uninstallation started...
VERBOSE: Continue with removal?
VERBOSE: Prerequisite processing started...
VERBOSE: Prerequisite processing succeeded.
Success Restart Needed Exit Code Feature Result
------- -------------- --------- --------------
True No Success {Windows Search Service, Windows Server Ba...
VERBOSE: Uninstallation succeeded.
This -ComputerName parameter is a string parameter, not an array as shown below with the help command.
help Remove-WindowsFeature -Parameter ComputerName -ComputerName [<String≫]
So to remove the windows features from the multiple computers, we need to use the foreach loop and -ComputerName parameter or through the Invoke-Command. Using Invoke-Command will be easier.
Invoke-Command -ComputerName Test1-Win2k16,Test1-Win2k12 -ScriptBlock{Remove-WindowsFeature Windows-Server-Backup,Search-Service}
The above command will ensure to remove multiple features on the multiple remote computers. | [
{
"code": null,
"e": 1172,
"s": 1062,
"text": "To remove windows features, we can use command Remove-WindowsFeature command is used along with feature name."
},
{
"code": null,
"e": 1218,
"s": 1172,
"text": "Remove-WindowsFeature Search-Service -Verbose"
},
{
"code": null,
"e": 1545,
"s": 1218,
"text": "VERBOSE: Uninstallation started...\nVERBOSE: Continue with removal?\nVERBOSE: Prerequisite processing started...\nVERBOSE: Prerequisite processing succeeded.\nSuccess Restart Needed Exit Code Feature Result\n------- -------------- --------- --------------\nTrue No Success {Windows Search Service}\nVERBOSE: Uninstallation succeeded."
},
{
"code": null,
"e": 1757,
"s": 1545,
"text": "If the windows feature has the management tools like as in Web-Server (IIS) feature, you can add the same in the command line. If the server requires restart then you can add the -Restart parameter. For example,"
},
{
"code": null,
"e": 1832,
"s": 1757,
"text": "Remove-WindowsFeature Web-Server -IncludeManagementTools -Restart -Verbose"
},
{
"code": null,
"e": 1958,
"s": 1832,
"text": "If we check the -Name parameter, it supports the string array. This means we can remove multiple roles and features together."
},
{
"code": null,
"e": 2019,
"s": 1958,
"text": "help Remove-WindowsFeature -Parameter Name -Name <Feature[]>"
},
{
"code": null,
"e": 2137,
"s": 2019,
"text": "Example of removal of multiple features together and with -LogPath parameter to log the output on the local computer."
},
{
"code": null,
"e": 2620,
"s": 2137,
"text": "PS C:\\Users\\Administrator> Remove-WindowsFeature Windows-Server-Backup, Search-Service -LogPath C:\\Temp\\Uninstallfeatures.txt -Verbose\nVERBOSE: Uninstallation started...\nVERBOSE: Continue with removal?\nVERBOSE: Prerequisite processing started...\nVERBOSE: Prerequisite processing succeeded.\nSuccess Restart Needed Exit Code Feature Result\n------- -------------- --------- --------------\nTrue No Success {Windows Search Service, Windows Server Ba...\nVERBOSE: Uninstallation succeeded."
},
{
"code": null,
"e": 2725,
"s": 2620,
"text": "To remove windows features on the remote computer, you need to use -ComputerName parameter. For example,"
},
{
"code": null,
"e": 2822,
"s": 2725,
"text": "Remove-WindowsFeature Windows-Server-Backup, Search-Service -ComputerName Test1-Win2k16 -Verbose"
},
{
"code": null,
"e": 3294,
"s": 2822,
"text": "PS C:\\Scripts\\IISRestart> Remove-WindowsFeature Windows-Server-Backup, Search-Service -ComputerName Test1-Win2k16 -Verbose\nVERBOSE: Uninstallation started...\nVERBOSE: Continue with removal?\nVERBOSE: Prerequisite processing started...\nVERBOSE: Prerequisite processing succeeded.\n\nSuccess Restart Needed Exit Code Feature Result\n------- -------------- --------- --------------\nTrue No Success {Windows Search Service, Windows Server Ba...\nVERBOSE: Uninstallation succeeded."
},
{
"code": null,
"e": 3397,
"s": 3294,
"text": "This -ComputerName parameter is a string parameter, not an array as shown below with the help command."
},
{
"code": null,
"e": 3473,
"s": 3397,
"text": "help Remove-WindowsFeature -Parameter ComputerName -ComputerName [<String≫]"
},
{
"code": null,
"e": 3664,
"s": 3473,
"text": "So to remove the windows features from the multiple computers, we need to use the foreach loop and -ComputerName parameter or through the Invoke-Command. Using Invoke-Command will be easier."
},
{
"code": null,
"e": 3794,
"s": 3664,
"text": "Invoke-Command -ComputerName Test1-Win2k16,Test1-Win2k12 -ScriptBlock{Remove-WindowsFeature Windows-Server-Backup,Search-Service}"
},
{
"code": null,
"e": 3886,
"s": 3794,
"text": "The above command will ensure to remove multiple features on the multiple remote computers."
}
] |
Remove new line characters from rows in MySQL? | The Trim() function is used to remove new line characters from data rows in MySQL. Let us see an example. First, we will create a table. The CREATE command is used to create a table.
mysql> create table tblDemotrail
- > (
- > id int,
- > name varchar(100)
- > );
Query OK, 0 rows affected (0.57 sec)
Let us now insert some records.
mysql> insert into tblDemotrail values(1,'John ');
Query OK, 1 row affected (0.15 sec)
mysql> insert into tblDemotrail values(2,' Carol');
Query OK, 1 row affected (0.32 sec)
mysql> insert into tblDemotrail values(3,' Sam ');
Query OK, 1 row affected (0.17 sec)
mysql> insert into tblDemotrail values(4,' Tom\n ');
Query OK, 1 row affected (0.18 sec)
mysql> insert into tblDemotrail values(5,' \nTim ');
Query OK, 1 row affected (0.12 sec)
Let us display all the records.
mysql> select *from tblDemotrail;
The following is the output that doesn’t look like normal record, since we included newline characters while adding records.
+------+------------------+
| id | name |
+------+------------------+
| 1 |John |
| 2 | Carol |
| 3 | Sam |
| 4 | Tom |
| 5 |Tim |
+------+------------------+
5 rows in set (0.00 sec)
To remove new line characters, you need to use the following query.
mysql> update tblDemotrail SET name = TRIM(TRAILING '\n' FROM name);
Query OK, 0 rows affected (0.00 sec)
Rows matched: 5 Changed: 0 Warnings: 0 | [
{
"code": null,
"e": 1245,
"s": 1062,
"text": "The Trim() function is used to remove new line characters from data rows in MySQL. Let us see an example. First, we will create a table. The CREATE command is used to create a table."
},
{
"code": null,
"e": 1362,
"s": 1245,
"text": "mysql> create table tblDemotrail\n- > (\n- > id int,\n- > name varchar(100)\n- > );\nQuery OK, 0 rows affected (0.57 sec)"
},
{
"code": null,
"e": 1394,
"s": 1362,
"text": "Let us now insert some records."
},
{
"code": null,
"e": 1838,
"s": 1394,
"text": "mysql> insert into tblDemotrail values(1,'John ');\nQuery OK, 1 row affected (0.15 sec)\n\nmysql> insert into tblDemotrail values(2,' Carol');\nQuery OK, 1 row affected (0.32 sec)\n\nmysql> insert into tblDemotrail values(3,' Sam ');\nQuery OK, 1 row affected (0.17 sec)\n\nmysql> insert into tblDemotrail values(4,' Tom\\n ');\nQuery OK, 1 row affected (0.18 sec)\n\nmysql> insert into tblDemotrail values(5,' \\nTim ');\nQuery OK, 1 row affected (0.12 sec)"
},
{
"code": null,
"e": 1870,
"s": 1838,
"text": "Let us display all the records."
},
{
"code": null,
"e": 1904,
"s": 1870,
"text": "mysql> select *from tblDemotrail;"
},
{
"code": null,
"e": 2029,
"s": 1904,
"text": "The following is the output that doesn’t look like normal record, since we included newline characters while adding records."
},
{
"code": null,
"e": 2306,
"s": 2029,
"text": "+------+------------------+\n| id | name |\n+------+------------------+\n| 1 |John |\n| 2 | Carol |\n| 3 | Sam |\n| 4 | Tom |\n| 5 |Tim |\n+------+------------------+\n5 rows in set (0.00 sec)"
},
{
"code": null,
"e": 2374,
"s": 2306,
"text": "To remove new line characters, you need to use the following query."
},
{
"code": null,
"e": 2519,
"s": 2374,
"text": "mysql> update tblDemotrail SET name = TRIM(TRAILING '\\n' FROM name);\nQuery OK, 0 rows affected (0.00 sec)\nRows matched: 5 Changed: 0 Warnings: 0"
}
] |
C Program for Program for array rotation? | Write a C program to left rotate an array by n position. How to rotate left rotate an array n times in C programming. Logic to rotate an array to left by n position in C program.
Input: arr[]=1 2 3 4 5 6 7 8 9 10
N=3
Output: 4 5 6 7 8 9 10 1 2 3
Read elements in an array say arr.
Read elements in an array say arr.
Read number of times to rotate in some variable say N.
Read number of times to rotate in some variable say N.
Left Rotate the given array by 1 for N times. In real left rotation is shifting of array elements to one position left and copying first element to last.
Left Rotate the given array by 1 for N times. In real left rotation is shifting of array elements to one position left and copying first element to last.
#include <iostream>
using namespace std;
int main() {
int arr[] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
int i, N, len, j;
N=3;
len=10;
int temp=0;
for (i = 0; i < N; i++) {
int x = arr[0];
for (j = 0; j < len; j++) {
temp=arr[j];
arr[j] = arr[j + 1];
arr[j+1]=temp;
}
arr[len - 1] = x;
}
for (i = 0; i < len; i++) {
cout<< arr[i]<<"\t";
}
} | [
{
"code": null,
"e": 1241,
"s": 1062,
"text": "Write a C program to left rotate an array by n position. How to rotate left rotate an array n times in C programming. Logic to rotate an array to left by n position in C program."
},
{
"code": null,
"e": 1308,
"s": 1241,
"text": "Input: arr[]=1 2 3 4 5 6 7 8 9 10\nN=3\nOutput: 4 5 6 7 8 9 10 1 2 3"
},
{
"code": null,
"e": 1343,
"s": 1308,
"text": "Read elements in an array say arr."
},
{
"code": null,
"e": 1378,
"s": 1343,
"text": "Read elements in an array say arr."
},
{
"code": null,
"e": 1433,
"s": 1378,
"text": "Read number of times to rotate in some variable say N."
},
{
"code": null,
"e": 1488,
"s": 1433,
"text": "Read number of times to rotate in some variable say N."
},
{
"code": null,
"e": 1642,
"s": 1488,
"text": "Left Rotate the given array by 1 for N times. In real left rotation is shifting of array elements to one position left and copying first element to last."
},
{
"code": null,
"e": 1796,
"s": 1642,
"text": "Left Rotate the given array by 1 for N times. In real left rotation is shifting of array elements to one position left and copying first element to last."
},
{
"code": null,
"e": 2216,
"s": 1796,
"text": "#include <iostream>\nusing namespace std;\nint main() {\n int arr[] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};\n int i, N, len, j;\n N=3;\n len=10;\n int temp=0;\n for (i = 0; i < N; i++) {\n int x = arr[0];\n for (j = 0; j < len; j++) {\n temp=arr[j];\n arr[j] = arr[j + 1];\n arr[j+1]=temp;\n }\n arr[len - 1] = x;\n }\n for (i = 0; i < len; i++) {\n cout<< arr[i]<<\"\\t\";\n }\n}"
}
] |
Python Program to Merge Two Lists and Sort it | When it is required to merge two lists and sort them, a method can be defined that sorts the list using ‘sort’ method.
Below is the demonstration of the same −
Live Demo
def merge_list(list_1, list_2):
merged_list = list_1 + list_2
merged_list.sort()
return(merged_list)
list_1 = [20, 18, 9, 51, 48, 31]
list_2 = [28, 33, 3, 22, 15, 20]
print("The first list is :")
print(list_1)
print("The second list is :")
print(list_2)
print(merge_list(list_1, list_2))
The first list is :
[20, 18, 9, 51, 48, 31]
The second list is :
[28, 33, 3, 22, 15, 20]
[3, 9, 15, 18, 20, 20, 22, 28, 31, 33, 48, 51]
A method named ‘merge_list’ is defined that takes two lists as parameters.
A method named ‘merge_list’ is defined that takes two lists as parameters.
The two lists are concatenated using the ‘+’ operator.
The two lists are concatenated using the ‘+’ operator.
It is assigned to a variable.
It is assigned to a variable.
The sort method is used to sort the final result.
The sort method is used to sort the final result.
Outside the method, two lists are defined, and displayed on the console.
Outside the method, two lists are defined, and displayed on the console.
The method is called by passing these two lists.
The method is called by passing these two lists.
The output is displayed on the console.
The output is displayed on the console. | [
{
"code": null,
"e": 1181,
"s": 1062,
"text": "When it is required to merge two lists and sort them, a method can be defined that sorts the list using ‘sort’ method."
},
{
"code": null,
"e": 1222,
"s": 1181,
"text": "Below is the demonstration of the same −"
},
{
"code": null,
"e": 1233,
"s": 1222,
"text": " Live Demo"
},
{
"code": null,
"e": 1531,
"s": 1233,
"text": "def merge_list(list_1, list_2):\n merged_list = list_1 + list_2\n merged_list.sort()\n return(merged_list)\n\nlist_1 = [20, 18, 9, 51, 48, 31]\nlist_2 = [28, 33, 3, 22, 15, 20]\nprint(\"The first list is :\")\nprint(list_1)\nprint(\"The second list is :\")\nprint(list_2)\nprint(merge_list(list_1, list_2))"
},
{
"code": null,
"e": 1667,
"s": 1531,
"text": "The first list is :\n[20, 18, 9, 51, 48, 31]\nThe second list is :\n[28, 33, 3, 22, 15, 20]\n[3, 9, 15, 18, 20, 20, 22, 28, 31, 33, 48, 51]"
},
{
"code": null,
"e": 1742,
"s": 1667,
"text": "A method named ‘merge_list’ is defined that takes two lists as parameters."
},
{
"code": null,
"e": 1817,
"s": 1742,
"text": "A method named ‘merge_list’ is defined that takes two lists as parameters."
},
{
"code": null,
"e": 1872,
"s": 1817,
"text": "The two lists are concatenated using the ‘+’ operator."
},
{
"code": null,
"e": 1927,
"s": 1872,
"text": "The two lists are concatenated using the ‘+’ operator."
},
{
"code": null,
"e": 1957,
"s": 1927,
"text": "It is assigned to a variable."
},
{
"code": null,
"e": 1987,
"s": 1957,
"text": "It is assigned to a variable."
},
{
"code": null,
"e": 2037,
"s": 1987,
"text": "The sort method is used to sort the final result."
},
{
"code": null,
"e": 2087,
"s": 2037,
"text": "The sort method is used to sort the final result."
},
{
"code": null,
"e": 2160,
"s": 2087,
"text": "Outside the method, two lists are defined, and displayed on the console."
},
{
"code": null,
"e": 2233,
"s": 2160,
"text": "Outside the method, two lists are defined, and displayed on the console."
},
{
"code": null,
"e": 2282,
"s": 2233,
"text": "The method is called by passing these two lists."
},
{
"code": null,
"e": 2331,
"s": 2282,
"text": "The method is called by passing these two lists."
},
{
"code": null,
"e": 2371,
"s": 2331,
"text": "The output is displayed on the console."
},
{
"code": null,
"e": 2411,
"s": 2371,
"text": "The output is displayed on the console."
}
] |
How to Use Pandas apply() inplace? - GeeksforGeeks | 28 Nov, 2021
In this article, we are going to see how to use Pandas apply() inplace in Python.
In Python, this function is equivalent to the map() function. It takes a function as an input and applies it to a DataFrame as a whole. If you’re dealing with data in the form of tables, you’ll need to choose which axis your function should act on ( 0 for columns; and 1 for rows).
No, the apply() method doesn’t contain an inplace parameter, unlike these pandas methods which have an inplace parameter:
df.drop()
df.rename( inplace=True)
fillna()
dropna()
sort_values()
reset_index()
sort_index()
rename()
The data is edited in place when inplace = True, which means it will return nothing and the data frame will be updated. When inplace = False, which is the default, the operation is carried out and a copy of the object is returned.
in the below code. we first imported the pandas package and imported our CSV file using pd.read_csv(). after importing we use the apply function on the ‘experience’ column of our data frame. we convert the strings of that column to uppercase.
Used CSV file:
Python3
# codeimport pandas as pd # importing our datasetdf = pd.read_csv('hiring.csv')# viewing the dataFrameprint(df) # we change the case of all the strings# in experience column to uppercasedf['experience'] = df['experience'].apply(str.upper) # viewing the modified columnprint(df['experience'])
Output:
0 FIVE
1 TWO
2 SEVEN
3 THREE
4 ELEVEN
Name: experience, dtype: object
In this example, we use apply() method on multiple columns. we change the datatype of the columns from float to int. Used CSV file click here.
Python3
import pandas as pdimport numpy as np # importing our datasetdata = pd.read_csv('cluster_blobs.csv') # viewing the dataFrameprint(df) # we convert the datatype of columns from float to int.data[['X1', 'X2']] = data[['X1', 'X2']].apply(np.int64) # viewing the modified columnprint(data[['X1', 'X2']])
Output:
in this example, we use the same CSV file as before. here we use the apply() method on the entire data frame. we change the datatype of the columns from float to int.
Python3
import pandas as pdimport numpy as np # importing our datasetdata = pd.read_csv('cluster_blobs.csv') # viewing the dataFrameprint(data) # we convert the datatype of# columns from float to int.data = data.apply(np.int64) # viewing the modified columnprint(data)
Output:
Picked
Python pandas-methods
Python-pandas
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": "\n28 Nov, 2021"
},
{
"code": null,
"e": 25619,
"s": 25537,
"text": "In this article, we are going to see how to use Pandas apply() inplace in Python."
},
{
"code": null,
"e": 25902,
"s": 25619,
"text": "In Python, this function is equivalent to the map() function. It takes a function as an input and applies it to a DataFrame as a whole. If you’re dealing with data in the form of tables, you’ll need to choose which axis your function should act on ( 0 for columns; and 1 for rows). "
},
{
"code": null,
"e": 26024,
"s": 25902,
"text": "No, the apply() method doesn’t contain an inplace parameter, unlike these pandas methods which have an inplace parameter:"
},
{
"code": null,
"e": 26034,
"s": 26024,
"text": "df.drop()"
},
{
"code": null,
"e": 26059,
"s": 26034,
"text": "df.rename( inplace=True)"
},
{
"code": null,
"e": 26068,
"s": 26059,
"text": "fillna()"
},
{
"code": null,
"e": 26077,
"s": 26068,
"text": "dropna()"
},
{
"code": null,
"e": 26091,
"s": 26077,
"text": "sort_values()"
},
{
"code": null,
"e": 26105,
"s": 26091,
"text": "reset_index()"
},
{
"code": null,
"e": 26118,
"s": 26105,
"text": "sort_index()"
},
{
"code": null,
"e": 26127,
"s": 26118,
"text": "rename()"
},
{
"code": null,
"e": 26358,
"s": 26127,
"text": "The data is edited in place when inplace = True, which means it will return nothing and the data frame will be updated. When inplace = False, which is the default, the operation is carried out and a copy of the object is returned."
},
{
"code": null,
"e": 26601,
"s": 26358,
"text": "in the below code. we first imported the pandas package and imported our CSV file using pd.read_csv(). after importing we use the apply function on the ‘experience’ column of our data frame. we convert the strings of that column to uppercase."
},
{
"code": null,
"e": 26616,
"s": 26601,
"text": "Used CSV file:"
},
{
"code": null,
"e": 26624,
"s": 26616,
"text": "Python3"
},
{
"code": "# codeimport pandas as pd # importing our datasetdf = pd.read_csv('hiring.csv')# viewing the dataFrameprint(df) # we change the case of all the strings# in experience column to uppercasedf['experience'] = df['experience'].apply(str.upper) # viewing the modified columnprint(df['experience'])",
"e": 26919,
"s": 26624,
"text": null
},
{
"code": null,
"e": 26927,
"s": 26919,
"text": "Output:"
},
{
"code": null,
"e": 27019,
"s": 26927,
"text": "0 FIVE\n1 TWO\n2 SEVEN\n3 THREE\n4 ELEVEN\nName: experience, dtype: object"
},
{
"code": null,
"e": 27162,
"s": 27019,
"text": "In this example, we use apply() method on multiple columns. we change the datatype of the columns from float to int. Used CSV file click here."
},
{
"code": null,
"e": 27170,
"s": 27162,
"text": "Python3"
},
{
"code": "import pandas as pdimport numpy as np # importing our datasetdata = pd.read_csv('cluster_blobs.csv') # viewing the dataFrameprint(df) # we convert the datatype of columns from float to int.data[['X1', 'X2']] = data[['X1', 'X2']].apply(np.int64) # viewing the modified columnprint(data[['X1', 'X2']])",
"e": 27474,
"s": 27170,
"text": null
},
{
"code": null,
"e": 27482,
"s": 27474,
"text": "Output:"
},
{
"code": null,
"e": 27649,
"s": 27482,
"text": "in this example, we use the same CSV file as before. here we use the apply() method on the entire data frame. we change the datatype of the columns from float to int."
},
{
"code": null,
"e": 27657,
"s": 27649,
"text": "Python3"
},
{
"code": "import pandas as pdimport numpy as np # importing our datasetdata = pd.read_csv('cluster_blobs.csv') # viewing the dataFrameprint(data) # we convert the datatype of# columns from float to int.data = data.apply(np.int64) # viewing the modified columnprint(data)",
"e": 27922,
"s": 27657,
"text": null
},
{
"code": null,
"e": 27930,
"s": 27922,
"text": "Output:"
},
{
"code": null,
"e": 27937,
"s": 27930,
"text": "Picked"
},
{
"code": null,
"e": 27959,
"s": 27937,
"text": "Python pandas-methods"
},
{
"code": null,
"e": 27973,
"s": 27959,
"text": "Python-pandas"
},
{
"code": null,
"e": 27980,
"s": 27973,
"text": "Python"
},
{
"code": null,
"e": 28078,
"s": 27980,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 28110,
"s": 28078,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 28152,
"s": 28110,
"text": "Check if element exists in list in Python"
},
{
"code": null,
"e": 28194,
"s": 28152,
"text": "How To Convert Python Dictionary To JSON?"
},
{
"code": null,
"e": 28221,
"s": 28194,
"text": "Python Classes and Objects"
},
{
"code": null,
"e": 28277,
"s": 28221,
"text": "How to drop one or multiple columns in Pandas Dataframe"
},
{
"code": null,
"e": 28299,
"s": 28277,
"text": "Defaultdict in Python"
},
{
"code": null,
"e": 28338,
"s": 28299,
"text": "Python | Get unique values from a list"
},
{
"code": null,
"e": 28369,
"s": 28338,
"text": "Python | os.path.join() method"
},
{
"code": null,
"e": 28398,
"s": 28369,
"text": "Create a directory in Python"
}
] |
How to create a transparent or blurred card using CSS ? - GeeksforGeeks | 29 Sep, 2021
In this article, we will create a transparent or blurred card using basic HTML and CSS properties. The blurred effect is also called the glass effect.
Approach:
In the body tag, create the layout of the card.
Define the classes to each of the components to use the CSS properties.
To apply the glass or blur effect, use the backdrop filter property to blur the card.
Example: Create a glass or blur or transparent card using the above approach. As mentioned in the first step, we will create the layout of the card under the body tag.
HTML
<!DOCTYPE html><html> <head> <title>Page Title</title></head> <body> <div class="background"> <div class="card"> <img src="https://media.geeksforgeeks.org/wp-content/cdn-uploads/20190710102234/download3.png" alt="image" /> <h1>GeeksforGeeks</h1> <h3>Happy Coding</h3> </div> </div></body> </html>
In the above code, we have created a nested div tag that holds an image and some text and assigned classes to these div tags that will be used for stylings. For Stylings we have used basic CSS properties.
Note: You can create another CSS file for stylings or can use the same HTML file to use the same HTML file write CSS properties under the style tag.
CSS
.background { background-color: green; height: 150px; padding: 10px;} .card { margin-right: auto; margin-left: auto; width: 250px; box-shadow: 0 15px 25px rgba(129, 124, 124, 0.2); height: 300px; border-radius: 5px; backdrop-filter: blur(14px); background-color: rgba(255, 255, 255, 0.2); padding: 10px; text-align: center;} .card img { height: 60%;}
In the above-mentioned code, under the card class, we have added backdrop filter property to blur which will be responsible for the blur effect. The CSS backdrop-filter property is used to apply effects to the area behind an element.
Note: For a better understanding of backdrop-filter property click on the mentioned link.
Complete Code:
HTML
<!DOCTYPE html><html lang="en"> <head> <title>Blur Card</title> <style> .background { background-color: green; height: 150px; padding: 10px; } .card { margin-right: auto; margin-left: auto; width: 250px; box-shadow: 0 15px 25px rgba(129, 124, 124, 0.2); height: 300px; border-radius: 5px; backdrop-filter: blur(14px); background-color: rgba(255, 255, 255, 0.2); padding: 10px; text-align: center; } .card img { height: 60%; } </style></head> <body> <div class="background"> <div class="card"> <img src="https://media.geeksforgeeks.org/wp-content/cdn-uploads/20190710102234/download3.png" alt="image" /> <h1>GeeksforGeeks</h1> <h3>Happy Coding</h3> </div> </div></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.
CSS-Properties
CSS-Questions
HTML-Questions
CSS
HTML
Web Technologies
HTML
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Design a web page using HTML and CSS
How to set space between the flexbox ?
Form validation using jQuery
Search Bar using HTML, CSS and JavaScript
How to style a checkbox using CSS?
How to set the default value for an HTML <select> element ?
Hide or show elements in HTML using display property
How to set input type date in dd-mm-yyyy format using HTML ?
REST API (Introduction)
How to Insert Form Data into Database using PHP ? | [
{
"code": null,
"e": 26621,
"s": 26593,
"text": "\n29 Sep, 2021"
},
{
"code": null,
"e": 26772,
"s": 26621,
"text": "In this article, we will create a transparent or blurred card using basic HTML and CSS properties. The blurred effect is also called the glass effect."
},
{
"code": null,
"e": 26783,
"s": 26772,
"text": "Approach: "
},
{
"code": null,
"e": 26831,
"s": 26783,
"text": "In the body tag, create the layout of the card."
},
{
"code": null,
"e": 26903,
"s": 26831,
"text": "Define the classes to each of the components to use the CSS properties."
},
{
"code": null,
"e": 26989,
"s": 26903,
"text": "To apply the glass or blur effect, use the backdrop filter property to blur the card."
},
{
"code": null,
"e": 27157,
"s": 26989,
"text": "Example: Create a glass or blur or transparent card using the above approach. As mentioned in the first step, we will create the layout of the card under the body tag."
},
{
"code": null,
"e": 27162,
"s": 27157,
"text": "HTML"
},
{
"code": "<!DOCTYPE html><html> <head> <title>Page Title</title></head> <body> <div class=\"background\"> <div class=\"card\"> <img src=\"https://media.geeksforgeeks.org/wp-content/cdn-uploads/20190710102234/download3.png\" alt=\"image\" /> <h1>GeeksforGeeks</h1> <h3>Happy Coding</h3> </div> </div></body> </html>",
"e": 27533,
"s": 27162,
"text": null
},
{
"code": null,
"e": 27738,
"s": 27533,
"text": "In the above code, we have created a nested div tag that holds an image and some text and assigned classes to these div tags that will be used for stylings. For Stylings we have used basic CSS properties."
},
{
"code": null,
"e": 27887,
"s": 27738,
"text": "Note: You can create another CSS file for stylings or can use the same HTML file to use the same HTML file write CSS properties under the style tag."
},
{
"code": null,
"e": 27891,
"s": 27887,
"text": "CSS"
},
{
"code": ".background { background-color: green; height: 150px; padding: 10px;} .card { margin-right: auto; margin-left: auto; width: 250px; box-shadow: 0 15px 25px rgba(129, 124, 124, 0.2); height: 300px; border-radius: 5px; backdrop-filter: blur(14px); background-color: rgba(255, 255, 255, 0.2); padding: 10px; text-align: center;} .card img { height: 60%;}",
"e": 28286,
"s": 27891,
"text": null
},
{
"code": null,
"e": 28520,
"s": 28286,
"text": "In the above-mentioned code, under the card class, we have added backdrop filter property to blur which will be responsible for the blur effect. The CSS backdrop-filter property is used to apply effects to the area behind an element."
},
{
"code": null,
"e": 28610,
"s": 28520,
"text": "Note: For a better understanding of backdrop-filter property click on the mentioned link."
},
{
"code": null,
"e": 28625,
"s": 28610,
"text": "Complete Code:"
},
{
"code": null,
"e": 28630,
"s": 28625,
"text": "HTML"
},
{
"code": "<!DOCTYPE html><html lang=\"en\"> <head> <title>Blur Card</title> <style> .background { background-color: green; height: 150px; padding: 10px; } .card { margin-right: auto; margin-left: auto; width: 250px; box-shadow: 0 15px 25px rgba(129, 124, 124, 0.2); height: 300px; border-radius: 5px; backdrop-filter: blur(14px); background-color: rgba(255, 255, 255, 0.2); padding: 10px; text-align: center; } .card img { height: 60%; } </style></head> <body> <div class=\"background\"> <div class=\"card\"> <img src=\"https://media.geeksforgeeks.org/wp-content/cdn-uploads/20190710102234/download3.png\" alt=\"image\" /> <h1>GeeksforGeeks</h1> <h3>Happy Coding</h3> </div> </div></body> </html>",
"e": 29587,
"s": 28630,
"text": null
},
{
"code": null,
"e": 29596,
"s": 29587,
"text": "Output: "
},
{
"code": null,
"e": 29733,
"s": 29596,
"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": 29748,
"s": 29733,
"text": "CSS-Properties"
},
{
"code": null,
"e": 29762,
"s": 29748,
"text": "CSS-Questions"
},
{
"code": null,
"e": 29777,
"s": 29762,
"text": "HTML-Questions"
},
{
"code": null,
"e": 29781,
"s": 29777,
"text": "CSS"
},
{
"code": null,
"e": 29786,
"s": 29781,
"text": "HTML"
},
{
"code": null,
"e": 29803,
"s": 29786,
"text": "Web Technologies"
},
{
"code": null,
"e": 29808,
"s": 29803,
"text": "HTML"
},
{
"code": null,
"e": 29906,
"s": 29808,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 29943,
"s": 29906,
"text": "Design a web page using HTML and CSS"
},
{
"code": null,
"e": 29982,
"s": 29943,
"text": "How to set space between the flexbox ?"
},
{
"code": null,
"e": 30011,
"s": 29982,
"text": "Form validation using jQuery"
},
{
"code": null,
"e": 30053,
"s": 30011,
"text": "Search Bar using HTML, CSS and JavaScript"
},
{
"code": null,
"e": 30088,
"s": 30053,
"text": "How to style a checkbox using CSS?"
},
{
"code": null,
"e": 30148,
"s": 30088,
"text": "How to set the default value for an HTML <select> element ?"
},
{
"code": null,
"e": 30201,
"s": 30148,
"text": "Hide or show elements in HTML using display property"
},
{
"code": null,
"e": 30262,
"s": 30201,
"text": "How to set input type date in dd-mm-yyyy format using HTML ?"
},
{
"code": null,
"e": 30286,
"s": 30262,
"text": "REST API (Introduction)"
}
] |
Subsets and Splits