title
stringlengths 3
221
| text
stringlengths 17
477k
| parsed
listlengths 0
3.17k
|
---|---|---|
Find the sum of the ascii values of characters which are present at prime positions - GeeksforGeeks | 10 May, 2021
Given string str of size N, the task is to find the sum of all ASCII values of the characters which are present at prime positions.Examples:
Input: str = “abcdef” Output: 298 ‘b’, ‘c’ and ‘e’ are the only characters which are at prime positions i.e. 2, 3 and 5 respectively. And sum of their ASCII values is 298.Input: str = “geeksforgeeks” Output: 644
Approach: An efficient approach is to traverse through the whole string and find if the particular position is prime or not. If the position of the current character is prime then add the ASCII value of the character to the answer.Below is the implementation of the above approach:
C++
Java
Python3
C#
Javascript
// C++ implementation of the approach#include <bits/stdc++.h>using namespace std; // Function that returns true// if n is primebool isPrime(int n){ if (n == 0 || n == 1) return false; for (int i = 2; i * i <= n; i++) if (n % i == 0) return false; return true;} // Function to return the sum// of the ascii values of the characters// which are present at prime positionsint sumAscii(string str, int n){ // To store the sum int sum = 0; // For every character for (int i = 0; i < n; i++) { // If current position is prime // then add the ASCII value of the // character at the current position if (isPrime(i + 1)) sum += (int)(str[i]); } return sum;} // Driver codeint main(){ string str = "geeksforgeeks"; int n = str.size(); cout << sumAscii(str, n); return 0;}
// Java implementation of the approachimport java.util.*; class GFG{ // Function that returns true // if n is prime static boolean isPrime(int n) { if (n == 0 || n == 1) { return false; } for (int i = 2; i * i <= n; i++) { if (n % i == 0) { return false; } } return true; } // Function to return the sum // of the ascii values of the characters // which are present at prime positions static int sumAscii(String str, int n) { // To store the sum int sum = 0; // For every character for (int i = 0; i < n; i++) { // If current position is prime // then add the ASCII value of the // character at the current position if (isPrime(i + 1)) { sum += (int) (str.charAt(i)); } } return sum; } // Driver code public static void main(String[] args) { String str = "geeksforgeeks"; int n = str.length(); System.out.println(sumAscii(str, n)); }} // This code contributed by Rajput-Ji
# Python3 implementation of the approach from math import sqrt # Function that returns true# if n is primedef isPrime(n) : if (n == 0 or n == 1) : return False; for i in range(2, int(sqrt(n)) + 1) : if (n % i == 0): return False; return True; # Function to return the sum# of the ascii values of the characters# which are present at prime positionsdef sumAscii(string, n) : # To store the sum sum = 0; # For every character for i in range(n) : # If current position is prime # then add the ASCII value of the # character at the current position if (isPrime(i + 1)) : sum += ord(string[i]); return sum; # Driver codeif __name__ == "__main__" : string = "geeksforgeeks"; n = len(string); print(sumAscii(string, n)); # This code is contributed by AnkitRai01
// C# implementation of the approachusing System; class GFG{ // Function that returns true // if n is prime static bool isPrime(int n) { if (n == 0 || n == 1) { return false; } for (int i = 2; i * i <= n; i++) { if (n % i == 0) { return false; } } return true; } // Function to return the sum // of the ascii values of the characters // which are present at prime positions static int sumAscii(string str, int n) { // To store the sum int sum = 0; // For every character for (int i = 0; i < n; i++) { // If current position is prime // then add the ASCII value of the // character at the current position if (isPrime(i + 1)) { sum += (int) (str[i]); } } return sum; } // Driver code public static void Main() { string str = "geeksforgeeks"; int n = str.Length; Console.WriteLine(sumAscii(str, n)); }} // This code contributed by anuj_67..
<script> // Javascript implementation of the approach // Function that returns true// if n is primefunction isPrime(n){ if (n == 0 || n == 1) return false; for (let i = 2; i * i <= n; i++) if (n % i == 0) return false; return true;} // Function to return the sum// of the ascii values of the characters// which are present at prime positionsfunction sumAscii(str, n){ // To store the sum let sum = 0; // For every character for (let i = 0; i < n; i++) { // If current position is prime // then add the ASCII value of the // character at the current position if (isPrime(i + 1)) sum += str.charCodeAt(i); } return sum;} // Driver code let str = "geeksforgeeks"; let n = str.length; document.write(sumAscii(str, n)); </script>
644
Rajput-Ji
vt_m
ankthon
souravmahato348
ASCII
Prime Number
Competitive Programming
Mathematical
Strings
Strings
Mathematical
Prime Number
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Bits manipulation (Important tactics)
Modulo 10^9+7 (1000000007)
Prefix Sum Array - Implementation and Applications in Competitive Programming
Formatted output in Java
Breadth First Traversal ( BFS ) on a 2D array
Program for Fibonacci numbers
Write a program to print all permutations of a given string
C++ Data Types
Set in C++ Standard Template Library (STL)
Coin Change | DP-7 | [
{
"code": null,
"e": 25472,
"s": 25444,
"text": "\n10 May, 2021"
},
{
"code": null,
"e": 25615,
"s": 25472,
"text": "Given string str of size N, the task is to find the sum of all ASCII values of the characters which are present at prime positions.Examples: "
},
{
"code": null,
"e": 25829,
"s": 25615,
"text": "Input: str = “abcdef” Output: 298 ‘b’, ‘c’ and ‘e’ are the only characters which are at prime positions i.e. 2, 3 and 5 respectively. And sum of their ASCII values is 298.Input: str = “geeksforgeeks” Output: 644 "
},
{
"code": null,
"e": 26115,
"s": 25831,
"text": "Approach: An efficient approach is to traverse through the whole string and find if the particular position is prime or not. If the position of the current character is prime then add the ASCII value of the character to the answer.Below is the implementation of the above approach: "
},
{
"code": null,
"e": 26119,
"s": 26115,
"text": "C++"
},
{
"code": null,
"e": 26124,
"s": 26119,
"text": "Java"
},
{
"code": null,
"e": 26132,
"s": 26124,
"text": "Python3"
},
{
"code": null,
"e": 26135,
"s": 26132,
"text": "C#"
},
{
"code": null,
"e": 26146,
"s": 26135,
"text": "Javascript"
},
{
"code": "// C++ implementation of the approach#include <bits/stdc++.h>using namespace std; // Function that returns true// if n is primebool isPrime(int n){ if (n == 0 || n == 1) return false; for (int i = 2; i * i <= n; i++) if (n % i == 0) return false; return true;} // Function to return the sum// of the ascii values of the characters// which are present at prime positionsint sumAscii(string str, int n){ // To store the sum int sum = 0; // For every character for (int i = 0; i < n; i++) { // If current position is prime // then add the ASCII value of the // character at the current position if (isPrime(i + 1)) sum += (int)(str[i]); } return sum;} // Driver codeint main(){ string str = \"geeksforgeeks\"; int n = str.size(); cout << sumAscii(str, n); return 0;}",
"e": 27017,
"s": 26146,
"text": null
},
{
"code": "// Java implementation of the approachimport java.util.*; class GFG{ // Function that returns true // if n is prime static boolean isPrime(int n) { if (n == 0 || n == 1) { return false; } for (int i = 2; i * i <= n; i++) { if (n % i == 0) { return false; } } return true; } // Function to return the sum // of the ascii values of the characters // which are present at prime positions static int sumAscii(String str, int n) { // To store the sum int sum = 0; // For every character for (int i = 0; i < n; i++) { // If current position is prime // then add the ASCII value of the // character at the current position if (isPrime(i + 1)) { sum += (int) (str.charAt(i)); } } return sum; } // Driver code public static void main(String[] args) { String str = \"geeksforgeeks\"; int n = str.length(); System.out.println(sumAscii(str, n)); }} // This code contributed by Rajput-Ji",
"e": 28202,
"s": 27017,
"text": null
},
{
"code": "# Python3 implementation of the approach from math import sqrt # Function that returns true# if n is primedef isPrime(n) : if (n == 0 or n == 1) : return False; for i in range(2, int(sqrt(n)) + 1) : if (n % i == 0): return False; return True; # Function to return the sum# of the ascii values of the characters# which are present at prime positionsdef sumAscii(string, n) : # To store the sum sum = 0; # For every character for i in range(n) : # If current position is prime # then add the ASCII value of the # character at the current position if (isPrime(i + 1)) : sum += ord(string[i]); return sum; # Driver codeif __name__ == \"__main__\" : string = \"geeksforgeeks\"; n = len(string); print(sumAscii(string, n)); # This code is contributed by AnkitRai01",
"e": 29077,
"s": 28202,
"text": null
},
{
"code": "// C# implementation of the approachusing System; class GFG{ // Function that returns true // if n is prime static bool isPrime(int n) { if (n == 0 || n == 1) { return false; } for (int i = 2; i * i <= n; i++) { if (n % i == 0) { return false; } } return true; } // Function to return the sum // of the ascii values of the characters // which are present at prime positions static int sumAscii(string str, int n) { // To store the sum int sum = 0; // For every character for (int i = 0; i < n; i++) { // If current position is prime // then add the ASCII value of the // character at the current position if (isPrime(i + 1)) { sum += (int) (str[i]); } } return sum; } // Driver code public static void Main() { string str = \"geeksforgeeks\"; int n = str.Length; Console.WriteLine(sumAscii(str, n)); }} // This code contributed by anuj_67..",
"e": 30237,
"s": 29077,
"text": null
},
{
"code": "<script> // Javascript implementation of the approach // Function that returns true// if n is primefunction isPrime(n){ if (n == 0 || n == 1) return false; for (let i = 2; i * i <= n; i++) if (n % i == 0) return false; return true;} // Function to return the sum// of the ascii values of the characters// which are present at prime positionsfunction sumAscii(str, n){ // To store the sum let sum = 0; // For every character for (let i = 0; i < n; i++) { // If current position is prime // then add the ASCII value of the // character at the current position if (isPrime(i + 1)) sum += str.charCodeAt(i); } return sum;} // Driver code let str = \"geeksforgeeks\"; let n = str.length; document.write(sumAscii(str, n)); </script>",
"e": 31067,
"s": 30237,
"text": null
},
{
"code": null,
"e": 31071,
"s": 31067,
"text": "644"
},
{
"code": null,
"e": 31083,
"s": 31073,
"text": "Rajput-Ji"
},
{
"code": null,
"e": 31088,
"s": 31083,
"text": "vt_m"
},
{
"code": null,
"e": 31096,
"s": 31088,
"text": "ankthon"
},
{
"code": null,
"e": 31112,
"s": 31096,
"text": "souravmahato348"
},
{
"code": null,
"e": 31118,
"s": 31112,
"text": "ASCII"
},
{
"code": null,
"e": 31131,
"s": 31118,
"text": "Prime Number"
},
{
"code": null,
"e": 31155,
"s": 31131,
"text": "Competitive Programming"
},
{
"code": null,
"e": 31168,
"s": 31155,
"text": "Mathematical"
},
{
"code": null,
"e": 31176,
"s": 31168,
"text": "Strings"
},
{
"code": null,
"e": 31184,
"s": 31176,
"text": "Strings"
},
{
"code": null,
"e": 31197,
"s": 31184,
"text": "Mathematical"
},
{
"code": null,
"e": 31210,
"s": 31197,
"text": "Prime Number"
},
{
"code": null,
"e": 31308,
"s": 31210,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 31346,
"s": 31308,
"text": "Bits manipulation (Important tactics)"
},
{
"code": null,
"e": 31373,
"s": 31346,
"text": "Modulo 10^9+7 (1000000007)"
},
{
"code": null,
"e": 31451,
"s": 31373,
"text": "Prefix Sum Array - Implementation and Applications in Competitive Programming"
},
{
"code": null,
"e": 31476,
"s": 31451,
"text": "Formatted output in Java"
},
{
"code": null,
"e": 31522,
"s": 31476,
"text": "Breadth First Traversal ( BFS ) on a 2D array"
},
{
"code": null,
"e": 31552,
"s": 31522,
"text": "Program for Fibonacci numbers"
},
{
"code": null,
"e": 31612,
"s": 31552,
"text": "Write a program to print all permutations of a given string"
},
{
"code": null,
"e": 31627,
"s": 31612,
"text": "C++ Data Types"
},
{
"code": null,
"e": 31670,
"s": 31627,
"text": "Set in C++ Standard Template Library (STL)"
}
] |
Linear Regression from Scratch with NumPy — Implementation (Finally!) | by Levent Baş | Towards Data Science | Welcome to the second part of Linear Regression from Scratch with NumPy series! After explaining the intuition behind linear regression, now it is time to dive into the code for implementation of linear regression. If you want to catch up on linear regression intuition you can read the previous part of this series from here. Now, let’s get our hands dirty!
First things first, we start by importing necessary libraries to help us along the way. As I have mentioned before, we won’t be using any packages that will give us already implemented algorithm models such as sklearn.linear_model since it won't help us grasp what is the underlying principles of implementing an algorithm because it is an out-of-the-box (hence, ready-made) solution. We want to do it the hard way, not the easy way.
Moreover, do notice that we can use sklearn package (or other packages) to make use of its useful functions, such as loading a dataset, as long as we don't use its already implemented algorithm models.
We will be using:
numpy (obviously) to do all of the vectorized numerical computations on the dataset including the implementation of the algorithm,
matplotlib to plot graphs for better understanding the problem at hand with some visual aid,
sklearn.datasets to load a toy dataset to play around with our written code.
Total samples in our dataset is: 506
Now, it’s time to load the dataset we will be using throughout this post. The sklearn.datasets package offers some toy datasets to illustrate the behaviour of some algorithms and we will be using load_boston()function to return a regression dataset. Here, dataset.data represents the feature samples and dataset.target returns the target values, also called labels.
It is important to note that, when we are loading the target values, we are adding a new dimension to the data (dataset.target[:,np.newaxis]), so that we can use the data as a column vector. Remember, linear algebra makes a distinction between row vectors and column vectors.
However, in NumPy there are only n-dimensional arrays and no concept for row and column vectors, per se. We can use arrays of shape (n, 1) to imitate column vectors and (1, n) for row vectors. Ergo, we can use our target values of shape (n, ) as a column vector of shape (n, 1) by adding an axis explicitly. Luckily, we can do that with NumPy's own newaxis function which is used to increase the dimension of an array by one more dimension, when used once.
We have chosen the (1/2) x Mean Squared Error (MSE) as our cost function, so we’ll implement it here. h denotes our hypothesis function which is just a candidate function for our mapping from inputs (X) to outputs (y).
When we take the inner product of our features with the parameters (X @ params), we are explicitly stating that we will be using linear regression for our hypothesis from a broad list of other machine learning algorithms, that is, we have decided that the relation between feature and target values is best described by the linear regression.
We can now implement gradient descent algorithm. Here, n_iters denotes the number of iterations for the gradient descent. We want to keep the history of our costs returned by the cost function in each iteration so we use a NumPy array J_history for that.
As for the update rule, 1/n_samples) * X.T @ (X @ params - y) corresponds to the partial derivative of the cost function with respect to the parameters. So, params holds the updated parameter values according to the update rule.
Before we run the gradient descent algorithm on our dataset, we normalize the data. Normalization is a technique often applied as part of data preparation in machine learning pipeline which typically means rescaling the values into a range of [0,1] to boost our accuracy while lowering the cost (error). Also, note that we initialize the paramaters (params) to zeros.
Initial cost is: 296.0734584980237 Optimal parameters are: [[22.53279993] [-0.83980839] [ 0.92612237] [-0.17541988] [ 0.72676226] [-1.82369448] [ 2.78447498] [-0.05650494] [-2.96695543] [ 1.80785186] [-1.1802415 ] [-1.99990382] [ 0.85595908] [-3.69524414]] Final cost is: [11.00713381]
There you have it! We have run the algorithm successfully as we can clearly see that the cost decreased drastically from 296 to 11. The gradient_descent function returned the optimal parameter values, consequently, we can now use them to predict new target values.
Finally, after implementing linear regression from scratch we can rearrange the code we have written so far, add more code to it, make some modifications and turn it into a class implementation so that we have our very own linear regression module! There you go:
Do notice the similarities between our implementation and sklearn's own implementation of linear regression.
I have done it on purpose of course, to show you that we can write a simplified version of a widely used module that works in a similar way to sklearn's implementation.
I (mostly) did it for the fun, though!
We have done a pretty good job with that implementation, haven’t we? Our training accuracy is almost the same as the sklearn's accuracy. Also, test accuracy is not so bad comparing to the test accuracy of sklearn.
Undoubtedly, this has been fun. I encourage you to code this all by yourself after you finish reading the article.
You can also check out my GitHub profile to read the code along a jupyter notebook or simply use the code for implementation.
I’ll be back with more implementations and blog posts in the future. | [
{
"code": null,
"e": 530,
"s": 171,
"text": "Welcome to the second part of Linear Regression from Scratch with NumPy series! After explaining the intuition behind linear regression, now it is time to dive into the code for implementation of linear regression. If you want to catch up on linear regression intuition you can read the previous part of this series from here. Now, let’s get our hands dirty!"
},
{
"code": null,
"e": 964,
"s": 530,
"text": "First things first, we start by importing necessary libraries to help us along the way. As I have mentioned before, we won’t be using any packages that will give us already implemented algorithm models such as sklearn.linear_model since it won't help us grasp what is the underlying principles of implementing an algorithm because it is an out-of-the-box (hence, ready-made) solution. We want to do it the hard way, not the easy way."
},
{
"code": null,
"e": 1166,
"s": 964,
"text": "Moreover, do notice that we can use sklearn package (or other packages) to make use of its useful functions, such as loading a dataset, as long as we don't use its already implemented algorithm models."
},
{
"code": null,
"e": 1184,
"s": 1166,
"text": "We will be using:"
},
{
"code": null,
"e": 1315,
"s": 1184,
"text": "numpy (obviously) to do all of the vectorized numerical computations on the dataset including the implementation of the algorithm,"
},
{
"code": null,
"e": 1408,
"s": 1315,
"text": "matplotlib to plot graphs for better understanding the problem at hand with some visual aid,"
},
{
"code": null,
"e": 1485,
"s": 1408,
"text": "sklearn.datasets to load a toy dataset to play around with our written code."
},
{
"code": null,
"e": 1522,
"s": 1485,
"text": "Total samples in our dataset is: 506"
},
{
"code": null,
"e": 1888,
"s": 1522,
"text": "Now, it’s time to load the dataset we will be using throughout this post. The sklearn.datasets package offers some toy datasets to illustrate the behaviour of some algorithms and we will be using load_boston()function to return a regression dataset. Here, dataset.data represents the feature samples and dataset.target returns the target values, also called labels."
},
{
"code": null,
"e": 2164,
"s": 1888,
"text": "It is important to note that, when we are loading the target values, we are adding a new dimension to the data (dataset.target[:,np.newaxis]), so that we can use the data as a column vector. Remember, linear algebra makes a distinction between row vectors and column vectors."
},
{
"code": null,
"e": 2621,
"s": 2164,
"text": "However, in NumPy there are only n-dimensional arrays and no concept for row and column vectors, per se. We can use arrays of shape (n, 1) to imitate column vectors and (1, n) for row vectors. Ergo, we can use our target values of shape (n, ) as a column vector of shape (n, 1) by adding an axis explicitly. Luckily, we can do that with NumPy's own newaxis function which is used to increase the dimension of an array by one more dimension, when used once."
},
{
"code": null,
"e": 2840,
"s": 2621,
"text": "We have chosen the (1/2) x Mean Squared Error (MSE) as our cost function, so we’ll implement it here. h denotes our hypothesis function which is just a candidate function for our mapping from inputs (X) to outputs (y)."
},
{
"code": null,
"e": 3183,
"s": 2840,
"text": "When we take the inner product of our features with the parameters (X @ params), we are explicitly stating that we will be using linear regression for our hypothesis from a broad list of other machine learning algorithms, that is, we have decided that the relation between feature and target values is best described by the linear regression."
},
{
"code": null,
"e": 3438,
"s": 3183,
"text": "We can now implement gradient descent algorithm. Here, n_iters denotes the number of iterations for the gradient descent. We want to keep the history of our costs returned by the cost function in each iteration so we use a NumPy array J_history for that."
},
{
"code": null,
"e": 3667,
"s": 3438,
"text": "As for the update rule, 1/n_samples) * X.T @ (X @ params - y) corresponds to the partial derivative of the cost function with respect to the parameters. So, params holds the updated parameter values according to the update rule."
},
{
"code": null,
"e": 4035,
"s": 3667,
"text": "Before we run the gradient descent algorithm on our dataset, we normalize the data. Normalization is a technique often applied as part of data preparation in machine learning pipeline which typically means rescaling the values into a range of [0,1] to boost our accuracy while lowering the cost (error). Also, note that we initialize the paramaters (params) to zeros."
},
{
"code": null,
"e": 4324,
"s": 4035,
"text": "Initial cost is: 296.0734584980237 Optimal parameters are: [[22.53279993] [-0.83980839] [ 0.92612237] [-0.17541988] [ 0.72676226] [-1.82369448] [ 2.78447498] [-0.05650494] [-2.96695543] [ 1.80785186] [-1.1802415 ] [-1.99990382] [ 0.85595908] [-3.69524414]] Final cost is: [11.00713381]"
},
{
"code": null,
"e": 4589,
"s": 4324,
"text": "There you have it! We have run the algorithm successfully as we can clearly see that the cost decreased drastically from 296 to 11. The gradient_descent function returned the optimal parameter values, consequently, we can now use them to predict new target values."
},
{
"code": null,
"e": 4852,
"s": 4589,
"text": "Finally, after implementing linear regression from scratch we can rearrange the code we have written so far, add more code to it, make some modifications and turn it into a class implementation so that we have our very own linear regression module! There you go:"
},
{
"code": null,
"e": 4961,
"s": 4852,
"text": "Do notice the similarities between our implementation and sklearn's own implementation of linear regression."
},
{
"code": null,
"e": 5130,
"s": 4961,
"text": "I have done it on purpose of course, to show you that we can write a simplified version of a widely used module that works in a similar way to sklearn's implementation."
},
{
"code": null,
"e": 5169,
"s": 5130,
"text": "I (mostly) did it for the fun, though!"
},
{
"code": null,
"e": 5383,
"s": 5169,
"text": "We have done a pretty good job with that implementation, haven’t we? Our training accuracy is almost the same as the sklearn's accuracy. Also, test accuracy is not so bad comparing to the test accuracy of sklearn."
},
{
"code": null,
"e": 5498,
"s": 5383,
"text": "Undoubtedly, this has been fun. I encourage you to code this all by yourself after you finish reading the article."
},
{
"code": null,
"e": 5624,
"s": 5498,
"text": "You can also check out my GitHub profile to read the code along a jupyter notebook or simply use the code for implementation."
}
] |
Comprehensive Guide to Multiclass Classification With Sklearn | Towards Data Science | Learn how to tackle any multiclass classification problem with Sklearn. The tutorial covers how to choose a model selection strategy, several multiclass evaluation metrics and how to use them finishing off with hyperparameter tuning to optimize for user-defined metrics.
Even though multi-class classification is not as common, it certainly poses a much bigger challenge than binary classification problems. You can literally take my word for it because this article has been the most challenging post I have ever written (have written close to 70).
I found that the topic of multiclass classification is deep and full of nuances. I have read so many articles, read multiple StackOverflow threads, created a few of my own, and spent several hours exploring the Sklearn user guide and doing experiments. The core topics of multiclass classification such as
choosing a strategy to binarize the problem
choosing a base mode
understanding excruciatingly many metrics
filtering out a single metric that solves your business problem and customizing it
tuning hyperparameters for this custom metric
and finally putting all the theory into practice with Sklearn
have all been scattered in the dark, sordid corners of the Internet. This was enough to conclude that no single resource shows an end-to-end workflow of dealing with multiclass classification problems on the Internet (maybe, I missed it).
For this reason, this article will be a comprehensive tutorial on how to solve any multiclass supervised classification problem using Sklearn. You will learn both the theory and the implementation of the above core concepts. It is going to be a long and technical read, so get a coffee!
Depending on the model you choose, Sklearn approaches multiclass classification problems in 3 different ways. In other words, Sklearn estimators are grouped into 3 categories by their strategy to deal with multi-class data.
The first and the biggest group of estimators are the ones that support multi-class classification natively:
naive_bayes.BernoulliNB
tree.DecisionTreeClassifier
tree.ExtraTreeClassifier
ensemble.ExtraTreesClassifier
naive_bayes.GaussianNB
neighbors.KNeighborsClassifier
svm.LinearSVC (setting multi_class=”crammer_singer”)`
linear_model.LogisticRegression (setting multi_class=”multinomial”)
linear_model.LogisticRegressionCV (setting multi_class=”multinomial”)
For an N-class problem, they produce N by N confusion matrix, and most of the evaluation metrics are derived from it:
We will focus on multiclass confusion matrices later in the tutorial.
Other supervised classification algorithms were mainly designed for the binary case. However, Sklearn implements two strategies called One-vs-One (OVO) and One-vs-Rest (OVR, also called One-vs-All) to convert a multi-class problem into a series of binary tasks.
OVO splits a multi-class problem into a single binary classification task for each pair of classes. In other words, for each pair, a single binary classifier will be built. For example, a target with 4 classes — brain, lung, breast, and kidney cancer, uses 6 individual classifiers to binarize the problem:
Classifier 1: lung vs. breast
Classifier 2: lung vs. kidney
Classifier 3: lung vs. brain
Classifier 4: breast vs. kidney
Classifier 5: breast vs. brain
Classifier 6: kidney vs. brain
Sklearn suggests these classifiers to work best with the OVO approach:
svm.NuSVC
svm.SVC
gaussian_process.GaussianProcessClassifier (setting multi_class = “one_vs_one”)
Sklearn also provides a wrapper estimator for the above models under sklearn.multiclass.OneVsOneClassifier:
A major downside of this strategy is its computation workload. As each pair of classes require a separate binary classifier, targets with high cardinality may take too long to train. To compute the number of classifiers that will be built for an N-class problem, the following formula is used:
In practice, the One-vs-Rest strategy is much preferred because of this disadvantage.
Alternatively, the OVR strategy creates an individual classifier for each class in the target. Essentially, each binary classifier chooses a single class and marks it as positive, encoding it as 1. The rest of the classes are considered negative labels and, thus, encoded with 0. For classifying 4 types of cancer:
Classifier 1: lung vs. [breast, kidney, brain] — (lung cancer, not lung cancer)
Classifier 2: breast vs. [lung, kidney, brain] — (breast cancer, not breast cancer)
Classifier 3: kidney vs. [lung, breast, brain] — (kidney cancer, not kidney cancer)
Classifier 4: brain vs. [lung, breast kidney] — (brain cancer, not brain cancer)
Sklearn suggests these classifiers to work best with the OVR approach:
ensemble.GradientBoostingClassifier
gaussian_process.GaussianProcessClassifier (setting multi_class = “one_vs_rest”)
svm.LinearSVC (setting multi_class=”ovr”)
linear_model.LogisticRegression (setting multi_class=”ovr”)
linear_model.LogisticRegressionCV (setting multi_class=”ovr”)
linear_model.SGDClassifier
linear_model.Perceptron
Alternatively, you can use the above models with the default OneVsRestClassifier:
Even though this strategy significantly lowers the computational cost, the fact that only one class is considered positive and the rest as negative makes each binary problem an imbalanced classification. This problem is even more pronounced for classes with low proportions in the target.
In both approaches, depending on the passed estimator, the results of all binary classifiers can be summarized in two ways:
majority of the vote: each binary classifier predicts one class, and the class that got the most votes from all classifiers is chosen
depending on the argmax of class membership probability scores: classifiers such as LogisticRegression computes probability scores for each class (.predict_proba()). Then, the argmax of the sum of the scores is chosen.
We will talk more about how to score each of these strategies later in the tutorial.
As an example problem, we will be predicting the quality of diamonds using the Diamonds dataset from Kaggle:
The above output shows the features are on different scales, suggesting we use some type of normalization. This step is essential for many linear-based models to perform well.
The dataset contains a mixture of numeric and categorical features. I covered preprocessing steps for binary classification in my last article in detail. You can easily apply the ideas to the multi-class case, so I will keep the explanations here nice and short.
The target is ‘cut’, which has 5 classes: Ideal, Premium, Very Good, Good, and Fair (descending quality). We will encode the textual features with OneHotEncoder.
Let’s take a quick look at the distributions of each numeric feature to decide what type of normalization to use:
>>> diamonds.hist(figsize=(16, 12));
Price and carat show skewed distributions. We will use a logarithmic transformer to make them as normally distributed as possible. For the rest, simple standardization is enough. If you are not familiar with numeric transformations, check out my article on the topic. Also, the below code contains an example of Sklearn pipelines, and you can learn all about them from here.
Let’s get to work:
The first version of our pipeline uses RandomForestClassifier. Let's look at its confusion matrix by generating predictions:
In lines 8 and 9, we are creating the matrix and using a special Sklearn function to plot it. ConfusionMatrixDisplay also has display_labels argument, to which we are passing the class names accessed by pipeline.classes_ attribute.
If you read my other article on binary classification, you know that confusion matrices are the holy grail of supervised classification problems. In a 2 by 2 matrix, the matrix terms are easy to interpret and locate.
Even though it gets more difficult to interpret the matrix as the number of classes increases, there are sure-fire ways to find your way around any matrix of any shape.
The first step is always identifying your positive and negative classes. This depends on the problem you are trying to solve. As a jewelry store owner, I may want my classifier to differentiate Ideal and Premium diamonds better than other types, making these types of diamonds my positive class. Other classes will be considered negative.
Establishing positive and negative classes early on is very important in evaluating model performance and in hyperparameter tuning. After doing this, you should define your true positives, true negatives, false positives, and false negatives. In our case:
Positive classes: Ideal and Premium diamonds
Negative classes: Very Good, Good, and Fair diamonds
True Positives, type 1: actual Ideal, predicted Ideal
True Positives, type 2: actual Premium, predicted Premium
True Negatives: the rest of the diamond types predicted correctly
False Positives: actual value belongs to any of the 3 negative classes but predicted either Ideal or Premium
False Negatives: actual value is either Ideal or Premium but predicted by any of the 3 negative classes.
Always list out the terms of your matrix in this manner, and the rest of your workflow will be much easier, as you will see in the next section.
This section is only about the nitty-gritty details of how Sklearn calculates common metrics for multiclass classification. Specifically, we will peek under the hood of the 4 most common metrics: ROC_AUC, precision, recall, and f1 score. Even though I will give a brief overview of each metric, I will mostly focus on using them in practice. If you want a deeper explanation of what each metric measures, please refer to this article.
The first metric we will discuss is the ROC AUC score or area under the receiver operating characteristic curve. It is mostly used when we want to measure a classifier’s performance to differentiate between each class. This means that ROC AUC is better suited for balanced classification tasks.
In essence, the ROC AUC score is used for binary classification and with models that can generate class membership probabilities based on some threshold. Here is a brief overview of the steps to calculate ROC AUC for binary classification:
A binary classifier that can generate class membership probabilities such as LogisticRegression with its predict_proba method.An initial, close to 0 decision threshold is chosen. For example, if the probability is higher than 0.1, the class is predicted negative else positive.Using this threshold, a confusion matrix is created.True positive rate (TPR) and false positive rate (FPR) are found.A new threshold is chosen, and steps 3–4 are repeated.Repeat steps 2–5 for various thresholds between 0 and 1 to create a set of TPRs and FPRs.Plot all TPRs vs. FPRs to generate the receiver operating characteristic curve.Calculate the area under this curve.
A binary classifier that can generate class membership probabilities such as LogisticRegression with its predict_proba method.
An initial, close to 0 decision threshold is chosen. For example, if the probability is higher than 0.1, the class is predicted negative else positive.
Using this threshold, a confusion matrix is created.
True positive rate (TPR) and false positive rate (FPR) are found.
A new threshold is chosen, and steps 3–4 are repeated.
Repeat steps 2–5 for various thresholds between 0 and 1 to create a set of TPRs and FPRs.
Plot all TPRs vs. FPRs to generate the receiver operating characteristic curve.
Calculate the area under this curve.
For multiclass classification, you can calculate the ROC AUC for all classes using either OVO or OVR strategies. Since we agreed that OVR is a better option, here is how ROC AUC is calculated for OVR classification:
Each binary classifier created using OVR finds the ROC AUC score for its own class using the above steps.ROC AUC scores of all classifiers are then averaged using either of these 2 methods:
Each binary classifier created using OVR finds the ROC AUC score for its own class using the above steps.
ROC AUC scores of all classifiers are then averaged using either of these 2 methods:
“macro”: this is simply the arithmetic mean of the scores
“weighted”: this takes class imbalance into account by finding a weighted average. Each ROC AUC is multiplied by their class weight and summed, then divided by the total number of samples.
As an example, let’s say there are 100 samples in the target — class 1 (45), class 2 (30), class 3 (25). OVR creates 3 binary classifiers, 1 for each class, and their ROC AUC scores are 0.75, 0.68, 0.84, respectively. The weighted ROC AUC score across all classes will be:
ROC AUC (weighted): ((45 * 0.75) + (30 * 0.68) + (25 * 0.84)) / 100 = 0.7515
Here is the implementation of all this in Sklearn:
Above, we calculated ROC AUC for our diamond classification problem and got an excellent score. Don’t forget to set the multi_class and average parameters properly when using roc_auc_score. If you want to generate the score for a particular class, here is how you do it:
ROC AUC score is only a good metric to see how the classifier differentiates between classes. A higher ROC AUC score does not necessarily mean a better model. On top of that, we care more about our model’s ability to classify Ideal and Premium diamonds, so a metric like ROC AUC is not a good option for our case.
A better metric to measure our pipeline’s performance would be using precision, recall, and F1 scores. For the binary case, they are easy and intuitive to understand:
In a multiclass case, these 3 metrics are calculated per-class basis. For example, let’s look at the confusion matrix again:
Precision tells us what proportion of predicted positives is truly positive. If we want to calculate precision for Ideal diamonds, true positives would be the number of Ideal diamonds predicted correctly (the center of the matrix, 6626). False positives would be any cells that count the number of times our classifier predicted other types of diamonds as Ideal. These would be the cells above and below the center of the matrix (1013 + 521 + 31 + 8 = 1573). Using the formula of precision, we calculate it to be:
Precision (Ideal) = TP / (TP + FP) = 6626 / (6626 + 1573) = 0.808
Recall is calculated similarly. We know the number of true positives — 6626. False negatives would be any cells that count the number of times the classifier predicted the Ideal type of diamonds belonging to any other negative class. These would be the cells right and left to the center of the matrix (3 + 9 + 363 + 111 = 486). Using the formula of recall, we calculate it to be:
Recall (Ideal) = TP / (TP + FN) = 6626 / (6626 + 486) = 0.93
So, how do we choose between recall and precision for the Ideal class? It depends on the type of problem you are trying to solve. If you want to minimize the instances where other, cheaper types of diamonds are predicted as Ideal, you should optimize precision. As a jewelry store owner, you might be sued for fraud for selling cheaper diamonds as expensive Ideal diamonds.
On the other hand, if you want to minimize the instances where you accidentally sell Ideal diamonds for a lower price, you should optimize for recall of the Ideal class. Indeed, you won’t get sued, but you might lose money.
The third option is to have a model that is equally good at the above 2 scenarios. In other words, a model with high precision and recall. Fortunately, there is a metric that measures just that: the F1 score. F1 score takes the harmonic mean of precision and recall and produces a value between 0 and 1:
So, the F1 score for the Ideal class would be:
F1 (Ideal) = 2 * (0.808 * 0.93) / (0.808 + 0.93) = 0.87
Up to this point, we calculated the 3 metrics only for the Ideal class. But in multiclass classification, Sklearn computes them for all classes. You can use classification_report to see this:
You can check that our calculations for the Ideal class were correct. The last column of the table — support shows how many samples are there for each class. Also, the last 2 rows show averaged scores for the 3 metrics. We already covered what macro and weighted averages are in the example of ROC AUC.
For imbalanced classification tasks such as these, you rarely choose averaged precision, recall of F1 scores. Again, choosing one metric to optimize for a particular class depends on your business problem. For our case, we will choose to optimize the F1 score of Ideal and Premium classes (yes, you can choose multiple classes simultaneously). First, let’s see how to calculate weighted F1 across all class:
The above is consistent with the output of classification_report. To choose the F1 scores for Ideal and Premium classes, specify the labels parameter:
Finally, let’s see how to optimize these metrics with hyperparameter tuning.
Optimizing the model performance for a metric is almost the same as when we did for the binary case. The only difference is how we pass a scoring function to a hyperparameter tuner like GridSearch.
Up until now, we were using the RandomForestClassifier pipeline, so we will create a hyperparameter grid for this estimator:
Don’t forget to prepend each hyperparameter name with the step name you chose in the pipeline for your estimator. When we created our pipeline, we specified RandomForests as ‘base’. See this discussion for more info.
We will use the HalvingGridSeachCV (HGS), which was much faster than a regular GridSearch. You can read this article to see my experiments:
towardsdatascience.com
Before we feed the above grid to HGS, let’s create a custom scoring function. In the binary case, we could pass string values as the names of the metrics we wanted to use, such as ‘precision’ or ‘recall.’ But in multiclass case, those functions accept additional parameters, and we cannot do that if we pass the function names as strings. To solve this, Sklearn provides make_scorer function:
As we did in the last section, we pasted custom values for average and labels parameters.
Finally, let’s initialize the HGS and fit it to the full data with 3-fold cross-validation:
After the search is done, you can get the best score and estimator with .best_score_ and .best_estimator_ attributes, respectively.
Your model is only as good as the metric you choose to evaluate it with. Hyperparameter tuning will be time-consuming but assuming you did everything right until this point and gave a good enough parameter grid, everything will turn out as expected. If not, it is an iterative process, so take your time by tweaking the preprocessing steps, take a second look at your chosen metrics, and maybe widen your search grid. Thank you for reading!
Multi-Class Metrics Made Simple, Part I: Precision and Recall
Multi-Class Metrics Made Simple, Part II: the F1-score
How to Calculate Precision, Recall, and F-Measure for Imbalanced Classification
How to choose between ROC AUC and the F1 score?
What are the differences between AUC and F1-score?
Classification Metrics
Multiclass and multioutput algorithms | [
{
"code": null,
"e": 442,
"s": 171,
"text": "Learn how to tackle any multiclass classification problem with Sklearn. The tutorial covers how to choose a model selection strategy, several multiclass evaluation metrics and how to use them finishing off with hyperparameter tuning to optimize for user-defined metrics."
},
{
"code": null,
"e": 721,
"s": 442,
"text": "Even though multi-class classification is not as common, it certainly poses a much bigger challenge than binary classification problems. You can literally take my word for it because this article has been the most challenging post I have ever written (have written close to 70)."
},
{
"code": null,
"e": 1027,
"s": 721,
"text": "I found that the topic of multiclass classification is deep and full of nuances. I have read so many articles, read multiple StackOverflow threads, created a few of my own, and spent several hours exploring the Sklearn user guide and doing experiments. The core topics of multiclass classification such as"
},
{
"code": null,
"e": 1071,
"s": 1027,
"text": "choosing a strategy to binarize the problem"
},
{
"code": null,
"e": 1092,
"s": 1071,
"text": "choosing a base mode"
},
{
"code": null,
"e": 1134,
"s": 1092,
"text": "understanding excruciatingly many metrics"
},
{
"code": null,
"e": 1217,
"s": 1134,
"text": "filtering out a single metric that solves your business problem and customizing it"
},
{
"code": null,
"e": 1263,
"s": 1217,
"text": "tuning hyperparameters for this custom metric"
},
{
"code": null,
"e": 1325,
"s": 1263,
"text": "and finally putting all the theory into practice with Sklearn"
},
{
"code": null,
"e": 1564,
"s": 1325,
"text": "have all been scattered in the dark, sordid corners of the Internet. This was enough to conclude that no single resource shows an end-to-end workflow of dealing with multiclass classification problems on the Internet (maybe, I missed it)."
},
{
"code": null,
"e": 1851,
"s": 1564,
"text": "For this reason, this article will be a comprehensive tutorial on how to solve any multiclass supervised classification problem using Sklearn. You will learn both the theory and the implementation of the above core concepts. It is going to be a long and technical read, so get a coffee!"
},
{
"code": null,
"e": 2075,
"s": 1851,
"text": "Depending on the model you choose, Sklearn approaches multiclass classification problems in 3 different ways. In other words, Sklearn estimators are grouped into 3 categories by their strategy to deal with multi-class data."
},
{
"code": null,
"e": 2184,
"s": 2075,
"text": "The first and the biggest group of estimators are the ones that support multi-class classification natively:"
},
{
"code": null,
"e": 2208,
"s": 2184,
"text": "naive_bayes.BernoulliNB"
},
{
"code": null,
"e": 2236,
"s": 2208,
"text": "tree.DecisionTreeClassifier"
},
{
"code": null,
"e": 2261,
"s": 2236,
"text": "tree.ExtraTreeClassifier"
},
{
"code": null,
"e": 2291,
"s": 2261,
"text": "ensemble.ExtraTreesClassifier"
},
{
"code": null,
"e": 2314,
"s": 2291,
"text": "naive_bayes.GaussianNB"
},
{
"code": null,
"e": 2345,
"s": 2314,
"text": "neighbors.KNeighborsClassifier"
},
{
"code": null,
"e": 2399,
"s": 2345,
"text": "svm.LinearSVC (setting multi_class=”crammer_singer”)`"
},
{
"code": null,
"e": 2467,
"s": 2399,
"text": "linear_model.LogisticRegression (setting multi_class=”multinomial”)"
},
{
"code": null,
"e": 2537,
"s": 2467,
"text": "linear_model.LogisticRegressionCV (setting multi_class=”multinomial”)"
},
{
"code": null,
"e": 2655,
"s": 2537,
"text": "For an N-class problem, they produce N by N confusion matrix, and most of the evaluation metrics are derived from it:"
},
{
"code": null,
"e": 2725,
"s": 2655,
"text": "We will focus on multiclass confusion matrices later in the tutorial."
},
{
"code": null,
"e": 2987,
"s": 2725,
"text": "Other supervised classification algorithms were mainly designed for the binary case. However, Sklearn implements two strategies called One-vs-One (OVO) and One-vs-Rest (OVR, also called One-vs-All) to convert a multi-class problem into a series of binary tasks."
},
{
"code": null,
"e": 3294,
"s": 2987,
"text": "OVO splits a multi-class problem into a single binary classification task for each pair of classes. In other words, for each pair, a single binary classifier will be built. For example, a target with 4 classes — brain, lung, breast, and kidney cancer, uses 6 individual classifiers to binarize the problem:"
},
{
"code": null,
"e": 3324,
"s": 3294,
"text": "Classifier 1: lung vs. breast"
},
{
"code": null,
"e": 3354,
"s": 3324,
"text": "Classifier 2: lung vs. kidney"
},
{
"code": null,
"e": 3383,
"s": 3354,
"text": "Classifier 3: lung vs. brain"
},
{
"code": null,
"e": 3415,
"s": 3383,
"text": "Classifier 4: breast vs. kidney"
},
{
"code": null,
"e": 3446,
"s": 3415,
"text": "Classifier 5: breast vs. brain"
},
{
"code": null,
"e": 3477,
"s": 3446,
"text": "Classifier 6: kidney vs. brain"
},
{
"code": null,
"e": 3548,
"s": 3477,
"text": "Sklearn suggests these classifiers to work best with the OVO approach:"
},
{
"code": null,
"e": 3558,
"s": 3548,
"text": "svm.NuSVC"
},
{
"code": null,
"e": 3566,
"s": 3558,
"text": "svm.SVC"
},
{
"code": null,
"e": 3646,
"s": 3566,
"text": "gaussian_process.GaussianProcessClassifier (setting multi_class = “one_vs_one”)"
},
{
"code": null,
"e": 3754,
"s": 3646,
"text": "Sklearn also provides a wrapper estimator for the above models under sklearn.multiclass.OneVsOneClassifier:"
},
{
"code": null,
"e": 4048,
"s": 3754,
"text": "A major downside of this strategy is its computation workload. As each pair of classes require a separate binary classifier, targets with high cardinality may take too long to train. To compute the number of classifiers that will be built for an N-class problem, the following formula is used:"
},
{
"code": null,
"e": 4134,
"s": 4048,
"text": "In practice, the One-vs-Rest strategy is much preferred because of this disadvantage."
},
{
"code": null,
"e": 4449,
"s": 4134,
"text": "Alternatively, the OVR strategy creates an individual classifier for each class in the target. Essentially, each binary classifier chooses a single class and marks it as positive, encoding it as 1. The rest of the classes are considered negative labels and, thus, encoded with 0. For classifying 4 types of cancer:"
},
{
"code": null,
"e": 4529,
"s": 4449,
"text": "Classifier 1: lung vs. [breast, kidney, brain] — (lung cancer, not lung cancer)"
},
{
"code": null,
"e": 4613,
"s": 4529,
"text": "Classifier 2: breast vs. [lung, kidney, brain] — (breast cancer, not breast cancer)"
},
{
"code": null,
"e": 4697,
"s": 4613,
"text": "Classifier 3: kidney vs. [lung, breast, brain] — (kidney cancer, not kidney cancer)"
},
{
"code": null,
"e": 4778,
"s": 4697,
"text": "Classifier 4: brain vs. [lung, breast kidney] — (brain cancer, not brain cancer)"
},
{
"code": null,
"e": 4849,
"s": 4778,
"text": "Sklearn suggests these classifiers to work best with the OVR approach:"
},
{
"code": null,
"e": 4885,
"s": 4849,
"text": "ensemble.GradientBoostingClassifier"
},
{
"code": null,
"e": 4966,
"s": 4885,
"text": "gaussian_process.GaussianProcessClassifier (setting multi_class = “one_vs_rest”)"
},
{
"code": null,
"e": 5008,
"s": 4966,
"text": "svm.LinearSVC (setting multi_class=”ovr”)"
},
{
"code": null,
"e": 5068,
"s": 5008,
"text": "linear_model.LogisticRegression (setting multi_class=”ovr”)"
},
{
"code": null,
"e": 5130,
"s": 5068,
"text": "linear_model.LogisticRegressionCV (setting multi_class=”ovr”)"
},
{
"code": null,
"e": 5157,
"s": 5130,
"text": "linear_model.SGDClassifier"
},
{
"code": null,
"e": 5181,
"s": 5157,
"text": "linear_model.Perceptron"
},
{
"code": null,
"e": 5263,
"s": 5181,
"text": "Alternatively, you can use the above models with the default OneVsRestClassifier:"
},
{
"code": null,
"e": 5552,
"s": 5263,
"text": "Even though this strategy significantly lowers the computational cost, the fact that only one class is considered positive and the rest as negative makes each binary problem an imbalanced classification. This problem is even more pronounced for classes with low proportions in the target."
},
{
"code": null,
"e": 5676,
"s": 5552,
"text": "In both approaches, depending on the passed estimator, the results of all binary classifiers can be summarized in two ways:"
},
{
"code": null,
"e": 5810,
"s": 5676,
"text": "majority of the vote: each binary classifier predicts one class, and the class that got the most votes from all classifiers is chosen"
},
{
"code": null,
"e": 6029,
"s": 5810,
"text": "depending on the argmax of class membership probability scores: classifiers such as LogisticRegression computes probability scores for each class (.predict_proba()). Then, the argmax of the sum of the scores is chosen."
},
{
"code": null,
"e": 6114,
"s": 6029,
"text": "We will talk more about how to score each of these strategies later in the tutorial."
},
{
"code": null,
"e": 6223,
"s": 6114,
"text": "As an example problem, we will be predicting the quality of diamonds using the Diamonds dataset from Kaggle:"
},
{
"code": null,
"e": 6399,
"s": 6223,
"text": "The above output shows the features are on different scales, suggesting we use some type of normalization. This step is essential for many linear-based models to perform well."
},
{
"code": null,
"e": 6662,
"s": 6399,
"text": "The dataset contains a mixture of numeric and categorical features. I covered preprocessing steps for binary classification in my last article in detail. You can easily apply the ideas to the multi-class case, so I will keep the explanations here nice and short."
},
{
"code": null,
"e": 6824,
"s": 6662,
"text": "The target is ‘cut’, which has 5 classes: Ideal, Premium, Very Good, Good, and Fair (descending quality). We will encode the textual features with OneHotEncoder."
},
{
"code": null,
"e": 6938,
"s": 6824,
"text": "Let’s take a quick look at the distributions of each numeric feature to decide what type of normalization to use:"
},
{
"code": null,
"e": 6975,
"s": 6938,
"text": ">>> diamonds.hist(figsize=(16, 12));"
},
{
"code": null,
"e": 7350,
"s": 6975,
"text": "Price and carat show skewed distributions. We will use a logarithmic transformer to make them as normally distributed as possible. For the rest, simple standardization is enough. If you are not familiar with numeric transformations, check out my article on the topic. Also, the below code contains an example of Sklearn pipelines, and you can learn all about them from here."
},
{
"code": null,
"e": 7369,
"s": 7350,
"text": "Let’s get to work:"
},
{
"code": null,
"e": 7494,
"s": 7369,
"text": "The first version of our pipeline uses RandomForestClassifier. Let's look at its confusion matrix by generating predictions:"
},
{
"code": null,
"e": 7726,
"s": 7494,
"text": "In lines 8 and 9, we are creating the matrix and using a special Sklearn function to plot it. ConfusionMatrixDisplay also has display_labels argument, to which we are passing the class names accessed by pipeline.classes_ attribute."
},
{
"code": null,
"e": 7943,
"s": 7726,
"text": "If you read my other article on binary classification, you know that confusion matrices are the holy grail of supervised classification problems. In a 2 by 2 matrix, the matrix terms are easy to interpret and locate."
},
{
"code": null,
"e": 8112,
"s": 7943,
"text": "Even though it gets more difficult to interpret the matrix as the number of classes increases, there are sure-fire ways to find your way around any matrix of any shape."
},
{
"code": null,
"e": 8451,
"s": 8112,
"text": "The first step is always identifying your positive and negative classes. This depends on the problem you are trying to solve. As a jewelry store owner, I may want my classifier to differentiate Ideal and Premium diamonds better than other types, making these types of diamonds my positive class. Other classes will be considered negative."
},
{
"code": null,
"e": 8707,
"s": 8451,
"text": "Establishing positive and negative classes early on is very important in evaluating model performance and in hyperparameter tuning. After doing this, you should define your true positives, true negatives, false positives, and false negatives. In our case:"
},
{
"code": null,
"e": 8752,
"s": 8707,
"text": "Positive classes: Ideal and Premium diamonds"
},
{
"code": null,
"e": 8805,
"s": 8752,
"text": "Negative classes: Very Good, Good, and Fair diamonds"
},
{
"code": null,
"e": 8859,
"s": 8805,
"text": "True Positives, type 1: actual Ideal, predicted Ideal"
},
{
"code": null,
"e": 8917,
"s": 8859,
"text": "True Positives, type 2: actual Premium, predicted Premium"
},
{
"code": null,
"e": 8983,
"s": 8917,
"text": "True Negatives: the rest of the diamond types predicted correctly"
},
{
"code": null,
"e": 9092,
"s": 8983,
"text": "False Positives: actual value belongs to any of the 3 negative classes but predicted either Ideal or Premium"
},
{
"code": null,
"e": 9197,
"s": 9092,
"text": "False Negatives: actual value is either Ideal or Premium but predicted by any of the 3 negative classes."
},
{
"code": null,
"e": 9342,
"s": 9197,
"text": "Always list out the terms of your matrix in this manner, and the rest of your workflow will be much easier, as you will see in the next section."
},
{
"code": null,
"e": 9777,
"s": 9342,
"text": "This section is only about the nitty-gritty details of how Sklearn calculates common metrics for multiclass classification. Specifically, we will peek under the hood of the 4 most common metrics: ROC_AUC, precision, recall, and f1 score. Even though I will give a brief overview of each metric, I will mostly focus on using them in practice. If you want a deeper explanation of what each metric measures, please refer to this article."
},
{
"code": null,
"e": 10072,
"s": 9777,
"text": "The first metric we will discuss is the ROC AUC score or area under the receiver operating characteristic curve. It is mostly used when we want to measure a classifier’s performance to differentiate between each class. This means that ROC AUC is better suited for balanced classification tasks."
},
{
"code": null,
"e": 10312,
"s": 10072,
"text": "In essence, the ROC AUC score is used for binary classification and with models that can generate class membership probabilities based on some threshold. Here is a brief overview of the steps to calculate ROC AUC for binary classification:"
},
{
"code": null,
"e": 10965,
"s": 10312,
"text": "A binary classifier that can generate class membership probabilities such as LogisticRegression with its predict_proba method.An initial, close to 0 decision threshold is chosen. For example, if the probability is higher than 0.1, the class is predicted negative else positive.Using this threshold, a confusion matrix is created.True positive rate (TPR) and false positive rate (FPR) are found.A new threshold is chosen, and steps 3–4 are repeated.Repeat steps 2–5 for various thresholds between 0 and 1 to create a set of TPRs and FPRs.Plot all TPRs vs. FPRs to generate the receiver operating characteristic curve.Calculate the area under this curve."
},
{
"code": null,
"e": 11092,
"s": 10965,
"text": "A binary classifier that can generate class membership probabilities such as LogisticRegression with its predict_proba method."
},
{
"code": null,
"e": 11244,
"s": 11092,
"text": "An initial, close to 0 decision threshold is chosen. For example, if the probability is higher than 0.1, the class is predicted negative else positive."
},
{
"code": null,
"e": 11297,
"s": 11244,
"text": "Using this threshold, a confusion matrix is created."
},
{
"code": null,
"e": 11363,
"s": 11297,
"text": "True positive rate (TPR) and false positive rate (FPR) are found."
},
{
"code": null,
"e": 11418,
"s": 11363,
"text": "A new threshold is chosen, and steps 3–4 are repeated."
},
{
"code": null,
"e": 11508,
"s": 11418,
"text": "Repeat steps 2–5 for various thresholds between 0 and 1 to create a set of TPRs and FPRs."
},
{
"code": null,
"e": 11588,
"s": 11508,
"text": "Plot all TPRs vs. FPRs to generate the receiver operating characteristic curve."
},
{
"code": null,
"e": 11625,
"s": 11588,
"text": "Calculate the area under this curve."
},
{
"code": null,
"e": 11841,
"s": 11625,
"text": "For multiclass classification, you can calculate the ROC AUC for all classes using either OVO or OVR strategies. Since we agreed that OVR is a better option, here is how ROC AUC is calculated for OVR classification:"
},
{
"code": null,
"e": 12031,
"s": 11841,
"text": "Each binary classifier created using OVR finds the ROC AUC score for its own class using the above steps.ROC AUC scores of all classifiers are then averaged using either of these 2 methods:"
},
{
"code": null,
"e": 12137,
"s": 12031,
"text": "Each binary classifier created using OVR finds the ROC AUC score for its own class using the above steps."
},
{
"code": null,
"e": 12222,
"s": 12137,
"text": "ROC AUC scores of all classifiers are then averaged using either of these 2 methods:"
},
{
"code": null,
"e": 12280,
"s": 12222,
"text": "“macro”: this is simply the arithmetic mean of the scores"
},
{
"code": null,
"e": 12469,
"s": 12280,
"text": "“weighted”: this takes class imbalance into account by finding a weighted average. Each ROC AUC is multiplied by their class weight and summed, then divided by the total number of samples."
},
{
"code": null,
"e": 12742,
"s": 12469,
"text": "As an example, let’s say there are 100 samples in the target — class 1 (45), class 2 (30), class 3 (25). OVR creates 3 binary classifiers, 1 for each class, and their ROC AUC scores are 0.75, 0.68, 0.84, respectively. The weighted ROC AUC score across all classes will be:"
},
{
"code": null,
"e": 12819,
"s": 12742,
"text": "ROC AUC (weighted): ((45 * 0.75) + (30 * 0.68) + (25 * 0.84)) / 100 = 0.7515"
},
{
"code": null,
"e": 12870,
"s": 12819,
"text": "Here is the implementation of all this in Sklearn:"
},
{
"code": null,
"e": 13141,
"s": 12870,
"text": "Above, we calculated ROC AUC for our diamond classification problem and got an excellent score. Don’t forget to set the multi_class and average parameters properly when using roc_auc_score. If you want to generate the score for a particular class, here is how you do it:"
},
{
"code": null,
"e": 13455,
"s": 13141,
"text": "ROC AUC score is only a good metric to see how the classifier differentiates between classes. A higher ROC AUC score does not necessarily mean a better model. On top of that, we care more about our model’s ability to classify Ideal and Premium diamonds, so a metric like ROC AUC is not a good option for our case."
},
{
"code": null,
"e": 13622,
"s": 13455,
"text": "A better metric to measure our pipeline’s performance would be using precision, recall, and F1 scores. For the binary case, they are easy and intuitive to understand:"
},
{
"code": null,
"e": 13747,
"s": 13622,
"text": "In a multiclass case, these 3 metrics are calculated per-class basis. For example, let’s look at the confusion matrix again:"
},
{
"code": null,
"e": 14261,
"s": 13747,
"text": "Precision tells us what proportion of predicted positives is truly positive. If we want to calculate precision for Ideal diamonds, true positives would be the number of Ideal diamonds predicted correctly (the center of the matrix, 6626). False positives would be any cells that count the number of times our classifier predicted other types of diamonds as Ideal. These would be the cells above and below the center of the matrix (1013 + 521 + 31 + 8 = 1573). Using the formula of precision, we calculate it to be:"
},
{
"code": null,
"e": 14327,
"s": 14261,
"text": "Precision (Ideal) = TP / (TP + FP) = 6626 / (6626 + 1573) = 0.808"
},
{
"code": null,
"e": 14708,
"s": 14327,
"text": "Recall is calculated similarly. We know the number of true positives — 6626. False negatives would be any cells that count the number of times the classifier predicted the Ideal type of diamonds belonging to any other negative class. These would be the cells right and left to the center of the matrix (3 + 9 + 363 + 111 = 486). Using the formula of recall, we calculate it to be:"
},
{
"code": null,
"e": 14769,
"s": 14708,
"text": "Recall (Ideal) = TP / (TP + FN) = 6626 / (6626 + 486) = 0.93"
},
{
"code": null,
"e": 15143,
"s": 14769,
"text": "So, how do we choose between recall and precision for the Ideal class? It depends on the type of problem you are trying to solve. If you want to minimize the instances where other, cheaper types of diamonds are predicted as Ideal, you should optimize precision. As a jewelry store owner, you might be sued for fraud for selling cheaper diamonds as expensive Ideal diamonds."
},
{
"code": null,
"e": 15367,
"s": 15143,
"text": "On the other hand, if you want to minimize the instances where you accidentally sell Ideal diamonds for a lower price, you should optimize for recall of the Ideal class. Indeed, you won’t get sued, but you might lose money."
},
{
"code": null,
"e": 15671,
"s": 15367,
"text": "The third option is to have a model that is equally good at the above 2 scenarios. In other words, a model with high precision and recall. Fortunately, there is a metric that measures just that: the F1 score. F1 score takes the harmonic mean of precision and recall and produces a value between 0 and 1:"
},
{
"code": null,
"e": 15718,
"s": 15671,
"text": "So, the F1 score for the Ideal class would be:"
},
{
"code": null,
"e": 15774,
"s": 15718,
"text": "F1 (Ideal) = 2 * (0.808 * 0.93) / (0.808 + 0.93) = 0.87"
},
{
"code": null,
"e": 15966,
"s": 15774,
"text": "Up to this point, we calculated the 3 metrics only for the Ideal class. But in multiclass classification, Sklearn computes them for all classes. You can use classification_report to see this:"
},
{
"code": null,
"e": 16269,
"s": 15966,
"text": "You can check that our calculations for the Ideal class were correct. The last column of the table — support shows how many samples are there for each class. Also, the last 2 rows show averaged scores for the 3 metrics. We already covered what macro and weighted averages are in the example of ROC AUC."
},
{
"code": null,
"e": 16677,
"s": 16269,
"text": "For imbalanced classification tasks such as these, you rarely choose averaged precision, recall of F1 scores. Again, choosing one metric to optimize for a particular class depends on your business problem. For our case, we will choose to optimize the F1 score of Ideal and Premium classes (yes, you can choose multiple classes simultaneously). First, let’s see how to calculate weighted F1 across all class:"
},
{
"code": null,
"e": 16828,
"s": 16677,
"text": "The above is consistent with the output of classification_report. To choose the F1 scores for Ideal and Premium classes, specify the labels parameter:"
},
{
"code": null,
"e": 16905,
"s": 16828,
"text": "Finally, let’s see how to optimize these metrics with hyperparameter tuning."
},
{
"code": null,
"e": 17103,
"s": 16905,
"text": "Optimizing the model performance for a metric is almost the same as when we did for the binary case. The only difference is how we pass a scoring function to a hyperparameter tuner like GridSearch."
},
{
"code": null,
"e": 17228,
"s": 17103,
"text": "Up until now, we were using the RandomForestClassifier pipeline, so we will create a hyperparameter grid for this estimator:"
},
{
"code": null,
"e": 17445,
"s": 17228,
"text": "Don’t forget to prepend each hyperparameter name with the step name you chose in the pipeline for your estimator. When we created our pipeline, we specified RandomForests as ‘base’. See this discussion for more info."
},
{
"code": null,
"e": 17585,
"s": 17445,
"text": "We will use the HalvingGridSeachCV (HGS), which was much faster than a regular GridSearch. You can read this article to see my experiments:"
},
{
"code": null,
"e": 17608,
"s": 17585,
"text": "towardsdatascience.com"
},
{
"code": null,
"e": 18001,
"s": 17608,
"text": "Before we feed the above grid to HGS, let’s create a custom scoring function. In the binary case, we could pass string values as the names of the metrics we wanted to use, such as ‘precision’ or ‘recall.’ But in multiclass case, those functions accept additional parameters, and we cannot do that if we pass the function names as strings. To solve this, Sklearn provides make_scorer function:"
},
{
"code": null,
"e": 18091,
"s": 18001,
"text": "As we did in the last section, we pasted custom values for average and labels parameters."
},
{
"code": null,
"e": 18183,
"s": 18091,
"text": "Finally, let’s initialize the HGS and fit it to the full data with 3-fold cross-validation:"
},
{
"code": null,
"e": 18315,
"s": 18183,
"text": "After the search is done, you can get the best score and estimator with .best_score_ and .best_estimator_ attributes, respectively."
},
{
"code": null,
"e": 18756,
"s": 18315,
"text": "Your model is only as good as the metric you choose to evaluate it with. Hyperparameter tuning will be time-consuming but assuming you did everything right until this point and gave a good enough parameter grid, everything will turn out as expected. If not, it is an iterative process, so take your time by tweaking the preprocessing steps, take a second look at your chosen metrics, and maybe widen your search grid. Thank you for reading!"
},
{
"code": null,
"e": 18818,
"s": 18756,
"text": "Multi-Class Metrics Made Simple, Part I: Precision and Recall"
},
{
"code": null,
"e": 18873,
"s": 18818,
"text": "Multi-Class Metrics Made Simple, Part II: the F1-score"
},
{
"code": null,
"e": 18953,
"s": 18873,
"text": "How to Calculate Precision, Recall, and F-Measure for Imbalanced Classification"
},
{
"code": null,
"e": 19001,
"s": 18953,
"text": "How to choose between ROC AUC and the F1 score?"
},
{
"code": null,
"e": 19052,
"s": 19001,
"text": "What are the differences between AUC and F1-score?"
},
{
"code": null,
"e": 19075,
"s": 19052,
"text": "Classification Metrics"
}
] |
How to match a range of characters using Java regex | To match a range of characters i.e. to match all the characters between two specified characters in a sequence you can use the character class as
[a-z]
The expression “[a-zA-Z]” accepts any English alphabet.
The expression “[a-zA-Z]” accepts any English alphabet.
The expression “[0-9&&[^35]]” accepts numbers except 3 and 5.
The expression “[0-9&&[^35]]” accepts numbers except 3 and 5.
import java.util.Scanner;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class Example {
public static void main(String args[]) {
//Reading String from user
System.out.println("Enter a String");
Scanner sc = new Scanner(System.in);
String input = sc.nextLine();
String regex = "^[a-zA-Z0-9]*$";
//Compiling the regular expression
Pattern pattern = Pattern.compile(regex);
//Retrieving the matcher object
Matcher matcher = pattern.matcher(input);
if(matcher.matches()) {
System.out.println("Match occurred");
} else {
System.out.println("Match not occurred");
}
}
}
Enter a String
Hello
Match occurred
Enter a String
sample#
Match not occurred
import java.util.Scanner;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class Example {
public static void main(String args[]) {
//Reading String from user
System.out.println("Enter a String");
Scanner sc = new Scanner(System.in);
String input = sc.nextLine();
String regex = "[0-9&&[^35]]";
//Compiling the regular expression
Pattern pattern = Pattern.compile(regex);
//Retrieving the matcher object
Matcher matcher = pattern.matcher(input);
int count = 0;
while(matcher.find()) {
count++;
}
System.out.println("Occurrences :"+count);
}
}
Enter a String
111223333555689
Occurrences :8 | [
{
"code": null,
"e": 1209,
"s": 1062,
"text": "To match a range of characters i.e. to match all the characters between two specified characters in a sequence you can use the character class as "
},
{
"code": null,
"e": 1215,
"s": 1209,
"text": "[a-z]"
},
{
"code": null,
"e": 1271,
"s": 1215,
"text": "The expression “[a-zA-Z]” accepts any English alphabet."
},
{
"code": null,
"e": 1327,
"s": 1271,
"text": "The expression “[a-zA-Z]” accepts any English alphabet."
},
{
"code": null,
"e": 1389,
"s": 1327,
"text": "The expression “[0-9&&[^35]]” accepts numbers except 3 and 5."
},
{
"code": null,
"e": 1451,
"s": 1389,
"text": "The expression “[0-9&&[^35]]” accepts numbers except 3 and 5."
},
{
"code": null,
"e": 2136,
"s": 1451,
"text": "import java.util.Scanner;\nimport java.util.regex.Matcher;\nimport java.util.regex.Pattern;\npublic class Example {\n public static void main(String args[]) {\n //Reading String from user\n System.out.println(\"Enter a String\");\n Scanner sc = new Scanner(System.in);\n String input = sc.nextLine();\n String regex = \"^[a-zA-Z0-9]*$\";\n //Compiling the regular expression\n Pattern pattern = Pattern.compile(regex);\n //Retrieving the matcher object\n Matcher matcher = pattern.matcher(input);\n if(matcher.matches()) {\n System.out.println(\"Match occurred\");\n } else {\n System.out.println(\"Match not occurred\");\n }\n }\n}"
},
{
"code": null,
"e": 2172,
"s": 2136,
"text": "Enter a String\nHello\nMatch occurred"
},
{
"code": null,
"e": 2214,
"s": 2172,
"text": "Enter a String\nsample#\nMatch not occurred"
},
{
"code": null,
"e": 2872,
"s": 2214,
"text": "import java.util.Scanner;\nimport java.util.regex.Matcher;\nimport java.util.regex.Pattern;\npublic class Example {\n public static void main(String args[]) {\n //Reading String from user\n System.out.println(\"Enter a String\");\n Scanner sc = new Scanner(System.in);\n String input = sc.nextLine();\n String regex = \"[0-9&&[^35]]\";\n //Compiling the regular expression\n Pattern pattern = Pattern.compile(regex);\n //Retrieving the matcher object\n Matcher matcher = pattern.matcher(input);\n int count = 0;\n while(matcher.find()) {\n count++;\n }\n System.out.println(\"Occurrences :\"+count);\n }\n}"
},
{
"code": null,
"e": 2918,
"s": 2872,
"text": "Enter a String\n111223333555689\nOccurrences :8"
}
] |
Character.valueOf() in Java with examples - GeeksforGeeks | 06 Dec, 2018
Java.lang.Character.valueOf() is an inbuilt method in Java that returns a Character instance representing the specified char value. If a new Character instance is not required, this method is generally used in preference to the constructor Character(char), since this method is likely to yield significantly better space and time performance by caching frequently requested values. This method will always cache values range [‘\u0000’ to ‘\u007F’] inclusive and may cache other values outside of this range.
Syntax:
public static Character valueOf(char ch)
Parameter:
ch- this parameter specifies the character.
Returns: This method returns a Character instance representing ch.
The program below demonstrates the Java.lang.Character.valueOf() function:
Program 1:
// Java program to demonstrate the// Java.lang.Character.valueOf() method// when the assigned char is a character import java.lang.*; public class Gfg { public static void main(String[] args) { // Create a character object Character c = new Character('z'); // assign the primitive value to a character char ch = c.charValue(); System.out.println("Character value of " + ch + " is " + c); }}
Character value of z is z
Program 2:
// Java program to demonstrate the// Java.lang.Character.valueOf() method// when the assigned char is a number import java.lang.*; public class Gfg { public static void main(String[] args) { // Create a character object Character c = new Character('5'); // assign the primitive value to a character char ch = c.charValue(); System.out.println("Character value of " + ch + " is " + c); }}
Character value of 5 is 5
Java-Character
Java-Functions
Java-lang package
Java
Java Programs
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Functional Interfaces in Java
Stream In Java
Constructors in Java
Different ways of Reading a text file in Java
Exceptions in Java
Convert a String to Character array in Java
Java Programming Examples
Convert Double to Integer in Java
Implementing a Linked List in Java using Class
Factory method design pattern in Java | [
{
"code": null,
"e": 23557,
"s": 23529,
"text": "\n06 Dec, 2018"
},
{
"code": null,
"e": 24065,
"s": 23557,
"text": "Java.lang.Character.valueOf() is an inbuilt method in Java that returns a Character instance representing the specified char value. If a new Character instance is not required, this method is generally used in preference to the constructor Character(char), since this method is likely to yield significantly better space and time performance by caching frequently requested values. This method will always cache values range [‘\\u0000’ to ‘\\u007F’] inclusive and may cache other values outside of this range."
},
{
"code": null,
"e": 24073,
"s": 24065,
"text": "Syntax:"
},
{
"code": null,
"e": 24172,
"s": 24073,
"text": "public static Character valueOf(char ch)\n\nParameter: \nch- this parameter specifies the character.\n"
},
{
"code": null,
"e": 24239,
"s": 24172,
"text": "Returns: This method returns a Character instance representing ch."
},
{
"code": null,
"e": 24314,
"s": 24239,
"text": "The program below demonstrates the Java.lang.Character.valueOf() function:"
},
{
"code": null,
"e": 24325,
"s": 24314,
"text": "Program 1:"
},
{
"code": "// Java program to demonstrate the// Java.lang.Character.valueOf() method// when the assigned char is a character import java.lang.*; public class Gfg { public static void main(String[] args) { // Create a character object Character c = new Character('z'); // assign the primitive value to a character char ch = c.charValue(); System.out.println(\"Character value of \" + ch + \" is \" + c); }}",
"e": 24768,
"s": 24325,
"text": null
},
{
"code": null,
"e": 24795,
"s": 24768,
"text": "Character value of z is z\n"
},
{
"code": null,
"e": 24806,
"s": 24795,
"text": "Program 2:"
},
{
"code": "// Java program to demonstrate the// Java.lang.Character.valueOf() method// when the assigned char is a number import java.lang.*; public class Gfg { public static void main(String[] args) { // Create a character object Character c = new Character('5'); // assign the primitive value to a character char ch = c.charValue(); System.out.println(\"Character value of \" + ch + \" is \" + c); }}",
"e": 25246,
"s": 24806,
"text": null
},
{
"code": null,
"e": 25273,
"s": 25246,
"text": "Character value of 5 is 5\n"
},
{
"code": null,
"e": 25288,
"s": 25273,
"text": "Java-Character"
},
{
"code": null,
"e": 25303,
"s": 25288,
"text": "Java-Functions"
},
{
"code": null,
"e": 25321,
"s": 25303,
"text": "Java-lang package"
},
{
"code": null,
"e": 25326,
"s": 25321,
"text": "Java"
},
{
"code": null,
"e": 25340,
"s": 25326,
"text": "Java Programs"
},
{
"code": null,
"e": 25345,
"s": 25340,
"text": "Java"
},
{
"code": null,
"e": 25443,
"s": 25345,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 25452,
"s": 25443,
"text": "Comments"
},
{
"code": null,
"e": 25465,
"s": 25452,
"text": "Old Comments"
},
{
"code": null,
"e": 25495,
"s": 25465,
"text": "Functional Interfaces in Java"
},
{
"code": null,
"e": 25510,
"s": 25495,
"text": "Stream In Java"
},
{
"code": null,
"e": 25531,
"s": 25510,
"text": "Constructors in Java"
},
{
"code": null,
"e": 25577,
"s": 25531,
"text": "Different ways of Reading a text file in Java"
},
{
"code": null,
"e": 25596,
"s": 25577,
"text": "Exceptions in Java"
},
{
"code": null,
"e": 25640,
"s": 25596,
"text": "Convert a String to Character array in Java"
},
{
"code": null,
"e": 25666,
"s": 25640,
"text": "Java Programming Examples"
},
{
"code": null,
"e": 25700,
"s": 25666,
"text": "Convert Double to Integer in Java"
},
{
"code": null,
"e": 25747,
"s": 25700,
"text": "Implementing a Linked List in Java using Class"
}
] |
ASP.NET MVC - Views | In an ASP.NET MVC application, there is nothing like a page and it also doesn’t include anything that directly corresponds to a page when you specify a path in URL. The closest thing to a page in an ASP.NET MVC application is known as a View.
In ASP.NET MVC application, all incoming browser requests are handled by the controller and these requests are mapped to controller actions. A controller action might return a view or it might also perform some other type of action such as redirecting to another controller action.
Let’s take a look at a simple example of View by creating a new ASP.NET MVC project.
Step 1 − Open the Visual Studio and click File → New → Project menu option.
A new Project dialog opens.
Step 2 − From the left pane, select Templates → Visual C# → Web.
Step 3 − In the middle pane, select ASP.NET Web Application.
Step 4 − Enter the project name ‘MVCViewDemo’ in the Name field and click Ok to continue. You will see the following dialog which asks you to set the initial content for the ASP.NET project.
Step 5 − To keep things simple, select the Empty option and check the MVC checkbox in the ‘Add folders and core references for’ section and click Ok.
It will create a basic MVC project with minimal predefined content. We now need to add controller.
Step 6 − Right-click on the controller folder in the solution explorer and select Add → Controller.
It will display the Add Scaffold dialog.
Step 7 − Select the MVC 5 Controller – Empty option and click ‘Add’ button.
The Add Controller dialog will appear.
Step 8 − Set the name to HomeController and click ‘Add’ button.
You will see a new C# file ‘HomeController.cs’ in the Controllers folder which is open for editing in Visual Studio as well.
Let’s update the HomeController.cs file, which contains two action methods as shown in the following code.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
namespace MVCViewDemo.Controllers {
public class HomeController : Controller{
// GET: Home
public ActionResult Index(){
return View();
}
public string Mycontroller(){
return "Hi, I am a controller";
}
}
}
Step 9 − Run this application and apend /Home/MyController to the URL in the browser and press enter. You will receive the following output.
As MyController action simply returns the string, to return a View from the action we need to add a View first.
Step 10 − Before adding a view let’s add another action, which will return a default view.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
namespace MVCViewDemo.Controllers {
public class HomeController : Controller{
// GET: Home
public ActionResult Index(){
return View();
}
public string Mycontroller(){
return "Hi, I am a controller";
}
public ActionResult MyView(){
return View();
}
}
}
Step 11 − Run this application and apend /Home/MyView to the URL in the browser and press enter. You will receive the following output.
You can see here that we have an error and this error is actually quite descriptive, which tells us it can't find the MyView view.
Step 12 − To add a view, right-click inside the MyView action and select Add view.
It will display the Add View dialog and it is going to add the default name.
Step 13 − Uncheck the ‘Use a layout page’ checkbox and click ‘Add’ button.
We now have the default code inside view.
Step 14 − Add some text in this view using the following code.
@{
Layout = null;
}
<!DOCTYPE html>
<html>
<head>
<meta name = "viewport" content = "width = device-width" />
<title>MyView</title>
</head>
<body>
<div>
Hi, I am a view
</div>
</body>
</html>
Step 15 − Run this application and apend /Home/MyView to the URL in the browser. Press enter and you will receive the following output.
You can now see the text from the View.
51 Lectures
5.5 hours
Anadi Sharma
44 Lectures
4.5 hours
Kaushik Roy Chowdhury
42 Lectures
18 hours
SHIVPRASAD KOIRALA
57 Lectures
3.5 hours
University Code
40 Lectures
2.5 hours
University Code
138 Lectures
9 hours
Bhrugen Patel
Print
Add Notes
Bookmark this page | [
{
"code": null,
"e": 2512,
"s": 2269,
"text": "In an ASP.NET MVC application, there is nothing like a page and it also doesn’t include anything that directly corresponds to a page when you specify a path in URL. The closest thing to a page in an ASP.NET MVC application is known as a View."
},
{
"code": null,
"e": 2794,
"s": 2512,
"text": "In ASP.NET MVC application, all incoming browser requests are handled by the controller and these requests are mapped to controller actions. A controller action might return a view or it might also perform some other type of action such as redirecting to another controller action."
},
{
"code": null,
"e": 2879,
"s": 2794,
"text": "Let’s take a look at a simple example of View by creating a new ASP.NET MVC project."
},
{
"code": null,
"e": 2955,
"s": 2879,
"text": "Step 1 − Open the Visual Studio and click File → New → Project menu option."
},
{
"code": null,
"e": 2983,
"s": 2955,
"text": "A new Project dialog opens."
},
{
"code": null,
"e": 3048,
"s": 2983,
"text": "Step 2 − From the left pane, select Templates → Visual C# → Web."
},
{
"code": null,
"e": 3109,
"s": 3048,
"text": "Step 3 − In the middle pane, select ASP.NET Web Application."
},
{
"code": null,
"e": 3300,
"s": 3109,
"text": "Step 4 − Enter the project name ‘MVCViewDemo’ in the Name field and click Ok to continue. You will see the following dialog which asks you to set the initial content for the ASP.NET project."
},
{
"code": null,
"e": 3450,
"s": 3300,
"text": "Step 5 − To keep things simple, select the Empty option and check the MVC checkbox in the ‘Add folders and core references for’ section and click Ok."
},
{
"code": null,
"e": 3549,
"s": 3450,
"text": "It will create a basic MVC project with minimal predefined content. We now need to add controller."
},
{
"code": null,
"e": 3649,
"s": 3549,
"text": "Step 6 − Right-click on the controller folder in the solution explorer and select Add → Controller."
},
{
"code": null,
"e": 3690,
"s": 3649,
"text": "It will display the Add Scaffold dialog."
},
{
"code": null,
"e": 3766,
"s": 3690,
"text": "Step 7 − Select the MVC 5 Controller – Empty option and click ‘Add’ button."
},
{
"code": null,
"e": 3805,
"s": 3766,
"text": "The Add Controller dialog will appear."
},
{
"code": null,
"e": 3869,
"s": 3805,
"text": "Step 8 − Set the name to HomeController and click ‘Add’ button."
},
{
"code": null,
"e": 3994,
"s": 3869,
"text": "You will see a new C# file ‘HomeController.cs’ in the Controllers folder which is open for editing in Visual Studio as well."
},
{
"code": null,
"e": 4101,
"s": 3994,
"text": "Let’s update the HomeController.cs file, which contains two action methods as shown in the following code."
},
{
"code": null,
"e": 4472,
"s": 4101,
"text": "using System;\nusing System.Collections.Generic;\nusing System.Linq;\n\nusing System.Web;\nusing System.Web.Mvc;\n\nnamespace MVCViewDemo.Controllers {\n public class HomeController : Controller{\n // GET: Home\n public ActionResult Index(){\n return View();\n }\n\t\t\n public string Mycontroller(){\n return \"Hi, I am a controller\";\n }\n }\n}"
},
{
"code": null,
"e": 4613,
"s": 4472,
"text": "Step 9 − Run this application and apend /Home/MyController to the URL in the browser and press enter. You will receive the following output."
},
{
"code": null,
"e": 4725,
"s": 4613,
"text": "As MyController action simply returns the string, to return a View from the action we need to add a View first."
},
{
"code": null,
"e": 4816,
"s": 4725,
"text": "Step 10 − Before adding a view let’s add another action, which will return a default view."
},
{
"code": null,
"e": 5258,
"s": 4816,
"text": "using System;\nusing System.Collections.Generic;\nusing System.Linq;\n\nusing System.Web;\nusing System.Web.Mvc;\n\nnamespace MVCViewDemo.Controllers {\n public class HomeController : Controller{\n // GET: Home\n public ActionResult Index(){\n return View();\n }\n\t\t\n public string Mycontroller(){\n return \"Hi, I am a controller\";\n }\n\t\t\n public ActionResult MyView(){\n return View();\n }\n }\n}"
},
{
"code": null,
"e": 5394,
"s": 5258,
"text": "Step 11 − Run this application and apend /Home/MyView to the URL in the browser and press enter. You will receive the following output."
},
{
"code": null,
"e": 5525,
"s": 5394,
"text": "You can see here that we have an error and this error is actually quite descriptive, which tells us it can't find the MyView view."
},
{
"code": null,
"e": 5608,
"s": 5525,
"text": "Step 12 − To add a view, right-click inside the MyView action and select Add view."
},
{
"code": null,
"e": 5685,
"s": 5608,
"text": "It will display the Add View dialog and it is going to add the default name."
},
{
"code": null,
"e": 5760,
"s": 5685,
"text": "Step 13 − Uncheck the ‘Use a layout page’ checkbox and click ‘Add’ button."
},
{
"code": null,
"e": 5802,
"s": 5760,
"text": "We now have the default code inside view."
},
{
"code": null,
"e": 5865,
"s": 5802,
"text": "Step 14 − Add some text in this view using the following code."
},
{
"code": null,
"e": 6110,
"s": 5865,
"text": "@{\n Layout = null;\n}\n\n<!DOCTYPE html>\n<html>\n <head>\n <meta name = \"viewport\" content = \"width = device-width\" />\n <title>MyView</title>\n </head>\n\t\n <body>\n <div>\n Hi, I am a view\n </div>\n </body>\n\t\n</html>"
},
{
"code": null,
"e": 6246,
"s": 6110,
"text": "Step 15 − Run this application and apend /Home/MyView to the URL in the browser. Press enter and you will receive the following output."
},
{
"code": null,
"e": 6286,
"s": 6246,
"text": "You can now see the text from the View."
},
{
"code": null,
"e": 6321,
"s": 6286,
"text": "\n 51 Lectures \n 5.5 hours \n"
},
{
"code": null,
"e": 6335,
"s": 6321,
"text": " Anadi Sharma"
},
{
"code": null,
"e": 6370,
"s": 6335,
"text": "\n 44 Lectures \n 4.5 hours \n"
},
{
"code": null,
"e": 6393,
"s": 6370,
"text": " Kaushik Roy Chowdhury"
},
{
"code": null,
"e": 6427,
"s": 6393,
"text": "\n 42 Lectures \n 18 hours \n"
},
{
"code": null,
"e": 6447,
"s": 6427,
"text": " SHIVPRASAD KOIRALA"
},
{
"code": null,
"e": 6482,
"s": 6447,
"text": "\n 57 Lectures \n 3.5 hours \n"
},
{
"code": null,
"e": 6499,
"s": 6482,
"text": " University Code"
},
{
"code": null,
"e": 6534,
"s": 6499,
"text": "\n 40 Lectures \n 2.5 hours \n"
},
{
"code": null,
"e": 6551,
"s": 6534,
"text": " University Code"
},
{
"code": null,
"e": 6585,
"s": 6551,
"text": "\n 138 Lectures \n 9 hours \n"
},
{
"code": null,
"e": 6600,
"s": 6585,
"text": " Bhrugen Patel"
},
{
"code": null,
"e": 6607,
"s": 6600,
"text": " Print"
},
{
"code": null,
"e": 6618,
"s": 6607,
"text": " Add Notes"
}
] |
How to use waiter functionality for bucket_not_exists using Boto3 and AWS Client? | Problem Statement − Use boto3 library in Python to check whether a bucket does not exist using waiter functionality. For example, use waiters to check whether Bucket_2 does not exist in S3.
Step 1 − Import boto3 and botocore exceptions to handle exceptions.
Step 2 − Use bucket_name as the parameter in the function.
Step 3 − Create an AWS session using boto3 library.
Step 4 − Create an AWS client for S3.
Step 5 − Now create the wait object for bucket_not_exists using get_waiter function.
Step 6 − Now, use the wait object to validate whether the bucket does not exist. By default, it checks in every 5 seconds until a successful state is reached. Here successful state means bucket should not be present in S3. An error is returned after 20 failed checks. However, the user can define polling time and max attempts.
Step 7 − It returns None.
Step 8 − Handle the generic exception if something went wrong while checking the bucket.
Use the following code to use waiter to check whether bucket_not_exists −
import boto3
from botocore.exceptions import ClientError
def use_waiters_check_bucket_not_exists(bucket_name):
session = boto3.session.Session()
s3_client = session.client('s3')
try:
waiter = s3_client.get_waiter('bucket_not_exists')
waiter.wait(Bucket=bucket_name,
WaiterConfig={
'Delay': 2, 'MaxAttempts': 5})
print('Bucket not exist: ' + bucket_name)
except ClientError as e:
raise Exception( "boto3 client error in use_waiters_check_bucket_not_exists: " + e.__str__())
except Exception as e:
raise Exception( "Unexpected error in use_waiters_check_bucket_not_exists: " + e.__str__())
print(use_waiters_check_bucket_not_exists("Bucket_2"))
print(use_waiters_check_bucket_not_exists("Bucket_1"))
Bucket not exist: Bucket_2
None
botocore.exceptions.WaiterError: Waiter BucketNotExists failed: Max
attempts exceeded
"Unexpected error in use_waiters_check_bucket_not_exists: " +
e.__str__())
Exception: Unexpected error in use_waiters_check_bucket_not_exists:
Waiter BucketNotExists failed: Max attempts exceed
For Bucket_2, the output is print statement and None. Since the response doesn’t return anything, it prints None.
For Bucket_1, the output is an exception, since this bucket exists even after max attempts to check.
In exception, it can be read that Max attempts exceeded. | [
{
"code": null,
"e": 1252,
"s": 1062,
"text": "Problem Statement − Use boto3 library in Python to check whether a bucket does not exist using waiter functionality. For example, use waiters to check whether Bucket_2 does not exist in S3."
},
{
"code": null,
"e": 1320,
"s": 1252,
"text": "Step 1 − Import boto3 and botocore exceptions to handle exceptions."
},
{
"code": null,
"e": 1379,
"s": 1320,
"text": "Step 2 − Use bucket_name as the parameter in the function."
},
{
"code": null,
"e": 1431,
"s": 1379,
"text": "Step 3 − Create an AWS session using boto3 library."
},
{
"code": null,
"e": 1469,
"s": 1431,
"text": "Step 4 − Create an AWS client for S3."
},
{
"code": null,
"e": 1554,
"s": 1469,
"text": "Step 5 − Now create the wait object for bucket_not_exists using get_waiter function."
},
{
"code": null,
"e": 1882,
"s": 1554,
"text": "Step 6 − Now, use the wait object to validate whether the bucket does not exist. By default, it checks in every 5 seconds until a successful state is reached. Here successful state means bucket should not be present in S3. An error is returned after 20 failed checks. However, the user can define polling time and max attempts."
},
{
"code": null,
"e": 1908,
"s": 1882,
"text": "Step 7 − It returns None."
},
{
"code": null,
"e": 1997,
"s": 1908,
"text": "Step 8 − Handle the generic exception if something went wrong while checking the bucket."
},
{
"code": null,
"e": 2071,
"s": 1997,
"text": "Use the following code to use waiter to check whether bucket_not_exists −"
},
{
"code": null,
"e": 2855,
"s": 2071,
"text": "import boto3\nfrom botocore.exceptions import ClientError\n\ndef use_waiters_check_bucket_not_exists(bucket_name):\n session = boto3.session.Session()\n s3_client = session.client('s3')\n try:\n waiter = s3_client.get_waiter('bucket_not_exists')\n waiter.wait(Bucket=bucket_name,\n WaiterConfig={\n 'Delay': 2, 'MaxAttempts': 5})\n print('Bucket not exist: ' + bucket_name)\n except ClientError as e:\n raise Exception( \"boto3 client error in use_waiters_check_bucket_not_exists: \" + e.__str__())\n except Exception as e:\n raise Exception( \"Unexpected error in use_waiters_check_bucket_not_exists: \" + e.__str__())\n\nprint(use_waiters_check_bucket_not_exists(\"Bucket_2\"))\nprint(use_waiters_check_bucket_not_exists(\"Bucket_1\"))"
},
{
"code": null,
"e": 3170,
"s": 2855,
"text": "Bucket not exist: Bucket_2\nNone\n\nbotocore.exceptions.WaiterError: Waiter BucketNotExists failed: Max\nattempts exceeded\n\"Unexpected error in use_waiters_check_bucket_not_exists: \" +\ne.__str__())\nException: Unexpected error in use_waiters_check_bucket_not_exists:\nWaiter BucketNotExists failed: Max attempts exceed\n\n"
},
{
"code": null,
"e": 3284,
"s": 3170,
"text": "For Bucket_2, the output is print statement and None. Since the response doesn’t return anything, it prints None."
},
{
"code": null,
"e": 3385,
"s": 3284,
"text": "For Bucket_1, the output is an exception, since this bucket exists even after max attempts to check."
},
{
"code": null,
"e": 3442,
"s": 3385,
"text": "In exception, it can be read that Max attempts exceeded."
}
] |
Groovy - Unit Testing | The fundamental unit of an object-oriented system is the class. Therefore unit testing consists of testig within a class. The approach taken is to create an object of the class under testing and use it to check that selected methods execute as expected. Not every method can be tested, since it is not always pratical to test each and every thing. But unit testing should be conducted for key and critical methods.
JUnit is an open-source testing framework that is the accepted industry standard for the automated unit testing of Java code. Fortunately, the JUnit framework can be easily used for testing Groovy classes. All that is required is to extend the GroovyTestCase class that is part of the standard Groovy environment. The Groovy test case class is based on the Junit test case.
Let assume we have the following class defined in a an application class file −
class Example {
static void main(String[] args) {
Student mst = new Student();
mst.name = "Joe";
mst.ID = 1;
println(mst.Display())
}
}
public class Student {
String name;
int ID;
String Display() {
return name +ID;
}
}
The output of the above program is given below.
Joe1
And now suppose we wanted to write a test case for the Student class. A typical test case would look like the one below. The following points need to be noted about the following code −
The test case class extends the GroovyTestCase class
We are using the assert statement to ensure that the Display method returns the right string.
class StudentTest extends GroovyTestCase {
void testDisplay() {
def stud = new Student(name : 'Joe', ID : '1')
def expected = 'Joe1'
assertToString(stud.Display(), expected)
}
}
Normally as the number of unit tests increases, it would become difficult to keep on executing all the test cases one by one. Hence Groovy provides a facility to create a test suite that can encapsulate all test cases into one logicial unit. The following codesnippet shows how this can be achieved. The following things should be noted about the code −
The GroovyTestSuite is used to encapsulate all test cases into one.
The GroovyTestSuite is used to encapsulate all test cases into one.
In the following example, we are assuming that we have two tests case files, one called StudentTest and the other is EmployeeTest which contains all of the necessary testing.
In the following example, we are assuming that we have two tests case files, one called StudentTest and the other is EmployeeTest which contains all of the necessary testing.
import groovy.util.GroovyTestSuite
import junit.framework.Test
import junit.textui.TestRunner
class AllTests {
static Test suite() {
def allTests = new GroovyTestSuite()
allTests.addTestSuite(StudentTest.class)
allTests.addTestSuite(EmployeeTest.class)
return allTests
}
}
TestRunner.run(AllTests.suite())
52 Lectures
8 hours
Krishna Sakinala
49 Lectures
2.5 hours
Packt Publishing
Print
Add Notes
Bookmark this page | [
{
"code": null,
"e": 2653,
"s": 2238,
"text": "The fundamental unit of an object-oriented system is the class. Therefore unit testing consists of testig within a class. The approach taken is to create an object of the class under testing and use it to check that selected methods execute as expected. Not every method can be tested, since it is not always pratical to test each and every thing. But unit testing should be conducted for key and critical methods."
},
{
"code": null,
"e": 3027,
"s": 2653,
"text": "JUnit is an open-source testing framework that is the accepted industry standard for the automated unit testing of Java code. Fortunately, the JUnit framework can be easily used for testing Groovy classes. All that is required is to extend the GroovyTestCase class that is part of the standard Groovy environment. The Groovy test case class is based on the Junit test case."
},
{
"code": null,
"e": 3107,
"s": 3027,
"text": "Let assume we have the following class defined in a an application class file −"
},
{
"code": null,
"e": 3383,
"s": 3107,
"text": "class Example {\n static void main(String[] args) {\n Student mst = new Student();\n mst.name = \"Joe\";\n mst.ID = 1;\n println(mst.Display())\n } \n} \n \npublic class Student {\n String name;\n int ID;\n\t\n String Display() {\n return name +ID;\n } \n}"
},
{
"code": null,
"e": 3431,
"s": 3383,
"text": "The output of the above program is given below."
},
{
"code": null,
"e": 3437,
"s": 3431,
"text": "Joe1\n"
},
{
"code": null,
"e": 3623,
"s": 3437,
"text": "And now suppose we wanted to write a test case for the Student class. A typical test case would look like the one below. The following points need to be noted about the following code −"
},
{
"code": null,
"e": 3676,
"s": 3623,
"text": "The test case class extends the GroovyTestCase class"
},
{
"code": null,
"e": 3770,
"s": 3676,
"text": "We are using the assert statement to ensure that the Display method returns the right string."
},
{
"code": null,
"e": 3972,
"s": 3770,
"text": "class StudentTest extends GroovyTestCase {\n void testDisplay() {\n def stud = new Student(name : 'Joe', ID : '1')\n def expected = 'Joe1'\n assertToString(stud.Display(), expected)\n }\n}"
},
{
"code": null,
"e": 4326,
"s": 3972,
"text": "Normally as the number of unit tests increases, it would become difficult to keep on executing all the test cases one by one. Hence Groovy provides a facility to create a test suite that can encapsulate all test cases into one logicial unit. The following codesnippet shows how this can be achieved. The following things should be noted about the code −"
},
{
"code": null,
"e": 4394,
"s": 4326,
"text": "The GroovyTestSuite is used to encapsulate all test cases into one."
},
{
"code": null,
"e": 4462,
"s": 4394,
"text": "The GroovyTestSuite is used to encapsulate all test cases into one."
},
{
"code": null,
"e": 4637,
"s": 4462,
"text": "In the following example, we are assuming that we have two tests case files, one called StudentTest and the other is EmployeeTest which contains all of the necessary testing."
},
{
"code": null,
"e": 4812,
"s": 4637,
"text": "In the following example, we are assuming that we have two tests case files, one called StudentTest and the other is EmployeeTest which contains all of the necessary testing."
},
{
"code": null,
"e": 5161,
"s": 4812,
"text": "import groovy.util.GroovyTestSuite \nimport junit.framework.Test \nimport junit.textui.TestRunner \n\nclass AllTests { \n static Test suite() { \n def allTests = new GroovyTestSuite() \n allTests.addTestSuite(StudentTest.class) \n allTests.addTestSuite(EmployeeTest.class) \n return allTests \n } \n} \n\nTestRunner.run(AllTests.suite())"
},
{
"code": null,
"e": 5194,
"s": 5161,
"text": "\n 52 Lectures \n 8 hours \n"
},
{
"code": null,
"e": 5212,
"s": 5194,
"text": " Krishna Sakinala"
},
{
"code": null,
"e": 5247,
"s": 5212,
"text": "\n 49 Lectures \n 2.5 hours \n"
},
{
"code": null,
"e": 5265,
"s": 5247,
"text": " Packt Publishing"
},
{
"code": null,
"e": 5272,
"s": 5265,
"text": " Print"
},
{
"code": null,
"e": 5283,
"s": 5272,
"text": " Add Notes"
}
] |
HTML DOM Anchor target Property | The HTML DOM target property associated with the anchor tag (<a>) specifies where the new web page will open after clicking the URL. It can have the following values −
_blank − This will open the linked document in a new window.
_parent − This will open the linked document in the parent frameset.
_top − This will open the linked document in the full body window.
_self − This will open the linked document in the same window. This is the default behavior
framename − This will open the linked document in the specified framename.
Following is the syntax for −
Returning the target property −
anchorObject.target
Setting the target property −
anchorObject.target = "_blank|_self|_parent|_top|framename"
Let us see an example of anchor target property −
Live Demo
<!DOCTYPE html>
<html>
<body>
<p><a id="Anchor" target="_self" href="https://www.examplesite.com">example site</a></p>
<p><a id="Anchor2" href="https://www.examplesite.com">example site</a></p>
<p>Click the button to see the value of the target attribute.</p>
<button onclick="getTarget1()">GetTarget</button>
<button onclick="setTarget2()">SetTarget</button>
<p id="Target1"></p>
<script>
function getTarget1() {
var x = document.getElementById("Anchor").target;
document.getElementById("Target1").innerHTML = x;
}
function setTarget2(){
document.getElementById("Anchor2").innerHTML="Target has been set";
document.getElementById("Target1").target="newframe";
}
</script>
</body>
</html>
This will produce the following output −
After clicking on “GetTarget” button −
After clicking on “SetTarget” button −
In the above example −
We have taken one anchor tag with target attribute and with a value _self and another one with default _blank −
<p><a id="Anchor" target="_self" href="https://www.examplesite.com">example site</a></p>
<p><a id="Anchor2" href="https://www.examplesite.com">example site</a></p>
We have then created two buttons named GetTarget and SetTarget to execute the getTarget1() and setTarget2() functions respectively.
<button onclick="getTarget1()">GetTarget</button>
<button onclick="setTarget2()">SetTarget</button>
The getTarget1() will get the target value from the first link and display in the paragraph tag with id=”Target1”. The setTarget2() will set the target value of link2 from default _blank to custom frame “newframe”.
function getTarget1() {
var x = document.getElementById("Anchor").target;
document.getElementById("Target1").innerHTML = x;
}
function setTarget2(){
document.getElementById("Target1").innerHTML="Target has been set";
document.getElementById("Anchor2").target="_blank";
} | [
{
"code": null,
"e": 1230,
"s": 1062,
"text": "The HTML DOM target property associated with the anchor tag (<a>) specifies where the new web page will open after clicking the URL. It can have the following values −"
},
{
"code": null,
"e": 1291,
"s": 1230,
"text": "_blank − This will open the linked document in a new window."
},
{
"code": null,
"e": 1360,
"s": 1291,
"text": "_parent − This will open the linked document in the parent frameset."
},
{
"code": null,
"e": 1427,
"s": 1360,
"text": "_top − This will open the linked document in the full body window."
},
{
"code": null,
"e": 1519,
"s": 1427,
"text": "_self − This will open the linked document in the same window. This is the default behavior"
},
{
"code": null,
"e": 1594,
"s": 1519,
"text": "framename − This will open the linked document in the specified framename."
},
{
"code": null,
"e": 1624,
"s": 1594,
"text": "Following is the syntax for −"
},
{
"code": null,
"e": 1656,
"s": 1624,
"text": "Returning the target property −"
},
{
"code": null,
"e": 1676,
"s": 1656,
"text": "anchorObject.target"
},
{
"code": null,
"e": 1706,
"s": 1676,
"text": "Setting the target property −"
},
{
"code": null,
"e": 1766,
"s": 1706,
"text": "anchorObject.target = \"_blank|_self|_parent|_top|framename\""
},
{
"code": null,
"e": 1816,
"s": 1766,
"text": "Let us see an example of anchor target property −"
},
{
"code": null,
"e": 1826,
"s": 1816,
"text": "Live Demo"
},
{
"code": null,
"e": 2551,
"s": 1826,
"text": "<!DOCTYPE html>\n<html>\n<body>\n<p><a id=\"Anchor\" target=\"_self\" href=\"https://www.examplesite.com\">example site</a></p>\n<p><a id=\"Anchor2\" href=\"https://www.examplesite.com\">example site</a></p>\n<p>Click the button to see the value of the target attribute.</p>\n<button onclick=\"getTarget1()\">GetTarget</button>\n<button onclick=\"setTarget2()\">SetTarget</button>\n<p id=\"Target1\"></p>\n<script>\n function getTarget1() {\n var x = document.getElementById(\"Anchor\").target;\n document.getElementById(\"Target1\").innerHTML = x;\n }\n function setTarget2(){\n document.getElementById(\"Anchor2\").innerHTML=\"Target has been set\";\n document.getElementById(\"Target1\").target=\"newframe\";\n }\n</script>\n</body>\n</html>"
},
{
"code": null,
"e": 2592,
"s": 2551,
"text": "This will produce the following output −"
},
{
"code": null,
"e": 2631,
"s": 2592,
"text": "After clicking on “GetTarget” button −"
},
{
"code": null,
"e": 2670,
"s": 2631,
"text": "After clicking on “SetTarget” button −"
},
{
"code": null,
"e": 2693,
"s": 2670,
"text": "In the above example −"
},
{
"code": null,
"e": 2805,
"s": 2693,
"text": "We have taken one anchor tag with target attribute and with a value _self and another one with default _blank −"
},
{
"code": null,
"e": 2969,
"s": 2805,
"text": "<p><a id=\"Anchor\" target=\"_self\" href=\"https://www.examplesite.com\">example site</a></p>\n<p><a id=\"Anchor2\" href=\"https://www.examplesite.com\">example site</a></p>"
},
{
"code": null,
"e": 3101,
"s": 2969,
"text": "We have then created two buttons named GetTarget and SetTarget to execute the getTarget1() and setTarget2() functions respectively."
},
{
"code": null,
"e": 3201,
"s": 3101,
"text": "<button onclick=\"getTarget1()\">GetTarget</button>\n<button onclick=\"setTarget2()\">SetTarget</button>"
},
{
"code": null,
"e": 3416,
"s": 3201,
"text": "The getTarget1() will get the target value from the first link and display in the paragraph tag with id=”Target1”. The setTarget2() will set the target value of link2 from default _blank to custom frame “newframe”."
},
{
"code": null,
"e": 3699,
"s": 3416,
"text": "function getTarget1() {\n var x = document.getElementById(\"Anchor\").target;\n document.getElementById(\"Target1\").innerHTML = x;\n}\nfunction setTarget2(){\n document.getElementById(\"Target1\").innerHTML=\"Target has been set\";\n document.getElementById(\"Anchor2\").target=\"_blank\";\n}"
}
] |
Can we add null elements to a Set in Java? | A Set is a collection that cannot contain duplicate elements. It models the mathematical set abstraction.
It does not allow duplicate elements and allow one null value at most.
Set also adds a stronger contract on the behavior of the equals and hashCode operations, allowing Set instances to be compared meaningfully even if their implementation types differ.
There are three classes implementing this interface −
HashSet − Set implementation based on hash table.
LinkedHashSet − HashSet implementation based on linked list.
TreeSet − Set implementation based on trees.
As per the definition a set object does not allow duplicate values but it does allow at most one null value.
Null values in HashSet − The HashSet object allows null values but, you can add only one null element to it. Though you add more null values if you try to print its contents, it displays only one null.
import java.util.HashSet;
import java.util.Set;
public class HashSetExample {
public static void main(String args[]) {
Set<Integer> hashSet = new HashSet<Integer>();
//Populating the HashSet
hashSet.add(1124);
hashSet.add(3654);
hashSet.add(7854);
hashSet.add(9945);
System.out.println(hashSet);
//Adding null elements
hashSet.add(null);
hashSet.add(null);
hashSet.add(null);
System.out.println(hashSet);
}
}
[1124, 3654, 9945, 7854]
[null, 1124, 3654, 9945, 7854]
Null values in LinkedHashSet: Just like the HashSet object, this also allows null values but, you can add only one null element to it. Though you add more null values if you try to print its contents, it displays only one null.
import java.util.LinkedHashSet;
import java.util.Set;
public class LinkedHashSetExample {
public static void main(String args[]) {
Set<Integer> linkedHashSet = new LinkedHashSet<Integer>();
//Populating the HashSet
linkedHashSet.add(1124);
linkedHashSet.add(3654);
linkedHashSet.add(7854);
linkedHashSet.add(9945);
System.out.println(linkedHashSet);
//Adding null elements
linkedHashSet.add(null);
linkedHashSet.add(null);
linkedHashSet.add(null);
System.out.println(linkedHashSet);
}
}
[1124, 3654, 9945, 7854]
[null, 1124, 3654, 9945, 7854]
Null values in TreeSet − The TreeSet object doesn’t allows null values but, If you try to add them, a runtime exception will be generated at.
import java.util.Set;
import java.util.TreeSet;
public class TreeSetExample {
public static void main(String args[]) {
Set<Integer> treeSet = new TreeSet<Integer>();
//Populating the HashSet
treeSet.add(1124);
treeSet.add(3654);
treeSet.add(7854);
treeSet.add(9945);
System.out.println(treeSet);
//Adding null elements
treeSet.add(null);
treeSet.add(null);
treeSet.add(null);
System.out.println(treeSet);
}
}
[1124, 3654, 7854, 9945]
Exception in thread "main" java.lang.NullPointerException
at java.util.TreeMap.put(Unknown Source)
at java.util.TreeSet.add(Unknown Source)
at MyPackage.TreeSetExample.main(TreeSetExample.java:16) | [
{
"code": null,
"e": 1168,
"s": 1062,
"text": "A Set is a collection that cannot contain duplicate elements. It models the mathematical set abstraction."
},
{
"code": null,
"e": 1239,
"s": 1168,
"text": "It does not allow duplicate elements and allow one null value at most."
},
{
"code": null,
"e": 1422,
"s": 1239,
"text": "Set also adds a stronger contract on the behavior of the equals and hashCode operations, allowing Set instances to be compared meaningfully even if their implementation types differ."
},
{
"code": null,
"e": 1476,
"s": 1422,
"text": "There are three classes implementing this interface −"
},
{
"code": null,
"e": 1526,
"s": 1476,
"text": "HashSet − Set implementation based on hash table."
},
{
"code": null,
"e": 1587,
"s": 1526,
"text": "LinkedHashSet − HashSet implementation based on linked list."
},
{
"code": null,
"e": 1632,
"s": 1587,
"text": "TreeSet − Set implementation based on trees."
},
{
"code": null,
"e": 1741,
"s": 1632,
"text": "As per the definition a set object does not allow duplicate values but it does allow at most one null value."
},
{
"code": null,
"e": 1943,
"s": 1741,
"text": "Null values in HashSet − The HashSet object allows null values but, you can add only one null element to it. Though you add more null values if you try to print its contents, it displays only one null."
},
{
"code": null,
"e": 2430,
"s": 1943,
"text": "import java.util.HashSet;\nimport java.util.Set;\npublic class HashSetExample {\n public static void main(String args[]) {\n Set<Integer> hashSet = new HashSet<Integer>();\n //Populating the HashSet\n hashSet.add(1124);\n hashSet.add(3654);\n hashSet.add(7854);\n hashSet.add(9945);\n System.out.println(hashSet);\n //Adding null elements\n hashSet.add(null);\n hashSet.add(null);\n hashSet.add(null);\n System.out.println(hashSet);\n }\n}"
},
{
"code": null,
"e": 2486,
"s": 2430,
"text": "[1124, 3654, 9945, 7854]\n[null, 1124, 3654, 9945, 7854]"
},
{
"code": null,
"e": 2714,
"s": 2486,
"text": "Null values in LinkedHashSet: Just like the HashSet object, this also allows null values but, you can add only one null element to it. Though you add more null values if you try to print its contents, it displays only one null."
},
{
"code": null,
"e": 3279,
"s": 2714,
"text": "import java.util.LinkedHashSet;\nimport java.util.Set;\npublic class LinkedHashSetExample {\n public static void main(String args[]) {\n Set<Integer> linkedHashSet = new LinkedHashSet<Integer>();\n //Populating the HashSet\n linkedHashSet.add(1124);\n linkedHashSet.add(3654);\n linkedHashSet.add(7854);\n linkedHashSet.add(9945);\n System.out.println(linkedHashSet);\n //Adding null elements\n linkedHashSet.add(null);\n linkedHashSet.add(null);\n linkedHashSet.add(null);\n System.out.println(linkedHashSet);\n }\n}"
},
{
"code": null,
"e": 3335,
"s": 3279,
"text": "[1124, 3654, 9945, 7854]\n[null, 1124, 3654, 9945, 7854]"
},
{
"code": null,
"e": 3477,
"s": 3335,
"text": "Null values in TreeSet − The TreeSet object doesn’t allows null values but, If you try to add them, a runtime exception will be generated at."
},
{
"code": null,
"e": 3964,
"s": 3477,
"text": "import java.util.Set;\nimport java.util.TreeSet;\npublic class TreeSetExample {\n public static void main(String args[]) {\n Set<Integer> treeSet = new TreeSet<Integer>();\n //Populating the HashSet\n treeSet.add(1124);\n treeSet.add(3654);\n treeSet.add(7854);\n treeSet.add(9945);\n System.out.println(treeSet);\n //Adding null elements\n treeSet.add(null);\n treeSet.add(null);\n treeSet.add(null);\n System.out.println(treeSet);\n }\n}"
},
{
"code": null,
"e": 4195,
"s": 3964,
"text": "[1124, 3654, 7854, 9945]\nException in thread \"main\" java.lang.NullPointerException\n at java.util.TreeMap.put(Unknown Source)\n at java.util.TreeSet.add(Unknown Source)\n at MyPackage.TreeSetExample.main(TreeSetExample.java:16)"
}
] |
How to create real-time Face Detector | by Dimid | Towards Data Science | In this article, I will show you how to write a real-time face detector using Python, TensorFlow/Keras and OpenCV.
I’ll note right away, that all code files are available in this repo.
gitlab.com
First, in Theoretical Part I will tell you a little about the concepts that will be useful for us (Transfer Learning and Data Augmentation), and then I will go to the code analysis in the Practical Part section.
Note, that you must have TensorFlow and OpenCV libraries installed to run this code. You can do it manually or simply run pip install -r requirements.txt command after you have the repo downloaded. You can also do it with conda commands conda install -c conda-forge numpy, opencv, tensorflow.
Here I want to build a face detector that also can distinguish me from other people. You can see the results of my work at the end of this article.
The initial task can be divided into two subtasks:
Train a model for face classification.Adapt the model to work with a webcam as a detector.
Train a model for face classification.
Adapt the model to work with a webcam as a detector.
In more detail, the task can be divided into the following stages:
Dataset Collection.Search for a Base Model for Transfer Learning.Train a Model.Transform Classifier into Detector.
Dataset Collection.
Search for a Base Model for Transfer Learning.
Train a Model.
Transform Classifier into Detector.
Before I begin to analyze these stages, I would like to very briefly outline the concepts that will be useful for us.
At this point, I must say that this tutorial is not as detailed as it could be. For example, I will not explain what convolution is or why pooling layers are needed in CNN architecture. Of course, you need to know this to understand how CNN works, but I think that this tutorial will be too cumbersome if I explain all the concepts. On the other hand, other people have already explained many things and did it better than me. For example, here you can read about CNN in general, and here — about popular CNN architectures.
Since we are talking about image recognition, we will use CNN — Convolutional Neural Networks, the architecture that has achieved the greatest success in this task.
Unlike classical neural networks (here I mean FDN — Feedforward Neural Network), in CNN, neurons are:
firstly: arranged in the form of a matrix (tensor), not an array,
and secondly: they are connected only with a small number of neurons of the previous layer, so layers are NOT fully connected.
This approach allows you to significantly reduce the number of network parameters and make the search for templates more efficient for images.
At the bottom of this image, I want to explain that the layer in CNN is a tensor (it is often drawn as a parallelepiped). I will talk about a tensor as a sequence of matrices. So each of these tensors is just a series of matrices standing on top of each other like pizza boxes. In turn, matrices are simply a sequence of neurons that are arranged in the form of a matrix, not an array, as in classic networks.
Transfer Learning is the most important concept for this task since it is very difficult (almost impossible) to build a face classifier from scratch. Transfer Learning is the process of using a pretrained model for your own task.
This happens as follows. You find a model that is trained for a similar task (for example, recognizing 1000 classes of images, as in ImageNet, when you need to recognize only a few). Then you use its weights (freeze them, which means that they will not change), and finish training the model on your small dataset. After that, you can also unfreeze all the weights and continue training the model with a very small learning rate.
This process becomes possible due to the features of the CNN architecture and the image recognition task (but also can be used with different architectures). The network learns to see patterns from layer to layer (from input to output) and they are getting more and more complicated. It turns out that the general patterns for all problems are approximately the same, which allows us to use pretrained weights.
Another important concept in the image classification problem is data augmentation. Data augmentation is the process of artificially increasing a dataset size by applying some transformations to the original images. For example, we can use horizontal and vertical reflection, small rotation or magnification, color inversion, and so on. This will significantly increase the size of the dataset and, accordingly, the generalization ability of the network.
towardsdatascience.com
In the example above (first image in the article), when the shift values are quite high, sometimes there is a situation when only part of the image is visible. On the one hand, this is good (the network can learn to recognize a cat not by its muzzle, but by its paws and tail in the case of images where the head is not visible), but it can also confuse the network if you overdo such transformation.
There are several approaches to data augmentation in TensorFlow. We can generate images and save them to disk, or we can feed the generator directly to the network. I chose the first option, to do it more explicitly. But there are two ways here as well: generate a random number of images or generate several versions of a specific image. You can see the implementation of both options in the data_augmentation.ipynb notebook. I used the second option and specifically generated five transformations for each image.
The project has the following structure:
me_not_me_detector├───article├───datasets│ ├───face_dataset_test_images│ │ ├───me # contains TEST images for ME class│ │ └───not_me # contains TEST images for NOT_ME class│ ├───face_dataset_train_aug_images (optional)│ │ ├───me # contains aug TRAIN images for ME class│ │ └───not_me # contains aug TRAIN images for NOT_ME class│ └───face_dataset_train_images│ ├───me # contains TRAIN images for ME class│ └───not_me # contains TRAIN images for NOT_ME class├───models│ .gitignore│ data_augmentation.ipynb│ me_not_me_classifier.ipynb│ me_not_me_classifier_model_comparison.ipynb│ me_not_me_detector.ipynb│ README.md└── requirements.txt
Let’s talk about folders.
The article folder contains the data for this tutorial.
The modelsfolder contains trained models for their test and further use.
The datasets folder contains three folders - for a train set, test set and augmented train set (optional). Each of them contains two subfolders for two classes - me and not_me. In the general case, it contains N subfolders for the N-class classification problem.
Now let’s talk about the code files — jupyter notebooks.
data_augmentation.ipynbfile creates an augmented dataset from an initial one and provides some information about the dataset.
me_not_me_classifier_model_comparison.ipynbfile contains code to train and test five different models.
me_not_me_classifier.ipynbfile does the same thing, but for one particular model. You can use it as an example to build your own classifier.
me_not_me_detector.ipynbfile uses the OpenCV library and turns the classifier into a real-time detector.
Other files are used as additional files:
.gitignore contains files that will not be pushed in git,
requirements.txt contains the list of libraries that have to be installed to run this code, etc.
First of all, we need to collect a dataset. I used my photos and photos of my family to train the model, but you can also train the model on some other face datasets. I used only personal photos to check whether such a small dataset is enough for the model to show acceptable quality.
I cropped the face from each photo and resized them to the size of 250x250 (which you don’t have to do, since TensorFlow can do it for you). Here are some examples of photos from the initial dataset:
In total, I collected 215 photos, where 82 are me and 133 are not_me.
For the test set, I immediately put aside 20 photos. This can be done automatically, but I did it manually because the dataset is too small. For the train set, I applied my data augmentation code from data_augmentation.ipynbnotebook. Thus, the dataset increased five times! (five photos were generated for each photo). Here is an example of the generated photos:
When the dataset is ready, we can start training the model.
There is nothing complicated here — I just used different models that are trained on the ImageNet dataset. If they don’t have good accuracy, then I think I will use something like VGGFace models like here. But the quality I got is good enough. We can load pretrained model with this code:
Now we have to freeze these weights, add some layers on top of the model and train the model on our little dataset.
As I said earlier, me_not_me_classifier_model_comparison.ipynbfile contains the code for different models. You can use it to do your own experiment. Code examples below are taken from me_not_me_classifier.ipynb. We will use ResNet50 as the initial model here.
After import libraries and dataset loading, we load pretrained model exactly as in the code above. After that, we need to restore the top of the model — the dense part. Note, that this part is different for different models. To know what layers do you need, you can load the model with top and without top, call model.summary() method and see, how do they differ:
To add layers I use TensorFlow Functional API. Of course, you need some knowledge about TensorFlow and CNN, but you also can try to add different layers and get non-original architecture. In my case, we need a global average pooling layer and dense layer. Don’t forget to freeze other weights beforehand.
After that, we continue to configure the model. I added a ModelCheckpoint object to save the model on the disk if something goes wrong and also EarlyStopping as a regularization technique. As an optimization method, I used Adam with a standard learning rate value. I also tried using various scheduling techniques, but they did not bring many results.
So now we can start the training process. After it’s over you will have a ready-to-use model. You can check its functionality with the Testing section code in me_not_me_classifier.ipynb file.
Now we have to use OpenCV library for web camera access and face detection.
Frankly speaking, the phrase “transform classifier into detector” is incorrect because of the definitions of the classifier and detector. A classifier (understood as an image classifier) is a model that receives an image as an input, and at the output gives a label of one of the possible classes (in our case, me or not_me). A detector (understood as a face detector) is a model that receives an image as an input and outputs the coordinates of the bounding box around faces if there are faces in this picture.
I use this phrase to show that the final program (which continues to be a classifier) now also gives out exactly where the face is in the picture. In addition, now it can work correctly in the case when there are several faces in the photo at once.
Training a face detector is a very difficult task (mainly due to the fact that the data is difficult to label), so I will use the face detector provided by OpenCV. It is very simple to use. In the code below, the faces variable is an array of all the faces in the image. For each face, there are four values for the bounding box:
x — x coordinate of the upper-left corner,
y — y coordinate of the upper-left corner,
w — width of the bounding box,
h — height of the bounding box.
The following code highlights your face in the webcam image in real-time, as shown in the image below.
Now all that remains is to load the pretrained model, pass it the fragment of the image where the face is located, and display the text on the screen! In fact, at this stage I faced a small difficulty — the model recognized me only sometimes. This happened because I trained her on images “with a margin”, where not only the face was located.
I could add images with a different scale to the dataset, but I decided to do it honestly. To do this, I wrote the function get_extended_image(), which increases the size of the cropped image with a certain coefficient k. The larger the k, the larger the area around the face. To explain the operation of this function (or to confuse you even more), I give the following image (for simplicity, here k = 0.3. The scale is not observed. Note, that the upper left coordinate is (0, 0)). You can also see clippings of my face with different k parameters (according to the OpenCV, it uses a BGR instead of RGB, but instead of adjusting the color, let’s imagine that I am an avatar). For the resulting model, I used k = 0.5.
I want to note that I used MobileNet as a base model. Initially, I used ResNet50, because it showed the best quality, but the image lagged a little, and there are no such problems with the lighter MobileNet. I tested all this on a computer with an i7–10750H and 32G RAM.
That’s it! You can find the finished code in the me_not_me_detector.ipynb notebook, but note that to use it, you need to have a model in the models folder, otherwise you will get an error in the load the model cell. Here is the result.
I must say that although the model is quite simple, it already recognizes me well, for example, if part of the face is covered. Also, I don’t have a photo of Willem Dafoe in the dataset, so the model hasn’t seen him before.
What about face in mask recognition — you can see that if my nose is fully covered, the program stops recognizing my face (or when it is rotated too much). But this is a problem on the detector side because it stops transmitting the image to the model. That is because OpenCV face detectors usually don’t see people in masks. But I suppose that if you can collect a large dataset, you can also teach your model to distinguish people in masks.
What surprised me — it is easier for the model to recognize me when the lower part of the face is covered than the upper part. You can see that when I put on a hat or cover my forehead with my hand, the model begins to doubt. I think this is due to the fact that in all the photos I have my head is open and I have about one hairstyle.
Below I present the results of training different models with or without data augmentation (x5 data augmentation in this case). The best quality (99% validation accuracy) was shown by ResNet50. But as I said above, I used a model based on MobileNet, because it showed itself well in real-time operation.
These results show that data augmentation can significantly increase the quality of the model. In this case validation loss drops 10 times but this is about the very little dataset. I tried to generate more images and got more accuracy. This parameter (the coefficient of the dataset increasing — so the number of augmented images generated for each image) can be chosen with cross-validation. The best model I got among MobileNet’s was one with validation loss = 0.09886 and validation accuracy = 0.9589, and coefficient of the dataset increasing = 15.
At the same time, the learning process became dramatically slower. It makes sense, dataset size increases, and learning time increases too. You can see the plot of the dependence of the training time on the size of the dataset below — it is almost linear.
The next table is the extended version of the previous. Here you can see the number of parameters, depth of the model, and test accuracy. Note that layers are counted as the number of model.layers objects, which is not quite correct, but gives an idea of the depth of the models. Test accuracy doesn’t have a lot of statistical power, because I had only 20 test images.
One thing about VGG. I replaced two 4096 dense layers with two 1024 dense layers, and the model showed approximately the same result, although the number of parameters fell in three times (from 134 million to 41 million, and the trainable — from 119 million to 27 million). The size on the disk is 368 MB for this model.
From the work done, I can make the following conclusions. Some of them are more obvious, some of them are less:
The dataset that you need to collect should be as diverse as possible and at the same time as similar as possible to real data.
More simple models are training faster, making predictions faster and taking less place on the hard disk. More simple models have fewer parameters, but, at the same time, can be deeper.
Transfer Learning is a very powerful technique that allows you to solve your task even with a tiny dataset.
Data Augmentation technique allows you to significantly increase the quality of your models, but it also increases training time. You can choose a data augmentation coefficient with cross-validation.
The result strongly depends on random initialization. Therefore, even the training process with the same parameters should be run several times. For example, in 22 minutes and 150 epochs, I got the result 0.1334 for validation loss with ResNet50 without data augmentation, which is 39% better than regular ResNet50.
Now I will say one more phrase that will confuse you even more.
The convolutional part of the network (up to dense layers) transforms the original image into a point in some high-dimensional space (this is similar to the concept of embedding), and dense layers then build a separating hyperplane in this space.
So, it is better to build a model that will better locate these points, and then you can do with a more simple classifier. Of course, the rules by which these representations are built are very complex, which is why we need deep models with a large number of parameters.
A network that creates embeddings well can solve tasks for which it was not originally trained. So, a good model will locate all my photos close to each other (in some high-dimensional space) and all Willem Dafoe’s photos close to each other. But at the same time, these two clouds of points should be located far apart. Now, when you show a network a photo of another person, it will be able to say that it is not_me, but in addition, it will be able to give out the person he most resembles or note that this person was not in the dataset. This is a variation of Metric Learning, Triplet Loss is used here.
I hope these materials were useful to you. Follow me on Medium to get more articles like this.
If you have any questions or comments, I will be glad to get any feedback. Ask me in the comments, or connect via LinkedIn or Twitter.
To support me as a writer and to get access to thousands of other Medium articles, get Medium membership using my referral link (no extra charge for you). | [
{
"code": null,
"e": 287,
"s": 172,
"text": "In this article, I will show you how to write a real-time face detector using Python, TensorFlow/Keras and OpenCV."
},
{
"code": null,
"e": 357,
"s": 287,
"text": "I’ll note right away, that all code files are available in this repo."
},
{
"code": null,
"e": 368,
"s": 357,
"text": "gitlab.com"
},
{
"code": null,
"e": 580,
"s": 368,
"text": "First, in Theoretical Part I will tell you a little about the concepts that will be useful for us (Transfer Learning and Data Augmentation), and then I will go to the code analysis in the Practical Part section."
},
{
"code": null,
"e": 873,
"s": 580,
"text": "Note, that you must have TensorFlow and OpenCV libraries installed to run this code. You can do it manually or simply run pip install -r requirements.txt command after you have the repo downloaded. You can also do it with conda commands conda install -c conda-forge numpy, opencv, tensorflow."
},
{
"code": null,
"e": 1021,
"s": 873,
"text": "Here I want to build a face detector that also can distinguish me from other people. You can see the results of my work at the end of this article."
},
{
"code": null,
"e": 1072,
"s": 1021,
"text": "The initial task can be divided into two subtasks:"
},
{
"code": null,
"e": 1163,
"s": 1072,
"text": "Train a model for face classification.Adapt the model to work with a webcam as a detector."
},
{
"code": null,
"e": 1202,
"s": 1163,
"text": "Train a model for face classification."
},
{
"code": null,
"e": 1255,
"s": 1202,
"text": "Adapt the model to work with a webcam as a detector."
},
{
"code": null,
"e": 1322,
"s": 1255,
"text": "In more detail, the task can be divided into the following stages:"
},
{
"code": null,
"e": 1437,
"s": 1322,
"text": "Dataset Collection.Search for a Base Model for Transfer Learning.Train a Model.Transform Classifier into Detector."
},
{
"code": null,
"e": 1457,
"s": 1437,
"text": "Dataset Collection."
},
{
"code": null,
"e": 1504,
"s": 1457,
"text": "Search for a Base Model for Transfer Learning."
},
{
"code": null,
"e": 1519,
"s": 1504,
"text": "Train a Model."
},
{
"code": null,
"e": 1555,
"s": 1519,
"text": "Transform Classifier into Detector."
},
{
"code": null,
"e": 1673,
"s": 1555,
"text": "Before I begin to analyze these stages, I would like to very briefly outline the concepts that will be useful for us."
},
{
"code": null,
"e": 2197,
"s": 1673,
"text": "At this point, I must say that this tutorial is not as detailed as it could be. For example, I will not explain what convolution is or why pooling layers are needed in CNN architecture. Of course, you need to know this to understand how CNN works, but I think that this tutorial will be too cumbersome if I explain all the concepts. On the other hand, other people have already explained many things and did it better than me. For example, here you can read about CNN in general, and here — about popular CNN architectures."
},
{
"code": null,
"e": 2362,
"s": 2197,
"text": "Since we are talking about image recognition, we will use CNN — Convolutional Neural Networks, the architecture that has achieved the greatest success in this task."
},
{
"code": null,
"e": 2464,
"s": 2362,
"text": "Unlike classical neural networks (here I mean FDN — Feedforward Neural Network), in CNN, neurons are:"
},
{
"code": null,
"e": 2530,
"s": 2464,
"text": "firstly: arranged in the form of a matrix (tensor), not an array,"
},
{
"code": null,
"e": 2657,
"s": 2530,
"text": "and secondly: they are connected only with a small number of neurons of the previous layer, so layers are NOT fully connected."
},
{
"code": null,
"e": 2800,
"s": 2657,
"text": "This approach allows you to significantly reduce the number of network parameters and make the search for templates more efficient for images."
},
{
"code": null,
"e": 3210,
"s": 2800,
"text": "At the bottom of this image, I want to explain that the layer in CNN is a tensor (it is often drawn as a parallelepiped). I will talk about a tensor as a sequence of matrices. So each of these tensors is just a series of matrices standing on top of each other like pizza boxes. In turn, matrices are simply a sequence of neurons that are arranged in the form of a matrix, not an array, as in classic networks."
},
{
"code": null,
"e": 3440,
"s": 3210,
"text": "Transfer Learning is the most important concept for this task since it is very difficult (almost impossible) to build a face classifier from scratch. Transfer Learning is the process of using a pretrained model for your own task."
},
{
"code": null,
"e": 3870,
"s": 3440,
"text": "This happens as follows. You find a model that is trained for a similar task (for example, recognizing 1000 classes of images, as in ImageNet, when you need to recognize only a few). Then you use its weights (freeze them, which means that they will not change), and finish training the model on your small dataset. After that, you can also unfreeze all the weights and continue training the model with a very small learning rate."
},
{
"code": null,
"e": 4281,
"s": 3870,
"text": "This process becomes possible due to the features of the CNN architecture and the image recognition task (but also can be used with different architectures). The network learns to see patterns from layer to layer (from input to output) and they are getting more and more complicated. It turns out that the general patterns for all problems are approximately the same, which allows us to use pretrained weights."
},
{
"code": null,
"e": 4736,
"s": 4281,
"text": "Another important concept in the image classification problem is data augmentation. Data augmentation is the process of artificially increasing a dataset size by applying some transformations to the original images. For example, we can use horizontal and vertical reflection, small rotation or magnification, color inversion, and so on. This will significantly increase the size of the dataset and, accordingly, the generalization ability of the network."
},
{
"code": null,
"e": 4759,
"s": 4736,
"text": "towardsdatascience.com"
},
{
"code": null,
"e": 5160,
"s": 4759,
"text": "In the example above (first image in the article), when the shift values are quite high, sometimes there is a situation when only part of the image is visible. On the one hand, this is good (the network can learn to recognize a cat not by its muzzle, but by its paws and tail in the case of images where the head is not visible), but it can also confuse the network if you overdo such transformation."
},
{
"code": null,
"e": 5676,
"s": 5160,
"text": "There are several approaches to data augmentation in TensorFlow. We can generate images and save them to disk, or we can feed the generator directly to the network. I chose the first option, to do it more explicitly. But there are two ways here as well: generate a random number of images or generate several versions of a specific image. You can see the implementation of both options in the data_augmentation.ipynb notebook. I used the second option and specifically generated five transformations for each image."
},
{
"code": null,
"e": 5717,
"s": 5676,
"text": "The project has the following structure:"
},
{
"code": null,
"e": 6415,
"s": 5717,
"text": "me_not_me_detector├───article├───datasets│ ├───face_dataset_test_images│ │ ├───me # contains TEST images for ME class│ │ └───not_me # contains TEST images for NOT_ME class│ ├───face_dataset_train_aug_images (optional)│ │ ├───me # contains aug TRAIN images for ME class│ │ └───not_me # contains aug TRAIN images for NOT_ME class│ └───face_dataset_train_images│ ├───me # contains TRAIN images for ME class│ └───not_me # contains TRAIN images for NOT_ME class├───models│ .gitignore│ data_augmentation.ipynb│ me_not_me_classifier.ipynb│ me_not_me_classifier_model_comparison.ipynb│ me_not_me_detector.ipynb│ README.md└── requirements.txt"
},
{
"code": null,
"e": 6441,
"s": 6415,
"text": "Let’s talk about folders."
},
{
"code": null,
"e": 6497,
"s": 6441,
"text": "The article folder contains the data for this tutorial."
},
{
"code": null,
"e": 6570,
"s": 6497,
"text": "The modelsfolder contains trained models for their test and further use."
},
{
"code": null,
"e": 6833,
"s": 6570,
"text": "The datasets folder contains three folders - for a train set, test set and augmented train set (optional). Each of them contains two subfolders for two classes - me and not_me. In the general case, it contains N subfolders for the N-class classification problem."
},
{
"code": null,
"e": 6890,
"s": 6833,
"text": "Now let’s talk about the code files — jupyter notebooks."
},
{
"code": null,
"e": 7016,
"s": 6890,
"text": "data_augmentation.ipynbfile creates an augmented dataset from an initial one and provides some information about the dataset."
},
{
"code": null,
"e": 7119,
"s": 7016,
"text": "me_not_me_classifier_model_comparison.ipynbfile contains code to train and test five different models."
},
{
"code": null,
"e": 7260,
"s": 7119,
"text": "me_not_me_classifier.ipynbfile does the same thing, but for one particular model. You can use it as an example to build your own classifier."
},
{
"code": null,
"e": 7365,
"s": 7260,
"text": "me_not_me_detector.ipynbfile uses the OpenCV library and turns the classifier into a real-time detector."
},
{
"code": null,
"e": 7407,
"s": 7365,
"text": "Other files are used as additional files:"
},
{
"code": null,
"e": 7465,
"s": 7407,
"text": ".gitignore contains files that will not be pushed in git,"
},
{
"code": null,
"e": 7562,
"s": 7465,
"text": "requirements.txt contains the list of libraries that have to be installed to run this code, etc."
},
{
"code": null,
"e": 7847,
"s": 7562,
"text": "First of all, we need to collect a dataset. I used my photos and photos of my family to train the model, but you can also train the model on some other face datasets. I used only personal photos to check whether such a small dataset is enough for the model to show acceptable quality."
},
{
"code": null,
"e": 8047,
"s": 7847,
"text": "I cropped the face from each photo and resized them to the size of 250x250 (which you don’t have to do, since TensorFlow can do it for you). Here are some examples of photos from the initial dataset:"
},
{
"code": null,
"e": 8117,
"s": 8047,
"text": "In total, I collected 215 photos, where 82 are me and 133 are not_me."
},
{
"code": null,
"e": 8480,
"s": 8117,
"text": "For the test set, I immediately put aside 20 photos. This can be done automatically, but I did it manually because the dataset is too small. For the train set, I applied my data augmentation code from data_augmentation.ipynbnotebook. Thus, the dataset increased five times! (five photos were generated for each photo). Here is an example of the generated photos:"
},
{
"code": null,
"e": 8540,
"s": 8480,
"text": "When the dataset is ready, we can start training the model."
},
{
"code": null,
"e": 8829,
"s": 8540,
"text": "There is nothing complicated here — I just used different models that are trained on the ImageNet dataset. If they don’t have good accuracy, then I think I will use something like VGGFace models like here. But the quality I got is good enough. We can load pretrained model with this code:"
},
{
"code": null,
"e": 8945,
"s": 8829,
"text": "Now we have to freeze these weights, add some layers on top of the model and train the model on our little dataset."
},
{
"code": null,
"e": 9205,
"s": 8945,
"text": "As I said earlier, me_not_me_classifier_model_comparison.ipynbfile contains the code for different models. You can use it to do your own experiment. Code examples below are taken from me_not_me_classifier.ipynb. We will use ResNet50 as the initial model here."
},
{
"code": null,
"e": 9569,
"s": 9205,
"text": "After import libraries and dataset loading, we load pretrained model exactly as in the code above. After that, we need to restore the top of the model — the dense part. Note, that this part is different for different models. To know what layers do you need, you can load the model with top and without top, call model.summary() method and see, how do they differ:"
},
{
"code": null,
"e": 9874,
"s": 9569,
"text": "To add layers I use TensorFlow Functional API. Of course, you need some knowledge about TensorFlow and CNN, but you also can try to add different layers and get non-original architecture. In my case, we need a global average pooling layer and dense layer. Don’t forget to freeze other weights beforehand."
},
{
"code": null,
"e": 10226,
"s": 9874,
"text": "After that, we continue to configure the model. I added a ModelCheckpoint object to save the model on the disk if something goes wrong and also EarlyStopping as a regularization technique. As an optimization method, I used Adam with a standard learning rate value. I also tried using various scheduling techniques, but they did not bring many results."
},
{
"code": null,
"e": 10418,
"s": 10226,
"text": "So now we can start the training process. After it’s over you will have a ready-to-use model. You can check its functionality with the Testing section code in me_not_me_classifier.ipynb file."
},
{
"code": null,
"e": 10494,
"s": 10418,
"text": "Now we have to use OpenCV library for web camera access and face detection."
},
{
"code": null,
"e": 11006,
"s": 10494,
"text": "Frankly speaking, the phrase “transform classifier into detector” is incorrect because of the definitions of the classifier and detector. A classifier (understood as an image classifier) is a model that receives an image as an input, and at the output gives a label of one of the possible classes (in our case, me or not_me). A detector (understood as a face detector) is a model that receives an image as an input and outputs the coordinates of the bounding box around faces if there are faces in this picture."
},
{
"code": null,
"e": 11255,
"s": 11006,
"text": "I use this phrase to show that the final program (which continues to be a classifier) now also gives out exactly where the face is in the picture. In addition, now it can work correctly in the case when there are several faces in the photo at once."
},
{
"code": null,
"e": 11585,
"s": 11255,
"text": "Training a face detector is a very difficult task (mainly due to the fact that the data is difficult to label), so I will use the face detector provided by OpenCV. It is very simple to use. In the code below, the faces variable is an array of all the faces in the image. For each face, there are four values for the bounding box:"
},
{
"code": null,
"e": 11628,
"s": 11585,
"text": "x — x coordinate of the upper-left corner,"
},
{
"code": null,
"e": 11671,
"s": 11628,
"text": "y — y coordinate of the upper-left corner,"
},
{
"code": null,
"e": 11702,
"s": 11671,
"text": "w — width of the bounding box,"
},
{
"code": null,
"e": 11734,
"s": 11702,
"text": "h — height of the bounding box."
},
{
"code": null,
"e": 11837,
"s": 11734,
"text": "The following code highlights your face in the webcam image in real-time, as shown in the image below."
},
{
"code": null,
"e": 12180,
"s": 11837,
"text": "Now all that remains is to load the pretrained model, pass it the fragment of the image where the face is located, and display the text on the screen! In fact, at this stage I faced a small difficulty — the model recognized me only sometimes. This happened because I trained her on images “with a margin”, where not only the face was located."
},
{
"code": null,
"e": 12899,
"s": 12180,
"text": "I could add images with a different scale to the dataset, but I decided to do it honestly. To do this, I wrote the function get_extended_image(), which increases the size of the cropped image with a certain coefficient k. The larger the k, the larger the area around the face. To explain the operation of this function (or to confuse you even more), I give the following image (for simplicity, here k = 0.3. The scale is not observed. Note, that the upper left coordinate is (0, 0)). You can also see clippings of my face with different k parameters (according to the OpenCV, it uses a BGR instead of RGB, but instead of adjusting the color, let’s imagine that I am an avatar). For the resulting model, I used k = 0.5."
},
{
"code": null,
"e": 13170,
"s": 12899,
"text": "I want to note that I used MobileNet as a base model. Initially, I used ResNet50, because it showed the best quality, but the image lagged a little, and there are no such problems with the lighter MobileNet. I tested all this on a computer with an i7–10750H and 32G RAM."
},
{
"code": null,
"e": 13406,
"s": 13170,
"text": "That’s it! You can find the finished code in the me_not_me_detector.ipynb notebook, but note that to use it, you need to have a model in the models folder, otherwise you will get an error in the load the model cell. Here is the result."
},
{
"code": null,
"e": 13630,
"s": 13406,
"text": "I must say that although the model is quite simple, it already recognizes me well, for example, if part of the face is covered. Also, I don’t have a photo of Willem Dafoe in the dataset, so the model hasn’t seen him before."
},
{
"code": null,
"e": 14073,
"s": 13630,
"text": "What about face in mask recognition — you can see that if my nose is fully covered, the program stops recognizing my face (or when it is rotated too much). But this is a problem on the detector side because it stops transmitting the image to the model. That is because OpenCV face detectors usually don’t see people in masks. But I suppose that if you can collect a large dataset, you can also teach your model to distinguish people in masks."
},
{
"code": null,
"e": 14409,
"s": 14073,
"text": "What surprised me — it is easier for the model to recognize me when the lower part of the face is covered than the upper part. You can see that when I put on a hat or cover my forehead with my hand, the model begins to doubt. I think this is due to the fact that in all the photos I have my head is open and I have about one hairstyle."
},
{
"code": null,
"e": 14713,
"s": 14409,
"text": "Below I present the results of training different models with or without data augmentation (x5 data augmentation in this case). The best quality (99% validation accuracy) was shown by ResNet50. But as I said above, I used a model based on MobileNet, because it showed itself well in real-time operation."
},
{
"code": null,
"e": 15267,
"s": 14713,
"text": "These results show that data augmentation can significantly increase the quality of the model. In this case validation loss drops 10 times but this is about the very little dataset. I tried to generate more images and got more accuracy. This parameter (the coefficient of the dataset increasing — so the number of augmented images generated for each image) can be chosen with cross-validation. The best model I got among MobileNet’s was one with validation loss = 0.09886 and validation accuracy = 0.9589, and coefficient of the dataset increasing = 15."
},
{
"code": null,
"e": 15523,
"s": 15267,
"text": "At the same time, the learning process became dramatically slower. It makes sense, dataset size increases, and learning time increases too. You can see the plot of the dependence of the training time on the size of the dataset below — it is almost linear."
},
{
"code": null,
"e": 15893,
"s": 15523,
"text": "The next table is the extended version of the previous. Here you can see the number of parameters, depth of the model, and test accuracy. Note that layers are counted as the number of model.layers objects, which is not quite correct, but gives an idea of the depth of the models. Test accuracy doesn’t have a lot of statistical power, because I had only 20 test images."
},
{
"code": null,
"e": 16214,
"s": 15893,
"text": "One thing about VGG. I replaced two 4096 dense layers with two 1024 dense layers, and the model showed approximately the same result, although the number of parameters fell in three times (from 134 million to 41 million, and the trainable — from 119 million to 27 million). The size on the disk is 368 MB for this model."
},
{
"code": null,
"e": 16326,
"s": 16214,
"text": "From the work done, I can make the following conclusions. Some of them are more obvious, some of them are less:"
},
{
"code": null,
"e": 16454,
"s": 16326,
"text": "The dataset that you need to collect should be as diverse as possible and at the same time as similar as possible to real data."
},
{
"code": null,
"e": 16640,
"s": 16454,
"text": "More simple models are training faster, making predictions faster and taking less place on the hard disk. More simple models have fewer parameters, but, at the same time, can be deeper."
},
{
"code": null,
"e": 16748,
"s": 16640,
"text": "Transfer Learning is a very powerful technique that allows you to solve your task even with a tiny dataset."
},
{
"code": null,
"e": 16948,
"s": 16748,
"text": "Data Augmentation technique allows you to significantly increase the quality of your models, but it also increases training time. You can choose a data augmentation coefficient with cross-validation."
},
{
"code": null,
"e": 17264,
"s": 16948,
"text": "The result strongly depends on random initialization. Therefore, even the training process with the same parameters should be run several times. For example, in 22 minutes and 150 epochs, I got the result 0.1334 for validation loss with ResNet50 without data augmentation, which is 39% better than regular ResNet50."
},
{
"code": null,
"e": 17328,
"s": 17264,
"text": "Now I will say one more phrase that will confuse you even more."
},
{
"code": null,
"e": 17575,
"s": 17328,
"text": "The convolutional part of the network (up to dense layers) transforms the original image into a point in some high-dimensional space (this is similar to the concept of embedding), and dense layers then build a separating hyperplane in this space."
},
{
"code": null,
"e": 17846,
"s": 17575,
"text": "So, it is better to build a model that will better locate these points, and then you can do with a more simple classifier. Of course, the rules by which these representations are built are very complex, which is why we need deep models with a large number of parameters."
},
{
"code": null,
"e": 18455,
"s": 17846,
"text": "A network that creates embeddings well can solve tasks for which it was not originally trained. So, a good model will locate all my photos close to each other (in some high-dimensional space) and all Willem Dafoe’s photos close to each other. But at the same time, these two clouds of points should be located far apart. Now, when you show a network a photo of another person, it will be able to say that it is not_me, but in addition, it will be able to give out the person he most resembles or note that this person was not in the dataset. This is a variation of Metric Learning, Triplet Loss is used here."
},
{
"code": null,
"e": 18550,
"s": 18455,
"text": "I hope these materials were useful to you. Follow me on Medium to get more articles like this."
},
{
"code": null,
"e": 18685,
"s": 18550,
"text": "If you have any questions or comments, I will be glad to get any feedback. Ask me in the comments, or connect via LinkedIn or Twitter."
}
] |
How can we implement a custom iterable in Java? | An Iterable interface is defined in java.lang package and introduced with Java 5 version. An object that implements this interface allows it to be the target of the "for-each" statement. This for-each loop is used for iterating over arrays and collections. An Iterable interface can also be implemented to create custom behavior.
public interface Iterable<T>
import static java.lang.String.format;
import java.util.*;
// Person class
class Person {
private String firstName, lastName;
private int age;
public Person(){ }
public Person(String firstName, String lastName, int age) {
this.firstName = firstName;
this.lastName = lastName;
this.age = age;
}
public String getFirstName() {
return firstName;
}
public String getLastName() {
return lastName;
}
public int getAge() {
return age;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
public void setAge(int age) {
this.age = age;
}
@Override
public String toString() {
return format("First Name:\t%s\tLast Name:\t%s\tAge:\t%d", firstName, lastName, age);
}
}
// PersonArrayList class
public class PersonArrayList implements Iterable<Person> {
private List<Person> persons;
private static final int MIN_AGE = 10;
public PersonArrayList() {
persons = new ArrayList<Person>(MIN_AGE);
}
public PersonArrayList(int age) {
persons = new ArrayList<Person>(age);
}
public void addPerson(Person p) {
persons.add(p);
}
public void removePerson(Person p) {
persons.remove(p);
}
public int age() {
return persons.size();
}
@Override
public Iterator<Person> iterator() {
return persons.iterator();
}
public static void main(String[] args) {
Person p1 = new Person("Adithya", "Sai", 20);
Person p2 = new Person("Jai","Dev", 30);
PersonArrayList pList = new PersonArrayList();
pList.addPerson(p1);
pList.addPerson(p2);
for (Person person : pList) {
System.out.println(person);
}
}
}
First Name: Adithya Last Name: Sai Age: 20
First Name: Jai Last Name: Dev Age: 30 | [
{
"code": null,
"e": 1392,
"s": 1062,
"text": "An Iterable interface is defined in java.lang package and introduced with Java 5 version. An object that implements this interface allows it to be the target of the \"for-each\" statement. This for-each loop is used for iterating over arrays and collections. An Iterable interface can also be implemented to create custom behavior."
},
{
"code": null,
"e": 1421,
"s": 1392,
"text": "public interface Iterable<T>"
},
{
"code": null,
"e": 3239,
"s": 1421,
"text": "import static java.lang.String.format;\nimport java.util.*;\n// Person class\nclass Person {\n private String firstName, lastName;\n private int age;\n public Person(){ }\n public Person(String firstName, String lastName, int age) {\n this.firstName = firstName;\n this.lastName = lastName;\n this.age = age;\n }\n public String getFirstName() {\n return firstName;\n }\n public String getLastName() {\n return lastName;\n }\n public int getAge() {\n return age;\n }\n public void setFirstName(String firstName) {\n this.firstName = firstName;\n }\n public void setLastName(String lastName) {\n this.lastName = lastName;\n }\n public void setAge(int age) {\n this.age = age;\n }\n @Override\n public String toString() {\n return format(\"First Name:\\t%s\\tLast Name:\\t%s\\tAge:\\t%d\", firstName, lastName, age);\n }\n}\n// PersonArrayList class\npublic class PersonArrayList implements Iterable<Person> {\n private List<Person> persons;\n private static final int MIN_AGE = 10;\n public PersonArrayList() {\n persons = new ArrayList<Person>(MIN_AGE);\n }\n public PersonArrayList(int age) {\n persons = new ArrayList<Person>(age);\n }\n public void addPerson(Person p) {\n persons.add(p);\n }\n public void removePerson(Person p) {\n persons.remove(p);\n }\n public int age() {\n return persons.size();\n }\n @Override\n public Iterator<Person> iterator() {\n return persons.iterator();\n }\n public static void main(String[] args) {\n Person p1 = new Person(\"Adithya\", \"Sai\", 20);\n Person p2 = new Person(\"Jai\",\"Dev\", 30);\n PersonArrayList pList = new PersonArrayList();\n pList.addPerson(p1);\n pList.addPerson(p2);\n for (Person person : pList) {\n System.out.println(person);\n }\n }\n}"
},
{
"code": null,
"e": 3343,
"s": 3239,
"text": "First Name: Adithya Last Name: Sai Age: 20\nFirst Name: Jai Last Name: Dev Age: 30"
}
] |
Perl kill Function | This function sends a signal to a list of processes. Returns the number of processes successfully signaled.
If SIGNAL is zero, no signal is sent to the process. This is a useful way to check that a child process is alive and hasn't changed its UID. The precise list of signals supported is entirely dependent on the system implementation −
Name Effect
SIGABRT Aborts the process
SIGARLM Alarm signal
SIGFPE Arithmetic exception
SIGHUP Hang up.
SIGILL Illegal instruction
SIGINT Interrupt
SIGKILL Termination signal
SIGPIPE Write to a pipe with no readers.
SIGQUIT Quit signal.
SIGSEGV Segmentation fault
SIGTERM Termination signal
SIGUSER1 Application-defined signal 1
SIGUSER2 Application-defined signal 2
Following is the simple syntax for this function −
kill EXPR, LIST
This function returns the number of processes successfully signaled.
Following is the example code showing its basic usage −
#!/usr/bin/perl
$cnt = kill 0, getppid(), getpgrp(), 2000;
print "Signal sent to $cnt process\n";
When above code is executed, it produces the following result −
Signal sent to 2 process
46 Lectures
4.5 hours
Devi Killada
11 Lectures
1.5 hours
Harshit Srivastava
30 Lectures
6 hours
TELCOMA Global
24 Lectures
2 hours
Mohammad Nauman
68 Lectures
7 hours
Stone River ELearning
58 Lectures
6.5 hours
Stone River ELearning
Print
Add Notes
Bookmark this page | [
{
"code": null,
"e": 2328,
"s": 2220,
"text": "This function sends a signal to a list of processes. Returns the number of processes successfully signaled."
},
{
"code": null,
"e": 2560,
"s": 2328,
"text": "If SIGNAL is zero, no signal is sent to the process. This is a useful way to check that a child process is alive and hasn't changed its UID. The precise list of signals supported is entirely dependent on the system implementation −"
},
{
"code": null,
"e": 2951,
"s": 2560,
"text": "Name \t\t Effect\nSIGABRT\t\tAborts the process\nSIGARLM\t\tAlarm signal\nSIGFPE\t\tArithmetic exception\nSIGHUP \t\tHang up.\nSIGILL \t\tIllegal instruction\nSIGINT \t\tInterrupt\nSIGKILL \t Termination signal\nSIGPIPE \t Write to a pipe with no readers.\nSIGQUIT\t\tQuit signal.\nSIGSEGV\t\tSegmentation fault\nSIGTERM\t\tTermination signal\nSIGUSER1\t Application-defined signal 1\nSIGUSER2\t Application-defined signal 2\n"
},
{
"code": null,
"e": 3002,
"s": 2951,
"text": "Following is the simple syntax for this function −"
},
{
"code": null,
"e": 3019,
"s": 3002,
"text": "kill EXPR, LIST\n"
},
{
"code": null,
"e": 3088,
"s": 3019,
"text": "This function returns the number of processes successfully signaled."
},
{
"code": null,
"e": 3144,
"s": 3088,
"text": "Following is the example code showing its basic usage −"
},
{
"code": null,
"e": 3244,
"s": 3144,
"text": "#!/usr/bin/perl\n\n$cnt = kill 0, getppid(), getpgrp(), 2000;\n\nprint \"Signal sent to $cnt process\\n\";"
},
{
"code": null,
"e": 3308,
"s": 3244,
"text": "When above code is executed, it produces the following result −"
},
{
"code": null,
"e": 3334,
"s": 3308,
"text": "Signal sent to 2 process\n"
},
{
"code": null,
"e": 3369,
"s": 3334,
"text": "\n 46 Lectures \n 4.5 hours \n"
},
{
"code": null,
"e": 3383,
"s": 3369,
"text": " Devi Killada"
},
{
"code": null,
"e": 3418,
"s": 3383,
"text": "\n 11 Lectures \n 1.5 hours \n"
},
{
"code": null,
"e": 3438,
"s": 3418,
"text": " Harshit Srivastava"
},
{
"code": null,
"e": 3471,
"s": 3438,
"text": "\n 30 Lectures \n 6 hours \n"
},
{
"code": null,
"e": 3487,
"s": 3471,
"text": " TELCOMA Global"
},
{
"code": null,
"e": 3520,
"s": 3487,
"text": "\n 24 Lectures \n 2 hours \n"
},
{
"code": null,
"e": 3537,
"s": 3520,
"text": " Mohammad Nauman"
},
{
"code": null,
"e": 3570,
"s": 3537,
"text": "\n 68 Lectures \n 7 hours \n"
},
{
"code": null,
"e": 3593,
"s": 3570,
"text": " Stone River ELearning"
},
{
"code": null,
"e": 3628,
"s": 3593,
"text": "\n 58 Lectures \n 6.5 hours \n"
},
{
"code": null,
"e": 3651,
"s": 3628,
"text": " Stone River ELearning"
},
{
"code": null,
"e": 3658,
"s": 3651,
"text": " Print"
},
{
"code": null,
"e": 3669,
"s": 3658,
"text": " Add Notes"
}
] |
Drillthrough like a PRO in Power BI | by Nikola Ilic | Towards Data Science | I must admit that the Power BI development team does really awesome job! Every month (or even less, like in these April and May Power BI Desktop update), they are going above and beyond and introducing fantastic new features.
In March 2020, Microsoft announced Page Navigation as an action for buttons as generally available and at the same time introduced Drillthrough action for buttons as a preview feature. It sounded really appealing to me since I have a lot of users who are not aware of “right-click” Drillthrough capability, so I had to create different workarounds, such as tooltips, in order to engage users to use Drillthrough in the reports.
With new Drillthrough action for buttons now generally available, let’s try to make full use and offer our users unforgettable experience...
As usual, I will use the Contoso sample database for demonstration. Before proceeding further, another very interesting feature related to buttons is that now you can customize button for Disabled state (until now, you were able to customize button for Default, On Hover and On Press states).
Let’s see how this works in reality:
I’ve added a blank button and formatted it for Disabled state (grey color).
Next thing I do, because I have multiple Drillthrough pages within my report, I am giving my users a possibility of what kind of details they would like to see. In my example, they can choose to see “Sales Amount per Brand” or “Sales Amount per Color”.
To achieve this, I need to create a new table which will hold data about drillthrough pages. Go to Enter data under Data ribbon and simply enter names of your drillthrough pages (it is of key importance that values in the table exactly match your drillthrough pages’ names). I’ve also added a column for ranking, just in case I want to sort pages in a different order than alphabetically.
Now, just drag slicer on the canvas and put Page name column in the Field value. One more little trick to improve user’s experience: depending on the user’s selection, we want to dynamically adjust the text on the button which will be used for Drillthrough action.
Therefore, I’ve created a simple DAX measure, which captures the user’s selection:
Selected Page = "Open "& SELECTEDVALUE('Pages DT'[Page])
This will dynamically change the text on the button:
To achieve that, under formatting options of the button, choose Button Text and select option on the right:
Choose to format by Field Value and select our newly created measure, Selected Page.
The next step is to instruct our button on what to do, depending on the user’s selection. Go to Action property of the button, again choose the option on the right and select Page under the “Based on field” dropdown menu and leave default First as Summarization type. Since we defined user selection to one value exclusively within a slicer (by turning Single Select ON), we don’t need to worry — whatever user selects, this will be first (and only) selection...
One last thing to do is to format button Fill property, so the user can recognize when it is ready for drilling down. As I mentioned previously, the button is greyed out in the Disabled state. But, as soon as I choose a single data point from my table, look at what will happen!
Our button becomes blue and now the user can interact with it and click on it in order to be navigated to a drillthrough page, which contains details about the Sales Amount for June 2009. How cool is that!
Once we go back to the main page and select Sales Amt Color under Drillthrough Page slicer, the button goes back to Disabled state and we will be informed that we need to select one single brand if we want to drill through to a page which contains data per brand color.
So, let’s check how it works:
I’ve chosen the Adventure Works brand within Sales Amt by Brand Name visual and my button is ready for action again! Once I click on it, I will be navigated to a page which displays data per product color for Adventure Works brand:
Same as in the previous example, as soon as I’m back on the main page, the button again becomes greyed out.
To summarize, here is the complete behavior of our button:
With dynamic formatting of the buttons and tweaking actions to enable usage of different drillthrough pages, you can really create an awesome user experience for your Power BI reports, avoiding the complexity of working with multiple bookmarks.
Become a member and read every story on Medium!
Subscribe here to get more insightful data articles! | [
{
"code": null,
"e": 397,
"s": 171,
"text": "I must admit that the Power BI development team does really awesome job! Every month (or even less, like in these April and May Power BI Desktop update), they are going above and beyond and introducing fantastic new features."
},
{
"code": null,
"e": 825,
"s": 397,
"text": "In March 2020, Microsoft announced Page Navigation as an action for buttons as generally available and at the same time introduced Drillthrough action for buttons as a preview feature. It sounded really appealing to me since I have a lot of users who are not aware of “right-click” Drillthrough capability, so I had to create different workarounds, such as tooltips, in order to engage users to use Drillthrough in the reports."
},
{
"code": null,
"e": 966,
"s": 825,
"text": "With new Drillthrough action for buttons now generally available, let’s try to make full use and offer our users unforgettable experience..."
},
{
"code": null,
"e": 1259,
"s": 966,
"text": "As usual, I will use the Contoso sample database for demonstration. Before proceeding further, another very interesting feature related to buttons is that now you can customize button for Disabled state (until now, you were able to customize button for Default, On Hover and On Press states)."
},
{
"code": null,
"e": 1296,
"s": 1259,
"text": "Let’s see how this works in reality:"
},
{
"code": null,
"e": 1372,
"s": 1296,
"text": "I’ve added a blank button and formatted it for Disabled state (grey color)."
},
{
"code": null,
"e": 1625,
"s": 1372,
"text": "Next thing I do, because I have multiple Drillthrough pages within my report, I am giving my users a possibility of what kind of details they would like to see. In my example, they can choose to see “Sales Amount per Brand” or “Sales Amount per Color”."
},
{
"code": null,
"e": 2014,
"s": 1625,
"text": "To achieve this, I need to create a new table which will hold data about drillthrough pages. Go to Enter data under Data ribbon and simply enter names of your drillthrough pages (it is of key importance that values in the table exactly match your drillthrough pages’ names). I’ve also added a column for ranking, just in case I want to sort pages in a different order than alphabetically."
},
{
"code": null,
"e": 2279,
"s": 2014,
"text": "Now, just drag slicer on the canvas and put Page name column in the Field value. One more little trick to improve user’s experience: depending on the user’s selection, we want to dynamically adjust the text on the button which will be used for Drillthrough action."
},
{
"code": null,
"e": 2362,
"s": 2279,
"text": "Therefore, I’ve created a simple DAX measure, which captures the user’s selection:"
},
{
"code": null,
"e": 2419,
"s": 2362,
"text": "Selected Page = \"Open \"& SELECTEDVALUE('Pages DT'[Page])"
},
{
"code": null,
"e": 2472,
"s": 2419,
"text": "This will dynamically change the text on the button:"
},
{
"code": null,
"e": 2580,
"s": 2472,
"text": "To achieve that, under formatting options of the button, choose Button Text and select option on the right:"
},
{
"code": null,
"e": 2665,
"s": 2580,
"text": "Choose to format by Field Value and select our newly created measure, Selected Page."
},
{
"code": null,
"e": 3128,
"s": 2665,
"text": "The next step is to instruct our button on what to do, depending on the user’s selection. Go to Action property of the button, again choose the option on the right and select Page under the “Based on field” dropdown menu and leave default First as Summarization type. Since we defined user selection to one value exclusively within a slicer (by turning Single Select ON), we don’t need to worry — whatever user selects, this will be first (and only) selection..."
},
{
"code": null,
"e": 3407,
"s": 3128,
"text": "One last thing to do is to format button Fill property, so the user can recognize when it is ready for drilling down. As I mentioned previously, the button is greyed out in the Disabled state. But, as soon as I choose a single data point from my table, look at what will happen!"
},
{
"code": null,
"e": 3613,
"s": 3407,
"text": "Our button becomes blue and now the user can interact with it and click on it in order to be navigated to a drillthrough page, which contains details about the Sales Amount for June 2009. How cool is that!"
},
{
"code": null,
"e": 3883,
"s": 3613,
"text": "Once we go back to the main page and select Sales Amt Color under Drillthrough Page slicer, the button goes back to Disabled state and we will be informed that we need to select one single brand if we want to drill through to a page which contains data per brand color."
},
{
"code": null,
"e": 3913,
"s": 3883,
"text": "So, let’s check how it works:"
},
{
"code": null,
"e": 4145,
"s": 3913,
"text": "I’ve chosen the Adventure Works brand within Sales Amt by Brand Name visual and my button is ready for action again! Once I click on it, I will be navigated to a page which displays data per product color for Adventure Works brand:"
},
{
"code": null,
"e": 4253,
"s": 4145,
"text": "Same as in the previous example, as soon as I’m back on the main page, the button again becomes greyed out."
},
{
"code": null,
"e": 4312,
"s": 4253,
"text": "To summarize, here is the complete behavior of our button:"
},
{
"code": null,
"e": 4557,
"s": 4312,
"text": "With dynamic formatting of the buttons and tweaking actions to enable usage of different drillthrough pages, you can really create an awesome user experience for your Power BI reports, avoiding the complexity of working with multiple bookmarks."
},
{
"code": null,
"e": 4605,
"s": 4557,
"text": "Become a member and read every story on Medium!"
}
] |
File.WriteAllBytes() Method in C# with Examples - GeeksforGeeks | 26 Feb, 2021
File.WriteAllBytes(String) is an inbuilt File class method that is used to create a new file then writes the specified byte array to the file and then closes the file. If the target file already exists, it is overwritten.
Syntax:
public static void WriteAllBytes (string path, byte[] bytes);
Parameter: This function accepts two parameters which are illustrated below:
path: This is the specified file where the byte array is going to be written.
bytes: This is the specified bytes that are going to be written into the file.
Exceptions:
ArgumentException: The path is a zero-length string, contains only white space, or one or more invalid characters as defined by InvalidPathChars.
ArgumentNullException: The path is null or the byte array is empty.
PathTooLongException: The specified path, file name, or both exceed the system-defined maximum length.
DirectoryNotFoundException: The specified path is invalid.
IOException: An I/O error occurred while opening the file.
UnauthorizedAccessException: The path specified a file that is read-only. OR the path specified a file that is hidden. OR this operation is not supported on the current platform. OR the path specified a directory. OR the caller does not have the required permission.
NotSupportedException: The path is in an invalid format.
SecurityException: The caller does not have the required permission.
Below are the programs to illustrate the File.WriteAllBytes(String, Byte[]) method.Program 1: Initially, no file was created. Below code, itself creates a file file.txt and writes some specified byte array and then finally close the file.
CSharp
// C# program to illustrate the usage// of File.WriteAllBytes() method // Using System, System.IO// and System.Text namespacesusing System;using System.IO;using System.Text; class GFG { static void Main(string[] args) { // Specifying a file name var path = @"file.txt"; // Specifying a byte array string text = "GFG is a CS portal."; byte[] data = Encoding.ASCII.GetBytes(text); // Calling the WriteAllBytes() function // to write specified byte array to the file File.WriteAllBytes(path, data); Console.WriteLine("The data has been written to the file."); }}
Output:
The data has been written to the file.
Above code gives the output as shown above and creates a file with some specified contents shown below-
Program 2: Initially, a file was created with some contents shown below:
Below code, overwrites the above file contents with a specified byte array data.
CSharp
// C# program to illustrate the usage// of File.WriteAllBytes() method // Using System, System.IO// and System.Text namespacesusing System;using System.IO;using System.Text; class GFG { static void Main(string[] args) { // Specifying a file name var path = @"file.txt"; // Specifying a byte array data string text = "GeeksforGeeks"; byte[] data = Encoding.ASCII.GetBytes(text); // Calling the WriteAllBytes() function // to overwrite the file contents with the // specified byte array data File.WriteAllBytes(path, data); Console.WriteLine("The data has been overwritten to the file."); }}
Output:
The data has been overwritten to the file.
After running above code, the above output is shown and the file contents get overwritten which is shown below-
arorakashish0911
CSharp-File-Handling
C#
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
C# Dictionary with examples
C# | Method Overriding
C# | Class and Object
Difference between Ref and Out keywords in C#
Introduction to .NET Framework
C# | Constructors
C# | String.IndexOf( ) Method | Set - 1
Extension Method in C#
C# | Abstract Classes
C# | Delegates | [
{
"code": null,
"e": 24856,
"s": 24828,
"text": "\n26 Feb, 2021"
},
{
"code": null,
"e": 25079,
"s": 24856,
"text": "File.WriteAllBytes(String) is an inbuilt File class method that is used to create a new file then writes the specified byte array to the file and then closes the file. If the target file already exists, it is overwritten. "
},
{
"code": null,
"e": 25089,
"s": 25079,
"text": "Syntax: "
},
{
"code": null,
"e": 25151,
"s": 25089,
"text": "public static void WriteAllBytes (string path, byte[] bytes);"
},
{
"code": null,
"e": 25230,
"s": 25151,
"text": "Parameter: This function accepts two parameters which are illustrated below: "
},
{
"code": null,
"e": 25308,
"s": 25230,
"text": "path: This is the specified file where the byte array is going to be written."
},
{
"code": null,
"e": 25387,
"s": 25308,
"text": "bytes: This is the specified bytes that are going to be written into the file."
},
{
"code": null,
"e": 25400,
"s": 25387,
"text": "Exceptions: "
},
{
"code": null,
"e": 25546,
"s": 25400,
"text": "ArgumentException: The path is a zero-length string, contains only white space, or one or more invalid characters as defined by InvalidPathChars."
},
{
"code": null,
"e": 25614,
"s": 25546,
"text": "ArgumentNullException: The path is null or the byte array is empty."
},
{
"code": null,
"e": 25717,
"s": 25614,
"text": "PathTooLongException: The specified path, file name, or both exceed the system-defined maximum length."
},
{
"code": null,
"e": 25776,
"s": 25717,
"text": "DirectoryNotFoundException: The specified path is invalid."
},
{
"code": null,
"e": 25835,
"s": 25776,
"text": "IOException: An I/O error occurred while opening the file."
},
{
"code": null,
"e": 26102,
"s": 25835,
"text": "UnauthorizedAccessException: The path specified a file that is read-only. OR the path specified a file that is hidden. OR this operation is not supported on the current platform. OR the path specified a directory. OR the caller does not have the required permission."
},
{
"code": null,
"e": 26159,
"s": 26102,
"text": "NotSupportedException: The path is in an invalid format."
},
{
"code": null,
"e": 26228,
"s": 26159,
"text": "SecurityException: The caller does not have the required permission."
},
{
"code": null,
"e": 26468,
"s": 26228,
"text": "Below are the programs to illustrate the File.WriteAllBytes(String, Byte[]) method.Program 1: Initially, no file was created. Below code, itself creates a file file.txt and writes some specified byte array and then finally close the file. "
},
{
"code": null,
"e": 26475,
"s": 26468,
"text": "CSharp"
},
{
"code": "// C# program to illustrate the usage// of File.WriteAllBytes() method // Using System, System.IO// and System.Text namespacesusing System;using System.IO;using System.Text; class GFG { static void Main(string[] args) { // Specifying a file name var path = @\"file.txt\"; // Specifying a byte array string text = \"GFG is a CS portal.\"; byte[] data = Encoding.ASCII.GetBytes(text); // Calling the WriteAllBytes() function // to write specified byte array to the file File.WriteAllBytes(path, data); Console.WriteLine(\"The data has been written to the file.\"); }}",
"e": 27109,
"s": 26475,
"text": null
},
{
"code": null,
"e": 27119,
"s": 27109,
"text": "Output: "
},
{
"code": null,
"e": 27158,
"s": 27119,
"text": "The data has been written to the file."
},
{
"code": null,
"e": 27263,
"s": 27158,
"text": "Above code gives the output as shown above and creates a file with some specified contents shown below- "
},
{
"code": null,
"e": 27337,
"s": 27263,
"text": "Program 2: Initially, a file was created with some contents shown below: "
},
{
"code": null,
"e": 27419,
"s": 27337,
"text": "Below code, overwrites the above file contents with a specified byte array data. "
},
{
"code": null,
"e": 27426,
"s": 27419,
"text": "CSharp"
},
{
"code": "// C# program to illustrate the usage// of File.WriteAllBytes() method // Using System, System.IO// and System.Text namespacesusing System;using System.IO;using System.Text; class GFG { static void Main(string[] args) { // Specifying a file name var path = @\"file.txt\"; // Specifying a byte array data string text = \"GeeksforGeeks\"; byte[] data = Encoding.ASCII.GetBytes(text); // Calling the WriteAllBytes() function // to overwrite the file contents with the // specified byte array data File.WriteAllBytes(path, data); Console.WriteLine(\"The data has been overwritten to the file.\"); }}",
"e": 28097,
"s": 27426,
"text": null
},
{
"code": null,
"e": 28107,
"s": 28097,
"text": "Output: "
},
{
"code": null,
"e": 28150,
"s": 28107,
"text": "The data has been overwritten to the file."
},
{
"code": null,
"e": 28263,
"s": 28150,
"text": "After running above code, the above output is shown and the file contents get overwritten which is shown below- "
},
{
"code": null,
"e": 28282,
"s": 28265,
"text": "arorakashish0911"
},
{
"code": null,
"e": 28303,
"s": 28282,
"text": "CSharp-File-Handling"
},
{
"code": null,
"e": 28306,
"s": 28303,
"text": "C#"
},
{
"code": null,
"e": 28404,
"s": 28306,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 28413,
"s": 28404,
"text": "Comments"
},
{
"code": null,
"e": 28426,
"s": 28413,
"text": "Old Comments"
},
{
"code": null,
"e": 28454,
"s": 28426,
"text": "C# Dictionary with examples"
},
{
"code": null,
"e": 28477,
"s": 28454,
"text": "C# | Method Overriding"
},
{
"code": null,
"e": 28499,
"s": 28477,
"text": "C# | Class and Object"
},
{
"code": null,
"e": 28545,
"s": 28499,
"text": "Difference between Ref and Out keywords in C#"
},
{
"code": null,
"e": 28576,
"s": 28545,
"text": "Introduction to .NET Framework"
},
{
"code": null,
"e": 28594,
"s": 28576,
"text": "C# | Constructors"
},
{
"code": null,
"e": 28634,
"s": 28594,
"text": "C# | String.IndexOf( ) Method | Set - 1"
},
{
"code": null,
"e": 28657,
"s": 28634,
"text": "Extension Method in C#"
},
{
"code": null,
"e": 28679,
"s": 28657,
"text": "C# | Abstract Classes"
}
] |
Print words of a string in reverse order - GeeksforGeeks | 08 Mar, 2022
Let there be a string say “I AM A GEEK”. So, the output should be “GEEK A AM I” . This can done in many ways. One of the solutions is given in Reverse words in a string .
Examples:
Input : I AM A GEEK
Output : GEEK A AM I
Input : GfG IS THE BEST
Output : BEST THE IS GfG
This can be done in more simpler way by using the property of the “%s format specifier” .Property: %s will get all the values until it gets NULL i.e. ‘\0’.
Example: char String[] = “I AM A GEEK” is stored as shown in the image below :
Approach: Traverse the string from the last character, and move towards the first character. While traversing, if a space character is encountered, put a NULL in that position and print the remaining string just after the NULL character. Repeat this until the loop is over and when the loop ends, print the string, the %s will make the printing of characters until it encounters the first NULL character.
Let us see the approach with the help of diagrams:step 1: Traverse from the last character until it encounters a space character .
Step 2: Put a NULL character at the position of space character and print the string after it.
Step 3: At the end, the loop ends when it reaches the first character, so print the remaining characters, it will be printed the first NULL character, hence the first word will be printed.
C++
C
Java
Python3
C#
PHP
Javascript
// C++ program to print reverse// of words in a string.#include <iostream> using namespace std; string wordReverse(string str){ int i = str.length() - 1; int start, end = i + 1; string result = ""; while (i >= 0) { if (str[i] == ' ') { start = i + 1; while (start != end) result += str[start++]; result += ' '; end = i; } i--; } start = 0; while (start != end) result += str[start++]; return result;} // Driver codeint main(){ string str = "I AM A GEEK"; cout << wordReverse(str); return 0;} // This code is contributed// by Imam
// C program to print reverse of words in// a string.#include <stdio.h>#include <string.h> void printReverse(char str[]){ int length = strlen(str); // Traverse string from end int i; for (i = length - 1; i >= 0; i--) { if (str[i] == ' ') { // putting the NULL character at the // position of space characters for // next iteration. str[i] = '\0'; // Start from next character printf("%s ", &(str[i]) + 1); } } // printing the last word printf("%s", str);} // Driver codeint main(){ char str[] = "I AM A GEEK"; printReverse(str); return 0;}
// Java program to print reverse// of words in a string.import java.io.*;import java.lang.*;import java.util.*; class GFG { static String wordReverse(String str) { int i = str.length() - 1; int start, end = i + 1; String result = ""; while (i >= 0) { if (str.charAt(i) == ' ') { start = i + 1; while (start != end) result += str.charAt(start++); result += ' '; end = i; } i--; } start = 0; while (start != end) result += str.charAt(start++); return result; } // Driver code public static void main(String[] args) { String str = "I AM A GEEK"; System.out.print(wordReverse(str)); }} // This code is contributed// by Akanksha Rai(Abby_akku)
# Python3 program to print reverse# of words in a string. def wordReverse(str): i = len(str)-1 start = end = i+1 result = '' while i >= 0: if str[i] == ' ': start = i+1 while start != end: result += str[start] start += 1 result += ' ' end = i i -= 1 start = 0 while start != end: result += str[start] start += 1 return result # Driver Codestr = 'I AM A GEEK'print(wordReverse(str)) # This code is contributed# by SamyuktaSHegde
// C# program to print reverse// of words in a string.using System;class GFG { static String wordReverse(String str) { int i = str.Length - 1; int start, end = i + 1; String result = ""; while (i >= 0) { if (str[i] == ' ') { start = i + 1; while (start != end) result += str[start++]; result += ' '; end = i; } i--; } start = 0; while (start != end) result += str[start++]; return result; } // Driver code public static void Main() { String str = "I AM A GEEK"; Console.Write(wordReverse(str)); }} // This code is contributed// by Akanksha Rai(Abby_akku)
<?php// PHP program to print reverse// of words in a stringfunction wordReverse($str){ $i = strlen($str) - 1; $end = $i + 1; $result = ""; while($i >= 0) { if($str[$i] == ' ') { $start = $i + 1; while($start != $end) $result = $result . $str[$start++]; $result = $result . ' '; $end = $i; } $i--; } $start = 0; while($start != $end) $result = $result . $str[$start++]; return $result;} // Driver code$str = "I AM A GEEK";echo wordReverse($str); // This code is contributed by ita_c?>
<script> // Javascript program to print reverse// of words in a string.function wordReverse(str){ var i = str.length - 1; var start, end = i + 1; var result = ""; while (i >= 0) { if (str[i] == ' ') { start = i + 1; while (start != end) result += str[start++]; result += ' '; end = i; } i--; } start = 0; while (start != end) result += str[start++]; return result;} // Driver codevar str = "I AM A GEEK"; document.write(wordReverse(str)); // This code is contributed by rutvik_56 </script>
Output:
GEEK A AM I
Time Complexity: O(len(str))
Auxiliary Space: O(len(str))
Without using any extra space:
Go through the string and mirror each word in the string, then, at the end, mirror the whole string.
The following C++ code can handle multiple contiguous spaces.
C++
Javascript
#include <algorithm>#include <iostream>#include <string> using namespace std; string reverse_words(string s){ int left = 0, i = 0, n = s.size(); while (s[i] == ' ') i++; left = i; while (i < n) { if (i + 1 == n || s[i] == ' ') { int j = i - 1; if (i + 1 == n) j++; while (left < j) swap(s[left++], s[j--]); left = i + 1; } if (s[left] == ' ' && i > left) left = i; i++; } //reverse(s.begin(), s.end()); return s;} int main(){ string str = "I AM A GEEK"; str = reverse_words(str); cout << str; return 0; // This code is contributed // by Gatea David}
<script> // JavaScript code for the approach function reverse_words(s){ let left = 0, i = 0, n = s.length; while (s[i] == ' ') i++; left = i; while (i < n) { if (i + 1 == n || s[i] == ' ') { let j = i - 1; if (i + 1 == n) j++; let temp; let a = s.split(""); while (left < j){ temp = a[left]; a[left] = a[j]; a[j] = temp; left++; j--; } s = a.join(""); left = i + 1; } if (s[left] == ' ' && i > left) left = i; i++; } s = s.split('').reverse().join(''); return s;} // driver code let str = "I AM A GEEK"; str = reverse_words(str); document.write(str); // This code is contributed by shinjanpatra </script>
Output:
GEEK A AM I
Time Complexity: O(len(str))
Auxiliary Space: O(1)
This article is contributed by MAZHAR IMAM KHAN. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
Imam
Akanksha_Rai
SamyuktaSHegde
ukasp
subhammahato348
rutvik_56
gulshankumarar231
simmytarika5
davidgatea21
shinjanpatra
Mentor Graphics
Reverse
Strings
Technical Scripter
Strings
Reverse
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Check for Balanced Brackets in an expression (well-formedness) using Stack
Python program to check if a string is palindrome or not
KMP Algorithm for Pattern Searching
Convert string to char array in C++
Longest Palindromic Substring | Set 1
Array of Strings in C++ (5 Different Ways to Create)
Caesar Cipher in Cryptography
Check whether two strings are anagram of each other
Top 50 String Coding Problems for Interviews
Length of the longest substring without repeating characters | [
{
"code": null,
"e": 24650,
"s": 24622,
"text": "\n08 Mar, 2022"
},
{
"code": null,
"e": 24821,
"s": 24650,
"text": "Let there be a string say “I AM A GEEK”. So, the output should be “GEEK A AM I” . This can done in many ways. One of the solutions is given in Reverse words in a string ."
},
{
"code": null,
"e": 24832,
"s": 24821,
"text": "Examples: "
},
{
"code": null,
"e": 24923,
"s": 24832,
"text": "Input : I AM A GEEK\nOutput : GEEK A AM I\n\nInput : GfG IS THE BEST\nOutput : BEST THE IS GfG"
},
{
"code": null,
"e": 25080,
"s": 24923,
"text": "This can be done in more simpler way by using the property of the “%s format specifier” .Property: %s will get all the values until it gets NULL i.e. ‘\\0’. "
},
{
"code": null,
"e": 25161,
"s": 25080,
"text": "Example: char String[] = “I AM A GEEK” is stored as shown in the image below : "
},
{
"code": null,
"e": 25567,
"s": 25161,
"text": "Approach: Traverse the string from the last character, and move towards the first character. While traversing, if a space character is encountered, put a NULL in that position and print the remaining string just after the NULL character. Repeat this until the loop is over and when the loop ends, print the string, the %s will make the printing of characters until it encounters the first NULL character. "
},
{
"code": null,
"e": 25700,
"s": 25567,
"text": "Let us see the approach with the help of diagrams:step 1: Traverse from the last character until it encounters a space character . "
},
{
"code": null,
"e": 25796,
"s": 25700,
"text": "Step 2: Put a NULL character at the position of space character and print the string after it. "
},
{
"code": null,
"e": 25985,
"s": 25796,
"text": "Step 3: At the end, the loop ends when it reaches the first character, so print the remaining characters, it will be printed the first NULL character, hence the first word will be printed."
},
{
"code": null,
"e": 25989,
"s": 25985,
"text": "C++"
},
{
"code": null,
"e": 25991,
"s": 25989,
"text": "C"
},
{
"code": null,
"e": 25996,
"s": 25991,
"text": "Java"
},
{
"code": null,
"e": 26004,
"s": 25996,
"text": "Python3"
},
{
"code": null,
"e": 26007,
"s": 26004,
"text": "C#"
},
{
"code": null,
"e": 26011,
"s": 26007,
"text": "PHP"
},
{
"code": null,
"e": 26022,
"s": 26011,
"text": "Javascript"
},
{
"code": "// C++ program to print reverse// of words in a string.#include <iostream> using namespace std; string wordReverse(string str){ int i = str.length() - 1; int start, end = i + 1; string result = \"\"; while (i >= 0) { if (str[i] == ' ') { start = i + 1; while (start != end) result += str[start++]; result += ' '; end = i; } i--; } start = 0; while (start != end) result += str[start++]; return result;} // Driver codeint main(){ string str = \"I AM A GEEK\"; cout << wordReverse(str); return 0;} // This code is contributed// by Imam",
"e": 26678,
"s": 26022,
"text": null
},
{
"code": "// C program to print reverse of words in// a string.#include <stdio.h>#include <string.h> void printReverse(char str[]){ int length = strlen(str); // Traverse string from end int i; for (i = length - 1; i >= 0; i--) { if (str[i] == ' ') { // putting the NULL character at the // position of space characters for // next iteration. str[i] = '\\0'; // Start from next character printf(\"%s \", &(str[i]) + 1); } } // printing the last word printf(\"%s\", str);} // Driver codeint main(){ char str[] = \"I AM A GEEK\"; printReverse(str); return 0;}",
"e": 27332,
"s": 26678,
"text": null
},
{
"code": "// Java program to print reverse// of words in a string.import java.io.*;import java.lang.*;import java.util.*; class GFG { static String wordReverse(String str) { int i = str.length() - 1; int start, end = i + 1; String result = \"\"; while (i >= 0) { if (str.charAt(i) == ' ') { start = i + 1; while (start != end) result += str.charAt(start++); result += ' '; end = i; } i--; } start = 0; while (start != end) result += str.charAt(start++); return result; } // Driver code public static void main(String[] args) { String str = \"I AM A GEEK\"; System.out.print(wordReverse(str)); }} // This code is contributed// by Akanksha Rai(Abby_akku)",
"e": 28192,
"s": 27332,
"text": null
},
{
"code": "# Python3 program to print reverse# of words in a string. def wordReverse(str): i = len(str)-1 start = end = i+1 result = '' while i >= 0: if str[i] == ' ': start = i+1 while start != end: result += str[start] start += 1 result += ' ' end = i i -= 1 start = 0 while start != end: result += str[start] start += 1 return result # Driver Codestr = 'I AM A GEEK'print(wordReverse(str)) # This code is contributed# by SamyuktaSHegde",
"e": 28746,
"s": 28192,
"text": null
},
{
"code": "// C# program to print reverse// of words in a string.using System;class GFG { static String wordReverse(String str) { int i = str.Length - 1; int start, end = i + 1; String result = \"\"; while (i >= 0) { if (str[i] == ' ') { start = i + 1; while (start != end) result += str[start++]; result += ' '; end = i; } i--; } start = 0; while (start != end) result += str[start++]; return result; } // Driver code public static void Main() { String str = \"I AM A GEEK\"; Console.Write(wordReverse(str)); }} // This code is contributed// by Akanksha Rai(Abby_akku)",
"e": 29522,
"s": 28746,
"text": null
},
{
"code": "<?php// PHP program to print reverse// of words in a stringfunction wordReverse($str){ $i = strlen($str) - 1; $end = $i + 1; $result = \"\"; while($i >= 0) { if($str[$i] == ' ') { $start = $i + 1; while($start != $end) $result = $result . $str[$start++]; $result = $result . ' '; $end = $i; } $i--; } $start = 0; while($start != $end) $result = $result . $str[$start++]; return $result;} // Driver code$str = \"I AM A GEEK\";echo wordReverse($str); // This code is contributed by ita_c?>",
"e": 30163,
"s": 29522,
"text": null
},
{
"code": "<script> // Javascript program to print reverse// of words in a string.function wordReverse(str){ var i = str.length - 1; var start, end = i + 1; var result = \"\"; while (i >= 0) { if (str[i] == ' ') { start = i + 1; while (start != end) result += str[start++]; result += ' '; end = i; } i--; } start = 0; while (start != end) result += str[start++]; return result;} // Driver codevar str = \"I AM A GEEK\"; document.write(wordReverse(str)); // This code is contributed by rutvik_56 </script>",
"e": 30802,
"s": 30163,
"text": null
},
{
"code": null,
"e": 30811,
"s": 30802,
"text": "Output: "
},
{
"code": null,
"e": 30823,
"s": 30811,
"text": "GEEK A AM I"
},
{
"code": null,
"e": 30852,
"s": 30823,
"text": "Time Complexity: O(len(str))"
},
{
"code": null,
"e": 30881,
"s": 30852,
"text": "Auxiliary Space: O(len(str))"
},
{
"code": null,
"e": 30912,
"s": 30881,
"text": "Without using any extra space:"
},
{
"code": null,
"e": 31013,
"s": 30912,
"text": "Go through the string and mirror each word in the string, then, at the end, mirror the whole string."
},
{
"code": null,
"e": 31075,
"s": 31013,
"text": "The following C++ code can handle multiple contiguous spaces."
},
{
"code": null,
"e": 31079,
"s": 31075,
"text": "C++"
},
{
"code": null,
"e": 31090,
"s": 31079,
"text": "Javascript"
},
{
"code": "#include <algorithm>#include <iostream>#include <string> using namespace std; string reverse_words(string s){ int left = 0, i = 0, n = s.size(); while (s[i] == ' ') i++; left = i; while (i < n) { if (i + 1 == n || s[i] == ' ') { int j = i - 1; if (i + 1 == n) j++; while (left < j) swap(s[left++], s[j--]); left = i + 1; } if (s[left] == ' ' && i > left) left = i; i++; } //reverse(s.begin(), s.end()); return s;} int main(){ string str = \"I AM A GEEK\"; str = reverse_words(str); cout << str; return 0; // This code is contributed // by Gatea David}",
"e": 31849,
"s": 31090,
"text": null
},
{
"code": "<script> // JavaScript code for the approach function reverse_words(s){ let left = 0, i = 0, n = s.length; while (s[i] == ' ') i++; left = i; while (i < n) { if (i + 1 == n || s[i] == ' ') { let j = i - 1; if (i + 1 == n) j++; let temp; let a = s.split(\"\"); while (left < j){ temp = a[left]; a[left] = a[j]; a[j] = temp; left++; j--; } s = a.join(\"\"); left = i + 1; } if (s[left] == ' ' && i > left) left = i; i++; } s = s.split('').reverse().join(''); return s;} // driver code let str = \"I AM A GEEK\"; str = reverse_words(str); document.write(str); // This code is contributed by shinjanpatra </script>",
"e": 32726,
"s": 31849,
"text": null
},
{
"code": null,
"e": 32734,
"s": 32726,
"text": "Output:"
},
{
"code": null,
"e": 32746,
"s": 32734,
"text": "GEEK A AM I"
},
{
"code": null,
"e": 32775,
"s": 32746,
"text": "Time Complexity: O(len(str))"
},
{
"code": null,
"e": 32797,
"s": 32775,
"text": "Auxiliary Space: O(1)"
},
{
"code": null,
"e": 33221,
"s": 32797,
"text": "This article is contributed by MAZHAR IMAM KHAN. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above."
},
{
"code": null,
"e": 33226,
"s": 33221,
"text": "Imam"
},
{
"code": null,
"e": 33239,
"s": 33226,
"text": "Akanksha_Rai"
},
{
"code": null,
"e": 33254,
"s": 33239,
"text": "SamyuktaSHegde"
},
{
"code": null,
"e": 33260,
"s": 33254,
"text": "ukasp"
},
{
"code": null,
"e": 33276,
"s": 33260,
"text": "subhammahato348"
},
{
"code": null,
"e": 33286,
"s": 33276,
"text": "rutvik_56"
},
{
"code": null,
"e": 33304,
"s": 33286,
"text": "gulshankumarar231"
},
{
"code": null,
"e": 33317,
"s": 33304,
"text": "simmytarika5"
},
{
"code": null,
"e": 33330,
"s": 33317,
"text": "davidgatea21"
},
{
"code": null,
"e": 33343,
"s": 33330,
"text": "shinjanpatra"
},
{
"code": null,
"e": 33359,
"s": 33343,
"text": "Mentor Graphics"
},
{
"code": null,
"e": 33367,
"s": 33359,
"text": "Reverse"
},
{
"code": null,
"e": 33375,
"s": 33367,
"text": "Strings"
},
{
"code": null,
"e": 33394,
"s": 33375,
"text": "Technical Scripter"
},
{
"code": null,
"e": 33402,
"s": 33394,
"text": "Strings"
},
{
"code": null,
"e": 33410,
"s": 33402,
"text": "Reverse"
},
{
"code": null,
"e": 33508,
"s": 33410,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 33583,
"s": 33508,
"text": "Check for Balanced Brackets in an expression (well-formedness) using Stack"
},
{
"code": null,
"e": 33640,
"s": 33583,
"text": "Python program to check if a string is palindrome or not"
},
{
"code": null,
"e": 33676,
"s": 33640,
"text": "KMP Algorithm for Pattern Searching"
},
{
"code": null,
"e": 33712,
"s": 33676,
"text": "Convert string to char array in C++"
},
{
"code": null,
"e": 33750,
"s": 33712,
"text": "Longest Palindromic Substring | Set 1"
},
{
"code": null,
"e": 33803,
"s": 33750,
"text": "Array of Strings in C++ (5 Different Ways to Create)"
},
{
"code": null,
"e": 33833,
"s": 33803,
"text": "Caesar Cipher in Cryptography"
},
{
"code": null,
"e": 33885,
"s": 33833,
"text": "Check whether two strings are anagram of each other"
},
{
"code": null,
"e": 33930,
"s": 33885,
"text": "Top 50 String Coding Problems for Interviews"
}
] |
Fifteen Jupyter Notebook Extensions to a Docker Image | by Bruce H. Cottman, Ph.D. | Towards Data Science | The Docker image for our Jupyter Python and R users required them to set their Nbextensions preferences after every launch. We were able to increase Jupyter notebook user productivity by setting commonly used Nbextensions preferences in the Docker image.
We have a shared disk where anybody can copy the template files to their local directory structure.
|-- dockerSeasons |-- dev |--- Dockerfile |--- docker-compose.yml |-- test |--- Dockerfile |--- docker-compose.yml
Each member of Dev and Test copies Release 1.3.0dockerSeasons directory over to their PROJECTS directory.
- PROJECTS... |-- <project-name> |-- dockerSeasons |-- dev |--- Dockerfile |--- docker-compose.yml |--- README.md |--- <ln> requirements.txt |-- test |--- Dockerfile |--- docker-compose.yml |--- README.md |--- <ln> requirements.txt |-- src |-- test |--- requirements.txt |--- README.md..
Note: Dev 1.0.3 is able to use the 0.0.3 PROJECTS directory structure unchanged. Release 3.0.1dockerSeasons overwrites docker 0.0.3 directory.
Test modifies <project-name>/requirements.txt for the difference in Python packages they do and don't require. Then the Test symbolically links <project-name>/requirements.txt(in the <project-name>/dockerSeasons/test directory) with the command:
# MacOS and linux variants$ ln ../../requirements.txt requirements.txt
The only differences in the Test directory are the files requirements.txt, the files in directory dockerSeasons/test/ . Test moves this directory structure to stage server and 3 redundant production servers. The server farm is internal.
1.0.3 released a dockerfile template that enabled Dev and Test to customize each Docker image by requirements.txt.
In a previous article, I showed the Dockerfile used to create a Docker image with Jupyter notebook. We are now on DES 1.3.0 (Docker Enterprise Solution) with a different specification of the Dockerfile for Jupyter notebook users.
The meaningful change is that jupyterthemes (nbextentsions) stage after requirements.txt. Through trial and feedback, we found that Dev and Test changed requirements.txt less often than jupyterthemes.
Changing the order of staging from less frequent changes to more frequent changes allowed us to take advantage of Docker buffering. The result is faster Dockerfile builds than prior.
Depending on what is in requirements.txt, we experience full builds up to 10 minutes. By putting jupyterthemes last, we experience builds (no requirements.txt change) of approximately 30 seconds.
You might consider the frequency of changes and order of builds in your Dockerfile builds.
The DES 1.3.0 release of the partial Dockerfile is:
FROM python:3.7FROM jupyter/minimal-notebookWORKDIR $HOMERUN python -m pip install --upgrade pipCOPY requirements.txt ./requirements.txtRUN python -m pip install -r requirements.txRUN python -m pip install --upgrade --no-deps --force-reinstall notebook#RUN python -m pip install jupyterthemesRUN python -m pip install --upgrade jupyterthemesRUN python -m pip install jupyter_contrib_nbextensions
Note: Do not execute the following commands from your terminal shell. If you do, you install jupyterthemes in your local copy of jupyter. The bigger problem is that you reset your local nbextentsions settings in your local copy of jupyter.
pip install jupyterthemespip install --upgrade jupyterthemespip install jupyter_contrib_nbextensions
We had to build the Dockerfile in two steps because we need to find what jupyterthemes are available and what their names are. First, we executed the partial Dockerfile listed above.
We launched juptyer using command updev (described later in this article). We then ran the following in a Jupyter notebook.
!jupyter nbextension list
output->>
Known nbextensions: config dir: /home/jovyan/.jupyter/nbconfig notebook section nbextensions_configurator/config_menu/main enabled - Validating: problems found: - require? X nbextensions_configurator/config_menu/main contrib_nbextensions_help_item/main enabled - Validating: OK jupyter-js-widgets/extension enabled - Validating: problems found: - require? X jupyter-js-widgets/extension jupyter-notebook-gist/notebook-extension enabled - Validating: problems found: - require? X jupyter-notebook-gist/notebook-extension autosavetime/main enabled - Validating: OK codefolding/main enabled - Validating: OK code_font_size/code_font_size enabled - Validating: OK code_prettify/code_prettify enabled - Validating: OK collapsible_headings/main enabled - Validating: OK comment-uncomment/main enabled - Validating: OK equation-numbering/main enabled - Validating: OK execute_time/ExecuteTime enabled - Validating: OK gist_it/main enabled - Validating: OK hide_input/main enabled - Validating: OK spellchecker/main enabled - Validating: OK toc2/main enabled - Validating: OK toggle_all_line_numbers/main enabled - Validating: OK tree section nbextensions_configurator/tree_tab/main enabled - Validating: problems found: - require? X nbextensions_configurator/tree_tab/main config dir: /opt/conda/etc/jupyter/nbconfig notebook section plotlywidget/extension enabled - Validating: OK
Now we had the Nbextensions names to add to the 1.3.0 release dockerfile!
The dockerfile for Dev enabled the following Nbextensions shown after the comment #enable the Nbextensions.
FROM python:3.7FROM jupyter/minimal-notebookWORKDIR $HOMERUN python -m pip install --upgrade pipCOPY requirements.txt ./requirements.txtRUN python -m pip install -r requirements.txRUN python -m pip install --upgrade --no-deps --force-reinstall notebook#RUN python -m pip install jupyterthemesRUN python -m pip install --upgrade jupyterthemesRUN python -m pip install jupyter_contrib_nbextensionsRUN jupyter contrib nbextension install --user# enable the NbextensionsRUN jupyter nbextension enable contrib_nbextensions_help_item/mainRUN jupyter nbextension enable autosavetime/mainRUN jupyter nbextension enable codefolding/mainRUN jupyter nbextension enable code_font_size/code_font_sizeRUN jupyter nbextension enable code_prettify/code_prettifyRUN jupyter nbextension enable collapsible_headings/mainRUN jupyter nbextension enable comment-uncomment/mainRUN jupyter nbextension enable equation-numbering/mainRUN jupyter nbextension enable execute_time/ExecuteTime RUN jupyter nbextension enable gist_it/main RUN jupyter nbextension enable hide_input/main RUN jupyter nbextension enable spellchecker/mainRUN jupyter nbextension enable toc2/mainRUN jupyter nbextension enable toggle_all_line_numbers/main
Docker-Compose is used to manage several containers at the same time for the same application. This tool offers the same features as Docker but allows you to have more complex applications.
Docker-Compose can merge more than one Docker container into one runtime image. Currently, we use Docker-Compose for only one Docker image (dockerfile.yaml).
version: '3'services: dev: build: '.' ports: - "127.0.0.1:8889:8888" volumes: - ../../../.:/docker working_dir: /docker
note: When you use command updev (described later in this article) the docker-compose command volume: - ./../../. causes <path-to-projects> to be mapped to /docker , the internal directory of the docker image. The subsequent launch of jupyter uses <path-to-projects> as its top level directory. Please use the example directory structure shown above or else substitute your own local directory structure for - ./../../. .
The Docker commands are setup by adding the following commands to your ̃/.bashrc_profile or ̃/bashrc.txt.
devdir='<path-to-projects>/photon/photonai/dockerSeasons/dev/'testdir='<path-to-projects>/photon/photonai/dockerSeasons/test/'echo $devdirecho $testdirexport testdirexport devdir#alias updev="(cd $devdir; docker-compose up) &"alias downdev="(cd $devdir; docker-compose down) &"alias builddev="(cd $devdir; docker-compose build) &"#alias uptest="(cd $testdir; docker-compose up) & "alias downtest="(cd $testdir; docker-compose down) &"alias buildtest="cd $testdir; docker-compose build) &"
If you can not find the file ̃/bashrc.txt create it with touch ̃/bashrc.txt.(MacOs or one of various Linux, or Unix operating systems.)
Note: Remember to source ̃/.bashrc_profile and/or ̃/bashrc.txt when you done editing them.
The updev command resulted in the following stream of messages on my terminal console. (Yours will have different timestamps and other slight differences.)
dev_1 | [I 15:53:33.389 NotebookApp] [jupyter_nbextensions_configurator] enabled 0.4.1dev_1 | [I 15:53:33.817 NotebookApp] JupyterLab extension loaded from /opt/conda/lib/python3.7/site-packages/jupyterlabdev_1 | [I 15:53:33.818 NotebookApp] JupyterLab application directory is /opt/conda/share/jupyter/labdev_1 | [I 15:53:34.196 NotebookApp] Serving notebooks from local directory: /dockerdev_1 | [I 15:53:34.196 NotebookApp] The Jupyter Notebook is running at:dev_1 | [I 15:53:34.196 NotebookApp] http://dd974d01052d:8888/?token=78824facb945e1bf386a6ead41f7b147d5ac4240dc673421dev_1 | [I 15:53:34.196 NotebookApp] or http://127.0.0.1:8888/?token=78824facb945e1bf386a6ead41f7b147d5ac4240dc673421
Note: The updev command outputs:
..http://127.0.0.1:8888/?token=12377aa1c91b45e66e45eb5d5bdf2115cad2dae5b61be5c0
Because we map port 8888 to port 8889(Dev ) and port 8890(Test ) in the dockerfile.yaml. Users of DET 1.3.0 release must cut&paste the following into their web browser.
http://127.0.0.1:8889/?token=12377aa1c91b45e66e45eb5d5bdf2115cad2dae5b61be5c0
Does that seem a lot of detail to “Adding Jupyter Notebook Extensions to a Docker Image.” Perhaps it is. I recap:
Add the Nbextensionsyou want in the Jupyter user Dockerfile. TheNbextensions names and how to enable them are given above.Edit the dockerfile.yaml volume: - ./../../. ,if necessary. The subsequent launch of jupyter uses <./../../.as its top level directory.Optionally, “Automate the Frequently Used docker-compose commands” by adding them to your ̃/.bashrc_profile file.Finally, enable the Nbextensions:
Add the Nbextensionsyou want in the Jupyter user Dockerfile. TheNbextensions names and how to enable them are given above.
Edit the dockerfile.yaml volume: - ./../../. ,if necessary. The subsequent launch of jupyter uses <./../../.as its top level directory.
Optionally, “Automate the Frequently Used docker-compose commands” by adding them to your ̃/.bashrc_profile file.
Finally, enable the Nbextensions:
It took a couple of days of twist, turns, and wrong paths to get to DET 1.3.0 release. I hope you take less time to implement your Docker solution and, this article helps in your effort.
If you have a suggestion or improvements, please comment.
There is more detail on the Docker implementation I use in:
medium.com
medium.com
Note: You can adapt the Docker code to your project from a clone-able GitHub repo. | [
{
"code": null,
"e": 426,
"s": 171,
"text": "The Docker image for our Jupyter Python and R users required them to set their Nbextensions preferences after every launch. We were able to increase Jupyter notebook user productivity by setting commonly used Nbextensions preferences in the Docker image."
},
{
"code": null,
"e": 526,
"s": 426,
"text": "We have a shared disk where anybody can copy the template files to their local directory structure."
},
{
"code": null,
"e": 681,
"s": 526,
"text": "|-- dockerSeasons |-- dev |--- Dockerfile |--- docker-compose.yml |-- test |--- Dockerfile |--- docker-compose.yml"
},
{
"code": null,
"e": 787,
"s": 681,
"text": "Each member of Dev and Test copies Release 1.3.0dockerSeasons directory over to their PROJECTS directory."
},
{
"code": null,
"e": 1278,
"s": 787,
"text": "- PROJECTS... |-- <project-name> |-- dockerSeasons |-- dev |--- Dockerfile |--- docker-compose.yml |--- README.md |--- <ln> requirements.txt |-- test |--- Dockerfile |--- docker-compose.yml |--- README.md |--- <ln> requirements.txt |-- src |-- test |--- requirements.txt |--- README.md.."
},
{
"code": null,
"e": 1421,
"s": 1278,
"text": "Note: Dev 1.0.3 is able to use the 0.0.3 PROJECTS directory structure unchanged. Release 3.0.1dockerSeasons overwrites docker 0.0.3 directory."
},
{
"code": null,
"e": 1667,
"s": 1421,
"text": "Test modifies <project-name>/requirements.txt for the difference in Python packages they do and don't require. Then the Test symbolically links <project-name>/requirements.txt(in the <project-name>/dockerSeasons/test directory) with the command:"
},
{
"code": null,
"e": 1738,
"s": 1667,
"text": "# MacOS and linux variants$ ln ../../requirements.txt requirements.txt"
},
{
"code": null,
"e": 1975,
"s": 1738,
"text": "The only differences in the Test directory are the files requirements.txt, the files in directory dockerSeasons/test/ . Test moves this directory structure to stage server and 3 redundant production servers. The server farm is internal."
},
{
"code": null,
"e": 2090,
"s": 1975,
"text": "1.0.3 released a dockerfile template that enabled Dev and Test to customize each Docker image by requirements.txt."
},
{
"code": null,
"e": 2320,
"s": 2090,
"text": "In a previous article, I showed the Dockerfile used to create a Docker image with Jupyter notebook. We are now on DES 1.3.0 (Docker Enterprise Solution) with a different specification of the Dockerfile for Jupyter notebook users."
},
{
"code": null,
"e": 2521,
"s": 2320,
"text": "The meaningful change is that jupyterthemes (nbextentsions) stage after requirements.txt. Through trial and feedback, we found that Dev and Test changed requirements.txt less often than jupyterthemes."
},
{
"code": null,
"e": 2704,
"s": 2521,
"text": "Changing the order of staging from less frequent changes to more frequent changes allowed us to take advantage of Docker buffering. The result is faster Dockerfile builds than prior."
},
{
"code": null,
"e": 2900,
"s": 2704,
"text": "Depending on what is in requirements.txt, we experience full builds up to 10 minutes. By putting jupyterthemes last, we experience builds (no requirements.txt change) of approximately 30 seconds."
},
{
"code": null,
"e": 2991,
"s": 2900,
"text": "You might consider the frequency of changes and order of builds in your Dockerfile builds."
},
{
"code": null,
"e": 3043,
"s": 2991,
"text": "The DES 1.3.0 release of the partial Dockerfile is:"
},
{
"code": null,
"e": 3440,
"s": 3043,
"text": "FROM python:3.7FROM jupyter/minimal-notebookWORKDIR $HOMERUN python -m pip install --upgrade pipCOPY requirements.txt ./requirements.txtRUN python -m pip install -r requirements.txRUN python -m pip install --upgrade --no-deps --force-reinstall notebook#RUN python -m pip install jupyterthemesRUN python -m pip install --upgrade jupyterthemesRUN python -m pip install jupyter_contrib_nbextensions"
},
{
"code": null,
"e": 3680,
"s": 3440,
"text": "Note: Do not execute the following commands from your terminal shell. If you do, you install jupyterthemes in your local copy of jupyter. The bigger problem is that you reset your local nbextentsions settings in your local copy of jupyter."
},
{
"code": null,
"e": 3781,
"s": 3680,
"text": "pip install jupyterthemespip install --upgrade jupyterthemespip install jupyter_contrib_nbextensions"
},
{
"code": null,
"e": 3964,
"s": 3781,
"text": "We had to build the Dockerfile in two steps because we need to find what jupyterthemes are available and what their names are. First, we executed the partial Dockerfile listed above."
},
{
"code": null,
"e": 4088,
"s": 3964,
"text": "We launched juptyer using command updev (described later in this article). We then ran the following in a Jupyter notebook."
},
{
"code": null,
"e": 4114,
"s": 4088,
"text": "!jupyter nbextension list"
},
{
"code": null,
"e": 4124,
"s": 4114,
"text": "output->>"
},
{
"code": null,
"e": 5770,
"s": 4124,
"text": "Known nbextensions: config dir: /home/jovyan/.jupyter/nbconfig notebook section nbextensions_configurator/config_menu/main enabled - Validating: problems found: - require? X nbextensions_configurator/config_menu/main contrib_nbextensions_help_item/main enabled - Validating: OK jupyter-js-widgets/extension enabled - Validating: problems found: - require? X jupyter-js-widgets/extension jupyter-notebook-gist/notebook-extension enabled - Validating: problems found: - require? X jupyter-notebook-gist/notebook-extension autosavetime/main enabled - Validating: OK codefolding/main enabled - Validating: OK code_font_size/code_font_size enabled - Validating: OK code_prettify/code_prettify enabled - Validating: OK collapsible_headings/main enabled - Validating: OK comment-uncomment/main enabled - Validating: OK equation-numbering/main enabled - Validating: OK execute_time/ExecuteTime enabled - Validating: OK gist_it/main enabled - Validating: OK hide_input/main enabled - Validating: OK spellchecker/main enabled - Validating: OK toc2/main enabled - Validating: OK toggle_all_line_numbers/main enabled - Validating: OK tree section nbextensions_configurator/tree_tab/main enabled - Validating: problems found: - require? X nbextensions_configurator/tree_tab/main config dir: /opt/conda/etc/jupyter/nbconfig notebook section plotlywidget/extension enabled - Validating: OK"
},
{
"code": null,
"e": 5844,
"s": 5770,
"text": "Now we had the Nbextensions names to add to the 1.3.0 release dockerfile!"
},
{
"code": null,
"e": 5952,
"s": 5844,
"text": "The dockerfile for Dev enabled the following Nbextensions shown after the comment #enable the Nbextensions."
},
{
"code": null,
"e": 7156,
"s": 5952,
"text": "FROM python:3.7FROM jupyter/minimal-notebookWORKDIR $HOMERUN python -m pip install --upgrade pipCOPY requirements.txt ./requirements.txtRUN python -m pip install -r requirements.txRUN python -m pip install --upgrade --no-deps --force-reinstall notebook#RUN python -m pip install jupyterthemesRUN python -m pip install --upgrade jupyterthemesRUN python -m pip install jupyter_contrib_nbextensionsRUN jupyter contrib nbextension install --user# enable the NbextensionsRUN jupyter nbextension enable contrib_nbextensions_help_item/mainRUN jupyter nbextension enable autosavetime/mainRUN jupyter nbextension enable codefolding/mainRUN jupyter nbextension enable code_font_size/code_font_sizeRUN jupyter nbextension enable code_prettify/code_prettifyRUN jupyter nbextension enable collapsible_headings/mainRUN jupyter nbextension enable comment-uncomment/mainRUN jupyter nbextension enable equation-numbering/mainRUN jupyter nbextension enable execute_time/ExecuteTime RUN jupyter nbextension enable gist_it/main RUN jupyter nbextension enable hide_input/main RUN jupyter nbextension enable spellchecker/mainRUN jupyter nbextension enable toc2/mainRUN jupyter nbextension enable toggle_all_line_numbers/main"
},
{
"code": null,
"e": 7346,
"s": 7156,
"text": "Docker-Compose is used to manage several containers at the same time for the same application. This tool offers the same features as Docker but allows you to have more complex applications."
},
{
"code": null,
"e": 7504,
"s": 7346,
"text": "Docker-Compose can merge more than one Docker container into one runtime image. Currently, we use Docker-Compose for only one Docker image (dockerfile.yaml)."
},
{
"code": null,
"e": 7649,
"s": 7504,
"text": "version: '3'services: dev: build: '.' ports: - \"127.0.0.1:8889:8888\" volumes: - ../../../.:/docker working_dir: /docker"
},
{
"code": null,
"e": 8071,
"s": 7649,
"text": "note: When you use command updev (described later in this article) the docker-compose command volume: - ./../../. causes <path-to-projects> to be mapped to /docker , the internal directory of the docker image. The subsequent launch of jupyter uses <path-to-projects> as its top level directory. Please use the example directory structure shown above or else substitute your own local directory structure for - ./../../. ."
},
{
"code": null,
"e": 8179,
"s": 8071,
"text": "The Docker commands are setup by adding the following commands to your ̃/.bashrc_profile or ̃/bashrc.txt."
},
{
"code": null,
"e": 8668,
"s": 8179,
"text": "devdir='<path-to-projects>/photon/photonai/dockerSeasons/dev/'testdir='<path-to-projects>/photon/photonai/dockerSeasons/test/'echo $devdirecho $testdirexport testdirexport devdir#alias updev=\"(cd $devdir; docker-compose up) &\"alias downdev=\"(cd $devdir; docker-compose down) &\"alias builddev=\"(cd $devdir; docker-compose build) &\"#alias uptest=\"(cd $testdir; docker-compose up) & \"alias downtest=\"(cd $testdir; docker-compose down) &\"alias buildtest=\"cd $testdir; docker-compose build) &\""
},
{
"code": null,
"e": 8805,
"s": 8668,
"text": "If you can not find the file ̃/bashrc.txt create it with touch ̃/bashrc.txt.(MacOs or one of various Linux, or Unix operating systems.)"
},
{
"code": null,
"e": 8898,
"s": 8805,
"text": "Note: Remember to source ̃/.bashrc_profile and/or ̃/bashrc.txt when you done editing them."
},
{
"code": null,
"e": 9054,
"s": 8898,
"text": "The updev command resulted in the following stream of messages on my terminal console. (Yours will have different timestamps and other slight differences.)"
},
{
"code": null,
"e": 9759,
"s": 9054,
"text": "dev_1 | [I 15:53:33.389 NotebookApp] [jupyter_nbextensions_configurator] enabled 0.4.1dev_1 | [I 15:53:33.817 NotebookApp] JupyterLab extension loaded from /opt/conda/lib/python3.7/site-packages/jupyterlabdev_1 | [I 15:53:33.818 NotebookApp] JupyterLab application directory is /opt/conda/share/jupyter/labdev_1 | [I 15:53:34.196 NotebookApp] Serving notebooks from local directory: /dockerdev_1 | [I 15:53:34.196 NotebookApp] The Jupyter Notebook is running at:dev_1 | [I 15:53:34.196 NotebookApp] http://dd974d01052d:8888/?token=78824facb945e1bf386a6ead41f7b147d5ac4240dc673421dev_1 | [I 15:53:34.196 NotebookApp] or http://127.0.0.1:8888/?token=78824facb945e1bf386a6ead41f7b147d5ac4240dc673421"
},
{
"code": null,
"e": 9792,
"s": 9759,
"text": "Note: The updev command outputs:"
},
{
"code": null,
"e": 9872,
"s": 9792,
"text": "..http://127.0.0.1:8888/?token=12377aa1c91b45e66e45eb5d5bdf2115cad2dae5b61be5c0"
},
{
"code": null,
"e": 10041,
"s": 9872,
"text": "Because we map port 8888 to port 8889(Dev ) and port 8890(Test ) in the dockerfile.yaml. Users of DET 1.3.0 release must cut&paste the following into their web browser."
},
{
"code": null,
"e": 10119,
"s": 10041,
"text": "http://127.0.0.1:8889/?token=12377aa1c91b45e66e45eb5d5bdf2115cad2dae5b61be5c0"
},
{
"code": null,
"e": 10233,
"s": 10119,
"text": "Does that seem a lot of detail to “Adding Jupyter Notebook Extensions to a Docker Image.” Perhaps it is. I recap:"
},
{
"code": null,
"e": 10638,
"s": 10233,
"text": "Add the Nbextensionsyou want in the Jupyter user Dockerfile. TheNbextensions names and how to enable them are given above.Edit the dockerfile.yaml volume: - ./../../. ,if necessary. The subsequent launch of jupyter uses <./../../.as its top level directory.Optionally, “Automate the Frequently Used docker-compose commands” by adding them to your ̃/.bashrc_profile file.Finally, enable the Nbextensions:"
},
{
"code": null,
"e": 10761,
"s": 10638,
"text": "Add the Nbextensionsyou want in the Jupyter user Dockerfile. TheNbextensions names and how to enable them are given above."
},
{
"code": null,
"e": 10897,
"s": 10761,
"text": "Edit the dockerfile.yaml volume: - ./../../. ,if necessary. The subsequent launch of jupyter uses <./../../.as its top level directory."
},
{
"code": null,
"e": 11012,
"s": 10897,
"text": "Optionally, “Automate the Frequently Used docker-compose commands” by adding them to your ̃/.bashrc_profile file."
},
{
"code": null,
"e": 11046,
"s": 11012,
"text": "Finally, enable the Nbextensions:"
},
{
"code": null,
"e": 11233,
"s": 11046,
"text": "It took a couple of days of twist, turns, and wrong paths to get to DET 1.3.0 release. I hope you take less time to implement your Docker solution and, this article helps in your effort."
},
{
"code": null,
"e": 11291,
"s": 11233,
"text": "If you have a suggestion or improvements, please comment."
},
{
"code": null,
"e": 11351,
"s": 11291,
"text": "There is more detail on the Docker implementation I use in:"
},
{
"code": null,
"e": 11362,
"s": 11351,
"text": "medium.com"
},
{
"code": null,
"e": 11373,
"s": 11362,
"text": "medium.com"
}
] |
How to set new id attribute with jQuery? | To implement this, extract id from attr() and use replace() to replace the id attribute.
Following is the 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>
<link rel="stylesheet" href="//code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css">
<script src="https://code.jquery.com/jquery-1.12.4.js"></script>
<script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>
<body>
<div id="first-name">
</body>
<script>
$('[id*="-"]').each(function () {
console.log('Previous Id attribute: ' + $(this).attr('id'));
$(this).attr('id', $(this).attr('id').replace('-', '----'));
console.log('Now Id Attribute: ' + $(this).attr('id'));
});
</script>
</html>
To run the above program, save the file name “anyName.html(index.html)”. Right click on the file and select the option “Open with Live Server” in VS Code editor.
This will produce the following output −
Following is the value on console − | [
{
"code": null,
"e": 1151,
"s": 1062,
"text": "To implement this, extract id from attr() and use replace() to replace the id attribute."
},
{
"code": null,
"e": 1175,
"s": 1151,
"text": "Following is the code −"
},
{
"code": null,
"e": 1878,
"s": 1175,
"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</head>\n<link rel=\"stylesheet\" href=\"//code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css\">\n<script src=\"https://code.jquery.com/jquery-1.12.4.js\"></script>\n<script src=\"https://code.jquery.com/ui/1.12.1/jquery-ui.js\"></script>\n<body>\n <div id=\"first-name\">\n</body>\n<script>\n $('[id*=\"-\"]').each(function () {\n console.log('Previous Id attribute: ' + $(this).attr('id'));\n $(this).attr('id', $(this).attr('id').replace('-', '----'));\n console.log('Now Id Attribute: ' + $(this).attr('id'));\n });\n</script>\n</html>"
},
{
"code": null,
"e": 2040,
"s": 1878,
"text": "To run the above program, save the file name “anyName.html(index.html)”. Right click on the file and select the option “Open with Live Server” in VS Code editor."
},
{
"code": null,
"e": 2081,
"s": 2040,
"text": "This will produce the following output −"
},
{
"code": null,
"e": 2117,
"s": 2081,
"text": "Following is the value on console −"
}
] |
How to use PowerShell as a Calculator? Or How to use PowerShell for arithmetic operations? | You can use the PowerShell console to perform arithmetic operations, the same way the calculator does.
You can use the PowerShell console to perform arithmetic operations, the same way the calculator does.
To do the addition operation,
2+3
Output − 5
For complex, additional operations as well it is too quick.
For complex, additional operations as well it is too quick.
10024455 + 554668 + 9964455
Output − 20543578
Floating numbers operation,
Floating numbers operation,
5569899.65 + 554886.32
Output − 6124785.97
To perform subtract operation,
To perform subtract operation,
55564488556 - 55141256665
Output − 423231891
With Integer and floating number subtraction,
With Integer and floating number subtraction,
5569899 - 554886.32
Output − 5015012.68
Divide Operation,
Divide Operation,
556989 / 554
Output − 1005.39530685921
Multiplication operation,
Multiplication operation,
5533 * 445
Output − 2462185
Multiple Operations,
Multiple Operations,
(445 + 5443) * 332 / 32
Output − 61088
When you perform any arithmetic operation, when values separated by command, it will give the wrong values. For example,
When you perform any arithmetic operation, when values separated by command, it will give the wrong values. For example,
5,4 + 2
Output −
5
4
2
The above output is wrong because the comma(,) creates an array.
Powershell also works with Units like MB, GB, and KB. When you specify number and unit, there should not be space in between them. For example, 12mb is valid but 12 mb is invalid. It is case insensitive, so you can use MB or mb, GB or gb or KB or kb.
Powershell also works with Units like MB, GB, and KB. When you specify number and unit, there should not be space in between them. For example, 12mb is valid but 12 mb is invalid. It is case insensitive, so you can use MB or mb, GB or gb or KB or kb.
1gb / 1mb
Output − 1024
2gb * 6
Output − 12884901888
5GB - 2GB
Output − 3221225472
PowerShell also understands the hexadecimal values.
PowerShell also understands the hexadecimal values.
15 + 0xAF
Output − 190
0xAFF
Output − 2815 | [
{
"code": null,
"e": 1165,
"s": 1062,
"text": "You can use the PowerShell console to perform arithmetic operations, the same way the calculator does."
},
{
"code": null,
"e": 1268,
"s": 1165,
"text": "You can use the PowerShell console to perform arithmetic operations, the same way the calculator does."
},
{
"code": null,
"e": 1298,
"s": 1268,
"text": "To do the addition operation,"
},
{
"code": null,
"e": 1302,
"s": 1298,
"text": "2+3"
},
{
"code": null,
"e": 1313,
"s": 1302,
"text": "Output − 5"
},
{
"code": null,
"e": 1373,
"s": 1313,
"text": "For complex, additional operations as well it is too quick."
},
{
"code": null,
"e": 1433,
"s": 1373,
"text": "For complex, additional operations as well it is too quick."
},
{
"code": null,
"e": 1461,
"s": 1433,
"text": "10024455 + 554668 + 9964455"
},
{
"code": null,
"e": 1479,
"s": 1461,
"text": "Output − 20543578"
},
{
"code": null,
"e": 1507,
"s": 1479,
"text": "Floating numbers operation,"
},
{
"code": null,
"e": 1535,
"s": 1507,
"text": "Floating numbers operation,"
},
{
"code": null,
"e": 1558,
"s": 1535,
"text": "5569899.65 + 554886.32"
},
{
"code": null,
"e": 1578,
"s": 1558,
"text": "Output − 6124785.97"
},
{
"code": null,
"e": 1609,
"s": 1578,
"text": "To perform subtract operation,"
},
{
"code": null,
"e": 1640,
"s": 1609,
"text": "To perform subtract operation,"
},
{
"code": null,
"e": 1667,
"s": 1640,
"text": "55564488556 - 55141256665\n"
},
{
"code": null,
"e": 1686,
"s": 1667,
"text": "Output − 423231891"
},
{
"code": null,
"e": 1732,
"s": 1686,
"text": "With Integer and floating number subtraction,"
},
{
"code": null,
"e": 1778,
"s": 1732,
"text": "With Integer and floating number subtraction,"
},
{
"code": null,
"e": 1798,
"s": 1778,
"text": "5569899 - 554886.32"
},
{
"code": null,
"e": 1818,
"s": 1798,
"text": "Output − 5015012.68"
},
{
"code": null,
"e": 1836,
"s": 1818,
"text": "Divide Operation,"
},
{
"code": null,
"e": 1854,
"s": 1836,
"text": "Divide Operation,"
},
{
"code": null,
"e": 1867,
"s": 1854,
"text": "556989 / 554"
},
{
"code": null,
"e": 1893,
"s": 1867,
"text": "Output − 1005.39530685921"
},
{
"code": null,
"e": 1919,
"s": 1893,
"text": "Multiplication operation,"
},
{
"code": null,
"e": 1945,
"s": 1919,
"text": "Multiplication operation,"
},
{
"code": null,
"e": 1956,
"s": 1945,
"text": "5533 * 445"
},
{
"code": null,
"e": 1973,
"s": 1956,
"text": "Output − 2462185"
},
{
"code": null,
"e": 1994,
"s": 1973,
"text": "Multiple Operations,"
},
{
"code": null,
"e": 2015,
"s": 1994,
"text": "Multiple Operations,"
},
{
"code": null,
"e": 2040,
"s": 2015,
"text": "(445 + 5443) * 332 / 32\n"
},
{
"code": null,
"e": 2055,
"s": 2040,
"text": "Output − 61088"
},
{
"code": null,
"e": 2176,
"s": 2055,
"text": "When you perform any arithmetic operation, when values separated by command, it will give the wrong values. For example,"
},
{
"code": null,
"e": 2297,
"s": 2176,
"text": "When you perform any arithmetic operation, when values separated by command, it will give the wrong values. For example,"
},
{
"code": null,
"e": 2305,
"s": 2297,
"text": "5,4 + 2"
},
{
"code": null,
"e": 2314,
"s": 2305,
"text": "Output −"
},
{
"code": null,
"e": 2320,
"s": 2314,
"text": "5\n4\n2"
},
{
"code": null,
"e": 2385,
"s": 2320,
"text": "The above output is wrong because the comma(,) creates an array."
},
{
"code": null,
"e": 2636,
"s": 2385,
"text": "Powershell also works with Units like MB, GB, and KB. When you specify number and unit, there should not be space in between them. For example, 12mb is valid but 12 mb is invalid. It is case insensitive, so you can use MB or mb, GB or gb or KB or kb."
},
{
"code": null,
"e": 2887,
"s": 2636,
"text": "Powershell also works with Units like MB, GB, and KB. When you specify number and unit, there should not be space in between them. For example, 12mb is valid but 12 mb is invalid. It is case insensitive, so you can use MB or mb, GB or gb or KB or kb."
},
{
"code": null,
"e": 2897,
"s": 2887,
"text": "1gb / 1mb"
},
{
"code": null,
"e": 2911,
"s": 2897,
"text": "Output − 1024"
},
{
"code": null,
"e": 2919,
"s": 2911,
"text": "2gb * 6"
},
{
"code": null,
"e": 2940,
"s": 2919,
"text": "Output − 12884901888"
},
{
"code": null,
"e": 2951,
"s": 2940,
"text": "5GB - 2GB\n"
},
{
"code": null,
"e": 2971,
"s": 2951,
"text": "Output − 3221225472"
},
{
"code": null,
"e": 3023,
"s": 2971,
"text": "PowerShell also understands the hexadecimal values."
},
{
"code": null,
"e": 3075,
"s": 3023,
"text": "PowerShell also understands the hexadecimal values."
},
{
"code": null,
"e": 3085,
"s": 3075,
"text": "15 + 0xAF"
},
{
"code": null,
"e": 3098,
"s": 3085,
"text": "Output − 190"
},
{
"code": null,
"e": 3104,
"s": 3098,
"text": "0xAFF"
},
{
"code": null,
"e": 3118,
"s": 3104,
"text": "Output − 2815"
}
] |
How to prevent Serialization to break a Singleton Class Pattern? | A Singleton pattern states that a class can have a single instance and multiple instances are not permitted to be created. For this purpose, we make the constructor of the class a private and return a instance via a static method. But using serialization, we can still create multiple instance of a class. See the example below −
Live Demo
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable;
public class Tester{
public static void main(String[] args)
throws ClassNotFoundException, IOException{
A a = A.getInstance();
A b = (A) getSerializedCopy(a);
System.out.println(a.hashCode());
System.out.println(b.hashCode());
}
public static Object getSerializedCopy(Object sourceObject)
throws IOException, ClassNotFoundException {
ObjectOutputStream objectOutputStream = null;
ObjectInputStream objectInputStream = null;
ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
objectOutputStream = new ObjectOutputStream(byteArrayOutputStream);
objectOutputStream.writeObject(sourceObject);
objectOutputStream.flush();
objectInputStream = new ObjectInputStream(
new ByteArrayInputStream(byteArrayOutputStream.toByteArray()));
return objectInputStream.readObject();
}
}
class A implements Serializable {
private static A a;
private A(){}
public static A getInstance(){
if(a == null){
a = new A();
}
return a;
}
}
1550089733
865113938
Here you can see, we've created another object of a Singleton class. Let's see how to prevent such a situation −
Override readResolve() method in the singleton class.
// implement readResolve method
protected Object readResolve() {
return a;
}
1550089733
1550089733 | [
{
"code": null,
"e": 1392,
"s": 1062,
"text": "A Singleton pattern states that a class can have a single instance and multiple instances are not permitted to be created. For this purpose, we make the constructor of the class a private and return a instance via a static method. But using serialization, we can still create multiple instance of a class. See the example below −"
},
{
"code": null,
"e": 1403,
"s": 1392,
"text": " Live Demo"
},
{
"code": null,
"e": 2680,
"s": 1403,
"text": "import java.io.ByteArrayInputStream;\nimport java.io.ByteArrayOutputStream;\nimport java.io.IOException;\nimport java.io.ObjectInputStream;\nimport java.io.ObjectOutputStream;\nimport java.io.Serializable;\n\npublic class Tester{\n public static void main(String[] args)\n throws ClassNotFoundException, IOException{\n\n A a = A.getInstance();\n A b = (A) getSerializedCopy(a);\n\n System.out.println(a.hashCode());\n System.out.println(b.hashCode());\n }\n\n public static Object getSerializedCopy(Object sourceObject)\n throws IOException, ClassNotFoundException {\n ObjectOutputStream objectOutputStream = null;\n ObjectInputStream objectInputStream = null;\n ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();\n objectOutputStream = new ObjectOutputStream(byteArrayOutputStream);\n objectOutputStream.writeObject(sourceObject);\n objectOutputStream.flush();\n objectInputStream = new ObjectInputStream(\n\n new ByteArrayInputStream(byteArrayOutputStream.toByteArray()));\n return objectInputStream.readObject();\n }\n}\n\nclass A implements Serializable {\n private static A a;\n private A(){}\n\n public static A getInstance(){\n if(a == null){\n a = new A();\n }\n return a;\n }\n}"
},
{
"code": null,
"e": 2701,
"s": 2680,
"text": "1550089733\n865113938"
},
{
"code": null,
"e": 2814,
"s": 2701,
"text": "Here you can see, we've created another object of a Singleton class. Let's see how to prevent such a situation −"
},
{
"code": null,
"e": 2868,
"s": 2814,
"text": "Override readResolve() method in the singleton class."
},
{
"code": null,
"e": 2948,
"s": 2868,
"text": "// implement readResolve method\nprotected Object readResolve() {\n return a;\n}"
},
{
"code": null,
"e": 2970,
"s": 2948,
"text": "1550089733\n1550089733"
}
] |
Making a Bar Chart Race Plot using Plotly — made easy | by Luis Chaves | Towards Data Science | Have you ever seen these racing bar plots for ranking things or people over time? They are getting popular, they are fun to look at and they enable seeing who or what has topped a certain ranking over time. You might have seen the ranking of countries by COVID19 cases in 2020, or the ranking of the richest people from Rockefeller to Jeff Bezos. Whatever sort of ranking you are into, today you will learn how to make a racing plot of your own using Python and Plotly! — package provided too :)
Acknowledgments
Amanda Iglesias Moreno wrote a Medium post in 2017 on making a Bar chart race plot with the top baby names in Barcelona. I learned quite a bit from that post, my intention in this article is to use what I have learned from her post and other resources to make code that can be used for any specific use case.
This Plotly tutorial offers all the code to make an animated Gapminder scatterplot. While the example is very rich, little to no code is explained. I am writing this post to help others understand what all the Plotly arguments mean. When I use “weird” Plotly arguments I will explain what they do in simple terms in the code comments.
If you are not interested in seeing the inside of how to make this kind of plot, I’ve written a package for you to plot your own data hassle-free. Simply install the following package using pip
pip install raceplotly
And then run the following in a python script:
And you will obtain the timeline of the top 10 most-produced crops between 1961 and 2018 (see below). I obtained the data from the Food and Agriculture Organisation (FAO).
Please submit issues to the raceplotly repository if you find any or PRs if you want to offer improvements!
To those of you that are left here, thank you. I will try to be as succinct as possible in making you understand how to build one of these plots and go beyond.
Many new Plotly users first come across the plotly.express library. In this library, the Plotly developers have removed the complexity of Plotly figures to make it more user-friendly. Though whenever one wants to go beyond the plotly.express capacities it becomes necessary to see what is happening under the hood.
The first thing to know is that all Plotly figures contain 3 main elements: data, layout, and frames.
The data element is a python list containing information about the kind of plot you want to make: scatter plot, bar plot, funnel plot, heatmap, choropleth... and the relevant arguments for such plot: x, y, z, color, size...
The layout element is a python dictionary containing information about how the plot looks like, i.e. properties of the figure(title, size, legend, background-color...), properties of the axis (title, color, ticks...), and about the interactive properties of the figure (buttons, sliders, what and where to display when the user clicks or hovers over the figure). Additionally, many arguments are present to tweak every single kind of graph (specific to bar plots, specific to funnel plots...).
The frames element allow the user to make animated plots. frames is a python list containing each frame to be rendered in sequential order.
If you want more detail please refer to the official Plotly fundamentals guide about their Figure Data Structure and/or the documentation for the core Plotly Figure.
As with many other plotting libraries, Plotly offers a vast range of arguments to modify a plot. While this is useful when you wish to perfect a plot, it can also be overwhelming, especially when getting started or prototyping. Let’s now explore how to write a Plotly figure in python to generate a race bar plot like the one above.
As mentioned in Plotly Fundamentals, in python a Plotly figure can be a dictionary or a plotly.graph_objects.Figure instance. I personally do not prefer one over the other, I like creating an instance first but then access. We will be creating the Plotly figure element by element, first data then layout, and then frames, though of course, you could do this all in one block.
We will first load our data (the one I downloaded from FAO):
Note: If you are using a custom dataset, make sure it has 3 columns: one corresponding to the items you are ranking (Item in this tutorial), one corresponding to the value by which you are ranking (Value in this tutorial), and another corresponding to the year or date of each corresponding item-value pair (Year in this tutorial)
Now let’s instantiate our figure:
import plotly.graph_objects as gofig = { "data": [], "layout": {}, "frames": []}
Next, let’s define the data element. As we said before this must be a python list that contains the kind of plot we wish to make (in this case a bar plot) and the corresponding columns of our data frame corresponding to each axis. In our case we are building an animation and the data we select for the default figure will correspond to the data slice shown before the animation starts. Here I have chosen to make the default frame the one with the earliest available data (from 1961).
We also need one color per item we are ranking. Amanda Iglesias Moreno in her 2017 post, writes a function to assign an RGB triplet to each category. Using list comprehensions we can do this in one line (see code below).
Note: To see what’s possible with texttemplate refer to Plotly docs
Now let’s move on to populate the layout. My default choice here was to use a white background with no axis info in the y-axis (corresponding to the item names), given we are already displaying that information with text annotations. Additionally, I decided to show the x-axis ticks and their corresponding values and to set the x-axis to a fixed value (equal to the maximum ever value in the table).
Because we are creating an animated plot we must include two extra entries in our layout: update buttons (Play and Pause) and a slider. We will leave the slider empty for now as we will populate a slider dictionary when we create the frames. Plotly offers a layout property called updatemenus which allows us to create buttons, drop-down menus, update the layout, and control animations.
Note: The transition duration corresponds to how long the frame transition takes. Low values will make the transitions very snappy, like switching pictures whereas longer values will make it more like a video. The frame duration controls how long each frame is displayed.
Finally, we will create the frames corresponding to the top 10 for each year. In this step, we also populate the sliders property of the layout. This is done in this way so that each frame is linked to a position in the slider. First, we initialize a dictionary with the sliders meta-information and an empty stepslist:
Next, we make the frames and generate the steps:
Finally, and after all this hard work you can simply run go.Figure(fig) to display your hard-earned figure.
We need a whole lot of code to generate a Bar Chart Race plot. Moving that code around is painful, I encourage you to use raceplotly if you plan to use this often!
One thing I should point out is that our bars do not slide past each other when overtaking one another. I have not been able to implement this with Plotly, Ted Petrou managed to do so using matplotlib so check him out!
If you have made it this far, I hope you’ve found this useful. If you have any specific issue with your own plot feel free to get in touch.
PS: I must point you at the Flourish app for code-free happiness | [
{
"code": null,
"e": 667,
"s": 171,
"text": "Have you ever seen these racing bar plots for ranking things or people over time? They are getting popular, they are fun to look at and they enable seeing who or what has topped a certain ranking over time. You might have seen the ranking of countries by COVID19 cases in 2020, or the ranking of the richest people from Rockefeller to Jeff Bezos. Whatever sort of ranking you are into, today you will learn how to make a racing plot of your own using Python and Plotly! — package provided too :)"
},
{
"code": null,
"e": 683,
"s": 667,
"text": "Acknowledgments"
},
{
"code": null,
"e": 992,
"s": 683,
"text": "Amanda Iglesias Moreno wrote a Medium post in 2017 on making a Bar chart race plot with the top baby names in Barcelona. I learned quite a bit from that post, my intention in this article is to use what I have learned from her post and other resources to make code that can be used for any specific use case."
},
{
"code": null,
"e": 1327,
"s": 992,
"text": "This Plotly tutorial offers all the code to make an animated Gapminder scatterplot. While the example is very rich, little to no code is explained. I am writing this post to help others understand what all the Plotly arguments mean. When I use “weird” Plotly arguments I will explain what they do in simple terms in the code comments."
},
{
"code": null,
"e": 1521,
"s": 1327,
"text": "If you are not interested in seeing the inside of how to make this kind of plot, I’ve written a package for you to plot your own data hassle-free. Simply install the following package using pip"
},
{
"code": null,
"e": 1544,
"s": 1521,
"text": "pip install raceplotly"
},
{
"code": null,
"e": 1591,
"s": 1544,
"text": "And then run the following in a python script:"
},
{
"code": null,
"e": 1763,
"s": 1591,
"text": "And you will obtain the timeline of the top 10 most-produced crops between 1961 and 2018 (see below). I obtained the data from the Food and Agriculture Organisation (FAO)."
},
{
"code": null,
"e": 1871,
"s": 1763,
"text": "Please submit issues to the raceplotly repository if you find any or PRs if you want to offer improvements!"
},
{
"code": null,
"e": 2031,
"s": 1871,
"text": "To those of you that are left here, thank you. I will try to be as succinct as possible in making you understand how to build one of these plots and go beyond."
},
{
"code": null,
"e": 2346,
"s": 2031,
"text": "Many new Plotly users first come across the plotly.express library. In this library, the Plotly developers have removed the complexity of Plotly figures to make it more user-friendly. Though whenever one wants to go beyond the plotly.express capacities it becomes necessary to see what is happening under the hood."
},
{
"code": null,
"e": 2448,
"s": 2346,
"text": "The first thing to know is that all Plotly figures contain 3 main elements: data, layout, and frames."
},
{
"code": null,
"e": 2672,
"s": 2448,
"text": "The data element is a python list containing information about the kind of plot you want to make: scatter plot, bar plot, funnel plot, heatmap, choropleth... and the relevant arguments for such plot: x, y, z, color, size..."
},
{
"code": null,
"e": 3166,
"s": 2672,
"text": "The layout element is a python dictionary containing information about how the plot looks like, i.e. properties of the figure(title, size, legend, background-color...), properties of the axis (title, color, ticks...), and about the interactive properties of the figure (buttons, sliders, what and where to display when the user clicks or hovers over the figure). Additionally, many arguments are present to tweak every single kind of graph (specific to bar plots, specific to funnel plots...)."
},
{
"code": null,
"e": 3306,
"s": 3166,
"text": "The frames element allow the user to make animated plots. frames is a python list containing each frame to be rendered in sequential order."
},
{
"code": null,
"e": 3472,
"s": 3306,
"text": "If you want more detail please refer to the official Plotly fundamentals guide about their Figure Data Structure and/or the documentation for the core Plotly Figure."
},
{
"code": null,
"e": 3805,
"s": 3472,
"text": "As with many other plotting libraries, Plotly offers a vast range of arguments to modify a plot. While this is useful when you wish to perfect a plot, it can also be overwhelming, especially when getting started or prototyping. Let’s now explore how to write a Plotly figure in python to generate a race bar plot like the one above."
},
{
"code": null,
"e": 4182,
"s": 3805,
"text": "As mentioned in Plotly Fundamentals, in python a Plotly figure can be a dictionary or a plotly.graph_objects.Figure instance. I personally do not prefer one over the other, I like creating an instance first but then access. We will be creating the Plotly figure element by element, first data then layout, and then frames, though of course, you could do this all in one block."
},
{
"code": null,
"e": 4243,
"s": 4182,
"text": "We will first load our data (the one I downloaded from FAO):"
},
{
"code": null,
"e": 4574,
"s": 4243,
"text": "Note: If you are using a custom dataset, make sure it has 3 columns: one corresponding to the items you are ranking (Item in this tutorial), one corresponding to the value by which you are ranking (Value in this tutorial), and another corresponding to the year or date of each corresponding item-value pair (Year in this tutorial)"
},
{
"code": null,
"e": 4608,
"s": 4574,
"text": "Now let’s instantiate our figure:"
},
{
"code": null,
"e": 4698,
"s": 4608,
"text": "import plotly.graph_objects as gofig = { \"data\": [], \"layout\": {}, \"frames\": []}"
},
{
"code": null,
"e": 5184,
"s": 4698,
"text": "Next, let’s define the data element. As we said before this must be a python list that contains the kind of plot we wish to make (in this case a bar plot) and the corresponding columns of our data frame corresponding to each axis. In our case we are building an animation and the data we select for the default figure will correspond to the data slice shown before the animation starts. Here I have chosen to make the default frame the one with the earliest available data (from 1961)."
},
{
"code": null,
"e": 5405,
"s": 5184,
"text": "We also need one color per item we are ranking. Amanda Iglesias Moreno in her 2017 post, writes a function to assign an RGB triplet to each category. Using list comprehensions we can do this in one line (see code below)."
},
{
"code": null,
"e": 5473,
"s": 5405,
"text": "Note: To see what’s possible with texttemplate refer to Plotly docs"
},
{
"code": null,
"e": 5874,
"s": 5473,
"text": "Now let’s move on to populate the layout. My default choice here was to use a white background with no axis info in the y-axis (corresponding to the item names), given we are already displaying that information with text annotations. Additionally, I decided to show the x-axis ticks and their corresponding values and to set the x-axis to a fixed value (equal to the maximum ever value in the table)."
},
{
"code": null,
"e": 6262,
"s": 5874,
"text": "Because we are creating an animated plot we must include two extra entries in our layout: update buttons (Play and Pause) and a slider. We will leave the slider empty for now as we will populate a slider dictionary when we create the frames. Plotly offers a layout property called updatemenus which allows us to create buttons, drop-down menus, update the layout, and control animations."
},
{
"code": null,
"e": 6534,
"s": 6262,
"text": "Note: The transition duration corresponds to how long the frame transition takes. Low values will make the transitions very snappy, like switching pictures whereas longer values will make it more like a video. The frame duration controls how long each frame is displayed."
},
{
"code": null,
"e": 6854,
"s": 6534,
"text": "Finally, we will create the frames corresponding to the top 10 for each year. In this step, we also populate the sliders property of the layout. This is done in this way so that each frame is linked to a position in the slider. First, we initialize a dictionary with the sliders meta-information and an empty stepslist:"
},
{
"code": null,
"e": 6903,
"s": 6854,
"text": "Next, we make the frames and generate the steps:"
},
{
"code": null,
"e": 7011,
"s": 6903,
"text": "Finally, and after all this hard work you can simply run go.Figure(fig) to display your hard-earned figure."
},
{
"code": null,
"e": 7175,
"s": 7011,
"text": "We need a whole lot of code to generate a Bar Chart Race plot. Moving that code around is painful, I encourage you to use raceplotly if you plan to use this often!"
},
{
"code": null,
"e": 7394,
"s": 7175,
"text": "One thing I should point out is that our bars do not slide past each other when overtaking one another. I have not been able to implement this with Plotly, Ted Petrou managed to do so using matplotlib so check him out!"
},
{
"code": null,
"e": 7534,
"s": 7394,
"text": "If you have made it this far, I hope you’ve found this useful. If you have any specific issue with your own plot feel free to get in touch."
}
] |
Scala List take() method with example - GeeksforGeeks | 13 Aug, 2019
The take() method belongs to the value member of the class List. It is utilized to take the first n elements from the list.
Method Definition: deftake(n: Int): List[A]
Where, n is the number of elements to be taken from the list.
Return Type:It returns a list containing only the first n elements from the stated list or returns the whole list if n is more than the number of elements in the given list.
Example #1:
// Scala program of take()// method // Creating objectobject GfG{ // Main method def main(args:Array[String]) { // Creating a List val list = List(1, 2, 3, 4, 5, 6, 7) // Applying take method val result = list.take(4) // Displays output println(result) }}
List(1, 2, 3, 4)
Example #2:
// Scala program of take()// method // Creating objectobject GfG{ // Main method def main(args:Array[String]) { // Creating a List val list = List("a", "b", "c", "d", "e", "f") // Applying take method val result = list.take(4) // Displays output println(result) }}
List(a, b, c, d)
Scala
Scala-list
Scala-Method
Scala
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Type Casting in Scala
Class and Object in Scala
Scala Lists
Operators in Scala
Scala Tutorial – Learn Scala with Step By Step Guide
Scala Constructors
Scala String substring() method with example
Scala | Arrays
How to get the first element of List in Scala
Scala String replace() method with example | [
{
"code": null,
"e": 25493,
"s": 25465,
"text": "\n13 Aug, 2019"
},
{
"code": null,
"e": 25617,
"s": 25493,
"text": "The take() method belongs to the value member of the class List. It is utilized to take the first n elements from the list."
},
{
"code": null,
"e": 25661,
"s": 25617,
"text": "Method Definition: deftake(n: Int): List[A]"
},
{
"code": null,
"e": 25723,
"s": 25661,
"text": "Where, n is the number of elements to be taken from the list."
},
{
"code": null,
"e": 25897,
"s": 25723,
"text": "Return Type:It returns a list containing only the first n elements from the stated list or returns the whole list if n is more than the number of elements in the given list."
},
{
"code": null,
"e": 25909,
"s": 25897,
"text": "Example #1:"
},
{
"code": "// Scala program of take()// method // Creating objectobject GfG{ // Main method def main(args:Array[String]) { // Creating a List val list = List(1, 2, 3, 4, 5, 6, 7) // Applying take method val result = list.take(4) // Displays output println(result) }}",
"e": 26257,
"s": 25909,
"text": null
},
{
"code": null,
"e": 26275,
"s": 26257,
"text": "List(1, 2, 3, 4)\n"
},
{
"code": null,
"e": 26287,
"s": 26275,
"text": "Example #2:"
},
{
"code": "// Scala program of take()// method // Creating objectobject GfG{ // Main method def main(args:Array[String]) { // Creating a List val list = List(\"a\", \"b\", \"c\", \"d\", \"e\", \"f\") // Applying take method val result = list.take(4) // Displays output println(result) }}",
"e": 26644,
"s": 26287,
"text": null
},
{
"code": null,
"e": 26662,
"s": 26644,
"text": "List(a, b, c, d)\n"
},
{
"code": null,
"e": 26668,
"s": 26662,
"text": "Scala"
},
{
"code": null,
"e": 26679,
"s": 26668,
"text": "Scala-list"
},
{
"code": null,
"e": 26692,
"s": 26679,
"text": "Scala-Method"
},
{
"code": null,
"e": 26698,
"s": 26692,
"text": "Scala"
},
{
"code": null,
"e": 26796,
"s": 26698,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 26818,
"s": 26796,
"text": "Type Casting in Scala"
},
{
"code": null,
"e": 26844,
"s": 26818,
"text": "Class and Object in Scala"
},
{
"code": null,
"e": 26856,
"s": 26844,
"text": "Scala Lists"
},
{
"code": null,
"e": 26875,
"s": 26856,
"text": "Operators in Scala"
},
{
"code": null,
"e": 26928,
"s": 26875,
"text": "Scala Tutorial – Learn Scala with Step By Step Guide"
},
{
"code": null,
"e": 26947,
"s": 26928,
"text": "Scala Constructors"
},
{
"code": null,
"e": 26992,
"s": 26947,
"text": "Scala String substring() method with example"
},
{
"code": null,
"e": 27007,
"s": 26992,
"text": "Scala | Arrays"
},
{
"code": null,
"e": 27053,
"s": 27007,
"text": "How to get the first element of List in Scala"
}
] |
Special Keyboard | Practice | GeeksforGeeks | Imagine you have a special keyboard with the following keys:
Key 1: Prints 'A' on screen
Key 2: (Ctrl-A): Select screen
Key 3: (Ctrl-C): Copy selection to buffer
Key 4: (Ctrl-V): Print buffer on screen appending it after what has already been printed.
Find maximum numbers of A's that can be produced by pressing keys on the special keyboard N times.
Example 1:
Input: N = 3
Output: 3
Explaination: Press key 1 three times.
Example 2:
Input: N = 7
Output: 9
Explaination: The best key sequence is
key 1, key 1, key 1, key 2, key 3,
key4, key 4.
Your Task:
You do not need to read input or print anything. Your task is to complete the function optimalKeys() which takes N as input parameter and returns the maximum number of A's that can be on the screen after performing N operations.
Expected Time Complexity: O(N2)
Expected Auxiliary Space: O(N)
Constraints:
1 < N < 75
+1
bokonist3 weeks ago
O(N) space, O(N) time C++ solution with comments
.
.
#define lli long long int
long long int optimalKeys(int N)
{
if(N<=6)
return N;
lli screenSize[N+1], scp, scpp, scppp;
screenSize[0]=0;
for(int i=1;i<=6;i++)
screenSize[i]=i;
for(int i=7;i<=N;i++)
{
// option 1 is select, copy, paste the screensize at cur-3 using 3 keystrokes, doubling the size at cur-3
scp = 2* screenSize[i-3];
//option 2 is scpp the screensize at cur-4, using 4 keystrokes, tripling the size at cur-4
scpp = 3* screenSize[i-4];
//option 3 is scppp the screensize at cur-5, using 5 keystrokes, quadrupling the size at cur-5
scppp = 4 * screenSize[i-5];
screenSize[i] = max({scp, scpp, scppp}); //select the maximum from these 3
}
return screenSize[N];
}
0
putyavka3 weeks ago
Time O(N), Space O(N)
class Solution{
struct Entry {
long long f, g;
};
public:
long long int optimalKeys(int N){
vector<pair<Entry, Entry>> F(N + 4);
F[1] = {{1, 1},{}};
for (int i = 1; i < N; i++) {
auto& p = F[i];
auto& p1 = F[i + 1];
auto& p3 = F[i + 3];
if (p.first.f + p.first.g > p.second.f + p.second.g)
p1.first = { p.first.f + p.first.g, p.first.g };
else
p1.first = { p.second.f + p.second.g, p.second.g };
if (p.first.f > p.second.f)
p3.second = { p.first.f << 1, p.first.f };
else
p3.second = { p.second.f << 1, p.second.f };
}
return max(F[N].first.f, F[N].second.f);
}
};
+1
shyamprakash8071 month ago
Python solution :
Time taken : 0.0 / 5.7
class Solution: def optimalKeys(self, N): # code here if N <= 6: return N dp = [i if i<=6 else 0 for i in range(N+1)] for i in range(7, N+1): c = 2 for j in range(i-3, 0, -1): if dp[j]*c >= dp[i]: dp[i] = dp[j]*c else: break c += 1 return dp[N]
0
shashankrustagii4 months ago
//https://www.youtube.com/watch?v=c_y7H7qZJRU
class Solution{
public:
long long int optimalKeys(int N)
{
if(N <=6) return N;
vector<int> dp(N+1,0);
for(int i=1;i<=6;i++) dp[i]=i;
for(int i=7;i<=N;i++){
for(int j=i-3;j>=1;j--){
int curr = dp[j]*(i-j-1);
dp[i]=max(curr,dp[i]);
}
}
return dp[N];
}
};
+1
shashankrustagii4 months ago
//https://www.youtube.com/watch?v=c_y7H7qZJRU
class Solution{
public:
long long int optimalKeys(int N)
{
if(N <=6) return N;
vector<int> dp(N+1,0);
for(int i=1;i<=6;i++) dp[i]=i;
for(int i=7;i<=N;i++){
for(int j=i-3;j>=1;j--){
int curr = dp[j]*(i-j-1);
dp[i]=max(curr,dp[i]);
}
}
return dp[N];
}
};
0
shashankrustagii
This comment was deleted.
0
amrit_kumar4 months ago
c++ simple iterative
long long int optimalKeys(int N)
{
if(N <=6) return N;
int screen[N];
for(int i=1;i<=6;i++)
screen[i-1] = i;
for(int i=7;i<=N;i++)
{
int mul = 2;
int res = 0;
for(int j=i-3;j>=1;j--)
{
int cur = mul *screen[j-1];
res = max(cur,res);
mul++;
}
screen[i-1] = res;
}
return screen[N-1];
}
0
geminicode4 months ago
This is pure maths .. try solving it on paper you'll get it .
If stuck look at this solution.
#1. prints 1 char
#2. after 2 more presses doubles the char on the screen.
# max(dp[i], max we can get using j + (N- j we used -2 traversal)*jleft
# we will use dp
dp = [i for i in range(N+1)]
dp[1] = 1
for i in range(2,N+1):
for j in range(1,i):
if (N-j-2) > 0:
dp[i] = max(dp[i], dp[j]+ ((i-j-2)*dp[j]))
return dp[N]
+2
ankitkrrrrr6 months ago
class Solution{public: long long int optimalKeys(int N){ if(N<=6) return N; long long int dp[N+1]; dp[0]=0; for(int i=1;i<=6;i++) dp[i]=i; for(int i=7;i<=N;i++) dp[i]=max({2*dp[i-3],3*dp[i-4],4*dp[i-5]}); return dp[N]; }};
0
ahmadashad07867 months ago
long long int optimalKeys(int n){ // code here if(n<=6){ return n; } int dp[n+1]; for(int i=0; i<=n; i++){ dp[i]=i; } for(int i=7; i<=n; i++){ for(int j=i-3; j>=1; j--){ int curr=dp[j]*(i-j-1); dp[i]=max(dp[i],curr); } } return dp[n]; }
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": 300,
"s": 238,
"text": "Imagine you have a special keyboard with the following keys: "
},
{
"code": null,
"e": 493,
"s": 300,
"text": "Key 1: Prints 'A' on screen\nKey 2: (Ctrl-A): Select screen\nKey 3: (Ctrl-C): Copy selection to buffer\nKey 4: (Ctrl-V): Print buffer on screen appending it after what has already been printed. "
},
{
"code": null,
"e": 593,
"s": 493,
"text": "Find maximum numbers of A's that can be produced by pressing keys on the special keyboard N times. "
},
{
"code": null,
"e": 605,
"s": 593,
"text": "\nExample 1:"
},
{
"code": null,
"e": 667,
"s": 605,
"text": "Input: N = 3\nOutput: 3\nExplaination: Press key 1 three times."
},
{
"code": null,
"e": 679,
"s": 667,
"text": "\nExample 2:"
},
{
"code": null,
"e": 790,
"s": 679,
"text": "Input: N = 7\nOutput: 9\nExplaination: The best key sequence is \nkey 1, key 1, key 1, key 2, key 3,\nkey4, key 4."
},
{
"code": null,
"e": 1031,
"s": 790,
"text": "\nYour Task:\nYou do not need to read input or print anything. Your task is to complete the function optimalKeys() which takes N as input parameter and returns the maximum number of A's that can be on the screen after performing N operations."
},
{
"code": null,
"e": 1095,
"s": 1031,
"text": "\nExpected Time Complexity: O(N2)\nExpected Auxiliary Space: O(N)"
},
{
"code": null,
"e": 1120,
"s": 1095,
"text": "\nConstraints:\n1 < N < 75"
},
{
"code": null,
"e": 1123,
"s": 1120,
"text": "+1"
},
{
"code": null,
"e": 1143,
"s": 1123,
"text": "bokonist3 weeks ago"
},
{
"code": null,
"e": 1192,
"s": 1143,
"text": "O(N) space, O(N) time C++ solution with comments"
},
{
"code": null,
"e": 1194,
"s": 1192,
"text": "."
},
{
"code": null,
"e": 1196,
"s": 1194,
"text": "."
},
{
"code": null,
"e": 1975,
"s": 1196,
"text": "#define lli long long int\nlong long int optimalKeys(int N)\n{\n if(N<=6) \n return N;\n lli screenSize[N+1], scp, scpp, scppp;\n screenSize[0]=0;\n for(int i=1;i<=6;i++)\n screenSize[i]=i;\n for(int i=7;i<=N;i++)\n {\n // option 1 is select, copy, paste the screensize at cur-3 using 3 keystrokes, doubling the size at cur-3\n scp = 2* screenSize[i-3];\n //option 2 is scpp the screensize at cur-4, using 4 keystrokes, tripling the size at cur-4\n scpp = 3* screenSize[i-4];\n //option 3 is scppp the screensize at cur-5, using 5 keystrokes, quadrupling the size at cur-5\n scppp = 4 * screenSize[i-5];\n screenSize[i] = max({scp, scpp, scppp}); //select the maximum from these 3\n }\n return screenSize[N];\n}"
},
{
"code": null,
"e": 1977,
"s": 1975,
"text": "0"
},
{
"code": null,
"e": 1997,
"s": 1977,
"text": "putyavka3 weeks ago"
},
{
"code": null,
"e": 2019,
"s": 1997,
"text": "Time O(N), Space O(N)"
},
{
"code": null,
"e": 2796,
"s": 2019,
"text": "class Solution{\n struct Entry {\n long long f, g;\n };\npublic:\n long long int optimalKeys(int N){\n vector<pair<Entry, Entry>> F(N + 4);\n F[1] = {{1, 1},{}};\n for (int i = 1; i < N; i++) {\n auto& p = F[i];\n auto& p1 = F[i + 1];\n auto& p3 = F[i + 3];\n if (p.first.f + p.first.g > p.second.f + p.second.g)\n p1.first = { p.first.f + p.first.g, p.first.g };\n else\n p1.first = { p.second.f + p.second.g, p.second.g };\n if (p.first.f > p.second.f)\n p3.second = { p.first.f << 1, p.first.f };\n else\n p3.second = { p.second.f << 1, p.second.f };\n }\n return max(F[N].first.f, F[N].second.f);\n }\n};"
},
{
"code": null,
"e": 2799,
"s": 2796,
"text": "+1"
},
{
"code": null,
"e": 2826,
"s": 2799,
"text": "shyamprakash8071 month ago"
},
{
"code": null,
"e": 2844,
"s": 2826,
"text": "Python solution :"
},
{
"code": null,
"e": 2867,
"s": 2844,
"text": "Time taken : 0.0 / 5.7"
},
{
"code": null,
"e": 3275,
"s": 2869,
"text": "class Solution: def optimalKeys(self, N): # code here if N <= 6: return N dp = [i if i<=6 else 0 for i in range(N+1)] for i in range(7, N+1): c = 2 for j in range(i-3, 0, -1): if dp[j]*c >= dp[i]: dp[i] = dp[j]*c else: break c += 1 return dp[N] "
},
{
"code": null,
"e": 3277,
"s": 3275,
"text": "0"
},
{
"code": null,
"e": 3306,
"s": 3277,
"text": "shashankrustagii4 months ago"
},
{
"code": null,
"e": 3734,
"s": 3306,
"text": "//https://www.youtube.com/watch?v=c_y7H7qZJRU\nclass Solution{\npublic:\n long long int optimalKeys(int N)\n {\n if(N <=6) return N;\n vector<int> dp(N+1,0);\n for(int i=1;i<=6;i++) dp[i]=i;\n for(int i=7;i<=N;i++){\n for(int j=i-3;j>=1;j--){\n int curr = dp[j]*(i-j-1);\n dp[i]=max(curr,dp[i]);\n }\n \n }\n return dp[N];\n }\n};"
},
{
"code": null,
"e": 3737,
"s": 3734,
"text": "+1"
},
{
"code": null,
"e": 3766,
"s": 3737,
"text": "shashankrustagii4 months ago"
},
{
"code": null,
"e": 4196,
"s": 3768,
"text": "//https://www.youtube.com/watch?v=c_y7H7qZJRU\nclass Solution{\npublic:\n long long int optimalKeys(int N)\n {\n if(N <=6) return N;\n vector<int> dp(N+1,0);\n for(int i=1;i<=6;i++) dp[i]=i;\n for(int i=7;i<=N;i++){\n for(int j=i-3;j>=1;j--){\n int curr = dp[j]*(i-j-1);\n dp[i]=max(curr,dp[i]);\n }\n \n }\n return dp[N];\n }\n};"
},
{
"code": null,
"e": 4198,
"s": 4196,
"text": "0"
},
{
"code": null,
"e": 4215,
"s": 4198,
"text": "shashankrustagii"
},
{
"code": null,
"e": 4241,
"s": 4215,
"text": "This comment was deleted."
},
{
"code": null,
"e": 4243,
"s": 4241,
"text": "0"
},
{
"code": null,
"e": 4267,
"s": 4243,
"text": "amrit_kumar4 months ago"
},
{
"code": null,
"e": 4288,
"s": 4267,
"text": "c++ simple iterative"
},
{
"code": null,
"e": 4801,
"s": 4288,
"text": "long long int optimalKeys(int N)\n {\n if(N <=6) return N;\n \n int screen[N];\n \n for(int i=1;i<=6;i++)\n screen[i-1] = i;\n \n for(int i=7;i<=N;i++)\n {\n int mul = 2;\n int res = 0;\n for(int j=i-3;j>=1;j--)\n {\n int cur = mul *screen[j-1];\n res = max(cur,res);\n mul++;\n }\n screen[i-1] = res;\n }\n return screen[N-1];\n \n }"
},
{
"code": null,
"e": 4803,
"s": 4801,
"text": "0"
},
{
"code": null,
"e": 4826,
"s": 4803,
"text": "geminicode4 months ago"
},
{
"code": null,
"e": 4888,
"s": 4826,
"text": "This is pure maths .. try solving it on paper you'll get it ."
},
{
"code": null,
"e": 4920,
"s": 4888,
"text": "If stuck look at this solution."
},
{
"code": null,
"e": 5343,
"s": 4920,
"text": "#1. prints 1 char\n #2. after 2 more presses doubles the char on the screen.\n # max(dp[i], max we can get using j + (N- j we used -2 traversal)*jleft\n # we will use dp\n dp = [i for i in range(N+1)]\n dp[1] = 1\n for i in range(2,N+1):\n for j in range(1,i):\n if (N-j-2) > 0:\n dp[i] = max(dp[i], dp[j]+ ((i-j-2)*dp[j]))\n return dp[N]"
},
{
"code": null,
"e": 5346,
"s": 5343,
"text": "+2"
},
{
"code": null,
"e": 5370,
"s": 5346,
"text": "ankitkrrrrr6 months ago"
},
{
"code": null,
"e": 5645,
"s": 5370,
"text": "class Solution{public: long long int optimalKeys(int N){ if(N<=6) return N; long long int dp[N+1]; dp[0]=0; for(int i=1;i<=6;i++) dp[i]=i; for(int i=7;i<=N;i++) dp[i]=max({2*dp[i-3],3*dp[i-4],4*dp[i-5]}); return dp[N]; }};"
},
{
"code": null,
"e": 5647,
"s": 5645,
"text": "0"
},
{
"code": null,
"e": 5674,
"s": 5647,
"text": "ahmadashad07867 months ago"
},
{
"code": null,
"e": 6049,
"s": 5674,
"text": "long long int optimalKeys(int n){ // code here if(n<=6){ return n; } int dp[n+1]; for(int i=0; i<=n; i++){ dp[i]=i; } for(int i=7; i<=n; i++){ for(int j=i-3; j>=1; j--){ int curr=dp[j]*(i-j-1); dp[i]=max(dp[i],curr); } } return dp[n]; }"
},
{
"code": null,
"e": 6195,
"s": 6049,
"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": 6231,
"s": 6195,
"text": " Login to access your submissions. "
},
{
"code": null,
"e": 6241,
"s": 6231,
"text": "\nProblem\n"
},
{
"code": null,
"e": 6251,
"s": 6241,
"text": "\nContest\n"
},
{
"code": null,
"e": 6314,
"s": 6251,
"text": "Reset the IDE using the second button on the top right corner."
},
{
"code": null,
"e": 6462,
"s": 6314,
"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": 6670,
"s": 6462,
"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": 6776,
"s": 6670,
"text": "You can access the hints to get an idea about what is expected of you as well as the final solution code."
}
] |
Binary Indexed Tree : Range Updates and Point Queries - GeeksforGeeks | 25 Feb, 2020
Given an array arr[0..n-1]. The following operations need to be performed.
update(l, r, val) : Add ‘val’ to all the elements in the array from [l, r].getElement(i) : Find element in the array indexed at ‘i’.Initially all the elements in the array are 0. Queries can be in any order, i.e., there can be many updates before point query.Example:Input : arr = {0, 0, 0, 0, 0}
Queries: update : l = 0, r = 4, val = 2
getElement : i = 3
update : l = 3, r = 4, val = 3
getElement : i = 3
Output: Element at 3 is 2
Element at 3 is 5
Explanation : Array after first update becomes
{2, 2, 2, 2, 2}
Array after second update becomes
{2, 2, 2, 5, 5}
Method 1 [update : O(n), getElement() : O(1)]update(l, r, val) : Iterate over the subarray from l to r and increase all the elements by val.getElement(i) : To get the element at i’th index, simply return arr[i].The time complexity in worst case is O(q*n) where q is number of queries and n is number of elements. Method 2 [update : O(1), getElement() : O(n)]We can avoid updating all elements and can update only 2 indexes of the array!update(l, r, val) : Add ‘val’ to the lth element and subtract ‘val’ from the (r+1)th element, do this for all the update queries. arr[l] = arr[l] + val
arr[r+1] = arr[r+1] - val
getElement(i) : To get ith element in the array find the sum of all integers in the array from 0 to i.(Prefix Sum).
Let’s analyze the update query.
Why to add val to lth index?
Adding val to lth index means that all the elements after l are increased by val, since we will be computing the prefix sum for every element.
Why to subtract val from (r+1)th index?
A range update was required from [l,r] but what we have updated is [l, n-1] so we need to remove val from all the elements after r i.e., subtract val from (r+1)th index.
Thus the val is added to range [l,r].
Below is implementation of above approach.
C++JavaPython3C#PHP
C++
// C++ program to demonstrate Range Update // and Point Queries Without using BIT #include <bits/stdc++.h> using namespace std; // Updates such that getElement() gets an increased // value when queried from l to r. void update(int arr[], int l, int r, int val) { arr[l] += val; arr[r+1] -= val; } // Get the element indexed at i int getElement(int arr[], int i) { // To get ith element sum of all the elements // from 0 to i need to be computed int res = 0; for (int j = 0 ; j <= i; j++) res += arr[j]; return res; } // Driver program to test above function int main() { int arr[] = {0, 0, 0, 0, 0}; int n = sizeof(arr) / sizeof(arr[0]); int l = 2, r = 4, val = 2; update(arr, l, r, val); //Find the element at Index 4 int index = 4; cout << "Element at index " << index << " is " << getElement(arr, index) << endl; l = 0, r = 3, val = 4; update(arr,l,r,val); //Find the element at Index 3 index = 3; cout << "Element at index " << index << " is " << getElement(arr, index) << endl; return 0; }
Java// Java program to demonstrate Range Update // and Point Queries Without using BIT class GfG { // Updates such that getElement() gets an increased // value when queried from l to r. static void update(int arr[], int l, int r, int val) { arr[l] += val; if(r + 1 < arr.length) arr[r+1] -= val; } // Get the element indexed at i static int getElement(int arr[], int i) { // To get ith element sum of all the elements // from 0 to i need to be computed int res = 0; for (int j = 0 ; j <= i; j++) res += arr[j]; return res; } // Driver program to test above function public static void main(String[] args) { int arr[] = {0, 0, 0, 0, 0}; int n = arr.length; int l = 2, r = 4, val = 2; update(arr, l, r, val); //Find the element at Index 4 int index = 4; System.out.println("Element at index " + index + " is " +getElement(arr, index)); l = 0; r = 3; val = 4; update(arr,l,r,val); //Find the element at Index 3 index = 3; System.out.println("Element at index " + index + " is " +getElement(arr, index)); }} Python3# Python3 program to demonstrate Range # Update and PoQueries Without using BIT # Updates such that getElement() gets an # increased value when queried from l to r. def update(arr, l, r, val): arr[l] += val if r + 1 < len(arr): arr[r + 1] -= val # Get the element indexed at i def getElement(arr, i): # To get ith element sum of all the elements # from 0 to i need to be computed res = 0 for j in range(i + 1): res += arr[j] return res # Driver Codeif __name__ == '__main__': arr = [0, 0, 0, 0, 0] n = len(arr) l = 2 r = 4 val = 2 update(arr, l, r, val) # Find the element at Index 4 index = 4 print("Element at index", index, "is", getElement(arr, index)) l = 0 r = 3 val = 4 update(arr, l, r, val) # Find the element at Index 3 index = 3 print("Element at index", index, "is", getElement(arr, index)) # This code is contributed by PranchalKC#// C# program to demonstrate Range Update // and Point Queries Without using BIT using System; class GfG { // Updates such that getElement() // gets an increased value when// queried from l to r. static void update(int []arr, int l, int r, int val) { arr[l] += val; if(r + 1 < arr.Length) arr[r + 1] -= val; } // Get the element indexed at i static int getElement(int []arr, int i) { // To get ith element sum of all the elements // from 0 to i need to be computed int res = 0; for (int j = 0 ; j <= i; j++) res += arr[j]; return res; } // Driver code public static void Main(String[] args) { int []arr = {0, 0, 0, 0, 0}; int n = arr.Length; int l = 2, r = 4, val = 2; update(arr, l, r, val); //Find the element at Index 4 int index = 4; Console.WriteLine("Element at index " + index + " is " + getElement(arr, index)); l = 0; r = 3; val = 4; update(arr,l,r,val); //Find the element at Index 3 index = 3; Console.WriteLine("Element at index " + index + " is " + getElement(arr, index)); } } // This code is contributed by PrinciRaj1992PHP<?php// PHP program to demonstrate Range Update // and Point Queries Without using BIT // Updates such that getElement() gets an // increased value when queried from l to r. function update(&$arr, $l, $r, $val) { $arr[$l] += $val; if($r + 1 < sizeof($arr)) $arr[$r + 1] -= $val; } // Get the element indexed at i function getElement(&$arr, $i) { // To get ith element sum of all the elements // from 0 to i need to be computed $res = 0; for ($j = 0 ; $j <= $i; $j++) $res += $arr[$j]; return $res; } // Driver Code$arr = array(0, 0, 0, 0, 0); $n = sizeof($arr); $l = 2; $r = 4; $val = 2; update($arr, $l, $r, $val); // Find the element at Index 4 $index = 4; echo("Element at index " . $index . " is " . getElement($arr, $index) . "\n"); $l = 0;$r = 3;$val = 4; update($arr, $l, $r, $val); // Find the element at Index 3 $index = 3; echo("Element at index " . $index . " is " . getElement($arr, $index)); // This code is contributed by Code_Mech?>Output:Element at index 4 is 2
Element at index 3 is 6
Time complexity : O(q*n) where q is number of queries. Method 3 (Using Binary Indexed Tree)In method 2, we have seen that the problem can reduced to update and prefix sum queries. We have seen that BIT can be used to do update and prefix sum queries in O(Logn) time.Below is the implementation.C++JavaPython3C#C++// C++ code to demonstrate Range Update and// Point Queries on a Binary Index Tree#include <bits/stdc++.h>using namespace std; // Updates a node in Binary Index Tree (BITree) at given index// in BITree. The given value 'val' is added to BITree[i] and// all of its ancestors in tree.void updateBIT(int BITree[], int n, int index, int val){ // index in BITree[] is 1 more than the index in arr[] index = index + 1; // Traverse all ancestors and add 'val' while (index <= n) { // Add 'val' to current node of BI Tree BITree[index] += val; // Update index to that of parent in update View index += index & (-index); }} // Constructs and returns a Binary Indexed Tree for given// array of size n.int *constructBITree(int arr[], int n){ // Create and initialize BITree[] as 0 int *BITree = new int[n+1]; for (int i=1; i<=n; i++) BITree[i] = 0; // Store the actual values in BITree[] using update() for (int i=0; i<n; i++) updateBIT(BITree, n, i, arr[i]); // Uncomment below lines to see contents of BITree[] //for (int i=1; i<=n; i++) // cout << BITree[i] << " "; return BITree;} // SERVES THE PURPOSE OF getElement()// Returns sum of arr[0..index]. This function assumes// that the array is preprocessed and partial sums of// array elements are stored in BITree[]int getSum(int BITree[], int index){ int sum = 0; // Iniialize result // index in BITree[] is 1 more than the index in arr[] index = index + 1; // Traverse ancestors of BITree[index] while (index>0) { // Add current element of BITree to sum sum += BITree[index]; // Move index to parent node in getSum View index -= index & (-index); } return sum;} // Updates such that getElement() gets an increased// value when queried from l to r.void update(int BITree[], int l, int r, int n, int val){ // Increase value at 'l' by 'val' updateBIT(BITree, n, l, val); // Decrease value at 'r+1' by 'val' updateBIT(BITree, n, r+1, -val);} // Driver program to test above functionint main(){ int arr[] = {0, 0, 0, 0, 0}; int n = sizeof(arr)/sizeof(arr[0]); int *BITree = constructBITree(arr, n); // Add 2 to all the element from [2,4] int l = 2, r = 4, val = 2; update(BITree, l, r, n, val); // Find the element at Index 4 int index = 4; cout << "Element at index " << index << " is " << getSum(BITree,index) << "\n"; // Add 2 to all the element from [0,3] l = 0, r = 3, val = 4; update(BITree, l, r, n, val); // Find the element at Index 3 index = 3; cout << "Element at index " << index << " is " << getSum(BITree,index) << "\n" ; return 0;}Java/* Java code to demonstrate Range Update and* Point Queries on a Binary Index Tree.* This method only works when all array* values are initially 0.*/class GFG{ // Max tree size final static int MAX = 1000; static int BITree[] = new int[MAX]; // Updates a node in Binary Index // Tree (BITree) at given index // in BITree. The given value 'val' // is added to BITree[i] and // all of its ancestors in tree. public static void updateBIT(int n, int index, int val) { // index in BITree[] is 1 // more than the index in arr[] index = index + 1; // Traverse all ancestors // and add 'val' while (index <= n) { // Add 'val' to current // node of BITree BITree[index] += val; // Update index to that // of parent in update View index += index & (-index); } } // Constructs Binary Indexed Tree // for given array of size n. public static void constructBITree(int arr[], int n) { // Initialize BITree[] as 0 for(int i = 1; i <= n; i++) BITree[i] = 0; // Store the actual values // in BITree[] using update() for(int i = 0; i < n; i++) updateBIT(n, i, arr[i]); // Uncomment below lines to // see contents of BITree[] // for (int i=1; i<=n; i++) // cout << BITree[i] << " "; } // SERVES THE PURPOSE OF getElement() // Returns sum of arr[0..index]. This // function assumes that the array is // preprocessed and partial sums of // array elements are stored in BITree[] public static int getSum(int index) { int sum = 0; //Initialize result // index in BITree[] is 1 more // than the index in arr[] index = index + 1; // Traverse ancestors // of BITree[index] while (index > 0) { // Add current element // of BITree to sum sum += BITree[index]; // Move index to parent // node in getSum View index -= index & (-index); } // Return the sum return sum; } // Updates such that getElement() // gets an increased value when // queried from l to r. public static void update(int l, int r, int n, int val) { // Increase value at // 'l' by 'val' updateBIT(n, l, val); // Decrease value at // 'r+1' by 'val' updateBIT(n, r + 1, -val); } // Driver Code public static void main(String args[]) { int arr[] = {0, 0, 0, 0, 0}; int n = arr.length; constructBITree(arr,n); // Add 2 to all the // element from [2,4] int l = 2, r = 4, val = 2; update(l, r, n, val); int index = 4; System.out.println("Element at index "+ index + " is "+ getSum(index)); // Add 2 to all the // element from [0,3] l = 0; r = 3; val = 4; update(l, r, n, val); // Find the element // at Index 3 index = 3; System.out.println("Element at index "+ index + " is "+ getSum(index)); }}// This code is contributed// by Puneet Kumar.Python3# Python3 code to demonstrate Range Update and# PoQueries on a Binary Index Tree # Updates a node in Binary Index Tree (BITree) at given index# in BITree. The given value 'val' is added to BITree[i] and# all of its ancestors in tree.def updateBIT(BITree, n, index, val): # index in BITree[] is 1 more than the index in arr[] index = index + 1 # Traverse all ancestors and add 'val' while (index <= n): # Add 'val' to current node of BI Tree BITree[index] += val # Update index to that of parent in update View index += index & (-index) # Constructs and returns a Binary Indexed Tree for given# array of size n.def constructBITree(arr, n): # Create and initialize BITree[] as 0 BITree = [0]*(n+1) # Store the actual values in BITree[] using update() for i in range(n): updateBIT(BITree, n, i, arr[i]) return BITree # SERVES THE PURPOSE OF getElement()# Returns sum of arr[0..index]. This function assumes# that the array is preprocessed and partial sums of# array elements are stored in BITree[]def getSum(BITree, index): sum = 0 # Iniialize result # index in BITree[] is 1 more than the index in arr[] index = index + 1 # Traverse ancestors of BITree[index] while (index > 0): # Add current element of BITree to sum sum += BITree[index] # Move index to parent node in getSum View index -= index & (-index) return sum # Updates such that getElement() gets an increased# value when queried from l to r.def update(BITree, l, r, n, val): # Increase value at 'l' by 'val' updateBIT(BITree, n, l, val) # Decrease value at 'r+1' by 'val' updateBIT(BITree, n, r+1, -val) # Driver codearr = [0, 0, 0, 0, 0]n = len(arr)BITree = constructBITree(arr, n) # Add 2 to all the element from [2,4]l = 2r = 4val = 2update(BITree, l, r, n, val) # Find the element at Index 4index = 4print("Element at index", index, "is", getSum(BITree, index)) # Add 2 to all the element from [0,3]l = 0r = 3val = 4update(BITree, l, r, n, val) # Find the element at Index 3index = 3print("Element at index", index, "is", getSum(BITree,index)) # This code is contributed by mohit kumar 29C#using System; /* C# code to demonstrate Range Update and * Point Queries on a Binary Index Tree. * This method only works when all array * values are initially 0.*/public class GFG{ // Max tree size public const int MAX = 1000; public static int[] BITree = new int[MAX]; // Updates a node in Binary Index // Tree (BITree) at given index // in BITree. The given value 'val' // is added to BITree[i] and // all of its ancestors in tree. public static void updateBIT(int n, int index, int val) { // index in BITree[] is 1 // more than the index in arr[] index = index + 1; // Traverse all ancestors // and add 'val' while (index <= n) { // Add 'val' to current // node of BITree BITree[index] += val; // Update index to that // of parent in update View index += index & (-index); } } // Constructs Binary Indexed Tree // for given array of size n. public static void constructBITree(int[] arr, int n) { // Initialize BITree[] as 0 for (int i = 1; i <= n; i++) { BITree[i] = 0; } // Store the actual values // in BITree[] using update() for (int i = 0; i < n; i++) { updateBIT(n, i, arr[i]); } // Uncomment below lines to // see contents of BITree[] // for (int i=1; i<=n; i++) // cout << BITree[i] << " "; } // SERVES THE PURPOSE OF getElement() // Returns sum of arr[0..index]. This // function assumes that the array is // preprocessed and partial sums of // array elements are stored in BITree[] public static int getSum(int index) { int sum = 0; //Initialize result // index in BITree[] is 1 more // than the index in arr[] index = index + 1; // Traverse ancestors // of BITree[index] while (index > 0) { // Add current element // of BITree to sum sum += BITree[index]; // Move index to parent // node in getSum View index -= index & (-index); } // Return the sum return sum; } // Updates such that getElement() // gets an increased value when // queried from l to r. public static void update(int l, int r, int n, int val) { // Increase value at // 'l' by 'val' updateBIT(n, l, val); // Decrease value at // 'r+1' by 'val' updateBIT(n, r + 1, -val); } // Driver Code public static void Main(string[] args) { int[] arr = new int[] {0, 0, 0, 0, 0}; int n = arr.Length; constructBITree(arr,n); // Add 2 to all the // element from [2,4] int l = 2, r = 4, val = 2; update(l, r, n, val); int index = 4; Console.WriteLine("Element at index " + index + " is " + getSum(index)); // Add 2 to all the // element from [0,3] l = 0; r = 3; val = 4; update(l, r, n, val); // Find the element // at Index 3 index = 3; Console.WriteLine("Element at index " + index + " is " + getSum(index)); }} // This code is contributed by Shrikant13Output:Element at index 4 is 2
Element at index 3 is 6
Time Complexity : O(q * log n) + O(n * log n) where q is number of queries.Method 1 is efficient when most of the queries are getElement(), method 2 is efficient when most of the queries are updates() and method 3 is preferred when there is mix of both queries.This article is contributed by Chirag Agarwal. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.My Personal Notes
arrow_drop_upSave
update(l, r, val) : Add ‘val’ to all the elements in the array from [l, r].
getElement(i) : Find element in the array indexed at ‘i’.Initially all the elements in the array are 0. Queries can be in any order, i.e., there can be many updates before point query.Example:Input : arr = {0, 0, 0, 0, 0}
Queries: update : l = 0, r = 4, val = 2
getElement : i = 3
update : l = 3, r = 4, val = 3
getElement : i = 3
Output: Element at 3 is 2
Element at 3 is 5
Explanation : Array after first update becomes
{2, 2, 2, 2, 2}
Array after second update becomes
{2, 2, 2, 5, 5}
Method 1 [update : O(n), getElement() : O(1)]update(l, r, val) : Iterate over the subarray from l to r and increase all the elements by val.getElement(i) : To get the element at i’th index, simply return arr[i].The time complexity in worst case is O(q*n) where q is number of queries and n is number of elements. Method 2 [update : O(1), getElement() : O(n)]We can avoid updating all elements and can update only 2 indexes of the array!update(l, r, val) : Add ‘val’ to the lth element and subtract ‘val’ from the (r+1)th element, do this for all the update queries. arr[l] = arr[l] + val
arr[r+1] = arr[r+1] - val
getElement(i) : To get ith element in the array find the sum of all integers in the array from 0 to i.(Prefix Sum).
Let’s analyze the update query.
Why to add val to lth index?
Adding val to lth index means that all the elements after l are increased by val, since we will be computing the prefix sum for every element.
Why to subtract val from (r+1)th index?
A range update was required from [l,r] but what we have updated is [l, n-1] so we need to remove val from all the elements after r i.e., subtract val from (r+1)th index.
Thus the val is added to range [l,r].
Below is implementation of above approach.
C++JavaPython3C#PHP
C++
// C++ program to demonstrate Range Update // and Point Queries Without using BIT #include <bits/stdc++.h> using namespace std; // Updates such that getElement() gets an increased // value when queried from l to r. void update(int arr[], int l, int r, int val) { arr[l] += val; arr[r+1] -= val; } // Get the element indexed at i int getElement(int arr[], int i) { // To get ith element sum of all the elements // from 0 to i need to be computed int res = 0; for (int j = 0 ; j <= i; j++) res += arr[j]; return res; } // Driver program to test above function int main() { int arr[] = {0, 0, 0, 0, 0}; int n = sizeof(arr) / sizeof(arr[0]); int l = 2, r = 4, val = 2; update(arr, l, r, val); //Find the element at Index 4 int index = 4; cout << "Element at index " << index << " is " << getElement(arr, index) << endl; l = 0, r = 3, val = 4; update(arr,l,r,val); //Find the element at Index 3 index = 3; cout << "Element at index " << index << " is " << getElement(arr, index) << endl; return 0; }
Java// Java program to demonstrate Range Update // and Point Queries Without using BIT class GfG { // Updates such that getElement() gets an increased // value when queried from l to r. static void update(int arr[], int l, int r, int val) { arr[l] += val; if(r + 1 < arr.length) arr[r+1] -= val; } // Get the element indexed at i static int getElement(int arr[], int i) { // To get ith element sum of all the elements // from 0 to i need to be computed int res = 0; for (int j = 0 ; j <= i; j++) res += arr[j]; return res; } // Driver program to test above function public static void main(String[] args) { int arr[] = {0, 0, 0, 0, 0}; int n = arr.length; int l = 2, r = 4, val = 2; update(arr, l, r, val); //Find the element at Index 4 int index = 4; System.out.println("Element at index " + index + " is " +getElement(arr, index)); l = 0; r = 3; val = 4; update(arr,l,r,val); //Find the element at Index 3 index = 3; System.out.println("Element at index " + index + " is " +getElement(arr, index)); }} Python3# Python3 program to demonstrate Range # Update and PoQueries Without using BIT # Updates such that getElement() gets an # increased value when queried from l to r. def update(arr, l, r, val): arr[l] += val if r + 1 < len(arr): arr[r + 1] -= val # Get the element indexed at i def getElement(arr, i): # To get ith element sum of all the elements # from 0 to i need to be computed res = 0 for j in range(i + 1): res += arr[j] return res # Driver Codeif __name__ == '__main__': arr = [0, 0, 0, 0, 0] n = len(arr) l = 2 r = 4 val = 2 update(arr, l, r, val) # Find the element at Index 4 index = 4 print("Element at index", index, "is", getElement(arr, index)) l = 0 r = 3 val = 4 update(arr, l, r, val) # Find the element at Index 3 index = 3 print("Element at index", index, "is", getElement(arr, index)) # This code is contributed by PranchalKC#// C# program to demonstrate Range Update // and Point Queries Without using BIT using System; class GfG { // Updates such that getElement() // gets an increased value when// queried from l to r. static void update(int []arr, int l, int r, int val) { arr[l] += val; if(r + 1 < arr.Length) arr[r + 1] -= val; } // Get the element indexed at i static int getElement(int []arr, int i) { // To get ith element sum of all the elements // from 0 to i need to be computed int res = 0; for (int j = 0 ; j <= i; j++) res += arr[j]; return res; } // Driver code public static void Main(String[] args) { int []arr = {0, 0, 0, 0, 0}; int n = arr.Length; int l = 2, r = 4, val = 2; update(arr, l, r, val); //Find the element at Index 4 int index = 4; Console.WriteLine("Element at index " + index + " is " + getElement(arr, index)); l = 0; r = 3; val = 4; update(arr,l,r,val); //Find the element at Index 3 index = 3; Console.WriteLine("Element at index " + index + " is " + getElement(arr, index)); } } // This code is contributed by PrinciRaj1992PHP<?php// PHP program to demonstrate Range Update // and Point Queries Without using BIT // Updates such that getElement() gets an // increased value when queried from l to r. function update(&$arr, $l, $r, $val) { $arr[$l] += $val; if($r + 1 < sizeof($arr)) $arr[$r + 1] -= $val; } // Get the element indexed at i function getElement(&$arr, $i) { // To get ith element sum of all the elements // from 0 to i need to be computed $res = 0; for ($j = 0 ; $j <= $i; $j++) $res += $arr[$j]; return $res; } // Driver Code$arr = array(0, 0, 0, 0, 0); $n = sizeof($arr); $l = 2; $r = 4; $val = 2; update($arr, $l, $r, $val); // Find the element at Index 4 $index = 4; echo("Element at index " . $index . " is " . getElement($arr, $index) . "\n"); $l = 0;$r = 3;$val = 4; update($arr, $l, $r, $val); // Find the element at Index 3 $index = 3; echo("Element at index " . $index . " is " . getElement($arr, $index)); // This code is contributed by Code_Mech?>Output:Element at index 4 is 2
Element at index 3 is 6
Time complexity : O(q*n) where q is number of queries. Method 3 (Using Binary Indexed Tree)In method 2, we have seen that the problem can reduced to update and prefix sum queries. We have seen that BIT can be used to do update and prefix sum queries in O(Logn) time.Below is the implementation.C++JavaPython3C#C++// C++ code to demonstrate Range Update and// Point Queries on a Binary Index Tree#include <bits/stdc++.h>using namespace std; // Updates a node in Binary Index Tree (BITree) at given index// in BITree. The given value 'val' is added to BITree[i] and// all of its ancestors in tree.void updateBIT(int BITree[], int n, int index, int val){ // index in BITree[] is 1 more than the index in arr[] index = index + 1; // Traverse all ancestors and add 'val' while (index <= n) { // Add 'val' to current node of BI Tree BITree[index] += val; // Update index to that of parent in update View index += index & (-index); }} // Constructs and returns a Binary Indexed Tree for given// array of size n.int *constructBITree(int arr[], int n){ // Create and initialize BITree[] as 0 int *BITree = new int[n+1]; for (int i=1; i<=n; i++) BITree[i] = 0; // Store the actual values in BITree[] using update() for (int i=0; i<n; i++) updateBIT(BITree, n, i, arr[i]); // Uncomment below lines to see contents of BITree[] //for (int i=1; i<=n; i++) // cout << BITree[i] << " "; return BITree;} // SERVES THE PURPOSE OF getElement()// Returns sum of arr[0..index]. This function assumes// that the array is preprocessed and partial sums of// array elements are stored in BITree[]int getSum(int BITree[], int index){ int sum = 0; // Iniialize result // index in BITree[] is 1 more than the index in arr[] index = index + 1; // Traverse ancestors of BITree[index] while (index>0) { // Add current element of BITree to sum sum += BITree[index]; // Move index to parent node in getSum View index -= index & (-index); } return sum;} // Updates such that getElement() gets an increased// value when queried from l to r.void update(int BITree[], int l, int r, int n, int val){ // Increase value at 'l' by 'val' updateBIT(BITree, n, l, val); // Decrease value at 'r+1' by 'val' updateBIT(BITree, n, r+1, -val);} // Driver program to test above functionint main(){ int arr[] = {0, 0, 0, 0, 0}; int n = sizeof(arr)/sizeof(arr[0]); int *BITree = constructBITree(arr, n); // Add 2 to all the element from [2,4] int l = 2, r = 4, val = 2; update(BITree, l, r, n, val); // Find the element at Index 4 int index = 4; cout << "Element at index " << index << " is " << getSum(BITree,index) << "\n"; // Add 2 to all the element from [0,3] l = 0, r = 3, val = 4; update(BITree, l, r, n, val); // Find the element at Index 3 index = 3; cout << "Element at index " << index << " is " << getSum(BITree,index) << "\n" ; return 0;}Java/* Java code to demonstrate Range Update and* Point Queries on a Binary Index Tree.* This method only works when all array* values are initially 0.*/class GFG{ // Max tree size final static int MAX = 1000; static int BITree[] = new int[MAX]; // Updates a node in Binary Index // Tree (BITree) at given index // in BITree. The given value 'val' // is added to BITree[i] and // all of its ancestors in tree. public static void updateBIT(int n, int index, int val) { // index in BITree[] is 1 // more than the index in arr[] index = index + 1; // Traverse all ancestors // and add 'val' while (index <= n) { // Add 'val' to current // node of BITree BITree[index] += val; // Update index to that // of parent in update View index += index & (-index); } } // Constructs Binary Indexed Tree // for given array of size n. public static void constructBITree(int arr[], int n) { // Initialize BITree[] as 0 for(int i = 1; i <= n; i++) BITree[i] = 0; // Store the actual values // in BITree[] using update() for(int i = 0; i < n; i++) updateBIT(n, i, arr[i]); // Uncomment below lines to // see contents of BITree[] // for (int i=1; i<=n; i++) // cout << BITree[i] << " "; } // SERVES THE PURPOSE OF getElement() // Returns sum of arr[0..index]. This // function assumes that the array is // preprocessed and partial sums of // array elements are stored in BITree[] public static int getSum(int index) { int sum = 0; //Initialize result // index in BITree[] is 1 more // than the index in arr[] index = index + 1; // Traverse ancestors // of BITree[index] while (index > 0) { // Add current element // of BITree to sum sum += BITree[index]; // Move index to parent // node in getSum View index -= index & (-index); } // Return the sum return sum; } // Updates such that getElement() // gets an increased value when // queried from l to r. public static void update(int l, int r, int n, int val) { // Increase value at // 'l' by 'val' updateBIT(n, l, val); // Decrease value at // 'r+1' by 'val' updateBIT(n, r + 1, -val); } // Driver Code public static void main(String args[]) { int arr[] = {0, 0, 0, 0, 0}; int n = arr.length; constructBITree(arr,n); // Add 2 to all the // element from [2,4] int l = 2, r = 4, val = 2; update(l, r, n, val); int index = 4; System.out.println("Element at index "+ index + " is "+ getSum(index)); // Add 2 to all the // element from [0,3] l = 0; r = 3; val = 4; update(l, r, n, val); // Find the element // at Index 3 index = 3; System.out.println("Element at index "+ index + " is "+ getSum(index)); }}// This code is contributed// by Puneet Kumar.Python3# Python3 code to demonstrate Range Update and# PoQueries on a Binary Index Tree # Updates a node in Binary Index Tree (BITree) at given index# in BITree. The given value 'val' is added to BITree[i] and# all of its ancestors in tree.def updateBIT(BITree, n, index, val): # index in BITree[] is 1 more than the index in arr[] index = index + 1 # Traverse all ancestors and add 'val' while (index <= n): # Add 'val' to current node of BI Tree BITree[index] += val # Update index to that of parent in update View index += index & (-index) # Constructs and returns a Binary Indexed Tree for given# array of size n.def constructBITree(arr, n): # Create and initialize BITree[] as 0 BITree = [0]*(n+1) # Store the actual values in BITree[] using update() for i in range(n): updateBIT(BITree, n, i, arr[i]) return BITree # SERVES THE PURPOSE OF getElement()# Returns sum of arr[0..index]. This function assumes# that the array is preprocessed and partial sums of# array elements are stored in BITree[]def getSum(BITree, index): sum = 0 # Iniialize result # index in BITree[] is 1 more than the index in arr[] index = index + 1 # Traverse ancestors of BITree[index] while (index > 0): # Add current element of BITree to sum sum += BITree[index] # Move index to parent node in getSum View index -= index & (-index) return sum # Updates such that getElement() gets an increased# value when queried from l to r.def update(BITree, l, r, n, val): # Increase value at 'l' by 'val' updateBIT(BITree, n, l, val) # Decrease value at 'r+1' by 'val' updateBIT(BITree, n, r+1, -val) # Driver codearr = [0, 0, 0, 0, 0]n = len(arr)BITree = constructBITree(arr, n) # Add 2 to all the element from [2,4]l = 2r = 4val = 2update(BITree, l, r, n, val) # Find the element at Index 4index = 4print("Element at index", index, "is", getSum(BITree, index)) # Add 2 to all the element from [0,3]l = 0r = 3val = 4update(BITree, l, r, n, val) # Find the element at Index 3index = 3print("Element at index", index, "is", getSum(BITree,index)) # This code is contributed by mohit kumar 29C#using System; /* C# code to demonstrate Range Update and * Point Queries on a Binary Index Tree. * This method only works when all array * values are initially 0.*/public class GFG{ // Max tree size public const int MAX = 1000; public static int[] BITree = new int[MAX]; // Updates a node in Binary Index // Tree (BITree) at given index // in BITree. The given value 'val' // is added to BITree[i] and // all of its ancestors in tree. public static void updateBIT(int n, int index, int val) { // index in BITree[] is 1 // more than the index in arr[] index = index + 1; // Traverse all ancestors // and add 'val' while (index <= n) { // Add 'val' to current // node of BITree BITree[index] += val; // Update index to that // of parent in update View index += index & (-index); } } // Constructs Binary Indexed Tree // for given array of size n. public static void constructBITree(int[] arr, int n) { // Initialize BITree[] as 0 for (int i = 1; i <= n; i++) { BITree[i] = 0; } // Store the actual values // in BITree[] using update() for (int i = 0; i < n; i++) { updateBIT(n, i, arr[i]); } // Uncomment below lines to // see contents of BITree[] // for (int i=1; i<=n; i++) // cout << BITree[i] << " "; } // SERVES THE PURPOSE OF getElement() // Returns sum of arr[0..index]. This // function assumes that the array is // preprocessed and partial sums of // array elements are stored in BITree[] public static int getSum(int index) { int sum = 0; //Initialize result // index in BITree[] is 1 more // than the index in arr[] index = index + 1; // Traverse ancestors // of BITree[index] while (index > 0) { // Add current element // of BITree to sum sum += BITree[index]; // Move index to parent // node in getSum View index -= index & (-index); } // Return the sum return sum; } // Updates such that getElement() // gets an increased value when // queried from l to r. public static void update(int l, int r, int n, int val) { // Increase value at // 'l' by 'val' updateBIT(n, l, val); // Decrease value at // 'r+1' by 'val' updateBIT(n, r + 1, -val); } // Driver Code public static void Main(string[] args) { int[] arr = new int[] {0, 0, 0, 0, 0}; int n = arr.Length; constructBITree(arr,n); // Add 2 to all the // element from [2,4] int l = 2, r = 4, val = 2; update(l, r, n, val); int index = 4; Console.WriteLine("Element at index " + index + " is " + getSum(index)); // Add 2 to all the // element from [0,3] l = 0; r = 3; val = 4; update(l, r, n, val); // Find the element // at Index 3 index = 3; Console.WriteLine("Element at index " + index + " is " + getSum(index)); }} // This code is contributed by Shrikant13Output:Element at index 4 is 2
Element at index 3 is 6
Time Complexity : O(q * log n) + O(n * log n) where q is number of queries.Method 1 is efficient when most of the queries are getElement(), method 2 is efficient when most of the queries are updates() and method 3 is preferred when there is mix of both queries.This article is contributed by Chirag Agarwal. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.My Personal Notes
arrow_drop_upSave
Initially all the elements in the array are 0. Queries can be in any order, i.e., there can be many updates before point query.
Example:
Input : arr = {0, 0, 0, 0, 0}
Queries: update : l = 0, r = 4, val = 2
getElement : i = 3
update : l = 3, r = 4, val = 3
getElement : i = 3
Output: Element at 3 is 2
Element at 3 is 5
Explanation : Array after first update becomes
{2, 2, 2, 2, 2}
Array after second update becomes
{2, 2, 2, 5, 5}
Method 1 [update : O(n), getElement() : O(1)]
update(l, r, val) : Iterate over the subarray from l to r and increase all the elements by val.getElement(i) : To get the element at i’th index, simply return arr[i].
update(l, r, val) : Iterate over the subarray from l to r and increase all the elements by val.
getElement(i) : To get the element at i’th index, simply return arr[i].
The time complexity in worst case is O(q*n) where q is number of queries and n is number of elements.
Method 2 [update : O(1), getElement() : O(n)]
We can avoid updating all elements and can update only 2 indexes of the array!
update(l, r, val) : Add ‘val’ to the lth element and subtract ‘val’ from the (r+1)th element, do this for all the update queries. arr[l] = arr[l] + val
arr[r+1] = arr[r+1] - val
getElement(i) : To get ith element in the array find the sum of all integers in the array from 0 to i.(Prefix Sum).
update(l, r, val) : Add ‘val’ to the lth element and subtract ‘val’ from the (r+1)th element, do this for all the update queries. arr[l] = arr[l] + val
arr[r+1] = arr[r+1] - val
getElement(i) : To get ith element in the array find the sum of all integers in the array from 0 to i.(Prefix Sum).
arr[l] = arr[l] + val
arr[r+1] = arr[r+1] - val
getElement(i) : To get ith element in the array find the sum of all integers in the array from 0 to i.(Prefix Sum).
getElement(i) : To get ith element in the array find the sum of all integers in the array from 0 to i.(Prefix Sum).
C++
Java
Python3
C#
PHP
// C++ program to demonstrate Range Update // and Point Queries Without using BIT #include <bits/stdc++.h> using namespace std; // Updates such that getElement() gets an increased // value when queried from l to r. void update(int arr[], int l, int r, int val) { arr[l] += val; arr[r+1] -= val; } // Get the element indexed at i int getElement(int arr[], int i) { // To get ith element sum of all the elements // from 0 to i need to be computed int res = 0; for (int j = 0 ; j <= i; j++) res += arr[j]; return res; } // Driver program to test above function int main() { int arr[] = {0, 0, 0, 0, 0}; int n = sizeof(arr) / sizeof(arr[0]); int l = 2, r = 4, val = 2; update(arr, l, r, val); //Find the element at Index 4 int index = 4; cout << "Element at index " << index << " is " << getElement(arr, index) << endl; l = 0, r = 3, val = 4; update(arr,l,r,val); //Find the element at Index 3 index = 3; cout << "Element at index " << index << " is " << getElement(arr, index) << endl; return 0; }
// Java program to demonstrate Range Update // and Point Queries Without using BIT class GfG { // Updates such that getElement() gets an increased // value when queried from l to r. static void update(int arr[], int l, int r, int val) { arr[l] += val; if(r + 1 < arr.length) arr[r+1] -= val; } // Get the element indexed at i static int getElement(int arr[], int i) { // To get ith element sum of all the elements // from 0 to i need to be computed int res = 0; for (int j = 0 ; j <= i; j++) res += arr[j]; return res; } // Driver program to test above function public static void main(String[] args) { int arr[] = {0, 0, 0, 0, 0}; int n = arr.length; int l = 2, r = 4, val = 2; update(arr, l, r, val); //Find the element at Index 4 int index = 4; System.out.println("Element at index " + index + " is " +getElement(arr, index)); l = 0; r = 3; val = 4; update(arr,l,r,val); //Find the element at Index 3 index = 3; System.out.println("Element at index " + index + " is " +getElement(arr, index)); }}
# Python3 program to demonstrate Range # Update and PoQueries Without using BIT # Updates such that getElement() gets an # increased value when queried from l to r. def update(arr, l, r, val): arr[l] += val if r + 1 < len(arr): arr[r + 1] -= val # Get the element indexed at i def getElement(arr, i): # To get ith element sum of all the elements # from 0 to i need to be computed res = 0 for j in range(i + 1): res += arr[j] return res # Driver Codeif __name__ == '__main__': arr = [0, 0, 0, 0, 0] n = len(arr) l = 2 r = 4 val = 2 update(arr, l, r, val) # Find the element at Index 4 index = 4 print("Element at index", index, "is", getElement(arr, index)) l = 0 r = 3 val = 4 update(arr, l, r, val) # Find the element at Index 3 index = 3 print("Element at index", index, "is", getElement(arr, index)) # This code is contributed by PranchalK
// C# program to demonstrate Range Update // and Point Queries Without using BIT using System; class GfG { // Updates such that getElement() // gets an increased value when// queried from l to r. static void update(int []arr, int l, int r, int val) { arr[l] += val; if(r + 1 < arr.Length) arr[r + 1] -= val; } // Get the element indexed at i static int getElement(int []arr, int i) { // To get ith element sum of all the elements // from 0 to i need to be computed int res = 0; for (int j = 0 ; j <= i; j++) res += arr[j]; return res; } // Driver code public static void Main(String[] args) { int []arr = {0, 0, 0, 0, 0}; int n = arr.Length; int l = 2, r = 4, val = 2; update(arr, l, r, val); //Find the element at Index 4 int index = 4; Console.WriteLine("Element at index " + index + " is " + getElement(arr, index)); l = 0; r = 3; val = 4; update(arr,l,r,val); //Find the element at Index 3 index = 3; Console.WriteLine("Element at index " + index + " is " + getElement(arr, index)); } } // This code is contributed by PrinciRaj1992
<?php// PHP program to demonstrate Range Update // and Point Queries Without using BIT // Updates such that getElement() gets an // increased value when queried from l to r. function update(&$arr, $l, $r, $val) { $arr[$l] += $val; if($r + 1 < sizeof($arr)) $arr[$r + 1] -= $val; } // Get the element indexed at i function getElement(&$arr, $i) { // To get ith element sum of all the elements // from 0 to i need to be computed $res = 0; for ($j = 0 ; $j <= $i; $j++) $res += $arr[$j]; return $res; } // Driver Code$arr = array(0, 0, 0, 0, 0); $n = sizeof($arr); $l = 2; $r = 4; $val = 2; update($arr, $l, $r, $val); // Find the element at Index 4 $index = 4; echo("Element at index " . $index . " is " . getElement($arr, $index) . "\n"); $l = 0;$r = 3;$val = 4; update($arr, $l, $r, $val); // Find the element at Index 3 $index = 3; echo("Element at index " . $index . " is " . getElement($arr, $index)); // This code is contributed by Code_Mech?>
Element at index 4 is 2
Element at index 3 is 6
Time complexity : O(q*n) where q is number of queries.
Method 3 (Using Binary Indexed Tree)
In method 2, we have seen that the problem can reduced to update and prefix sum queries. We have seen that BIT can be used to do update and prefix sum queries in O(Logn) time.
Below is the implementation.
C++
Java
Python3
C#
// C++ code to demonstrate Range Update and// Point Queries on a Binary Index Tree#include <bits/stdc++.h>using namespace std; // Updates a node in Binary Index Tree (BITree) at given index// in BITree. The given value 'val' is added to BITree[i] and// all of its ancestors in tree.void updateBIT(int BITree[], int n, int index, int val){ // index in BITree[] is 1 more than the index in arr[] index = index + 1; // Traverse all ancestors and add 'val' while (index <= n) { // Add 'val' to current node of BI Tree BITree[index] += val; // Update index to that of parent in update View index += index & (-index); }} // Constructs and returns a Binary Indexed Tree for given// array of size n.int *constructBITree(int arr[], int n){ // Create and initialize BITree[] as 0 int *BITree = new int[n+1]; for (int i=1; i<=n; i++) BITree[i] = 0; // Store the actual values in BITree[] using update() for (int i=0; i<n; i++) updateBIT(BITree, n, i, arr[i]); // Uncomment below lines to see contents of BITree[] //for (int i=1; i<=n; i++) // cout << BITree[i] << " "; return BITree;} // SERVES THE PURPOSE OF getElement()// Returns sum of arr[0..index]. This function assumes// that the array is preprocessed and partial sums of// array elements are stored in BITree[]int getSum(int BITree[], int index){ int sum = 0; // Iniialize result // index in BITree[] is 1 more than the index in arr[] index = index + 1; // Traverse ancestors of BITree[index] while (index>0) { // Add current element of BITree to sum sum += BITree[index]; // Move index to parent node in getSum View index -= index & (-index); } return sum;} // Updates such that getElement() gets an increased// value when queried from l to r.void update(int BITree[], int l, int r, int n, int val){ // Increase value at 'l' by 'val' updateBIT(BITree, n, l, val); // Decrease value at 'r+1' by 'val' updateBIT(BITree, n, r+1, -val);} // Driver program to test above functionint main(){ int arr[] = {0, 0, 0, 0, 0}; int n = sizeof(arr)/sizeof(arr[0]); int *BITree = constructBITree(arr, n); // Add 2 to all the element from [2,4] int l = 2, r = 4, val = 2; update(BITree, l, r, n, val); // Find the element at Index 4 int index = 4; cout << "Element at index " << index << " is " << getSum(BITree,index) << "\n"; // Add 2 to all the element from [0,3] l = 0, r = 3, val = 4; update(BITree, l, r, n, val); // Find the element at Index 3 index = 3; cout << "Element at index " << index << " is " << getSum(BITree,index) << "\n" ; return 0;}
/* Java code to demonstrate Range Update and* Point Queries on a Binary Index Tree.* This method only works when all array* values are initially 0.*/class GFG{ // Max tree size final static int MAX = 1000; static int BITree[] = new int[MAX]; // Updates a node in Binary Index // Tree (BITree) at given index // in BITree. The given value 'val' // is added to BITree[i] and // all of its ancestors in tree. public static void updateBIT(int n, int index, int val) { // index in BITree[] is 1 // more than the index in arr[] index = index + 1; // Traverse all ancestors // and add 'val' while (index <= n) { // Add 'val' to current // node of BITree BITree[index] += val; // Update index to that // of parent in update View index += index & (-index); } } // Constructs Binary Indexed Tree // for given array of size n. public static void constructBITree(int arr[], int n) { // Initialize BITree[] as 0 for(int i = 1; i <= n; i++) BITree[i] = 0; // Store the actual values // in BITree[] using update() for(int i = 0; i < n; i++) updateBIT(n, i, arr[i]); // Uncomment below lines to // see contents of BITree[] // for (int i=1; i<=n; i++) // cout << BITree[i] << " "; } // SERVES THE PURPOSE OF getElement() // Returns sum of arr[0..index]. This // function assumes that the array is // preprocessed and partial sums of // array elements are stored in BITree[] public static int getSum(int index) { int sum = 0; //Initialize result // index in BITree[] is 1 more // than the index in arr[] index = index + 1; // Traverse ancestors // of BITree[index] while (index > 0) { // Add current element // of BITree to sum sum += BITree[index]; // Move index to parent // node in getSum View index -= index & (-index); } // Return the sum return sum; } // Updates such that getElement() // gets an increased value when // queried from l to r. public static void update(int l, int r, int n, int val) { // Increase value at // 'l' by 'val' updateBIT(n, l, val); // Decrease value at // 'r+1' by 'val' updateBIT(n, r + 1, -val); } // Driver Code public static void main(String args[]) { int arr[] = {0, 0, 0, 0, 0}; int n = arr.length; constructBITree(arr,n); // Add 2 to all the // element from [2,4] int l = 2, r = 4, val = 2; update(l, r, n, val); int index = 4; System.out.println("Element at index "+ index + " is "+ getSum(index)); // Add 2 to all the // element from [0,3] l = 0; r = 3; val = 4; update(l, r, n, val); // Find the element // at Index 3 index = 3; System.out.println("Element at index "+ index + " is "+ getSum(index)); }}// This code is contributed// by Puneet Kumar.
# Python3 code to demonstrate Range Update and# PoQueries on a Binary Index Tree # Updates a node in Binary Index Tree (BITree) at given index# in BITree. The given value 'val' is added to BITree[i] and# all of its ancestors in tree.def updateBIT(BITree, n, index, val): # index in BITree[] is 1 more than the index in arr[] index = index + 1 # Traverse all ancestors and add 'val' while (index <= n): # Add 'val' to current node of BI Tree BITree[index] += val # Update index to that of parent in update View index += index & (-index) # Constructs and returns a Binary Indexed Tree for given# array of size n.def constructBITree(arr, n): # Create and initialize BITree[] as 0 BITree = [0]*(n+1) # Store the actual values in BITree[] using update() for i in range(n): updateBIT(BITree, n, i, arr[i]) return BITree # SERVES THE PURPOSE OF getElement()# Returns sum of arr[0..index]. This function assumes# that the array is preprocessed and partial sums of# array elements are stored in BITree[]def getSum(BITree, index): sum = 0 # Iniialize result # index in BITree[] is 1 more than the index in arr[] index = index + 1 # Traverse ancestors of BITree[index] while (index > 0): # Add current element of BITree to sum sum += BITree[index] # Move index to parent node in getSum View index -= index & (-index) return sum # Updates such that getElement() gets an increased# value when queried from l to r.def update(BITree, l, r, n, val): # Increase value at 'l' by 'val' updateBIT(BITree, n, l, val) # Decrease value at 'r+1' by 'val' updateBIT(BITree, n, r+1, -val) # Driver codearr = [0, 0, 0, 0, 0]n = len(arr)BITree = constructBITree(arr, n) # Add 2 to all the element from [2,4]l = 2r = 4val = 2update(BITree, l, r, n, val) # Find the element at Index 4index = 4print("Element at index", index, "is", getSum(BITree, index)) # Add 2 to all the element from [0,3]l = 0r = 3val = 4update(BITree, l, r, n, val) # Find the element at Index 3index = 3print("Element at index", index, "is", getSum(BITree,index)) # This code is contributed by mohit kumar 29
using System; /* C# code to demonstrate Range Update and * Point Queries on a Binary Index Tree. * This method only works when all array * values are initially 0.*/public class GFG{ // Max tree size public const int MAX = 1000; public static int[] BITree = new int[MAX]; // Updates a node in Binary Index // Tree (BITree) at given index // in BITree. The given value 'val' // is added to BITree[i] and // all of its ancestors in tree. public static void updateBIT(int n, int index, int val) { // index in BITree[] is 1 // more than the index in arr[] index = index + 1; // Traverse all ancestors // and add 'val' while (index <= n) { // Add 'val' to current // node of BITree BITree[index] += val; // Update index to that // of parent in update View index += index & (-index); } } // Constructs Binary Indexed Tree // for given array of size n. public static void constructBITree(int[] arr, int n) { // Initialize BITree[] as 0 for (int i = 1; i <= n; i++) { BITree[i] = 0; } // Store the actual values // in BITree[] using update() for (int i = 0; i < n; i++) { updateBIT(n, i, arr[i]); } // Uncomment below lines to // see contents of BITree[] // for (int i=1; i<=n; i++) // cout << BITree[i] << " "; } // SERVES THE PURPOSE OF getElement() // Returns sum of arr[0..index]. This // function assumes that the array is // preprocessed and partial sums of // array elements are stored in BITree[] public static int getSum(int index) { int sum = 0; //Initialize result // index in BITree[] is 1 more // than the index in arr[] index = index + 1; // Traverse ancestors // of BITree[index] while (index > 0) { // Add current element // of BITree to sum sum += BITree[index]; // Move index to parent // node in getSum View index -= index & (-index); } // Return the sum return sum; } // Updates such that getElement() // gets an increased value when // queried from l to r. public static void update(int l, int r, int n, int val) { // Increase value at // 'l' by 'val' updateBIT(n, l, val); // Decrease value at // 'r+1' by 'val' updateBIT(n, r + 1, -val); } // Driver Code public static void Main(string[] args) { int[] arr = new int[] {0, 0, 0, 0, 0}; int n = arr.Length; constructBITree(arr,n); // Add 2 to all the // element from [2,4] int l = 2, r = 4, val = 2; update(l, r, n, val); int index = 4; Console.WriteLine("Element at index " + index + " is " + getSum(index)); // Add 2 to all the // element from [0,3] l = 0; r = 3; val = 4; update(l, r, n, val); // Find the element // at Index 3 index = 3; Console.WriteLine("Element at index " + index + " is " + getSum(index)); }} // This code is contributed by Shrikant13
Output:
Element at index 4 is 2
Element at index 3 is 6
Time Complexity : O(q * log n) + O(n * log n) where q is number of queries.
Method 1 is efficient when most of the queries are getElement(), method 2 is efficient when most of the queries are updates() and method 3 is preferred when there is mix of both queries.
This article is contributed by Chirag Agarwal. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
p_unit
shrikanth13
prerna saini
princiraj1992
PranchalKatiyar
Code_Mech
nidhi_biet
mohit kumar 29
array-range-queries
Binary Indexed Tree
Advanced Data Structure
Tree
Tree
Binary Indexed Tree
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Agents in Artificial Intelligence
Decision Tree Introduction with example
AVL Tree | Set 2 (Deletion)
Red-Black Tree | Set 2 (Insert)
Disjoint Set Data Structures
Tree Traversals (Inorder, Preorder and Postorder)
Binary Tree | Set 1 (Introduction)
Level Order Binary Tree Traversal
Binary Tree | Set 3 (Types of Binary Tree)
Inorder Tree Traversal without Recursion | [
{
"code": null,
"e": 25911,
"s": 25883,
"text": "\n25 Feb, 2020"
},
{
"code": null,
"e": 25986,
"s": 25911,
"text": "Given an array arr[0..n-1]. The following operations need to be performed."
},
{
"code": null,
"e": 46476,
"s": 25986,
"text": "update(l, r, val) : Add ‘val’ to all the elements in the array from [l, r].getElement(i) : Find element in the array indexed at ‘i’.Initially all the elements in the array are 0. Queries can be in any order, i.e., there can be many updates before point query.Example:Input : arr = {0, 0, 0, 0, 0}\nQueries: update : l = 0, r = 4, val = 2\n getElement : i = 3\n update : l = 3, r = 4, val = 3 \n getElement : i = 3\n\nOutput: Element at 3 is 2\n Element at 3 is 5\n \nExplanation : Array after first update becomes\n {2, 2, 2, 2, 2}\n Array after second update becomes\n {2, 2, 2, 5, 5}\n Method 1 [update : O(n), getElement() : O(1)]update(l, r, val) : Iterate over the subarray from l to r and increase all the elements by val.getElement(i) : To get the element at i’th index, simply return arr[i].The time complexity in worst case is O(q*n) where q is number of queries and n is number of elements. Method 2 [update : O(1), getElement() : O(n)]We can avoid updating all elements and can update only 2 indexes of the array!update(l, r, val) : Add ‘val’ to the lth element and subtract ‘val’ from the (r+1)th element, do this for all the update queries. arr[l] = arr[l] + val\n arr[r+1] = arr[r+1] - val \ngetElement(i) : To get ith element in the array find the sum of all integers in the array from 0 to i.(Prefix Sum). \n\nLet’s analyze the update query.\n\nWhy to add val to lth index?\nAdding val to lth index means that all the elements after l are increased by val, since we will be computing the prefix sum for every element.\n\nWhy to subtract val from (r+1)th index?\nA range update was required from [l,r] but what we have updated is [l, n-1] so we need to remove val from all the elements after r i.e., subtract val from (r+1)th index.\nThus the val is added to range [l,r].\n\nBelow is implementation of above approach.\nC++JavaPython3C#PHP\nC++\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n// C++ program to demonstrate Range Update // and Point Queries Without using BIT #include <bits/stdc++.h> using namespace std; // Updates such that getElement() gets an increased // value when queried from l to r. void update(int arr[], int l, int r, int val) { arr[l] += val; arr[r+1] -= val; } // Get the element indexed at i int getElement(int arr[], int i) { // To get ith element sum of all the elements // from 0 to i need to be computed int res = 0; for (int j = 0 ; j <= i; j++) res += arr[j]; return res; } // Driver program to test above function int main() { int arr[] = {0, 0, 0, 0, 0}; int n = sizeof(arr) / sizeof(arr[0]); int l = 2, r = 4, val = 2; update(arr, l, r, val); //Find the element at Index 4 int index = 4; cout << \"Element at index \" << index << \" is \" << getElement(arr, index) << endl; l = 0, r = 3, val = 4; update(arr,l,r,val); //Find the element at Index 3 index = 3; cout << \"Element at index \" << index << \" is \" << getElement(arr, index) << endl; return 0; } \n\n\n\n\n\n\nJava// Java program to demonstrate Range Update // and Point Queries Without using BIT class GfG { // Updates such that getElement() gets an increased // value when queried from l to r. static void update(int arr[], int l, int r, int val) { arr[l] += val; if(r + 1 < arr.length) arr[r+1] -= val; } // Get the element indexed at i static int getElement(int arr[], int i) { // To get ith element sum of all the elements // from 0 to i need to be computed int res = 0; for (int j = 0 ; j <= i; j++) res += arr[j]; return res; } // Driver program to test above function public static void main(String[] args) { int arr[] = {0, 0, 0, 0, 0}; int n = arr.length; int l = 2, r = 4, val = 2; update(arr, l, r, val); //Find the element at Index 4 int index = 4; System.out.println(\"Element at index \" + index + \" is \" +getElement(arr, index)); l = 0; r = 3; val = 4; update(arr,l,r,val); //Find the element at Index 3 index = 3; System.out.println(\"Element at index \" + index + \" is \" +getElement(arr, index)); }} Python3# Python3 program to demonstrate Range # Update and PoQueries Without using BIT # Updates such that getElement() gets an # increased value when queried from l to r. def update(arr, l, r, val): arr[l] += val if r + 1 < len(arr): arr[r + 1] -= val # Get the element indexed at i def getElement(arr, i): # To get ith element sum of all the elements # from 0 to i need to be computed res = 0 for j in range(i + 1): res += arr[j] return res # Driver Codeif __name__ == '__main__': arr = [0, 0, 0, 0, 0] n = len(arr) l = 2 r = 4 val = 2 update(arr, l, r, val) # Find the element at Index 4 index = 4 print(\"Element at index\", index, \"is\", getElement(arr, index)) l = 0 r = 3 val = 4 update(arr, l, r, val) # Find the element at Index 3 index = 3 print(\"Element at index\", index, \"is\", getElement(arr, index)) # This code is contributed by PranchalKC#// C# program to demonstrate Range Update // and Point Queries Without using BIT using System; class GfG { // Updates such that getElement() // gets an increased value when// queried from l to r. static void update(int []arr, int l, int r, int val) { arr[l] += val; if(r + 1 < arr.Length) arr[r + 1] -= val; } // Get the element indexed at i static int getElement(int []arr, int i) { // To get ith element sum of all the elements // from 0 to i need to be computed int res = 0; for (int j = 0 ; j <= i; j++) res += arr[j]; return res; } // Driver code public static void Main(String[] args) { int []arr = {0, 0, 0, 0, 0}; int n = arr.Length; int l = 2, r = 4, val = 2; update(arr, l, r, val); //Find the element at Index 4 int index = 4; Console.WriteLine(\"Element at index \" + index + \" is \" + getElement(arr, index)); l = 0; r = 3; val = 4; update(arr,l,r,val); //Find the element at Index 3 index = 3; Console.WriteLine(\"Element at index \" + index + \" is \" + getElement(arr, index)); } } // This code is contributed by PrinciRaj1992PHP<?php// PHP program to demonstrate Range Update // and Point Queries Without using BIT // Updates such that getElement() gets an // increased value when queried from l to r. function update(&$arr, $l, $r, $val) { $arr[$l] += $val; if($r + 1 < sizeof($arr)) $arr[$r + 1] -= $val; } // Get the element indexed at i function getElement(&$arr, $i) { // To get ith element sum of all the elements // from 0 to i need to be computed $res = 0; for ($j = 0 ; $j <= $i; $j++) $res += $arr[$j]; return $res; } // Driver Code$arr = array(0, 0, 0, 0, 0); $n = sizeof($arr); $l = 2; $r = 4; $val = 2; update($arr, $l, $r, $val); // Find the element at Index 4 $index = 4; echo(\"Element at index \" . $index . \" is \" . getElement($arr, $index) . \"\\n\"); $l = 0;$r = 3;$val = 4; update($arr, $l, $r, $val); // Find the element at Index 3 $index = 3; echo(\"Element at index \" . $index . \" is \" . getElement($arr, $index)); // This code is contributed by Code_Mech?>Output:Element at index 4 is 2\nElement at index 3 is 6\nTime complexity : O(q*n) where q is number of queries. Method 3 (Using Binary Indexed Tree)In method 2, we have seen that the problem can reduced to update and prefix sum queries. We have seen that BIT can be used to do update and prefix sum queries in O(Logn) time.Below is the implementation.C++JavaPython3C#C++// C++ code to demonstrate Range Update and// Point Queries on a Binary Index Tree#include <bits/stdc++.h>using namespace std; // Updates a node in Binary Index Tree (BITree) at given index// in BITree. The given value 'val' is added to BITree[i] and// all of its ancestors in tree.void updateBIT(int BITree[], int n, int index, int val){ // index in BITree[] is 1 more than the index in arr[] index = index + 1; // Traverse all ancestors and add 'val' while (index <= n) { // Add 'val' to current node of BI Tree BITree[index] += val; // Update index to that of parent in update View index += index & (-index); }} // Constructs and returns a Binary Indexed Tree for given// array of size n.int *constructBITree(int arr[], int n){ // Create and initialize BITree[] as 0 int *BITree = new int[n+1]; for (int i=1; i<=n; i++) BITree[i] = 0; // Store the actual values in BITree[] using update() for (int i=0; i<n; i++) updateBIT(BITree, n, i, arr[i]); // Uncomment below lines to see contents of BITree[] //for (int i=1; i<=n; i++) // cout << BITree[i] << \" \"; return BITree;} // SERVES THE PURPOSE OF getElement()// Returns sum of arr[0..index]. This function assumes// that the array is preprocessed and partial sums of// array elements are stored in BITree[]int getSum(int BITree[], int index){ int sum = 0; // Iniialize result // index in BITree[] is 1 more than the index in arr[] index = index + 1; // Traverse ancestors of BITree[index] while (index>0) { // Add current element of BITree to sum sum += BITree[index]; // Move index to parent node in getSum View index -= index & (-index); } return sum;} // Updates such that getElement() gets an increased// value when queried from l to r.void update(int BITree[], int l, int r, int n, int val){ // Increase value at 'l' by 'val' updateBIT(BITree, n, l, val); // Decrease value at 'r+1' by 'val' updateBIT(BITree, n, r+1, -val);} // Driver program to test above functionint main(){ int arr[] = {0, 0, 0, 0, 0}; int n = sizeof(arr)/sizeof(arr[0]); int *BITree = constructBITree(arr, n); // Add 2 to all the element from [2,4] int l = 2, r = 4, val = 2; update(BITree, l, r, n, val); // Find the element at Index 4 int index = 4; cout << \"Element at index \" << index << \" is \" << getSum(BITree,index) << \"\\n\"; // Add 2 to all the element from [0,3] l = 0, r = 3, val = 4; update(BITree, l, r, n, val); // Find the element at Index 3 index = 3; cout << \"Element at index \" << index << \" is \" << getSum(BITree,index) << \"\\n\" ; return 0;}Java/* Java code to demonstrate Range Update and* Point Queries on a Binary Index Tree.* This method only works when all array* values are initially 0.*/class GFG{ // Max tree size final static int MAX = 1000; static int BITree[] = new int[MAX]; // Updates a node in Binary Index // Tree (BITree) at given index // in BITree. The given value 'val' // is added to BITree[i] and // all of its ancestors in tree. public static void updateBIT(int n, int index, int val) { // index in BITree[] is 1 // more than the index in arr[] index = index + 1; // Traverse all ancestors // and add 'val' while (index <= n) { // Add 'val' to current // node of BITree BITree[index] += val; // Update index to that // of parent in update View index += index & (-index); } } // Constructs Binary Indexed Tree // for given array of size n. public static void constructBITree(int arr[], int n) { // Initialize BITree[] as 0 for(int i = 1; i <= n; i++) BITree[i] = 0; // Store the actual values // in BITree[] using update() for(int i = 0; i < n; i++) updateBIT(n, i, arr[i]); // Uncomment below lines to // see contents of BITree[] // for (int i=1; i<=n; i++) // cout << BITree[i] << \" \"; } // SERVES THE PURPOSE OF getElement() // Returns sum of arr[0..index]. This // function assumes that the array is // preprocessed and partial sums of // array elements are stored in BITree[] public static int getSum(int index) { int sum = 0; //Initialize result // index in BITree[] is 1 more // than the index in arr[] index = index + 1; // Traverse ancestors // of BITree[index] while (index > 0) { // Add current element // of BITree to sum sum += BITree[index]; // Move index to parent // node in getSum View index -= index & (-index); } // Return the sum return sum; } // Updates such that getElement() // gets an increased value when // queried from l to r. public static void update(int l, int r, int n, int val) { // Increase value at // 'l' by 'val' updateBIT(n, l, val); // Decrease value at // 'r+1' by 'val' updateBIT(n, r + 1, -val); } // Driver Code public static void main(String args[]) { int arr[] = {0, 0, 0, 0, 0}; int n = arr.length; constructBITree(arr,n); // Add 2 to all the // element from [2,4] int l = 2, r = 4, val = 2; update(l, r, n, val); int index = 4; System.out.println(\"Element at index \"+ index + \" is \"+ getSum(index)); // Add 2 to all the // element from [0,3] l = 0; r = 3; val = 4; update(l, r, n, val); // Find the element // at Index 3 index = 3; System.out.println(\"Element at index \"+ index + \" is \"+ getSum(index)); }}// This code is contributed// by Puneet Kumar.Python3# Python3 code to demonstrate Range Update and# PoQueries on a Binary Index Tree # Updates a node in Binary Index Tree (BITree) at given index# in BITree. The given value 'val' is added to BITree[i] and# all of its ancestors in tree.def updateBIT(BITree, n, index, val): # index in BITree[] is 1 more than the index in arr[] index = index + 1 # Traverse all ancestors and add 'val' while (index <= n): # Add 'val' to current node of BI Tree BITree[index] += val # Update index to that of parent in update View index += index & (-index) # Constructs and returns a Binary Indexed Tree for given# array of size n.def constructBITree(arr, n): # Create and initialize BITree[] as 0 BITree = [0]*(n+1) # Store the actual values in BITree[] using update() for i in range(n): updateBIT(BITree, n, i, arr[i]) return BITree # SERVES THE PURPOSE OF getElement()# Returns sum of arr[0..index]. This function assumes# that the array is preprocessed and partial sums of# array elements are stored in BITree[]def getSum(BITree, index): sum = 0 # Iniialize result # index in BITree[] is 1 more than the index in arr[] index = index + 1 # Traverse ancestors of BITree[index] while (index > 0): # Add current element of BITree to sum sum += BITree[index] # Move index to parent node in getSum View index -= index & (-index) return sum # Updates such that getElement() gets an increased# value when queried from l to r.def update(BITree, l, r, n, val): # Increase value at 'l' by 'val' updateBIT(BITree, n, l, val) # Decrease value at 'r+1' by 'val' updateBIT(BITree, n, r+1, -val) # Driver codearr = [0, 0, 0, 0, 0]n = len(arr)BITree = constructBITree(arr, n) # Add 2 to all the element from [2,4]l = 2r = 4val = 2update(BITree, l, r, n, val) # Find the element at Index 4index = 4print(\"Element at index\", index, \"is\", getSum(BITree, index)) # Add 2 to all the element from [0,3]l = 0r = 3val = 4update(BITree, l, r, n, val) # Find the element at Index 3index = 3print(\"Element at index\", index, \"is\", getSum(BITree,index)) # This code is contributed by mohit kumar 29C#using System; /* C# code to demonstrate Range Update and * Point Queries on a Binary Index Tree. * This method only works when all array * values are initially 0.*/public class GFG{ // Max tree size public const int MAX = 1000; public static int[] BITree = new int[MAX]; // Updates a node in Binary Index // Tree (BITree) at given index // in BITree. The given value 'val' // is added to BITree[i] and // all of its ancestors in tree. public static void updateBIT(int n, int index, int val) { // index in BITree[] is 1 // more than the index in arr[] index = index + 1; // Traverse all ancestors // and add 'val' while (index <= n) { // Add 'val' to current // node of BITree BITree[index] += val; // Update index to that // of parent in update View index += index & (-index); } } // Constructs Binary Indexed Tree // for given array of size n. public static void constructBITree(int[] arr, int n) { // Initialize BITree[] as 0 for (int i = 1; i <= n; i++) { BITree[i] = 0; } // Store the actual values // in BITree[] using update() for (int i = 0; i < n; i++) { updateBIT(n, i, arr[i]); } // Uncomment below lines to // see contents of BITree[] // for (int i=1; i<=n; i++) // cout << BITree[i] << \" \"; } // SERVES THE PURPOSE OF getElement() // Returns sum of arr[0..index]. This // function assumes that the array is // preprocessed and partial sums of // array elements are stored in BITree[] public static int getSum(int index) { int sum = 0; //Initialize result // index in BITree[] is 1 more // than the index in arr[] index = index + 1; // Traverse ancestors // of BITree[index] while (index > 0) { // Add current element // of BITree to sum sum += BITree[index]; // Move index to parent // node in getSum View index -= index & (-index); } // Return the sum return sum; } // Updates such that getElement() // gets an increased value when // queried from l to r. public static void update(int l, int r, int n, int val) { // Increase value at // 'l' by 'val' updateBIT(n, l, val); // Decrease value at // 'r+1' by 'val' updateBIT(n, r + 1, -val); } // Driver Code public static void Main(string[] args) { int[] arr = new int[] {0, 0, 0, 0, 0}; int n = arr.Length; constructBITree(arr,n); // Add 2 to all the // element from [2,4] int l = 2, r = 4, val = 2; update(l, r, n, val); int index = 4; Console.WriteLine(\"Element at index \" + index + \" is \" + getSum(index)); // Add 2 to all the // element from [0,3] l = 0; r = 3; val = 4; update(l, r, n, val); // Find the element // at Index 3 index = 3; Console.WriteLine(\"Element at index \" + index + \" is \" + getSum(index)); }} // This code is contributed by Shrikant13Output:Element at index 4 is 2\nElement at index 3 is 6\nTime Complexity : O(q * log n) + O(n * log n) where q is number of queries.Method 1 is efficient when most of the queries are getElement(), method 2 is efficient when most of the queries are updates() and method 3 is preferred when there is mix of both queries.This article is contributed by Chirag Agarwal. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.My Personal Notes\narrow_drop_upSave"
},
{
"code": null,
"e": 46552,
"s": 46476,
"text": "update(l, r, val) : Add ‘val’ to all the elements in the array from [l, r]."
},
{
"code": null,
"e": 66967,
"s": 46552,
"text": "getElement(i) : Find element in the array indexed at ‘i’.Initially all the elements in the array are 0. Queries can be in any order, i.e., there can be many updates before point query.Example:Input : arr = {0, 0, 0, 0, 0}\nQueries: update : l = 0, r = 4, val = 2\n getElement : i = 3\n update : l = 3, r = 4, val = 3 \n getElement : i = 3\n\nOutput: Element at 3 is 2\n Element at 3 is 5\n \nExplanation : Array after first update becomes\n {2, 2, 2, 2, 2}\n Array after second update becomes\n {2, 2, 2, 5, 5}\n Method 1 [update : O(n), getElement() : O(1)]update(l, r, val) : Iterate over the subarray from l to r and increase all the elements by val.getElement(i) : To get the element at i’th index, simply return arr[i].The time complexity in worst case is O(q*n) where q is number of queries and n is number of elements. Method 2 [update : O(1), getElement() : O(n)]We can avoid updating all elements and can update only 2 indexes of the array!update(l, r, val) : Add ‘val’ to the lth element and subtract ‘val’ from the (r+1)th element, do this for all the update queries. arr[l] = arr[l] + val\n arr[r+1] = arr[r+1] - val \ngetElement(i) : To get ith element in the array find the sum of all integers in the array from 0 to i.(Prefix Sum). \n\nLet’s analyze the update query.\n\nWhy to add val to lth index?\nAdding val to lth index means that all the elements after l are increased by val, since we will be computing the prefix sum for every element.\n\nWhy to subtract val from (r+1)th index?\nA range update was required from [l,r] but what we have updated is [l, n-1] so we need to remove val from all the elements after r i.e., subtract val from (r+1)th index.\nThus the val is added to range [l,r].\n\nBelow is implementation of above approach.\nC++JavaPython3C#PHP\nC++\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n// C++ program to demonstrate Range Update // and Point Queries Without using BIT #include <bits/stdc++.h> using namespace std; // Updates such that getElement() gets an increased // value when queried from l to r. void update(int arr[], int l, int r, int val) { arr[l] += val; arr[r+1] -= val; } // Get the element indexed at i int getElement(int arr[], int i) { // To get ith element sum of all the elements // from 0 to i need to be computed int res = 0; for (int j = 0 ; j <= i; j++) res += arr[j]; return res; } // Driver program to test above function int main() { int arr[] = {0, 0, 0, 0, 0}; int n = sizeof(arr) / sizeof(arr[0]); int l = 2, r = 4, val = 2; update(arr, l, r, val); //Find the element at Index 4 int index = 4; cout << \"Element at index \" << index << \" is \" << getElement(arr, index) << endl; l = 0, r = 3, val = 4; update(arr,l,r,val); //Find the element at Index 3 index = 3; cout << \"Element at index \" << index << \" is \" << getElement(arr, index) << endl; return 0; } \n\n\n\n\n\n\nJava// Java program to demonstrate Range Update // and Point Queries Without using BIT class GfG { // Updates such that getElement() gets an increased // value when queried from l to r. static void update(int arr[], int l, int r, int val) { arr[l] += val; if(r + 1 < arr.length) arr[r+1] -= val; } // Get the element indexed at i static int getElement(int arr[], int i) { // To get ith element sum of all the elements // from 0 to i need to be computed int res = 0; for (int j = 0 ; j <= i; j++) res += arr[j]; return res; } // Driver program to test above function public static void main(String[] args) { int arr[] = {0, 0, 0, 0, 0}; int n = arr.length; int l = 2, r = 4, val = 2; update(arr, l, r, val); //Find the element at Index 4 int index = 4; System.out.println(\"Element at index \" + index + \" is \" +getElement(arr, index)); l = 0; r = 3; val = 4; update(arr,l,r,val); //Find the element at Index 3 index = 3; System.out.println(\"Element at index \" + index + \" is \" +getElement(arr, index)); }} Python3# Python3 program to demonstrate Range # Update and PoQueries Without using BIT # Updates such that getElement() gets an # increased value when queried from l to r. def update(arr, l, r, val): arr[l] += val if r + 1 < len(arr): arr[r + 1] -= val # Get the element indexed at i def getElement(arr, i): # To get ith element sum of all the elements # from 0 to i need to be computed res = 0 for j in range(i + 1): res += arr[j] return res # Driver Codeif __name__ == '__main__': arr = [0, 0, 0, 0, 0] n = len(arr) l = 2 r = 4 val = 2 update(arr, l, r, val) # Find the element at Index 4 index = 4 print(\"Element at index\", index, \"is\", getElement(arr, index)) l = 0 r = 3 val = 4 update(arr, l, r, val) # Find the element at Index 3 index = 3 print(\"Element at index\", index, \"is\", getElement(arr, index)) # This code is contributed by PranchalKC#// C# program to demonstrate Range Update // and Point Queries Without using BIT using System; class GfG { // Updates such that getElement() // gets an increased value when// queried from l to r. static void update(int []arr, int l, int r, int val) { arr[l] += val; if(r + 1 < arr.Length) arr[r + 1] -= val; } // Get the element indexed at i static int getElement(int []arr, int i) { // To get ith element sum of all the elements // from 0 to i need to be computed int res = 0; for (int j = 0 ; j <= i; j++) res += arr[j]; return res; } // Driver code public static void Main(String[] args) { int []arr = {0, 0, 0, 0, 0}; int n = arr.Length; int l = 2, r = 4, val = 2; update(arr, l, r, val); //Find the element at Index 4 int index = 4; Console.WriteLine(\"Element at index \" + index + \" is \" + getElement(arr, index)); l = 0; r = 3; val = 4; update(arr,l,r,val); //Find the element at Index 3 index = 3; Console.WriteLine(\"Element at index \" + index + \" is \" + getElement(arr, index)); } } // This code is contributed by PrinciRaj1992PHP<?php// PHP program to demonstrate Range Update // and Point Queries Without using BIT // Updates such that getElement() gets an // increased value when queried from l to r. function update(&$arr, $l, $r, $val) { $arr[$l] += $val; if($r + 1 < sizeof($arr)) $arr[$r + 1] -= $val; } // Get the element indexed at i function getElement(&$arr, $i) { // To get ith element sum of all the elements // from 0 to i need to be computed $res = 0; for ($j = 0 ; $j <= $i; $j++) $res += $arr[$j]; return $res; } // Driver Code$arr = array(0, 0, 0, 0, 0); $n = sizeof($arr); $l = 2; $r = 4; $val = 2; update($arr, $l, $r, $val); // Find the element at Index 4 $index = 4; echo(\"Element at index \" . $index . \" is \" . getElement($arr, $index) . \"\\n\"); $l = 0;$r = 3;$val = 4; update($arr, $l, $r, $val); // Find the element at Index 3 $index = 3; echo(\"Element at index \" . $index . \" is \" . getElement($arr, $index)); // This code is contributed by Code_Mech?>Output:Element at index 4 is 2\nElement at index 3 is 6\nTime complexity : O(q*n) where q is number of queries. Method 3 (Using Binary Indexed Tree)In method 2, we have seen that the problem can reduced to update and prefix sum queries. We have seen that BIT can be used to do update and prefix sum queries in O(Logn) time.Below is the implementation.C++JavaPython3C#C++// C++ code to demonstrate Range Update and// Point Queries on a Binary Index Tree#include <bits/stdc++.h>using namespace std; // Updates a node in Binary Index Tree (BITree) at given index// in BITree. The given value 'val' is added to BITree[i] and// all of its ancestors in tree.void updateBIT(int BITree[], int n, int index, int val){ // index in BITree[] is 1 more than the index in arr[] index = index + 1; // Traverse all ancestors and add 'val' while (index <= n) { // Add 'val' to current node of BI Tree BITree[index] += val; // Update index to that of parent in update View index += index & (-index); }} // Constructs and returns a Binary Indexed Tree for given// array of size n.int *constructBITree(int arr[], int n){ // Create and initialize BITree[] as 0 int *BITree = new int[n+1]; for (int i=1; i<=n; i++) BITree[i] = 0; // Store the actual values in BITree[] using update() for (int i=0; i<n; i++) updateBIT(BITree, n, i, arr[i]); // Uncomment below lines to see contents of BITree[] //for (int i=1; i<=n; i++) // cout << BITree[i] << \" \"; return BITree;} // SERVES THE PURPOSE OF getElement()// Returns sum of arr[0..index]. This function assumes// that the array is preprocessed and partial sums of// array elements are stored in BITree[]int getSum(int BITree[], int index){ int sum = 0; // Iniialize result // index in BITree[] is 1 more than the index in arr[] index = index + 1; // Traverse ancestors of BITree[index] while (index>0) { // Add current element of BITree to sum sum += BITree[index]; // Move index to parent node in getSum View index -= index & (-index); } return sum;} // Updates such that getElement() gets an increased// value when queried from l to r.void update(int BITree[], int l, int r, int n, int val){ // Increase value at 'l' by 'val' updateBIT(BITree, n, l, val); // Decrease value at 'r+1' by 'val' updateBIT(BITree, n, r+1, -val);} // Driver program to test above functionint main(){ int arr[] = {0, 0, 0, 0, 0}; int n = sizeof(arr)/sizeof(arr[0]); int *BITree = constructBITree(arr, n); // Add 2 to all the element from [2,4] int l = 2, r = 4, val = 2; update(BITree, l, r, n, val); // Find the element at Index 4 int index = 4; cout << \"Element at index \" << index << \" is \" << getSum(BITree,index) << \"\\n\"; // Add 2 to all the element from [0,3] l = 0, r = 3, val = 4; update(BITree, l, r, n, val); // Find the element at Index 3 index = 3; cout << \"Element at index \" << index << \" is \" << getSum(BITree,index) << \"\\n\" ; return 0;}Java/* Java code to demonstrate Range Update and* Point Queries on a Binary Index Tree.* This method only works when all array* values are initially 0.*/class GFG{ // Max tree size final static int MAX = 1000; static int BITree[] = new int[MAX]; // Updates a node in Binary Index // Tree (BITree) at given index // in BITree. The given value 'val' // is added to BITree[i] and // all of its ancestors in tree. public static void updateBIT(int n, int index, int val) { // index in BITree[] is 1 // more than the index in arr[] index = index + 1; // Traverse all ancestors // and add 'val' while (index <= n) { // Add 'val' to current // node of BITree BITree[index] += val; // Update index to that // of parent in update View index += index & (-index); } } // Constructs Binary Indexed Tree // for given array of size n. public static void constructBITree(int arr[], int n) { // Initialize BITree[] as 0 for(int i = 1; i <= n; i++) BITree[i] = 0; // Store the actual values // in BITree[] using update() for(int i = 0; i < n; i++) updateBIT(n, i, arr[i]); // Uncomment below lines to // see contents of BITree[] // for (int i=1; i<=n; i++) // cout << BITree[i] << \" \"; } // SERVES THE PURPOSE OF getElement() // Returns sum of arr[0..index]. This // function assumes that the array is // preprocessed and partial sums of // array elements are stored in BITree[] public static int getSum(int index) { int sum = 0; //Initialize result // index in BITree[] is 1 more // than the index in arr[] index = index + 1; // Traverse ancestors // of BITree[index] while (index > 0) { // Add current element // of BITree to sum sum += BITree[index]; // Move index to parent // node in getSum View index -= index & (-index); } // Return the sum return sum; } // Updates such that getElement() // gets an increased value when // queried from l to r. public static void update(int l, int r, int n, int val) { // Increase value at // 'l' by 'val' updateBIT(n, l, val); // Decrease value at // 'r+1' by 'val' updateBIT(n, r + 1, -val); } // Driver Code public static void main(String args[]) { int arr[] = {0, 0, 0, 0, 0}; int n = arr.length; constructBITree(arr,n); // Add 2 to all the // element from [2,4] int l = 2, r = 4, val = 2; update(l, r, n, val); int index = 4; System.out.println(\"Element at index \"+ index + \" is \"+ getSum(index)); // Add 2 to all the // element from [0,3] l = 0; r = 3; val = 4; update(l, r, n, val); // Find the element // at Index 3 index = 3; System.out.println(\"Element at index \"+ index + \" is \"+ getSum(index)); }}// This code is contributed// by Puneet Kumar.Python3# Python3 code to demonstrate Range Update and# PoQueries on a Binary Index Tree # Updates a node in Binary Index Tree (BITree) at given index# in BITree. The given value 'val' is added to BITree[i] and# all of its ancestors in tree.def updateBIT(BITree, n, index, val): # index in BITree[] is 1 more than the index in arr[] index = index + 1 # Traverse all ancestors and add 'val' while (index <= n): # Add 'val' to current node of BI Tree BITree[index] += val # Update index to that of parent in update View index += index & (-index) # Constructs and returns a Binary Indexed Tree for given# array of size n.def constructBITree(arr, n): # Create and initialize BITree[] as 0 BITree = [0]*(n+1) # Store the actual values in BITree[] using update() for i in range(n): updateBIT(BITree, n, i, arr[i]) return BITree # SERVES THE PURPOSE OF getElement()# Returns sum of arr[0..index]. This function assumes# that the array is preprocessed and partial sums of# array elements are stored in BITree[]def getSum(BITree, index): sum = 0 # Iniialize result # index in BITree[] is 1 more than the index in arr[] index = index + 1 # Traverse ancestors of BITree[index] while (index > 0): # Add current element of BITree to sum sum += BITree[index] # Move index to parent node in getSum View index -= index & (-index) return sum # Updates such that getElement() gets an increased# value when queried from l to r.def update(BITree, l, r, n, val): # Increase value at 'l' by 'val' updateBIT(BITree, n, l, val) # Decrease value at 'r+1' by 'val' updateBIT(BITree, n, r+1, -val) # Driver codearr = [0, 0, 0, 0, 0]n = len(arr)BITree = constructBITree(arr, n) # Add 2 to all the element from [2,4]l = 2r = 4val = 2update(BITree, l, r, n, val) # Find the element at Index 4index = 4print(\"Element at index\", index, \"is\", getSum(BITree, index)) # Add 2 to all the element from [0,3]l = 0r = 3val = 4update(BITree, l, r, n, val) # Find the element at Index 3index = 3print(\"Element at index\", index, \"is\", getSum(BITree,index)) # This code is contributed by mohit kumar 29C#using System; /* C# code to demonstrate Range Update and * Point Queries on a Binary Index Tree. * This method only works when all array * values are initially 0.*/public class GFG{ // Max tree size public const int MAX = 1000; public static int[] BITree = new int[MAX]; // Updates a node in Binary Index // Tree (BITree) at given index // in BITree. The given value 'val' // is added to BITree[i] and // all of its ancestors in tree. public static void updateBIT(int n, int index, int val) { // index in BITree[] is 1 // more than the index in arr[] index = index + 1; // Traverse all ancestors // and add 'val' while (index <= n) { // Add 'val' to current // node of BITree BITree[index] += val; // Update index to that // of parent in update View index += index & (-index); } } // Constructs Binary Indexed Tree // for given array of size n. public static void constructBITree(int[] arr, int n) { // Initialize BITree[] as 0 for (int i = 1; i <= n; i++) { BITree[i] = 0; } // Store the actual values // in BITree[] using update() for (int i = 0; i < n; i++) { updateBIT(n, i, arr[i]); } // Uncomment below lines to // see contents of BITree[] // for (int i=1; i<=n; i++) // cout << BITree[i] << \" \"; } // SERVES THE PURPOSE OF getElement() // Returns sum of arr[0..index]. This // function assumes that the array is // preprocessed and partial sums of // array elements are stored in BITree[] public static int getSum(int index) { int sum = 0; //Initialize result // index in BITree[] is 1 more // than the index in arr[] index = index + 1; // Traverse ancestors // of BITree[index] while (index > 0) { // Add current element // of BITree to sum sum += BITree[index]; // Move index to parent // node in getSum View index -= index & (-index); } // Return the sum return sum; } // Updates such that getElement() // gets an increased value when // queried from l to r. public static void update(int l, int r, int n, int val) { // Increase value at // 'l' by 'val' updateBIT(n, l, val); // Decrease value at // 'r+1' by 'val' updateBIT(n, r + 1, -val); } // Driver Code public static void Main(string[] args) { int[] arr = new int[] {0, 0, 0, 0, 0}; int n = arr.Length; constructBITree(arr,n); // Add 2 to all the // element from [2,4] int l = 2, r = 4, val = 2; update(l, r, n, val); int index = 4; Console.WriteLine(\"Element at index \" + index + \" is \" + getSum(index)); // Add 2 to all the // element from [0,3] l = 0; r = 3; val = 4; update(l, r, n, val); // Find the element // at Index 3 index = 3; Console.WriteLine(\"Element at index \" + index + \" is \" + getSum(index)); }} // This code is contributed by Shrikant13Output:Element at index 4 is 2\nElement at index 3 is 6\nTime Complexity : O(q * log n) + O(n * log n) where q is number of queries.Method 1 is efficient when most of the queries are getElement(), method 2 is efficient when most of the queries are updates() and method 3 is preferred when there is mix of both queries.This article is contributed by Chirag Agarwal. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.My Personal Notes\narrow_drop_upSave"
},
{
"code": null,
"e": 67095,
"s": 66967,
"text": "Initially all the elements in the array are 0. Queries can be in any order, i.e., there can be many updates before point query."
},
{
"code": null,
"e": 67104,
"s": 67095,
"text": "Example:"
},
{
"code": null,
"e": 67482,
"s": 67104,
"text": "Input : arr = {0, 0, 0, 0, 0}\nQueries: update : l = 0, r = 4, val = 2\n getElement : i = 3\n update : l = 3, r = 4, val = 3 \n getElement : i = 3\n\nOutput: Element at 3 is 2\n Element at 3 is 5\n \nExplanation : Array after first update becomes\n {2, 2, 2, 2, 2}\n Array after second update becomes\n {2, 2, 2, 5, 5}\n"
},
{
"code": null,
"e": 67530,
"s": 67484,
"text": "Method 1 [update : O(n), getElement() : O(1)]"
},
{
"code": null,
"e": 67697,
"s": 67530,
"text": "update(l, r, val) : Iterate over the subarray from l to r and increase all the elements by val.getElement(i) : To get the element at i’th index, simply return arr[i]."
},
{
"code": null,
"e": 67793,
"s": 67697,
"text": "update(l, r, val) : Iterate over the subarray from l to r and increase all the elements by val."
},
{
"code": null,
"e": 67865,
"s": 67793,
"text": "getElement(i) : To get the element at i’th index, simply return arr[i]."
},
{
"code": null,
"e": 67967,
"s": 67865,
"text": "The time complexity in worst case is O(q*n) where q is number of queries and n is number of elements."
},
{
"code": null,
"e": 68015,
"s": 67969,
"text": "Method 2 [update : O(1), getElement() : O(n)]"
},
{
"code": null,
"e": 68094,
"s": 68015,
"text": "We can avoid updating all elements and can update only 2 indexes of the array!"
},
{
"code": null,
"e": 68395,
"s": 68094,
"text": "update(l, r, val) : Add ‘val’ to the lth element and subtract ‘val’ from the (r+1)th element, do this for all the update queries. arr[l] = arr[l] + val\n arr[r+1] = arr[r+1] - val \ngetElement(i) : To get ith element in the array find the sum of all integers in the array from 0 to i.(Prefix Sum). "
},
{
"code": null,
"e": 68696,
"s": 68395,
"text": "update(l, r, val) : Add ‘val’ to the lth element and subtract ‘val’ from the (r+1)th element, do this for all the update queries. arr[l] = arr[l] + val\n arr[r+1] = arr[r+1] - val \ngetElement(i) : To get ith element in the array find the sum of all integers in the array from 0 to i.(Prefix Sum). "
},
{
"code": null,
"e": 68868,
"s": 68696,
"text": " arr[l] = arr[l] + val\n arr[r+1] = arr[r+1] - val \ngetElement(i) : To get ith element in the array find the sum of all integers in the array from 0 to i.(Prefix Sum). "
},
{
"code": null,
"e": 68985,
"s": 68868,
"text": "getElement(i) : To get ith element in the array find the sum of all integers in the array from 0 to i.(Prefix Sum). "
},
{
"code": null,
"e": 68989,
"s": 68985,
"text": "C++"
},
{
"code": null,
"e": 68994,
"s": 68989,
"text": "Java"
},
{
"code": null,
"e": 69002,
"s": 68994,
"text": "Python3"
},
{
"code": null,
"e": 69005,
"s": 69002,
"text": "C#"
},
{
"code": null,
"e": 69009,
"s": 69005,
"text": "PHP"
},
{
"code": "// C++ program to demonstrate Range Update // and Point Queries Without using BIT #include <bits/stdc++.h> using namespace std; // Updates such that getElement() gets an increased // value when queried from l to r. void update(int arr[], int l, int r, int val) { arr[l] += val; arr[r+1] -= val; } // Get the element indexed at i int getElement(int arr[], int i) { // To get ith element sum of all the elements // from 0 to i need to be computed int res = 0; for (int j = 0 ; j <= i; j++) res += arr[j]; return res; } // Driver program to test above function int main() { int arr[] = {0, 0, 0, 0, 0}; int n = sizeof(arr) / sizeof(arr[0]); int l = 2, r = 4, val = 2; update(arr, l, r, val); //Find the element at Index 4 int index = 4; cout << \"Element at index \" << index << \" is \" << getElement(arr, index) << endl; l = 0, r = 3, val = 4; update(arr,l,r,val); //Find the element at Index 3 index = 3; cout << \"Element at index \" << index << \" is \" << getElement(arr, index) << endl; return 0; } \n",
"e": 70130,
"s": 69009,
"text": null
},
{
"code": "// Java program to demonstrate Range Update // and Point Queries Without using BIT class GfG { // Updates such that getElement() gets an increased // value when queried from l to r. static void update(int arr[], int l, int r, int val) { arr[l] += val; if(r + 1 < arr.length) arr[r+1] -= val; } // Get the element indexed at i static int getElement(int arr[], int i) { // To get ith element sum of all the elements // from 0 to i need to be computed int res = 0; for (int j = 0 ; j <= i; j++) res += arr[j]; return res; } // Driver program to test above function public static void main(String[] args) { int arr[] = {0, 0, 0, 0, 0}; int n = arr.length; int l = 2, r = 4, val = 2; update(arr, l, r, val); //Find the element at Index 4 int index = 4; System.out.println(\"Element at index \" + index + \" is \" +getElement(arr, index)); l = 0; r = 3; val = 4; update(arr,l,r,val); //Find the element at Index 3 index = 3; System.out.println(\"Element at index \" + index + \" is \" +getElement(arr, index)); }} ",
"e": 71241,
"s": 70130,
"text": null
},
{
"code": "# Python3 program to demonstrate Range # Update and PoQueries Without using BIT # Updates such that getElement() gets an # increased value when queried from l to r. def update(arr, l, r, val): arr[l] += val if r + 1 < len(arr): arr[r + 1] -= val # Get the element indexed at i def getElement(arr, i): # To get ith element sum of all the elements # from 0 to i need to be computed res = 0 for j in range(i + 1): res += arr[j] return res # Driver Codeif __name__ == '__main__': arr = [0, 0, 0, 0, 0] n = len(arr) l = 2 r = 4 val = 2 update(arr, l, r, val) # Find the element at Index 4 index = 4 print(\"Element at index\", index, \"is\", getElement(arr, index)) l = 0 r = 3 val = 4 update(arr, l, r, val) # Find the element at Index 3 index = 3 print(\"Element at index\", index, \"is\", getElement(arr, index)) # This code is contributed by PranchalK",
"e": 72218,
"s": 71241,
"text": null
},
{
"code": "// C# program to demonstrate Range Update // and Point Queries Without using BIT using System; class GfG { // Updates such that getElement() // gets an increased value when// queried from l to r. static void update(int []arr, int l, int r, int val) { arr[l] += val; if(r + 1 < arr.Length) arr[r + 1] -= val; } // Get the element indexed at i static int getElement(int []arr, int i) { // To get ith element sum of all the elements // from 0 to i need to be computed int res = 0; for (int j = 0 ; j <= i; j++) res += arr[j]; return res; } // Driver code public static void Main(String[] args) { int []arr = {0, 0, 0, 0, 0}; int n = arr.Length; int l = 2, r = 4, val = 2; update(arr, l, r, val); //Find the element at Index 4 int index = 4; Console.WriteLine(\"Element at index \" + index + \" is \" + getElement(arr, index)); l = 0; r = 3; val = 4; update(arr,l,r,val); //Find the element at Index 3 index = 3; Console.WriteLine(\"Element at index \" + index + \" is \" + getElement(arr, index)); } } // This code is contributed by PrinciRaj1992",
"e": 73491,
"s": 72218,
"text": null
},
{
"code": "<?php// PHP program to demonstrate Range Update // and Point Queries Without using BIT // Updates such that getElement() gets an // increased value when queried from l to r. function update(&$arr, $l, $r, $val) { $arr[$l] += $val; if($r + 1 < sizeof($arr)) $arr[$r + 1] -= $val; } // Get the element indexed at i function getElement(&$arr, $i) { // To get ith element sum of all the elements // from 0 to i need to be computed $res = 0; for ($j = 0 ; $j <= $i; $j++) $res += $arr[$j]; return $res; } // Driver Code$arr = array(0, 0, 0, 0, 0); $n = sizeof($arr); $l = 2; $r = 4; $val = 2; update($arr, $l, $r, $val); // Find the element at Index 4 $index = 4; echo(\"Element at index \" . $index . \" is \" . getElement($arr, $index) . \"\\n\"); $l = 0;$r = 3;$val = 4; update($arr, $l, $r, $val); // Find the element at Index 3 $index = 3; echo(\"Element at index \" . $index . \" is \" . getElement($arr, $index)); // This code is contributed by Code_Mech?>",
"e": 74505,
"s": 73491,
"text": null
},
{
"code": null,
"e": 74554,
"s": 74505,
"text": "Element at index 4 is 2\nElement at index 3 is 6\n"
},
{
"code": null,
"e": 74609,
"s": 74554,
"text": "Time complexity : O(q*n) where q is number of queries."
},
{
"code": null,
"e": 74648,
"s": 74611,
"text": "Method 3 (Using Binary Indexed Tree)"
},
{
"code": null,
"e": 74824,
"s": 74648,
"text": "In method 2, we have seen that the problem can reduced to update and prefix sum queries. We have seen that BIT can be used to do update and prefix sum queries in O(Logn) time."
},
{
"code": null,
"e": 74853,
"s": 74824,
"text": "Below is the implementation."
},
{
"code": null,
"e": 74857,
"s": 74853,
"text": "C++"
},
{
"code": null,
"e": 74862,
"s": 74857,
"text": "Java"
},
{
"code": null,
"e": 74870,
"s": 74862,
"text": "Python3"
},
{
"code": null,
"e": 74873,
"s": 74870,
"text": "C#"
},
{
"code": "// C++ code to demonstrate Range Update and// Point Queries on a Binary Index Tree#include <bits/stdc++.h>using namespace std; // Updates a node in Binary Index Tree (BITree) at given index// in BITree. The given value 'val' is added to BITree[i] and// all of its ancestors in tree.void updateBIT(int BITree[], int n, int index, int val){ // index in BITree[] is 1 more than the index in arr[] index = index + 1; // Traverse all ancestors and add 'val' while (index <= n) { // Add 'val' to current node of BI Tree BITree[index] += val; // Update index to that of parent in update View index += index & (-index); }} // Constructs and returns a Binary Indexed Tree for given// array of size n.int *constructBITree(int arr[], int n){ // Create and initialize BITree[] as 0 int *BITree = new int[n+1]; for (int i=1; i<=n; i++) BITree[i] = 0; // Store the actual values in BITree[] using update() for (int i=0; i<n; i++) updateBIT(BITree, n, i, arr[i]); // Uncomment below lines to see contents of BITree[] //for (int i=1; i<=n; i++) // cout << BITree[i] << \" \"; return BITree;} // SERVES THE PURPOSE OF getElement()// Returns sum of arr[0..index]. This function assumes// that the array is preprocessed and partial sums of// array elements are stored in BITree[]int getSum(int BITree[], int index){ int sum = 0; // Iniialize result // index in BITree[] is 1 more than the index in arr[] index = index + 1; // Traverse ancestors of BITree[index] while (index>0) { // Add current element of BITree to sum sum += BITree[index]; // Move index to parent node in getSum View index -= index & (-index); } return sum;} // Updates such that getElement() gets an increased// value when queried from l to r.void update(int BITree[], int l, int r, int n, int val){ // Increase value at 'l' by 'val' updateBIT(BITree, n, l, val); // Decrease value at 'r+1' by 'val' updateBIT(BITree, n, r+1, -val);} // Driver program to test above functionint main(){ int arr[] = {0, 0, 0, 0, 0}; int n = sizeof(arr)/sizeof(arr[0]); int *BITree = constructBITree(arr, n); // Add 2 to all the element from [2,4] int l = 2, r = 4, val = 2; update(BITree, l, r, n, val); // Find the element at Index 4 int index = 4; cout << \"Element at index \" << index << \" is \" << getSum(BITree,index) << \"\\n\"; // Add 2 to all the element from [0,3] l = 0, r = 3, val = 4; update(BITree, l, r, n, val); // Find the element at Index 3 index = 3; cout << \"Element at index \" << index << \" is \" << getSum(BITree,index) << \"\\n\" ; return 0;}",
"e": 77613,
"s": 74873,
"text": null
},
{
"code": "/* Java code to demonstrate Range Update and* Point Queries on a Binary Index Tree.* This method only works when all array* values are initially 0.*/class GFG{ // Max tree size final static int MAX = 1000; static int BITree[] = new int[MAX]; // Updates a node in Binary Index // Tree (BITree) at given index // in BITree. The given value 'val' // is added to BITree[i] and // all of its ancestors in tree. public static void updateBIT(int n, int index, int val) { // index in BITree[] is 1 // more than the index in arr[] index = index + 1; // Traverse all ancestors // and add 'val' while (index <= n) { // Add 'val' to current // node of BITree BITree[index] += val; // Update index to that // of parent in update View index += index & (-index); } } // Constructs Binary Indexed Tree // for given array of size n. public static void constructBITree(int arr[], int n) { // Initialize BITree[] as 0 for(int i = 1; i <= n; i++) BITree[i] = 0; // Store the actual values // in BITree[] using update() for(int i = 0; i < n; i++) updateBIT(n, i, arr[i]); // Uncomment below lines to // see contents of BITree[] // for (int i=1; i<=n; i++) // cout << BITree[i] << \" \"; } // SERVES THE PURPOSE OF getElement() // Returns sum of arr[0..index]. This // function assumes that the array is // preprocessed and partial sums of // array elements are stored in BITree[] public static int getSum(int index) { int sum = 0; //Initialize result // index in BITree[] is 1 more // than the index in arr[] index = index + 1; // Traverse ancestors // of BITree[index] while (index > 0) { // Add current element // of BITree to sum sum += BITree[index]; // Move index to parent // node in getSum View index -= index & (-index); } // Return the sum return sum; } // Updates such that getElement() // gets an increased value when // queried from l to r. public static void update(int l, int r, int n, int val) { // Increase value at // 'l' by 'val' updateBIT(n, l, val); // Decrease value at // 'r+1' by 'val' updateBIT(n, r + 1, -val); } // Driver Code public static void main(String args[]) { int arr[] = {0, 0, 0, 0, 0}; int n = arr.length; constructBITree(arr,n); // Add 2 to all the // element from [2,4] int l = 2, r = 4, val = 2; update(l, r, n, val); int index = 4; System.out.println(\"Element at index \"+ index + \" is \"+ getSum(index)); // Add 2 to all the // element from [0,3] l = 0; r = 3; val = 4; update(l, r, n, val); // Find the element // at Index 3 index = 3; System.out.println(\"Element at index \"+ index + \" is \"+ getSum(index)); }}// This code is contributed// by Puneet Kumar.",
"e": 81132,
"s": 77613,
"text": null
},
{
"code": "# Python3 code to demonstrate Range Update and# PoQueries on a Binary Index Tree # Updates a node in Binary Index Tree (BITree) at given index# in BITree. The given value 'val' is added to BITree[i] and# all of its ancestors in tree.def updateBIT(BITree, n, index, val): # index in BITree[] is 1 more than the index in arr[] index = index + 1 # Traverse all ancestors and add 'val' while (index <= n): # Add 'val' to current node of BI Tree BITree[index] += val # Update index to that of parent in update View index += index & (-index) # Constructs and returns a Binary Indexed Tree for given# array of size n.def constructBITree(arr, n): # Create and initialize BITree[] as 0 BITree = [0]*(n+1) # Store the actual values in BITree[] using update() for i in range(n): updateBIT(BITree, n, i, arr[i]) return BITree # SERVES THE PURPOSE OF getElement()# Returns sum of arr[0..index]. This function assumes# that the array is preprocessed and partial sums of# array elements are stored in BITree[]def getSum(BITree, index): sum = 0 # Iniialize result # index in BITree[] is 1 more than the index in arr[] index = index + 1 # Traverse ancestors of BITree[index] while (index > 0): # Add current element of BITree to sum sum += BITree[index] # Move index to parent node in getSum View index -= index & (-index) return sum # Updates such that getElement() gets an increased# value when queried from l to r.def update(BITree, l, r, n, val): # Increase value at 'l' by 'val' updateBIT(BITree, n, l, val) # Decrease value at 'r+1' by 'val' updateBIT(BITree, n, r+1, -val) # Driver codearr = [0, 0, 0, 0, 0]n = len(arr)BITree = constructBITree(arr, n) # Add 2 to all the element from [2,4]l = 2r = 4val = 2update(BITree, l, r, n, val) # Find the element at Index 4index = 4print(\"Element at index\", index, \"is\", getSum(BITree, index)) # Add 2 to all the element from [0,3]l = 0r = 3val = 4update(BITree, l, r, n, val) # Find the element at Index 3index = 3print(\"Element at index\", index, \"is\", getSum(BITree,index)) # This code is contributed by mohit kumar 29",
"e": 83368,
"s": 81132,
"text": null
},
{
"code": "using System; /* C# code to demonstrate Range Update and * Point Queries on a Binary Index Tree. * This method only works when all array * values are initially 0.*/public class GFG{ // Max tree size public const int MAX = 1000; public static int[] BITree = new int[MAX]; // Updates a node in Binary Index // Tree (BITree) at given index // in BITree. The given value 'val' // is added to BITree[i] and // all of its ancestors in tree. public static void updateBIT(int n, int index, int val) { // index in BITree[] is 1 // more than the index in arr[] index = index + 1; // Traverse all ancestors // and add 'val' while (index <= n) { // Add 'val' to current // node of BITree BITree[index] += val; // Update index to that // of parent in update View index += index & (-index); } } // Constructs Binary Indexed Tree // for given array of size n. public static void constructBITree(int[] arr, int n) { // Initialize BITree[] as 0 for (int i = 1; i <= n; i++) { BITree[i] = 0; } // Store the actual values // in BITree[] using update() for (int i = 0; i < n; i++) { updateBIT(n, i, arr[i]); } // Uncomment below lines to // see contents of BITree[] // for (int i=1; i<=n; i++) // cout << BITree[i] << \" \"; } // SERVES THE PURPOSE OF getElement() // Returns sum of arr[0..index]. This // function assumes that the array is // preprocessed and partial sums of // array elements are stored in BITree[] public static int getSum(int index) { int sum = 0; //Initialize result // index in BITree[] is 1 more // than the index in arr[] index = index + 1; // Traverse ancestors // of BITree[index] while (index > 0) { // Add current element // of BITree to sum sum += BITree[index]; // Move index to parent // node in getSum View index -= index & (-index); } // Return the sum return sum; } // Updates such that getElement() // gets an increased value when // queried from l to r. public static void update(int l, int r, int n, int val) { // Increase value at // 'l' by 'val' updateBIT(n, l, val); // Decrease value at // 'r+1' by 'val' updateBIT(n, r + 1, -val); } // Driver Code public static void Main(string[] args) { int[] arr = new int[] {0, 0, 0, 0, 0}; int n = arr.Length; constructBITree(arr,n); // Add 2 to all the // element from [2,4] int l = 2, r = 4, val = 2; update(l, r, n, val); int index = 4; Console.WriteLine(\"Element at index \" + index + \" is \" + getSum(index)); // Add 2 to all the // element from [0,3] l = 0; r = 3; val = 4; update(l, r, n, val); // Find the element // at Index 3 index = 3; Console.WriteLine(\"Element at index \" + index + \" is \" + getSum(index)); }} // This code is contributed by Shrikant13",
"e": 86771,
"s": 83368,
"text": null
},
{
"code": null,
"e": 86779,
"s": 86771,
"text": "Output:"
},
{
"code": null,
"e": 86828,
"s": 86779,
"text": "Element at index 4 is 2\nElement at index 3 is 6\n"
},
{
"code": null,
"e": 86904,
"s": 86828,
"text": "Time Complexity : O(q * log n) + O(n * log n) where q is number of queries."
},
{
"code": null,
"e": 87091,
"s": 86904,
"text": "Method 1 is efficient when most of the queries are getElement(), method 2 is efficient when most of the queries are updates() and method 3 is preferred when there is mix of both queries."
},
{
"code": null,
"e": 87393,
"s": 87091,
"text": "This article is contributed by Chirag Agarwal. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks."
},
{
"code": null,
"e": 87518,
"s": 87393,
"text": "Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above."
},
{
"code": null,
"e": 87525,
"s": 87518,
"text": "p_unit"
},
{
"code": null,
"e": 87537,
"s": 87525,
"text": "shrikanth13"
},
{
"code": null,
"e": 87550,
"s": 87537,
"text": "prerna saini"
},
{
"code": null,
"e": 87564,
"s": 87550,
"text": "princiraj1992"
},
{
"code": null,
"e": 87580,
"s": 87564,
"text": "PranchalKatiyar"
},
{
"code": null,
"e": 87590,
"s": 87580,
"text": "Code_Mech"
},
{
"code": null,
"e": 87601,
"s": 87590,
"text": "nidhi_biet"
},
{
"code": null,
"e": 87616,
"s": 87601,
"text": "mohit kumar 29"
},
{
"code": null,
"e": 87636,
"s": 87616,
"text": "array-range-queries"
},
{
"code": null,
"e": 87656,
"s": 87636,
"text": "Binary Indexed Tree"
},
{
"code": null,
"e": 87680,
"s": 87656,
"text": "Advanced Data Structure"
},
{
"code": null,
"e": 87685,
"s": 87680,
"text": "Tree"
},
{
"code": null,
"e": 87690,
"s": 87685,
"text": "Tree"
},
{
"code": null,
"e": 87710,
"s": 87690,
"text": "Binary Indexed Tree"
},
{
"code": null,
"e": 87808,
"s": 87710,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 87842,
"s": 87808,
"text": "Agents in Artificial Intelligence"
},
{
"code": null,
"e": 87882,
"s": 87842,
"text": "Decision Tree Introduction with example"
},
{
"code": null,
"e": 87910,
"s": 87882,
"text": "AVL Tree | Set 2 (Deletion)"
},
{
"code": null,
"e": 87942,
"s": 87910,
"text": "Red-Black Tree | Set 2 (Insert)"
},
{
"code": null,
"e": 87971,
"s": 87942,
"text": "Disjoint Set Data Structures"
},
{
"code": null,
"e": 88021,
"s": 87971,
"text": "Tree Traversals (Inorder, Preorder and Postorder)"
},
{
"code": null,
"e": 88056,
"s": 88021,
"text": "Binary Tree | Set 1 (Introduction)"
},
{
"code": null,
"e": 88090,
"s": 88056,
"text": "Level Order Binary Tree Traversal"
},
{
"code": null,
"e": 88133,
"s": 88090,
"text": "Binary Tree | Set 3 (Types of Binary Tree)"
}
] |
JavaScript | Intl.DateTimeFormat.prototype.resolvedOptions() Method - GeeksforGeeks | 20 Nov, 2021
The Intl.DateTimeFormat.prototype.resolvedOptions() method is an inbuilt method in JavaScript which returns a new object with properties reflecting the locale, date and time formatting options computed during initialization of this DateTimeFormat object.Syntax:
dateTimeFormat.resolvedOptions()
Parameters: This method does not accept any parameters.Return value: This method returns a new object with properties reflecting the locale and date and time.Below examples illustrate the Intl.DateTimeFormat.prototype.resolvedOptions() method in JavaScript:Example 1:
javascript
const geeks = new Intl.DateTimeFormat('zh-CN', { timeZone: 'UTC' });const result = geeks.resolvedOptions();console.log(result.locale);console.log(result.calendar);console.log(result.timeZone); const geeks1 = new Intl.DateTimeFormat('LT');const result1 = geeks1.resolvedOptions();console.log(result1.locale);console.log(result1.calendar);
Output:
"zh-CN"
"gregory"
"UTC"
"lt"
"gregory"
Example 2:
javascript
var geeks = new Intl.DateTimeFormat('de-XX', { timeZone: 'UTC' });var result = geeks.resolvedOptions(); console.log(result.locale); console.log(result.calendar); console.log(result.numberingSystem);console.log(result.timeZone); console.log(result.month);
Output:
"de"
"gregory"
"latn"
"UTC"
"numeric"
Supported Browsers: The browsers supported by Intl.DateTimeFormat.prototype.resolvedOptions() method are listed below:
Google Chrome 24 and above
Edge 12 and above
Firefox 29 and above
Opera 15 and above
Safari 10 and above
ysachin2314
javascript-functions
JavaScript
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Remove elements from a JavaScript Array
Convert a string to an integer in JavaScript
Difference between var, let and const keywords in JavaScript
Differences between Functional Components and Class Components in React
How to Open URL in New Tab using JavaScript ?
Remove elements from a JavaScript Array
Installation of Node.js on Linux
Convert a string to an integer in JavaScript
How to fetch data from an API in ReactJS ?
How to insert spaces/tabs in text using HTML/CSS? | [
{
"code": null,
"e": 26177,
"s": 26149,
"text": "\n20 Nov, 2021"
},
{
"code": null,
"e": 26441,
"s": 26177,
"text": "The Intl.DateTimeFormat.prototype.resolvedOptions() method is an inbuilt method in JavaScript which returns a new object with properties reflecting the locale, date and time formatting options computed during initialization of this DateTimeFormat object.Syntax: "
},
{
"code": null,
"e": 26474,
"s": 26441,
"text": "dateTimeFormat.resolvedOptions()"
},
{
"code": null,
"e": 26744,
"s": 26474,
"text": "Parameters: This method does not accept any parameters.Return value: This method returns a new object with properties reflecting the locale and date and time.Below examples illustrate the Intl.DateTimeFormat.prototype.resolvedOptions() method in JavaScript:Example 1: "
},
{
"code": null,
"e": 26755,
"s": 26744,
"text": "javascript"
},
{
"code": "const geeks = new Intl.DateTimeFormat('zh-CN', { timeZone: 'UTC' });const result = geeks.resolvedOptions();console.log(result.locale);console.log(result.calendar);console.log(result.timeZone); const geeks1 = new Intl.DateTimeFormat('LT');const result1 = geeks1.resolvedOptions();console.log(result1.locale);console.log(result1.calendar);",
"e": 27093,
"s": 26755,
"text": null
},
{
"code": null,
"e": 27103,
"s": 27093,
"text": "Output: "
},
{
"code": null,
"e": 27142,
"s": 27103,
"text": "\"zh-CN\"\n\"gregory\"\n\"UTC\"\n\"lt\"\n\"gregory\""
},
{
"code": null,
"e": 27155,
"s": 27142,
"text": "Example 2: "
},
{
"code": null,
"e": 27166,
"s": 27155,
"text": "javascript"
},
{
"code": "var geeks = new Intl.DateTimeFormat('de-XX', { timeZone: 'UTC' });var result = geeks.resolvedOptions(); console.log(result.locale); console.log(result.calendar); console.log(result.numberingSystem);console.log(result.timeZone); console.log(result.month);",
"e": 27437,
"s": 27166,
"text": null
},
{
"code": null,
"e": 27447,
"s": 27437,
"text": "Output: "
},
{
"code": null,
"e": 27485,
"s": 27447,
"text": "\"de\"\n\"gregory\"\n\"latn\"\n\"UTC\"\n\"numeric\""
},
{
"code": null,
"e": 27606,
"s": 27485,
"text": "Supported Browsers: The browsers supported by Intl.DateTimeFormat.prototype.resolvedOptions() method are listed below: "
},
{
"code": null,
"e": 27633,
"s": 27606,
"text": "Google Chrome 24 and above"
},
{
"code": null,
"e": 27651,
"s": 27633,
"text": "Edge 12 and above"
},
{
"code": null,
"e": 27672,
"s": 27651,
"text": "Firefox 29 and above"
},
{
"code": null,
"e": 27691,
"s": 27672,
"text": "Opera 15 and above"
},
{
"code": null,
"e": 27711,
"s": 27691,
"text": "Safari 10 and above"
},
{
"code": null,
"e": 27725,
"s": 27713,
"text": "ysachin2314"
},
{
"code": null,
"e": 27746,
"s": 27725,
"text": "javascript-functions"
},
{
"code": null,
"e": 27757,
"s": 27746,
"text": "JavaScript"
},
{
"code": null,
"e": 27774,
"s": 27757,
"text": "Web Technologies"
},
{
"code": null,
"e": 27872,
"s": 27774,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 27912,
"s": 27872,
"text": "Remove elements from a JavaScript Array"
},
{
"code": null,
"e": 27957,
"s": 27912,
"text": "Convert a string to an integer in JavaScript"
},
{
"code": null,
"e": 28018,
"s": 27957,
"text": "Difference between var, let and const keywords in JavaScript"
},
{
"code": null,
"e": 28090,
"s": 28018,
"text": "Differences between Functional Components and Class Components in React"
},
{
"code": null,
"e": 28136,
"s": 28090,
"text": "How to Open URL in New Tab using JavaScript ?"
},
{
"code": null,
"e": 28176,
"s": 28136,
"text": "Remove elements from a JavaScript Array"
},
{
"code": null,
"e": 28209,
"s": 28176,
"text": "Installation of Node.js on Linux"
},
{
"code": null,
"e": 28254,
"s": 28209,
"text": "Convert a string to an integer in JavaScript"
},
{
"code": null,
"e": 28297,
"s": 28254,
"text": "How to fetch data from an API in ReactJS ?"
}
] |
How to Find the Percentage of Two Cells in Microsoft Excel? - GeeksforGeeks | 18 Jul, 2021
If you want to find the percentage of two cells in Microsoft Excel, Simply select an empty cell, where you want to display the percentage of the two cells.
Type in the following formula in the selected cell :
=address of cell1/address of cell2
For example, I want to print out the percentage of C2 and C3, so the formulae will be: =C2/C3, in an empty cell C4.
As soon as you click on the return key, You will get your percentage calculated in cell C4.
However, if a decimal value is displayed in the cell. Like 0.10, Simply press the shortcut key Ctrl+Shift+% to format as a percent or convert the numeric value into the percentage style and press the Return key.
The Decimal value will be converted to a percentage.
Before
After
You can also go to the Number section under the Home tab and press the % Symbol to convert to percentage format.
% symbol under the Number listbox
Microsoft
Picked
Excel
Microsoft
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Use Solver in Excel?
How to Find the Last Used Row and Column in Excel VBA?
Macros in Excel
How to Get Length of Array in Excel VBA?
How to Remove Duplicates From Array Using VBA in Excel?
How to Extract the Last Word From a Cell in Excel?
Using CHOOSE Function along with VLOOKUP in Excel
Introduction to Excel Spreadsheet
How to Show Percentages in Stacked Column Chart in Excel?
How to Sum Values Based on Criteria in Another Column in Excel? | [
{
"code": null,
"e": 25167,
"s": 25139,
"text": "\n18 Jul, 2021"
},
{
"code": null,
"e": 25323,
"s": 25167,
"text": "If you want to find the percentage of two cells in Microsoft Excel, Simply select an empty cell, where you want to display the percentage of the two cells."
},
{
"code": null,
"e": 25376,
"s": 25323,
"text": "Type in the following formula in the selected cell :"
},
{
"code": null,
"e": 25411,
"s": 25376,
"text": "=address of cell1/address of cell2"
},
{
"code": null,
"e": 25527,
"s": 25411,
"text": "For example, I want to print out the percentage of C2 and C3, so the formulae will be: =C2/C3, in an empty cell C4."
},
{
"code": null,
"e": 25619,
"s": 25527,
"text": "As soon as you click on the return key, You will get your percentage calculated in cell C4."
},
{
"code": null,
"e": 25831,
"s": 25619,
"text": "However, if a decimal value is displayed in the cell. Like 0.10, Simply press the shortcut key Ctrl+Shift+% to format as a percent or convert the numeric value into the percentage style and press the Return key."
},
{
"code": null,
"e": 25884,
"s": 25831,
"text": "The Decimal value will be converted to a percentage."
},
{
"code": null,
"e": 25891,
"s": 25884,
"text": "Before"
},
{
"code": null,
"e": 25897,
"s": 25891,
"text": "After"
},
{
"code": null,
"e": 26010,
"s": 25897,
"text": "You can also go to the Number section under the Home tab and press the % Symbol to convert to percentage format."
},
{
"code": null,
"e": 26044,
"s": 26010,
"text": "% symbol under the Number listbox"
},
{
"code": null,
"e": 26054,
"s": 26044,
"text": "Microsoft"
},
{
"code": null,
"e": 26061,
"s": 26054,
"text": "Picked"
},
{
"code": null,
"e": 26067,
"s": 26061,
"text": "Excel"
},
{
"code": null,
"e": 26077,
"s": 26067,
"text": "Microsoft"
},
{
"code": null,
"e": 26175,
"s": 26077,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 26203,
"s": 26175,
"text": "How to Use Solver in Excel?"
},
{
"code": null,
"e": 26258,
"s": 26203,
"text": "How to Find the Last Used Row and Column in Excel VBA?"
},
{
"code": null,
"e": 26274,
"s": 26258,
"text": "Macros in Excel"
},
{
"code": null,
"e": 26315,
"s": 26274,
"text": "How to Get Length of Array in Excel VBA?"
},
{
"code": null,
"e": 26371,
"s": 26315,
"text": "How to Remove Duplicates From Array Using VBA in Excel?"
},
{
"code": null,
"e": 26422,
"s": 26371,
"text": "How to Extract the Last Word From a Cell in Excel?"
},
{
"code": null,
"e": 26472,
"s": 26422,
"text": "Using CHOOSE Function along with VLOOKUP in Excel"
},
{
"code": null,
"e": 26506,
"s": 26472,
"text": "Introduction to Excel Spreadsheet"
},
{
"code": null,
"e": 26564,
"s": 26506,
"text": "How to Show Percentages in Stacked Column Chart in Excel?"
}
] |
Docker - Installation | Let’s go through the installation of each product.
Once the installer has been downloaded, double-click it to start the installer and then follow the steps given below.
Step 1 − Click on the Agreement terms and then the Install button to proceed ahead with the installation.
Step 2 − Once complete, click the Finish button to complete the installation.
Once the installer has been downloaded, double-click it to start the installer and then follow the steps given below.
Step 1 − Click the Next button on the start screen.
Step 2 − Keep the default location on the next screen and click the Next button.
Step 3 − Keep the default components and click the Next button to proceed.
Step 4 − Keep the Additional Tasks as they are and then click the Next button.
Step 5 − On the final screen, click the Install button.
Let’s now look at how Docker Toolbox can be used to work with Docker containers on Windows. The first step is to launch the Docker Toolbox application for which the shortcut is created on the desktop when the installation of Docker toolbox is carried out.
Next, you will see the configuration being carried out when Docker toolbox is launched.
Once done, you will see Docker configured and launched. You will get an interactive shell for Docker.
To test that Docker runs properly, we can use the Docker run command to download and run a simple HelloWorld Docker container.
The working of the Docker run command is given below −
docker run
This command is used to run a command in a Docker container.
docker run image
Image − This is the name of the image which is used to run the container.
Image − This is the name of the image which is used to run the container.
The output will run the command in the desired container.
sudo docker run hello-world
This command will download the hello-world image, if it is not already present, and run the hello-world as a container.
When we run the above command, we will get the following result −
If you want to run the Ubuntu OS on Windows, you can download the Ubuntu Image using the following command −
Docker run –it ubuntu bash
Here you are telling Docker to run the command in the interactive mode via the –it option.
In the output you can see that the Ubuntu image is downloaded and run and then you will be logged in as a root user in the Ubuntu container.
70 Lectures
12 hours
Anshul Chauhan
41 Lectures
5 hours
AR Shankar
31 Lectures
3 hours
Abhilash Nelson
15 Lectures
2 hours
Harshit Srivastava, Pranjal Srivastava
33 Lectures
4 hours
Mumshad Mannambeth
13 Lectures
53 mins
Musab Zayadneh
Print
Add Notes
Bookmark this page | [
{
"code": null,
"e": 2391,
"s": 2340,
"text": "Let’s go through the installation of each product."
},
{
"code": null,
"e": 2509,
"s": 2391,
"text": "Once the installer has been downloaded, double-click it to start the installer and then follow the steps given below."
},
{
"code": null,
"e": 2615,
"s": 2509,
"text": "Step 1 − Click on the Agreement terms and then the Install button to proceed ahead with the installation."
},
{
"code": null,
"e": 2693,
"s": 2615,
"text": "Step 2 − Once complete, click the Finish button to complete the installation."
},
{
"code": null,
"e": 2811,
"s": 2693,
"text": "Once the installer has been downloaded, double-click it to start the installer and then follow the steps given below."
},
{
"code": null,
"e": 2863,
"s": 2811,
"text": "Step 1 − Click the Next button on the start screen."
},
{
"code": null,
"e": 2944,
"s": 2863,
"text": "Step 2 − Keep the default location on the next screen and click the Next button."
},
{
"code": null,
"e": 3019,
"s": 2944,
"text": "Step 3 − Keep the default components and click the Next button to proceed."
},
{
"code": null,
"e": 3098,
"s": 3019,
"text": "Step 4 − Keep the Additional Tasks as they are and then click the Next button."
},
{
"code": null,
"e": 3154,
"s": 3098,
"text": "Step 5 − On the final screen, click the Install button."
},
{
"code": null,
"e": 3410,
"s": 3154,
"text": "Let’s now look at how Docker Toolbox can be used to work with Docker containers on Windows. The first step is to launch the Docker Toolbox application for which the shortcut is created on the desktop when the installation of Docker toolbox is carried out."
},
{
"code": null,
"e": 3498,
"s": 3410,
"text": "Next, you will see the configuration being carried out when Docker toolbox is launched."
},
{
"code": null,
"e": 3600,
"s": 3498,
"text": "Once done, you will see Docker configured and launched. You will get an interactive shell for Docker."
},
{
"code": null,
"e": 3727,
"s": 3600,
"text": "To test that Docker runs properly, we can use the Docker run command to download and run a simple HelloWorld Docker container."
},
{
"code": null,
"e": 3782,
"s": 3727,
"text": "The working of the Docker run command is given below −"
},
{
"code": null,
"e": 3795,
"s": 3782,
"text": "docker run \n"
},
{
"code": null,
"e": 3856,
"s": 3795,
"text": "This command is used to run a command in a Docker container."
},
{
"code": null,
"e": 3874,
"s": 3856,
"text": "docker run image\n"
},
{
"code": null,
"e": 3948,
"s": 3874,
"text": "Image − This is the name of the image which is used to run the container."
},
{
"code": null,
"e": 4022,
"s": 3948,
"text": "Image − This is the name of the image which is used to run the container."
},
{
"code": null,
"e": 4080,
"s": 4022,
"text": "The output will run the command in the desired container."
},
{
"code": null,
"e": 4108,
"s": 4080,
"text": "sudo docker run hello-world"
},
{
"code": null,
"e": 4228,
"s": 4108,
"text": "This command will download the hello-world image, if it is not already present, and run the hello-world as a container."
},
{
"code": null,
"e": 4294,
"s": 4228,
"text": "When we run the above command, we will get the following result −"
},
{
"code": null,
"e": 4403,
"s": 4294,
"text": "If you want to run the Ubuntu OS on Windows, you can download the Ubuntu Image using the following command −"
},
{
"code": null,
"e": 4431,
"s": 4403,
"text": "Docker run –it ubuntu bash\n"
},
{
"code": null,
"e": 4522,
"s": 4431,
"text": "Here you are telling Docker to run the command in the interactive mode via the –it option."
},
{
"code": null,
"e": 4663,
"s": 4522,
"text": "In the output you can see that the Ubuntu image is downloaded and run and then you will be logged in as a root user in the Ubuntu container."
},
{
"code": null,
"e": 4697,
"s": 4663,
"text": "\n 70 Lectures \n 12 hours \n"
},
{
"code": null,
"e": 4713,
"s": 4697,
"text": " Anshul Chauhan"
},
{
"code": null,
"e": 4746,
"s": 4713,
"text": "\n 41 Lectures \n 5 hours \n"
},
{
"code": null,
"e": 4758,
"s": 4746,
"text": " AR Shankar"
},
{
"code": null,
"e": 4791,
"s": 4758,
"text": "\n 31 Lectures \n 3 hours \n"
},
{
"code": null,
"e": 4808,
"s": 4791,
"text": " Abhilash Nelson"
},
{
"code": null,
"e": 4841,
"s": 4808,
"text": "\n 15 Lectures \n 2 hours \n"
},
{
"code": null,
"e": 4881,
"s": 4841,
"text": " Harshit Srivastava, Pranjal Srivastava"
},
{
"code": null,
"e": 4914,
"s": 4881,
"text": "\n 33 Lectures \n 4 hours \n"
},
{
"code": null,
"e": 4934,
"s": 4914,
"text": " Mumshad Mannambeth"
},
{
"code": null,
"e": 4966,
"s": 4934,
"text": "\n 13 Lectures \n 53 mins\n"
},
{
"code": null,
"e": 4982,
"s": 4966,
"text": " Musab Zayadneh"
},
{
"code": null,
"e": 4989,
"s": 4982,
"text": " Print"
},
{
"code": null,
"e": 5000,
"s": 4989,
"text": " Add Notes"
}
] |
Maximum number of candies that can be bought - GeeksforGeeks | 19 May, 2021
Given an array arr[] of size n where arr[i] is the number of candies of type i. You have an unlimited amount of money. The task is to buy as many candies as possible satisfying the following conditions: If you buy x(i) candies of type i (clearly, 0 ≤ x(i) ≤ arr[i]), then for all j (1 ≤ j ≤ i) at least one of the following must hold:
x(j) < x(i) (you bought less candies of type j than of type i)x(j) = 0 (you bought 0 candies of type j)
x(j) < x(i) (you bought less candies of type j than of type i)
x(j) = 0 (you bought 0 candies of type j)
Examples:
Input:arr[] = {1, 2, 1, 3, 6} Output: 10 x[] = {0, 0, 1, 3, 6} where x[i] is the number of candies bought of type iInput: arr[] = {3, 2, 5, 4, 10} Output: 20Input: arr[] = {1, 1, 1, 1} Output: 1
Approach: We can use a greedy approach and start from the end of the array. If we have taken x candies of type i + 1 then we can only take min(arr[i], x – 1) candies of type i. If this value is negative, we cannot buy candies of the current type.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 to return the maximum candies// that can be boughtint maxCandies(int arr[], int n){ // Buy all the candies of the last type int prevBought = arr[n - 1]; int candies = prevBought; // Starting from second last for (int i = n - 2; i >= 0; i--) { // Amount of candies of the current // type that can be bought int x = min(prevBought - 1, arr[i]); if (x >= 0) { // Add candies of current type // that can be bought candies += x; // Update the previous bought amount prevBought = x; } } return candies;} // Driver codeint main(){ int arr[] = { 1, 2, 1, 3, 6 }; int n = sizeof(arr) / sizeof(arr[0]); cout << maxCandies(arr, n); return 0;}
// Java implementation of the approachclass GFG{ // Function to return the maximum candies// that can be boughtstatic int maxCandies(int arr[], int n){ // Buy all the candies of the last type int prevBought = arr[n - 1]; int candies = prevBought; // Starting from second last for (int i = n - 2; i >= 0; i--) { // Amount of candies of the current // type that can be bought int x = Math.min(prevBought - 1, arr[i]); if (x >= 0) { // Add candies of current type // that can be bought candies += x; // Update the previous bought amount prevBought = x; } } return candies;} // Driver codepublic static void main(String[] args){ int arr[] = { 1, 2, 1, 3, 6 }; int n = arr.length; System.out.println(maxCandies(arr, n));}} // This code is contributed by Code_Mech.
# Python3 implementation of the approach # Function to return the maximum candies# that can be boughtdef maxCandies(arr, n) : # Buy all the candies of the last type prevBought = arr[n - 1]; candies = prevBought; # Starting from second last for i in range(n - 2, -1, -1) : # Amount of candies of the current # type that can be bought x = min(prevBought - 1, arr[i]); if (x >= 0) : # Add candies of current type # that can be bought candies += x; # Update the previous bought amount prevBought = x; return candies; # Driver codeif __name__ == "__main__" : arr = [ 1, 2, 1, 3, 6 ]; n = len(arr) print(maxCandies(arr, n)); # This code is contributed by Ryuga
// C# implementation of the approachusing System; class GFG{ // Function to return the maximum candies// that can be boughtstatic int maxCandies(int[] arr, int n){ // Buy all the candies of the last type int prevBought = arr[n - 1]; int candies = prevBought; // Starting from second last for (int i = n - 2; i >= 0; i--) { // Amount of candies of the current // type that can be bought int x = Math.Min(prevBought - 1, arr[i]); if (x >= 0) { // Add candies of current type // that can be bought candies += x; // Update the previous bought amount prevBought = x; } } return candies;} // Driver codepublic static void Main(){ int[] arr= { 1, 2, 1, 3, 6 }; int n = arr.Length; Console.WriteLine(maxCandies(arr, n));}} // This code is contributed by Code_Mech.
<?php// PHP implementation of the approach // Function to return the maximum candies// that can be boughtfunction maxCandies($arr, $n){ // Buy all the candies of the last type $prevBought = $arr[$n - 1]; $candies = $prevBought; // Starting from second last for ($i = $n - 2; $i >= 0; $i--) { // Amount of candies of the current // type that can be bought $x = min($prevBought - 1, $arr[$i]); if ($x >= 0) { // Add candies of current type // that can be bought $candies += $x; // Update the previous bought amount $prevBought = $x; } } return $candies;} // Driver code$arr = array(1, 2, 1, 3, 6 );$n = sizeof($arr);echo(maxCandies($arr, $n)); // This code is contributed by Code_Mech.?>
<script> // Javascript implementation of the approach // Function to return the maximum candies// that can be boughtfunction maxCandies(arr, n){ // Buy all the candies of the last type let prevBought = arr[n - 1]; let candies = prevBought; // Starting from second last for (let i = n - 2; i >= 0; i--) { // Amount of candies of the current // type that can be bought let x = Math.min(prevBought - 1, arr[i]); if (x >= 0) { // Add candies of current type // that can be bought candies += x; // Update the previous bought amount prevBought = x; } } return candies;} // Driver Code let arr = [ 1, 2, 1, 3, 6 ]; let n = arr.length; document.write(maxCandies(arr, n)); </script>
10
ankthon
Code_Mech
target_2
Constructive Algorithms
Arrays
Competitive Programming
Greedy
Mathematical
Arrays
Greedy
Mathematical
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
Stack Data Structure (Introduction and Program)
Introduction to Arrays
Multidimensional Arrays in Java
Competitive Programming - A Complete Guide
Practice for cracking any coding interview
Arrow operator -> in C/C++ with Examples
Prefix Sum Array - Implementation and Applications in Competitive Programming
Top 10 Algorithms and Data Structures for Competitive Programming | [
{
"code": null,
"e": 26387,
"s": 26359,
"text": "\n19 May, 2021"
},
{
"code": null,
"e": 26724,
"s": 26387,
"text": "Given an array arr[] of size n where arr[i] is the number of candies of type i. You have an unlimited amount of money. The task is to buy as many candies as possible satisfying the following conditions: If you buy x(i) candies of type i (clearly, 0 ≤ x(i) ≤ arr[i]), then for all j (1 ≤ j ≤ i) at least one of the following must hold: "
},
{
"code": null,
"e": 26828,
"s": 26724,
"text": "x(j) < x(i) (you bought less candies of type j than of type i)x(j) = 0 (you bought 0 candies of type j)"
},
{
"code": null,
"e": 26891,
"s": 26828,
"text": "x(j) < x(i) (you bought less candies of type j than of type i)"
},
{
"code": null,
"e": 26933,
"s": 26891,
"text": "x(j) = 0 (you bought 0 candies of type j)"
},
{
"code": null,
"e": 26945,
"s": 26933,
"text": "Examples: "
},
{
"code": null,
"e": 27142,
"s": 26945,
"text": "Input:arr[] = {1, 2, 1, 3, 6} Output: 10 x[] = {0, 0, 1, 3, 6} where x[i] is the number of candies bought of type iInput: arr[] = {3, 2, 5, 4, 10} Output: 20Input: arr[] = {1, 1, 1, 1} Output: 1 "
},
{
"code": null,
"e": 27443,
"s": 27144,
"text": "Approach: We can use a greedy approach and start from the end of the array. If we have taken x candies of type i + 1 then we can only take min(arr[i], x – 1) candies of type i. If this value is negative, we cannot buy candies of the current type.Below is the implementation of the above approach: "
},
{
"code": null,
"e": 27447,
"s": 27443,
"text": "C++"
},
{
"code": null,
"e": 27452,
"s": 27447,
"text": "Java"
},
{
"code": null,
"e": 27460,
"s": 27452,
"text": "Python3"
},
{
"code": null,
"e": 27463,
"s": 27460,
"text": "C#"
},
{
"code": null,
"e": 27467,
"s": 27463,
"text": "PHP"
},
{
"code": null,
"e": 27478,
"s": 27467,
"text": "Javascript"
},
{
"code": "// C++ implementation of the approach#include <bits/stdc++.h>using namespace std; // Function to return the maximum candies// that can be boughtint maxCandies(int arr[], int n){ // Buy all the candies of the last type int prevBought = arr[n - 1]; int candies = prevBought; // Starting from second last for (int i = n - 2; i >= 0; i--) { // Amount of candies of the current // type that can be bought int x = min(prevBought - 1, arr[i]); if (x >= 0) { // Add candies of current type // that can be bought candies += x; // Update the previous bought amount prevBought = x; } } return candies;} // Driver codeint main(){ int arr[] = { 1, 2, 1, 3, 6 }; int n = sizeof(arr) / sizeof(arr[0]); cout << maxCandies(arr, n); return 0;}",
"e": 28335,
"s": 27478,
"text": null
},
{
"code": "// Java implementation of the approachclass GFG{ // Function to return the maximum candies// that can be boughtstatic int maxCandies(int arr[], int n){ // Buy all the candies of the last type int prevBought = arr[n - 1]; int candies = prevBought; // Starting from second last for (int i = n - 2; i >= 0; i--) { // Amount of candies of the current // type that can be bought int x = Math.min(prevBought - 1, arr[i]); if (x >= 0) { // Add candies of current type // that can be bought candies += x; // Update the previous bought amount prevBought = x; } } return candies;} // Driver codepublic static void main(String[] args){ int arr[] = { 1, 2, 1, 3, 6 }; int n = arr.length; System.out.println(maxCandies(arr, n));}} // This code is contributed by Code_Mech.",
"e": 29236,
"s": 28335,
"text": null
},
{
"code": "# Python3 implementation of the approach # Function to return the maximum candies# that can be boughtdef maxCandies(arr, n) : # Buy all the candies of the last type prevBought = arr[n - 1]; candies = prevBought; # Starting from second last for i in range(n - 2, -1, -1) : # Amount of candies of the current # type that can be bought x = min(prevBought - 1, arr[i]); if (x >= 0) : # Add candies of current type # that can be bought candies += x; # Update the previous bought amount prevBought = x; return candies; # Driver codeif __name__ == \"__main__\" : arr = [ 1, 2, 1, 3, 6 ]; n = len(arr) print(maxCandies(arr, n)); # This code is contributed by Ryuga",
"e": 30064,
"s": 29236,
"text": null
},
{
"code": "// C# implementation of the approachusing System; class GFG{ // Function to return the maximum candies// that can be boughtstatic int maxCandies(int[] arr, int n){ // Buy all the candies of the last type int prevBought = arr[n - 1]; int candies = prevBought; // Starting from second last for (int i = n - 2; i >= 0; i--) { // Amount of candies of the current // type that can be bought int x = Math.Min(prevBought - 1, arr[i]); if (x >= 0) { // Add candies of current type // that can be bought candies += x; // Update the previous bought amount prevBought = x; } } return candies;} // Driver codepublic static void Main(){ int[] arr= { 1, 2, 1, 3, 6 }; int n = arr.Length; Console.WriteLine(maxCandies(arr, n));}} // This code is contributed by Code_Mech.",
"e": 30962,
"s": 30064,
"text": null
},
{
"code": "<?php// PHP implementation of the approach // Function to return the maximum candies// that can be boughtfunction maxCandies($arr, $n){ // Buy all the candies of the last type $prevBought = $arr[$n - 1]; $candies = $prevBought; // Starting from second last for ($i = $n - 2; $i >= 0; $i--) { // Amount of candies of the current // type that can be bought $x = min($prevBought - 1, $arr[$i]); if ($x >= 0) { // Add candies of current type // that can be bought $candies += $x; // Update the previous bought amount $prevBought = $x; } } return $candies;} // Driver code$arr = array(1, 2, 1, 3, 6 );$n = sizeof($arr);echo(maxCandies($arr, $n)); // This code is contributed by Code_Mech.?>",
"e": 31776,
"s": 30962,
"text": null
},
{
"code": "<script> // Javascript implementation of the approach // Function to return the maximum candies// that can be boughtfunction maxCandies(arr, n){ // Buy all the candies of the last type let prevBought = arr[n - 1]; let candies = prevBought; // Starting from second last for (let i = n - 2; i >= 0; i--) { // Amount of candies of the current // type that can be bought let x = Math.min(prevBought - 1, arr[i]); if (x >= 0) { // Add candies of current type // that can be bought candies += x; // Update the previous bought amount prevBought = x; } } return candies;} // Driver Code let arr = [ 1, 2, 1, 3, 6 ]; let n = arr.length; document.write(maxCandies(arr, n)); </script>",
"e": 32621,
"s": 31776,
"text": null
},
{
"code": null,
"e": 32624,
"s": 32621,
"text": "10"
},
{
"code": null,
"e": 32634,
"s": 32626,
"text": "ankthon"
},
{
"code": null,
"e": 32644,
"s": 32634,
"text": "Code_Mech"
},
{
"code": null,
"e": 32653,
"s": 32644,
"text": "target_2"
},
{
"code": null,
"e": 32677,
"s": 32653,
"text": "Constructive Algorithms"
},
{
"code": null,
"e": 32684,
"s": 32677,
"text": "Arrays"
},
{
"code": null,
"e": 32708,
"s": 32684,
"text": "Competitive Programming"
},
{
"code": null,
"e": 32715,
"s": 32708,
"text": "Greedy"
},
{
"code": null,
"e": 32728,
"s": 32715,
"text": "Mathematical"
},
{
"code": null,
"e": 32735,
"s": 32728,
"text": "Arrays"
},
{
"code": null,
"e": 32742,
"s": 32735,
"text": "Greedy"
},
{
"code": null,
"e": 32755,
"s": 32742,
"text": "Mathematical"
},
{
"code": null,
"e": 32853,
"s": 32755,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 32921,
"s": 32853,
"text": "Maximum and minimum of an array using minimum number of comparisons"
},
{
"code": null,
"e": 32965,
"s": 32921,
"text": "Top 50 Array Coding Problems for Interviews"
},
{
"code": null,
"e": 33013,
"s": 32965,
"text": "Stack Data Structure (Introduction and Program)"
},
{
"code": null,
"e": 33036,
"s": 33013,
"text": "Introduction to Arrays"
},
{
"code": null,
"e": 33068,
"s": 33036,
"text": "Multidimensional Arrays in Java"
},
{
"code": null,
"e": 33111,
"s": 33068,
"text": "Competitive Programming - A Complete Guide"
},
{
"code": null,
"e": 33154,
"s": 33111,
"text": "Practice for cracking any coding interview"
},
{
"code": null,
"e": 33195,
"s": 33154,
"text": "Arrow operator -> in C/C++ with Examples"
},
{
"code": null,
"e": 33273,
"s": 33195,
"text": "Prefix Sum Array - Implementation and Applications in Competitive Programming"
}
] |
Transmission Modes in Computer Networks (Simplex, Half-Duplex and Full-Duplex) - GeeksforGeeks | 10 Mar, 2022
Transmission mode means transferring data between two devices. It is also known as a communication mode. Buses and networks are designed to allow communication to occur between individual devices that are interconnected. There are three types of transmission mode:-
These are explained as following below.
1. Simplex Mode –In Simplex mode, the communication is unidirectional, as on a one-way street. Only one of the two devices on a link can transmit, the other can only receive. The simplex mode can use the entire capacity of the channel to send data in one direction. Example: Keyboard and traditional monitors. The keyboard can only introduce input, the monitor can only give the output.
2. Half-Duplex Mode –In half-duplex mode, each station can both transmit and receive, but not at the same time. When one device is sending, the other can only receive, and vice versa. The half-duplex mode is used in cases where there is no need for communication in both directions at the same time. The entire capacity of the channel can be utilized for each direction. Example: Walkie-talkie in which message is sent one at a time and messages are sent in both directions.
Channel capacity=Bandwidth * Propagation Delay
3. Full-Duplex Mode –In full-duplex mode, both stations can transmit and receive simultaneously. In full_duplex mode, signals going in one direction share the capacity of the link with signals going in another direction, this sharing can occur in two ways:
Either the link must contain two physically separate transmission paths, one for sending and the other for receiving.
Or the capacity is divided between signals traveling in both directions.
Full-duplex mode is used when communication in both directions is required all the time. The capacity of the channel, however, must be divided between the two directions. Example: Telephone Network in which there is communication between two persons by a telephone line, through which both can talk and listen at the same time.
Channel Capacity=2* Bandwidth*propagation Delay
References- Data Communication and Network,5th Edition, Behrouz A.Forouzan.
This article is contributed by Saloni Gupta. 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.
yeeshaj
Pushpender007
vaibhavsinghtanwar
Computer Networks
Computer Networks
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Differences between IPv4 and IPv6
Socket Programming in Python
Caesar Cipher in Cryptography
UDP Server-Client implementation in C
Socket Programming in Java
Advanced Encryption Standard (AES)
Intrusion Detection System (IDS)
Secure Socket Layer (SSL)
Cryptography and its Types
Wireless Sensor Network (WSN) | [
{
"code": null,
"e": 37948,
"s": 37920,
"text": "\n10 Mar, 2022"
},
{
"code": null,
"e": 38217,
"s": 37948,
"text": "Transmission mode means transferring data between two devices. It is also known as a communication mode. Buses and networks are designed to allow communication to occur between individual devices that are interconnected. There are three types of transmission mode:- "
},
{
"code": null,
"e": 38259,
"s": 38219,
"text": "These are explained as following below."
},
{
"code": null,
"e": 38647,
"s": 38259,
"text": "1. Simplex Mode –In Simplex mode, the communication is unidirectional, as on a one-way street. Only one of the two devices on a link can transmit, the other can only receive. The simplex mode can use the entire capacity of the channel to send data in one direction. Example: Keyboard and traditional monitors. The keyboard can only introduce input, the monitor can only give the output. "
},
{
"code": null,
"e": 39125,
"s": 38649,
"text": "2. Half-Duplex Mode –In half-duplex mode, each station can both transmit and receive, but not at the same time. When one device is sending, the other can only receive, and vice versa. The half-duplex mode is used in cases where there is no need for communication in both directions at the same time. The entire capacity of the channel can be utilized for each direction. Example: Walkie-talkie in which message is sent one at a time and messages are sent in both directions. "
},
{
"code": null,
"e": 39172,
"s": 39125,
"text": "Channel capacity=Bandwidth * Propagation Delay"
},
{
"code": null,
"e": 39430,
"s": 39172,
"text": "3. Full-Duplex Mode –In full-duplex mode, both stations can transmit and receive simultaneously. In full_duplex mode, signals going in one direction share the capacity of the link with signals going in another direction, this sharing can occur in two ways: "
},
{
"code": null,
"e": 39548,
"s": 39430,
"text": "Either the link must contain two physically separate transmission paths, one for sending and the other for receiving."
},
{
"code": null,
"e": 39623,
"s": 39548,
"text": "Or the capacity is divided between signals traveling in both directions. "
},
{
"code": null,
"e": 39952,
"s": 39623,
"text": "Full-duplex mode is used when communication in both directions is required all the time. The capacity of the channel, however, must be divided between the two directions. Example: Telephone Network in which there is communication between two persons by a telephone line, through which both can talk and listen at the same time. "
},
{
"code": null,
"e": 40000,
"s": 39952,
"text": "Channel Capacity=2* Bandwidth*propagation Delay"
},
{
"code": null,
"e": 40077,
"s": 40000,
"text": "References- Data Communication and Network,5th Edition, Behrouz A.Forouzan. "
},
{
"code": null,
"e": 40374,
"s": 40077,
"text": "This article is contributed by Saloni Gupta. 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": 40499,
"s": 40374,
"text": "Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above."
},
{
"code": null,
"e": 40507,
"s": 40499,
"text": "yeeshaj"
},
{
"code": null,
"e": 40521,
"s": 40507,
"text": "Pushpender007"
},
{
"code": null,
"e": 40540,
"s": 40521,
"text": "vaibhavsinghtanwar"
},
{
"code": null,
"e": 40558,
"s": 40540,
"text": "Computer Networks"
},
{
"code": null,
"e": 40576,
"s": 40558,
"text": "Computer Networks"
},
{
"code": null,
"e": 40674,
"s": 40576,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 40708,
"s": 40674,
"text": "Differences between IPv4 and IPv6"
},
{
"code": null,
"e": 40737,
"s": 40708,
"text": "Socket Programming in Python"
},
{
"code": null,
"e": 40767,
"s": 40737,
"text": "Caesar Cipher in Cryptography"
},
{
"code": null,
"e": 40805,
"s": 40767,
"text": "UDP Server-Client implementation in C"
},
{
"code": null,
"e": 40832,
"s": 40805,
"text": "Socket Programming in Java"
},
{
"code": null,
"e": 40867,
"s": 40832,
"text": "Advanced Encryption Standard (AES)"
},
{
"code": null,
"e": 40900,
"s": 40867,
"text": "Intrusion Detection System (IDS)"
},
{
"code": null,
"e": 40926,
"s": 40900,
"text": "Secure Socket Layer (SSL)"
},
{
"code": null,
"e": 40953,
"s": 40926,
"text": "Cryptography and its Types"
}
] |
Rotate a matrix by 90 degree without using any extra space | Set 2 - GeeksforGeeks | 12 May, 2022
Given a square matrix, turn it by 90 degrees in anti-clockwise direction without using any extra space.
Examples:
Input:
1 2 3
4 5 6
7 8 9
Output:
3 6 9
2 5 8
1 4 7
Rotated the input matrix by
90 degrees in anti-clockwise direction.
Input:
1 2 3 4
5 6 7 8
9 10 11 12
13 14 15 16
Output:
4 8 12 16
3 7 11 15
2 6 10 14
1 5 9 13
Rotated the input matrix by
90 degrees in anti-clockwise direction.
An approach that requires extra space is already discussed in a different article: Inplace rotate square matrix by 90 degrees | Set 1
This post discusses the same problem with a different approach which is space-optimized.Approach: The idea is to find the transpose of the matrix and then reverse the columns of the transposed matrix. Here is an example to show how this works.
Algorithm:
To solve the given problem there are two tasks. 1st is finding the transpose and second is reversing the columns without using extra spaceA transpose of a matrix is when the matrix is flipped over its diagonal, i.e the row index of an element becomes the column index and vice versa. So to find the transpose interchange the elements at position (i, j) with (j, i). Run two loops, the outer loop from 0 to row count and inner loop from 0 to index of the outer loop.To reverse the column of the transposed matrix, run two nested loops, the outer loop from 0 to column count and inner loop from 0 to row count/2, interchange elements at (i, j) with (i, row[count-1-j]), where i and j are indices of inner and outer loop respectively.
To solve the given problem there are two tasks. 1st is finding the transpose and second is reversing the columns without using extra space
A transpose of a matrix is when the matrix is flipped over its diagonal, i.e the row index of an element becomes the column index and vice versa. So to find the transpose interchange the elements at position (i, j) with (j, i). Run two loops, the outer loop from 0 to row count and inner loop from 0 to index of the outer loop.
To reverse the column of the transposed matrix, run two nested loops, the outer loop from 0 to column count and inner loop from 0 to row count/2, interchange elements at (i, j) with (i, row[count-1-j]), where i and j are indices of inner and outer loop respectively.
C++
Java
C#
Python3
PHP
Javascript
// C++ program for left// rotation of matrix by 90 degree// without using extra space#include <bits/stdc++.h>using namespace std;#define R 4#define C 4 // After transpose we swap// elements of column// one by one for finding left// rotation of matrix// by 90 degreevoid reverseColumns(int arr[R][C]){ for (int i = 0; i < C; i++) for (int j = 0, k = C - 1; j < k; j++, k--) swap(arr[j][i], arr[k][i]);} // Function for do transpose of matrixvoid transpose(int arr[R][C]){ for (int i = 0; i < R; i++) for (int j = i; j < C; j++) swap(arr[i][j], arr[j][i]);} // Function for print matrixvoid printMatrix(int arr[R][C]){ for (int i = 0; i < R; i++) { for (int j = 0; j < C; j++) cout << arr[i][j] << " "; cout << '\n'; }} // Function to anticlockwise// rotate matrix by 90 degreevoid rotate90(int arr[R][C]){ transpose(arr); reverseColumns(arr);} // Driven codeint main(){ int arr[R][C] = { { 1, 2, 3, 4 }, { 5, 6, 7, 8 }, { 9, 10, 11, 12 }, { 13, 14, 15, 16 } }; rotate90(arr); printMatrix(arr); return 0;}
// JAVA Code for left Rotation of a// matrix by 90 degree without using// any extra spaceimport java.util.*; class GFG { // After transpose we swap elements of // column one by one for finding left // rotation of matrix by 90 degree static void reverseColumns(int arr[][]) { for (int i = 0; i < arr[0].length; i++) for (int j = 0, k = arr[0].length - 1; j < k; j++, k--) { int temp = arr[j][i]; arr[j][i] = arr[k][i]; arr[k][i] = temp; } } // Function for do transpose of matrix static void transpose(int arr[][]) { for (int i = 0; i < arr.length; i++) for (int j = i; j < arr[0].length; j++) { int temp = arr[j][i]; arr[j][i] = arr[i][j]; arr[i][j] = temp; } } // Function for print matrix static void printMatrix(int arr[][]) { for (int i = 0; i < arr.length; i++) { for (int j = 0; j < arr[0].length; j++) System.out.print(arr[i][j] + " "); System.out.println(""); } } // Function to anticlockwise rotate // matrix by 90 degree static void rotate90(int arr[][]) { transpose(arr); reverseColumns(arr); } /* Driver program to test above function */ public static void main(String[] args) { int arr[][] = { { 1, 2, 3, 4 }, { 5, 6, 7, 8 }, { 9, 10, 11, 12 }, { 13, 14, 15, 16 } }; rotate90(arr); printMatrix(arr); }} // This code is contributed by Arnav Kr. Mandal.
// C# program for left rotation// of matrix by 90 degree// without using extra spaceusing System; class GFG { static int R = 4; static int C = 4; // After transpose we swap // elements of column one // by one for finding left // rotation of matrix by // 90 degree static void reverseColumns(int[, ] arr) { for (int i = 0; i < C; i++) for (int j = 0, k = C - 1; j < k; j++, k--) { int temp = arr[j, i]; arr[j, i] = arr[k, i]; arr[k, i] = temp; } } // Function for do // transpose of matrix static void transpose(int[, ] arr) { for (int i = 0; i < R; i++) for (int j = i; j < C; j++) { int temp = arr[j, i]; arr[j, i] = arr[i, j]; arr[i, j] = temp; } } // Function for print matrix static void printMatrix(int[, ] arr) { for (int i = 0; i < R; i++) { for (int j = 0; j < C; j++) Console.Write(arr[i, j] + " "); Console.WriteLine(""); } } // Function to anticlockwise // rotate matrix by 90 degree static void rotate90(int[, ] arr) { transpose(arr); reverseColumns(arr); } // Driver code static void Main() { int[, ] arr = { { 1, 2, 3, 4 }, { 5, 6, 7, 8 }, { 9, 10, 11, 12 }, { 13, 14, 15, 16 } }; rotate90(arr); printMatrix(arr); } // This code is contributed // by Sam007}
# Python 3 program for left rotation of matrix by 90# degree without using extra space R = 4C = 4 # After transpose we swap elements of column# one by one for finding left rotation of matrix# by 90 degree def reverseColumns(arr): for i in range(C): j = 0 k = C-1 while j < k: t = arr[j][i] arr[j][i] = arr[k][i] arr[k][i] = t j += 1 k -= 1 # Function for do transpose of matrix def transpose(arr): for i in range(R): for j in range(i, C): t = arr[i][j] arr[i][j] = arr[j][i] arr[j][i] = t # Function for print matrix def printMatrix(arr): for i in range(R): for j in range(C): print(str(arr[i][j]), end=" ") print() # Function to anticlockwise rotate matrix# by 90 degree def rotate90(arr): transpose(arr) reverseColumns(arr) # Driven codearr = [[1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12], [13, 14, 15, 16] ]rotate90(arr)printMatrix(arr)
<?php// PHP program for left rotation of matrix by 90 $R = 4;$C = 4;// Function to rotate the matrix by 90 degreefunction reverseColumns(&$arr){ global $C; for ($i = 0; $i < $C; $i++) { for ($j = 0, $k = $C - 1; $j < $k; $j++, $k--) { $t = $arr[$j][$i]; $arr[$j][$i] = $arr[$k][$i]; $arr[$k][$i] = $t; } } } // Function for transpose of matrixfunction transpose(&$arr){ global $R, $C; for ($i = 0; $i < $R; $i++) { for ($j = $i; $j < $C; $j++) { $t = $arr[$i][$j]; $arr[$i][$j] = $arr[$j][$i]; $arr[$j][$i] = $t; } }} // Function for display the matrixfunction printMatrix(&$arr){ global $R, $C; for ($i = 0; $i < $R; $i++) { for ($j = 0; $j < $C; $j++) echo $arr[$i][$j]." "; echo "\n"; }} // Function to anticlockwise rotate matrix// by 90 degreefunction rotate90(&$arr){ transpose($arr); reverseColumns($arr);} // Driven code $arr = array( array( 1, 2, 3, 4 ), array( 5, 6, 7, 8 ), array( 9, 10, 11, 12 ), array( 13, 14, 15, 16 ) );rotate90($arr);printMatrix($arr);return 0;?>
<script> // JAVASCRIPT Code for left Rotation of a// matrix by 90 degree without using// any extra space // After transpose we swap elements of // column one by one for finding left // rotation of matrix by 90 degree function reverseColumns(arr) { for (let i = 0; i < arr[0].length; i++) for (let j = 0, k = arr[0].length - 1; j < k; j++, k--) { let temp = arr[j][i]; arr[j][i] = arr[k][i]; arr[k][i] = temp; } } // Function for do transpose of matrix function transpose(arr) { for (let i = 0; i < arr.length; i++) for (let j = i; j < arr[0].length; j++) { let temp = arr[j][i]; arr[j][i] = arr[i][j]; arr[i][j] = temp; } } // Function for print matrix function printMatrix(arr) { for (let i = 0; i < arr.length; i++) { for (let j = 0; j < arr[0].length; j++) document.write(arr[i][j] + " "); document.write("<br>"); } } // Function to anticlockwise rotate // matrix by 90 degree function rotate90(arr) { transpose(arr); reverseColumns(arr); } /* Driver program to test above function */ let arr = [[1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12], [13, 14, 15, 16] ]; rotate90(arr) printMatrix(arr) // This code is contributed by rag2127 </script>
4 8 12 16
3 7 11 15
2 6 10 14
1 5 9 13
Complexity Analysis:
Time complexity :O(R*C). The matrix is traversed twice, so the complexity is O(R*C).
Space complexity :O(1). The space complexity is constant as no extra space is required.
Another Approach using a single traversal of the matrix :
The idea is to traverse along the boundaries of the matrix and shift the positions of the elements in 900 anticlockwise directions in each boundary. There are such (n/2-1) boundaries in the matrix.
Algorithm:
Iterate over all the boundaries in the matrix. There are total (n/2-1) boundariesFor each boundary take the 4 corner elements and swap them such that the 4 corner elements get rotated in anticlockwise directions. Then take the next 4 elements along the edges(left, right, top, bottom) and swap them in an anticlockwise direction. Continue as long as all the elements in that particular boundary get rotated in 900 anticlockwise directions.Then move on to the next inner boundary and continue the process as long the whole matrix is rotated in 900 anticlockwise direction.
Iterate over all the boundaries in the matrix. There are total (n/2-1) boundaries
For each boundary take the 4 corner elements and swap them such that the 4 corner elements get rotated in anticlockwise directions. Then take the next 4 elements along the edges(left, right, top, bottom) and swap them in an anticlockwise direction. Continue as long as all the elements in that particular boundary get rotated in 900 anticlockwise directions.
Then move on to the next inner boundary and continue the process as long the whole matrix is rotated in 900 anticlockwise direction.
Original array
total n/2-1 boundaries
for outermost boundary
for next inner boundary
C++14
Java
Python3
C#
Javascript
// C++ program for left rotation of matrix// by 90 degree without using extra space#include <bits/stdc++.h>using namespace std;#define R 4#define C 4 // Function to rotate matrix anticlockwise by 90 degrees.void rotateby90(int arr[R][C]){ int n = R; // n=size of the square matrix int a = 0, b = 0, c = 0, d = 0; // iterate over all the boundaries of the matrix for (int i = 0; i <= n / 2 - 1; i++) { // for each boundary, keep on taking 4 elements (one // each along the 4 edges) and swap them in // anticlockwise manner for (int j = 0; j <= n - 2 * i - 2; j++) { a = arr[i + j][i]; b = arr[n - 1 - i][i + j]; c = arr[n - 1 - i - j][n - 1 - i]; d = arr[i][n - 1 - i - j]; arr[i + j][i] = d; arr[n - 1 - i][i + j] = a; arr[n - 1 - i - j][n - 1 - i] = b; arr[i][n - 1 - i - j] = c; } }} // Function for print matrixvoid printMatrix(int arr[R][C]){ for (int i = 0; i < R; i++) { for (int j = 0; j < C; j++) cout << arr[i][j] << " "; cout << '\n'; }} // Driven codeint main(){ int arr[R][C] = { { 1, 2, 3, 4 }, { 5, 6, 7, 8 }, { 9, 10, 11, 12 }, { 13, 14, 15, 16 } }; rotateby90(arr); printMatrix(arr); return 0;} // This code is contributed by Md. Enjamum// Hossain(enja_2001)
// JAVA Code for left Rotation of a matrix// by 90 degree without using any extra spaceimport java.util.*; class GFG { // Function to rotate matrix anticlockwise by 90 // degrees. static void rotateby90(int arr[][]) { int n = arr.length; int a = 0, b = 0, c = 0, d = 0; // iterate over all the boundaries of the matrix for (int i = 0; i <= n / 2 - 1; i++) { // for each boundary, keep on taking 4 elements // (one each along the 4 edges) and swap them in // anticlockwise manner for (int j = 0; j <= n - 2 * i - 2; j++) { a = arr[i + j][i]; b = arr[n - 1 - i][i + j]; c = arr[n - 1 - i - j][n - 1 - i]; d = arr[i][n - 1 - i - j]; arr[i + j][i] = d; arr[n - 1 - i][i + j] = a; arr[n - 1 - i - j][n - 1 - i] = b; arr[i][n - 1 - i - j] = c; } } } // Function for print matrix static void printMatrix(int arr[][]) { for (int i = 0; i < arr.length; i++) { for (int j = 0; j < arr[0].length; j++) System.out.print(arr[i][j] + " "); System.out.println(""); } } /* Driver program to test above function */ public static void main(String[] args) { int arr[][] = { { 1, 2, 3, 4 }, { 5, 6, 7, 8 }, { 9, 10, 11, 12 }, { 13, 14, 15, 16 } }; rotateby90(arr); printMatrix(arr); }} // This code is contributed by Md. Enjamum// Hossain(enja_2001)
# Function to rotate matrix anticlockwise by 90 degrees.def rotateby90(arr): n = len(arr) a,b,c,d = 0,0,0,0 # iterate over all the boundaries of the matrix for i in range(n // 2): # for each boundary, keep on taking 4 elements # (one each along the 4 edges) and swap them in # anticlockwise manner for j in range(n - 2 * i - 1): a = arr[i + j][i] b = arr[n - 1 - i][i + j] c = arr[n - 1 - i - j][n - 1 - i] d = arr[i][n - 1 - i - j] arr[i + j][i] = d arr[n - 1 - i][i + j] = a arr[n - 1 - i - j][n - 1 - i] = b arr[i][n - 1 - i - j] = c # Function for print matrixdef printMatrix(arr): for i in range(len(arr)): for j in range(len(arr[0])): print(arr[i][j] ,end = " ") print() # Driver program to test above functionarr=[[ 1, 2, 3, 4 ], [ 5, 6, 7, 8 ], [ 9, 10, 11, 12 ], [ 13, 14, 15, 16 ]]rotateby90(arr)printMatrix(arr) # this code is contributed by shinjanpatra
// C# Code for left Rotation of a matrix// by 90 degree without using any extra spaceusing System;using System.Collections.Generic; public class GFG { // Function to rotate matrix anticlockwise by 90 // degrees. static void rotateby90(int [,]arr) { int n = arr.GetLength(0); int a = 0, b = 0, c = 0, d = 0; // iterate over all the boundaries of the matrix for (int i = 0; i <= n / 2 - 1; i++) { // for each boundary, keep on taking 4 elements // (one each along the 4 edges) and swap them in // anticlockwise manner for (int j = 0; j <= n - 2 * i - 2; j++) { a = arr[i + j,i]; b = arr[n - 1 - i,i + j]; c = arr[n - 1 - i - j,n - 1 - i]; d = arr[i,n - 1 - i - j]; arr[i + j,i] = d; arr[n - 1 - i,i + j] = a; arr[n - 1 - i - j,n - 1 - i] = b; arr[i,n - 1 - i - j] = c; } } } // Function for print matrix static void printMatrix(int [,]arr) { for (int i = 0; i < arr.GetLength(0); i++) { for (int j = 0; j < arr.GetLength(1); j++) Console.Write(arr[i,j] + " "); Console.WriteLine(""); } } /* Driver program to test above function */ public static void Main(String[] args) { int [,]arr = { { 1, 2, 3, 4 }, { 5, 6, 7, 8 }, { 9, 10, 11, 12 }, { 13, 14, 15, 16 } }; rotateby90(arr); printMatrix(arr); }} // This code is contributed by umadevi9616
<script> // JavaScript Code for left Rotation of a matrix// by 90 degree without using any extra space // Function to rotate matrix anticlockwise by 90 // degrees.function rotateby90(arr){ let n = arr.length; let a = 0, b = 0, c = 0, d = 0; // iterate over all the boundaries of the matrix for (let i = 0; i <= n / 2 - 1; i++) { // for each boundary, keep on taking 4 elements // (one each along the 4 edges) and swap them in // anticlockwise manner for (let j = 0; j <= n - 2 * i - 2; j++) { a = arr[i + j][i]; b = arr[n - 1 - i][i + j]; c = arr[n - 1 - i - j][n - 1 - i]; d = arr[i][n - 1 - i - j]; arr[i + j][i] = d; arr[n - 1 - i][i + j] = a; arr[n - 1 - i - j][n - 1 - i] = b; arr[i][n - 1 - i - j] = c; } }} // Function for print matrixfunction printMatrix(arr){ for (let i = 0; i < arr.length; i++) { for (let j = 0; j < arr[0].length; j++) document.write(arr[i][j] + " "); document.write("<br>"); }} /* Driver program to test above function */let arr=[[ 1, 2, 3, 4 ], [ 5, 6, 7, 8 ], [ 9, 10, 11, 12 ], [ 13, 14, 15, 16 ]];rotateby90(arr);printMatrix(arr); // This code is contributed by avanitrachhadiya2155 </script>
4 8 12 16
3 7 11 15
2 6 10 14
1 5 9 13
Complexity Analysis:
Time complexity :O(R*C). The matrix is traversed only once, so the time complexity is O(R*C).
Space complexity :O(1). The space complexity is O(1) as no extra space is required.
Implementation: Let’s see a method of Python numpy that can be used to arrive at the particular solution.
Python3
# Alternative implementation using numpyimport numpy # Driven codearr = [[1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12], [13, 14, 15, 16] ] # Define flip algorithm (Note numpy.flip is a builtin f# function for versions > v.1.12.0) def flip(m, axis): if not hasattr(m, 'ndim'): m = asarray(m) indexer = [slice(None)] * m.ndim try: indexer[axis] = slice(None, None, -1) except IndexError: raise ValueError("axis =% i is invalid for the % i-dimensional input array" % (axis, m.ndim)) return m[tuple(indexer)] # Transpose the matrixtrans = numpy.transpose(arr) # Flip the matrix anti-clockwise (1 for clockwise)flipmat = flip(trans, 0) print("\nnumpy implementation\n")print(flipmat)
Output:
numpy implementation
[[ 4 8 12 16]
[ 3 7 11 15]
[ 2 6 10 14]
[ 1 5 9 13]]
Note: The above steps/programs do left (or anticlockwise) rotation. Let’s see how to do the right rotation or clockwise rotation. The approach would be similar. Find the transpose of the matrix and then reverse the rows of the transposed matrix. This is how it is done.
This article is contributed by DANISH_RAZA . If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to [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.
Rotating Along the Boundaries
We can start at the first 4 corners of the given matrix and then keep incrementing the row and column indices to moves around.
At any given moment we will have four corners lu (left-up),ld(left-down),ru(right-up),rd(right-down).
To left rotate we will first swap the ru and ld, then lu and ld and lastly ru and rd.
C++
Java
C#
Javascript
#include <bits/stdc++.h>using namespace std; //Function to rotate matrix anticlockwise by 90 degrees.void rotateby90(vector<vector<int> >& matrix){ int n=matrix.size(); int mid; if(n%2==0) mid=n/2-1; else mid=n/2; for(int i=0,j=n-1;i<=mid;i++,j--) { for(int k=0;k<j-i;k++) { swap(matrix[i][j-k],matrix[j][i+k]); //ru ld swap(matrix[i+k][i],matrix[j][i+k]); //lu ld swap(matrix[i][j-k],matrix[j-k][j]); //ru rd } } } void printMatrix(vector<vector<int>>& arr){ int n=arr.size(); for(int i=0;i<n;i++) { for(int j=0;j<n;j++) { cout<<arr[i][j]<<" "; } cout<<endl; }}int main() { vector<vector<int>> arr = { { 1, 2, 3, 4 }, { 5, 6, 7, 8 }, { 9, 10, 11, 12 }, { 13, 14, 15, 16 } }; rotateby90(arr); printMatrix(arr); return 0;}
import java.util.*; class GFG{ private static int[][] swap(int[][] matrix, int x1,int x2,int y1, int y2) { int temp = matrix[x1][x2] ; matrix[x1][x2] = matrix[y1][y2]; matrix[y1][y2] = temp; return matrix; } //Function to rotate matrix anticlockwise by 90 degrees.static int[][] rotateby90(int[][] matrix){ int n=matrix.length; int mid; if(n % 2 == 0) mid = n / 2 - 1; else mid = n / 2; for(int i = 0, j = n - 1; i <= mid; i++, j--) { for(int k = 0; k < j - i; k++) { matrix= swap(matrix, i, j - k, j, i + k); //ru ld matrix= swap(matrix, i + k, i, j, i + k); //lu ld matrix= swap(matrix, i, j - k, j - k, j); //ru rd } } return matrix;} static void printMatrix(int[][] arr){ int n = arr.length; for(int i = 0; i < n; i++) { for(int j = 0; j < n; j++) { System.out.print(arr[i][j] + " "); } System.out.println(); }}public static void main(String[] args) { int[][] arr = { { 1, 2, 3, 4 }, { 5, 6, 7, 8 }, { 9, 10, 11, 12 }, { 13, 14, 15, 16 } }; arr = rotateby90(arr); printMatrix(arr);}} // This code is contributed by umadevi9616
using System; public class GFG{ private static int[,] swap(int[,] matrix, int x1,int x2,int y1, int y2) { int temp = matrix[x1,x2] ; matrix[x1,x2] = matrix[y1,y2]; matrix[y1,y2] = temp; return matrix; } //Function to rotate matrix anticlockwise by 90 degrees.static int[,] rotateby90(int[,] matrix){ int n=matrix.GetLength(0); int mid; if(n % 2 == 0) mid = (n / 2 - 1); else mid = (n / 2); for(int i = 0, j = n - 1; i <= mid; i++, j--) { for(int k = 0; k < j - i; k++) { matrix= swap(matrix, i, j - k, j, i + k); //ru ld matrix= swap(matrix, i + k, i, j, i + k); //lu ld matrix= swap(matrix, i, j - k, j - k, j); //ru rd } } return matrix;} static void printMatrix(int[,] arr){ int n = arr.GetLength(0); for(int i = 0; i < n; i++) { for(int j = 0; j < n; j++) { Console.Write(arr[i,j] + " "); } Console.WriteLine(); }}public static void Main(String[] args) { int[,] arr = { { 1, 2, 3, 4 }, { 5, 6, 7, 8 }, { 9, 10, 11, 12 }, { 13, 14, 15, 16 } }; arr = rotateby90(arr); printMatrix(arr);}} // This code is contributed by Rajput-Ji
<script> function swap(matrix , x1 , x2 , y1 , y2) { var temp = matrix[x1][x2]; matrix[x1][x2] = matrix[y1][y2]; matrix[y1][y2] = temp; return matrix; } // Function to rotate matrix anticlockwise by 90 degrees. function rotateby90(matrix) { var n = matrix.length; var mid; if (n % 2 == 0) mid = n / 2 - 1; else mid = n / 2; for (i = 0, j = n - 1; i <= mid; i++, j--) { for (k = 0; k < j - i; k++) { matrix = swap(matrix, i, j - k, j, i + k); // ru ld matrix = swap(matrix, i + k, i, j, i + k); // lu ld matrix = swap(matrix, i, j - k, j - k, j); // ru rd } } return matrix; } function printMatrix(arr) { var n = arr.length; for (i = 0; i < n; i++) { for (j = 0; j < n; j++) { document.write(arr[i][j] + " "); } document.write("<br/>"); } } var arr = [ [ 1, 2, 3, 4 ], [ 5, 6, 7, 8 ], [ 9, 10, 11, 12 ], [ 13, 14, 15, 16 ] ]; arr = rotateby90(arr); printMatrix(arr); // This code is contributed by Rajput-Ji</script>
Output:
4 8 12 16
3 7 11 15
2 6 10 14
1 5 9 13
Time Complexity: O(n^2)
Space Complexity : O(1)
Sam007
ukasp
bpgreyling
andrew1234
rag2127
enja_2001
avanitrachhadiya2155
anikakapoor
piyushbisht3
umadevi9616
surindertarika1234
Rajput-Ji
shinjanpatra
rotation
Matrix
Matrix
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Matrix Chain Multiplication | DP-8
Program to find largest element in an array
Print a given matrix in spiral form
Rat in a Maze | Backtracking-2
Maximum size square sub-matrix with all 1s
Sudoku | Backtracking-7
Find the number of islands | Set 1 (Using DFS)
Divide and Conquer | Set 5 (Strassen's Matrix Multiplication)
Count all possible paths from top left to bottom right of a mXn matrix
Maximum size rectangle binary sub-matrix with all 1s | [
{
"code": null,
"e": 39005,
"s": 38977,
"text": "\n12 May, 2022"
},
{
"code": null,
"e": 39109,
"s": 39005,
"text": "Given a square matrix, turn it by 90 degrees in anti-clockwise direction without using any extra space."
},
{
"code": null,
"e": 39120,
"s": 39109,
"text": "Examples: "
},
{
"code": null,
"e": 39447,
"s": 39120,
"text": "Input:\n 1 2 3\n 4 5 6\n 7 8 9\nOutput:\n 3 6 9 \n 2 5 8 \n 1 4 7 \nRotated the input matrix by\n90 degrees in anti-clockwise direction.\n\nInput:\n 1 2 3 4 \n 5 6 7 8 \n 9 10 11 12 \n13 14 15 16 \nOutput:\n 4 8 12 16 \n 3 7 11 15 \n 2 6 10 14 \n 1 5 9 13\nRotated the input matrix by\n90 degrees in anti-clockwise direction."
},
{
"code": null,
"e": 39581,
"s": 39447,
"text": "An approach that requires extra space is already discussed in a different article: Inplace rotate square matrix by 90 degrees | Set 1"
},
{
"code": null,
"e": 39826,
"s": 39581,
"text": "This post discusses the same problem with a different approach which is space-optimized.Approach: The idea is to find the transpose of the matrix and then reverse the columns of the transposed matrix. Here is an example to show how this works. "
},
{
"code": null,
"e": 39839,
"s": 39826,
"text": "Algorithm: "
},
{
"code": null,
"e": 40571,
"s": 39839,
"text": "To solve the given problem there are two tasks. 1st is finding the transpose and second is reversing the columns without using extra spaceA transpose of a matrix is when the matrix is flipped over its diagonal, i.e the row index of an element becomes the column index and vice versa. So to find the transpose interchange the elements at position (i, j) with (j, i). Run two loops, the outer loop from 0 to row count and inner loop from 0 to index of the outer loop.To reverse the column of the transposed matrix, run two nested loops, the outer loop from 0 to column count and inner loop from 0 to row count/2, interchange elements at (i, j) with (i, row[count-1-j]), where i and j are indices of inner and outer loop respectively."
},
{
"code": null,
"e": 40710,
"s": 40571,
"text": "To solve the given problem there are two tasks. 1st is finding the transpose and second is reversing the columns without using extra space"
},
{
"code": null,
"e": 41038,
"s": 40710,
"text": "A transpose of a matrix is when the matrix is flipped over its diagonal, i.e the row index of an element becomes the column index and vice versa. So to find the transpose interchange the elements at position (i, j) with (j, i). Run two loops, the outer loop from 0 to row count and inner loop from 0 to index of the outer loop."
},
{
"code": null,
"e": 41305,
"s": 41038,
"text": "To reverse the column of the transposed matrix, run two nested loops, the outer loop from 0 to column count and inner loop from 0 to row count/2, interchange elements at (i, j) with (i, row[count-1-j]), where i and j are indices of inner and outer loop respectively."
},
{
"code": null,
"e": 41309,
"s": 41305,
"text": "C++"
},
{
"code": null,
"e": 41314,
"s": 41309,
"text": "Java"
},
{
"code": null,
"e": 41317,
"s": 41314,
"text": "C#"
},
{
"code": null,
"e": 41325,
"s": 41317,
"text": "Python3"
},
{
"code": null,
"e": 41329,
"s": 41325,
"text": "PHP"
},
{
"code": null,
"e": 41340,
"s": 41329,
"text": "Javascript"
},
{
"code": "// C++ program for left// rotation of matrix by 90 degree// without using extra space#include <bits/stdc++.h>using namespace std;#define R 4#define C 4 // After transpose we swap// elements of column// one by one for finding left// rotation of matrix// by 90 degreevoid reverseColumns(int arr[R][C]){ for (int i = 0; i < C; i++) for (int j = 0, k = C - 1; j < k; j++, k--) swap(arr[j][i], arr[k][i]);} // Function for do transpose of matrixvoid transpose(int arr[R][C]){ for (int i = 0; i < R; i++) for (int j = i; j < C; j++) swap(arr[i][j], arr[j][i]);} // Function for print matrixvoid printMatrix(int arr[R][C]){ for (int i = 0; i < R; i++) { for (int j = 0; j < C; j++) cout << arr[i][j] << \" \"; cout << '\\n'; }} // Function to anticlockwise// rotate matrix by 90 degreevoid rotate90(int arr[R][C]){ transpose(arr); reverseColumns(arr);} // Driven codeint main(){ int arr[R][C] = { { 1, 2, 3, 4 }, { 5, 6, 7, 8 }, { 9, 10, 11, 12 }, { 13, 14, 15, 16 } }; rotate90(arr); printMatrix(arr); return 0;}",
"e": 42498,
"s": 41340,
"text": null
},
{
"code": "// JAVA Code for left Rotation of a// matrix by 90 degree without using// any extra spaceimport java.util.*; class GFG { // After transpose we swap elements of // column one by one for finding left // rotation of matrix by 90 degree static void reverseColumns(int arr[][]) { for (int i = 0; i < arr[0].length; i++) for (int j = 0, k = arr[0].length - 1; j < k; j++, k--) { int temp = arr[j][i]; arr[j][i] = arr[k][i]; arr[k][i] = temp; } } // Function for do transpose of matrix static void transpose(int arr[][]) { for (int i = 0; i < arr.length; i++) for (int j = i; j < arr[0].length; j++) { int temp = arr[j][i]; arr[j][i] = arr[i][j]; arr[i][j] = temp; } } // Function for print matrix static void printMatrix(int arr[][]) { for (int i = 0; i < arr.length; i++) { for (int j = 0; j < arr[0].length; j++) System.out.print(arr[i][j] + \" \"); System.out.println(\"\"); } } // Function to anticlockwise rotate // matrix by 90 degree static void rotate90(int arr[][]) { transpose(arr); reverseColumns(arr); } /* Driver program to test above function */ public static void main(String[] args) { int arr[][] = { { 1, 2, 3, 4 }, { 5, 6, 7, 8 }, { 9, 10, 11, 12 }, { 13, 14, 15, 16 } }; rotate90(arr); printMatrix(arr); }} // This code is contributed by Arnav Kr. Mandal.",
"e": 44157,
"s": 42498,
"text": null
},
{
"code": "// C# program for left rotation// of matrix by 90 degree// without using extra spaceusing System; class GFG { static int R = 4; static int C = 4; // After transpose we swap // elements of column one // by one for finding left // rotation of matrix by // 90 degree static void reverseColumns(int[, ] arr) { for (int i = 0; i < C; i++) for (int j = 0, k = C - 1; j < k; j++, k--) { int temp = arr[j, i]; arr[j, i] = arr[k, i]; arr[k, i] = temp; } } // Function for do // transpose of matrix static void transpose(int[, ] arr) { for (int i = 0; i < R; i++) for (int j = i; j < C; j++) { int temp = arr[j, i]; arr[j, i] = arr[i, j]; arr[i, j] = temp; } } // Function for print matrix static void printMatrix(int[, ] arr) { for (int i = 0; i < R; i++) { for (int j = 0; j < C; j++) Console.Write(arr[i, j] + \" \"); Console.WriteLine(\"\"); } } // Function to anticlockwise // rotate matrix by 90 degree static void rotate90(int[, ] arr) { transpose(arr); reverseColumns(arr); } // Driver code static void Main() { int[, ] arr = { { 1, 2, 3, 4 }, { 5, 6, 7, 8 }, { 9, 10, 11, 12 }, { 13, 14, 15, 16 } }; rotate90(arr); printMatrix(arr); } // This code is contributed // by Sam007}",
"e": 45730,
"s": 44157,
"text": null
},
{
"code": "# Python 3 program for left rotation of matrix by 90# degree without using extra space R = 4C = 4 # After transpose we swap elements of column# one by one for finding left rotation of matrix# by 90 degree def reverseColumns(arr): for i in range(C): j = 0 k = C-1 while j < k: t = arr[j][i] arr[j][i] = arr[k][i] arr[k][i] = t j += 1 k -= 1 # Function for do transpose of matrix def transpose(arr): for i in range(R): for j in range(i, C): t = arr[i][j] arr[i][j] = arr[j][i] arr[j][i] = t # Function for print matrix def printMatrix(arr): for i in range(R): for j in range(C): print(str(arr[i][j]), end=\" \") print() # Function to anticlockwise rotate matrix# by 90 degree def rotate90(arr): transpose(arr) reverseColumns(arr) # Driven codearr = [[1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12], [13, 14, 15, 16] ]rotate90(arr)printMatrix(arr)",
"e": 46754,
"s": 45730,
"text": null
},
{
"code": "<?php// PHP program for left rotation of matrix by 90 $R = 4;$C = 4;// Function to rotate the matrix by 90 degreefunction reverseColumns(&$arr){ global $C; for ($i = 0; $i < $C; $i++) { for ($j = 0, $k = $C - 1; $j < $k; $j++, $k--) { $t = $arr[$j][$i]; $arr[$j][$i] = $arr[$k][$i]; $arr[$k][$i] = $t; } } } // Function for transpose of matrixfunction transpose(&$arr){ global $R, $C; for ($i = 0; $i < $R; $i++) { for ($j = $i; $j < $C; $j++) { $t = $arr[$i][$j]; $arr[$i][$j] = $arr[$j][$i]; $arr[$j][$i] = $t; } }} // Function for display the matrixfunction printMatrix(&$arr){ global $R, $C; for ($i = 0; $i < $R; $i++) { for ($j = 0; $j < $C; $j++) echo $arr[$i][$j].\" \"; echo \"\\n\"; }} // Function to anticlockwise rotate matrix// by 90 degreefunction rotate90(&$arr){ transpose($arr); reverseColumns($arr);} // Driven code $arr = array( array( 1, 2, 3, 4 ), array( 5, 6, 7, 8 ), array( 9, 10, 11, 12 ), array( 13, 14, 15, 16 ) );rotate90($arr);printMatrix($arr);return 0;?>",
"e": 47963,
"s": 46754,
"text": null
},
{
"code": "<script> // JAVASCRIPT Code for left Rotation of a// matrix by 90 degree without using// any extra space // After transpose we swap elements of // column one by one for finding left // rotation of matrix by 90 degree function reverseColumns(arr) { for (let i = 0; i < arr[0].length; i++) for (let j = 0, k = arr[0].length - 1; j < k; j++, k--) { let temp = arr[j][i]; arr[j][i] = arr[k][i]; arr[k][i] = temp; } } // Function for do transpose of matrix function transpose(arr) { for (let i = 0; i < arr.length; i++) for (let j = i; j < arr[0].length; j++) { let temp = arr[j][i]; arr[j][i] = arr[i][j]; arr[i][j] = temp; } } // Function for print matrix function printMatrix(arr) { for (let i = 0; i < arr.length; i++) { for (let j = 0; j < arr[0].length; j++) document.write(arr[i][j] + \" \"); document.write(\"<br>\"); } } // Function to anticlockwise rotate // matrix by 90 degree function rotate90(arr) { transpose(arr); reverseColumns(arr); } /* Driver program to test above function */ let arr = [[1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12], [13, 14, 15, 16] ]; rotate90(arr) printMatrix(arr) // This code is contributed by rag2127 </script>",
"e": 49494,
"s": 47963,
"text": null
},
{
"code": null,
"e": 49540,
"s": 49497,
"text": "4 8 12 16 \n3 7 11 15 \n2 6 10 14 \n1 5 9 13 "
},
{
"code": null,
"e": 49564,
"s": 49542,
"text": "Complexity Analysis: "
},
{
"code": null,
"e": 49651,
"s": 49566,
"text": "Time complexity :O(R*C). The matrix is traversed twice, so the complexity is O(R*C)."
},
{
"code": null,
"e": 49739,
"s": 49651,
"text": "Space complexity :O(1). The space complexity is constant as no extra space is required."
},
{
"code": null,
"e": 49799,
"s": 49741,
"text": "Another Approach using a single traversal of the matrix :"
},
{
"code": null,
"e": 49999,
"s": 49801,
"text": "The idea is to traverse along the boundaries of the matrix and shift the positions of the elements in 900 anticlockwise directions in each boundary. There are such (n/2-1) boundaries in the matrix."
},
{
"code": null,
"e": 50013,
"s": 50001,
"text": "Algorithm: "
},
{
"code": null,
"e": 50587,
"s": 50015,
"text": "Iterate over all the boundaries in the matrix. There are total (n/2-1) boundariesFor each boundary take the 4 corner elements and swap them such that the 4 corner elements get rotated in anticlockwise directions. Then take the next 4 elements along the edges(left, right, top, bottom) and swap them in an anticlockwise direction. Continue as long as all the elements in that particular boundary get rotated in 900 anticlockwise directions.Then move on to the next inner boundary and continue the process as long the whole matrix is rotated in 900 anticlockwise direction."
},
{
"code": null,
"e": 50669,
"s": 50587,
"text": "Iterate over all the boundaries in the matrix. There are total (n/2-1) boundaries"
},
{
"code": null,
"e": 51028,
"s": 50669,
"text": "For each boundary take the 4 corner elements and swap them such that the 4 corner elements get rotated in anticlockwise directions. Then take the next 4 elements along the edges(left, right, top, bottom) and swap them in an anticlockwise direction. Continue as long as all the elements in that particular boundary get rotated in 900 anticlockwise directions."
},
{
"code": null,
"e": 51161,
"s": 51028,
"text": "Then move on to the next inner boundary and continue the process as long the whole matrix is rotated in 900 anticlockwise direction."
},
{
"code": null,
"e": 51176,
"s": 51161,
"text": "Original array"
},
{
"code": null,
"e": 51199,
"s": 51176,
"text": "total n/2-1 boundaries"
},
{
"code": null,
"e": 51222,
"s": 51199,
"text": "for outermost boundary"
},
{
"code": null,
"e": 51246,
"s": 51222,
"text": "for next inner boundary"
},
{
"code": null,
"e": 51254,
"s": 51248,
"text": "C++14"
},
{
"code": null,
"e": 51259,
"s": 51254,
"text": "Java"
},
{
"code": null,
"e": 51267,
"s": 51259,
"text": "Python3"
},
{
"code": null,
"e": 51270,
"s": 51267,
"text": "C#"
},
{
"code": null,
"e": 51281,
"s": 51270,
"text": "Javascript"
},
{
"code": "// C++ program for left rotation of matrix// by 90 degree without using extra space#include <bits/stdc++.h>using namespace std;#define R 4#define C 4 // Function to rotate matrix anticlockwise by 90 degrees.void rotateby90(int arr[R][C]){ int n = R; // n=size of the square matrix int a = 0, b = 0, c = 0, d = 0; // iterate over all the boundaries of the matrix for (int i = 0; i <= n / 2 - 1; i++) { // for each boundary, keep on taking 4 elements (one // each along the 4 edges) and swap them in // anticlockwise manner for (int j = 0; j <= n - 2 * i - 2; j++) { a = arr[i + j][i]; b = arr[n - 1 - i][i + j]; c = arr[n - 1 - i - j][n - 1 - i]; d = arr[i][n - 1 - i - j]; arr[i + j][i] = d; arr[n - 1 - i][i + j] = a; arr[n - 1 - i - j][n - 1 - i] = b; arr[i][n - 1 - i - j] = c; } }} // Function for print matrixvoid printMatrix(int arr[R][C]){ for (int i = 0; i < R; i++) { for (int j = 0; j < C; j++) cout << arr[i][j] << \" \"; cout << '\\n'; }} // Driven codeint main(){ int arr[R][C] = { { 1, 2, 3, 4 }, { 5, 6, 7, 8 }, { 9, 10, 11, 12 }, { 13, 14, 15, 16 } }; rotateby90(arr); printMatrix(arr); return 0;} // This code is contributed by Md. Enjamum// Hossain(enja_2001)",
"e": 52703,
"s": 51281,
"text": null
},
{
"code": "// JAVA Code for left Rotation of a matrix// by 90 degree without using any extra spaceimport java.util.*; class GFG { // Function to rotate matrix anticlockwise by 90 // degrees. static void rotateby90(int arr[][]) { int n = arr.length; int a = 0, b = 0, c = 0, d = 0; // iterate over all the boundaries of the matrix for (int i = 0; i <= n / 2 - 1; i++) { // for each boundary, keep on taking 4 elements // (one each along the 4 edges) and swap them in // anticlockwise manner for (int j = 0; j <= n - 2 * i - 2; j++) { a = arr[i + j][i]; b = arr[n - 1 - i][i + j]; c = arr[n - 1 - i - j][n - 1 - i]; d = arr[i][n - 1 - i - j]; arr[i + j][i] = d; arr[n - 1 - i][i + j] = a; arr[n - 1 - i - j][n - 1 - i] = b; arr[i][n - 1 - i - j] = c; } } } // Function for print matrix static void printMatrix(int arr[][]) { for (int i = 0; i < arr.length; i++) { for (int j = 0; j < arr[0].length; j++) System.out.print(arr[i][j] + \" \"); System.out.println(\"\"); } } /* Driver program to test above function */ public static void main(String[] args) { int arr[][] = { { 1, 2, 3, 4 }, { 5, 6, 7, 8 }, { 9, 10, 11, 12 }, { 13, 14, 15, 16 } }; rotateby90(arr); printMatrix(arr); }} // This code is contributed by Md. Enjamum// Hossain(enja_2001)",
"e": 54329,
"s": 52703,
"text": null
},
{
"code": "# Function to rotate matrix anticlockwise by 90 degrees.def rotateby90(arr): n = len(arr) a,b,c,d = 0,0,0,0 # iterate over all the boundaries of the matrix for i in range(n // 2): # for each boundary, keep on taking 4 elements # (one each along the 4 edges) and swap them in # anticlockwise manner for j in range(n - 2 * i - 1): a = arr[i + j][i] b = arr[n - 1 - i][i + j] c = arr[n - 1 - i - j][n - 1 - i] d = arr[i][n - 1 - i - j] arr[i + j][i] = d arr[n - 1 - i][i + j] = a arr[n - 1 - i - j][n - 1 - i] = b arr[i][n - 1 - i - j] = c # Function for print matrixdef printMatrix(arr): for i in range(len(arr)): for j in range(len(arr[0])): print(arr[i][j] ,end = \" \") print() # Driver program to test above functionarr=[[ 1, 2, 3, 4 ], [ 5, 6, 7, 8 ], [ 9, 10, 11, 12 ], [ 13, 14, 15, 16 ]]rotateby90(arr)printMatrix(arr) # this code is contributed by shinjanpatra",
"e": 55398,
"s": 54329,
"text": null
},
{
"code": "// C# Code for left Rotation of a matrix// by 90 degree without using any extra spaceusing System;using System.Collections.Generic; public class GFG { // Function to rotate matrix anticlockwise by 90 // degrees. static void rotateby90(int [,]arr) { int n = arr.GetLength(0); int a = 0, b = 0, c = 0, d = 0; // iterate over all the boundaries of the matrix for (int i = 0; i <= n / 2 - 1; i++) { // for each boundary, keep on taking 4 elements // (one each along the 4 edges) and swap them in // anticlockwise manner for (int j = 0; j <= n - 2 * i - 2; j++) { a = arr[i + j,i]; b = arr[n - 1 - i,i + j]; c = arr[n - 1 - i - j,n - 1 - i]; d = arr[i,n - 1 - i - j]; arr[i + j,i] = d; arr[n - 1 - i,i + j] = a; arr[n - 1 - i - j,n - 1 - i] = b; arr[i,n - 1 - i - j] = c; } } } // Function for print matrix static void printMatrix(int [,]arr) { for (int i = 0; i < arr.GetLength(0); i++) { for (int j = 0; j < arr.GetLength(1); j++) Console.Write(arr[i,j] + \" \"); Console.WriteLine(\"\"); } } /* Driver program to test above function */ public static void Main(String[] args) { int [,]arr = { { 1, 2, 3, 4 }, { 5, 6, 7, 8 }, { 9, 10, 11, 12 }, { 13, 14, 15, 16 } }; rotateby90(arr); printMatrix(arr); }} // This code is contributed by umadevi9616",
"e": 57034,
"s": 55398,
"text": null
},
{
"code": "<script> // JavaScript Code for left Rotation of a matrix// by 90 degree without using any extra space // Function to rotate matrix anticlockwise by 90 // degrees.function rotateby90(arr){ let n = arr.length; let a = 0, b = 0, c = 0, d = 0; // iterate over all the boundaries of the matrix for (let i = 0; i <= n / 2 - 1; i++) { // for each boundary, keep on taking 4 elements // (one each along the 4 edges) and swap them in // anticlockwise manner for (let j = 0; j <= n - 2 * i - 2; j++) { a = arr[i + j][i]; b = arr[n - 1 - i][i + j]; c = arr[n - 1 - i - j][n - 1 - i]; d = arr[i][n - 1 - i - j]; arr[i + j][i] = d; arr[n - 1 - i][i + j] = a; arr[n - 1 - i - j][n - 1 - i] = b; arr[i][n - 1 - i - j] = c; } }} // Function for print matrixfunction printMatrix(arr){ for (let i = 0; i < arr.length; i++) { for (let j = 0; j < arr[0].length; j++) document.write(arr[i][j] + \" \"); document.write(\"<br>\"); }} /* Driver program to test above function */let arr=[[ 1, 2, 3, 4 ], [ 5, 6, 7, 8 ], [ 9, 10, 11, 12 ], [ 13, 14, 15, 16 ]];rotateby90(arr);printMatrix(arr); // This code is contributed by avanitrachhadiya2155 </script>",
"e": 58498,
"s": 57034,
"text": null
},
{
"code": null,
"e": 58541,
"s": 58498,
"text": "4 8 12 16 \n3 7 11 15 \n2 6 10 14 \n1 5 9 13 "
},
{
"code": null,
"e": 58563,
"s": 58541,
"text": "Complexity Analysis: "
},
{
"code": null,
"e": 58657,
"s": 58563,
"text": "Time complexity :O(R*C). The matrix is traversed only once, so the time complexity is O(R*C)."
},
{
"code": null,
"e": 58741,
"s": 58657,
"text": "Space complexity :O(1). The space complexity is O(1) as no extra space is required."
},
{
"code": null,
"e": 58848,
"s": 58741,
"text": "Implementation: Let’s see a method of Python numpy that can be used to arrive at the particular solution. "
},
{
"code": null,
"e": 58856,
"s": 58848,
"text": "Python3"
},
{
"code": "# Alternative implementation using numpyimport numpy # Driven codearr = [[1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12], [13, 14, 15, 16] ] # Define flip algorithm (Note numpy.flip is a builtin f# function for versions > v.1.12.0) def flip(m, axis): if not hasattr(m, 'ndim'): m = asarray(m) indexer = [slice(None)] * m.ndim try: indexer[axis] = slice(None, None, -1) except IndexError: raise ValueError(\"axis =% i is invalid for the % i-dimensional input array\" % (axis, m.ndim)) return m[tuple(indexer)] # Transpose the matrixtrans = numpy.transpose(arr) # Flip the matrix anti-clockwise (1 for clockwise)flipmat = flip(trans, 0) print(\"\\nnumpy implementation\\n\")print(flipmat)",
"e": 59619,
"s": 58856,
"text": null
},
{
"code": null,
"e": 59629,
"s": 59619,
"text": "Output: "
},
{
"code": null,
"e": 59712,
"s": 59629,
"text": "numpy implementation\n\n[[ 4 8 12 16]\n [ 3 7 11 15]\n [ 2 6 10 14]\n [ 1 5 9 13]]"
},
{
"code": null,
"e": 59983,
"s": 59712,
"text": "Note: The above steps/programs do left (or anticlockwise) rotation. Let’s see how to do the right rotation or clockwise rotation. The approach would be similar. Find the transpose of the matrix and then reverse the rows of the transposed matrix. This is how it is done. "
},
{
"code": null,
"e": 60404,
"s": 59983,
"text": "This article is contributed by DANISH_RAZA . If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to [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": 60434,
"s": 60404,
"text": "Rotating Along the Boundaries"
},
{
"code": null,
"e": 60561,
"s": 60434,
"text": "We can start at the first 4 corners of the given matrix and then keep incrementing the row and column indices to moves around."
},
{
"code": null,
"e": 60663,
"s": 60561,
"text": "At any given moment we will have four corners lu (left-up),ld(left-down),ru(right-up),rd(right-down)."
},
{
"code": null,
"e": 60750,
"s": 60663,
"text": "To left rotate we will first swap the ru and ld, then lu and ld and lastly ru and rd."
},
{
"code": null,
"e": 60754,
"s": 60750,
"text": "C++"
},
{
"code": null,
"e": 60759,
"s": 60754,
"text": "Java"
},
{
"code": null,
"e": 60762,
"s": 60759,
"text": "C#"
},
{
"code": null,
"e": 60773,
"s": 60762,
"text": "Javascript"
},
{
"code": "#include <bits/stdc++.h>using namespace std; //Function to rotate matrix anticlockwise by 90 degrees.void rotateby90(vector<vector<int> >& matrix){ int n=matrix.size(); int mid; if(n%2==0) mid=n/2-1; else mid=n/2; for(int i=0,j=n-1;i<=mid;i++,j--) { for(int k=0;k<j-i;k++) { swap(matrix[i][j-k],matrix[j][i+k]); //ru ld swap(matrix[i+k][i],matrix[j][i+k]); //lu ld swap(matrix[i][j-k],matrix[j-k][j]); //ru rd } } } void printMatrix(vector<vector<int>>& arr){ int n=arr.size(); for(int i=0;i<n;i++) { for(int j=0;j<n;j++) { cout<<arr[i][j]<<\" \"; } cout<<endl; }}int main() { vector<vector<int>> arr = { { 1, 2, 3, 4 }, { 5, 6, 7, 8 }, { 9, 10, 11, 12 }, { 13, 14, 15, 16 } }; rotateby90(arr); printMatrix(arr); return 0;}",
"e": 61723,
"s": 60773,
"text": null
},
{
"code": "import java.util.*; class GFG{ private static int[][] swap(int[][] matrix, int x1,int x2,int y1, int y2) { int temp = matrix[x1][x2] ; matrix[x1][x2] = matrix[y1][y2]; matrix[y1][y2] = temp; return matrix; } //Function to rotate matrix anticlockwise by 90 degrees.static int[][] rotateby90(int[][] matrix){ int n=matrix.length; int mid; if(n % 2 == 0) mid = n / 2 - 1; else mid = n / 2; for(int i = 0, j = n - 1; i <= mid; i++, j--) { for(int k = 0; k < j - i; k++) { matrix= swap(matrix, i, j - k, j, i + k); //ru ld matrix= swap(matrix, i + k, i, j, i + k); //lu ld matrix= swap(matrix, i, j - k, j - k, j); //ru rd } } return matrix;} static void printMatrix(int[][] arr){ int n = arr.length; for(int i = 0; i < n; i++) { for(int j = 0; j < n; j++) { System.out.print(arr[i][j] + \" \"); } System.out.println(); }}public static void main(String[] args) { int[][] arr = { { 1, 2, 3, 4 }, { 5, 6, 7, 8 }, { 9, 10, 11, 12 }, { 13, 14, 15, 16 } }; arr = rotateby90(arr); printMatrix(arr);}} // This code is contributed by umadevi9616",
"e": 63025,
"s": 61723,
"text": null
},
{
"code": "using System; public class GFG{ private static int[,] swap(int[,] matrix, int x1,int x2,int y1, int y2) { int temp = matrix[x1,x2] ; matrix[x1,x2] = matrix[y1,y2]; matrix[y1,y2] = temp; return matrix; } //Function to rotate matrix anticlockwise by 90 degrees.static int[,] rotateby90(int[,] matrix){ int n=matrix.GetLength(0); int mid; if(n % 2 == 0) mid = (n / 2 - 1); else mid = (n / 2); for(int i = 0, j = n - 1; i <= mid; i++, j--) { for(int k = 0; k < j - i; k++) { matrix= swap(matrix, i, j - k, j, i + k); //ru ld matrix= swap(matrix, i + k, i, j, i + k); //lu ld matrix= swap(matrix, i, j - k, j - k, j); //ru rd } } return matrix;} static void printMatrix(int[,] arr){ int n = arr.GetLength(0); for(int i = 0; i < n; i++) { for(int j = 0; j < n; j++) { Console.Write(arr[i,j] + \" \"); } Console.WriteLine(); }}public static void Main(String[] args) { int[,] arr = { { 1, 2, 3, 4 }, { 5, 6, 7, 8 }, { 9, 10, 11, 12 }, { 13, 14, 15, 16 } }; arr = rotateby90(arr); printMatrix(arr);}} // This code is contributed by Rajput-Ji",
"e": 64327,
"s": 63025,
"text": null
},
{
"code": "<script> function swap(matrix , x1 , x2 , y1 , y2) { var temp = matrix[x1][x2]; matrix[x1][x2] = matrix[y1][y2]; matrix[y1][y2] = temp; return matrix; } // Function to rotate matrix anticlockwise by 90 degrees. function rotateby90(matrix) { var n = matrix.length; var mid; if (n % 2 == 0) mid = n / 2 - 1; else mid = n / 2; for (i = 0, j = n - 1; i <= mid; i++, j--) { for (k = 0; k < j - i; k++) { matrix = swap(matrix, i, j - k, j, i + k); // ru ld matrix = swap(matrix, i + k, i, j, i + k); // lu ld matrix = swap(matrix, i, j - k, j - k, j); // ru rd } } return matrix; } function printMatrix(arr) { var n = arr.length; for (i = 0; i < n; i++) { for (j = 0; j < n; j++) { document.write(arr[i][j] + \" \"); } document.write(\"<br/>\"); } } var arr = [ [ 1, 2, 3, 4 ], [ 5, 6, 7, 8 ], [ 9, 10, 11, 12 ], [ 13, 14, 15, 16 ] ]; arr = rotateby90(arr); printMatrix(arr); // This code is contributed by Rajput-Ji</script>",
"e": 65546,
"s": 64327,
"text": null
},
{
"code": null,
"e": 65556,
"s": 65546,
"text": "Output: "
},
{
"code": null,
"e": 65599,
"s": 65556,
"text": "4 8 12 16 \n3 7 11 15 \n2 6 10 14 \n1 5 9 13 "
},
{
"code": null,
"e": 65623,
"s": 65599,
"text": "Time Complexity: O(n^2)"
},
{
"code": null,
"e": 65647,
"s": 65623,
"text": "Space Complexity : O(1)"
},
{
"code": null,
"e": 65654,
"s": 65647,
"text": "Sam007"
},
{
"code": null,
"e": 65660,
"s": 65654,
"text": "ukasp"
},
{
"code": null,
"e": 65671,
"s": 65660,
"text": "bpgreyling"
},
{
"code": null,
"e": 65682,
"s": 65671,
"text": "andrew1234"
},
{
"code": null,
"e": 65690,
"s": 65682,
"text": "rag2127"
},
{
"code": null,
"e": 65700,
"s": 65690,
"text": "enja_2001"
},
{
"code": null,
"e": 65721,
"s": 65700,
"text": "avanitrachhadiya2155"
},
{
"code": null,
"e": 65733,
"s": 65721,
"text": "anikakapoor"
},
{
"code": null,
"e": 65746,
"s": 65733,
"text": "piyushbisht3"
},
{
"code": null,
"e": 65758,
"s": 65746,
"text": "umadevi9616"
},
{
"code": null,
"e": 65777,
"s": 65758,
"text": "surindertarika1234"
},
{
"code": null,
"e": 65787,
"s": 65777,
"text": "Rajput-Ji"
},
{
"code": null,
"e": 65800,
"s": 65787,
"text": "shinjanpatra"
},
{
"code": null,
"e": 65809,
"s": 65800,
"text": "rotation"
},
{
"code": null,
"e": 65816,
"s": 65809,
"text": "Matrix"
},
{
"code": null,
"e": 65823,
"s": 65816,
"text": "Matrix"
},
{
"code": null,
"e": 65921,
"s": 65823,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 65956,
"s": 65921,
"text": "Matrix Chain Multiplication | DP-8"
},
{
"code": null,
"e": 66000,
"s": 65956,
"text": "Program to find largest element in an array"
},
{
"code": null,
"e": 66036,
"s": 66000,
"text": "Print a given matrix in spiral form"
},
{
"code": null,
"e": 66067,
"s": 66036,
"text": "Rat in a Maze | Backtracking-2"
},
{
"code": null,
"e": 66110,
"s": 66067,
"text": "Maximum size square sub-matrix with all 1s"
},
{
"code": null,
"e": 66134,
"s": 66110,
"text": "Sudoku | Backtracking-7"
},
{
"code": null,
"e": 66181,
"s": 66134,
"text": "Find the number of islands | Set 1 (Using DFS)"
},
{
"code": null,
"e": 66243,
"s": 66181,
"text": "Divide and Conquer | Set 5 (Strassen's Matrix Multiplication)"
},
{
"code": null,
"e": 66314,
"s": 66243,
"text": "Count all possible paths from top left to bottom right of a mXn matrix"
}
] |
Python | Group and count similar records - GeeksforGeeks | 11 Nov, 2019
Sometimes, while working with records, we can have a problem in which we need to collect and maintain the counter value inside records. This kind of application is important in web development domain. Let’s discuss certain ways in which this task can be performed.
Method #1 : Using loop + Counter() + set()The combination of above functionalities can be employed to achieve this task. In this, we run a loop to capture each tuple and add to set and check if it’s already existing, then increase and add a counter value to it. The cumulative count is achieved by using Counter().
# Python3 code to demonstrate working of# Group and count similar records# using Counter() + loop + set()from collections import Counter # initialize listtest_list = [('gfg', ), ('is', ), ('best', ), ('gfg', ), ('is', ), ('for', ), ('geeks', )] # printing original listprint("The original list : " + str(test_list)) # Group and count similar records# using Counter() + loop + set()res = []temp = set()counter = Counter(test_list)for sub in test_list: if sub not in temp: res.append((counter[sub], ) + sub) temp.add(sub) # printing resultprint("Grouped and counted list is : " + str(res))
The original list : [(‘gfg’, ), (‘is’, ), (‘best’, ), (‘gfg’, ), (‘is’, ), (‘for’, ), (‘geeks’, )]Grouped and counted list is : [(2, ‘gfg’), (2, ‘is’), (1, ‘best’), (1, ‘for’), (1, ‘geeks’)]
Method #2 : Using Counter() + list comprehension + items()
This is one liner approach and recommended to use for programming. The task of loops is handled by list comprehension and items() is used to access all the elements of Counter converted dictionary to allow computations.
# Python3 code to demonstrate working of# Group and count similar records# using Counter() + list comprehension + items()from collections import Counter # initialize listtest_list = [('gfg', ), ('is', ), ('best', ), ('gfg', ), ('is', ), ('for', ), ('geeks', )] # printing original listprint("The original list : " + str(test_list)) # Group and count similar records# using Counter() + list comprehension + items()res = [(counter, ) + ele for ele, counter in Counter(test_list).items()] # printing resultprint("Grouped and counted list is : " + str(res))
The original list : [(‘gfg’, ), (‘is’, ), (‘best’, ), (‘gfg’, ), (‘is’, ), (‘for’, ), (‘geeks’, )]Grouped and counted list is : [(2, ‘gfg’), (2, ‘is’), (1, ‘best’), (1, ‘for’), (1, ‘geeks’)]
Python list-programs
Python
Python Programs
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Install PIP on Windows ?
Check if element exists in list in Python
How To Convert Python Dictionary To JSON?
How to drop one or multiple columns in Pandas Dataframe
Python Classes and Objects
Defaultdict in Python
Python | Get dictionary keys as a list
Python | Split string into list of characters
Python | Convert a list to dictionary
How to print without newline in Python? | [
{
"code": null,
"e": 25581,
"s": 25553,
"text": "\n11 Nov, 2019"
},
{
"code": null,
"e": 25846,
"s": 25581,
"text": "Sometimes, while working with records, we can have a problem in which we need to collect and maintain the counter value inside records. This kind of application is important in web development domain. Let’s discuss certain ways in which this task can be performed."
},
{
"code": null,
"e": 26161,
"s": 25846,
"text": "Method #1 : Using loop + Counter() + set()The combination of above functionalities can be employed to achieve this task. In this, we run a loop to capture each tuple and add to set and check if it’s already existing, then increase and add a counter value to it. The cumulative count is achieved by using Counter()."
},
{
"code": "# Python3 code to demonstrate working of# Group and count similar records# using Counter() + loop + set()from collections import Counter # initialize listtest_list = [('gfg', ), ('is', ), ('best', ), ('gfg', ), ('is', ), ('for', ), ('geeks', )] # printing original listprint(\"The original list : \" + str(test_list)) # Group and count similar records# using Counter() + loop + set()res = []temp = set()counter = Counter(test_list)for sub in test_list: if sub not in temp: res.append((counter[sub], ) + sub) temp.add(sub) # printing resultprint(\"Grouped and counted list is : \" + str(res))",
"e": 26792,
"s": 26161,
"text": null
},
{
"code": null,
"e": 26983,
"s": 26792,
"text": "The original list : [(‘gfg’, ), (‘is’, ), (‘best’, ), (‘gfg’, ), (‘is’, ), (‘for’, ), (‘geeks’, )]Grouped and counted list is : [(2, ‘gfg’), (2, ‘is’), (1, ‘best’), (1, ‘for’), (1, ‘geeks’)]"
},
{
"code": null,
"e": 27044,
"s": 26985,
"text": "Method #2 : Using Counter() + list comprehension + items()"
},
{
"code": null,
"e": 27264,
"s": 27044,
"text": "This is one liner approach and recommended to use for programming. The task of loops is handled by list comprehension and items() is used to access all the elements of Counter converted dictionary to allow computations."
},
{
"code": "# Python3 code to demonstrate working of# Group and count similar records# using Counter() + list comprehension + items()from collections import Counter # initialize listtest_list = [('gfg', ), ('is', ), ('best', ), ('gfg', ), ('is', ), ('for', ), ('geeks', )] # printing original listprint(\"The original list : \" + str(test_list)) # Group and count similar records# using Counter() + list comprehension + items()res = [(counter, ) + ele for ele, counter in Counter(test_list).items()] # printing resultprint(\"Grouped and counted list is : \" + str(res))",
"e": 27844,
"s": 27264,
"text": null
},
{
"code": null,
"e": 28035,
"s": 27844,
"text": "The original list : [(‘gfg’, ), (‘is’, ), (‘best’, ), (‘gfg’, ), (‘is’, ), (‘for’, ), (‘geeks’, )]Grouped and counted list is : [(2, ‘gfg’), (2, ‘is’), (1, ‘best’), (1, ‘for’), (1, ‘geeks’)]"
},
{
"code": null,
"e": 28056,
"s": 28035,
"text": "Python list-programs"
},
{
"code": null,
"e": 28063,
"s": 28056,
"text": "Python"
},
{
"code": null,
"e": 28079,
"s": 28063,
"text": "Python Programs"
},
{
"code": null,
"e": 28177,
"s": 28079,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 28209,
"s": 28177,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 28251,
"s": 28209,
"text": "Check if element exists in list in Python"
},
{
"code": null,
"e": 28293,
"s": 28251,
"text": "How To Convert Python Dictionary To JSON?"
},
{
"code": null,
"e": 28349,
"s": 28293,
"text": "How to drop one or multiple columns in Pandas Dataframe"
},
{
"code": null,
"e": 28376,
"s": 28349,
"text": "Python Classes and Objects"
},
{
"code": null,
"e": 28398,
"s": 28376,
"text": "Defaultdict in Python"
},
{
"code": null,
"e": 28437,
"s": 28398,
"text": "Python | Get dictionary keys as a list"
},
{
"code": null,
"e": 28483,
"s": 28437,
"text": "Python | Split string into list of characters"
},
{
"code": null,
"e": 28521,
"s": 28483,
"text": "Python | Convert a list to dictionary"
}
] |
GATE | GATE-CS-2017 (Set 1) | Question 14 - GeeksforGeeks | 16 Sep, 2021
Consider the following intermediate program in three address code
p = a - b
q = p * c
p = u * v
q = p + q
Which one of the following corresponds to a static single assignment from the above code
A)
p1 = a - b
q 1 = p1 * c
p1 = u * v
q1 = p1 + q1
B)
p3 = a - b
q4 = p3 * c
p4 = u * v
q5 = p4 + q4
C)
p 1 = a - b
q1 = p2 * c
p3 = u * v
q2 = p4 + q3
D)
p1 = a - b
q1 = p * c
p2 = u * v
q2 = p + q
(A) A(B) B(C) C(D) DAnswer: (B)Explanation: According to Static Single Assignment
A variable cannot be used more than once in the LHSA variable should be initialized atmost once.
A variable cannot be used more than once in the LHS
A variable should be initialized atmost once.
Now looking at the given options
a – code violates condition 1 as p1 is initialized again in this statement: p1 = u * v
c- code is not valid as q1 = p2 * c , q2 = p4 + q3 – In these statements p2, p4, q3 are not initialized anywhere
d- code is invalid as q2 = p + q is incorrect without moving it to register
Therefore, option B is only correct option.
YouTubeGeeksforGeeks GATE Computer Science16.4K subscribersGATE PYQ - Code Generation and Optimization | Joyojyoti Acharya | GeeksforGeeks GATE |Watch laterShareCopy linkInfoShoppingTap to unmuteIf playback doesn't begin shortly, try restarting your device.You're signed outVideos you watch may be added to the TV's watch history and influence TV recommendations. To avoid this, cancel and sign in to YouTube on your computer.CancelConfirmMore videosMore videosSwitch cameraShareInclude playlistAn error occurred while retrieving sharing information. Please try again later.Watch on0:000:000:55 / 59:20•Live•<div class="player-unavailable"><h1 class="message">An error occurred.</h1><div class="submessage"><a href="https://www.youtube.com/watch?v=4ab8S2Qs7h8" 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-2017 (Set 1)
GATE-GATE-CS-2017 (Set 1)
GATE
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
GATE | Gate IT 2007 | Question 25
GATE | GATE-CS-2001 | Question 39
GATE | GATE-CS-2000 | Question 41
GATE | GATE-CS-2005 | Question 6
GATE | GATE MOCK 2017 | Question 21
GATE | GATE MOCK 2017 | Question 24
GATE | GATE-CS-2006 | Question 47
GATE | Gate IT 2008 | Question 43
GATE | GATE-CS-2009 | Question 38
GATE | GATE-CS-2003 | Question 90 | [
{
"code": null,
"e": 25647,
"s": 25619,
"text": "\n16 Sep, 2021"
},
{
"code": null,
"e": 25713,
"s": 25647,
"text": "Consider the following intermediate program in three address code"
},
{
"code": null,
"e": 25755,
"s": 25713,
"text": "p = a - b\nq = p * c\np = u * v\nq = p + q\n"
},
{
"code": null,
"e": 25844,
"s": 25755,
"text": "Which one of the following corresponds to a static single assignment from the above code"
},
{
"code": null,
"e": 25847,
"s": 25844,
"text": "A)"
},
{
"code": null,
"e": 25898,
"s": 25847,
"text": "p1 = a - b\nq 1 = p1 * c\np1 = u * v\nq1 = p1 + q1 \n"
},
{
"code": null,
"e": 25901,
"s": 25898,
"text": "B)"
},
{
"code": null,
"e": 25949,
"s": 25901,
"text": "p3 = a - b\nq4 = p3 * c\np4 = u * v\nq5 = p4 + q4\n"
},
{
"code": null,
"e": 25952,
"s": 25949,
"text": "C)"
},
{
"code": null,
"e": 26003,
"s": 25952,
"text": "p 1 = a - b\nq1 = p2 * c\np3 = u * v\nq2 = p4 + q3\n"
},
{
"code": null,
"e": 26006,
"s": 26003,
"text": "D)"
},
{
"code": null,
"e": 26051,
"s": 26006,
"text": "p1 = a - b\nq1 = p * c\np2 = u * v\nq2 = p + q\n"
},
{
"code": null,
"e": 26133,
"s": 26051,
"text": "(A) A(B) B(C) C(D) DAnswer: (B)Explanation: According to Static Single Assignment"
},
{
"code": null,
"e": 26230,
"s": 26133,
"text": "A variable cannot be used more than once in the LHSA variable should be initialized atmost once."
},
{
"code": null,
"e": 26282,
"s": 26230,
"text": "A variable cannot be used more than once in the LHS"
},
{
"code": null,
"e": 26328,
"s": 26282,
"text": "A variable should be initialized atmost once."
},
{
"code": null,
"e": 26361,
"s": 26328,
"text": "Now looking at the given options"
},
{
"code": null,
"e": 26448,
"s": 26361,
"text": "a – code violates condition 1 as p1 is initialized again in this statement: p1 = u * v"
},
{
"code": null,
"e": 26562,
"s": 26448,
"text": "c- code is not valid as q1 = p2 * c , q2 = p4 + q3 – In these statements p2, p4, q3 are not initialized anywhere"
},
{
"code": null,
"e": 26639,
"s": 26562,
"text": "d- code is invalid as q2 = p + q is incorrect without moving it to register"
},
{
"code": null,
"e": 26683,
"s": 26639,
"text": "Therefore, option B is only correct option."
},
{
"code": null,
"e": 27597,
"s": 26683,
"text": "YouTubeGeeksforGeeks GATE Computer Science16.4K subscribersGATE PYQ - Code Generation and Optimization | Joyojyoti Acharya | GeeksforGeeks GATE |Watch laterShareCopy linkInfoShoppingTap to unmuteIf playback doesn't begin shortly, try restarting your device.You're signed outVideos you watch may be added to the TV's watch history and influence TV recommendations. To avoid this, cancel and sign in to YouTube on your computer.CancelConfirmMore videosMore videosSwitch cameraShareInclude playlistAn error occurred while retrieving sharing information. Please try again later.Watch on0:000:000:55 / 59:20•Live•<div class=\"player-unavailable\"><h1 class=\"message\">An error occurred.</h1><div class=\"submessage\"><a href=\"https://www.youtube.com/watch?v=4ab8S2Qs7h8\" 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": 27618,
"s": 27597,
"text": "GATE-CS-2017 (Set 1)"
},
{
"code": null,
"e": 27644,
"s": 27618,
"text": "GATE-GATE-CS-2017 (Set 1)"
},
{
"code": null,
"e": 27649,
"s": 27644,
"text": "GATE"
},
{
"code": null,
"e": 27747,
"s": 27649,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 27781,
"s": 27747,
"text": "GATE | Gate IT 2007 | Question 25"
},
{
"code": null,
"e": 27815,
"s": 27781,
"text": "GATE | GATE-CS-2001 | Question 39"
},
{
"code": null,
"e": 27849,
"s": 27815,
"text": "GATE | GATE-CS-2000 | Question 41"
},
{
"code": null,
"e": 27882,
"s": 27849,
"text": "GATE | GATE-CS-2005 | Question 6"
},
{
"code": null,
"e": 27918,
"s": 27882,
"text": "GATE | GATE MOCK 2017 | Question 21"
},
{
"code": null,
"e": 27954,
"s": 27918,
"text": "GATE | GATE MOCK 2017 | Question 24"
},
{
"code": null,
"e": 27988,
"s": 27954,
"text": "GATE | GATE-CS-2006 | Question 47"
},
{
"code": null,
"e": 28022,
"s": 27988,
"text": "GATE | Gate IT 2008 | Question 43"
},
{
"code": null,
"e": 28056,
"s": 28022,
"text": "GATE | GATE-CS-2009 | Question 38"
}
] |
Loading Resources from Classpath in Java with Example - GeeksforGeeks | 05 Feb, 2021
Resources are the collections of files or images or stuff of other formats. Java programs help us to load these files or images of the resources and perform a read and write operation on them. For example, we can load a file from any resource directory and will be then able to read the content of that file. Basically, we are mainly focusing on the topic of loading and not on how to read the files, but we will be using some ideas of how to read files to demonstrate our examples.
There are mainly two ways to load resources and perform operations on them. We can either load the file(present in resources folder) as inputstream or URL format and then perform operations on them.
So basically two methods named: getResource() and getResourceAsStream() are used to load the resources from the classpath. These methods generally return the URL’s and input streams respectively. These methods are present in the java.lang.Class package.
So here we are taking getting absolute classpath using classLoader() method. Also, we are using the getClass() method here to get the class whose path is to be loaded. Basically, it will be the class of the .class file of our code. So we should make sure that the resources are located in the path of the class.
So to load the file from the name itself using classpath is done by combining all the above-discussed method. After getting the file we have to read its content, so we will be performing a read operation on them.
We will be using obj.getClass().getClassLoader().getResourceAsStream() and obj.getClass().getClassLoader().getResource() methods to get the stream and URL of the file respectively and then perform the read operations on them.
So two main points to consider here are:
Here we are declaring the object of the public class of our file since the getClass() method is non-static. So we cannot call this method without an object.In the below code, we are considering file named GFG_text.txt which acts as a resource, and we are taking care that this resource is in same path as that of our .class file.
Here we are declaring the object of the public class of our file since the getClass() method is non-static. So we cannot call this method without an object.
In the below code, we are considering file named GFG_text.txt which acts as a resource, and we are taking care that this resource is in same path as that of our .class file.
Code 1: Using getResourceAsStream() method.
Java
// Java program to load resources from Classpath// using getResourceAsStream() method. import java.io.*;import java.nio.file.Files; //save file as the name of GFG2public class GFG2 { //main class public static void main(String[] args) throws Exception { // creating object of the class // important since the getClass() method is // not static. GFG2 obj = new GFG2(); // name of the resource // the resource is stored in our base path of the // .class file. String fileName = "GFG_text.txt"; System.out.println("Getting the data of file " + fileName); // declaring the input stream // and initializing the stream. InputStream instr = obj.getClass().getClassLoader().getResourceAsStream(fileName); // reading the files with buffered reader InputStreamReader strrd = new InputStreamReader(instr); BufferedReader rr = new BufferedReader(strrd); String line; // outputting each line of the file. while ((line = rr.readLine()) != null) System.out.println(line); } }
output of the above program.
Code 2: Using getResource() method.
Java
// Java program to load resources from Classpath// using getResource() method. import java.io.*;import java.net.URI;import java.net.URISyntaxException;import java.net.URL;import java.nio.charset.StandardCharsets;import java.nio.file.Files;import java.util.List; //save file as the name of GFG2public class GFG2 { //main class public static void main(String[] args) throws Exception { // creating object of the class // important since the getClass() method is // not static. GFG2 obj = new GFG2(); // name of the resource // the resource is stored in our base path of the // .class file. String fileName = "GFG_text.txt"; System.out.println("Getting the data of file " + fileName); // getting the URL of the resource // and creating a file object to the given URL URL url = obj.getClass().getClassLoader().getResource(fileName); File file = new File(url.toURI()); // reading the file data // by creating a list of strings // of each line List<String> line; // method of files class to read all the lines of the // file specified. line = Files.readAllLines(file.toPath(), StandardCharsets.UTF_8); // reading the list of the line in the file. for(String s: line) System.out.println(s); }}
output for the second code.
Picked
Technical Scripter 2020
Java
Java Programs
Technical Scripter
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Stream In Java
Constructors in Java
Exceptions in Java
Functional Interfaces in Java
Different ways of Reading a text file in Java
Java Programming Examples
Convert Double to Integer in Java
Implementing a Linked List in Java using Class
How to Iterate HashMap in Java?
Iterate through List in Java | [
{
"code": null,
"e": 25225,
"s": 25197,
"text": "\n05 Feb, 2021"
},
{
"code": null,
"e": 25709,
"s": 25225,
"text": "Resources are the collections of files or images or stuff of other formats. Java programs help us to load these files or images of the resources and perform a read and write operation on them. For example, we can load a file from any resource directory and will be then able to read the content of that file. Basically, we are mainly focusing on the topic of loading and not on how to read the files, but we will be using some ideas of how to read files to demonstrate our examples. "
},
{
"code": null,
"e": 25908,
"s": 25709,
"text": "There are mainly two ways to load resources and perform operations on them. We can either load the file(present in resources folder) as inputstream or URL format and then perform operations on them."
},
{
"code": null,
"e": 26162,
"s": 25908,
"text": "So basically two methods named: getResource() and getResourceAsStream() are used to load the resources from the classpath. These methods generally return the URL’s and input streams respectively. These methods are present in the java.lang.Class package."
},
{
"code": null,
"e": 26475,
"s": 26162,
"text": "So here we are taking getting absolute classpath using classLoader() method. Also, we are using the getClass() method here to get the class whose path is to be loaded. Basically, it will be the class of the .class file of our code. So we should make sure that the resources are located in the path of the class. "
},
{
"code": null,
"e": 26689,
"s": 26475,
"text": "So to load the file from the name itself using classpath is done by combining all the above-discussed method. After getting the file we have to read its content, so we will be performing a read operation on them. "
},
{
"code": null,
"e": 26915,
"s": 26689,
"text": "We will be using obj.getClass().getClassLoader().getResourceAsStream() and obj.getClass().getClassLoader().getResource() methods to get the stream and URL of the file respectively and then perform the read operations on them."
},
{
"code": null,
"e": 26956,
"s": 26915,
"text": "So two main points to consider here are:"
},
{
"code": null,
"e": 27286,
"s": 26956,
"text": "Here we are declaring the object of the public class of our file since the getClass() method is non-static. So we cannot call this method without an object.In the below code, we are considering file named GFG_text.txt which acts as a resource, and we are taking care that this resource is in same path as that of our .class file."
},
{
"code": null,
"e": 27443,
"s": 27286,
"text": "Here we are declaring the object of the public class of our file since the getClass() method is non-static. So we cannot call this method without an object."
},
{
"code": null,
"e": 27617,
"s": 27443,
"text": "In the below code, we are considering file named GFG_text.txt which acts as a resource, and we are taking care that this resource is in same path as that of our .class file."
},
{
"code": null,
"e": 27661,
"s": 27617,
"text": "Code 1: Using getResourceAsStream() method."
},
{
"code": null,
"e": 27666,
"s": 27661,
"text": "Java"
},
{
"code": "// Java program to load resources from Classpath// using getResourceAsStream() method. import java.io.*;import java.nio.file.Files; //save file as the name of GFG2public class GFG2 { //main class public static void main(String[] args) throws Exception { // creating object of the class // important since the getClass() method is // not static. GFG2 obj = new GFG2(); // name of the resource // the resource is stored in our base path of the // .class file. String fileName = \"GFG_text.txt\"; System.out.println(\"Getting the data of file \" + fileName); // declaring the input stream // and initializing the stream. InputStream instr = obj.getClass().getClassLoader().getResourceAsStream(fileName); // reading the files with buffered reader InputStreamReader strrd = new InputStreamReader(instr); BufferedReader rr = new BufferedReader(strrd); String line; // outputting each line of the file. while ((line = rr.readLine()) != null) System.out.println(line); } }",
"e": 28850,
"s": 27666,
"text": null
},
{
"code": null,
"e": 28879,
"s": 28850,
"text": "output of the above program."
},
{
"code": null,
"e": 28915,
"s": 28879,
"text": "Code 2: Using getResource() method."
},
{
"code": null,
"e": 28920,
"s": 28915,
"text": "Java"
},
{
"code": "// Java program to load resources from Classpath// using getResource() method. import java.io.*;import java.net.URI;import java.net.URISyntaxException;import java.net.URL;import java.nio.charset.StandardCharsets;import java.nio.file.Files;import java.util.List; //save file as the name of GFG2public class GFG2 { //main class public static void main(String[] args) throws Exception { // creating object of the class // important since the getClass() method is // not static. GFG2 obj = new GFG2(); // name of the resource // the resource is stored in our base path of the // .class file. String fileName = \"GFG_text.txt\"; System.out.println(\"Getting the data of file \" + fileName); // getting the URL of the resource // and creating a file object to the given URL URL url = obj.getClass().getClassLoader().getResource(fileName); File file = new File(url.toURI()); // reading the file data // by creating a list of strings // of each line List<String> line; // method of files class to read all the lines of the // file specified. line = Files.readAllLines(file.toPath(), StandardCharsets.UTF_8); // reading the list of the line in the file. for(String s: line) System.out.println(s); }}",
"e": 30358,
"s": 28920,
"text": null
},
{
"code": null,
"e": 30386,
"s": 30358,
"text": "output for the second code."
},
{
"code": null,
"e": 30393,
"s": 30386,
"text": "Picked"
},
{
"code": null,
"e": 30417,
"s": 30393,
"text": "Technical Scripter 2020"
},
{
"code": null,
"e": 30422,
"s": 30417,
"text": "Java"
},
{
"code": null,
"e": 30436,
"s": 30422,
"text": "Java Programs"
},
{
"code": null,
"e": 30455,
"s": 30436,
"text": "Technical Scripter"
},
{
"code": null,
"e": 30460,
"s": 30455,
"text": "Java"
},
{
"code": null,
"e": 30558,
"s": 30460,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 30573,
"s": 30558,
"text": "Stream In Java"
},
{
"code": null,
"e": 30594,
"s": 30573,
"text": "Constructors in Java"
},
{
"code": null,
"e": 30613,
"s": 30594,
"text": "Exceptions in Java"
},
{
"code": null,
"e": 30643,
"s": 30613,
"text": "Functional Interfaces in Java"
},
{
"code": null,
"e": 30689,
"s": 30643,
"text": "Different ways of Reading a text file in Java"
},
{
"code": null,
"e": 30715,
"s": 30689,
"text": "Java Programming Examples"
},
{
"code": null,
"e": 30749,
"s": 30715,
"text": "Convert Double to Integer in Java"
},
{
"code": null,
"e": 30796,
"s": 30749,
"text": "Implementing a Linked List in Java using Class"
},
{
"code": null,
"e": 30828,
"s": 30796,
"text": "How to Iterate HashMap in Java?"
}
] |
How to apply !important in CSS? - GeeksforGeeks | 10 May, 2022
The !important property in CSS is used to provide more weight (importance) than normal property. In CSS, the !important means that “this is important”, ignore all the subsequent rules, and apply !important rule and the !important keyword must be placed at the end of the line, immediately before the semicolon.
In other words, it adds importance to all the sub-properties that the shorthand property represents.
In normal use, a rule defined in an external style sheet which is overruled by a style defined in the head of the document, which in turn, is overruled by an inline style within the element itself (assuming equal specificity of the selectors).
Defining a rule with the !important attribute that discards the normal concerns as regards the later rule overriding the earlier ones.
So, it is used for overriding the styles that are previously declared in other style sources, in order to achieve a certain design.
Syntax:
element {
color: blue !important;
font-size: 14px !important;
...
}
Example 1:
HTML
<!DOCTYPE html><html> <head> <title>Document</title> <style> h1 { color: blue ; } h1 { color:white !important; } body { background-color:green !important; text-align:center; background-color:yellow; } </style> </head> <body> <h1>GeeksforGeeks</h1> <h2>!important property</h2> <p></p> </body></html>
Output:
In the above example, the background color of the body is green instead of yellow because “!important” is kept after the green background color inside the body tag.
Example 2:
HTML
<!DOCTYPE html><html> <head> <title>!important property</title> <style> .geeks { color: green !important; size: 10ex !important; background-color: lightgray !important; } .geeks { color: red; size: 100ex; text-align:justify; background-color: purple; } h1, h2 { text-align:center; } h1 { color:green; } body { width:65%; margin-left:15%; } #gfg { color: lightgreen !important; size: 10ex !important; text-align:justify !important; background-color: darkgreen !important; } #gfg { color: orange; size: 1000ex; background-color: magenta; } </style> </head> <body> <h1>GeeksforGeeks</h1> <h2>!important property</h2> <div class = geeks> A Computer Science portal for geeks. It contains well written, well thought and well explained computer science and programming articles and quizzes. </div> <div id = gfg> <p>Computer programming is the process of writing instructions that get executed by computers. The instructions, also known as code, are written in a programming language which the computer can understand and use to perform a task or solve a problem.</p> </div> </body></html>
Output:
CSS is the foundation of webpages, is used for webpage development by styling websites and web apps. You can learn CSS from the ground up by following this CSS Tutorial and CSS Examples.
Attention reader! Don’t stop learning now. Get hold of all the important HTML concepts with the Web Design for Beginners | HTML course.
hardikkoriintern
CSS-Misc
Picked
CSS
HTML
Web Technologies
HTML
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Top 10 Projects For Beginners To Practice HTML and CSS Skills
How to insert spaces/tabs in text using HTML/CSS?
How to update Node.js and NPM to next version ?
How to create footer to stay at the bottom of a Web page?
How to apply style to parent if it has child with CSS?
Top 10 Projects For Beginners To Practice HTML and CSS Skills
How to insert spaces/tabs in text using HTML/CSS?
How to update Node.js and NPM to next version ?
How to set the default value for an HTML <select> element ?
Hide or show elements in HTML using display property | [
{
"code": null,
"e": 25975,
"s": 25947,
"text": "\n10 May, 2022"
},
{
"code": null,
"e": 26286,
"s": 25975,
"text": "The !important property in CSS is used to provide more weight (importance) than normal property. In CSS, the !important means that “this is important”, ignore all the subsequent rules, and apply !important rule and the !important keyword must be placed at the end of the line, immediately before the semicolon."
},
{
"code": null,
"e": 26387,
"s": 26286,
"text": "In other words, it adds importance to all the sub-properties that the shorthand property represents."
},
{
"code": null,
"e": 26631,
"s": 26387,
"text": "In normal use, a rule defined in an external style sheet which is overruled by a style defined in the head of the document, which in turn, is overruled by an inline style within the element itself (assuming equal specificity of the selectors)."
},
{
"code": null,
"e": 26766,
"s": 26631,
"text": "Defining a rule with the !important attribute that discards the normal concerns as regards the later rule overriding the earlier ones."
},
{
"code": null,
"e": 26898,
"s": 26766,
"text": "So, it is used for overriding the styles that are previously declared in other style sources, in order to achieve a certain design."
},
{
"code": null,
"e": 26906,
"s": 26898,
"text": "Syntax:"
},
{
"code": null,
"e": 26988,
"s": 26906,
"text": "element {\n color: blue !important;\n font-size: 14px !important; \n ...\n}"
},
{
"code": null,
"e": 27000,
"s": 26988,
"text": "Example 1: "
},
{
"code": null,
"e": 27005,
"s": 27000,
"text": "HTML"
},
{
"code": "<!DOCTYPE html><html> <head> <title>Document</title> <style> h1 { color: blue ; } h1 { color:white !important; } body { background-color:green !important; text-align:center; background-color:yellow; } </style> </head> <body> <h1>GeeksforGeeks</h1> <h2>!important property</h2> <p></p> </body></html> ",
"e": 27519,
"s": 27005,
"text": null
},
{
"code": null,
"e": 27527,
"s": 27519,
"text": "Output:"
},
{
"code": null,
"e": 27696,
"s": 27530,
"text": "In the above example, the background color of the body is green instead of yellow because “!important” is kept after the green background color inside the body tag. "
},
{
"code": null,
"e": 27708,
"s": 27696,
"text": "Example 2: "
},
{
"code": null,
"e": 27713,
"s": 27708,
"text": "HTML"
},
{
"code": "<!DOCTYPE html><html> <head> <title>!important property</title> <style> .geeks { color: green !important; size: 10ex !important; background-color: lightgray !important; } .geeks { color: red; size: 100ex; text-align:justify; background-color: purple; } h1, h2 { text-align:center; } h1 { color:green; } body { width:65%; margin-left:15%; } #gfg { color: lightgreen !important; size: 10ex !important; text-align:justify !important; background-color: darkgreen !important; } #gfg { color: orange; size: 1000ex; background-color: magenta; } </style> </head> <body> <h1>GeeksforGeeks</h1> <h2>!important property</h2> <div class = geeks> A Computer Science portal for geeks. It contains well written, well thought and well explained computer science and programming articles and quizzes. </div> <div id = gfg> <p>Computer programming is the process of writing instructions that get executed by computers. The instructions, also known as code, are written in a programming language which the computer can understand and use to perform a task or solve a problem.</p> </div> </body></html> ",
"e": 29407,
"s": 27713,
"text": null
},
{
"code": null,
"e": 29415,
"s": 29407,
"text": "Output:"
},
{
"code": null,
"e": 29604,
"s": 29417,
"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": 29741,
"s": 29604,
"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": 29758,
"s": 29741,
"text": "hardikkoriintern"
},
{
"code": null,
"e": 29767,
"s": 29758,
"text": "CSS-Misc"
},
{
"code": null,
"e": 29774,
"s": 29767,
"text": "Picked"
},
{
"code": null,
"e": 29778,
"s": 29774,
"text": "CSS"
},
{
"code": null,
"e": 29783,
"s": 29778,
"text": "HTML"
},
{
"code": null,
"e": 29800,
"s": 29783,
"text": "Web Technologies"
},
{
"code": null,
"e": 29805,
"s": 29800,
"text": "HTML"
},
{
"code": null,
"e": 29903,
"s": 29805,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 29965,
"s": 29903,
"text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills"
},
{
"code": null,
"e": 30015,
"s": 29965,
"text": "How to insert spaces/tabs in text using HTML/CSS?"
},
{
"code": null,
"e": 30063,
"s": 30015,
"text": "How to update Node.js and NPM to next version ?"
},
{
"code": null,
"e": 30121,
"s": 30063,
"text": "How to create footer to stay at the bottom of a Web page?"
},
{
"code": null,
"e": 30176,
"s": 30121,
"text": "How to apply style to parent if it has child with CSS?"
},
{
"code": null,
"e": 30238,
"s": 30176,
"text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills"
},
{
"code": null,
"e": 30288,
"s": 30238,
"text": "How to insert spaces/tabs in text using HTML/CSS?"
},
{
"code": null,
"e": 30336,
"s": 30288,
"text": "How to update Node.js and NPM to next version ?"
},
{
"code": null,
"e": 30396,
"s": 30336,
"text": "How to set the default value for an HTML <select> element ?"
}
] |
Design an IIR Bandpass Chebyshev Type-2 Filter using Scipy - Python - GeeksforGeeks | 10 Nov, 2021
IR stands for Infinite Impulse Response, It is one of the striking features of many linear-time invariant systems that are distinguished by having an impulse response h(t)/h(n) which does not become zero after some point but instead continues infinitely.
IIR Chebyshev is a filter that is linear-time invariant filter just like the Butterworth however, it has a steeper roll-off compared to the Butterworth Filter. Chebyshev Filter is further classified as Chebyshev Type-I and Chebyshev Type-II according to the parameters such as pass band ripple and stop ripple.
Chebyshev Filter has a steeper roll-off compared to the Butterworth Filter.
Chebyshev Type-2 minimizes the absolute difference between the ideal and actual frequency response over the entire stopband by incorporating an equal ripple in the stopband.
The specifications are as follows:
Pass band frequency: 1400-2100 Hz
Stop band frequency: 1050-24500 Hz
Pass band ripple: 0.4dB
Stop band attenuation: 50 dB
Sampling frequency: 7 kHz
We will plot the magnitude, phase, impulse, step response of the filter.
Step-by-step Approach:
Step 1: Importing all the necessary libraries.
Python3
# import required libraryimport numpy as npimport scipy.signal as signalimport matplotlib.pyplot as plt
Step 2: Defining user-defined functions mfreqz() and impz(). The mfreqz is a function for magnitude and phase plotand the impz is a function for impulse and step response]
Python3
def mfreqz(b, a, Fs): # Compute frequency response of the filter # using signal.freqz function wz, hz = signal.freqz(b, a) # Calculate Magnitude from hz in dB Mag = 20*np.log10(abs(hz)) # Calculate phase angle in degree from hz Phase = np.unwrap(np.arctan2(np.imag(hz), np.real(hz)))*(180/np.pi) # Calculate frequency in Hz from wz Freq = wz*Fs/(2*np.pi) # Plot filter magnitude and phase responses using subplot. fig = plt.figure(figsize=(10, 6)) # Plot Magnitude response sub1 = plt.subplot(2, 1, 1) sub1.plot(Freq, Mag, 'r', linewidth=2) sub1.axis([1, Fs/2, -100, 5]) sub1.set_title('Magnitude Response', fontsize=20) sub1.set_xlabel('Frequency [Hz]', fontsize=20) sub1.set_ylabel('Magnitude [dB]', fontsize=20) sub1.grid() # Plot phase angle sub2 = plt.subplot(2, 1, 2) sub2.plot(Freq, Phase, 'g', linewidth=2) sub2.set_ylabel('Phase (degree)', fontsize=20) sub2.set_xlabel(r'Frequency (Hz)', fontsize=20) sub2.set_title(r'Phase response', fontsize=20) sub2.grid() plt.subplots_adjust(hspace=0.5) fig.tight_layout() plt.show() # Define impz(b,a) to calculate impulse# response and step response of a system# input: b= an array containing numerator# coefficients,a= an array containing# denominator coefficientsdef impz(b, a): # Define the impulse sequence of length 60 impulse = np.repeat(0., 60) impulse[0] = 1. x = np.arange(0, 60) # Compute the impulse response response = signal.lfilter(b, a, impulse) # Plot filter impulse and step response: fig = plt.figure(figsize=(10, 6)) plt.subplot(211) plt.stem(x, response, 'm', use_line_collection=True) plt.ylabel('Amplitude', fontsize=15) plt.xlabel(r'n (samples)', fontsize=15) plt.title(r'Impulse response', fontsize=15) plt.subplot(212) step = np.cumsum(response) plt.stem(x, step, 'g', use_line_collection=True) plt.ylabel('Amplitude', fontsize=15) plt.xlabel(r'n (samples)', fontsize=15) plt.title(r'Step response', fontsize=15) plt.subplots_adjust(hspace=0.5) fig.tight_layout() plt.show()
Step 3:Define variables with the given specifications of the filter.
Python3
# Given specification # Sampling frequency in HzFs = 7000 # Pass band frequency in Hzfp = np.array([1400, 2100]) # Stop band frequency in Hzfs = np.array([1050, 2450]) # Pass band ripple in dBAp = 0.4 # Stop band attenuation in dBAs = 50
Step 4: Compute the cut-off frequency
Python3
# Compute pass band and stop band edge frequencies # Normalized passband edge# frequencies w.r.t. Nyquist ratewp = fp/(Fs/2) # Normalized stopband# edge frequenciesws = fs/(Fs/2)
Step 5: Compute order of the Chebyshev type-2 digital filter.
Python3
# Compute order of the Chebyshev type-2# digital filter using signal.cheb2ordN, wc = signal.cheb2ord(wp, ws, Ap, As) # Print the order of the filter# and cutoff frequenciesprint('Order of the filter=', N)print('Cut-off frequency=', wc)
Output:
Step 6: Design digital Chebyshev type-2 bandpass filter.
Python3
# Design digital Chebyshev type-2 bandpass# filter using signal.cheby2 functionz, p = signal.cheby2(N, As, wc, 'bandpass') # Print numerator and denomerator# coefficients of the filterprint('Numerator Coefficients:', z)print('Denominator Coefficients:', p)
Output:
Step 7: Plot magnitude and phase response.
Python3
# Call mfreqz to plot the# magnitude and phase responsemfreqz(z, p, Fs)
Output:
Step 8: Plot impulse and step response of the filter.
Python3
# Call impz function to plot impulse# and step response of the filterimpz(z, p)
Output:
Below is the complete implementation of the above stepwise approach:
Python3
# import required libraryimport numpy as npimport scipy.signal as signalimport matplotlib.pyplot as plt def mfreqz(b, a, Fs): # Compute frequency response of the # filter using signal.freqz function wz, hz = signal.freqz(b, a) # Calculate Magnitude from hz in dB Mag = 20*np.log10(abs(hz)) # Calculate phase angle in degree from hz Phase = np.unwrap(np.arctan2(np.imag(hz), np.real(hz)))*(180/np.pi) # Calculate frequency in Hz from wz Freq = wz*Fs/(2*np.pi) # Plot filter magnitude and phase responses using subplot. fig = plt.figure(figsize=(10, 6)) # Plot Magnitude response sub1 = plt.subplot(2, 1, 1) sub1.plot(Freq, Mag, 'r', linewidth=2) sub1.axis([1, Fs/2, -100, 5]) sub1.set_title('Magnitude Response', fontsize=20) sub1.set_xlabel('Frequency [Hz]', fontsize=20) sub1.set_ylabel('Magnitude [dB]', fontsize=20) sub1.grid() # Plot phase angle sub2 = plt.subplot(2, 1, 2) sub2.plot(Freq, Phase, 'g', linewidth=2) sub2.set_ylabel('Phase (degree)', fontsize=20) sub2.set_xlabel(r'Frequency (Hz)', fontsize=20) sub2.set_title(r'Phase response', fontsize=20) sub2.grid() plt.subplots_adjust(hspace=0.5) fig.tight_layout() plt.show() # Define impz(b,a) to calculate impulse# response and step response of a system# input: b= an array containing numerator# coefficients,a= an array containing# denominator coefficientsdef impz(b, a): # Define the impulse sequence of length 60 impulse = np.repeat(0., 60) impulse[0] = 1. x = np.arange(0, 60) # Compute the impulse response response = signal.lfilter(b, a, impulse) # Plot filter impulse and step response: fig = plt.figure(figsize=(10, 6)) plt.subplot(211) plt.stem(x, response, 'm', use_line_collection=True) plt.ylabel('Amplitude', fontsize=15) plt.xlabel(r'n (samples)', fontsize=15) plt.title(r'Impulse response', fontsize=15) plt.subplot(212) step = np.cumsum(response) # Compute step response of the system plt.stem(x, step, 'g', use_line_collection=True) plt.ylabel('Amplitude', fontsize=15) plt.xlabel(r'n (samples)', fontsize=15) plt.title(r'Step response', fontsize=15) plt.subplots_adjust(hspace=0.5) fig.tight_layout() plt.show() # Given specification # Sampling frequency in HzFs = 7000 # Pass band frequency in Hzfp = np.array([1400, 2100]) # Stop band frequency in Hzfs = np.array([1050, 2450]) # Pass band ripple in dBAp = 0.4 # Stop band attenuation in dBAs = 50 # Compute pass band and# stop band edge frequencies # Normalized passband edge frequencies w.r.t. Nyquist ratewp = fp/(Fs/2) # Normalized stopband edge frequenciesws = fs/(Fs/2) # Compute order of the Chebyshev type-2# digital filter using signal.cheb2ordN, wc = signal.cheb2ord(wp, ws, Ap, As) # Print the order of the filter and cutoff frequenciesprint('Order of the filter=', N)print('Cut-off frequency=', wc) # Design digital Chebyshev type-2 bandpass# filter using signal.cheby2 functionz, p = signal.cheby2(N, As, wc, 'bandpass') # Print numerator and denomerator coefficients of the filterprint('Numerator Coefficients:', z)print('Denominator Coefficients:', p) # Call mfreqz to plot the# magnitude and phase responsemfreqz(z, p, Fs) # Call impz function to plot impulse# and step response of the filterimpz(z, p)
gulshankumarar231
Data Visualization
Python-matplotlib
Python-scipy
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Install PIP on Windows ?
Check if element exists in list in Python
How To Convert Python Dictionary To JSON?
How to drop one or multiple columns in Pandas Dataframe
Python Classes and Objects
Python | os.path.join() method
Python | Get unique values from a list
Create a directory in Python
Defaultdict in Python
Python | Pandas dataframe.groupby() | [
{
"code": null,
"e": 25537,
"s": 25509,
"text": "\n10 Nov, 2021"
},
{
"code": null,
"e": 25792,
"s": 25537,
"text": "IR stands for Infinite Impulse Response, It is one of the striking features of many linear-time invariant systems that are distinguished by having an impulse response h(t)/h(n) which does not become zero after some point but instead continues infinitely."
},
{
"code": null,
"e": 26103,
"s": 25792,
"text": "IIR Chebyshev is a filter that is linear-time invariant filter just like the Butterworth however, it has a steeper roll-off compared to the Butterworth Filter. Chebyshev Filter is further classified as Chebyshev Type-I and Chebyshev Type-II according to the parameters such as pass band ripple and stop ripple."
},
{
"code": null,
"e": 26179,
"s": 26103,
"text": "Chebyshev Filter has a steeper roll-off compared to the Butterworth Filter."
},
{
"code": null,
"e": 26353,
"s": 26179,
"text": "Chebyshev Type-2 minimizes the absolute difference between the ideal and actual frequency response over the entire stopband by incorporating an equal ripple in the stopband."
},
{
"code": null,
"e": 26390,
"s": 26353,
"text": "The specifications are as follows: "
},
{
"code": null,
"e": 26424,
"s": 26390,
"text": "Pass band frequency: 1400-2100 Hz"
},
{
"code": null,
"e": 26459,
"s": 26424,
"text": "Stop band frequency: 1050-24500 Hz"
},
{
"code": null,
"e": 26483,
"s": 26459,
"text": "Pass band ripple: 0.4dB"
},
{
"code": null,
"e": 26512,
"s": 26483,
"text": "Stop band attenuation: 50 dB"
},
{
"code": null,
"e": 26538,
"s": 26512,
"text": "Sampling frequency: 7 kHz"
},
{
"code": null,
"e": 26611,
"s": 26538,
"text": "We will plot the magnitude, phase, impulse, step response of the filter."
},
{
"code": null,
"e": 26634,
"s": 26611,
"text": "Step-by-step Approach:"
},
{
"code": null,
"e": 26681,
"s": 26634,
"text": "Step 1: Importing all the necessary libraries."
},
{
"code": null,
"e": 26689,
"s": 26681,
"text": "Python3"
},
{
"code": "# import required libraryimport numpy as npimport scipy.signal as signalimport matplotlib.pyplot as plt",
"e": 26793,
"s": 26689,
"text": null
},
{
"code": null,
"e": 26965,
"s": 26793,
"text": "Step 2: Defining user-defined functions mfreqz() and impz(). The mfreqz is a function for magnitude and phase plotand the impz is a function for impulse and step response]"
},
{
"code": null,
"e": 26973,
"s": 26965,
"text": "Python3"
},
{
"code": "def mfreqz(b, a, Fs): # Compute frequency response of the filter # using signal.freqz function wz, hz = signal.freqz(b, a) # Calculate Magnitude from hz in dB Mag = 20*np.log10(abs(hz)) # Calculate phase angle in degree from hz Phase = np.unwrap(np.arctan2(np.imag(hz), np.real(hz)))*(180/np.pi) # Calculate frequency in Hz from wz Freq = wz*Fs/(2*np.pi) # Plot filter magnitude and phase responses using subplot. fig = plt.figure(figsize=(10, 6)) # Plot Magnitude response sub1 = plt.subplot(2, 1, 1) sub1.plot(Freq, Mag, 'r', linewidth=2) sub1.axis([1, Fs/2, -100, 5]) sub1.set_title('Magnitude Response', fontsize=20) sub1.set_xlabel('Frequency [Hz]', fontsize=20) sub1.set_ylabel('Magnitude [dB]', fontsize=20) sub1.grid() # Plot phase angle sub2 = plt.subplot(2, 1, 2) sub2.plot(Freq, Phase, 'g', linewidth=2) sub2.set_ylabel('Phase (degree)', fontsize=20) sub2.set_xlabel(r'Frequency (Hz)', fontsize=20) sub2.set_title(r'Phase response', fontsize=20) sub2.grid() plt.subplots_adjust(hspace=0.5) fig.tight_layout() plt.show() # Define impz(b,a) to calculate impulse# response and step response of a system# input: b= an array containing numerator# coefficients,a= an array containing# denominator coefficientsdef impz(b, a): # Define the impulse sequence of length 60 impulse = np.repeat(0., 60) impulse[0] = 1. x = np.arange(0, 60) # Compute the impulse response response = signal.lfilter(b, a, impulse) # Plot filter impulse and step response: fig = plt.figure(figsize=(10, 6)) plt.subplot(211) plt.stem(x, response, 'm', use_line_collection=True) plt.ylabel('Amplitude', fontsize=15) plt.xlabel(r'n (samples)', fontsize=15) plt.title(r'Impulse response', fontsize=15) plt.subplot(212) step = np.cumsum(response) plt.stem(x, step, 'g', use_line_collection=True) plt.ylabel('Amplitude', fontsize=15) plt.xlabel(r'n (samples)', fontsize=15) plt.title(r'Step response', fontsize=15) plt.subplots_adjust(hspace=0.5) fig.tight_layout() plt.show()",
"e": 29092,
"s": 26973,
"text": null
},
{
"code": null,
"e": 29161,
"s": 29092,
"text": "Step 3:Define variables with the given specifications of the filter."
},
{
"code": null,
"e": 29169,
"s": 29161,
"text": "Python3"
},
{
"code": "# Given specification # Sampling frequency in HzFs = 7000 # Pass band frequency in Hzfp = np.array([1400, 2100]) # Stop band frequency in Hzfs = np.array([1050, 2450]) # Pass band ripple in dBAp = 0.4 # Stop band attenuation in dBAs = 50 ",
"e": 29411,
"s": 29169,
"text": null
},
{
"code": null,
"e": 29449,
"s": 29411,
"text": "Step 4: Compute the cut-off frequency"
},
{
"code": null,
"e": 29457,
"s": 29449,
"text": "Python3"
},
{
"code": "# Compute pass band and stop band edge frequencies # Normalized passband edge# frequencies w.r.t. Nyquist ratewp = fp/(Fs/2) # Normalized stopband# edge frequenciesws = fs/(Fs/2)",
"e": 29637,
"s": 29457,
"text": null
},
{
"code": null,
"e": 29699,
"s": 29637,
"text": "Step 5: Compute order of the Chebyshev type-2 digital filter."
},
{
"code": null,
"e": 29707,
"s": 29699,
"text": "Python3"
},
{
"code": "# Compute order of the Chebyshev type-2# digital filter using signal.cheb2ordN, wc = signal.cheb2ord(wp, ws, Ap, As) # Print the order of the filter# and cutoff frequenciesprint('Order of the filter=', N)print('Cut-off frequency=', wc)",
"e": 29943,
"s": 29707,
"text": null
},
{
"code": null,
"e": 29951,
"s": 29943,
"text": "Output:"
},
{
"code": null,
"e": 30008,
"s": 29951,
"text": "Step 6: Design digital Chebyshev type-2 bandpass filter."
},
{
"code": null,
"e": 30016,
"s": 30008,
"text": "Python3"
},
{
"code": "# Design digital Chebyshev type-2 bandpass# filter using signal.cheby2 functionz, p = signal.cheby2(N, As, wc, 'bandpass') # Print numerator and denomerator# coefficients of the filterprint('Numerator Coefficients:', z)print('Denominator Coefficients:', p)",
"e": 30274,
"s": 30016,
"text": null
},
{
"code": null,
"e": 30282,
"s": 30274,
"text": "Output:"
},
{
"code": null,
"e": 30325,
"s": 30282,
"text": "Step 7: Plot magnitude and phase response."
},
{
"code": null,
"e": 30333,
"s": 30325,
"text": "Python3"
},
{
"code": "# Call mfreqz to plot the# magnitude and phase responsemfreqz(z, p, Fs)",
"e": 30405,
"s": 30333,
"text": null
},
{
"code": null,
"e": 30413,
"s": 30405,
"text": "Output:"
},
{
"code": null,
"e": 30467,
"s": 30413,
"text": "Step 8: Plot impulse and step response of the filter."
},
{
"code": null,
"e": 30475,
"s": 30467,
"text": "Python3"
},
{
"code": "# Call impz function to plot impulse# and step response of the filterimpz(z, p)",
"e": 30555,
"s": 30475,
"text": null
},
{
"code": null,
"e": 30563,
"s": 30555,
"text": "Output:"
},
{
"code": null,
"e": 30632,
"s": 30563,
"text": "Below is the complete implementation of the above stepwise approach:"
},
{
"code": null,
"e": 30640,
"s": 30632,
"text": "Python3"
},
{
"code": "# import required libraryimport numpy as npimport scipy.signal as signalimport matplotlib.pyplot as plt def mfreqz(b, a, Fs): # Compute frequency response of the # filter using signal.freqz function wz, hz = signal.freqz(b, a) # Calculate Magnitude from hz in dB Mag = 20*np.log10(abs(hz)) # Calculate phase angle in degree from hz Phase = np.unwrap(np.arctan2(np.imag(hz), np.real(hz)))*(180/np.pi) # Calculate frequency in Hz from wz Freq = wz*Fs/(2*np.pi) # Plot filter magnitude and phase responses using subplot. fig = plt.figure(figsize=(10, 6)) # Plot Magnitude response sub1 = plt.subplot(2, 1, 1) sub1.plot(Freq, Mag, 'r', linewidth=2) sub1.axis([1, Fs/2, -100, 5]) sub1.set_title('Magnitude Response', fontsize=20) sub1.set_xlabel('Frequency [Hz]', fontsize=20) sub1.set_ylabel('Magnitude [dB]', fontsize=20) sub1.grid() # Plot phase angle sub2 = plt.subplot(2, 1, 2) sub2.plot(Freq, Phase, 'g', linewidth=2) sub2.set_ylabel('Phase (degree)', fontsize=20) sub2.set_xlabel(r'Frequency (Hz)', fontsize=20) sub2.set_title(r'Phase response', fontsize=20) sub2.grid() plt.subplots_adjust(hspace=0.5) fig.tight_layout() plt.show() # Define impz(b,a) to calculate impulse# response and step response of a system# input: b= an array containing numerator# coefficients,a= an array containing# denominator coefficientsdef impz(b, a): # Define the impulse sequence of length 60 impulse = np.repeat(0., 60) impulse[0] = 1. x = np.arange(0, 60) # Compute the impulse response response = signal.lfilter(b, a, impulse) # Plot filter impulse and step response: fig = plt.figure(figsize=(10, 6)) plt.subplot(211) plt.stem(x, response, 'm', use_line_collection=True) plt.ylabel('Amplitude', fontsize=15) plt.xlabel(r'n (samples)', fontsize=15) plt.title(r'Impulse response', fontsize=15) plt.subplot(212) step = np.cumsum(response) # Compute step response of the system plt.stem(x, step, 'g', use_line_collection=True) plt.ylabel('Amplitude', fontsize=15) plt.xlabel(r'n (samples)', fontsize=15) plt.title(r'Step response', fontsize=15) plt.subplots_adjust(hspace=0.5) fig.tight_layout() plt.show() # Given specification # Sampling frequency in HzFs = 7000 # Pass band frequency in Hzfp = np.array([1400, 2100]) # Stop band frequency in Hzfs = np.array([1050, 2450]) # Pass band ripple in dBAp = 0.4 # Stop band attenuation in dBAs = 50 # Compute pass band and# stop band edge frequencies # Normalized passband edge frequencies w.r.t. Nyquist ratewp = fp/(Fs/2) # Normalized stopband edge frequenciesws = fs/(Fs/2) # Compute order of the Chebyshev type-2# digital filter using signal.cheb2ordN, wc = signal.cheb2ord(wp, ws, Ap, As) # Print the order of the filter and cutoff frequenciesprint('Order of the filter=', N)print('Cut-off frequency=', wc) # Design digital Chebyshev type-2 bandpass# filter using signal.cheby2 functionz, p = signal.cheby2(N, As, wc, 'bandpass') # Print numerator and denomerator coefficients of the filterprint('Numerator Coefficients:', z)print('Denominator Coefficients:', p) # Call mfreqz to plot the# magnitude and phase responsemfreqz(z, p, Fs) # Call impz function to plot impulse# and step response of the filterimpz(z, p)",
"e": 33976,
"s": 30640,
"text": null
},
{
"code": null,
"e": 33994,
"s": 33976,
"text": "gulshankumarar231"
},
{
"code": null,
"e": 34013,
"s": 33994,
"text": "Data Visualization"
},
{
"code": null,
"e": 34031,
"s": 34013,
"text": "Python-matplotlib"
},
{
"code": null,
"e": 34044,
"s": 34031,
"text": "Python-scipy"
},
{
"code": null,
"e": 34051,
"s": 34044,
"text": "Python"
},
{
"code": null,
"e": 34149,
"s": 34051,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 34181,
"s": 34149,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 34223,
"s": 34181,
"text": "Check if element exists in list in Python"
},
{
"code": null,
"e": 34265,
"s": 34223,
"text": "How To Convert Python Dictionary To JSON?"
},
{
"code": null,
"e": 34321,
"s": 34265,
"text": "How to drop one or multiple columns in Pandas Dataframe"
},
{
"code": null,
"e": 34348,
"s": 34321,
"text": "Python Classes and Objects"
},
{
"code": null,
"e": 34379,
"s": 34348,
"text": "Python | os.path.join() method"
},
{
"code": null,
"e": 34418,
"s": 34379,
"text": "Python | Get unique values from a list"
},
{
"code": null,
"e": 34447,
"s": 34418,
"text": "Create a directory in Python"
},
{
"code": null,
"e": 34469,
"s": 34447,
"text": "Defaultdict in Python"
}
] |
Java Program to convert integer to boolean - GeeksforGeeks | 02 Jan, 2020
Given a integer value, the task is to convert this integer value into a boolean value in Java.
Examples:
Input: int = 1
Output: true
Input: int = 0
Output: false
Approach:
Get the boolean value to be converted.
Check if boolean value is true or false
If the integer value is greater than equal to 1, set the boolean value as true.
Else if the integer value is greater than 1, set the boolean value as false.
Example 1:
// Java Program to convert integer to boolean public class GFG { public static void main(String[] args) { // The integer value int intValue = 1; // The expected boolean value boolean boolValue; // Check if it's greater than equal to 1 if (intValue >= 1) { boolValue = true; } else { boolValue = false; } // Print the expected integer value System.out.println( intValue + " after converting into boolean = " + boolValue); }}
1 after converting into boolean = true
Example 2:
// Java Program to convert integer to boolean public class GFG { public static void main(String[] args) { // The integer value int intValue = 0; // The expected boolean value boolean boolValue; // Check if it's greater than equal to 1 if (intValue >= 1) { boolValue = true; } else { boolValue = false; } // Print the expected integer value System.out.println( intValue + " after converting into boolean = " + boolValue); }}
0 after converting into boolean = false
Java
Java Programs
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Object Oriented Programming (OOPs) Concept in Java
HashMap in Java with Examples
Stream In Java
Interfaces in Java
How to iterate any Map in Java
Initializing a List in Java
Convert a String to Character Array in Java
Java Programming Examples
Convert Double to Integer in Java
Implementing a Linked List in Java using Class | [
{
"code": null,
"e": 25705,
"s": 25677,
"text": "\n02 Jan, 2020"
},
{
"code": null,
"e": 25800,
"s": 25705,
"text": "Given a integer value, the task is to convert this integer value into a boolean value in Java."
},
{
"code": null,
"e": 25810,
"s": 25800,
"text": "Examples:"
},
{
"code": null,
"e": 25869,
"s": 25810,
"text": "Input: int = 1\nOutput: true\n\nInput: int = 0\nOutput: false\n"
},
{
"code": null,
"e": 25879,
"s": 25869,
"text": "Approach:"
},
{
"code": null,
"e": 25918,
"s": 25879,
"text": "Get the boolean value to be converted."
},
{
"code": null,
"e": 25958,
"s": 25918,
"text": "Check if boolean value is true or false"
},
{
"code": null,
"e": 26038,
"s": 25958,
"text": "If the integer value is greater than equal to 1, set the boolean value as true."
},
{
"code": null,
"e": 26115,
"s": 26038,
"text": "Else if the integer value is greater than 1, set the boolean value as false."
},
{
"code": null,
"e": 26126,
"s": 26115,
"text": "Example 1:"
},
{
"code": "// Java Program to convert integer to boolean public class GFG { public static void main(String[] args) { // The integer value int intValue = 1; // The expected boolean value boolean boolValue; // Check if it's greater than equal to 1 if (intValue >= 1) { boolValue = true; } else { boolValue = false; } // Print the expected integer value System.out.println( intValue + \" after converting into boolean = \" + boolValue); }}",
"e": 26702,
"s": 26126,
"text": null
},
{
"code": null,
"e": 26742,
"s": 26702,
"text": "1 after converting into boolean = true\n"
},
{
"code": null,
"e": 26753,
"s": 26742,
"text": "Example 2:"
},
{
"code": "// Java Program to convert integer to boolean public class GFG { public static void main(String[] args) { // The integer value int intValue = 0; // The expected boolean value boolean boolValue; // Check if it's greater than equal to 1 if (intValue >= 1) { boolValue = true; } else { boolValue = false; } // Print the expected integer value System.out.println( intValue + \" after converting into boolean = \" + boolValue); }}",
"e": 27329,
"s": 26753,
"text": null
},
{
"code": null,
"e": 27370,
"s": 27329,
"text": "0 after converting into boolean = false\n"
},
{
"code": null,
"e": 27375,
"s": 27370,
"text": "Java"
},
{
"code": null,
"e": 27389,
"s": 27375,
"text": "Java Programs"
},
{
"code": null,
"e": 27394,
"s": 27389,
"text": "Java"
},
{
"code": null,
"e": 27492,
"s": 27394,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 27543,
"s": 27492,
"text": "Object Oriented Programming (OOPs) Concept in Java"
},
{
"code": null,
"e": 27573,
"s": 27543,
"text": "HashMap in Java with Examples"
},
{
"code": null,
"e": 27588,
"s": 27573,
"text": "Stream In Java"
},
{
"code": null,
"e": 27607,
"s": 27588,
"text": "Interfaces in Java"
},
{
"code": null,
"e": 27638,
"s": 27607,
"text": "How to iterate any Map in Java"
},
{
"code": null,
"e": 27666,
"s": 27638,
"text": "Initializing a List in Java"
},
{
"code": null,
"e": 27710,
"s": 27666,
"text": "Convert a String to Character Array in Java"
},
{
"code": null,
"e": 27736,
"s": 27710,
"text": "Java Programming Examples"
},
{
"code": null,
"e": 27770,
"s": 27736,
"text": "Convert Double to Integer in Java"
}
] |
Template Inheritance in Flask - GeeksforGeeks | 05 Sep, 2020
Template inheritance is a very good feature of Jinja templating . Jinja is a web template engine for the Python programming language . We have seen that webpages of a website contains same footer , navigation bar etc. So instead of making same footer and navigation bar in all webpages separately , we make use of template inheritance , which allows us to create the part which is same in all webpages (eg. footer,navigation bar) only once and we also don’t need to write the html , head , title tag again and again . Lets define the common structure of web pages in base.html file. First of all we will render template using flask from main.py file .
Prerequisite – Flask – (Creating first simple application)
Step 1 – Create a flask app to render the main template
Python3
from flask import Flask, render_template # Setting up the applicationapp = Flask(__name__) # making route @app.route('/')def home(): return render_template('home.html') # running applicationif __name__ == '__main__': app.run(debug=True)
Step 2 – Create HTML Files
Now we will set up our base.html file in which we have one heading which will be common in all webpages.
Syntax :
{% block content %}
{% endblock %}
The code above and below these lines will be the same for every web pages and the code between them will be for a specific web page .
HTML
<!DOCTYPE html><html lang="en"><head> <title>Template Inheritance</title></head><body> <h1> This heading is common in all webpages </h1> {% block content %} {% endblock %} </body></html>
Now we will set up our home.html file in which we will inherit template from “base.html” file and will write some code for
home page also .
Syntax :
{% extends "base.html" %}
{% block content %}
write code here for home page only
{% endblock %}
HTML
{%extends "base.html" %}{%block content%} <h1>Welcome to Home</h1> {% endblock %}
Run your main.py file .
Output –
Below is the output.
This article is just a simple example. We can also add navigation bar , footer , etc to base.html file and can inherit to home.html file and many others .
Python Flask
Python
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python Dictionary
Read a file line by line in Python
How to Install PIP on Windows ?
Different ways to create Pandas Dataframe
Python String | replace()
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": 25647,
"s": 25619,
"text": "\n05 Sep, 2020"
},
{
"code": null,
"e": 26301,
"s": 25647,
"text": "Template inheritance is a very good feature of Jinja templating . Jinja is a web template engine for the Python programming language . We have seen that webpages of a website contains same footer , navigation bar etc. So instead of making same footer and navigation bar in all webpages separately , we make use of template inheritance , which allows us to create the part which is same in all webpages (eg. footer,navigation bar) only once and we also don’t need to write the html , head , title tag again and again . Lets define the common structure of web pages in base.html file. First of all we will render template using flask from main.py file ."
},
{
"code": null,
"e": 26361,
"s": 26301,
"text": "Prerequisite – Flask – (Creating first simple application)"
},
{
"code": null,
"e": 26420,
"s": 26363,
"text": "Step 1 – Create a flask app to render the main template "
},
{
"code": null,
"e": 26428,
"s": 26420,
"text": "Python3"
},
{
"code": "from flask import Flask, render_template # Setting up the applicationapp = Flask(__name__) # making route @app.route('/')def home(): return render_template('home.html') # running applicationif __name__ == '__main__': app.run(debug=True)",
"e": 26679,
"s": 26428,
"text": null
},
{
"code": null,
"e": 26706,
"s": 26679,
"text": "Step 2 – Create HTML Files"
},
{
"code": null,
"e": 26812,
"s": 26706,
"text": "Now we will set up our base.html file in which we have one heading which will be common in all webpages. "
},
{
"code": null,
"e": 26822,
"s": 26812,
"text": "Syntax : "
},
{
"code": null,
"e": 26857,
"s": 26822,
"text": "{% block content %}\n{% endblock %}"
},
{
"code": null,
"e": 26992,
"s": 26857,
"text": "The code above and below these lines will be the same for every web pages and the code between them will be for a specific web page . "
},
{
"code": null,
"e": 26997,
"s": 26992,
"text": "HTML"
},
{
"code": "<!DOCTYPE html><html lang=\"en\"><head> <title>Template Inheritance</title></head><body> <h1> This heading is common in all webpages </h1> {% block content %} {% endblock %} </body></html>",
"e": 27197,
"s": 26997,
"text": null
},
{
"code": null,
"e": 27324,
"s": 27200,
"text": "Now we will set up our home.html file in which we will inherit template from “base.html” file and will write some code for "
},
{
"code": null,
"e": 27342,
"s": 27324,
"text": "home page also . "
},
{
"code": null,
"e": 27351,
"s": 27342,
"text": "Syntax :"
},
{
"code": null,
"e": 27476,
"s": 27351,
"text": " {% extends \"base.html\" %}\n {% block content %}\n write code here for home page only \n {% endblock %}"
},
{
"code": null,
"e": 27481,
"s": 27476,
"text": "HTML"
},
{
"code": "{%extends \"base.html\" %}{%block content%} <h1>Welcome to Home</h1> {% endblock %}",
"e": 27565,
"s": 27481,
"text": null
},
{
"code": null,
"e": 27597,
"s": 27572,
"text": "Run your main.py file . "
},
{
"code": null,
"e": 27607,
"s": 27597,
"text": "Output – "
},
{
"code": null,
"e": 27628,
"s": 27607,
"text": "Below is the output."
},
{
"code": null,
"e": 27792,
"s": 27637,
"text": "This article is just a simple example. We can also add navigation bar , footer , etc to base.html file and can inherit to home.html file and many others ."
},
{
"code": null,
"e": 27805,
"s": 27792,
"text": "Python Flask"
},
{
"code": null,
"e": 27812,
"s": 27805,
"text": "Python"
},
{
"code": null,
"e": 27829,
"s": 27812,
"text": "Web Technologies"
},
{
"code": null,
"e": 27927,
"s": 27829,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 27945,
"s": 27927,
"text": "Python Dictionary"
},
{
"code": null,
"e": 27980,
"s": 27945,
"text": "Read a file line by line in Python"
},
{
"code": null,
"e": 28012,
"s": 27980,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 28054,
"s": 28012,
"text": "Different ways to create Pandas Dataframe"
},
{
"code": null,
"e": 28080,
"s": 28054,
"text": "Python String | replace()"
},
{
"code": null,
"e": 28120,
"s": 28080,
"text": "Remove elements from a JavaScript Array"
},
{
"code": null,
"e": 28153,
"s": 28120,
"text": "Installation of Node.js on Linux"
},
{
"code": null,
"e": 28198,
"s": 28153,
"text": "Convert a string to an integer in JavaScript"
},
{
"code": null,
"e": 28241,
"s": 28198,
"text": "How to fetch data from an API in ReactJS ?"
}
] |
Python | Harmonic Mean of List - GeeksforGeeks | 14 Jan, 2020
While working with Python, we can have a problem in which we need to find harmonic mean of a list cumulative. This problem is common in Data Science domain. Let’s discuss certain ways in which this problem can be solved.
Method #1 : Using loop + formulaThe simpler manner to approach this problem is to employ the formula for finding harmonic mean and perform using loop shorthands. This is the most basic approach to solve this problem.
# Python3 code to demonstrate working of# Harmonic Mean of List# using loop + formula # initialize listtest_list = [6, 7, 3, 9, 10, 15] # printing original listprint("The original list is : " + str(test_list)) # Harmonic Mean of List# using loop + formulasum = 0for ele in test_list: sum += 1 / ele res = len(test_list)/sum # printing resultprint("The harmonic mean of list is : " + str(res))
The original list is : [6, 7, 3, 9, 10, 15]
The harmonic mean of list is : 6.517241379310345
Method #2 : Using statistics.harmonic_mean()This task can also be performed using inbuilt function of harmonic_mean(). This is new in Python versions >= 3.8.
# Python3 code to demonstrate working of# Harmonic Mean of List# using statistics.harmonic_mean()import statistics # initialize listtest_list = [6, 7, 3, 9, 10, 15] # printing original listprint("The original list is : " + str(test_list)) # Harmonic Mean of List# using statistics.harmonic_mean()res = statistics.harmonic_mean(test_list) # printing resultprint("The harmomin mean of list is : " + str(res))
The original list is : [6, 7, 3, 9, 10, 15]
The harmonic mean of list is : 6.517241379310345
Python list-programs
Python
Python Programs
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python Dictionary
Read a file line by line in Python
How to Install PIP on Windows ?
Enumerate() in Python
Different ways to create Pandas Dataframe
Python program to convert a list to string
Defaultdict in Python
Python | Get dictionary keys as a list
Python | Split string into list of characters
Python | Convert a list to dictionary | [
{
"code": null,
"e": 25435,
"s": 25407,
"text": "\n14 Jan, 2020"
},
{
"code": null,
"e": 25656,
"s": 25435,
"text": "While working with Python, we can have a problem in which we need to find harmonic mean of a list cumulative. This problem is common in Data Science domain. Let’s discuss certain ways in which this problem can be solved."
},
{
"code": null,
"e": 25873,
"s": 25656,
"text": "Method #1 : Using loop + formulaThe simpler manner to approach this problem is to employ the formula for finding harmonic mean and perform using loop shorthands. This is the most basic approach to solve this problem."
},
{
"code": "# Python3 code to demonstrate working of# Harmonic Mean of List# using loop + formula # initialize listtest_list = [6, 7, 3, 9, 10, 15] # printing original listprint(\"The original list is : \" + str(test_list)) # Harmonic Mean of List# using loop + formulasum = 0for ele in test_list: sum += 1 / ele res = len(test_list)/sum # printing resultprint(\"The harmonic mean of list is : \" + str(res))",
"e": 26276,
"s": 25873,
"text": null
},
{
"code": null,
"e": 26370,
"s": 26276,
"text": "The original list is : [6, 7, 3, 9, 10, 15]\nThe harmonic mean of list is : 6.517241379310345\n"
},
{
"code": null,
"e": 26530,
"s": 26372,
"text": "Method #2 : Using statistics.harmonic_mean()This task can also be performed using inbuilt function of harmonic_mean(). This is new in Python versions >= 3.8."
},
{
"code": "# Python3 code to demonstrate working of# Harmonic Mean of List# using statistics.harmonic_mean()import statistics # initialize listtest_list = [6, 7, 3, 9, 10, 15] # printing original listprint(\"The original list is : \" + str(test_list)) # Harmonic Mean of List# using statistics.harmonic_mean()res = statistics.harmonic_mean(test_list) # printing resultprint(\"The harmomin mean of list is : \" + str(res))",
"e": 26942,
"s": 26530,
"text": null
},
{
"code": null,
"e": 27036,
"s": 26942,
"text": "The original list is : [6, 7, 3, 9, 10, 15]\nThe harmonic mean of list is : 6.517241379310345\n"
},
{
"code": null,
"e": 27057,
"s": 27036,
"text": "Python list-programs"
},
{
"code": null,
"e": 27064,
"s": 27057,
"text": "Python"
},
{
"code": null,
"e": 27080,
"s": 27064,
"text": "Python Programs"
},
{
"code": null,
"e": 27178,
"s": 27080,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 27196,
"s": 27178,
"text": "Python Dictionary"
},
{
"code": null,
"e": 27231,
"s": 27196,
"text": "Read a file line by line in Python"
},
{
"code": null,
"e": 27263,
"s": 27231,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 27285,
"s": 27263,
"text": "Enumerate() in Python"
},
{
"code": null,
"e": 27327,
"s": 27285,
"text": "Different ways to create Pandas Dataframe"
},
{
"code": null,
"e": 27370,
"s": 27327,
"text": "Python program to convert a list to string"
},
{
"code": null,
"e": 27392,
"s": 27370,
"text": "Defaultdict in Python"
},
{
"code": null,
"e": 27431,
"s": 27392,
"text": "Python | Get dictionary keys as a list"
},
{
"code": null,
"e": 27477,
"s": 27431,
"text": "Python | Split string into list of characters"
}
] |
C# | Copying the Hashtable elements to an Array Instance - GeeksforGeeks | 22 Jun, 2021
Hashtable.CopyTo(Array, Int32) Method is used to copy the elements of a Hashtable to a one-dimensional Array instance at the specified index.Syntax:
public virtual void CopyTo (Array array, int arrayIndex);
Parameters:
array : The one-dimensional Array that is the destination of the DictionaryEntry objects copied from Hashtable. The Array must have zero-based indexing.index : The zero-based index in array at which copying begins.
Exceptions:
ArgumentNullException : If the array is null.
ArgumentOutOfRangeException : If the index is less than zero.
InvalidCastException : If the type of the source Hashtable cannot be cast automatically to the type of the destination array.
ArgumentException : If array is multidimensional OR the number of elements in the source Hashtable is greater than the available space from arrayIndex to the end of the destination array.
Below programs illustrate the use of Hashtable.CopyTo(Array, Int32) Method:Example 1:
CSharp
// C# code to copy the Hashtable// elements to a one-dimensional Array// instance at the specified index.using System;using System.Collections; class GFG { // Driver code public static void Main() { // Creating a Hashtable named myhash Hashtable myhash = new Hashtable(); // Adding key/value pairs in myhash myhash.Add("A", "Apple"); myhash.Add("B", "Banana"); myhash.Add("C", "Cat"); myhash.Add("D", "Dog"); myhash.Add("E", "Elephant"); myhash.Add("F", "Fish"); // Creating a one-dimensional Array named myArr DictionaryEntry[] myArr = new DictionaryEntry[myhash.Count]; // copying the Hashtable entries // to a one-dimensional Array instance // at the specified index myhash.CopyTo(myArr, 0); for (int i = 0; i < myArr.Length; i++) Console.WriteLine(myArr[i].Key + " --> " + myArr[i].Value); }}
Output:
B --> Banana
C --> Cat
A --> Apple
F --> Fish
D --> Dog
E --> Elephant
Example 2:
CSharp
// C# code to copy the Hashtable// elements to a one-dimensional Array// instance at the specified index.using System;using System.Collections; class GFG { // Driver code public static void Main() { // Creating a Hashtable named myhash Hashtable myhash = new Hashtable(); // Adding key/value pairs in myhash myhash.Add("A", "Apple"); myhash.Add("B", "Banana"); myhash.Add("C", "Cat"); myhash.Add("D", "Dog"); myhash.Add("E", "Elephant"); myhash.Add("F", "Fish"); // Creating a one-dimensional Array named myArr DictionaryEntry[] myArr = new DictionaryEntry[myhash.Count]; // copying the HybridDictionary entries // to a one-dimensional Array instance // at the specified index // This should raise "ArgumentOutOfRangeException" // as index is less than 0 myhash.CopyTo(myArr, -2); for (int i = 0; i < myArr.Length; i++) Console.WriteLine(myArr[i].Key + " --> " + myArr[i].Value); }}
Runtime Error:
Unhandled Exception: System.ArgumentOutOfRangeException: Non-negative number required. Parameter name: arrayIndex
Note:
The elements are copied to the Array in the same order in which the enumerator iterates through the Hashtable.
To copy only the keys in the Hashtable, use Hashtable.Keys.CopyTo.
To copy only the values in the Hashtable, use Hashtable.Values.CopyTo.
This method is an O(n) operation, where n is Count.
Reference:
https://docs.microsoft.com/en-us/dotnet/api/system.collections.hashtable.copyto?view=netframework-4.7.2
anikakapoor
CSharp-Collections-Hashtable
CSharp-Collections-Namespace
CSharp-method
C#
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Extension Method in C#
HashSet in C# with Examples
C# | Inheritance
Partial Classes in C#
C# | Generics - Introduction
Top 50 C# Interview Questions & Answers
Switch Statement in C#
Convert String to Character Array in C#
C# | How to insert an element in an Array?
Linked List Implementation in C# | [
{
"code": null,
"e": 25547,
"s": 25519,
"text": "\n22 Jun, 2021"
},
{
"code": null,
"e": 25698,
"s": 25547,
"text": "Hashtable.CopyTo(Array, Int32) Method is used to copy the elements of a Hashtable to a one-dimensional Array instance at the specified index.Syntax: "
},
{
"code": null,
"e": 25756,
"s": 25698,
"text": "public virtual void CopyTo (Array array, int arrayIndex);"
},
{
"code": null,
"e": 25769,
"s": 25756,
"text": "Parameters: "
},
{
"code": null,
"e": 25986,
"s": 25769,
"text": "array : The one-dimensional Array that is the destination of the DictionaryEntry objects copied from Hashtable. The Array must have zero-based indexing.index : The zero-based index in array at which copying begins. "
},
{
"code": null,
"e": 26000,
"s": 25986,
"text": "Exceptions: "
},
{
"code": null,
"e": 26046,
"s": 26000,
"text": "ArgumentNullException : If the array is null."
},
{
"code": null,
"e": 26108,
"s": 26046,
"text": "ArgumentOutOfRangeException : If the index is less than zero."
},
{
"code": null,
"e": 26234,
"s": 26108,
"text": "InvalidCastException : If the type of the source Hashtable cannot be cast automatically to the type of the destination array."
},
{
"code": null,
"e": 26422,
"s": 26234,
"text": "ArgumentException : If array is multidimensional OR the number of elements in the source Hashtable is greater than the available space from arrayIndex to the end of the destination array."
},
{
"code": null,
"e": 26509,
"s": 26422,
"text": "Below programs illustrate the use of Hashtable.CopyTo(Array, Int32) Method:Example 1: "
},
{
"code": null,
"e": 26516,
"s": 26509,
"text": "CSharp"
},
{
"code": "// C# code to copy the Hashtable// elements to a one-dimensional Array// instance at the specified index.using System;using System.Collections; class GFG { // Driver code public static void Main() { // Creating a Hashtable named myhash Hashtable myhash = new Hashtable(); // Adding key/value pairs in myhash myhash.Add(\"A\", \"Apple\"); myhash.Add(\"B\", \"Banana\"); myhash.Add(\"C\", \"Cat\"); myhash.Add(\"D\", \"Dog\"); myhash.Add(\"E\", \"Elephant\"); myhash.Add(\"F\", \"Fish\"); // Creating a one-dimensional Array named myArr DictionaryEntry[] myArr = new DictionaryEntry[myhash.Count]; // copying the Hashtable entries // to a one-dimensional Array instance // at the specified index myhash.CopyTo(myArr, 0); for (int i = 0; i < myArr.Length; i++) Console.WriteLine(myArr[i].Key + \" --> \" + myArr[i].Value); }}",
"e": 27483,
"s": 26516,
"text": null
},
{
"code": null,
"e": 27493,
"s": 27483,
"text": "Output: "
},
{
"code": null,
"e": 27564,
"s": 27493,
"text": "B --> Banana\nC --> Cat\nA --> Apple\nF --> Fish\nD --> Dog\nE --> Elephant"
},
{
"code": null,
"e": 27576,
"s": 27564,
"text": "Example 2: "
},
{
"code": null,
"e": 27583,
"s": 27576,
"text": "CSharp"
},
{
"code": "// C# code to copy the Hashtable// elements to a one-dimensional Array// instance at the specified index.using System;using System.Collections; class GFG { // Driver code public static void Main() { // Creating a Hashtable named myhash Hashtable myhash = new Hashtable(); // Adding key/value pairs in myhash myhash.Add(\"A\", \"Apple\"); myhash.Add(\"B\", \"Banana\"); myhash.Add(\"C\", \"Cat\"); myhash.Add(\"D\", \"Dog\"); myhash.Add(\"E\", \"Elephant\"); myhash.Add(\"F\", \"Fish\"); // Creating a one-dimensional Array named myArr DictionaryEntry[] myArr = new DictionaryEntry[myhash.Count]; // copying the HybridDictionary entries // to a one-dimensional Array instance // at the specified index // This should raise \"ArgumentOutOfRangeException\" // as index is less than 0 myhash.CopyTo(myArr, -2); for (int i = 0; i < myArr.Length; i++) Console.WriteLine(myArr[i].Key + \" --> \" + myArr[i].Value); }}",
"e": 28650,
"s": 27583,
"text": null
},
{
"code": null,
"e": 28666,
"s": 28650,
"text": "Runtime Error: "
},
{
"code": null,
"e": 28782,
"s": 28666,
"text": "Unhandled Exception: System.ArgumentOutOfRangeException: Non-negative number required. Parameter name: arrayIndex "
},
{
"code": null,
"e": 28790,
"s": 28782,
"text": "Note: "
},
{
"code": null,
"e": 28901,
"s": 28790,
"text": "The elements are copied to the Array in the same order in which the enumerator iterates through the Hashtable."
},
{
"code": null,
"e": 28968,
"s": 28901,
"text": "To copy only the keys in the Hashtable, use Hashtable.Keys.CopyTo."
},
{
"code": null,
"e": 29039,
"s": 28968,
"text": "To copy only the values in the Hashtable, use Hashtable.Values.CopyTo."
},
{
"code": null,
"e": 29091,
"s": 29039,
"text": "This method is an O(n) operation, where n is Count."
},
{
"code": null,
"e": 29104,
"s": 29091,
"text": "Reference: "
},
{
"code": null,
"e": 29208,
"s": 29104,
"text": "https://docs.microsoft.com/en-us/dotnet/api/system.collections.hashtable.copyto?view=netframework-4.7.2"
},
{
"code": null,
"e": 29222,
"s": 29210,
"text": "anikakapoor"
},
{
"code": null,
"e": 29251,
"s": 29222,
"text": "CSharp-Collections-Hashtable"
},
{
"code": null,
"e": 29280,
"s": 29251,
"text": "CSharp-Collections-Namespace"
},
{
"code": null,
"e": 29294,
"s": 29280,
"text": "CSharp-method"
},
{
"code": null,
"e": 29297,
"s": 29294,
"text": "C#"
},
{
"code": null,
"e": 29395,
"s": 29297,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 29418,
"s": 29395,
"text": "Extension Method in C#"
},
{
"code": null,
"e": 29446,
"s": 29418,
"text": "HashSet in C# with Examples"
},
{
"code": null,
"e": 29463,
"s": 29446,
"text": "C# | Inheritance"
},
{
"code": null,
"e": 29485,
"s": 29463,
"text": "Partial Classes in C#"
},
{
"code": null,
"e": 29514,
"s": 29485,
"text": "C# | Generics - Introduction"
},
{
"code": null,
"e": 29554,
"s": 29514,
"text": "Top 50 C# Interview Questions & Answers"
},
{
"code": null,
"e": 29577,
"s": 29554,
"text": "Switch Statement in C#"
},
{
"code": null,
"e": 29617,
"s": 29577,
"text": "Convert String to Character Array in C#"
},
{
"code": null,
"e": 29660,
"s": 29617,
"text": "C# | How to insert an element in an Array?"
}
] |
Number of ways to select exactly K even numbers from given Array - GeeksforGeeks | 12 Sep, 2021
Given an array arr[] of n integers and an integer K, the task is to find the number of ways to select exactly K even numbers from the given array.
Examples:
Input: arr[] = {1, 2, 3, 4} k = 1 Output: 2 Explanation:The number of ways in which we can select one even number is 2.
Input: arr[] = {61, 65, 99, 26, 57, 68, 23, 2, 32, 30} k = 2Output:10Explanation:The number of ways in which we can select 2 even number is 10.
Approach: The idea is to apply the rule of combinatorics. For choosing r objects from the given n objects, the total number of ways of choosing is given by nCr. Below are the steps:
Count the total number of even elements from the given array(say cnt).Check if the value of K is greater than cnt then the number of ways will be equal to 0.Otherwise, the answer will be nCk.
Count the total number of even elements from the given array(say cnt).
Check if the value of K is greater than cnt then the number of ways will be equal to 0.
Otherwise, the answer will be nCk.
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;long long f[12]; // Function for calculating factorialvoid fact(){ // Factorial of n defined as: // n! = n * (n - 1) * ... * 1 f[0] = f[1] = 1; for (int i = 2; i <= 10; i++) f[i] = i * 1LL * f[i - 1];} // Function to find the number of ways to// select exactly K even numbers// from the given arrayvoid solve(int arr[], int n, int k){ fact(); // Count even numbers int even = 0; for (int i = 0; i < n; i++) { // Check if the current // number is even if (arr[i] % 2 == 0) even++; } // Check if the even numbers to be // chosen is greater than n. Then, // there is no way to pick it. if (k > even) cout << 0 << endl; else { // The number of ways will be nCk cout << f[even] / (f[k] * f[even - k]); }} // Driver Codeint main(){ // Given array arr[] int arr[] = { 1, 2, 3, 4 }; int n = sizeof arr / sizeof arr[0]; // Given count of even elements int k = 1; // Function Call solve(arr, n, k); return 0;}
// Java program for the above approachclass GFG{ static int []f = new int[12]; // Function for calculating factorialstatic void fact(){ // Factorial of n defined as: // n! = n * (n - 1) * ... * 1 f[0] = f[1] = 1; for(int i = 2; i <= 10; i++) f[i] = i * 1 * f[i - 1];} // Function to find the number of ways to// select exactly K even numbers// from the given arraystatic void solve(int arr[], int n, int k){ fact(); // Count even numbers int even = 0; for(int i = 0; i < n; i++) { // Check if the current // number is even if (arr[i] % 2 == 0) even++; } // Check if the even numbers to be // chosen is greater than n. Then, // there is no way to pick it. if (k > even) System.out.print(0 + "\n"); else { // The number of ways will be nCk System.out.print(f[even] / (f[k] * f[even - k])); }} // Driver Codepublic static void main(String[] args){ // Given array arr[] int arr[] = { 1, 2, 3, 4 }; int n = arr.length; // Given count of even elements int k = 1; // Function call solve(arr, n, k);}} // This code is contributed by Rajput-Ji
# Python3 program for the above approachf = [0] * 12 # Function for calculating factorialdef fact(): # Factorial of n defined as: # n! = n * (n - 1) * ... * 1 f[0] = f[1] = 1 for i in range(2, 11): f[i] = i * 1 * f[i - 1] # Function to find the number of ways to# select exactly K even numbers# from the given arraydef solve(arr, n, k): fact() # Count even numbers even = 0 for i in range(n): # Check if the current # number is even if (arr[i] % 2 == 0): even += 1 # Check if the even numbers to be # chosen is greater than n. Then, # there is no way to pick it. if (k > even): print(0) else: # The number of ways will be nCk print(f[even] // (f[k] * f[even - k])) # Driver Code # Given array arr[]arr = [ 1, 2, 3, 4 ] n = len(arr) # Given count of even elementsk = 1 # Function callsolve(arr, n, k) # This code is contributed by code_hunt
// C# program for the above approachusing System;class GFG{ static int []f = new int[12]; // Function for calculating factorialstatic void fact(){ // Factorial of n defined as: // n! = n * (n - 1) * ... * 1 f[0] = f[1] = 1; for(int i = 2; i <= 10; i++) f[i] = i * 1 * f[i - 1];} // Function to find the number of ways to// select exactly K even numbers// from the given arraystatic void solve(int []arr, int n, int k){ fact(); // Count even numbers int even = 0; for(int i = 0; i < n; i++) { // Check if the current // number is even if (arr[i] % 2 == 0) even++; } // Check if the even numbers to be // chosen is greater than n. Then, // there is no way to pick it. if (k > even) Console.Write(0 + "\n"); else { // The number of ways will be nCk Console.Write(f[even] / (f[k] * f[even - k])); }} // Driver Codepublic static void Main(String[] args){ // Given array []arr int []arr = { 1, 2, 3, 4 }; int n = arr.Length; // Given count of even elements int k = 1; // Function call solve(arr, n, k);}} // This code is contributed by sapnasingh4991
<script> // Javascript program for the above approachvar f = Array(12).fill(0); // Function for calculating factorialfunction fact(){ // Factorial of n defined as: // n! = n * (n - 1) * ... * 1 f[0] = f[1] = 1; for (var i = 2; i <= 10; i++) f[i] = i * 1 * f[i - 1];} // Function to find the number of ways to// select exactly K even numbers// from the given arrayfunction solve(arr, n, k){ fact(); // Count even numbers var even = 0; for (var i = 0; i < n; i++) { // Check if the current // number is even if (arr[i] % 2 == 0) even++; } // Check if the even numbers to be // chosen is greater than n. Then, // there is no way to pick it. if (k > even) document.write( 0 ); else { // The number of ways will be nCk document.write( f[even] / (f[k] * f[even - k])); }} // Driver Code // Given array arr[]var arr = [ 1, 2, 3, 4 ];var n = arr.length; // Given count of even elementsvar k = 1; // Function Callsolve(arr, n, k); </script>
2
Time Complexity: O(N) Auxiliary Space: O(N)
Rajput-Ji
sapnasingh4991
code_hunt
noob2000
sooda367
combionatrics
Permutation and Combination
school-programming
Arrays
Combinatorial
Dynamic Programming
Mathematical
Arrays
Dynamic Programming
Mathematical
Combinatorial
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Chocolate Distribution Problem
Count pairs with given sum
Window Sliding Technique
Reversal algorithm for array rotation
Next Greater Element
Write a program to print all permutations of a given string
Permutation and Combination in Python
Factorial of a large number
itertools.combinations() module in Python to print all possible combinations | [
{
"code": null,
"e": 26041,
"s": 26013,
"text": "\n12 Sep, 2021"
},
{
"code": null,
"e": 26188,
"s": 26041,
"text": "Given an array arr[] of n integers and an integer K, the task is to find the number of ways to select exactly K even numbers from the given array."
},
{
"code": null,
"e": 26199,
"s": 26188,
"text": "Examples: "
},
{
"code": null,
"e": 26319,
"s": 26199,
"text": "Input: arr[] = {1, 2, 3, 4} k = 1 Output: 2 Explanation:The number of ways in which we can select one even number is 2."
},
{
"code": null,
"e": 26464,
"s": 26319,
"text": "Input: arr[] = {61, 65, 99, 26, 57, 68, 23, 2, 32, 30} k = 2Output:10Explanation:The number of ways in which we can select 2 even number is 10."
},
{
"code": null,
"e": 26647,
"s": 26464,
"text": "Approach: The idea is to apply the rule of combinatorics. For choosing r objects from the given n objects, the total number of ways of choosing is given by nCr. Below are the steps:"
},
{
"code": null,
"e": 26839,
"s": 26647,
"text": "Count the total number of even elements from the given array(say cnt).Check if the value of K is greater than cnt then the number of ways will be equal to 0.Otherwise, the answer will be nCk."
},
{
"code": null,
"e": 26910,
"s": 26839,
"text": "Count the total number of even elements from the given array(say cnt)."
},
{
"code": null,
"e": 26998,
"s": 26910,
"text": "Check if the value of K is greater than cnt then the number of ways will be equal to 0."
},
{
"code": null,
"e": 27033,
"s": 26998,
"text": "Otherwise, the answer will be nCk."
},
{
"code": null,
"e": 27084,
"s": 27033,
"text": "Below is the implementation of the above approach:"
},
{
"code": null,
"e": 27088,
"s": 27084,
"text": "C++"
},
{
"code": null,
"e": 27093,
"s": 27088,
"text": "Java"
},
{
"code": null,
"e": 27101,
"s": 27093,
"text": "Python3"
},
{
"code": null,
"e": 27104,
"s": 27101,
"text": "C#"
},
{
"code": null,
"e": 27115,
"s": 27104,
"text": "Javascript"
},
{
"code": "// C++ program for the above approach#include <bits/stdc++.h>using namespace std;long long f[12]; // Function for calculating factorialvoid fact(){ // Factorial of n defined as: // n! = n * (n - 1) * ... * 1 f[0] = f[1] = 1; for (int i = 2; i <= 10; i++) f[i] = i * 1LL * f[i - 1];} // Function to find the number of ways to// select exactly K even numbers// from the given arrayvoid solve(int arr[], int n, int k){ fact(); // Count even numbers int even = 0; for (int i = 0; i < n; i++) { // Check if the current // number is even if (arr[i] % 2 == 0) even++; } // Check if the even numbers to be // chosen is greater than n. Then, // there is no way to pick it. if (k > even) cout << 0 << endl; else { // The number of ways will be nCk cout << f[even] / (f[k] * f[even - k]); }} // Driver Codeint main(){ // Given array arr[] int arr[] = { 1, 2, 3, 4 }; int n = sizeof arr / sizeof arr[0]; // Given count of even elements int k = 1; // Function Call solve(arr, n, k); return 0;}",
"e": 28232,
"s": 27115,
"text": null
},
{
"code": "// Java program for the above approachclass GFG{ static int []f = new int[12]; // Function for calculating factorialstatic void fact(){ // Factorial of n defined as: // n! = n * (n - 1) * ... * 1 f[0] = f[1] = 1; for(int i = 2; i <= 10; i++) f[i] = i * 1 * f[i - 1];} // Function to find the number of ways to// select exactly K even numbers// from the given arraystatic void solve(int arr[], int n, int k){ fact(); // Count even numbers int even = 0; for(int i = 0; i < n; i++) { // Check if the current // number is even if (arr[i] % 2 == 0) even++; } // Check if the even numbers to be // chosen is greater than n. Then, // there is no way to pick it. if (k > even) System.out.print(0 + \"\\n\"); else { // The number of ways will be nCk System.out.print(f[even] / (f[k] * f[even - k])); }} // Driver Codepublic static void main(String[] args){ // Given array arr[] int arr[] = { 1, 2, 3, 4 }; int n = arr.length; // Given count of even elements int k = 1; // Function call solve(arr, n, k);}} // This code is contributed by Rajput-Ji",
"e": 29451,
"s": 28232,
"text": null
},
{
"code": "# Python3 program for the above approachf = [0] * 12 # Function for calculating factorialdef fact(): # Factorial of n defined as: # n! = n * (n - 1) * ... * 1 f[0] = f[1] = 1 for i in range(2, 11): f[i] = i * 1 * f[i - 1] # Function to find the number of ways to# select exactly K even numbers# from the given arraydef solve(arr, n, k): fact() # Count even numbers even = 0 for i in range(n): # Check if the current # number is even if (arr[i] % 2 == 0): even += 1 # Check if the even numbers to be # chosen is greater than n. Then, # there is no way to pick it. if (k > even): print(0) else: # The number of ways will be nCk print(f[even] // (f[k] * f[even - k])) # Driver Code # Given array arr[]arr = [ 1, 2, 3, 4 ] n = len(arr) # Given count of even elementsk = 1 # Function callsolve(arr, n, k) # This code is contributed by code_hunt",
"e": 30421,
"s": 29451,
"text": null
},
{
"code": "// C# program for the above approachusing System;class GFG{ static int []f = new int[12]; // Function for calculating factorialstatic void fact(){ // Factorial of n defined as: // n! = n * (n - 1) * ... * 1 f[0] = f[1] = 1; for(int i = 2; i <= 10; i++) f[i] = i * 1 * f[i - 1];} // Function to find the number of ways to// select exactly K even numbers// from the given arraystatic void solve(int []arr, int n, int k){ fact(); // Count even numbers int even = 0; for(int i = 0; i < n; i++) { // Check if the current // number is even if (arr[i] % 2 == 0) even++; } // Check if the even numbers to be // chosen is greater than n. Then, // there is no way to pick it. if (k > even) Console.Write(0 + \"\\n\"); else { // The number of ways will be nCk Console.Write(f[even] / (f[k] * f[even - k])); }} // Driver Codepublic static void Main(String[] args){ // Given array []arr int []arr = { 1, 2, 3, 4 }; int n = arr.Length; // Given count of even elements int k = 1; // Function call solve(arr, n, k);}} // This code is contributed by sapnasingh4991",
"e": 31650,
"s": 30421,
"text": null
},
{
"code": "<script> // Javascript program for the above approachvar f = Array(12).fill(0); // Function for calculating factorialfunction fact(){ // Factorial of n defined as: // n! = n * (n - 1) * ... * 1 f[0] = f[1] = 1; for (var i = 2; i <= 10; i++) f[i] = i * 1 * f[i - 1];} // Function to find the number of ways to// select exactly K even numbers// from the given arrayfunction solve(arr, n, k){ fact(); // Count even numbers var even = 0; for (var i = 0; i < n; i++) { // Check if the current // number is even if (arr[i] % 2 == 0) even++; } // Check if the even numbers to be // chosen is greater than n. Then, // there is no way to pick it. if (k > even) document.write( 0 ); else { // The number of ways will be nCk document.write( f[even] / (f[k] * f[even - k])); }} // Driver Code // Given array arr[]var arr = [ 1, 2, 3, 4 ];var n = arr.length; // Given count of even elementsvar k = 1; // Function Callsolve(arr, n, k); </script>",
"e": 32693,
"s": 31650,
"text": null
},
{
"code": null,
"e": 32695,
"s": 32693,
"text": "2"
},
{
"code": null,
"e": 32740,
"s": 32695,
"text": "Time Complexity: O(N) Auxiliary Space: O(N) "
},
{
"code": null,
"e": 32752,
"s": 32742,
"text": "Rajput-Ji"
},
{
"code": null,
"e": 32767,
"s": 32752,
"text": "sapnasingh4991"
},
{
"code": null,
"e": 32777,
"s": 32767,
"text": "code_hunt"
},
{
"code": null,
"e": 32786,
"s": 32777,
"text": "noob2000"
},
{
"code": null,
"e": 32795,
"s": 32786,
"text": "sooda367"
},
{
"code": null,
"e": 32809,
"s": 32795,
"text": "combionatrics"
},
{
"code": null,
"e": 32837,
"s": 32809,
"text": "Permutation and Combination"
},
{
"code": null,
"e": 32856,
"s": 32837,
"text": "school-programming"
},
{
"code": null,
"e": 32863,
"s": 32856,
"text": "Arrays"
},
{
"code": null,
"e": 32877,
"s": 32863,
"text": "Combinatorial"
},
{
"code": null,
"e": 32897,
"s": 32877,
"text": "Dynamic Programming"
},
{
"code": null,
"e": 32910,
"s": 32897,
"text": "Mathematical"
},
{
"code": null,
"e": 32917,
"s": 32910,
"text": "Arrays"
},
{
"code": null,
"e": 32937,
"s": 32917,
"text": "Dynamic Programming"
},
{
"code": null,
"e": 32950,
"s": 32937,
"text": "Mathematical"
},
{
"code": null,
"e": 32964,
"s": 32950,
"text": "Combinatorial"
},
{
"code": null,
"e": 33062,
"s": 32964,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 33093,
"s": 33062,
"text": "Chocolate Distribution Problem"
},
{
"code": null,
"e": 33120,
"s": 33093,
"text": "Count pairs with given sum"
},
{
"code": null,
"e": 33145,
"s": 33120,
"text": "Window Sliding Technique"
},
{
"code": null,
"e": 33183,
"s": 33145,
"text": "Reversal algorithm for array rotation"
},
{
"code": null,
"e": 33204,
"s": 33183,
"text": "Next Greater Element"
},
{
"code": null,
"e": 33264,
"s": 33204,
"text": "Write a program to print all permutations of a given string"
},
{
"code": null,
"e": 33302,
"s": 33264,
"text": "Permutation and Combination in Python"
},
{
"code": null,
"e": 33330,
"s": 33302,
"text": "Factorial of a large number"
}
] |
Python | Simple FLAMES game using Tkinter - GeeksforGeeks | 10 Jun, 2021
Prerequisites:
Introduction to Tkinter
Program to implement simple FLAMES game
Python offers multiple options for developing a GUI (Graphical User Interface). Out of all the GUI methods, Tkinter is the most commonly used method. It is a standard Python interface to the Tk GUI toolkit shipped with Python. Python with Tkinter outputs the fastest and easiest way to create GUI applications. Now, it’s up to the imagination or necessity of the developer, what he/she wants to develop using this toolkit. To create a Tkinter :
Importing the module – Tkinter
Create the main window (container)
Add any number of widgets to the main window.
Apply the event Trigger on the widgets
The GUI would look like below:
Let’s create a GUI version of a simple FLAMES game.FLAMES is a popular game named after the acronym: Friends, Lovers, Affectionate, Marriage, Enemies, Sibling. This game does not accurately predict whether an individual is right for you, but it can be fun to play this with your friends.
Below is the implementation :
Python3
# import all functions from the tkinterfrom tkinter import * # function for removing common characters# with their respective occurrencesdef remove_match_char(list1, list2): for i in range(len(list1)) : for j in range(len(list2)) : # if common character is found # then remove that character # and return list of concatenated # list with True Flag if list1[i] == list2[j] : c = list1[i] # remove character from the list list1.remove(c) list2.remove(c) # concatenation of two list elements with * # * is act as border mark here list3 = list1 + ["*"] + list2 # return the concatenated list with True flag return [list3, True] # no common characters is found # return the concatenated list with False flag list3 = list1 + ["*"] + list2 return [list3, False] # function for telling the relationship statusdef tell_status() : # take a 1st player name from Player1_field entry box p1 = Player1_field.get() # converted all letters into lower case p1 = p1.lower() # replace any space with empty string p1.replace(" ", "") # make a list of letters or characters p1_list = list(p1) # take a 2nd player name from Player2_field entry box p2 = Player2_field.get() p2 = p2.lower() p2.replace(" ", "") p2_list = list(p2) # taking a flag as True initially proceed = True # keep calling remove_match_char function # until common characters is found or # keep looping until proceed flag is True while proceed : # function calling and store return value ret_list = remove_match_char(p1_list, p2_list) # take out concatenated list from return list con_list = ret_list[0] # take out flag value from return list proceed = ret_list[1] # find the index of "*" / border mark star_index = con_list.index("*") # list slicing perform # all characters before * store in p1_list p1_list = con_list[ : star_index] # all characters after * store in p2_list p2_list = con_list[star_index + 1 : ] # count total remaining characters count = len(p1_list) + len(p2_list) # list of FLAMES acronym result = ["Friends", "Love", "Affection", "Marriage", "Enemy", "Siblings"] # keep looping until only one item # is not remaining in the result list while len(result) > 1 : # store that index value from # where we have to perform slicing. split_index = (count % len(result) - 1) # this steps is done for performing # anticlock-wise circular fashion counting. if split_index >= 0 : # list slicing right = result[split_index + 1 : ] left = result[ : split_index] # list concatenation result = right + left else : result = result[ : len(result) - 1] # insert method inserting the # value in the text entry box. Status_field.insert(10, result[0]) # Function for clearing the # contents of all text entry boxes def clear_all() : Player1_field.delete(0, END) Player2_field.delete(0, END) Status_field.delete(0, END) # set focus on the Player1_field entry box Player1_field.focus_set() # Driver codeif __name__ == "__main__" : # Create a GUI window root = Tk() # Set the background colour of GUI window root.configure(background = 'light green') # Set the configuration of GUI window root.geometry("350x125") # set the name of tkinter GUI window root.title("Flames Game") # Create a Player 1 Name: label label1 = Label(root, text = "Player 1 Name: ", fg = 'black', bg = 'dark green') # Create a Player 2 Name: label label2 = Label(root, text = "Player 2 Name: ", fg = 'black', bg = 'dark green') # Create a Relation Status: label label3 = Label(root, text = "Relationship Status: ", fg = 'black', bg = 'red') # grid method is used for placing # the widgets at respective positions # in table like structure . label1.grid(row = 1, column = 0, sticky ="E") label2.grid(row = 2, column = 0, sticky ="E") label3.grid(row = 4, column = 0, sticky ="E") # Create a text entry box # for filling or typing the information. Player1_field = Entry(root) Player2_field = Entry(root) Status_field = Entry(root) # grid method is used for placing # the widgets at respective positions # in table like structure . # ipadx keyword argument set width of entry space . Player1_field.grid(row = 1, column = 1, ipadx ="50") Player2_field.grid(row = 2, column = 1, ipadx ="50") Status_field.grid(row = 4, column = 1, ipadx ="50") # Create a Submit Button and attached # to tell_status function button1 = Button(root, text = "Submit", bg = "red", fg = "black", command = tell_status) # Create a Clear Button and attached # to clear_all function button2 = Button(root, text = "Clear", bg = "red", fg = "black", command = clear_all) # grid method is used for placing # the widgets at respective positions # in table like structure . button1.grid(row = 3, column = 1) button2.grid(row = 5, column = 1) # Start the GUI root.mainloop()
Output :
nidhi_biet
abhigoya
simmytarika5
surinderdawra388
python-utility
Python
Python Programs
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python Dictionary
Read a file line by line in Python
How to Install PIP on Windows ?
Different ways to create Pandas Dataframe
Iterate over a list in Python
Python program to convert a list to string
Defaultdict in Python
Python | Get dictionary keys as a list
Python | Split string into list of characters
Python | Convert a list to dictionary | [
{
"code": null,
"e": 25605,
"s": 25577,
"text": "\n10 Jun, 2021"
},
{
"code": null,
"e": 25621,
"s": 25605,
"text": "Prerequisites: "
},
{
"code": null,
"e": 25645,
"s": 25621,
"text": "Introduction to Tkinter"
},
{
"code": null,
"e": 25685,
"s": 25645,
"text": "Program to implement simple FLAMES game"
},
{
"code": null,
"e": 26131,
"s": 25685,
"text": "Python offers multiple options for developing a GUI (Graphical User Interface). Out of all the GUI methods, Tkinter is the most commonly used method. It is a standard Python interface to the Tk GUI toolkit shipped with Python. Python with Tkinter outputs the fastest and easiest way to create GUI applications. Now, it’s up to the imagination or necessity of the developer, what he/she wants to develop using this toolkit. To create a Tkinter : "
},
{
"code": null,
"e": 26162,
"s": 26131,
"text": "Importing the module – Tkinter"
},
{
"code": null,
"e": 26197,
"s": 26162,
"text": "Create the main window (container)"
},
{
"code": null,
"e": 26243,
"s": 26197,
"text": "Add any number of widgets to the main window."
},
{
"code": null,
"e": 26282,
"s": 26243,
"text": "Apply the event Trigger on the widgets"
},
{
"code": null,
"e": 26313,
"s": 26282,
"text": "The GUI would look like below:"
},
{
"code": null,
"e": 26602,
"s": 26313,
"text": "Let’s create a GUI version of a simple FLAMES game.FLAMES is a popular game named after the acronym: Friends, Lovers, Affectionate, Marriage, Enemies, Sibling. This game does not accurately predict whether an individual is right for you, but it can be fun to play this with your friends. "
},
{
"code": null,
"e": 26633,
"s": 26602,
"text": "Below is the implementation : "
},
{
"code": null,
"e": 26641,
"s": 26633,
"text": "Python3"
},
{
"code": "# import all functions from the tkinterfrom tkinter import * # function for removing common characters# with their respective occurrencesdef remove_match_char(list1, list2): for i in range(len(list1)) : for j in range(len(list2)) : # if common character is found # then remove that character # and return list of concatenated # list with True Flag if list1[i] == list2[j] : c = list1[i] # remove character from the list list1.remove(c) list2.remove(c) # concatenation of two list elements with * # * is act as border mark here list3 = list1 + [\"*\"] + list2 # return the concatenated list with True flag return [list3, True] # no common characters is found # return the concatenated list with False flag list3 = list1 + [\"*\"] + list2 return [list3, False] # function for telling the relationship statusdef tell_status() : # take a 1st player name from Player1_field entry box p1 = Player1_field.get() # converted all letters into lower case p1 = p1.lower() # replace any space with empty string p1.replace(\" \", \"\") # make a list of letters or characters p1_list = list(p1) # take a 2nd player name from Player2_field entry box p2 = Player2_field.get() p2 = p2.lower() p2.replace(\" \", \"\") p2_list = list(p2) # taking a flag as True initially proceed = True # keep calling remove_match_char function # until common characters is found or # keep looping until proceed flag is True while proceed : # function calling and store return value ret_list = remove_match_char(p1_list, p2_list) # take out concatenated list from return list con_list = ret_list[0] # take out flag value from return list proceed = ret_list[1] # find the index of \"*\" / border mark star_index = con_list.index(\"*\") # list slicing perform # all characters before * store in p1_list p1_list = con_list[ : star_index] # all characters after * store in p2_list p2_list = con_list[star_index + 1 : ] # count total remaining characters count = len(p1_list) + len(p2_list) # list of FLAMES acronym result = [\"Friends\", \"Love\", \"Affection\", \"Marriage\", \"Enemy\", \"Siblings\"] # keep looping until only one item # is not remaining in the result list while len(result) > 1 : # store that index value from # where we have to perform slicing. split_index = (count % len(result) - 1) # this steps is done for performing # anticlock-wise circular fashion counting. if split_index >= 0 : # list slicing right = result[split_index + 1 : ] left = result[ : split_index] # list concatenation result = right + left else : result = result[ : len(result) - 1] # insert method inserting the # value in the text entry box. Status_field.insert(10, result[0]) # Function for clearing the # contents of all text entry boxes def clear_all() : Player1_field.delete(0, END) Player2_field.delete(0, END) Status_field.delete(0, END) # set focus on the Player1_field entry box Player1_field.focus_set() # Driver codeif __name__ == \"__main__\" : # Create a GUI window root = Tk() # Set the background colour of GUI window root.configure(background = 'light green') # Set the configuration of GUI window root.geometry(\"350x125\") # set the name of tkinter GUI window root.title(\"Flames Game\") # Create a Player 1 Name: label label1 = Label(root, text = \"Player 1 Name: \", fg = 'black', bg = 'dark green') # Create a Player 2 Name: label label2 = Label(root, text = \"Player 2 Name: \", fg = 'black', bg = 'dark green') # Create a Relation Status: label label3 = Label(root, text = \"Relationship Status: \", fg = 'black', bg = 'red') # grid method is used for placing # the widgets at respective positions # in table like structure . label1.grid(row = 1, column = 0, sticky =\"E\") label2.grid(row = 2, column = 0, sticky =\"E\") label3.grid(row = 4, column = 0, sticky =\"E\") # Create a text entry box # for filling or typing the information. Player1_field = Entry(root) Player2_field = Entry(root) Status_field = Entry(root) # grid method is used for placing # the widgets at respective positions # in table like structure . # ipadx keyword argument set width of entry space . Player1_field.grid(row = 1, column = 1, ipadx =\"50\") Player2_field.grid(row = 2, column = 1, ipadx =\"50\") Status_field.grid(row = 4, column = 1, ipadx =\"50\") # Create a Submit Button and attached # to tell_status function button1 = Button(root, text = \"Submit\", bg = \"red\", fg = \"black\", command = tell_status) # Create a Clear Button and attached # to clear_all function button2 = Button(root, text = \"Clear\", bg = \"red\", fg = \"black\", command = clear_all) # grid method is used for placing # the widgets at respective positions # in table like structure . button1.grid(row = 3, column = 1) button2.grid(row = 5, column = 1) # Start the GUI root.mainloop()",
"e": 32175,
"s": 26641,
"text": null
},
{
"code": null,
"e": 32186,
"s": 32175,
"text": "Output : "
},
{
"code": null,
"e": 32197,
"s": 32186,
"text": "nidhi_biet"
},
{
"code": null,
"e": 32206,
"s": 32197,
"text": "abhigoya"
},
{
"code": null,
"e": 32219,
"s": 32206,
"text": "simmytarika5"
},
{
"code": null,
"e": 32236,
"s": 32219,
"text": "surinderdawra388"
},
{
"code": null,
"e": 32251,
"s": 32236,
"text": "python-utility"
},
{
"code": null,
"e": 32258,
"s": 32251,
"text": "Python"
},
{
"code": null,
"e": 32274,
"s": 32258,
"text": "Python Programs"
},
{
"code": null,
"e": 32372,
"s": 32274,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 32390,
"s": 32372,
"text": "Python Dictionary"
},
{
"code": null,
"e": 32425,
"s": 32390,
"text": "Read a file line by line in Python"
},
{
"code": null,
"e": 32457,
"s": 32425,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 32499,
"s": 32457,
"text": "Different ways to create Pandas Dataframe"
},
{
"code": null,
"e": 32529,
"s": 32499,
"text": "Iterate over a list in Python"
},
{
"code": null,
"e": 32572,
"s": 32529,
"text": "Python program to convert a list to string"
},
{
"code": null,
"e": 32594,
"s": 32572,
"text": "Defaultdict in Python"
},
{
"code": null,
"e": 32633,
"s": 32594,
"text": "Python | Get dictionary keys as a list"
},
{
"code": null,
"e": 32679,
"s": 32633,
"text": "Python | Split string into list of characters"
}
] |
Convert binary to string using Python - GeeksforGeeks | 15 Oct, 2021
Data conversion has always been widely used utility and one among them can be the conversion of a binary equivalent to its string. Let’s discuss certain ways in which this can be done.Method #1:The naive approach is to convert the given binary data in decimal by taking the sum of binary digits (dn) times their power of 2*(2^n). The binary data is divided into sets of 7 bits because this set of binary as input, returns the corresponding decimal value which is ASCII code of the character of a string. This ASCII code is then converted to string using chr() function.Note: Here we do slicing of binary data in the set of 7 because, the original ASCII table is encoded on 7 bits, therefore, it has 128 characters.
Python3
# Python3 code to demonstrate working of# Converting binary to string# Using BinarytoDecimal(binary)+chr() # Defining BinarytoDecimal() functiondef BinaryToDecimal(binary): binary1 = binary decimal, i, n = 0, 0, 0 while(binary != 0): dec = binary % 10 decimal = decimal + dec * pow(2, i) binary = binary//10 i += 1 return (decimal) # Driver's code# initializing binary databin_data ='10001111100101110010111010111110011' # print binary dataprint("The binary value is:", bin_data) # initializing a empty string for# storing the string datastr_data =' ' # slicing the input and converting it# in decimal and then converting it in stringfor i in range(0, len(bin_data), 7): # slicing the bin_data from index range [0, 6] # and storing it as integer in temp_data temp_data = int(bin_data[i:i + 7]) # passing temp_data in BinarytoDecimal() function # to get decimal value of corresponding temp_data decimal_data = BinaryToDecimal(temp_data) # Decoding the decimal value returned by # BinarytoDecimal() function, using chr() # function which return the string corresponding # character for given ASCII value, and store it # in str_data str_data = str_data + chr(decimal_data) # printing the resultprint("The Binary value after string conversion is:", str_data)
Output:
The binary value is: 10001111100101110010111010111110011
The Binary value after string conversion is: Geeks
Method #2: Using int() function Whenever an int() function is provided with two arguments, it tells the int() function that the second argument is the base of the input string. If the input string is larger than 10, then Python assumes that the next sequence of digits comes from ABCD... .Therefore, this concept can be used for converting a binary sequence to string. Below is the implementation.
Python3
# Python3 code to demonstrate working of# Converting binary to string# Using BinarytoDecimal(binary)+chr() # Defining BinarytoDecimal() functiondef BinaryToDecimal(binary): # Using int function to convert to # string string = int(binary, 2) return string # Driver's code# initializing binary databin_data ='10001111100101110010111010111110011' # print binary dataprint("The binary value is:", bin_data) # initializing a empty string for# storing the string datastr_data =' ' # slicing the input and converting it# in decimal and then converting it in stringfor i in range(0, len(bin_data), 7): # slicing the bin_data from index range [0, 6] # and storing it in temp_data temp_data = bin_data[i:i + 7] # passing temp_data in BinarytoDecimal() function # to get decimal value of corresponding temp_data decimal_data = BinaryToDecimal(temp_data) # Decoding the decimal value returned by # BinarytoDecimal() function, using chr() # function which return the string corresponding # character for given ASCII value, and store it # in str_data str_data = str_data + chr(decimal_data) # printing the resultprint("The Binary value after string conversion is:", str_data)
Output:
The binary value is: 10001111100101110010111010111110011
The Binary value after string conversion is: Geeks
Akanksha_Rai
surindertarika1234
Python string-programs
python-string
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python Dictionary
Read a file line by line in Python
How to Install PIP on Windows ?
Enumerate() in Python
Different ways to create Pandas Dataframe
Iterate over a list in Python
Python String | replace()
*args and **kwargs in Python
Reading and Writing to text files in Python
Create a Pandas DataFrame from Lists | [
{
"code": null,
"e": 25961,
"s": 25933,
"text": "\n15 Oct, 2021"
},
{
"code": null,
"e": 26677,
"s": 25961,
"text": "Data conversion has always been widely used utility and one among them can be the conversion of a binary equivalent to its string. Let’s discuss certain ways in which this can be done.Method #1:The naive approach is to convert the given binary data in decimal by taking the sum of binary digits (dn) times their power of 2*(2^n). The binary data is divided into sets of 7 bits because this set of binary as input, returns the corresponding decimal value which is ASCII code of the character of a string. This ASCII code is then converted to string using chr() function.Note: Here we do slicing of binary data in the set of 7 because, the original ASCII table is encoded on 7 bits, therefore, it has 128 characters. "
},
{
"code": null,
"e": 26685,
"s": 26677,
"text": "Python3"
},
{
"code": "# Python3 code to demonstrate working of# Converting binary to string# Using BinarytoDecimal(binary)+chr() # Defining BinarytoDecimal() functiondef BinaryToDecimal(binary): binary1 = binary decimal, i, n = 0, 0, 0 while(binary != 0): dec = binary % 10 decimal = decimal + dec * pow(2, i) binary = binary//10 i += 1 return (decimal) # Driver's code# initializing binary databin_data ='10001111100101110010111010111110011' # print binary dataprint(\"The binary value is:\", bin_data) # initializing a empty string for# storing the string datastr_data =' ' # slicing the input and converting it# in decimal and then converting it in stringfor i in range(0, len(bin_data), 7): # slicing the bin_data from index range [0, 6] # and storing it as integer in temp_data temp_data = int(bin_data[i:i + 7]) # passing temp_data in BinarytoDecimal() function # to get decimal value of corresponding temp_data decimal_data = BinaryToDecimal(temp_data) # Decoding the decimal value returned by # BinarytoDecimal() function, using chr() # function which return the string corresponding # character for given ASCII value, and store it # in str_data str_data = str_data + chr(decimal_data) # printing the resultprint(\"The Binary value after string conversion is:\", str_data)",
"e": 28056,
"s": 26685,
"text": null
},
{
"code": null,
"e": 28065,
"s": 28056,
"text": "Output: "
},
{
"code": null,
"e": 28174,
"s": 28065,
"text": "The binary value is: 10001111100101110010111010111110011\nThe Binary value after string conversion is: Geeks"
},
{
"code": null,
"e": 28573,
"s": 28174,
"text": "Method #2: Using int() function Whenever an int() function is provided with two arguments, it tells the int() function that the second argument is the base of the input string. If the input string is larger than 10, then Python assumes that the next sequence of digits comes from ABCD... .Therefore, this concept can be used for converting a binary sequence to string. Below is the implementation. "
},
{
"code": null,
"e": 28581,
"s": 28573,
"text": "Python3"
},
{
"code": "# Python3 code to demonstrate working of# Converting binary to string# Using BinarytoDecimal(binary)+chr() # Defining BinarytoDecimal() functiondef BinaryToDecimal(binary): # Using int function to convert to # string string = int(binary, 2) return string # Driver's code# initializing binary databin_data ='10001111100101110010111010111110011' # print binary dataprint(\"The binary value is:\", bin_data) # initializing a empty string for# storing the string datastr_data =' ' # slicing the input and converting it# in decimal and then converting it in stringfor i in range(0, len(bin_data), 7): # slicing the bin_data from index range [0, 6] # and storing it in temp_data temp_data = bin_data[i:i + 7] # passing temp_data in BinarytoDecimal() function # to get decimal value of corresponding temp_data decimal_data = BinaryToDecimal(temp_data) # Decoding the decimal value returned by # BinarytoDecimal() function, using chr() # function which return the string corresponding # character for given ASCII value, and store it # in str_data str_data = str_data + chr(decimal_data) # printing the resultprint(\"The Binary value after string conversion is:\", str_data)",
"e": 29835,
"s": 28581,
"text": null
},
{
"code": null,
"e": 29845,
"s": 29835,
"text": "Output: "
},
{
"code": null,
"e": 29954,
"s": 29845,
"text": "The binary value is: 10001111100101110010111010111110011\nThe Binary value after string conversion is: Geeks"
},
{
"code": null,
"e": 29969,
"s": 29956,
"text": "Akanksha_Rai"
},
{
"code": null,
"e": 29988,
"s": 29969,
"text": "surindertarika1234"
},
{
"code": null,
"e": 30011,
"s": 29988,
"text": "Python string-programs"
},
{
"code": null,
"e": 30025,
"s": 30011,
"text": "python-string"
},
{
"code": null,
"e": 30032,
"s": 30025,
"text": "Python"
},
{
"code": null,
"e": 30130,
"s": 30032,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 30148,
"s": 30130,
"text": "Python Dictionary"
},
{
"code": null,
"e": 30183,
"s": 30148,
"text": "Read a file line by line in Python"
},
{
"code": null,
"e": 30215,
"s": 30183,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 30237,
"s": 30215,
"text": "Enumerate() in Python"
},
{
"code": null,
"e": 30279,
"s": 30237,
"text": "Different ways to create Pandas Dataframe"
},
{
"code": null,
"e": 30309,
"s": 30279,
"text": "Iterate over a list in Python"
},
{
"code": null,
"e": 30335,
"s": 30309,
"text": "Python String | replace()"
},
{
"code": null,
"e": 30364,
"s": 30335,
"text": "*args and **kwargs in Python"
},
{
"code": null,
"e": 30408,
"s": 30364,
"text": "Reading and Writing to text files in Python"
}
] |
Implementing Race Condition in C++ - GeeksforGeeks | 21 Jan, 2021
Prerequisite – Race Condition Vulnerability
When two concurrent threads in execution access a shared resource in a way that it unintentionally produces different results depending on the timing of the threads or processes, this gives rise to a Race Condition.
In Simpler Words :If our privileged program (application with elevated access control) somehow also has a code block with race-condition vulnerability, then attackers can exploit this by running parallel processes which can “race” against our privileged program. If they attack with an intention to change its actual intended behaviour then this can cause Race Conditions (RC’s) in our program.
Example :
/* A Vulnerable Program */
int main() {
char * fn = "/tmp/XYZ";
char buffer[60];
FILE *fp;
/* get user input */
scanf("%50s", buffer );
if(!access(fn, W_OK)){
fp = fopen(fn, "a+");
fwrite("\n", sizeof(char), 1, fp);
fwrite(buffer, sizeof(char), strlen(buffer), fp);
fclose(fp);
}
else printf("No permission \n");
}
Analysis of the User Program :
1. The program given above is an owned by root and is given that it’s a Set-UID program i.e. it’s a privilege program.
2. The function of the program is to append a string, inputted by the user, to the end of the file /tmp/XYZ which is created by us.
3. The given code runs with the root privilege hence this makes its effective user ID (euid) equal to 0. Which corresponds to a root hence it can overwrite any file.
4. Using access() system call, the program prevents itself from accidentally overwriting someone else’s file. It first checks whether the real user ID [uid] has the appropriate access permissions for the file /tmp/XYZ, with the access() call.
5. If the check turns out to be true and real user ID does actually have the privileges, then the program opens the file and appends the user’s input into the file.
6. There is an additional check present at the system call of fopen(), but it only checks the euid (effective user ID) rather than the uid (real user ID), and being a privileged program it is always satisfied because the program runs as a Set-UID program (privileged program) with euid of 0 (root user).
7. Now the actual point of error that can occur could be due to the time window between the check ‘access()’ and the use ‘fopen()’ of the file to be written. There is a large probability that the file used by access() system call is different from the file used by fopen() system call.
8. This is possible only if a malicious attacker can somehow make /tmp/XYZ a “symbolic link” to point to a protected file which is otherwise not accessible like /etc/shadow (which contains our passwords) within this time-of-check to the time-of-use window (TOCTOU window).
unlink("/tmp/XYZ");
symlink("/etc/passwd","/tmp/XYZ");
9. If successful the attacker can append the user input to the end of the /etc/shadow rather than the original target of the symlink, like the creation of a new root user with all privileges only by appending single statement to the shadow file.
10. Hence, this window can cause Race Condition Vulnerability.
So, with the possibility of a context switching between two system call namely, access() and open() there is also a possibility of a Race Condition Vulnerability.
Attacking Program Code :
#include<unistd.h>
int main(){
while(1){
unlink("/tmp/XYZ");
symlink("/home/seed/myfile", "/tmp/XYZ");
usleep(10000);
unlink("/tmp/XYZ");
symlink("/etc/passwd", "/tmp/XYZ");
usleep(10000);
}
return 0;
}
This program is intended to showcase the RC as by using usleep(10000), hence intentionally creating a TOCTOU window.
Here we are creating a symlink to a file (myfle) owned by us, a normal user, so to pass the access() check.
Then a window is generated so to sleep for 10000 microseconds to let our vulnerable process run.
Then it unlink the symlink and creates a symlink to /etc/passwd.
Counter Measures :
1. Applying the Principle of Least Privilege :According to the principle, we try De-Escalating the privileges of the file for all parts of a Set-UID program. Specially which do not require elevated privileges. For this, we use the geteuid and seteuid system calls to de-escalate and then re-escalate the privileges at the appropriate places in the vulnerable program.
2. Built-in Protection method for Ubuntu :
$ sudo sysctl -w kernel.yama.protected_sticky_symlinks=1
3. Repeated Checks for System Calls :Race Conditions are more probabilistic than deterministic (we can not determine when we would be able to get access to the file, it could happen during any instance within TOCTOU check window). Using Repeated checks on access() and open() system calls we can match the inode value of the file. While this value is the same in every check, we can say that the file is opened and if it’s different that means the file was changed, and we do not open it.
4. Atomic Operations :
f = open(file, O_CREAT | O_EXCL)
If the file already exists then these two specifiers which are stated above will not open the specified file. Hence implementing atomicity of the check and the use of the file.
References & Source Code: SEED Labs, Syracuse University.
Process Synchronization
Technical Scripter 2020
Operating Systems
Operating Systems
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Memory Management in Operating System
File Allocation Methods
Logical and Physical Address in Operating System
Difference between Internal and External fragmentation
File Access Methods in Operating System
Memory Hierarchy Design and its Characteristics
File Systems in Operating System
Process Table and Process Control Block (PCB)
States of a Process in Operating Systems
Introduction of Process Management | [
{
"code": null,
"e": 25737,
"s": 25709,
"text": "\n21 Jan, 2021"
},
{
"code": null,
"e": 25781,
"s": 25737,
"text": "Prerequisite – Race Condition Vulnerability"
},
{
"code": null,
"e": 25997,
"s": 25781,
"text": "When two concurrent threads in execution access a shared resource in a way that it unintentionally produces different results depending on the timing of the threads or processes, this gives rise to a Race Condition."
},
{
"code": null,
"e": 26392,
"s": 25997,
"text": "In Simpler Words :If our privileged program (application with elevated access control) somehow also has a code block with race-condition vulnerability, then attackers can exploit this by running parallel processes which can “race” against our privileged program. If they attack with an intention to change its actual intended behaviour then this can cause Race Conditions (RC’s) in our program."
},
{
"code": null,
"e": 26402,
"s": 26392,
"text": "Example :"
},
{
"code": null,
"e": 26782,
"s": 26402,
"text": "/* A Vulnerable Program */\nint main() {\n char * fn = \"/tmp/XYZ\";\n char buffer[60];\n FILE *fp;\n /* get user input */\n scanf(\"%50s\", buffer );\n\n if(!access(fn, W_OK)){\n fp = fopen(fn, \"a+\");\n fwrite(\"\\n\", sizeof(char), 1, fp);\n fwrite(buffer, sizeof(char), strlen(buffer), fp);\n fclose(fp);\n }\n else printf(\"No permission \\n\");\n}"
},
{
"code": null,
"e": 26813,
"s": 26782,
"text": "Analysis of the User Program :"
},
{
"code": null,
"e": 26932,
"s": 26813,
"text": "1. The program given above is an owned by root and is given that it’s a Set-UID program i.e. it’s a privilege program."
},
{
"code": null,
"e": 27064,
"s": 26932,
"text": "2. The function of the program is to append a string, inputted by the user, to the end of the file /tmp/XYZ which is created by us."
},
{
"code": null,
"e": 27230,
"s": 27064,
"text": "3. The given code runs with the root privilege hence this makes its effective user ID (euid) equal to 0. Which corresponds to a root hence it can overwrite any file."
},
{
"code": null,
"e": 27473,
"s": 27230,
"text": "4. Using access() system call, the program prevents itself from accidentally overwriting someone else’s file. It first checks whether the real user ID [uid] has the appropriate access permissions for the file /tmp/XYZ, with the access() call."
},
{
"code": null,
"e": 27638,
"s": 27473,
"text": "5. If the check turns out to be true and real user ID does actually have the privileges, then the program opens the file and appends the user’s input into the file."
},
{
"code": null,
"e": 27942,
"s": 27638,
"text": "6. There is an additional check present at the system call of fopen(), but it only checks the euid (effective user ID) rather than the uid (real user ID), and being a privileged program it is always satisfied because the program runs as a Set-UID program (privileged program) with euid of 0 (root user)."
},
{
"code": null,
"e": 28228,
"s": 27942,
"text": "7. Now the actual point of error that can occur could be due to the time window between the check ‘access()’ and the use ‘fopen()’ of the file to be written. There is a large probability that the file used by access() system call is different from the file used by fopen() system call."
},
{
"code": null,
"e": 28501,
"s": 28228,
"text": "8. This is possible only if a malicious attacker can somehow make /tmp/XYZ a “symbolic link” to point to a protected file which is otherwise not accessible like /etc/shadow (which contains our passwords) within this time-of-check to the time-of-use window (TOCTOU window)."
},
{
"code": null,
"e": 28556,
"s": 28501,
"text": "unlink(\"/tmp/XYZ\");\nsymlink(\"/etc/passwd\",\"/tmp/XYZ\");"
},
{
"code": null,
"e": 28802,
"s": 28556,
"text": "9. If successful the attacker can append the user input to the end of the /etc/shadow rather than the original target of the symlink, like the creation of a new root user with all privileges only by appending single statement to the shadow file."
},
{
"code": null,
"e": 28866,
"s": 28802,
"text": "10. Hence, this window can cause Race Condition Vulnerability. "
},
{
"code": null,
"e": 29030,
"s": 28866,
"text": "So, with the possibility of a context switching between two system call namely, access() and open() there is also a possibility of a Race Condition Vulnerability. "
},
{
"code": null,
"e": 29055,
"s": 29030,
"text": "Attacking Program Code :"
},
{
"code": null,
"e": 29323,
"s": 29055,
"text": "#include<unistd.h>\nint main(){\n while(1){\n unlink(\"/tmp/XYZ\");\n symlink(\"/home/seed/myfile\", \"/tmp/XYZ\");\n usleep(10000);\n\n unlink(\"/tmp/XYZ\");\n symlink(\"/etc/passwd\", \"/tmp/XYZ\");\n usleep(10000);\n }\n return 0;\n}"
},
{
"code": null,
"e": 29440,
"s": 29323,
"text": "This program is intended to showcase the RC as by using usleep(10000), hence intentionally creating a TOCTOU window."
},
{
"code": null,
"e": 29548,
"s": 29440,
"text": "Here we are creating a symlink to a file (myfle) owned by us, a normal user, so to pass the access() check."
},
{
"code": null,
"e": 29645,
"s": 29548,
"text": "Then a window is generated so to sleep for 10000 microseconds to let our vulnerable process run."
},
{
"code": null,
"e": 29710,
"s": 29645,
"text": "Then it unlink the symlink and creates a symlink to /etc/passwd."
},
{
"code": null,
"e": 29729,
"s": 29710,
"text": "Counter Measures :"
},
{
"code": null,
"e": 30097,
"s": 29729,
"text": "1. Applying the Principle of Least Privilege :According to the principle, we try De-Escalating the privileges of the file for all parts of a Set-UID program. Specially which do not require elevated privileges. For this, we use the geteuid and seteuid system calls to de-escalate and then re-escalate the privileges at the appropriate places in the vulnerable program."
},
{
"code": null,
"e": 30140,
"s": 30097,
"text": "2. Built-in Protection method for Ubuntu :"
},
{
"code": null,
"e": 30197,
"s": 30140,
"text": "$ sudo sysctl -w kernel.yama.protected_sticky_symlinks=1"
},
{
"code": null,
"e": 30686,
"s": 30197,
"text": "3. Repeated Checks for System Calls :Race Conditions are more probabilistic than deterministic (we can not determine when we would be able to get access to the file, it could happen during any instance within TOCTOU check window). Using Repeated checks on access() and open() system calls we can match the inode value of the file. While this value is the same in every check, we can say that the file is opened and if it’s different that means the file was changed, and we do not open it."
},
{
"code": null,
"e": 30710,
"s": 30686,
"text": "4. Atomic Operations : "
},
{
"code": null,
"e": 30743,
"s": 30710,
"text": "f = open(file, O_CREAT | O_EXCL)"
},
{
"code": null,
"e": 30920,
"s": 30743,
"text": "If the file already exists then these two specifiers which are stated above will not open the specified file. Hence implementing atomicity of the check and the use of the file."
},
{
"code": null,
"e": 30978,
"s": 30920,
"text": "References & Source Code: SEED Labs, Syracuse University."
},
{
"code": null,
"e": 31002,
"s": 30978,
"text": "Process Synchronization"
},
{
"code": null,
"e": 31026,
"s": 31002,
"text": "Technical Scripter 2020"
},
{
"code": null,
"e": 31044,
"s": 31026,
"text": "Operating Systems"
},
{
"code": null,
"e": 31062,
"s": 31044,
"text": "Operating Systems"
},
{
"code": null,
"e": 31160,
"s": 31062,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 31198,
"s": 31160,
"text": "Memory Management in Operating System"
},
{
"code": null,
"e": 31222,
"s": 31198,
"text": "File Allocation Methods"
},
{
"code": null,
"e": 31271,
"s": 31222,
"text": "Logical and Physical Address in Operating System"
},
{
"code": null,
"e": 31326,
"s": 31271,
"text": "Difference between Internal and External fragmentation"
},
{
"code": null,
"e": 31366,
"s": 31326,
"text": "File Access Methods in Operating System"
},
{
"code": null,
"e": 31414,
"s": 31366,
"text": "Memory Hierarchy Design and its Characteristics"
},
{
"code": null,
"e": 31447,
"s": 31414,
"text": "File Systems in Operating System"
},
{
"code": null,
"e": 31493,
"s": 31447,
"text": "Process Table and Process Control Block (PCB)"
},
{
"code": null,
"e": 31534,
"s": 31493,
"text": "States of a Process in Operating Systems"
}
] |
How to create Abstract Model Class in Django? - GeeksforGeeks | 16 Feb, 2021
Django is a high-level Python Web framework that encourages rapid development and clean, pragmatic design. Built by experienced developers, it takes care of much of the hassle of Web development, so you can focus on writing your app without needing to reinvent the wheel. It’s free and open source.
Model Inheritance in Django works almost identically to the way normal class inheritance works in python. In this article we will revolve around how to create abstract base class in Django Models.
Abstract Base Class :-
Abstract Base Class are useful when you want to put some common information into a number of other models. You write your base class and put abstract = True in the Meta Class. Suppose you have two model Student and Teacher.
models.py
Python3
from django.db import models class Student(models.Model): # STUDENT name = models.CharField(max_length=100) rollno = models.IntergerField() class Teacher(models.Model): # TEACHER name = models.CharField(max_length=100) ID = models.IntergerField()
So have you notice that one field name is common on both models.
So instead of adding common fields in both models ,we have create a another model and put those common fields in that model.
models.py
Python3
from django.db import models class common(models.Model): # COMM0N name = models.CharField(max_length=100) class Meta: abstract = True
So here I create a model common and put the common fields in that model.
Put abstract = True in the Meta class. After set abstract True, now it becomes an abstract class not a model,so now you can’t generate a database table.
Python3
class Student(common): # STUDENT rollno = models.IntegerField() class Teacher(common): # TEACHER ID = models.IntegerField()
Ubuntu
python3 manage.py makemigrations
python3 manage.py migrate
Now you can inherit the common name field in both Student and Teacher. Just like normal python inheritance.
Output :
Python Django
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Install PIP on Windows ?
Check if element exists in list in Python
How To Convert Python Dictionary To JSON?
How to drop one or multiple columns in Pandas Dataframe
Python Classes and Objects
Python | Get unique values from a list
Python | os.path.join() method
Defaultdict in Python
Create a directory in Python
Python | Pandas dataframe.groupby() | [
{
"code": null,
"e": 25563,
"s": 25535,
"text": "\n16 Feb, 2021"
},
{
"code": null,
"e": 25862,
"s": 25563,
"text": "Django is a high-level Python Web framework that encourages rapid development and clean, pragmatic design. Built by experienced developers, it takes care of much of the hassle of Web development, so you can focus on writing your app without needing to reinvent the wheel. It’s free and open source."
},
{
"code": null,
"e": 26059,
"s": 25862,
"text": "Model Inheritance in Django works almost identically to the way normal class inheritance works in python. In this article we will revolve around how to create abstract base class in Django Models."
},
{
"code": null,
"e": 26082,
"s": 26059,
"text": "Abstract Base Class :-"
},
{
"code": null,
"e": 26306,
"s": 26082,
"text": "Abstract Base Class are useful when you want to put some common information into a number of other models. You write your base class and put abstract = True in the Meta Class. Suppose you have two model Student and Teacher."
},
{
"code": null,
"e": 26316,
"s": 26306,
"text": "models.py"
},
{
"code": null,
"e": 26324,
"s": 26316,
"text": "Python3"
},
{
"code": "from django.db import models class Student(models.Model): # STUDENT name = models.CharField(max_length=100) rollno = models.IntergerField() class Teacher(models.Model): # TEACHER name = models.CharField(max_length=100) ID = models.IntergerField()",
"e": 26591,
"s": 26324,
"text": null
},
{
"code": null,
"e": 26657,
"s": 26591,
"text": "So have you notice that one field name is common on both models."
},
{
"code": null,
"e": 26782,
"s": 26657,
"text": "So instead of adding common fields in both models ,we have create a another model and put those common fields in that model."
},
{
"code": null,
"e": 26792,
"s": 26782,
"text": "models.py"
},
{
"code": null,
"e": 26800,
"s": 26792,
"text": "Python3"
},
{
"code": "from django.db import models class common(models.Model): # COMM0N name = models.CharField(max_length=100) class Meta: abstract = True",
"e": 26953,
"s": 26800,
"text": null
},
{
"code": null,
"e": 27026,
"s": 26953,
"text": "So here I create a model common and put the common fields in that model."
},
{
"code": null,
"e": 27179,
"s": 27026,
"text": "Put abstract = True in the Meta class. After set abstract True, now it becomes an abstract class not a model,so now you can’t generate a database table."
},
{
"code": null,
"e": 27187,
"s": 27179,
"text": "Python3"
},
{
"code": "class Student(common): # STUDENT rollno = models.IntegerField() class Teacher(common): # TEACHER ID = models.IntegerField()",
"e": 27322,
"s": 27187,
"text": null
},
{
"code": null,
"e": 27329,
"s": 27322,
"text": "Ubuntu"
},
{
"code": null,
"e": 27362,
"s": 27329,
"text": "python3 manage.py makemigrations"
},
{
"code": null,
"e": 27388,
"s": 27362,
"text": "python3 manage.py migrate"
},
{
"code": null,
"e": 27496,
"s": 27388,
"text": "Now you can inherit the common name field in both Student and Teacher. Just like normal python inheritance."
},
{
"code": null,
"e": 27505,
"s": 27496,
"text": "Output :"
},
{
"code": null,
"e": 27519,
"s": 27505,
"text": "Python Django"
},
{
"code": null,
"e": 27526,
"s": 27519,
"text": "Python"
},
{
"code": null,
"e": 27624,
"s": 27526,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 27656,
"s": 27624,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 27698,
"s": 27656,
"text": "Check if element exists in list in Python"
},
{
"code": null,
"e": 27740,
"s": 27698,
"text": "How To Convert Python Dictionary To JSON?"
},
{
"code": null,
"e": 27796,
"s": 27740,
"text": "How to drop one or multiple columns in Pandas Dataframe"
},
{
"code": null,
"e": 27823,
"s": 27796,
"text": "Python Classes and Objects"
},
{
"code": null,
"e": 27862,
"s": 27823,
"text": "Python | Get unique values from a list"
},
{
"code": null,
"e": 27893,
"s": 27862,
"text": "Python | os.path.join() method"
},
{
"code": null,
"e": 27915,
"s": 27893,
"text": "Defaultdict in Python"
},
{
"code": null,
"e": 27944,
"s": 27915,
"text": "Create a directory in Python"
}
] |
Range Structure in C# 8.0 - GeeksforGeeks | 09 Jul, 2021
C# 8.0 introduced a new predefined structure that is known as Range struct. This struct is used to represent a range that has a start and end indexes. It provides a new style to create a range using .. operator. This operator is used to create a range that has a starting and ending index. Also with the help of the Range struct you are allowed to create a variable of the range type.
C#
// C# program to illustrate how to create rangesusing System; namespace range_example { class GFG { // Main Method static void Main(string[] args) { int[] marks = new int[] {23, 45, 67, 88, 99, 56, 27, 67, 89, 90, 39}; // Creating variables of range type // And initialize the range // variables with a range // Using .. operator Range r1 = 1..5; Range r2 = 6..8; var a1 = marks[r1]; Console.Write("Marks List 1: "); foreach(var st_1 in a1) Console.Write($" {st_1} "); var a2 = marks[r2]; Console.Write("\nMarks List 2: "); foreach(var st_2 in a2) Console.Write($" {st_2} "); // Creating a range // Using .. operator var a3 = marks[2..4]; Console.Write("\nMarks List 3: "); foreach(var st_3 in a3) Console.Write($" {st_3} "); var a4 = marks[4..7]; Console.Write("\nMarks List 4: "); foreach(var st_4 in a4) Console.Write($" {st_4} "); }}}
Output:
Marks List 1: 45 67 88 99
Marks List 2: 27 67
Marks List 3: 67 88
Marks List 4: 99 56 27
gabaa406
rajeev0719singh
CSharp-8.0
C#
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
C# | Delegates
C# | Abstract Classes
Difference between Ref and Out keywords in C#
C# | Class and Object
Extension Method in C#
C# | Constructors
C# | String.IndexOf( ) Method | Set - 1
C# | Replace() Method
Introduction to .NET Framework
C# | Arrays | [
{
"code": null,
"e": 25245,
"s": 25217,
"text": "\n09 Jul, 2021"
},
{
"code": null,
"e": 25630,
"s": 25245,
"text": "C# 8.0 introduced a new predefined structure that is known as Range struct. This struct is used to represent a range that has a start and end indexes. It provides a new style to create a range using .. operator. This operator is used to create a range that has a starting and ending index. Also with the help of the Range struct you are allowed to create a variable of the range type."
},
{
"code": null,
"e": 25633,
"s": 25630,
"text": "C#"
},
{
"code": "// C# program to illustrate how to create rangesusing System; namespace range_example { class GFG { // Main Method static void Main(string[] args) { int[] marks = new int[] {23, 45, 67, 88, 99, 56, 27, 67, 89, 90, 39}; // Creating variables of range type // And initialize the range // variables with a range // Using .. operator Range r1 = 1..5; Range r2 = 6..8; var a1 = marks[r1]; Console.Write(\"Marks List 1: \"); foreach(var st_1 in a1) Console.Write($\" {st_1} \"); var a2 = marks[r2]; Console.Write(\"\\nMarks List 2: \"); foreach(var st_2 in a2) Console.Write($\" {st_2} \"); // Creating a range // Using .. operator var a3 = marks[2..4]; Console.Write(\"\\nMarks List 3: \"); foreach(var st_3 in a3) Console.Write($\" {st_3} \"); var a4 = marks[4..7]; Console.Write(\"\\nMarks List 4: \"); foreach(var st_4 in a4) Console.Write($\" {st_4} \"); }}}",
"e": 26708,
"s": 25633,
"text": null
},
{
"code": null,
"e": 26716,
"s": 26708,
"text": "Output:"
},
{
"code": null,
"e": 26819,
"s": 26716,
"text": "Marks List 1: 45 67 88 99 \nMarks List 2: 27 67 \nMarks List 3: 67 88 \nMarks List 4: 99 56 27"
},
{
"code": null,
"e": 26830,
"s": 26821,
"text": "gabaa406"
},
{
"code": null,
"e": 26846,
"s": 26830,
"text": "rajeev0719singh"
},
{
"code": null,
"e": 26857,
"s": 26846,
"text": "CSharp-8.0"
},
{
"code": null,
"e": 26860,
"s": 26857,
"text": "C#"
},
{
"code": null,
"e": 26958,
"s": 26860,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 26973,
"s": 26958,
"text": "C# | Delegates"
},
{
"code": null,
"e": 26995,
"s": 26973,
"text": "C# | Abstract Classes"
},
{
"code": null,
"e": 27041,
"s": 26995,
"text": "Difference between Ref and Out keywords in C#"
},
{
"code": null,
"e": 27063,
"s": 27041,
"text": "C# | Class and Object"
},
{
"code": null,
"e": 27086,
"s": 27063,
"text": "Extension Method in C#"
},
{
"code": null,
"e": 27104,
"s": 27086,
"text": "C# | Constructors"
},
{
"code": null,
"e": 27144,
"s": 27104,
"text": "C# | String.IndexOf( ) Method | Set - 1"
},
{
"code": null,
"e": 27166,
"s": 27144,
"text": "C# | Replace() Method"
},
{
"code": null,
"e": 27197,
"s": 27166,
"text": "Introduction to .NET Framework"
}
] |
Pandas — Save Memory with These Simple Tricks | by Soner Yıldırım | Towards Data Science | Memory is not a big concern when dealing with small-sized data. However, when it comes to large datasets, it becomes imperative to use memory efficiently. I will cover a few very simple tricks to reduce the size of a Pandas DataFrame. I will use a relatively large dataset about cryptocurrency market prices available on Kaggle. Let’s start with reading the data into a Pandas DataFrame.
import pandas as pdimport numpy as npdf = pd.read_csv("crypto-markets.csv")df.shape(942297, 13)
The dataframe has almost 1 million rows and 13 columns. It includes historical prices of cryptocurrencies.
Let’s check the size of this dataframe:
df.memory_usage()Index 80slug 7538376symbol 7538376name 7538376date 7538376ranknow 7538376open 7538376high 7538376low 7538376close 7538376volume 7538376market 7538376close_ratio 7538376spread 7538376dtype: int64
memory_usage() returns how much memory each row uses in bytes. We can check the memory usage for the complete dataframe in megabytes with a couple of math operations:
df.memory_usage().sum() / (1024**2) #converting to megabytes93.45909881591797
So the total size is 93.46 MB.
Let’s check the data types because we can represent the same amount information with more memory-friendly data types in some cases.
df.dtypesslug objectsymbol objectname objectdate objectranknow int64open float64high float64low float64close float64volume float64market float64close_ratio float64spread float64dtype: object
The first thing comes to mind should be “object” data type. If we have categorical data, it is better to use “category” data type instead of “object” especially when the number of categories is very low compared to the number of rows. This is the case for “slug”, “symbol” and “name” columns:
df.slug.value_counts().size2071
There are 2072 categories, which is very low compared to 1 million rows. Let’s convert these columns to “category” data type and see the reduction in memory usage:
df[['slug','symbol','name']] = df[['slug','symbol', 'name']].astype('category')df[['slug','symbol','name']].memory_usage()Index 80slug 1983082 #previous: 7538376symbol 1982554name 1983082dtype: int64
So the memory usage for each column reduced by %74. Let’s check how much we have saved in total:
df.memory_usage().sum() / (1024**2) #converting to megabytes77.56477165222168
The total size reduced to 77.56 MB from 93.46 MB.
The “ranknow” column shows the rank among different currency categories. Since there are 2072 categories, the maximum value should be 2072.
df.ranknow.max()2072
The data type of “ranknow” column is int64 but we can represent the range from 1 to 2072 using int16 as well. The range that can be represented with int16 is -32768 to +32767.
df["ranknow"] = df["ranknow"].astype("int16")df["ranknow"].memory_usage()1884674 #previous: 7538376
So the memory usage reduced by %75 as expected because we went down to int16 from int64.
The floating point numbers in the dataset are represented with “float64” but I can represent these numbers with “float32” which allows us to have 6 digits of precision. I think 6 digits is enough unless you are making highly sensitive measurements.
float32 (equivalent C type: float): 6 digits of precision
float64 (equivalent C type: double): 15 digits of precision
floats = df.select_dtypes(include=['float64']).columns.tolist()df[floats] = df[floats].astype('float32')df[floats].memory_usage()Index 80open 3769188 #previous: 7538376high 3769188low 3769188close 3769188volume 3769188market 3769188close_ratio 3769188spread 3769188dtype: int64
The conversion to “float32” from “float64” reduces the memory usage for these columns by %50 as expected.
In some cases, the dataframe may have redundant columns. Let’s take a look at the dataframe we have:
The columns “slug”, “symbol”, “name” represent the same thing in different formats. It is enough to only have one of these three columns so I can drop two columns. The dataframe you have may not have columns like this but it is always a good practice to look for redundant or unnecessary columns. For example, the dataframe might include “count”, “value” and “sum” columns. We can easily obtain sum by multiplying count and value so sum column is unnecessary. Some columns might be completely unrelated to the task you want to accomplish so just look for these columns. In my case, I will drop “symbol” and “name” columns and use “slug” column:
df.drop(['symbol','name'], axis=1, inplace=True)
Let’s check the size of the final dataframe:
df.memory_usage().sum() / (1024*1024)39.63435745239258
The total size reduced to 36.63 MB from 93.46 MB which I think is a great accomplishment. We were able to save 56,83 MB of memory.
Another advantage of reducing the size is to simplify and ease the computations. It takes less time to do calculations with float32 than with float64.
We should always look for ways to reduce the size when possible.
Thank you for reading. Please let me know if you have any feedback. | [
{
"code": null,
"e": 560,
"s": 172,
"text": "Memory is not a big concern when dealing with small-sized data. However, when it comes to large datasets, it becomes imperative to use memory efficiently. I will cover a few very simple tricks to reduce the size of a Pandas DataFrame. I will use a relatively large dataset about cryptocurrency market prices available on Kaggle. Let’s start with reading the data into a Pandas DataFrame."
},
{
"code": null,
"e": 656,
"s": 560,
"text": "import pandas as pdimport numpy as npdf = pd.read_csv(\"crypto-markets.csv\")df.shape(942297, 13)"
},
{
"code": null,
"e": 763,
"s": 656,
"text": "The dataframe has almost 1 million rows and 13 columns. It includes historical prices of cryptocurrencies."
},
{
"code": null,
"e": 803,
"s": 763,
"text": "Let’s check the size of this dataframe:"
},
{
"code": null,
"e": 1141,
"s": 803,
"text": "df.memory_usage()Index 80slug 7538376symbol 7538376name 7538376date 7538376ranknow 7538376open 7538376high 7538376low 7538376close 7538376volume 7538376market 7538376close_ratio 7538376spread 7538376dtype: int64"
},
{
"code": null,
"e": 1308,
"s": 1141,
"text": "memory_usage() returns how much memory each row uses in bytes. We can check the memory usage for the complete dataframe in megabytes with a couple of math operations:"
},
{
"code": null,
"e": 1386,
"s": 1308,
"text": "df.memory_usage().sum() / (1024**2) #converting to megabytes93.45909881591797"
},
{
"code": null,
"e": 1417,
"s": 1386,
"text": "So the total size is 93.46 MB."
},
{
"code": null,
"e": 1549,
"s": 1417,
"text": "Let’s check the data types because we can represent the same amount information with more memory-friendly data types in some cases."
},
{
"code": null,
"e": 1858,
"s": 1549,
"text": "df.dtypesslug objectsymbol objectname objectdate objectranknow int64open float64high float64low float64close float64volume float64market float64close_ratio float64spread float64dtype: object"
},
{
"code": null,
"e": 2151,
"s": 1858,
"text": "The first thing comes to mind should be “object” data type. If we have categorical data, it is better to use “category” data type instead of “object” especially when the number of categories is very low compared to the number of rows. This is the case for “slug”, “symbol” and “name” columns:"
},
{
"code": null,
"e": 2183,
"s": 2151,
"text": "df.slug.value_counts().size2071"
},
{
"code": null,
"e": 2347,
"s": 2183,
"text": "There are 2072 categories, which is very low compared to 1 million rows. Let’s convert these columns to “category” data type and see the reduction in memory usage:"
},
{
"code": null,
"e": 2569,
"s": 2347,
"text": "df[['slug','symbol','name']] = df[['slug','symbol', 'name']].astype('category')df[['slug','symbol','name']].memory_usage()Index 80slug 1983082 #previous: 7538376symbol 1982554name 1983082dtype: int64"
},
{
"code": null,
"e": 2666,
"s": 2569,
"text": "So the memory usage for each column reduced by %74. Let’s check how much we have saved in total:"
},
{
"code": null,
"e": 2744,
"s": 2666,
"text": "df.memory_usage().sum() / (1024**2) #converting to megabytes77.56477165222168"
},
{
"code": null,
"e": 2794,
"s": 2744,
"text": "The total size reduced to 77.56 MB from 93.46 MB."
},
{
"code": null,
"e": 2934,
"s": 2794,
"text": "The “ranknow” column shows the rank among different currency categories. Since there are 2072 categories, the maximum value should be 2072."
},
{
"code": null,
"e": 2955,
"s": 2934,
"text": "df.ranknow.max()2072"
},
{
"code": null,
"e": 3131,
"s": 2955,
"text": "The data type of “ranknow” column is int64 but we can represent the range from 1 to 2072 using int16 as well. The range that can be represented with int16 is -32768 to +32767."
},
{
"code": null,
"e": 3231,
"s": 3131,
"text": "df[\"ranknow\"] = df[\"ranknow\"].astype(\"int16\")df[\"ranknow\"].memory_usage()1884674 #previous: 7538376"
},
{
"code": null,
"e": 3320,
"s": 3231,
"text": "So the memory usage reduced by %75 as expected because we went down to int16 from int64."
},
{
"code": null,
"e": 3569,
"s": 3320,
"text": "The floating point numbers in the dataset are represented with “float64” but I can represent these numbers with “float32” which allows us to have 6 digits of precision. I think 6 digits is enough unless you are making highly sensitive measurements."
},
{
"code": null,
"e": 3627,
"s": 3569,
"text": "float32 (equivalent C type: float): 6 digits of precision"
},
{
"code": null,
"e": 3687,
"s": 3627,
"text": "float64 (equivalent C type: double): 15 digits of precision"
},
{
"code": null,
"e": 4046,
"s": 3687,
"text": "floats = df.select_dtypes(include=['float64']).columns.tolist()df[floats] = df[floats].astype('float32')df[floats].memory_usage()Index 80open 3769188 #previous: 7538376high 3769188low 3769188close 3769188volume 3769188market 3769188close_ratio 3769188spread 3769188dtype: int64"
},
{
"code": null,
"e": 4152,
"s": 4046,
"text": "The conversion to “float32” from “float64” reduces the memory usage for these columns by %50 as expected."
},
{
"code": null,
"e": 4253,
"s": 4152,
"text": "In some cases, the dataframe may have redundant columns. Let’s take a look at the dataframe we have:"
},
{
"code": null,
"e": 4898,
"s": 4253,
"text": "The columns “slug”, “symbol”, “name” represent the same thing in different formats. It is enough to only have one of these three columns so I can drop two columns. The dataframe you have may not have columns like this but it is always a good practice to look for redundant or unnecessary columns. For example, the dataframe might include “count”, “value” and “sum” columns. We can easily obtain sum by multiplying count and value so sum column is unnecessary. Some columns might be completely unrelated to the task you want to accomplish so just look for these columns. In my case, I will drop “symbol” and “name” columns and use “slug” column:"
},
{
"code": null,
"e": 4947,
"s": 4898,
"text": "df.drop(['symbol','name'], axis=1, inplace=True)"
},
{
"code": null,
"e": 4992,
"s": 4947,
"text": "Let’s check the size of the final dataframe:"
},
{
"code": null,
"e": 5047,
"s": 4992,
"text": "df.memory_usage().sum() / (1024*1024)39.63435745239258"
},
{
"code": null,
"e": 5178,
"s": 5047,
"text": "The total size reduced to 36.63 MB from 93.46 MB which I think is a great accomplishment. We were able to save 56,83 MB of memory."
},
{
"code": null,
"e": 5329,
"s": 5178,
"text": "Another advantage of reducing the size is to simplify and ease the computations. It takes less time to do calculations with float32 than with float64."
},
{
"code": null,
"e": 5394,
"s": 5329,
"text": "We should always look for ways to reduce the size when possible."
}
] |
Image Viewer App in Python using Tkinter - GeeksforGeeks | 04 Oct, 2021
Prerequisites: Python GUI – tkinter, Python: Pillow
Have you ever wondered to make a Image viewer with the help of Python? Here is a solution to making the Image viewer with the help of Python. We can do this with the help of Tkinter and pillow. We will discuss the module needed and code below.
Tkinter: Tkinter is library with the help of which we can make GUI(Graphical User Interface).
pip install tkinter
Pillow: We can add photos as it is an imaging library of Python.
pip install pillow
Now let’s code for it
Below Code demonstrates the basic structures, button initialization, and layout of the GUI produced
Python3
# importing the tkinter module and PIL that# is pillow modulefrom tkinter import *from PIL import ImageTk, Image # Calling the Tk (The initial constructor of tkinter)root = Tk() # We will make the title of our app as Image Viewerroot.title("Image Viewer") # The geometry of the box which will be displayed# on the screenroot.geometry("700x700") # Adding the images using the pillow module which# has a class ImageTk We can directly add the# photos in the tkinter folder or we have to# give a proper path for the imagesimage_no_1 = ImageTk.PhotoImage(Image.open("Sample.png"))image_no_2 = ImageTk.PhotoImage(Image.open("sample.png"))image_no_3 = ImageTk.PhotoImage(Image.open("Sample.png"))image_no_4 = ImageTk.PhotoImage(Image.open("sample.png")) # List of the images so that we traverse the listList_images = [image_no_1, image_no_2, image_no_3, image_no_4] label = Label(image=image_no_1) # We have to show the the box so this below line is neededlabel.grid(row=1, column=0, columnspan=3) # We will have three button back ,forward and exitbutton_back = Button(root, text="Back", command=back, state=DISABLED) # root.quit for closing the appbutton_exit = Button(root, text="Exit", command=root.quit) button_forward = Button(root, text="Forward", command=lambda: forward(1)) # grid function is for placing the buttons in the framebutton_back.grid(row=5, column=0)button_exit.grid(row=5, column=1)button_forward.grid(row=5, column=2) root.mainloop()
Forward function: This function is for adding the functionality to forward button
Python3
def forward(img_no): # GLobal variable so that we can have # access and change the variable # whenever needed global label global button_forward global button_back global button_exit label.grid_forget() # This is for clearing the screen so that # our next image can pop up label = Label(image=List_images[img_no-1]) # as the list starts from 0 so we are # subtracting one label.grid(row=1, column=0, columnspan=3) button_for = Button(root, text="forward", command=lambda: forward(img_no+1)) # img_no+1 as we want the next image to pop up if img_no == 4: button_forward = Button(root, text="Forward", state=DISABLED) # img_no-1 as we want previous image when we click # back button button_back = Button(root, text="Back", command=lambda: back(img_no-1)) # Placing the button in new grid button_back.grid(row=5, column=0) button_exit.grid(row=5, column=1) button_for.grid(row=5, column=2)
Backward Function: This function is for adding the functionality to backward button
Python3
def back(img_no): # We will have global variable to access these # variable and change whenever needed global label global button_forward global button_back global button_exit label.grid_forget() # for clearing the image for new image to pop up label = Label(image=List_images[img_no - 1]) label.grid(row=1, column=0, columnspan=3) button_forward = Button(root, text="forward", command=lambda: forward(img_no + 1)) button_back = Button(root, text="Back", command=lambda: back(img_no - 1)) print(img_no) # whenever the first image will be there we will # have the back button disabled if img_no == 1: button_back = Button(root, Text="Back", state=DISABLED) label.grid(row=1, column=0, columnspan=3) button_back.grid(row=5, column=0) button_exit.grid(row=5, column=1) button_for.grid(row=5, column=2)
Complete Code
Images Used and their order –
Order in which the images will be shown.
Python3
# importing the tkinter module and PIL# that is pillow modulefrom tkinter import *from PIL import ImageTk, Image def forward(img_no): # GLobal variable so that we can have # access and change the variable # whenever needed global label global button_forward global button_back global button_exit label.grid_forget() # This is for clearing the screen so that # our next image can pop up label = Label(image=List_images[img_no-1]) # as the list starts from 0 so we are # subtracting one label.grid(row=1, column=0, columnspan=3) button_for = Button(root, text="forward", command=lambda: forward(img_no+1)) # img_no+1 as we want the next image to pop up if img_no == 4: button_forward = Button(root, text="Forward", state=DISABLED) # img_no-1 as we want previous image when we click # back button button_back = Button(root, text="Back", command=lambda: back(img_no-1)) # Placing the button in new grid button_back.grid(row=5, column=0) button_exit.grid(row=5, column=1) button_for.grid(row=5, column=2) def back(img_no): # We will have global variable to access these # variable and change whenever needed global label global button_forward global button_back global button_exit label.grid_forget() # for clearing the image for new image to pop up label = Label(image=List_images[img_no - 1]) label.grid(row=1, column=0, columnspan=3) button_forward = Button(root, text="forward", command=lambda: forward(img_no + 1)) button_back = Button(root, text="Back", command=lambda: back(img_no - 1)) print(img_no) # whenever the first image will be there we will # have the back button disabled if img_no == 1: button_back = Button(root, Text="Back", state=DISABLED) label.grid(row=1, column=0, columnspan=3) button_back.grid(row=5, column=0) button_exit.grid(row=5, column=1) button_for.grid(row=5, column=2) # Calling the Tk (The initial constructor of tkinter)root = Tk() # We will make the title of our app as Image Viewerroot.title("Image Viewer") # The geometry of the box which will be displayed# on the screenroot.geometry("700x700") # Adding the images using the pillow module which# has a class ImageTk We can directly add the# photos in the tkinter folder or we have to# give a proper path for the imagesimage_no_1 = ImageTk.PhotoImage(Image.open("Sample.png"))image_no_2 = ImageTk.PhotoImage(Image.open("sample.png"))image_no_3 = ImageTk.PhotoImage(Image.open("Sample.png"))image_no_4 = ImageTk.PhotoImage(Image.open("sample.png")) # List of the images so that we traverse the listList_images = [image_no_1, image_no_2, image_no_3, image_no_4] label = Label(image=image_no_1) # We have to show the the box so this below line is neededlabel.grid(row=1, column=0, columnspan=3) # We will have three button back ,forward and exitbutton_back = Button(root, text="Back", command=back, state=DISABLED) # root.quit for closing the appbutton_exit = Button(root, text="Exit", command=root.quit) button_forward = Button(root, text="Forward", command=lambda: forward(1)) # grid function is for placing the buttons in the framebutton_back.grid(row=5, column=0)button_exit.grid(row=5, column=1)button_forward.grid(row=5, column=2) root.mainloop()
Output:
simmytarika5
surindertarika1234
simranarora5sos
Python Tkinter-exercises
Python-projects
Python-tkinter
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
How to Install PIP on Windows ?
How to drop one or multiple columns in Pandas Dataframe
Python OOPs Concepts
Python | Get unique values from a list
Check if element exists in list in Python
Python Classes and Objects
Python | os.path.join() method
How To Convert Python Dictionary To JSON?
Python | Pandas dataframe.groupby()
Create a directory in Python | [
{
"code": null,
"e": 24212,
"s": 24184,
"text": "\n04 Oct, 2021"
},
{
"code": null,
"e": 24264,
"s": 24212,
"text": "Prerequisites: Python GUI – tkinter, Python: Pillow"
},
{
"code": null,
"e": 24509,
"s": 24264,
"text": "Have you ever wondered to make a Image viewer with the help of Python? Here is a solution to making the Image viewer with the help of Python. We can do this with the help of Tkinter and pillow. We will discuss the module needed and code below. "
},
{
"code": null,
"e": 24604,
"s": 24509,
"text": "Tkinter: Tkinter is library with the help of which we can make GUI(Graphical User Interface)."
},
{
"code": null,
"e": 24625,
"s": 24604,
"text": " pip install tkinter"
},
{
"code": null,
"e": 24690,
"s": 24625,
"text": "Pillow: We can add photos as it is an imaging library of Python."
},
{
"code": null,
"e": 24710,
"s": 24690,
"text": " pip install pillow"
},
{
"code": null,
"e": 24732,
"s": 24710,
"text": "Now let’s code for it"
},
{
"code": null,
"e": 24832,
"s": 24732,
"text": "Below Code demonstrates the basic structures, button initialization, and layout of the GUI produced"
},
{
"code": null,
"e": 24840,
"s": 24832,
"text": "Python3"
},
{
"code": "# importing the tkinter module and PIL that# is pillow modulefrom tkinter import *from PIL import ImageTk, Image # Calling the Tk (The initial constructor of tkinter)root = Tk() # We will make the title of our app as Image Viewerroot.title(\"Image Viewer\") # The geometry of the box which will be displayed# on the screenroot.geometry(\"700x700\") # Adding the images using the pillow module which# has a class ImageTk We can directly add the# photos in the tkinter folder or we have to# give a proper path for the imagesimage_no_1 = ImageTk.PhotoImage(Image.open(\"Sample.png\"))image_no_2 = ImageTk.PhotoImage(Image.open(\"sample.png\"))image_no_3 = ImageTk.PhotoImage(Image.open(\"Sample.png\"))image_no_4 = ImageTk.PhotoImage(Image.open(\"sample.png\")) # List of the images so that we traverse the listList_images = [image_no_1, image_no_2, image_no_3, image_no_4] label = Label(image=image_no_1) # We have to show the the box so this below line is neededlabel.grid(row=1, column=0, columnspan=3) # We will have three button back ,forward and exitbutton_back = Button(root, text=\"Back\", command=back, state=DISABLED) # root.quit for closing the appbutton_exit = Button(root, text=\"Exit\", command=root.quit) button_forward = Button(root, text=\"Forward\", command=lambda: forward(1)) # grid function is for placing the buttons in the framebutton_back.grid(row=5, column=0)button_exit.grid(row=5, column=1)button_forward.grid(row=5, column=2) root.mainloop()",
"e": 26352,
"s": 24840,
"text": null
},
{
"code": null,
"e": 26434,
"s": 26352,
"text": "Forward function: This function is for adding the functionality to forward button"
},
{
"code": null,
"e": 26442,
"s": 26434,
"text": "Python3"
},
{
"code": "def forward(img_no): # GLobal variable so that we can have # access and change the variable # whenever needed global label global button_forward global button_back global button_exit label.grid_forget() # This is for clearing the screen so that # our next image can pop up label = Label(image=List_images[img_no-1]) # as the list starts from 0 so we are # subtracting one label.grid(row=1, column=0, columnspan=3) button_for = Button(root, text=\"forward\", command=lambda: forward(img_no+1)) # img_no+1 as we want the next image to pop up if img_no == 4: button_forward = Button(root, text=\"Forward\", state=DISABLED) # img_no-1 as we want previous image when we click # back button button_back = Button(root, text=\"Back\", command=lambda: back(img_no-1)) # Placing the button in new grid button_back.grid(row=5, column=0) button_exit.grid(row=5, column=1) button_for.grid(row=5, column=2)",
"e": 27492,
"s": 26442,
"text": null
},
{
"code": null,
"e": 27576,
"s": 27492,
"text": "Backward Function: This function is for adding the functionality to backward button"
},
{
"code": null,
"e": 27584,
"s": 27576,
"text": "Python3"
},
{
"code": "def back(img_no): # We will have global variable to access these # variable and change whenever needed global label global button_forward global button_back global button_exit label.grid_forget() # for clearing the image for new image to pop up label = Label(image=List_images[img_no - 1]) label.grid(row=1, column=0, columnspan=3) button_forward = Button(root, text=\"forward\", command=lambda: forward(img_no + 1)) button_back = Button(root, text=\"Back\", command=lambda: back(img_no - 1)) print(img_no) # whenever the first image will be there we will # have the back button disabled if img_no == 1: button_back = Button(root, Text=\"Back\", state=DISABLED) label.grid(row=1, column=0, columnspan=3) button_back.grid(row=5, column=0) button_exit.grid(row=5, column=1) button_for.grid(row=5, column=2)",
"e": 28505,
"s": 27584,
"text": null
},
{
"code": null,
"e": 28519,
"s": 28505,
"text": "Complete Code"
},
{
"code": null,
"e": 28550,
"s": 28519,
"text": "Images Used and their order – "
},
{
"code": null,
"e": 28591,
"s": 28550,
"text": "Order in which the images will be shown."
},
{
"code": null,
"e": 28599,
"s": 28591,
"text": "Python3"
},
{
"code": "# importing the tkinter module and PIL# that is pillow modulefrom tkinter import *from PIL import ImageTk, Image def forward(img_no): # GLobal variable so that we can have # access and change the variable # whenever needed global label global button_forward global button_back global button_exit label.grid_forget() # This is for clearing the screen so that # our next image can pop up label = Label(image=List_images[img_no-1]) # as the list starts from 0 so we are # subtracting one label.grid(row=1, column=0, columnspan=3) button_for = Button(root, text=\"forward\", command=lambda: forward(img_no+1)) # img_no+1 as we want the next image to pop up if img_no == 4: button_forward = Button(root, text=\"Forward\", state=DISABLED) # img_no-1 as we want previous image when we click # back button button_back = Button(root, text=\"Back\", command=lambda: back(img_no-1)) # Placing the button in new grid button_back.grid(row=5, column=0) button_exit.grid(row=5, column=1) button_for.grid(row=5, column=2) def back(img_no): # We will have global variable to access these # variable and change whenever needed global label global button_forward global button_back global button_exit label.grid_forget() # for clearing the image for new image to pop up label = Label(image=List_images[img_no - 1]) label.grid(row=1, column=0, columnspan=3) button_forward = Button(root, text=\"forward\", command=lambda: forward(img_no + 1)) button_back = Button(root, text=\"Back\", command=lambda: back(img_no - 1)) print(img_no) # whenever the first image will be there we will # have the back button disabled if img_no == 1: button_back = Button(root, Text=\"Back\", state=DISABLED) label.grid(row=1, column=0, columnspan=3) button_back.grid(row=5, column=0) button_exit.grid(row=5, column=1) button_for.grid(row=5, column=2) # Calling the Tk (The initial constructor of tkinter)root = Tk() # We will make the title of our app as Image Viewerroot.title(\"Image Viewer\") # The geometry of the box which will be displayed# on the screenroot.geometry(\"700x700\") # Adding the images using the pillow module which# has a class ImageTk We can directly add the# photos in the tkinter folder or we have to# give a proper path for the imagesimage_no_1 = ImageTk.PhotoImage(Image.open(\"Sample.png\"))image_no_2 = ImageTk.PhotoImage(Image.open(\"sample.png\"))image_no_3 = ImageTk.PhotoImage(Image.open(\"Sample.png\"))image_no_4 = ImageTk.PhotoImage(Image.open(\"sample.png\")) # List of the images so that we traverse the listList_images = [image_no_1, image_no_2, image_no_3, image_no_4] label = Label(image=image_no_1) # We have to show the the box so this below line is neededlabel.grid(row=1, column=0, columnspan=3) # We will have three button back ,forward and exitbutton_back = Button(root, text=\"Back\", command=back, state=DISABLED) # root.quit for closing the appbutton_exit = Button(root, text=\"Exit\", command=root.quit) button_forward = Button(root, text=\"Forward\", command=lambda: forward(1)) # grid function is for placing the buttons in the framebutton_back.grid(row=5, column=0)button_exit.grid(row=5, column=1)button_forward.grid(row=5, column=2) root.mainloop()",
"e": 32085,
"s": 28599,
"text": null
},
{
"code": null,
"e": 32093,
"s": 32085,
"text": "Output:"
},
{
"code": null,
"e": 32106,
"s": 32093,
"text": "simmytarika5"
},
{
"code": null,
"e": 32125,
"s": 32106,
"text": "surindertarika1234"
},
{
"code": null,
"e": 32141,
"s": 32125,
"text": "simranarora5sos"
},
{
"code": null,
"e": 32166,
"s": 32141,
"text": "Python Tkinter-exercises"
},
{
"code": null,
"e": 32182,
"s": 32166,
"text": "Python-projects"
},
{
"code": null,
"e": 32197,
"s": 32182,
"text": "Python-tkinter"
},
{
"code": null,
"e": 32204,
"s": 32197,
"text": "Python"
},
{
"code": null,
"e": 32302,
"s": 32204,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 32311,
"s": 32302,
"text": "Comments"
},
{
"code": null,
"e": 32324,
"s": 32311,
"text": "Old Comments"
},
{
"code": null,
"e": 32356,
"s": 32324,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 32412,
"s": 32356,
"text": "How to drop one or multiple columns in Pandas Dataframe"
},
{
"code": null,
"e": 32433,
"s": 32412,
"text": "Python OOPs Concepts"
},
{
"code": null,
"e": 32472,
"s": 32433,
"text": "Python | Get unique values from a list"
},
{
"code": null,
"e": 32514,
"s": 32472,
"text": "Check if element exists in list in Python"
},
{
"code": null,
"e": 32541,
"s": 32514,
"text": "Python Classes and Objects"
},
{
"code": null,
"e": 32572,
"s": 32541,
"text": "Python | os.path.join() method"
},
{
"code": null,
"e": 32614,
"s": 32572,
"text": "How To Convert Python Dictionary To JSON?"
},
{
"code": null,
"e": 32650,
"s": 32614,
"text": "Python | Pandas dataframe.groupby()"
}
] |
Creating a Powerful COVID-19 Mask Detection Tool with PyTorch | by David Yastremsky | Towards Data Science | Over the last year, COVID-19 has taken a social, economic, and human toll on the world. AI tools can identify proper mask-wearing to help reopen the world and prevent future pandemics.
Of course, this has deeper social implications, such as the tradeoff of privacy versus security. These are discussed in the accompanying arXiv research paper here.
In this post, I will walk you through the project that we created.
After reading this post, you will have the knowledge to create a similar pipeline not only for mask detection but any sort of image recognition.
Using the MaskedFace-Net and Flickr Faces datasets, we resized the images to be 128x128 to save space. We moved images into three folders (train, val, and test). Each folder had three subdirectories (correct/incorrect/no_mask). This allowed them to be easily loaded with PyTorch’s torchvision.
batch = 16train_dataset = torchvision.datasets.ImageFolder('./Data_Sample/train', transform = train_transform)val_dataset = torchvision.datasets.ImageFolder('./Data_Sample/val', transform = test_transform)test_dataset = torchvision.datasets.ImageFolder('./Data_Sample/test', transform = test_transform)train_dataset_loader = torch.utils.data.DataLoader(train_dataset, batch_size=batch, shuffle=True)val_dataset_loader = torch.utils.data.DataLoader(val_dataset, batch_size=batch, shuffle=True)test_dataset_loader = torch.utils.data.DataLoader(test_dataset, batch_size=batch, shuffle=False)
If you look at the code snippet, you’ll see that we used torchvision’s built-in arguments to apply transformations to our images.
For all data, we changed the image to a tensor and normalized it using some standard values. For training and validation data, we applied additional transformations. For example, recoloring, resizing, and blurring the image randomly. These are applied to each batch, meaning the model is trying to learn a moving target: training images with different noise applied each time.
import torchvision.transforms as transformstest_transform = transforms.Compose([transforms.ToTensor(),transforms.Normalize(mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225]),])
Transforms regularize your model to make it generalize better. As a result, it will perform better on real-world data.
With a goal like real-time image classification, accuracy and speed are both key. These often have a tradeoff, as larger models can have higher accuracy. To get a baseline, we started by applying faster machine learning models.
Boy, were we in for a surprise! We realized that our dataset’s use of synthetic models made predicting somewhat trivial. Under time pressure and without a dataset near the 180k images we were using, we pressed on to see how we could improve performance further.
For these simpler models, we trained scikit-learn’s random forest, cv2’s Haar cascade classifier, and a custom CNN using LeakyReLU and AdamW.
We next moved on to using state-of-the-art models. Top researchers train and finetune these models, using millions of dollars of computing. For general problems, they tend to work best.
We could train them on our data, seeing how they perform on our mask classification task. This transfer learning would be much faster than training it from scratch, as the weights would be close to optimal already. Our training would finetune them.
The below function was used with different torchvision models to see how well they perform.
# Takes the model and applies transfer learning# Returns the model and an array of validation accuraciesdef train_model(model, dataloaders, optimizer, criterion, scheduler, device, num_epochs=20): startTime = time.time() top_model = copy.deepcopy(model.state_dict()) top_acc = 0.0 for epoch in range(num_epochs): for data_split in ['Train', 'Validation']: if data_split == 'Train': scheduler.step() model.train() else: model.eval() # Track running loss and correct predictions running_loss = 0.0 running_correct = 0 # Move to device for inputs, labels in dataloaders[data_split]: inputs = inputs.to(device) labels = labels.to(device) # Zero out the gradient optimizer.zero_grad()# Forward pass # Gradient is turned on for train with torch.set_grad_enabled(data_split == "Train"): outputs = model(inputs) loss = criterion(outputs, labels) _, preds = torch.max(outputs, 1) if data_split == "Train": loss.backward() optimizer.step() # Update running loss and correct predictions running_loss += loss.item() * inputs.size(0) running_correct += torch.sum (labels.data == preds) epoch_loss = running_loss / dataloader_sizes[data_split] epoch_acc = running_correct.double() / dataloader_sizes[data_split] print('{} Loss: {:.2f}, Accuracy: {:.2f}'.format(data_split, epoch_loss, epoch_acc)) # If this the top model, deep copy it if data_split == "Validation" and epoch_acc > top_acc: top_acc = epoch_acc top_model = copy.deepcopy(model.state_dict()) print("Highest validation accuracy: {:.2f}".format(top_acc)) # Load best model's weights model.load_state_dict(top_model) return model;
Since our focus was speed, we chose four of the smaller yet performant neural networks and achieved the below results:
Massive improvement! But could we do better?
This was the golden step.
Distillation is a bleeding-edge technique that trains smaller models to make faster predictions. It distills the knowledge in a network. This is perfect for our use case.
In distillation, you train a student from a teacher model. Instead of training your model on your data, you train it on the predictions of another model. As a result, you replicate the results with a smaller network.
Distillation can be challenging and resource-intensive to implement. Luckily, KD_Lib for PyTorch provides implementations of research papers accessible as a library. The below code snippet was used for vanilla distillation.
import torchimport torch.optim as optimfrom torchvision import datasets, transformsfrom KD_Lib.KD import VanillaKD# Define modelsteacher_model = resnetstudent_model = inception# Define optimizersteacher_optimizer = optim.SGD(teacher_model.parameters(), 0.01)student_optimizer = optim.SGD(student_model.parameters(), 0.01)# Perform distillationdistiller = VanillaKD(teacher_model, student_model, train_dataset_loader, val_dataset_loader,teacher_optimizer, student_optimizer, device = 'cuda')distiller.train_teacher(epochs=5, plot_losses=True, save_model=True)distiller.train_student(epochs=5, plot_losses=True, save_model=True)distiller.evaluate(teacher=False)distiller.get_parameters()
Using vanilla distillation on our DenseNet model, we achieved 99.85% accuracy with our baseline CNN. The CNN outperformed every state-of-the-art model’s speed at 775 inferences/second on a V100. The CNN did this with <15% as many parameters.
Even more impressively, running distillation again continued to improve the accuracy. For example, results improved with a combination of NoisyTeacher, SelfTraining, and MessyCollab.
Side note: self-training uses your model as both the teacher and the student, how cool!
Creating a classifier for proper mask usage felt both timely and urgent.
The lessons in building out this pipeline are useful for any image classification task you would like to do. Hopefully, this pipeline helps with understanding and solving any image classification task you aim to do. Good luck!
Associated Paper: https://arxiv.org/pdf/2105.01816.pdf
Associated Demo: https://www.youtube.com/watch?v=iyf4uRWgkaI | [
{
"code": null,
"e": 356,
"s": 171,
"text": "Over the last year, COVID-19 has taken a social, economic, and human toll on the world. AI tools can identify proper mask-wearing to help reopen the world and prevent future pandemics."
},
{
"code": null,
"e": 520,
"s": 356,
"text": "Of course, this has deeper social implications, such as the tradeoff of privacy versus security. These are discussed in the accompanying arXiv research paper here."
},
{
"code": null,
"e": 587,
"s": 520,
"text": "In this post, I will walk you through the project that we created."
},
{
"code": null,
"e": 732,
"s": 587,
"text": "After reading this post, you will have the knowledge to create a similar pipeline not only for mask detection but any sort of image recognition."
},
{
"code": null,
"e": 1026,
"s": 732,
"text": "Using the MaskedFace-Net and Flickr Faces datasets, we resized the images to be 128x128 to save space. We moved images into three folders (train, val, and test). Each folder had three subdirectories (correct/incorrect/no_mask). This allowed them to be easily loaded with PyTorch’s torchvision."
},
{
"code": null,
"e": 1615,
"s": 1026,
"text": "batch = 16train_dataset = torchvision.datasets.ImageFolder('./Data_Sample/train', transform = train_transform)val_dataset = torchvision.datasets.ImageFolder('./Data_Sample/val', transform = test_transform)test_dataset = torchvision.datasets.ImageFolder('./Data_Sample/test', transform = test_transform)train_dataset_loader = torch.utils.data.DataLoader(train_dataset, batch_size=batch, shuffle=True)val_dataset_loader = torch.utils.data.DataLoader(val_dataset, batch_size=batch, shuffle=True)test_dataset_loader = torch.utils.data.DataLoader(test_dataset, batch_size=batch, shuffle=False)"
},
{
"code": null,
"e": 1745,
"s": 1615,
"text": "If you look at the code snippet, you’ll see that we used torchvision’s built-in arguments to apply transformations to our images."
},
{
"code": null,
"e": 2122,
"s": 1745,
"text": "For all data, we changed the image to a tensor and normalized it using some standard values. For training and validation data, we applied additional transformations. For example, recoloring, resizing, and blurring the image randomly. These are applied to each batch, meaning the model is trying to learn a moving target: training images with different noise applied each time."
},
{
"code": null,
"e": 2303,
"s": 2122,
"text": "import torchvision.transforms as transformstest_transform = transforms.Compose([transforms.ToTensor(),transforms.Normalize(mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225]),])"
},
{
"code": null,
"e": 2422,
"s": 2303,
"text": "Transforms regularize your model to make it generalize better. As a result, it will perform better on real-world data."
},
{
"code": null,
"e": 2650,
"s": 2422,
"text": "With a goal like real-time image classification, accuracy and speed are both key. These often have a tradeoff, as larger models can have higher accuracy. To get a baseline, we started by applying faster machine learning models."
},
{
"code": null,
"e": 2912,
"s": 2650,
"text": "Boy, were we in for a surprise! We realized that our dataset’s use of synthetic models made predicting somewhat trivial. Under time pressure and without a dataset near the 180k images we were using, we pressed on to see how we could improve performance further."
},
{
"code": null,
"e": 3054,
"s": 2912,
"text": "For these simpler models, we trained scikit-learn’s random forest, cv2’s Haar cascade classifier, and a custom CNN using LeakyReLU and AdamW."
},
{
"code": null,
"e": 3240,
"s": 3054,
"text": "We next moved on to using state-of-the-art models. Top researchers train and finetune these models, using millions of dollars of computing. For general problems, they tend to work best."
},
{
"code": null,
"e": 3489,
"s": 3240,
"text": "We could train them on our data, seeing how they perform on our mask classification task. This transfer learning would be much faster than training it from scratch, as the weights would be close to optimal already. Our training would finetune them."
},
{
"code": null,
"e": 3581,
"s": 3489,
"text": "The below function was used with different torchvision models to see how well they perform."
},
{
"code": null,
"e": 5250,
"s": 3581,
"text": "# Takes the model and applies transfer learning# Returns the model and an array of validation accuraciesdef train_model(model, dataloaders, optimizer, criterion, scheduler, device, num_epochs=20): startTime = time.time() top_model = copy.deepcopy(model.state_dict()) top_acc = 0.0 for epoch in range(num_epochs): for data_split in ['Train', 'Validation']: if data_split == 'Train': scheduler.step() model.train() else: model.eval() # Track running loss and correct predictions running_loss = 0.0 running_correct = 0 # Move to device for inputs, labels in dataloaders[data_split]: inputs = inputs.to(device) labels = labels.to(device) # Zero out the gradient optimizer.zero_grad()# Forward pass # Gradient is turned on for train with torch.set_grad_enabled(data_split == \"Train\"): outputs = model(inputs) loss = criterion(outputs, labels) _, preds = torch.max(outputs, 1) if data_split == \"Train\": loss.backward() optimizer.step() # Update running loss and correct predictions running_loss += loss.item() * inputs.size(0) running_correct += torch.sum (labels.data == preds) epoch_loss = running_loss / dataloader_sizes[data_split] epoch_acc = running_correct.double() / dataloader_sizes[data_split] print('{} Loss: {:.2f}, Accuracy: {:.2f}'.format(data_split, epoch_loss, epoch_acc)) # If this the top model, deep copy it if data_split == \"Validation\" and epoch_acc > top_acc: top_acc = epoch_acc top_model = copy.deepcopy(model.state_dict()) print(\"Highest validation accuracy: {:.2f}\".format(top_acc)) # Load best model's weights model.load_state_dict(top_model) return model;"
},
{
"code": null,
"e": 5369,
"s": 5250,
"text": "Since our focus was speed, we chose four of the smaller yet performant neural networks and achieved the below results:"
},
{
"code": null,
"e": 5414,
"s": 5369,
"text": "Massive improvement! But could we do better?"
},
{
"code": null,
"e": 5440,
"s": 5414,
"text": "This was the golden step."
},
{
"code": null,
"e": 5611,
"s": 5440,
"text": "Distillation is a bleeding-edge technique that trains smaller models to make faster predictions. It distills the knowledge in a network. This is perfect for our use case."
},
{
"code": null,
"e": 5828,
"s": 5611,
"text": "In distillation, you train a student from a teacher model. Instead of training your model on your data, you train it on the predictions of another model. As a result, you replicate the results with a smaller network."
},
{
"code": null,
"e": 6052,
"s": 5828,
"text": "Distillation can be challenging and resource-intensive to implement. Luckily, KD_Lib for PyTorch provides implementations of research papers accessible as a library. The below code snippet was used for vanilla distillation."
},
{
"code": null,
"e": 6738,
"s": 6052,
"text": "import torchimport torch.optim as optimfrom torchvision import datasets, transformsfrom KD_Lib.KD import VanillaKD# Define modelsteacher_model = resnetstudent_model = inception# Define optimizersteacher_optimizer = optim.SGD(teacher_model.parameters(), 0.01)student_optimizer = optim.SGD(student_model.parameters(), 0.01)# Perform distillationdistiller = VanillaKD(teacher_model, student_model, train_dataset_loader, val_dataset_loader,teacher_optimizer, student_optimizer, device = 'cuda')distiller.train_teacher(epochs=5, plot_losses=True, save_model=True)distiller.train_student(epochs=5, plot_losses=True, save_model=True)distiller.evaluate(teacher=False)distiller.get_parameters()"
},
{
"code": null,
"e": 6980,
"s": 6738,
"text": "Using vanilla distillation on our DenseNet model, we achieved 99.85% accuracy with our baseline CNN. The CNN outperformed every state-of-the-art model’s speed at 775 inferences/second on a V100. The CNN did this with <15% as many parameters."
},
{
"code": null,
"e": 7163,
"s": 6980,
"text": "Even more impressively, running distillation again continued to improve the accuracy. For example, results improved with a combination of NoisyTeacher, SelfTraining, and MessyCollab."
},
{
"code": null,
"e": 7251,
"s": 7163,
"text": "Side note: self-training uses your model as both the teacher and the student, how cool!"
},
{
"code": null,
"e": 7324,
"s": 7251,
"text": "Creating a classifier for proper mask usage felt both timely and urgent."
},
{
"code": null,
"e": 7551,
"s": 7324,
"text": "The lessons in building out this pipeline are useful for any image classification task you would like to do. Hopefully, this pipeline helps with understanding and solving any image classification task you aim to do. Good luck!"
},
{
"code": null,
"e": 7606,
"s": 7551,
"text": "Associated Paper: https://arxiv.org/pdf/2105.01816.pdf"
}
] |
JSP - Hits Counter | In this chapter, we will discuss Hits Counter in JSP. A hit counter tells you about the number of visits on a particular page of your web site. Usually you attach a hit counter with your index.jsp page assuming people first land on your home page.
To implement a hit counter you can make use of the Application Implicit object and associated methods getAttribute() and setAttribute().
This object is a representation of the JSP page through its entire lifecycle. This object is created when the JSP page is initialized and will be removed when the JSP page is removed by the jspDestroy() method.
Following is the syntax to set a variable at application level −
application.setAttribute(String Key, Object Value);
You can use the above method to set a hit counter variable and to reset the same variable. Following is the method to read the variable set by the previous method −
application.getAttribute(String Key);
Every time a user accesses your page, you can read the current value of the hit counter and increase it by one and again set it for future use.
This example shows how you can use JSP to count the total number of hits on a particular page. If you want to count the total number of hits of your website then you will have to include the same code in all the JSP pages.
<%@ page import = "java.io.*,java.util.*" %>
<html>
<head>
<title>Application object in JSP</title>
</head>
<body>
<%
Integer hitsCount = (Integer)application.getAttribute("hitCounter");
if( hitsCount ==null || hitsCount == 0 ) {
/* First visit */
out.println("Welcome to my website!");
hitsCount = 1;
} else {
/* return visit */
out.println("Welcome back to my website!");
hitsCount += 1;
}
application.setAttribute("hitCounter", hitsCount);
%>
<center>
<p>Total number of visits: <%= hitsCount%></p>
</center>
</body>
</html>
Let us now put the above code in main.jsp and call this JSP using the URL http://localhost:8080/main.jsp. This will display the hit counter value which increases as and when you refresh the page. You can try accessing the page using different browsers and you will find that the hit counter will keep increasing with every hit and you will receive the result as follows −
Welcome back to my website!
Total number of visits: 12
Welcome back to my website!
Total number of visits: 12
What when you restart your application, i.e., web server, this will reset your application variable and your counter will reset to zero. To avoid this loss, consider the following points −
Define a database table with a single count, let us say hitcount. Assign a zero value to it.
Define a database table with a single count, let us say hitcount. Assign a zero value to it.
With every hit, read the table to get the value of hitcount.
With every hit, read the table to get the value of hitcount.
Increase the value of hitcount by one and update the table with new value.
Increase the value of hitcount by one and update the table with new value.
Display new value of hitcount as total page hit counts.
Display new value of hitcount as total page hit counts.
If you want to count hits for all the pages, implement above logic for all the pages.
If you want to count hits for all the pages, implement above logic for all the pages.
108 Lectures
11 hours
Chaand Sheikh
517 Lectures
57 hours
Chaand Sheikh
41 Lectures
4.5 hours
Karthikeya T
42 Lectures
5.5 hours
TELCOMA Global
15 Lectures
3 hours
TELCOMA Global
44 Lectures
15 hours
Uplatz
Print
Add Notes
Bookmark this page | [
{
"code": null,
"e": 2487,
"s": 2239,
"text": "In this chapter, we will discuss Hits Counter in JSP. A hit counter tells you about the number of visits on a particular page of your web site. Usually you attach a hit counter with your index.jsp page assuming people first land on your home page."
},
{
"code": null,
"e": 2624,
"s": 2487,
"text": "To implement a hit counter you can make use of the Application Implicit object and associated methods getAttribute() and setAttribute()."
},
{
"code": null,
"e": 2835,
"s": 2624,
"text": "This object is a representation of the JSP page through its entire lifecycle. This object is created when the JSP page is initialized and will be removed when the JSP page is removed by the jspDestroy() method."
},
{
"code": null,
"e": 2900,
"s": 2835,
"text": "Following is the syntax to set a variable at application level −"
},
{
"code": null,
"e": 2953,
"s": 2900,
"text": "application.setAttribute(String Key, Object Value);\n"
},
{
"code": null,
"e": 3118,
"s": 2953,
"text": "You can use the above method to set a hit counter variable and to reset the same variable. Following is the method to read the variable set by the previous method −"
},
{
"code": null,
"e": 3157,
"s": 3118,
"text": "application.getAttribute(String Key);\n"
},
{
"code": null,
"e": 3301,
"s": 3157,
"text": "Every time a user accesses your page, you can read the current value of the hit counter and increase it by one and again set it for future use."
},
{
"code": null,
"e": 3524,
"s": 3301,
"text": "This example shows how you can use JSP to count the total number of hits on a particular page. If you want to count the total number of hits of your website then you will have to include the same code in all the JSP pages."
},
{
"code": null,
"e": 4229,
"s": 3524,
"text": "<%@ page import = \"java.io.*,java.util.*\" %>\n\n<html>\n <head>\n <title>Application object in JSP</title>\n </head>\n \n <body>\n <%\n Integer hitsCount = (Integer)application.getAttribute(\"hitCounter\");\n if( hitsCount ==null || hitsCount == 0 ) {\n /* First visit */\n out.println(\"Welcome to my website!\");\n hitsCount = 1;\n } else {\n /* return visit */\n out.println(\"Welcome back to my website!\");\n hitsCount += 1;\n }\n application.setAttribute(\"hitCounter\", hitsCount);\n %>\n <center>\n <p>Total number of visits: <%= hitsCount%></p>\n </center>\n \n </body>\n</html>"
},
{
"code": null,
"e": 4601,
"s": 4229,
"text": "Let us now put the above code in main.jsp and call this JSP using the URL http://localhost:8080/main.jsp. This will display the hit counter value which increases as and when you refresh the page. You can try accessing the page using different browsers and you will find that the hit counter will keep increasing with every hit and you will receive the result as follows −"
},
{
"code": null,
"e": 4659,
"s": 4601,
"text": "\nWelcome back to my website!\nTotal number of visits: 12\n\n"
},
{
"code": null,
"e": 4687,
"s": 4659,
"text": "Welcome back to my website!"
},
{
"code": null,
"e": 4714,
"s": 4687,
"text": "Total number of visits: 12"
},
{
"code": null,
"e": 4903,
"s": 4714,
"text": "What when you restart your application, i.e., web server, this will reset your application variable and your counter will reset to zero. To avoid this loss, consider the following points −"
},
{
"code": null,
"e": 4996,
"s": 4903,
"text": "Define a database table with a single count, let us say hitcount. Assign a zero value to it."
},
{
"code": null,
"e": 5089,
"s": 4996,
"text": "Define a database table with a single count, let us say hitcount. Assign a zero value to it."
},
{
"code": null,
"e": 5150,
"s": 5089,
"text": "With every hit, read the table to get the value of hitcount."
},
{
"code": null,
"e": 5211,
"s": 5150,
"text": "With every hit, read the table to get the value of hitcount."
},
{
"code": null,
"e": 5286,
"s": 5211,
"text": "Increase the value of hitcount by one and update the table with new value."
},
{
"code": null,
"e": 5361,
"s": 5286,
"text": "Increase the value of hitcount by one and update the table with new value."
},
{
"code": null,
"e": 5417,
"s": 5361,
"text": "Display new value of hitcount as total page hit counts."
},
{
"code": null,
"e": 5473,
"s": 5417,
"text": "Display new value of hitcount as total page hit counts."
},
{
"code": null,
"e": 5559,
"s": 5473,
"text": "If you want to count hits for all the pages, implement above logic for all the pages."
},
{
"code": null,
"e": 5645,
"s": 5559,
"text": "If you want to count hits for all the pages, implement above logic for all the pages."
},
{
"code": null,
"e": 5680,
"s": 5645,
"text": "\n 108 Lectures \n 11 hours \n"
},
{
"code": null,
"e": 5695,
"s": 5680,
"text": " Chaand Sheikh"
},
{
"code": null,
"e": 5730,
"s": 5695,
"text": "\n 517 Lectures \n 57 hours \n"
},
{
"code": null,
"e": 5745,
"s": 5730,
"text": " Chaand Sheikh"
},
{
"code": null,
"e": 5780,
"s": 5745,
"text": "\n 41 Lectures \n 4.5 hours \n"
},
{
"code": null,
"e": 5794,
"s": 5780,
"text": " Karthikeya T"
},
{
"code": null,
"e": 5829,
"s": 5794,
"text": "\n 42 Lectures \n 5.5 hours \n"
},
{
"code": null,
"e": 5845,
"s": 5829,
"text": " TELCOMA Global"
},
{
"code": null,
"e": 5878,
"s": 5845,
"text": "\n 15 Lectures \n 3 hours \n"
},
{
"code": null,
"e": 5894,
"s": 5878,
"text": " TELCOMA Global"
},
{
"code": null,
"e": 5928,
"s": 5894,
"text": "\n 44 Lectures \n 15 hours \n"
},
{
"code": null,
"e": 5936,
"s": 5928,
"text": " Uplatz"
},
{
"code": null,
"e": 5943,
"s": 5936,
"text": " Print"
},
{
"code": null,
"e": 5954,
"s": 5943,
"text": " Add Notes"
}
] |
Data Visualization — Advanced Bokeh Techniques | by Jim King | Towards Data Science | If you are looking to create powerful data visualizations then you should consider using Bokeh. In an earlier article, “How to Create an Interactive Geographic Map Using Python and Bokeh”, I demonstrated how to create an interactive geographic map using Bokeh. This article will take it a step further and demonstrate how to use an interactive map with a data table and text fields organized using a Bokeh layout to create an interactive dashboard for displaying data.
First, let’s take a look at the finished product which appeared in the article “Look Out Zillow Here Comes Jestimate!”:
Click Here for San Francisco 2018 Jestimates!
A Word About the Code
All the code, data and associated files for the project can be accessed at my GitHub. The project is separated into two Colab notebooks. One runs the linear regression model (creating the data for the visualization) and the other produces the interactive visualization using a Bokeh server on Heroku.
Installs and Imports
Let’s start with the installs and imports you will need for the graphs. Pandas, numpy and math are standard Python libraries used to clean and wrangle the data. The geopandas, json and bokeh imports are libraries needed for the mapping.
I work in Colab and needed to install fiona and geopandas. While you are developing the application in Colab, you will need to keep these installs in the code. However, once you start testing with the Bokeh server you will need to comment out these installs as Bokeh does not work well with the magic commands (!pip install).
# Install fiona - need to comment out for transfer to live site.# Turn on for running in a notebook%%capture!pip install fiona# Install geopandas - need to comment out for tranfer to live site.# Turn on for running in a notebook%%capture!pip install geopandas# Import librariesimport pandas as pdimport numpy as npimport mathimport geopandasimport jsonfrom bokeh.io import output_notebook, show, output_filefrom bokeh.plotting import figurefrom bokeh.models import GeoJSONDataSource, LinearColorMapper, ColorBar, NumeralTickFormatterfrom bokeh.palettes import brewerfrom bokeh.io.doc import curdocfrom bokeh.models import Slider, HoverTool, Select, TapTool, CustomJS, ColumnDataSource, TableColumn, DataTable, CDSView, GroupFilterfrom bokeh.layouts import widgetbox, row, column, gridplotfrom bokeh.models.widgets import TextInput
Preliminary Code
As the focus of this article is on the creation of the interactive dashboard, I will skip the following steps which are covered in detail in my previous article “How to Create an Interactive Geographic Map Using Python and Bokeh”.
Preparing the Mapping Data and GeoDataFrame — geopandas.read_file()Create the Colorbar Lookup Table — format_df dataframeCreating the JSON Data for the GeoJSONDataSource — json_data functionCreating a Plotting Function — make_plot functionThe Color Bar — ColorBar, part of make_plot functionThe Hover Tool — HoverTool
Preparing the Mapping Data and GeoDataFrame — geopandas.read_file()
Create the Colorbar Lookup Table — format_df dataframe
Creating the JSON Data for the GeoJSONDataSource — json_data function
Creating a Plotting Function — make_plot function
The Color Bar — ColorBar, part of make_plot function
The Hover Tool — HoverTool
Data Loading, Cleaning and Wrangling
I will briefly discuss the data used in the application, you can view the full cleaning and wrangling here if you are interested.
There are two dataframes of data used in the application: neighborhood data used to show aggregate statistics for 2018 for each neighborhood and display data for each individual property sold in 2018 produced by the linear regression code in my article “Look Out Zillow Here Comes Jestimate!”
neighborhood_data DataFrame
display_data DataFrame
Main Code for the Application
Let’s take a look at the main code for the application and then step through it in detail.
### Start of Main Program # Input geojson source that contains features for plotting for:# initial year 2018 and initial criteria sale_price_mediangeosource = GeoJSONDataSource(geojson = json_data(2018))original_geosource = geosourceinput_field = 'sale_price_mean'# Initialize the datatable - set datatable source, set intial neighborhood, set initial view by neighborhhood, set columnssource = ColumnDataSource(results_data)hood = 'Bernal Heights'subdist = '9a'view1 = CDSView(source=source, filters=[GroupFilter(column_name='subdist_no', group=subdist)])columns = [TableColumn(field = 'full_address', title = 'Address')]# Define a sequential multi-hue color palette.palette = brewer['Blues'][8]# Reverse color order so that dark blue is highest obesity.palette = palette[::-1]#Add hover tool to view neighborhood statshover = HoverTool(tooltips = [ ('Neighborhood','@neighborhood_name'), ('# Sales', '@sale_price_count'), ('Average Price', '$@sale_price_mean{,}'), ('Median Price', '$@sale_price_median{,}'), ('Average SF', '@sf_mean{,}'), ('Price/SF ', '$@price_sf_mean{,}'), ('Income Needed', '$@min_income{,}')])# Add tap tool to select neighborhood on maptap = TapTool()# Call the plotting functionp = make_plot(input_field)# Load the datatable, neighborhood, address, actual price, predicted price and difference for displaydata_table = DataTable(source = source, view = view1, columns = columns, width = 280, height = 280, editable = False)tap_neighborhood = TextInput(value = hood, title = 'Neighborhood')table_address = TextInput(value = '', title = 'Address')table_actual = TextInput(value = '', title = 'Actual Sale Price')table_predicted = TextInput(value = '', title = 'Predicted Sale Price')table_diff = TextInput(value = '', title = 'Difference')table_percent = TextInput(value = '', title = 'Error Percentage')table_shap = TextInput(value = '', title = 'Impact Features (SHAP Values)')# On change of source (datatable selection by mouse-click) fill the line items with values by property addresssource.selected.on_change('indices', function_source)# On change of geosource (neighborhood selection by mouse-click) fill the datatable with nieghborhood salesgeosource.selected.on_change('indices', function_geosource)# Layout the components with the plot in row postion (0) and the other components in a column in row position (1)layout = row(column(p, table_shap), column(tap_neighborhood, data_table, table_address, table_actual, table_predicted, table_diff, table_percent))# Add the layout to the current documentcurdoc().add_root(layout)# Use the following code to test in a notebook# Interactive features will not show in notebook#output_notebook()#show(p)
Step 1 — Initialize the Data
Bokeh offers several ways to work with data. In a typical Bokeh interactive graph the data source is a ColumnDataSource. This is a key concept in Bokeh. However, when using a map we use a GeoJSONDataSource. We will be using both!
# Input geojson source that contains features for plotting for:# initial year 2018 and initial criteria sale_price_mediangeosource = GeoJSONDataSource(geojson = json_data(2018))original_geosource = geosourceinput_field = 'sale_price_mean'# Initialize the datatable - set datatable source, set intial neighborhood, set initial view by neighborhhood, set columnssource = ColumnDataSource(results_data)hood = 'Bernal Heights'subdist = '9a'view1 = CDSView(source=source, filters=[GroupFilter(column_name='subdist_no', group=subdist)])columns = [TableColumn(field = 'full_address', title = 'Address')]
We pass the json_data function the year of data we would like loaded (2018). The json_data function then pulls the data from neighborhood_data for the selected year and merges it with the mapping data returning the merged file converted into JSON format for the Bokeh server. Our GeoJSONDataSource is geosource. The initial_field is initialized with sale_price_mean.
Our ColumnDataSource, source, is initialized with the results_data and a Column Data Source View (CDSView), view1, is initialized with the Bernal Heights neighborhood (subdist=9a). CDSView is a method for filtering data allowing you to show a subset of the data, in this case the Bernal Heights neighborhood. The column of the datatable is initialized to display the full address of the property.
Step 2 — Initalize the ColorBar, Tools and Map Plot
# Define a sequential multi-hue color palette.palette = brewer['Blues'][8]# Reverse color order so that dark blue is highest obesity.palette = palette[::-1]#Add hover tool to view neighborhood statshover = HoverTool(tooltips = [ ('Neighborhood','@neighborhood_name'), ('# Sales', '@sale_price_count'), ('Average Price', '$@sale_price_mean{,}'), ('Median Price', '$@sale_price_median{,}'), ('Average SF', '@sf_mean{,}'), ('Price/SF ', '$@price_sf_mean{,}'), ('Income Needed', '$@min_income{,}')])# Add tap tool to select neighborhood on maptap = TapTool()# Call the plotting functionp = make_plot(input_field)
The ColorBar palette, HoverTool and TapTool are initialized and the make_plot function is called creating the initial map plot showing the median price neighborhood heatmap.
Step 3 — Fill the Data Table and Text Fields with the Initial Data
# Load the datatable, neighborhood, address, actual price, predicted price and difference for displaydata_table = DataTable(source = source, view = view1, columns = columns, width = 280, height = 280, editable = False)tap_neighborhood = TextInput(value = hood, title = 'Neighborhood')table_address = TextInput(value = '', title = 'Address')table_actual = TextInput(value = '', title = 'Actual Sale Price')table_predicted = TextInput(value = '', title = 'Predicted Sale Price')table_diff = TextInput(value = '', title = 'Difference')table_percent = TextInput(value = '', title = 'Error Percentage')table_shap = TextInput(value = '', title = 'Impact Features (SHAP Values)')
The datatable is filled using the source (ColumnDataSource populated from results_data), view (view1 filtered for Bernal Heights), and columns (columns using only the full_address column). The TextInput widget in Bokeh is usually used to gather data from the user, but works perfectly fine for displaying data too! All the TextInput widgets are initialized with blanks.
Step 4 — The Callback Functions
This is were the key functionality for the interactivity comes into play. Bokeh widgets work on the callback principle using event handlers — either .on_change or .on_click — to provide custom interactive features. These event handlers then call custom callback functions in the form function(attr, old, new) where attr refers to the changed attribute’s name, and old and new refer to the previous and updated values of the attribute.
# On change of source (datatable selection by mouse-click) fill the line items with values by property addresssource.selected.on_change('indices', function_source)
For the datatable, this was easy, simply using the selected.on_change event_handler for source and calling the function function_source when a user clicks on a row of the datatable passing it the index of the row. The TextInput values are then updated from the source (results_data) by the selected index from the datatable.
def function_source(attr, old, new): try: selected_index = source.selected.indices[0] table_address.value = str(source.data['full_address'][selected_index]) table_actual.value = '${:,}'.format((source.data['sale_price'][selected_index])) table_predicted.value = '${:,}'.format((source.data['prediction'][selected_index])) table_diff.value = '${:,}'.format(source.data['difference'][selected_index]) table_percent.value = '{0:.0%}'.format((source.data['pred_percent'][selected_index])) table_shap.value = source.data['shap'][selected_index] except IndexError: pass
For the map, I wanted to be able to click on a neighborhood and fill the datatable based on the neighborhood selected. Oddly, there was no built-in .on_click event handler for the HoverTool. It’s clear the HoverTool knows which neighborhood it is hovering over, so I built my own!
I realized there was a TapTool and after testing it with the map I discovered it works as a selection tool. In other words, when you click the mouse over a polygon on the map, it actually selects the polygon using the neighborhood id as the index! This also triggers the .on_change event handler in geosource. So, using the same basic method used for the datatable:
# On change of geosource (neighborhood selection by mouse-click) fill the datatable with nieghborhood salesgeosource.selected.on_change('indices', function_geosource)
For the map, use the selected.on_change event_handler for geosource and call the function function_geosource when a user clicks on a neighborhood passing it the index of the neighborhood. Based on the new index (the neighborhood id/subdistr_no), the CDSView is reset to the new neighborhood, the datatable is re-filled with the new data from the view, and the TextInput values are set to blanks.
# On change of geosource (neighborhood selection by mouse-click) fill the datatable with nieghborhood sales def function_geosource(attr, old, new): try: selected_index = geosource.selected.indices[0] tap_neighborhood.value = sf.iloc[selected_index]['neighborhood_name'] subdist = sf.iloc[selected_index]['subdist_no'] hood = tap_neighborhood.value view1 = CDSView(source=source, filters=[GroupFilter(column_name='subdist_no', group=subdist)]) columns = [TableColumn(field = 'full_address', title = 'Address')] data_table = DataTable(source = source, view = view1, columns = columns, width = 280, height = 280, editable = False) table_address.value = '' table_actual.value = '' table_predicted.value = '' table_diff.value = '' table_percent.value = '' table_shap.value = '' # Replace the updated datatable in the layout layout.children[1] = column(tap_neighborhood, data_table, table_address, table_actual, table_predicted, table_diff, table_percent) except IndexError: pass
Step 5 — The Layout and Document
Bokeh offers several layout options for arranging plots and widgets. The three core objects for layouts are row(), column() and widgetbox(). It helps to think of the screen as a document laid out as a grid with rows, columns. A widgetbox is a container for widgets. In the application, the components are laid out as two columns in one row:
First Column — Contains the plot p (the map) and the TextInput widget table_shap (the Shapley value).Second Column — Contains the datatable tap_neighborhood and the rest of the TextInput widgets.
First Column — Contains the plot p (the map) and the TextInput widget table_shap (the Shapley value).
Second Column — Contains the datatable tap_neighborhood and the rest of the TextInput widgets.
# Layout the components with the plot in row postion (0) and the other components in a column in row position (1)layout = row(column(p, table_shap), column(tap_neighborhood, data_table, table_address, table_actual, table_predicted, table_diff, table_percent))# Add the layout to the current documentcurdoc().add_root(layout)
The layout is then added to the document for display.
I welcome constructive criticism and feedback so feel free to send me a private message.
Follow me on Twitter @The_Jim_King
The article originally appeared on my GitHub Pages site
This is Part of a Series of Articles Exploring San Francisco Real Estate Data
San Francisco Real Estate Data Source: San Francisco MLS, 2009–2018 Data | [
{
"code": null,
"e": 641,
"s": 172,
"text": "If you are looking to create powerful data visualizations then you should consider using Bokeh. In an earlier article, “How to Create an Interactive Geographic Map Using Python and Bokeh”, I demonstrated how to create an interactive geographic map using Bokeh. This article will take it a step further and demonstrate how to use an interactive map with a data table and text fields organized using a Bokeh layout to create an interactive dashboard for displaying data."
},
{
"code": null,
"e": 761,
"s": 641,
"text": "First, let’s take a look at the finished product which appeared in the article “Look Out Zillow Here Comes Jestimate!”:"
},
{
"code": null,
"e": 807,
"s": 761,
"text": "Click Here for San Francisco 2018 Jestimates!"
},
{
"code": null,
"e": 829,
"s": 807,
"text": "A Word About the Code"
},
{
"code": null,
"e": 1130,
"s": 829,
"text": "All the code, data and associated files for the project can be accessed at my GitHub. The project is separated into two Colab notebooks. One runs the linear regression model (creating the data for the visualization) and the other produces the interactive visualization using a Bokeh server on Heroku."
},
{
"code": null,
"e": 1151,
"s": 1130,
"text": "Installs and Imports"
},
{
"code": null,
"e": 1388,
"s": 1151,
"text": "Let’s start with the installs and imports you will need for the graphs. Pandas, numpy and math are standard Python libraries used to clean and wrangle the data. The geopandas, json and bokeh imports are libraries needed for the mapping."
},
{
"code": null,
"e": 1714,
"s": 1388,
"text": "I work in Colab and needed to install fiona and geopandas. While you are developing the application in Colab, you will need to keep these installs in the code. However, once you start testing with the Bokeh server you will need to comment out these installs as Bokeh does not work well with the magic commands (!pip install)."
},
{
"code": null,
"e": 2545,
"s": 1714,
"text": "# Install fiona - need to comment out for transfer to live site.# Turn on for running in a notebook%%capture!pip install fiona# Install geopandas - need to comment out for tranfer to live site.# Turn on for running in a notebook%%capture!pip install geopandas# Import librariesimport pandas as pdimport numpy as npimport mathimport geopandasimport jsonfrom bokeh.io import output_notebook, show, output_filefrom bokeh.plotting import figurefrom bokeh.models import GeoJSONDataSource, LinearColorMapper, ColorBar, NumeralTickFormatterfrom bokeh.palettes import brewerfrom bokeh.io.doc import curdocfrom bokeh.models import Slider, HoverTool, Select, TapTool, CustomJS, ColumnDataSource, TableColumn, DataTable, CDSView, GroupFilterfrom bokeh.layouts import widgetbox, row, column, gridplotfrom bokeh.models.widgets import TextInput"
},
{
"code": null,
"e": 2562,
"s": 2545,
"text": "Preliminary Code"
},
{
"code": null,
"e": 2793,
"s": 2562,
"text": "As the focus of this article is on the creation of the interactive dashboard, I will skip the following steps which are covered in detail in my previous article “How to Create an Interactive Geographic Map Using Python and Bokeh”."
},
{
"code": null,
"e": 3111,
"s": 2793,
"text": "Preparing the Mapping Data and GeoDataFrame — geopandas.read_file()Create the Colorbar Lookup Table — format_df dataframeCreating the JSON Data for the GeoJSONDataSource — json_data functionCreating a Plotting Function — make_plot functionThe Color Bar — ColorBar, part of make_plot functionThe Hover Tool — HoverTool"
},
{
"code": null,
"e": 3179,
"s": 3111,
"text": "Preparing the Mapping Data and GeoDataFrame — geopandas.read_file()"
},
{
"code": null,
"e": 3234,
"s": 3179,
"text": "Create the Colorbar Lookup Table — format_df dataframe"
},
{
"code": null,
"e": 3304,
"s": 3234,
"text": "Creating the JSON Data for the GeoJSONDataSource — json_data function"
},
{
"code": null,
"e": 3354,
"s": 3304,
"text": "Creating a Plotting Function — make_plot function"
},
{
"code": null,
"e": 3407,
"s": 3354,
"text": "The Color Bar — ColorBar, part of make_plot function"
},
{
"code": null,
"e": 3434,
"s": 3407,
"text": "The Hover Tool — HoverTool"
},
{
"code": null,
"e": 3471,
"s": 3434,
"text": "Data Loading, Cleaning and Wrangling"
},
{
"code": null,
"e": 3601,
"s": 3471,
"text": "I will briefly discuss the data used in the application, you can view the full cleaning and wrangling here if you are interested."
},
{
"code": null,
"e": 3894,
"s": 3601,
"text": "There are two dataframes of data used in the application: neighborhood data used to show aggregate statistics for 2018 for each neighborhood and display data for each individual property sold in 2018 produced by the linear regression code in my article “Look Out Zillow Here Comes Jestimate!”"
},
{
"code": null,
"e": 3922,
"s": 3894,
"text": "neighborhood_data DataFrame"
},
{
"code": null,
"e": 3945,
"s": 3922,
"text": "display_data DataFrame"
},
{
"code": null,
"e": 3975,
"s": 3945,
"text": "Main Code for the Application"
},
{
"code": null,
"e": 4066,
"s": 3975,
"text": "Let’s take a look at the main code for the application and then step through it in detail."
},
{
"code": null,
"e": 6938,
"s": 4066,
"text": "### Start of Main Program # Input geojson source that contains features for plotting for:# initial year 2018 and initial criteria sale_price_mediangeosource = GeoJSONDataSource(geojson = json_data(2018))original_geosource = geosourceinput_field = 'sale_price_mean'# Initialize the datatable - set datatable source, set intial neighborhood, set initial view by neighborhhood, set columnssource = ColumnDataSource(results_data)hood = 'Bernal Heights'subdist = '9a'view1 = CDSView(source=source, filters=[GroupFilter(column_name='subdist_no', group=subdist)])columns = [TableColumn(field = 'full_address', title = 'Address')]# Define a sequential multi-hue color palette.palette = brewer['Blues'][8]# Reverse color order so that dark blue is highest obesity.palette = palette[::-1]#Add hover tool to view neighborhood statshover = HoverTool(tooltips = [ ('Neighborhood','@neighborhood_name'), ('# Sales', '@sale_price_count'), ('Average Price', '$@sale_price_mean{,}'), ('Median Price', '$@sale_price_median{,}'), ('Average SF', '@sf_mean{,}'), ('Price/SF ', '$@price_sf_mean{,}'), ('Income Needed', '$@min_income{,}')])# Add tap tool to select neighborhood on maptap = TapTool()# Call the plotting functionp = make_plot(input_field)# Load the datatable, neighborhood, address, actual price, predicted price and difference for displaydata_table = DataTable(source = source, view = view1, columns = columns, width = 280, height = 280, editable = False)tap_neighborhood = TextInput(value = hood, title = 'Neighborhood')table_address = TextInput(value = '', title = 'Address')table_actual = TextInput(value = '', title = 'Actual Sale Price')table_predicted = TextInput(value = '', title = 'Predicted Sale Price')table_diff = TextInput(value = '', title = 'Difference')table_percent = TextInput(value = '', title = 'Error Percentage')table_shap = TextInput(value = '', title = 'Impact Features (SHAP Values)')# On change of source (datatable selection by mouse-click) fill the line items with values by property addresssource.selected.on_change('indices', function_source)# On change of geosource (neighborhood selection by mouse-click) fill the datatable with nieghborhood salesgeosource.selected.on_change('indices', function_geosource)# Layout the components with the plot in row postion (0) and the other components in a column in row position (1)layout = row(column(p, table_shap), column(tap_neighborhood, data_table, table_address, table_actual, table_predicted, table_diff, table_percent))# Add the layout to the current documentcurdoc().add_root(layout)# Use the following code to test in a notebook# Interactive features will not show in notebook#output_notebook()#show(p)"
},
{
"code": null,
"e": 6967,
"s": 6938,
"text": "Step 1 — Initialize the Data"
},
{
"code": null,
"e": 7197,
"s": 6967,
"text": "Bokeh offers several ways to work with data. In a typical Bokeh interactive graph the data source is a ColumnDataSource. This is a key concept in Bokeh. However, when using a map we use a GeoJSONDataSource. We will be using both!"
},
{
"code": null,
"e": 7794,
"s": 7197,
"text": "# Input geojson source that contains features for plotting for:# initial year 2018 and initial criteria sale_price_mediangeosource = GeoJSONDataSource(geojson = json_data(2018))original_geosource = geosourceinput_field = 'sale_price_mean'# Initialize the datatable - set datatable source, set intial neighborhood, set initial view by neighborhhood, set columnssource = ColumnDataSource(results_data)hood = 'Bernal Heights'subdist = '9a'view1 = CDSView(source=source, filters=[GroupFilter(column_name='subdist_no', group=subdist)])columns = [TableColumn(field = 'full_address', title = 'Address')]"
},
{
"code": null,
"e": 8161,
"s": 7794,
"text": "We pass the json_data function the year of data we would like loaded (2018). The json_data function then pulls the data from neighborhood_data for the selected year and merges it with the mapping data returning the merged file converted into JSON format for the Bokeh server. Our GeoJSONDataSource is geosource. The initial_field is initialized with sale_price_mean."
},
{
"code": null,
"e": 8558,
"s": 8161,
"text": "Our ColumnDataSource, source, is initialized with the results_data and a Column Data Source View (CDSView), view1, is initialized with the Bernal Heights neighborhood (subdist=9a). CDSView is a method for filtering data allowing you to show a subset of the data, in this case the Bernal Heights neighborhood. The column of the datatable is initialized to display the full address of the property."
},
{
"code": null,
"e": 8610,
"s": 8558,
"text": "Step 2 — Initalize the ColorBar, Tools and Map Plot"
},
{
"code": null,
"e": 9399,
"s": 8610,
"text": "# Define a sequential multi-hue color palette.palette = brewer['Blues'][8]# Reverse color order so that dark blue is highest obesity.palette = palette[::-1]#Add hover tool to view neighborhood statshover = HoverTool(tooltips = [ ('Neighborhood','@neighborhood_name'), ('# Sales', '@sale_price_count'), ('Average Price', '$@sale_price_mean{,}'), ('Median Price', '$@sale_price_median{,}'), ('Average SF', '@sf_mean{,}'), ('Price/SF ', '$@price_sf_mean{,}'), ('Income Needed', '$@min_income{,}')])# Add tap tool to select neighborhood on maptap = TapTool()# Call the plotting functionp = make_plot(input_field)"
},
{
"code": null,
"e": 9573,
"s": 9399,
"text": "The ColorBar palette, HoverTool and TapTool are initialized and the make_plot function is called creating the initial map plot showing the median price neighborhood heatmap."
},
{
"code": null,
"e": 9640,
"s": 9573,
"text": "Step 3 — Fill the Data Table and Text Fields with the Initial Data"
},
{
"code": null,
"e": 10313,
"s": 9640,
"text": "# Load the datatable, neighborhood, address, actual price, predicted price and difference for displaydata_table = DataTable(source = source, view = view1, columns = columns, width = 280, height = 280, editable = False)tap_neighborhood = TextInput(value = hood, title = 'Neighborhood')table_address = TextInput(value = '', title = 'Address')table_actual = TextInput(value = '', title = 'Actual Sale Price')table_predicted = TextInput(value = '', title = 'Predicted Sale Price')table_diff = TextInput(value = '', title = 'Difference')table_percent = TextInput(value = '', title = 'Error Percentage')table_shap = TextInput(value = '', title = 'Impact Features (SHAP Values)')"
},
{
"code": null,
"e": 10683,
"s": 10313,
"text": "The datatable is filled using the source (ColumnDataSource populated from results_data), view (view1 filtered for Bernal Heights), and columns (columns using only the full_address column). The TextInput widget in Bokeh is usually used to gather data from the user, but works perfectly fine for displaying data too! All the TextInput widgets are initialized with blanks."
},
{
"code": null,
"e": 10715,
"s": 10683,
"text": "Step 4 — The Callback Functions"
},
{
"code": null,
"e": 11150,
"s": 10715,
"text": "This is were the key functionality for the interactivity comes into play. Bokeh widgets work on the callback principle using event handlers — either .on_change or .on_click — to provide custom interactive features. These event handlers then call custom callback functions in the form function(attr, old, new) where attr refers to the changed attribute’s name, and old and new refer to the previous and updated values of the attribute."
},
{
"code": null,
"e": 11314,
"s": 11150,
"text": "# On change of source (datatable selection by mouse-click) fill the line items with values by property addresssource.selected.on_change('indices', function_source)"
},
{
"code": null,
"e": 11639,
"s": 11314,
"text": "For the datatable, this was easy, simply using the selected.on_change event_handler for source and calling the function function_source when a user clicks on a row of the datatable passing it the index of the row. The TextInput values are then updated from the source (results_data) by the selected index from the datatable."
},
{
"code": null,
"e": 12273,
"s": 11639,
"text": "def function_source(attr, old, new): try: selected_index = source.selected.indices[0] table_address.value = str(source.data['full_address'][selected_index]) table_actual.value = '${:,}'.format((source.data['sale_price'][selected_index])) table_predicted.value = '${:,}'.format((source.data['prediction'][selected_index])) table_diff.value = '${:,}'.format(source.data['difference'][selected_index]) table_percent.value = '{0:.0%}'.format((source.data['pred_percent'][selected_index])) table_shap.value = source.data['shap'][selected_index] except IndexError: pass"
},
{
"code": null,
"e": 12554,
"s": 12273,
"text": "For the map, I wanted to be able to click on a neighborhood and fill the datatable based on the neighborhood selected. Oddly, there was no built-in .on_click event handler for the HoverTool. It’s clear the HoverTool knows which neighborhood it is hovering over, so I built my own!"
},
{
"code": null,
"e": 12920,
"s": 12554,
"text": "I realized there was a TapTool and after testing it with the map I discovered it works as a selection tool. In other words, when you click the mouse over a polygon on the map, it actually selects the polygon using the neighborhood id as the index! This also triggers the .on_change event handler in geosource. So, using the same basic method used for the datatable:"
},
{
"code": null,
"e": 13087,
"s": 12920,
"text": "# On change of geosource (neighborhood selection by mouse-click) fill the datatable with nieghborhood salesgeosource.selected.on_change('indices', function_geosource)"
},
{
"code": null,
"e": 13483,
"s": 13087,
"text": "For the map, use the selected.on_change event_handler for geosource and call the function function_geosource when a user clicks on a neighborhood passing it the index of the neighborhood. Based on the new index (the neighborhood id/subdistr_no), the CDSView is reset to the new neighborhood, the datatable is re-filled with the new data from the view, and the TextInput values are set to blanks."
},
{
"code": null,
"e": 14632,
"s": 13483,
"text": "# On change of geosource (neighborhood selection by mouse-click) fill the datatable with nieghborhood sales def function_geosource(attr, old, new): try: selected_index = geosource.selected.indices[0] tap_neighborhood.value = sf.iloc[selected_index]['neighborhood_name'] subdist = sf.iloc[selected_index]['subdist_no'] hood = tap_neighborhood.value view1 = CDSView(source=source, filters=[GroupFilter(column_name='subdist_no', group=subdist)]) columns = [TableColumn(field = 'full_address', title = 'Address')] data_table = DataTable(source = source, view = view1, columns = columns, width = 280, height = 280, editable = False) table_address.value = '' table_actual.value = '' table_predicted.value = '' table_diff.value = '' table_percent.value = '' table_shap.value = '' # Replace the updated datatable in the layout layout.children[1] = column(tap_neighborhood, data_table, table_address, table_actual, table_predicted, table_diff, table_percent) except IndexError: pass"
},
{
"code": null,
"e": 14665,
"s": 14632,
"text": "Step 5 — The Layout and Document"
},
{
"code": null,
"e": 15006,
"s": 14665,
"text": "Bokeh offers several layout options for arranging plots and widgets. The three core objects for layouts are row(), column() and widgetbox(). It helps to think of the screen as a document laid out as a grid with rows, columns. A widgetbox is a container for widgets. In the application, the components are laid out as two columns in one row:"
},
{
"code": null,
"e": 15202,
"s": 15006,
"text": "First Column — Contains the plot p (the map) and the TextInput widget table_shap (the Shapley value).Second Column — Contains the datatable tap_neighborhood and the rest of the TextInput widgets."
},
{
"code": null,
"e": 15304,
"s": 15202,
"text": "First Column — Contains the plot p (the map) and the TextInput widget table_shap (the Shapley value)."
},
{
"code": null,
"e": 15399,
"s": 15304,
"text": "Second Column — Contains the datatable tap_neighborhood and the rest of the TextInput widgets."
},
{
"code": null,
"e": 15737,
"s": 15399,
"text": "# Layout the components with the plot in row postion (0) and the other components in a column in row position (1)layout = row(column(p, table_shap), column(tap_neighborhood, data_table, table_address, table_actual, table_predicted, table_diff, table_percent))# Add the layout to the current documentcurdoc().add_root(layout)"
},
{
"code": null,
"e": 15791,
"s": 15737,
"text": "The layout is then added to the document for display."
},
{
"code": null,
"e": 15880,
"s": 15791,
"text": "I welcome constructive criticism and feedback so feel free to send me a private message."
},
{
"code": null,
"e": 15915,
"s": 15880,
"text": "Follow me on Twitter @The_Jim_King"
},
{
"code": null,
"e": 15971,
"s": 15915,
"text": "The article originally appeared on my GitHub Pages site"
},
{
"code": null,
"e": 16049,
"s": 15971,
"text": "This is Part of a Series of Articles Exploring San Francisco Real Estate Data"
}
] |
Building a Simple UI with Python. Streamlit: A Browser-based Python UI... | by Max Reynolds | Towards Data Science | Showcasing a Python project with a user interface has never been easier. With the Streamlit framework you can build a browser-based UI using only Python code. In this demo, we will be building the UI for a maze solver program described in detail in a previous article.
towardsdatascience.com
Streamlit is a web framework intended for data scientists to easily deploy models and visualizations using Python. It is fast and minimalistic but also pretty and user-friendly. There are built-in widgets for user input like image-uploading, sliders, text input, and other familiar HTML elements like checkboxes and radio buttons. Whenever a user interacts with the streamlit application, the python script is re-run from top to bottom, an important concept to keep in mind when considering different states of your app.
You can install Streamlit with pip:
pip install streamlit
And run streamlit on a python script:
streamlit run app.py
In the previous demo, we built a Python program that will solve a maze given an image file and starting/ending locations. We would like to turn this program into a single-page web app where a user can upload a maze image (or use a default maze image), adjust the maze start and end locations, and see the final solved maze.
First, let’s create the UI for the image uploader and the option to use a default image. We can add text outputs using functions like st.write() or st.title(). We store a dynamically uploaded file using streamlit’s st.file_uploader() function. Finally, st.checkbox() will return a boolean based on whether the user has selected the checkbox.
The result:
We can then read our default or uploaded image into a usable OpenCV image format.
Once an image is uploaded, we want to show the image marked up with starting and ending points. We will use sliders to allow the user to reposition these points. The st.sidebar() function adds a sidebar to the page and st.slider() takes numerical input within a defined minimum and maximum. We can define slider minimum and maximum values dynamically based on the size of our maze image.
Whenever the user adjusts the sliders, the image is quickly re-rendered and the points change position.
Once the user has finalized the start and end positions, we want a button to solve the maze and display the solution. The st.spinner() element is displayed only while its child process is running, and the st.image() call is used to display an image.
In less than 40 lines of code we have created a simple UI for a Python image processing app. We did not need to write any traditional front-end code. Besides Streamlit’s ability to digest simple Python code, Streamlit intelligently re-runs the necessary parts of your script from top to bottom whenever the user interacts with the page or the script is changed. This allows for straightforward data flow and rapid development.
You can find the full code on Github and Part 1 explaining the algorithm behind the maze solver here. Streamlit documentation including important concepts and additional widgets is located here.
towardsdatascience.com
Registering for Medium membership supports my work. | [
{
"code": null,
"e": 441,
"s": 172,
"text": "Showcasing a Python project with a user interface has never been easier. With the Streamlit framework you can build a browser-based UI using only Python code. In this demo, we will be building the UI for a maze solver program described in detail in a previous article."
},
{
"code": null,
"e": 464,
"s": 441,
"text": "towardsdatascience.com"
},
{
"code": null,
"e": 985,
"s": 464,
"text": "Streamlit is a web framework intended for data scientists to easily deploy models and visualizations using Python. It is fast and minimalistic but also pretty and user-friendly. There are built-in widgets for user input like image-uploading, sliders, text input, and other familiar HTML elements like checkboxes and radio buttons. Whenever a user interacts with the streamlit application, the python script is re-run from top to bottom, an important concept to keep in mind when considering different states of your app."
},
{
"code": null,
"e": 1021,
"s": 985,
"text": "You can install Streamlit with pip:"
},
{
"code": null,
"e": 1043,
"s": 1021,
"text": "pip install streamlit"
},
{
"code": null,
"e": 1081,
"s": 1043,
"text": "And run streamlit on a python script:"
},
{
"code": null,
"e": 1102,
"s": 1081,
"text": "streamlit run app.py"
},
{
"code": null,
"e": 1426,
"s": 1102,
"text": "In the previous demo, we built a Python program that will solve a maze given an image file and starting/ending locations. We would like to turn this program into a single-page web app where a user can upload a maze image (or use a default maze image), adjust the maze start and end locations, and see the final solved maze."
},
{
"code": null,
"e": 1768,
"s": 1426,
"text": "First, let’s create the UI for the image uploader and the option to use a default image. We can add text outputs using functions like st.write() or st.title(). We store a dynamically uploaded file using streamlit’s st.file_uploader() function. Finally, st.checkbox() will return a boolean based on whether the user has selected the checkbox."
},
{
"code": null,
"e": 1780,
"s": 1768,
"text": "The result:"
},
{
"code": null,
"e": 1862,
"s": 1780,
"text": "We can then read our default or uploaded image into a usable OpenCV image format."
},
{
"code": null,
"e": 2250,
"s": 1862,
"text": "Once an image is uploaded, we want to show the image marked up with starting and ending points. We will use sliders to allow the user to reposition these points. The st.sidebar() function adds a sidebar to the page and st.slider() takes numerical input within a defined minimum and maximum. We can define slider minimum and maximum values dynamically based on the size of our maze image."
},
{
"code": null,
"e": 2354,
"s": 2250,
"text": "Whenever the user adjusts the sliders, the image is quickly re-rendered and the points change position."
},
{
"code": null,
"e": 2604,
"s": 2354,
"text": "Once the user has finalized the start and end positions, we want a button to solve the maze and display the solution. The st.spinner() element is displayed only while its child process is running, and the st.image() call is used to display an image."
},
{
"code": null,
"e": 3031,
"s": 2604,
"text": "In less than 40 lines of code we have created a simple UI for a Python image processing app. We did not need to write any traditional front-end code. Besides Streamlit’s ability to digest simple Python code, Streamlit intelligently re-runs the necessary parts of your script from top to bottom whenever the user interacts with the page or the script is changed. This allows for straightforward data flow and rapid development."
},
{
"code": null,
"e": 3226,
"s": 3031,
"text": "You can find the full code on Github and Part 1 explaining the algorithm behind the maze solver here. Streamlit documentation including important concepts and additional widgets is located here."
},
{
"code": null,
"e": 3249,
"s": 3226,
"text": "towardsdatascience.com"
}
] |
Effectively Final Variable in Java with Examples - GeeksforGeeks | 17 Aug, 2021
A final variable is a variable that is declared with a keyword known as ‘final‘.
Example:
final int number;
number = 77;
The Effectively Final variable is a local variable that follows the following properties are listed below as follows:
Not defined as final
Assigned to ONLY once.
Any local variable or parameter that’s assigned a worth just one occasion right now(or updated only once). It may not remain effectively final throughout the program. so this suggests that effectively final variable might lose its effectively final property after immediately the time it gets assigned/updated a minimum of another assignment. Additionally, an effectively final variable may be a variable whose value isn’t changed, but it isn’t declared with the ultimate keyword.
int number;
number = 7;
Note: Final and Effective Final are similar but just that effective Final variables are not declared with Keyword final.
Example:
Java
// Java Program to Illustrate Effective Final Keyword // Importing input output classesimport java.io.*; // Main classclass GFG { // Main friver method public static void main(String[] args) { // Calling the method where custom operands // are passed as parameters calculateValue(124, 53); } // Method 2 // To calculate the value by passing operands as // parameters public static void calculateValue(int operand1, int operand2) { // Operands and remainder are effectively final here int rem = 0; // Remainder lost its effectively final property // here because it gets its second assignment rem = operand1 % 5; // Operands are still effectively final here // Class 2 class operators { // Method 1 void setNum() { // operand1 lost its effectively final // property here because it gets its second // assignment operand1 = operand2 % 2; } // Method 2 int add() { // It does not compile because rem is not // effectively final return rem + operand2; } // Method 3 int multiply() { // It does not compile because both // remainder and operand1 are not // effectively final return rem * operand1; } } }}
Output: An error will be thrown as expected which can be perceived from the terminal output as shown below:
Lambda expression capture values
When a lambda expression uses an assigned local variable from its enclosing space there’s a crucial restriction. A lambda expression may only use a local variable whose value doesn’t change. That restriction is referred to as “variable capture” which is described as; lambda expression capture values, not variables.
The local variables that a lambda expression may use are referred to as “effectively final”.
An effectively final variable is one whose value doesn’t change after it’s first assigned. There is no need to explicitly declare such a variable as final, although doing so would not be an error.
Implementation: Consider we do have an area variable let it be ‘i’ which is initialized with the worth say be ‘7’, with within the lambda expression we try to vary that value by assigning a new value to i. This will end in compiler error – “Local variable i defined in an enclosing scope must be final or effectively final”.
Java
// Java Program to Illustrate Effective Final Keyword // Importing input output classesimport java.io.*; // Defining an interface@FunctionalInterface interface IFuncInt { // Method 1 int func(int num1, int num2); public String toString();} // Main driver methodpublic class GFG { // Main driver method public static void main(String[] args) { int i = 7; IFuncInt funcInt = (num1, num2) -> { // It produces an error due to effectively final // variable not declared i = num1 + num2; return i; }; }}
Output:
java-basics
Picked
Java
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Stream In Java
Constructors in Java
Different ways of Reading a text file in Java
Exceptions in Java
Functional Interfaces in Java
Generics in Java
Comparator Interface in Java with Examples
Introduction to Java
HashMap get() Method in Java
Strings in Java | [
{
"code": null,
"e": 23948,
"s": 23920,
"text": "\n17 Aug, 2021"
},
{
"code": null,
"e": 24029,
"s": 23948,
"text": "A final variable is a variable that is declared with a keyword known as ‘final‘."
},
{
"code": null,
"e": 24038,
"s": 24029,
"text": "Example:"
},
{
"code": null,
"e": 24069,
"s": 24038,
"text": "final int number;\nnumber = 77;"
},
{
"code": null,
"e": 24187,
"s": 24069,
"text": "The Effectively Final variable is a local variable that follows the following properties are listed below as follows:"
},
{
"code": null,
"e": 24208,
"s": 24187,
"text": "Not defined as final"
},
{
"code": null,
"e": 24231,
"s": 24208,
"text": "Assigned to ONLY once."
},
{
"code": null,
"e": 24712,
"s": 24231,
"text": "Any local variable or parameter that’s assigned a worth just one occasion right now(or updated only once). It may not remain effectively final throughout the program. so this suggests that effectively final variable might lose its effectively final property after immediately the time it gets assigned/updated a minimum of another assignment. Additionally, an effectively final variable may be a variable whose value isn’t changed, but it isn’t declared with the ultimate keyword."
},
{
"code": null,
"e": 24736,
"s": 24712,
"text": "int number;\nnumber = 7;"
},
{
"code": null,
"e": 24857,
"s": 24736,
"text": "Note: Final and Effective Final are similar but just that effective Final variables are not declared with Keyword final."
},
{
"code": null,
"e": 24866,
"s": 24857,
"text": "Example:"
},
{
"code": null,
"e": 24871,
"s": 24866,
"text": "Java"
},
{
"code": "// Java Program to Illustrate Effective Final Keyword // Importing input output classesimport java.io.*; // Main classclass GFG { // Main friver method public static void main(String[] args) { // Calling the method where custom operands // are passed as parameters calculateValue(124, 53); } // Method 2 // To calculate the value by passing operands as // parameters public static void calculateValue(int operand1, int operand2) { // Operands and remainder are effectively final here int rem = 0; // Remainder lost its effectively final property // here because it gets its second assignment rem = operand1 % 5; // Operands are still effectively final here // Class 2 class operators { // Method 1 void setNum() { // operand1 lost its effectively final // property here because it gets its second // assignment operand1 = operand2 % 2; } // Method 2 int add() { // It does not compile because rem is not // effectively final return rem + operand2; } // Method 3 int multiply() { // It does not compile because both // remainder and operand1 are not // effectively final return rem * operand1; } } }}",
"e": 26447,
"s": 24871,
"text": null
},
{
"code": null,
"e": 26555,
"s": 26447,
"text": "Output: An error will be thrown as expected which can be perceived from the terminal output as shown below:"
},
{
"code": null,
"e": 26588,
"s": 26555,
"text": "Lambda expression capture values"
},
{
"code": null,
"e": 26905,
"s": 26588,
"text": "When a lambda expression uses an assigned local variable from its enclosing space there’s a crucial restriction. A lambda expression may only use a local variable whose value doesn’t change. That restriction is referred to as “variable capture” which is described as; lambda expression capture values, not variables."
},
{
"code": null,
"e": 26998,
"s": 26905,
"text": "The local variables that a lambda expression may use are referred to as “effectively final”."
},
{
"code": null,
"e": 27195,
"s": 26998,
"text": "An effectively final variable is one whose value doesn’t change after it’s first assigned. There is no need to explicitly declare such a variable as final, although doing so would not be an error."
},
{
"code": null,
"e": 27520,
"s": 27195,
"text": "Implementation: Consider we do have an area variable let it be ‘i’ which is initialized with the worth say be ‘7’, with within the lambda expression we try to vary that value by assigning a new value to i. This will end in compiler error – “Local variable i defined in an enclosing scope must be final or effectively final”."
},
{
"code": null,
"e": 27525,
"s": 27520,
"text": "Java"
},
{
"code": "// Java Program to Illustrate Effective Final Keyword // Importing input output classesimport java.io.*; // Defining an interface@FunctionalInterface interface IFuncInt { // Method 1 int func(int num1, int num2); public String toString();} // Main driver methodpublic class GFG { // Main driver method public static void main(String[] args) { int i = 7; IFuncInt funcInt = (num1, num2) -> { // It produces an error due to effectively final // variable not declared i = num1 + num2; return i; }; }}",
"e": 28130,
"s": 27525,
"text": null
},
{
"code": null,
"e": 28138,
"s": 28130,
"text": "Output:"
},
{
"code": null,
"e": 28150,
"s": 28138,
"text": "java-basics"
},
{
"code": null,
"e": 28157,
"s": 28150,
"text": "Picked"
},
{
"code": null,
"e": 28162,
"s": 28157,
"text": "Java"
},
{
"code": null,
"e": 28167,
"s": 28162,
"text": "Java"
},
{
"code": null,
"e": 28265,
"s": 28167,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 28280,
"s": 28265,
"text": "Stream In Java"
},
{
"code": null,
"e": 28301,
"s": 28280,
"text": "Constructors in Java"
},
{
"code": null,
"e": 28347,
"s": 28301,
"text": "Different ways of Reading a text file in Java"
},
{
"code": null,
"e": 28366,
"s": 28347,
"text": "Exceptions in Java"
},
{
"code": null,
"e": 28396,
"s": 28366,
"text": "Functional Interfaces in Java"
},
{
"code": null,
"e": 28413,
"s": 28396,
"text": "Generics in Java"
},
{
"code": null,
"e": 28456,
"s": 28413,
"text": "Comparator Interface in Java with Examples"
},
{
"code": null,
"e": 28477,
"s": 28456,
"text": "Introduction to Java"
},
{
"code": null,
"e": 28506,
"s": 28477,
"text": "HashMap get() Method in Java"
}
] |
How to display a JFrame to the center of a screen in Java? | A JFrame is a subclass of Frame class and the components added to a frame are referred to as its contents, these are managed by the contentPane. We can add the components to a JFrame to use its contentPane instead. A JFrame is like a Window with border, title, and buttons. We can implement most of the java swing applications using JFrame.
By default, a JFrame can be displayed at the top-left position of a screen. We can display the center position of JFrame using the setLocationRelativeTo() method of Window class.
public void setLocationRelativeTo(Component c)
import javax.swing.*;
import java.awt.*;
public class JFrameCenterPositionTest extends JFrame {
public JFrameCenterPositionTest() {
setTitle("JFrameCenter Position");
add(new JLabel("JFrame set to center of the screen", SwingConstants.CENTER), BorderLayout.CENTER);
setSize(400, 300);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLocationRelativeTo(null); // this method display the JFrame to center position of a screen
setVisible(true);
}
public static void main (String[] args) {
new JFrameCenterPositionTest();
}
} | [
{
"code": null,
"e": 1403,
"s": 1062,
"text": "A JFrame is a subclass of Frame class and the components added to a frame are referred to as its contents, these are managed by the contentPane. We can add the components to a JFrame to use its contentPane instead. A JFrame is like a Window with border, title, and buttons. We can implement most of the java swing applications using JFrame."
},
{
"code": null,
"e": 1582,
"s": 1403,
"text": "By default, a JFrame can be displayed at the top-left position of a screen. We can display the center position of JFrame using the setLocationRelativeTo() method of Window class."
},
{
"code": null,
"e": 1629,
"s": 1582,
"text": "public void setLocationRelativeTo(Component c)"
},
{
"code": null,
"e": 2223,
"s": 1629,
"text": "import javax.swing.*;\nimport java.awt.*;\npublic class JFrameCenterPositionTest extends JFrame {\n public JFrameCenterPositionTest() {\n setTitle(\"JFrameCenter Position\");\n add(new JLabel(\"JFrame set to center of the screen\", SwingConstants.CENTER), BorderLayout.CENTER);\n setSize(400, 300);\n setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);\n setLocationRelativeTo(null); // this method display the JFrame to center position of a screen\n setVisible(true);\n }\n public static void main (String[] args) {\n new JFrameCenterPositionTest();\n }\n}"
}
] |
C++ Data Structures | C/C++ arrays allow you to define variables that combine several data items of the same kind, but structure is another user defined data type which allows you to combine data items of different kinds.
Structures are used to represent a record, suppose you want to keep track of your books in a library. You might want to track the following attributes about each book −
Title
Author
Subject
Book ID
To define a structure, you must use the struct statement. The struct statement defines a new data type, with more than one member, for your program. The format of the struct statement is this −
struct [structure tag] {
member definition;
member definition;
...
member definition;
} [one or more structure variables];
The structure tag is optional and each member definition is a normal variable definition, such as int i; or float f; or any other valid variable definition. At the end of the structure's definition, before the final semicolon, you can specify one or more structure variables but it is optional. Here is the way you would declare the Book structure −
struct Books {
char title[50];
char author[50];
char subject[100];
int book_id;
} book;
To access any member of a structure, we use the member access operator (.). The member access operator is coded as a period between the structure variable name and the structure member that we wish to access. You would use struct keyword to define variables of structure type. Following is the example to explain usage of structure −
#include <iostream>
#include <cstring>
using namespace std;
struct Books {
char title[50];
char author[50];
char subject[100];
int book_id;
};
int main() {
struct Books Book1; // Declare Book1 of type Book
struct Books Book2; // Declare Book2 of type Book
// book 1 specification
strcpy( Book1.title, "Learn C++ Programming");
strcpy( Book1.author, "Chand Miyan");
strcpy( Book1.subject, "C++ Programming");
Book1.book_id = 6495407;
// book 2 specification
strcpy( Book2.title, "Telecom Billing");
strcpy( Book2.author, "Yakit Singha");
strcpy( Book2.subject, "Telecom");
Book2.book_id = 6495700;
// Print Book1 info
cout << "Book 1 title : " << Book1.title <<endl;
cout << "Book 1 author : " << Book1.author <<endl;
cout << "Book 1 subject : " << Book1.subject <<endl;
cout << "Book 1 id : " << Book1.book_id <<endl;
// Print Book2 info
cout << "Book 2 title : " << Book2.title <<endl;
cout << "Book 2 author : " << Book2.author <<endl;
cout << "Book 2 subject : " << Book2.subject <<endl;
cout << "Book 2 id : " << Book2.book_id <<endl;
return 0;
}
When the above code is compiled and executed, it produces the following result −
Book 1 title : Learn C++ Programming
Book 1 author : Chand Miyan
Book 1 subject : C++ Programming
Book 1 id : 6495407
Book 2 title : Telecom Billing
Book 2 author : Yakit Singha
Book 2 subject : Telecom
Book 2 id : 6495700
You can pass a structure as a function argument in very similar way as you pass any other variable or pointer. You would access structure variables in the similar way as you have accessed in the above example −
#include <iostream>
#include <cstring>
using namespace std;
void printBook( struct Books book );
struct Books {
char title[50];
char author[50];
char subject[100];
int book_id;
};
int main() {
struct Books Book1; // Declare Book1 of type Book
struct Books Book2; // Declare Book2 of type Book
// book 1 specification
strcpy( Book1.title, "Learn C++ Programming");
strcpy( Book1.author, "Chand Miyan");
strcpy( Book1.subject, "C++ Programming");
Book1.book_id = 6495407;
// book 2 specification
strcpy( Book2.title, "Telecom Billing");
strcpy( Book2.author, "Yakit Singha");
strcpy( Book2.subject, "Telecom");
Book2.book_id = 6495700;
// Print Book1 info
printBook( Book1 );
// Print Book2 info
printBook( Book2 );
return 0;
}
void printBook( struct Books book ) {
cout << "Book title : " << book.title <<endl;
cout << "Book author : " << book.author <<endl;
cout << "Book subject : " << book.subject <<endl;
cout << "Book id : " << book.book_id <<endl;
}
When the above code is compiled and executed, it produces the following result −
Book title : Learn C++ Programming
Book author : Chand Miyan
Book subject : C++ Programming
Book id : 6495407
Book title : Telecom Billing
Book author : Yakit Singha
Book subject : Telecom
Book id : 6495700
You can define pointers to structures in very similar way as you define pointer to any other variable as follows −
struct Books *struct_pointer;
Now, you can store the address of a structure variable in the above defined pointer variable. To find the address of a structure variable, place the & operator before the structure's name as follows −
struct_pointer = &Book1;
To access the members of a structure using a pointer to that structure, you must use the -> operator as follows −
struct_pointer->title;
Let us re-write above example using structure pointer, hope this will be easy for you to understand the concept −
#include <iostream>
#include <cstring>
using namespace std;
void printBook( struct Books *book );
struct Books {
char title[50];
char author[50];
char subject[100];
int book_id;
};
int main() {
struct Books Book1; // Declare Book1 of type Book
struct Books Book2; // Declare Book2 of type Book
// Book 1 specification
strcpy( Book1.title, "Learn C++ Programming");
strcpy( Book1.author, "Chand Miyan");
strcpy( Book1.subject, "C++ Programming");
Book1.book_id = 6495407;
// Book 2 specification
strcpy( Book2.title, "Telecom Billing");
strcpy( Book2.author, "Yakit Singha");
strcpy( Book2.subject, "Telecom");
Book2.book_id = 6495700;
// Print Book1 info, passing address of structure
printBook( &Book1 );
// Print Book1 info, passing address of structure
printBook( &Book2 );
return 0;
}
// This function accept pointer to structure as parameter.
void printBook( struct Books *book ) {
cout << "Book title : " << book->title <<endl;
cout << "Book author : " << book->author <<endl;
cout << "Book subject : " << book->subject <<endl;
cout << "Book id : " << book->book_id <<endl;
}
When the above code is compiled and executed, it produces the following result −
Book title : Learn C++ Programming
Book author : Chand Miyan
Book subject : C++ Programming
Book id : 6495407
Book title : Telecom Billing
Book author : Yakit Singha
Book subject : Telecom
Book id : 6495700
There is an easier way to define structs or you could "alias" types you create. For example −
typedef struct {
char title[50];
char author[50];
char subject[100];
int book_id;
} Books;
Now, you can use Books directly to define variables of Books type without using struct keyword. Following is the example −
Books Book1, Book2;
You can use typedef keyword for non-structs as well as follows −
typedef long int *pint32;
pint32 x, y, z;
x, y and z are all pointers to long ints.
154 Lectures
11.5 hours
Arnab Chakraborty
14 Lectures
57 mins
Kaushik Roy Chowdhury
30 Lectures
12.5 hours
Frahaan Hussain
54 Lectures
3.5 hours
Frahaan Hussain
77 Lectures
5.5 hours
Frahaan Hussain
12 Lectures
3.5 hours
Frahaan Hussain
Print
Add Notes
Bookmark this page | [
{
"code": null,
"e": 2518,
"s": 2318,
"text": "C/C++ arrays allow you to define variables that combine several data items of the same kind, but structure is another user defined data type which allows you to combine data items of different kinds."
},
{
"code": null,
"e": 2687,
"s": 2518,
"text": "Structures are used to represent a record, suppose you want to keep track of your books in a library. You might want to track the following attributes about each book −"
},
{
"code": null,
"e": 2693,
"s": 2687,
"text": "Title"
},
{
"code": null,
"e": 2700,
"s": 2693,
"text": "Author"
},
{
"code": null,
"e": 2708,
"s": 2700,
"text": "Subject"
},
{
"code": null,
"e": 2716,
"s": 2708,
"text": "Book ID"
},
{
"code": null,
"e": 2910,
"s": 2716,
"text": "To define a structure, you must use the struct statement. The struct statement defines a new data type, with more than one member, for your program. The format of the struct statement is this −"
},
{
"code": null,
"e": 3048,
"s": 2910,
"text": "struct [structure tag] {\n member definition;\n member definition;\n ...\n member definition;\n} [one or more structure variables]; \n"
},
{
"code": null,
"e": 3398,
"s": 3048,
"text": "The structure tag is optional and each member definition is a normal variable definition, such as int i; or float f; or any other valid variable definition. At the end of the structure's definition, before the final semicolon, you can specify one or more structure variables but it is optional. Here is the way you would declare the Book structure −"
},
{
"code": null,
"e": 3506,
"s": 3398,
"text": "struct Books {\n char title[50];\n char author[50];\n char subject[100];\n int book_id;\n} book; \n"
},
{
"code": null,
"e": 3840,
"s": 3506,
"text": "To access any member of a structure, we use the member access operator (.). The member access operator is coded as a period between the structure variable name and the structure member that we wish to access. You would use struct keyword to define variables of structure type. Following is the example to explain usage of structure −"
},
{
"code": null,
"e": 5005,
"s": 3840,
"text": "#include <iostream>\n#include <cstring>\n \nusing namespace std;\n \nstruct Books {\n char title[50];\n char author[50];\n char subject[100];\n int book_id;\n};\n \nint main() {\n struct Books Book1; // Declare Book1 of type Book\n struct Books Book2; // Declare Book2 of type Book\n \n // book 1 specification\n strcpy( Book1.title, \"Learn C++ Programming\");\n strcpy( Book1.author, \"Chand Miyan\"); \n strcpy( Book1.subject, \"C++ Programming\");\n Book1.book_id = 6495407;\n\n // book 2 specification\n strcpy( Book2.title, \"Telecom Billing\");\n strcpy( Book2.author, \"Yakit Singha\");\n strcpy( Book2.subject, \"Telecom\");\n Book2.book_id = 6495700;\n \n // Print Book1 info\n cout << \"Book 1 title : \" << Book1.title <<endl;\n cout << \"Book 1 author : \" << Book1.author <<endl;\n cout << \"Book 1 subject : \" << Book1.subject <<endl;\n cout << \"Book 1 id : \" << Book1.book_id <<endl;\n\n // Print Book2 info\n cout << \"Book 2 title : \" << Book2.title <<endl;\n cout << \"Book 2 author : \" << Book2.author <<endl;\n cout << \"Book 2 subject : \" << Book2.subject <<endl;\n cout << \"Book 2 id : \" << Book2.book_id <<endl;\n\n return 0;\n}"
},
{
"code": null,
"e": 5086,
"s": 5005,
"text": "When the above code is compiled and executed, it produces the following result −"
},
{
"code": null,
"e": 5310,
"s": 5086,
"text": "Book 1 title : Learn C++ Programming\nBook 1 author : Chand Miyan\nBook 1 subject : C++ Programming\nBook 1 id : 6495407\nBook 2 title : Telecom Billing\nBook 2 author : Yakit Singha\nBook 2 subject : Telecom\nBook 2 id : 6495700\n"
},
{
"code": null,
"e": 5521,
"s": 5310,
"text": "You can pass a structure as a function argument in very similar way as you pass any other variable or pointer. You would access structure variables in the similar way as you have accessed in the above example −"
},
{
"code": null,
"e": 6583,
"s": 5521,
"text": "#include <iostream>\n#include <cstring>\n \nusing namespace std;\nvoid printBook( struct Books book );\n\nstruct Books {\n char title[50];\n char author[50];\n char subject[100];\n int book_id;\n};\n \nint main() {\n struct Books Book1; // Declare Book1 of type Book\n struct Books Book2; // Declare Book2 of type Book\n \n // book 1 specification\n strcpy( Book1.title, \"Learn C++ Programming\");\n strcpy( Book1.author, \"Chand Miyan\"); \n strcpy( Book1.subject, \"C++ Programming\");\n Book1.book_id = 6495407;\n\n // book 2 specification\n strcpy( Book2.title, \"Telecom Billing\");\n strcpy( Book2.author, \"Yakit Singha\");\n strcpy( Book2.subject, \"Telecom\");\n Book2.book_id = 6495700;\n \n // Print Book1 info\n printBook( Book1 );\n\n // Print Book2 info\n printBook( Book2 );\n\n return 0;\n}\nvoid printBook( struct Books book ) {\n cout << \"Book title : \" << book.title <<endl;\n cout << \"Book author : \" << book.author <<endl;\n cout << \"Book subject : \" << book.subject <<endl;\n cout << \"Book id : \" << book.book_id <<endl;\n}"
},
{
"code": null,
"e": 6664,
"s": 6583,
"text": "When the above code is compiled and executed, it produces the following result −"
},
{
"code": null,
"e": 6872,
"s": 6664,
"text": "Book title : Learn C++ Programming\nBook author : Chand Miyan\nBook subject : C++ Programming\nBook id : 6495407\nBook title : Telecom Billing\nBook author : Yakit Singha\nBook subject : Telecom\nBook id : 6495700\n"
},
{
"code": null,
"e": 6987,
"s": 6872,
"text": "You can define pointers to structures in very similar way as you define pointer to any other variable as follows −"
},
{
"code": null,
"e": 7018,
"s": 6987,
"text": "struct Books *struct_pointer;\n"
},
{
"code": null,
"e": 7219,
"s": 7018,
"text": "Now, you can store the address of a structure variable in the above defined pointer variable. To find the address of a structure variable, place the & operator before the structure's name as follows −"
},
{
"code": null,
"e": 7245,
"s": 7219,
"text": "struct_pointer = &Book1;\n"
},
{
"code": null,
"e": 7359,
"s": 7245,
"text": "To access the members of a structure using a pointer to that structure, you must use the -> operator as follows −"
},
{
"code": null,
"e": 7383,
"s": 7359,
"text": "struct_pointer->title;\n"
},
{
"code": null,
"e": 7497,
"s": 7383,
"text": "Let us re-write above example using structure pointer, hope this will be easy for you to understand the concept −"
},
{
"code": null,
"e": 8685,
"s": 7497,
"text": "#include <iostream>\n#include <cstring>\n \nusing namespace std;\nvoid printBook( struct Books *book );\n\nstruct Books {\n char title[50];\n char author[50];\n char subject[100];\n int book_id;\n};\nint main() {\n struct Books Book1; // Declare Book1 of type Book\n struct Books Book2; // Declare Book2 of type Book\n \n // Book 1 specification\n strcpy( Book1.title, \"Learn C++ Programming\");\n strcpy( Book1.author, \"Chand Miyan\"); \n strcpy( Book1.subject, \"C++ Programming\");\n Book1.book_id = 6495407;\n\n // Book 2 specification\n strcpy( Book2.title, \"Telecom Billing\");\n strcpy( Book2.author, \"Yakit Singha\");\n strcpy( Book2.subject, \"Telecom\");\n Book2.book_id = 6495700;\n \n // Print Book1 info, passing address of structure\n printBook( &Book1 );\n\n // Print Book1 info, passing address of structure\n printBook( &Book2 );\n\n return 0;\n}\n\n// This function accept pointer to structure as parameter.\nvoid printBook( struct Books *book ) {\n cout << \"Book title : \" << book->title <<endl;\n cout << \"Book author : \" << book->author <<endl;\n cout << \"Book subject : \" << book->subject <<endl;\n cout << \"Book id : \" << book->book_id <<endl;\n}"
},
{
"code": null,
"e": 8766,
"s": 8685,
"text": "When the above code is compiled and executed, it produces the following result −"
},
{
"code": null,
"e": 8974,
"s": 8766,
"text": "Book title : Learn C++ Programming\nBook author : Chand Miyan\nBook subject : C++ Programming\nBook id : 6495407\nBook title : Telecom Billing\nBook author : Yakit Singha\nBook subject : Telecom\nBook id : 6495700\n"
},
{
"code": null,
"e": 9068,
"s": 8974,
"text": "There is an easier way to define structs or you could \"alias\" types you create. For example −"
},
{
"code": null,
"e": 9177,
"s": 9068,
"text": "typedef struct {\n char title[50];\n char author[50];\n char subject[100];\n int book_id;\n} Books;\n"
},
{
"code": null,
"e": 9301,
"s": 9177,
"text": "Now, you can use Books directly to define variables of Books type without using struct keyword. Following is the example −"
},
{
"code": null,
"e": 9322,
"s": 9301,
"text": "Books Book1, Book2;\n"
},
{
"code": null,
"e": 9387,
"s": 9322,
"text": "You can use typedef keyword for non-structs as well as follows −"
},
{
"code": null,
"e": 9432,
"s": 9387,
"text": "typedef long int *pint32;\n \npint32 x, y, z;\n"
},
{
"code": null,
"e": 9474,
"s": 9432,
"text": "x, y and z are all pointers to long ints."
},
{
"code": null,
"e": 9511,
"s": 9474,
"text": "\n 154 Lectures \n 11.5 hours \n"
},
{
"code": null,
"e": 9530,
"s": 9511,
"text": " Arnab Chakraborty"
},
{
"code": null,
"e": 9562,
"s": 9530,
"text": "\n 14 Lectures \n 57 mins\n"
},
{
"code": null,
"e": 9585,
"s": 9562,
"text": " Kaushik Roy Chowdhury"
},
{
"code": null,
"e": 9621,
"s": 9585,
"text": "\n 30 Lectures \n 12.5 hours \n"
},
{
"code": null,
"e": 9638,
"s": 9621,
"text": " Frahaan Hussain"
},
{
"code": null,
"e": 9673,
"s": 9638,
"text": "\n 54 Lectures \n 3.5 hours \n"
},
{
"code": null,
"e": 9690,
"s": 9673,
"text": " Frahaan Hussain"
},
{
"code": null,
"e": 9725,
"s": 9690,
"text": "\n 77 Lectures \n 5.5 hours \n"
},
{
"code": null,
"e": 9742,
"s": 9725,
"text": " Frahaan Hussain"
},
{
"code": null,
"e": 9777,
"s": 9742,
"text": "\n 12 Lectures \n 3.5 hours \n"
},
{
"code": null,
"e": 9794,
"s": 9777,
"text": " Frahaan Hussain"
},
{
"code": null,
"e": 9801,
"s": 9794,
"text": " Print"
},
{
"code": null,
"e": 9812,
"s": 9801,
"text": " Add Notes"
}
] |
Chrome WebDriver Options | Selenium Chrome webdriver Options are handled with the class - selenium.webdriver.chrome.options.Options.
Some of the methods of the above mentioned class are listed below −
add_argument(args) − It is used to append arguments to a list.
add_argument(args) − It is used to append arguments to a list.
add_encoded_extension(ext) −It is used to append base 64 encoded string and the extension data to a list that will be utilised to get it to the ChromeDriver.
add_encoded_extension(ext) −It is used to append base 64 encoded string and the extension data to a list that will be utilised to get it to the ChromeDriver.
add_experimental_option(n, val) − It is used to append an experimental option which is passed to the Chrome browser.
add_experimental_option(n, val) − It is used to append an experimental option which is passed to the Chrome browser.
add_extension(ext) − It is used to append the extension path to a list that will be utilised to get it to the ChromeDriver.
add_extension(ext) − It is used to append the extension path to a list that will be utilised to get it to the ChromeDriver.
set_capability(n, val) − It is used to define a capability.
set_capability(n, val) − It is used to define a capability.
to_capabilities(n, val) − It is used to generate capabilities along with options and yields a dictionary with all the data.
to_capabilities(n, val) − It is used to generate capabilities along with options and yields a dictionary with all the data.
arguments −It is used to yield arguments list required for the browser.
arguments −It is used to yield arguments list required for the browser.
binary_location − It is used to obtain the binary location. If there is no path, an empty string is returned.
binary_location − It is used to obtain the binary location. If there is no path, an empty string is returned.
debugger_address − It is used to yield the remote devtools object.
debugger_address − It is used to yield the remote devtools object.
experimental_options − It is used to yield a dictionary of the Chrome experimental options.
extensions − It is used to yield an extensions list which shall be loaded to the Chrome browser.
extensions − It is used to yield an extensions list which shall be loaded to the Chrome browser.
headless −It is used to check if the headless argument is set or not.
headless −It is used to check if the headless argument is set or not.
The code implementation for the Selenium Chrome Webdriver options is as follows −
from selenium import webdriver
from selenium.webdriver.chrome.options import Options
#object of Options class
c = Options()
#passing headless parameter
c.add_argument("--headless")
#adding headless parameter to webdriver object
driver = webdriver.Chrome(executable_path='../drivers/chromedriver', options=c)
# implicit wait time
driver.implicitly_wait(5)
# url launch
driver.get("https −//www.tutorialspoint.com/about/about_careers.htm")
print('Page title − ' + driver.title)
# driver quit
driver.quit()
The output shows the message - Process with exit code 0 meaning that the above Python code executed successfully. Also, the page title of the application(obtained from the driver.title method) - About Careers at Tutorials Point - Tutorialspoint gets printed in the console.
46 Lectures
5.5 hours
Aditya Dua
296 Lectures
146 hours
Arun Motoori
411 Lectures
38.5 hours
In28Minutes Official
22 Lectures
7 hours
Arun Motoori
118 Lectures
17 hours
Arun Motoori
278 Lectures
38.5 hours
Lets Kode It
Print
Add Notes
Bookmark this page | [
{
"code": null,
"e": 2309,
"s": 2203,
"text": "Selenium Chrome webdriver Options are handled with the class - selenium.webdriver.chrome.options.Options."
},
{
"code": null,
"e": 2377,
"s": 2309,
"text": "Some of the methods of the above mentioned class are listed below −"
},
{
"code": null,
"e": 2440,
"s": 2377,
"text": "add_argument(args) − It is used to append arguments to a list."
},
{
"code": null,
"e": 2503,
"s": 2440,
"text": "add_argument(args) − It is used to append arguments to a list."
},
{
"code": null,
"e": 2661,
"s": 2503,
"text": "add_encoded_extension(ext) −It is used to append base 64 encoded string and the extension data to a list that will be utilised to get it to the ChromeDriver."
},
{
"code": null,
"e": 2819,
"s": 2661,
"text": "add_encoded_extension(ext) −It is used to append base 64 encoded string and the extension data to a list that will be utilised to get it to the ChromeDriver."
},
{
"code": null,
"e": 2936,
"s": 2819,
"text": "add_experimental_option(n, val) − It is used to append an experimental option which is passed to the Chrome browser."
},
{
"code": null,
"e": 3053,
"s": 2936,
"text": "add_experimental_option(n, val) − It is used to append an experimental option which is passed to the Chrome browser."
},
{
"code": null,
"e": 3177,
"s": 3053,
"text": "add_extension(ext) − It is used to append the extension path to a list that will be utilised to get it to the ChromeDriver."
},
{
"code": null,
"e": 3301,
"s": 3177,
"text": "add_extension(ext) − It is used to append the extension path to a list that will be utilised to get it to the ChromeDriver."
},
{
"code": null,
"e": 3361,
"s": 3301,
"text": "set_capability(n, val) − It is used to define a capability."
},
{
"code": null,
"e": 3421,
"s": 3361,
"text": "set_capability(n, val) − It is used to define a capability."
},
{
"code": null,
"e": 3545,
"s": 3421,
"text": "to_capabilities(n, val) − It is used to generate capabilities along with options and yields a dictionary with all the data."
},
{
"code": null,
"e": 3669,
"s": 3545,
"text": "to_capabilities(n, val) − It is used to generate capabilities along with options and yields a dictionary with all the data."
},
{
"code": null,
"e": 3741,
"s": 3669,
"text": "arguments −It is used to yield arguments list required for the browser."
},
{
"code": null,
"e": 3813,
"s": 3741,
"text": "arguments −It is used to yield arguments list required for the browser."
},
{
"code": null,
"e": 3923,
"s": 3813,
"text": "binary_location − It is used to obtain the binary location. If there is no path, an empty string is returned."
},
{
"code": null,
"e": 4033,
"s": 3923,
"text": "binary_location − It is used to obtain the binary location. If there is no path, an empty string is returned."
},
{
"code": null,
"e": 4100,
"s": 4033,
"text": "debugger_address − It is used to yield the remote devtools object."
},
{
"code": null,
"e": 4167,
"s": 4100,
"text": "debugger_address − It is used to yield the remote devtools object."
},
{
"code": null,
"e": 4259,
"s": 4167,
"text": "experimental_options − It is used to yield a dictionary of the Chrome experimental options."
},
{
"code": null,
"e": 4356,
"s": 4259,
"text": "extensions − It is used to yield an extensions list which shall be loaded to the Chrome browser."
},
{
"code": null,
"e": 4453,
"s": 4356,
"text": "extensions − It is used to yield an extensions list which shall be loaded to the Chrome browser."
},
{
"code": null,
"e": 4523,
"s": 4453,
"text": "headless −It is used to check if the headless argument is set or not."
},
{
"code": null,
"e": 4593,
"s": 4523,
"text": "headless −It is used to check if the headless argument is set or not."
},
{
"code": null,
"e": 4675,
"s": 4593,
"text": "The code implementation for the Selenium Chrome Webdriver options is as follows −"
},
{
"code": null,
"e": 5179,
"s": 4675,
"text": "from selenium import webdriver\nfrom selenium.webdriver.chrome.options import Options\n#object of Options class\nc = Options()\n#passing headless parameter\nc.add_argument(\"--headless\")\n#adding headless parameter to webdriver object\ndriver = webdriver.Chrome(executable_path='../drivers/chromedriver', options=c)\n# implicit wait time\ndriver.implicitly_wait(5)\n# url launch\ndriver.get(\"https −//www.tutorialspoint.com/about/about_careers.htm\")\nprint('Page title − ' + driver.title)\n# driver quit\ndriver.quit()"
},
{
"code": null,
"e": 5453,
"s": 5179,
"text": "The output shows the message - Process with exit code 0 meaning that the above Python code executed successfully. Also, the page title of the application(obtained from the driver.title method) - About Careers at Tutorials Point - Tutorialspoint gets printed in the console."
},
{
"code": null,
"e": 5488,
"s": 5453,
"text": "\n 46 Lectures \n 5.5 hours \n"
},
{
"code": null,
"e": 5500,
"s": 5488,
"text": " Aditya Dua"
},
{
"code": null,
"e": 5536,
"s": 5500,
"text": "\n 296 Lectures \n 146 hours \n"
},
{
"code": null,
"e": 5550,
"s": 5536,
"text": " Arun Motoori"
},
{
"code": null,
"e": 5587,
"s": 5550,
"text": "\n 411 Lectures \n 38.5 hours \n"
},
{
"code": null,
"e": 5609,
"s": 5587,
"text": " In28Minutes Official"
},
{
"code": null,
"e": 5642,
"s": 5609,
"text": "\n 22 Lectures \n 7 hours \n"
},
{
"code": null,
"e": 5656,
"s": 5642,
"text": " Arun Motoori"
},
{
"code": null,
"e": 5691,
"s": 5656,
"text": "\n 118 Lectures \n 17 hours \n"
},
{
"code": null,
"e": 5705,
"s": 5691,
"text": " Arun Motoori"
},
{
"code": null,
"e": 5742,
"s": 5705,
"text": "\n 278 Lectures \n 38.5 hours \n"
},
{
"code": null,
"e": 5756,
"s": 5742,
"text": " Lets Kode It"
},
{
"code": null,
"e": 5763,
"s": 5756,
"text": " Print"
},
{
"code": null,
"e": 5774,
"s": 5763,
"text": " Add Notes"
}
] |
How to Convert Integers to Strings in Pandas DataFrame? - GeeksforGeeks | 01 Aug, 2020
In this article, we’ll look at different methods to convert an integer into a string in a Pandas dataframe. In Pandas, there are different functions that we can use to achieve this task :
map(str)
astype(str)
apply(str)
applymap(str)
Example 1 : In this example, we’ll convert each value of a column of integers to string using the map(str) function.
# importing pandas as pdimport pandas as pd # creating a dictionary of integersdict = {'Integers' : [10, 50, 100, 350, 700]} # creating dataframe from dictionarydf = pd.DataFrame.from_dict(dict)print(df)print(df.dtypes) print('\n') # converting each value of column to a stringdf['Integers'] = df['Integers'].map(str)print(df)print(df.dtypes)
Output :
We can see in the above output that before the the datatype was int64 and after the conversion to a string, the datatype is an object which represents a string.
Example 2 : In this example, we’ll convert each value of a column of integers to string using the astype(str) function.
# importing pandas as pdimport pandas as pd # creating a dictionary of integersdict = {'Integers' : [10, 50, 100, 350, 700]} # creating dataframe from dictionarydf = pd.DataFrame.from_dict(dict)print(df)print(df.dtypes) print('\n') # converting each value of column to a stringdf['Integers'] = df['Integers'].astype(str) print(df)print(df.dtypes)
Output :
We can see in the above output that before the the datatype was int64 and after the conversion to a string, the datatype is an object which represents a string.
Example 3 : In this example, we’ll convert each value of a column of integers to string using the apply(str) function.
# importing pandas as pdimport pandas as pd # creating a dictionary of integersdict = {'Integers' : [10, 50, 100, 350, 700]} # creating dataframe from dictionarydf = pd.DataFrame.from_dict(dict)print(df)print(df.dtypes) print('\n') # converting each value of column to a stringdf['Integers'] = df['Integers'].apply(str)print(df)print(df.dtypes)
Output :
We can see in the above output that before the the datatype was int64 and after the conversion to a string, the datatype is an object which represents a string.
Example 4 : All the methods we saw above, convert a single column from an integer to a string. But we can also convert the whole dataframe into a string using the applymap(str) method.
# importing pandas as pdimport pandas as pd # creating a dictionary of integersdict = {'Roll No.' : [1, 2, 3, 4, 5], 'Marks':[79, 85, 91, 81, 95]} # creating dataframe from dictionarydf = pd.DataFrame.from_dict(dict)print(df)print(df.dtypes) print('\n') # converting each value of column to a stringdf = df.applymap(str)print(df)print(df.dtypes)
Output :
We can see in the above output that before the the datatype was int64 and after the conversion to a string, the datatype is an object which represents a string.
Python pandas-dataFrame
Python-pandas
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
How to Install PIP on Windows ?
How to drop one or multiple columns in Pandas Dataframe
How To Convert Python Dictionary To JSON?
Check if element exists in list in Python
Python | Pandas dataframe.groupby()
Defaultdict in Python
Python | Get unique values from a list
Python Classes and Objects
Python | os.path.join() method
Create a directory in Python | [
{
"code": null,
"e": 23901,
"s": 23873,
"text": "\n01 Aug, 2020"
},
{
"code": null,
"e": 24089,
"s": 23901,
"text": "In this article, we’ll look at different methods to convert an integer into a string in a Pandas dataframe. In Pandas, there are different functions that we can use to achieve this task :"
},
{
"code": null,
"e": 24098,
"s": 24089,
"text": "map(str)"
},
{
"code": null,
"e": 24110,
"s": 24098,
"text": "astype(str)"
},
{
"code": null,
"e": 24121,
"s": 24110,
"text": "apply(str)"
},
{
"code": null,
"e": 24135,
"s": 24121,
"text": "applymap(str)"
},
{
"code": null,
"e": 24252,
"s": 24135,
"text": "Example 1 : In this example, we’ll convert each value of a column of integers to string using the map(str) function."
},
{
"code": "# importing pandas as pdimport pandas as pd # creating a dictionary of integersdict = {'Integers' : [10, 50, 100, 350, 700]} # creating dataframe from dictionarydf = pd.DataFrame.from_dict(dict)print(df)print(df.dtypes) print('\\n') # converting each value of column to a stringdf['Integers'] = df['Integers'].map(str)print(df)print(df.dtypes)",
"e": 24600,
"s": 24252,
"text": null
},
{
"code": null,
"e": 24609,
"s": 24600,
"text": "Output :"
},
{
"code": null,
"e": 24770,
"s": 24609,
"text": "We can see in the above output that before the the datatype was int64 and after the conversion to a string, the datatype is an object which represents a string."
},
{
"code": null,
"e": 24890,
"s": 24770,
"text": "Example 2 : In this example, we’ll convert each value of a column of integers to string using the astype(str) function."
},
{
"code": "# importing pandas as pdimport pandas as pd # creating a dictionary of integersdict = {'Integers' : [10, 50, 100, 350, 700]} # creating dataframe from dictionarydf = pd.DataFrame.from_dict(dict)print(df)print(df.dtypes) print('\\n') # converting each value of column to a stringdf['Integers'] = df['Integers'].astype(str) print(df)print(df.dtypes)",
"e": 25243,
"s": 24890,
"text": null
},
{
"code": null,
"e": 25252,
"s": 25243,
"text": "Output :"
},
{
"code": null,
"e": 25413,
"s": 25252,
"text": "We can see in the above output that before the the datatype was int64 and after the conversion to a string, the datatype is an object which represents a string."
},
{
"code": null,
"e": 25532,
"s": 25413,
"text": "Example 3 : In this example, we’ll convert each value of a column of integers to string using the apply(str) function."
},
{
"code": "# importing pandas as pdimport pandas as pd # creating a dictionary of integersdict = {'Integers' : [10, 50, 100, 350, 700]} # creating dataframe from dictionarydf = pd.DataFrame.from_dict(dict)print(df)print(df.dtypes) print('\\n') # converting each value of column to a stringdf['Integers'] = df['Integers'].apply(str)print(df)print(df.dtypes)",
"e": 25882,
"s": 25532,
"text": null
},
{
"code": null,
"e": 25891,
"s": 25882,
"text": "Output :"
},
{
"code": null,
"e": 26052,
"s": 25891,
"text": "We can see in the above output that before the the datatype was int64 and after the conversion to a string, the datatype is an object which represents a string."
},
{
"code": null,
"e": 26237,
"s": 26052,
"text": "Example 4 : All the methods we saw above, convert a single column from an integer to a string. But we can also convert the whole dataframe into a string using the applymap(str) method."
},
{
"code": "# importing pandas as pdimport pandas as pd # creating a dictionary of integersdict = {'Roll No.' : [1, 2, 3, 4, 5], 'Marks':[79, 85, 91, 81, 95]} # creating dataframe from dictionarydf = pd.DataFrame.from_dict(dict)print(df)print(df.dtypes) print('\\n') # converting each value of column to a stringdf = df.applymap(str)print(df)print(df.dtypes)",
"e": 26588,
"s": 26237,
"text": null
},
{
"code": null,
"e": 26597,
"s": 26588,
"text": "Output :"
},
{
"code": null,
"e": 26758,
"s": 26597,
"text": "We can see in the above output that before the the datatype was int64 and after the conversion to a string, the datatype is an object which represents a string."
},
{
"code": null,
"e": 26782,
"s": 26758,
"text": "Python pandas-dataFrame"
},
{
"code": null,
"e": 26796,
"s": 26782,
"text": "Python-pandas"
},
{
"code": null,
"e": 26803,
"s": 26796,
"text": "Python"
},
{
"code": null,
"e": 26901,
"s": 26803,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 26910,
"s": 26901,
"text": "Comments"
},
{
"code": null,
"e": 26923,
"s": 26910,
"text": "Old Comments"
},
{
"code": null,
"e": 26955,
"s": 26923,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 27011,
"s": 26955,
"text": "How to drop one or multiple columns in Pandas Dataframe"
},
{
"code": null,
"e": 27053,
"s": 27011,
"text": "How To Convert Python Dictionary To JSON?"
},
{
"code": null,
"e": 27095,
"s": 27053,
"text": "Check if element exists in list in Python"
},
{
"code": null,
"e": 27131,
"s": 27095,
"text": "Python | Pandas dataframe.groupby()"
},
{
"code": null,
"e": 27153,
"s": 27131,
"text": "Defaultdict in Python"
},
{
"code": null,
"e": 27192,
"s": 27153,
"text": "Python | Get unique values from a list"
},
{
"code": null,
"e": 27219,
"s": 27192,
"text": "Python Classes and Objects"
},
{
"code": null,
"e": 27250,
"s": 27219,
"text": "Python | os.path.join() method"
}
] |
What is the MySQL VARCHAR max size? | The MySQL version before 5.0.3 was capable of storing 255 characters but from the version 5.0.3 , it is capable of storing 65,535 characters.
MySQL official documentation states −
The effective maximum length of a VARCHAR in MySQL 5.0.3 and later is subject to the maximum row size (65,535 bytes, which is shared among all columns) and the character set used. For example, utf8 characters can require up to three bytes per character, so a VARCHAR column that uses the utf8 character set can be declared to be a maximum of 21,844 characters.
Keep in mind that the limitation of maximum row size is 65,535 bytes.This states that including all columns it shouldn't be more than 65,535 bytes.
Let us see what happens if this is violated −
Here is a table with two columns, “one” varchar with the length of 32,765 and “two” with 32766.
Length = 32765+2 + 32766 + 2 = 65535.
CREATE TABLE IF NOT EXISTS `mytable` (
`one` varchar(32765) NOT NULL,
`two` varchar(32766) NOT NULL
) ENGINE=MyISAM DEFAULT CHARSET=latin1;
Now let us increase the column length −
CREATE TABLE IF NOT EXISTS `mytable` (
`one` varchar(32767) NOT NULL,
`two` varchar(32770) NOT NULL
) ENGINE=MyISAM DEFAULT CHARSET=latin1;
Above gives the following error −
#1118 - Row size too large. The maximum row size for the used table type, not counting BLOBs, is 65535. You have to change some columns to TEXT or BLOBs
The above itself states that −
The maximum row size is 65,535 bytes. If it exceeds, an error will be visible. | [
{
"code": null,
"e": 1204,
"s": 1062,
"text": "The MySQL version before 5.0.3 was capable of storing 255 characters but from the version 5.0.3 , it is capable of storing 65,535 characters."
},
{
"code": null,
"e": 1242,
"s": 1204,
"text": "MySQL official documentation states −"
},
{
"code": null,
"e": 1604,
"s": 1242,
"text": "The effective maximum length of a VARCHAR in MySQL 5.0.3 and later is subject to the maximum row size (65,535 bytes, which is shared among all columns) and the character set used. For example, utf8 characters can require up to three bytes per character, so a VARCHAR column that uses the utf8 character set can be declared to be a maximum of 21,844 characters. "
},
{
"code": null,
"e": 1752,
"s": 1604,
"text": "Keep in mind that the limitation of maximum row size is 65,535 bytes.This states that including all columns it shouldn't be more than 65,535 bytes."
},
{
"code": null,
"e": 1798,
"s": 1752,
"text": "Let us see what happens if this is violated −"
},
{
"code": null,
"e": 1894,
"s": 1798,
"text": "Here is a table with two columns, “one” varchar with the length of 32,765 and “two” with 32766."
},
{
"code": null,
"e": 1932,
"s": 1894,
"text": "Length = 32765+2 + 32766 + 2 = 65535."
},
{
"code": null,
"e": 2072,
"s": 1932,
"text": "CREATE TABLE IF NOT EXISTS `mytable` (\n`one` varchar(32765) NOT NULL,\n`two` varchar(32766) NOT NULL\n) ENGINE=MyISAM DEFAULT CHARSET=latin1;"
},
{
"code": null,
"e": 2112,
"s": 2072,
"text": "Now let us increase the column length −"
},
{
"code": null,
"e": 2252,
"s": 2112,
"text": "CREATE TABLE IF NOT EXISTS `mytable` (\n`one` varchar(32767) NOT NULL,\n`two` varchar(32770) NOT NULL\n) ENGINE=MyISAM DEFAULT CHARSET=latin1;"
},
{
"code": null,
"e": 2286,
"s": 2252,
"text": "Above gives the following error −"
},
{
"code": null,
"e": 2439,
"s": 2286,
"text": "#1118 - Row size too large. The maximum row size for the used table type, not counting BLOBs, is 65535. You have to change some columns to TEXT or BLOBs"
},
{
"code": null,
"e": 2470,
"s": 2439,
"text": "The above itself states that −"
},
{
"code": null,
"e": 2549,
"s": 2470,
"text": "The maximum row size is 65,535 bytes. If it exceeds, an error will be visible."
}
] |
Get the absolute values in Pandas - GeeksforGeeks | 18 Aug, 2020
Let us see how to get the absolute value of an element in Python Pandas. We can perform this task by using the abs() function. The abs() function is used to get a Series/DataFrame with absolute numeric value of each element.
Syntax : Series.abs() or DataFrame.abs()Parameters : NoneReturns : Series/DataFrame containing the absolute value of each element.
Example 1 : Absolute numeric values in a Series.
# import the libraryimport pandas as pd # create the Seriess = pd.Series([-2.8, 3, -4.44, 5])print(s) # fetching the absolute valuesprint("\nThe absolute values are :")print(s.abs())
Output :
Example 2 : Absolute numeric values in a Series with complex numbers.
# import the libraryimport pandas as pd # create the Seriess = pd.Series([2.2 + 1j])print(s) # fetching the absolute valuesprint("\nThe absolute values are :")print(s.abs())
Output :
Example 3 : Absolute numeric values in a Series with a Timedelta element.
# import the libraryimport pandas as pd # create the Seriess = pd.Series([pd.Timedelta('2 days')])print(s) # fetching the absolute valuesprint("\nThe absolute values are :")print(s.abs())
Output :
Example 4 : Fetching the absolute values from a DataFrame column.
# import the libraryimport pandas as pd # create the DataFramedf = pd.DataFrame({'p' : [2, 3, 4, 5], 'q' : [10, 20, 30, 40], 'r' : [200, 60, -40, -60]})display(df) # fetching the absolute valuesprint("\nThe absolute values are :")display(df.r.abs())
Output :
Python Pandas-exercise
Python pandas-series
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 ?
How To Convert Python Dictionary To JSON?
Check if element exists in list in Python
How to drop one or multiple columns in Pandas Dataframe
Python Classes and Objects
Python | os.path.join() method
Create a directory in Python
Python | Get unique values from a list
Python | Pandas dataframe.groupby()
Defaultdict in Python | [
{
"code": null,
"e": 25581,
"s": 25553,
"text": "\n18 Aug, 2020"
},
{
"code": null,
"e": 25806,
"s": 25581,
"text": "Let us see how to get the absolute value of an element in Python Pandas. We can perform this task by using the abs() function. The abs() function is used to get a Series/DataFrame with absolute numeric value of each element."
},
{
"code": null,
"e": 25937,
"s": 25806,
"text": "Syntax : Series.abs() or DataFrame.abs()Parameters : NoneReturns : Series/DataFrame containing the absolute value of each element."
},
{
"code": null,
"e": 25986,
"s": 25937,
"text": "Example 1 : Absolute numeric values in a Series."
},
{
"code": "# import the libraryimport pandas as pd # create the Seriess = pd.Series([-2.8, 3, -4.44, 5])print(s) # fetching the absolute valuesprint(\"\\nThe absolute values are :\")print(s.abs())",
"e": 26171,
"s": 25986,
"text": null
},
{
"code": null,
"e": 26180,
"s": 26171,
"text": "Output :"
},
{
"code": null,
"e": 26250,
"s": 26180,
"text": "Example 2 : Absolute numeric values in a Series with complex numbers."
},
{
"code": "# import the libraryimport pandas as pd # create the Seriess = pd.Series([2.2 + 1j])print(s) # fetching the absolute valuesprint(\"\\nThe absolute values are :\")print(s.abs())",
"e": 26426,
"s": 26250,
"text": null
},
{
"code": null,
"e": 26435,
"s": 26426,
"text": "Output :"
},
{
"code": null,
"e": 26509,
"s": 26435,
"text": "Example 3 : Absolute numeric values in a Series with a Timedelta element."
},
{
"code": "# import the libraryimport pandas as pd # create the Seriess = pd.Series([pd.Timedelta('2 days')])print(s) # fetching the absolute valuesprint(\"\\nThe absolute values are :\")print(s.abs())",
"e": 26699,
"s": 26509,
"text": null
},
{
"code": null,
"e": 26708,
"s": 26699,
"text": "Output :"
},
{
"code": null,
"e": 26774,
"s": 26708,
"text": "Example 4 : Fetching the absolute values from a DataFrame column."
},
{
"code": "# import the libraryimport pandas as pd # create the DataFramedf = pd.DataFrame({'p' : [2, 3, 4, 5], 'q' : [10, 20, 30, 40], 'r' : [200, 60, -40, -60]})display(df) # fetching the absolute valuesprint(\"\\nThe absolute values are :\")display(df.r.abs())",
"e": 27062,
"s": 26774,
"text": null
},
{
"code": null,
"e": 27071,
"s": 27062,
"text": "Output :"
},
{
"code": null,
"e": 27094,
"s": 27071,
"text": "Python Pandas-exercise"
},
{
"code": null,
"e": 27115,
"s": 27094,
"text": "Python pandas-series"
},
{
"code": null,
"e": 27129,
"s": 27115,
"text": "Python-pandas"
},
{
"code": null,
"e": 27136,
"s": 27129,
"text": "Python"
},
{
"code": null,
"e": 27234,
"s": 27136,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 27266,
"s": 27234,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 27308,
"s": 27266,
"text": "How To Convert Python Dictionary To JSON?"
},
{
"code": null,
"e": 27350,
"s": 27308,
"text": "Check if element exists in list in Python"
},
{
"code": null,
"e": 27406,
"s": 27350,
"text": "How to drop one or multiple columns in Pandas Dataframe"
},
{
"code": null,
"e": 27433,
"s": 27406,
"text": "Python Classes and Objects"
},
{
"code": null,
"e": 27464,
"s": 27433,
"text": "Python | os.path.join() method"
},
{
"code": null,
"e": 27493,
"s": 27464,
"text": "Create a directory in Python"
},
{
"code": null,
"e": 27532,
"s": 27493,
"text": "Python | Get unique values from a list"
},
{
"code": null,
"e": 27568,
"s": 27532,
"text": "Python | Pandas dataframe.groupby()"
}
] |
Concatenate two columns in MySQL? | To concatenate two columns, use CONCAT() function in MySQL. The syntax is as follows −
select CONCAT(yourColumnName1, ' ',yourColumnName2) as anyVariableName from yourTableName;
To understand the above concept, let us create a table. The query to create a table is as follows −
mysql> create table concatenateTwoColumnsDemo
−> (
−> StudentId int,
−> StudentName varchar(200),
−> StudentAge int
−> );
Query OK, 0 rows affected (1.06 sec)
Now you can insert some records in the table. The query to insert records is as follows −
mysql> insert into concatenateTwoColumnsDemo values(1,'Sam',21);
Query OK, 1 row affected (0.18 sec)
mysql> insert into concatenateTwoColumnsDemo values(2,'David',24);
Query OK, 1 row affected (0.17 sec)
mysql> insert into concatenateTwoColumnsDemo values(3,'Carol',22);
Query OK, 1 row affected (0.13 sec)
mysql> insert into concatenateTwoColumnsDemo values(4,'Johnson',19);
Query OK, 1 row affected (0.17 sec)
Display all records from the table with the help of select statement. The query is as follows −
mysql> select *from concatenateTwoColumnsDemo;
The following is the output −
+-----------+-------------+------------+
| StudentId | StudentName | StudentAge |
+-----------+-------------+------------+
| 1 | Sam | 21 |
| 2 | David | 24 |
| 3 | Carol | 22 |
| 4 | Johnson | 19 |
+-----------+-------------+------------+
4 rows in set (0.00 sec)
Implement the CONCAT() function to concatenate two columns. Here, we are concatenating columns StudentName and StudentAge. The query is as follows −
mysql> select CONCAT(StudentName, ' ',StudentAge) as NameAndAgeColumn from concatenateTwoColumnsDemo;
The following is the output displaying the concatenated columns −
+------------------+
| NameAndAgeColumn |
+------------------+
| Sam 21 |
| David 24 |
| Carol 22 |
| Johnson 19 |
+------------------+
4 rows in set (0.00 sec) | [
{
"code": null,
"e": 1149,
"s": 1062,
"text": "To concatenate two columns, use CONCAT() function in MySQL. The syntax is as follows −"
},
{
"code": null,
"e": 1240,
"s": 1149,
"text": "select CONCAT(yourColumnName1, ' ',yourColumnName2) as anyVariableName from yourTableName;"
},
{
"code": null,
"e": 1340,
"s": 1240,
"text": "To understand the above concept, let us create a table. The query to create a table is as follows −"
},
{
"code": null,
"e": 1514,
"s": 1340,
"text": "mysql> create table concatenateTwoColumnsDemo\n −> (\n −> StudentId int,\n −> StudentName varchar(200),\n −> StudentAge int\n −> );\nQuery OK, 0 rows affected (1.06 sec)"
},
{
"code": null,
"e": 1604,
"s": 1514,
"text": "Now you can insert some records in the table. The query to insert records is as follows −"
},
{
"code": null,
"e": 2019,
"s": 1604,
"text": "mysql> insert into concatenateTwoColumnsDemo values(1,'Sam',21);\nQuery OK, 1 row affected (0.18 sec)\n\nmysql> insert into concatenateTwoColumnsDemo values(2,'David',24);\nQuery OK, 1 row affected (0.17 sec)\n\nmysql> insert into concatenateTwoColumnsDemo values(3,'Carol',22);\nQuery OK, 1 row affected (0.13 sec)\n\nmysql> insert into concatenateTwoColumnsDemo values(4,'Johnson',19);\nQuery OK, 1 row affected (0.17 sec)"
},
{
"code": null,
"e": 2115,
"s": 2019,
"text": "Display all records from the table with the help of select statement. The query is as follows −"
},
{
"code": null,
"e": 2162,
"s": 2115,
"text": "mysql> select *from concatenateTwoColumnsDemo;"
},
{
"code": null,
"e": 2192,
"s": 2162,
"text": "The following is the output −"
},
{
"code": null,
"e": 2545,
"s": 2192,
"text": "+-----------+-------------+------------+\n| StudentId | StudentName | StudentAge |\n+-----------+-------------+------------+\n| 1 | Sam | 21 |\n| 2 | David | 24 |\n| 3 | Carol | 22 |\n| 4 | Johnson | 19 |\n+-----------+-------------+------------+\n4 rows in set (0.00 sec)"
},
{
"code": null,
"e": 2694,
"s": 2545,
"text": "Implement the CONCAT() function to concatenate two columns. Here, we are concatenating columns StudentName and StudentAge. The query is as follows −"
},
{
"code": null,
"e": 2796,
"s": 2694,
"text": "mysql> select CONCAT(StudentName, ' ',StudentAge) as NameAndAgeColumn from concatenateTwoColumnsDemo;"
},
{
"code": null,
"e": 2862,
"s": 2796,
"text": "The following is the output displaying the concatenated columns −"
},
{
"code": null,
"e": 3055,
"s": 2862,
"text": "+------------------+\n| NameAndAgeColumn |\n+------------------+\n| Sam 21 |\n| David 24 |\n| Carol 22 |\n| Johnson 19 |\n+------------------+\n4 rows in set (0.00 sec)"
}
] |
C++ Program to Implement AVL Tree | AVL tree is a self-balancing Binary Search Tree where the difference between heights of left and right subtrees cannot be more than one for all nodes.
Tree rotation is an operation that changes the structure without interfering with the order of the elements on an AVL tree. It moves one node up in the tree and one node down. It is used to change the shape of the tree, and to decrease its height by moving smaller subtrees down and larger subtrees up, resulting in improved performance of many tree operations. The direction of a rotation depends on the side which the tree nodes are shifted upon whilst others say that it depends on which child takes the root’s place. This is a C++ Program to Implement AVL Tree.
Function Descriptions:
height(avl *) : It calculate the height of the given AVL tree.
difference(avl *): It calculate the difference between height of sub trees of given tree
avl *rr_rotat(avl *): A right-right rotation is a combination of right rotation followed by right rotation.
avl *ll_rotat(avl *): A left-left rotation is a combination of left rotation followed by left rotation.
avl *lr_rotat(avl*): A left-right rotation is a combination of left rotation followed by right rotation.
avl *rl_rotat(avl *): It is a combination of right rotation followed by left rotation.
avl * balance(avl *): It perform balance operation to the tree by getting balance factor
avl * insert(avl*, int): It perform insert operation. Insert values in the tree using this function.
show(avl*, int): It display the values of the tree.
inorder(avl *): Traverses a tree in an in-order manner.
preorder(avl *): Traverses a tree in a pre-order manner.
postorder(avl*): Traverses a tree in a post-order manner
#include<iostream>
#include<cstdio>
#include<sstream>
#include<algorithm>
#define pow2(n) (1 << (n))
using namespace std;
struct avl {
int d;
struct avl *l;
struct avl *r;
}*r;
class avl_tree {
public:
int height(avl *);
int difference(avl *);
avl *rr_rotat(avl *);
avl *ll_rotat(avl *);
avl *lr_rotat(avl*);
avl *rl_rotat(avl *);
avl * balance(avl *);
avl * insert(avl*, int);
void show(avl*, int);
void inorder(avl *);
void preorder(avl *);
void postorder(avl*);
avl_tree() {
r = NULL;
}
};
int avl_tree::height(avl *t) {
int h = 0;
if (t != NULL) {
int l_height = height(t->l);
int r_height = height(t->r);
int max_height = max(l_height, r_height);
h = max_height + 1;
}
return h;
}
int avl_tree::difference(avl *t) {
int l_height = height(t->l);
int r_height = height(t->r);
int b_factor = l_height - r_height;
return b_factor;
}
avl *avl_tree::rr_rotat(avl *parent) {
avl *t;
t = parent->r;
parent->r = t->l;
t->l = parent;
cout<<"Right-Right Rotation";
return t;
}
avl *avl_tree::ll_rotat(avl *parent) {
avl *t;
t = parent->l;
parent->l = t->r;
t->r = parent;
cout<<"Left-Left Rotation";
return t;
}
avl *avl_tree::lr_rotat(avl *parent) {
avl *t;
t = parent->l;
parent->l = rr_rotat(t);
cout<<"Left-Right Rotation";
return ll_rotat(parent);
}
avl *avl_tree::rl_rotat(avl *parent) {
avl *t;
t = parent->r;
parent->r = ll_rotat(t);
cout<<"Right-Left Rotation";
return rr_rotat(parent);
}
avl *avl_tree::balance(avl *t) {
int bal_factor = difference(t);
if (bal_factor > 1) {
if (difference(t->l) > 0)
t = ll_rotat(t);
else
t = lr_rotat(t);
} else if (bal_factor < -1) {
if (difference(t->r) > 0)
t = rl_rotat(t);
else
t = rr_rotat(t);
}
return t;
}
avl *avl_tree::insert(avl *r, int v) {
if (r == NULL) {
r = new avl;
r->d = v;
r->l = NULL;
r->r = NULL;
return r;
} else if (v< r->d) {
r->l = insert(r->l, v);
r = balance(r);
} else if (v >= r->d) {
r->r = insert(r->r, v);
r = balance(r);
} return r;
}
void avl_tree::show(avl *p, int l) {
int i;
if (p != NULL) {
show(p->r, l+ 1);
cout<<" ";
if (p == r)
cout << "Root -> ";
for (i = 0; i < l&& p != r; i++)
cout << " ";
cout << p->d;
show(p->l, l + 1);
}
}
void avl_tree::inorder(avl *t) {
if (t == NULL)
return;
inorder(t->l);
cout << t->d << " ";
inorder(t->r);
}
void avl_tree::preorder(avl *t) {
if (t == NULL)
return;
cout << t->d << " ";
preorder(t->l);
preorder(t->r);
}
void avl_tree::postorder(avl *t) {
if (t == NULL)
return;
postorder(t ->l);
postorder(t ->r);
cout << t->d << " ";
}
int main() {
int c, i;
avl_tree avl;
while (1) {
cout << "1.Insert Element into the tree" << endl;
cout << "2.show Balanced AVL Tree" << endl;
cout << "3.InOrder traversal" << endl;
cout << "4.PreOrder traversal" << endl;
cout << "5.PostOrder traversal" << endl;
cout << "6.Exit" << endl;
cout << "Enter your Choice: ";
cin >> c;
switch (c) {
case 1:
cout << "Enter value to be inserted: ";
cin >> i;
r = avl.insert(r, i);
break;
case 2:
if (r == NULL) {
cout << "Tree is Empty" << endl;
continue;
}
cout << "Balanced AVL Tree:" << endl;
avl.show(r, 1);
cout<<endl;
break;
case 3:
cout << "Inorder Traversal:" << endl;
avl.inorder(r);
cout << endl;
break;
case 4:
cout << "Preorder Traversal:" << endl;
avl.preorder(r);
cout << endl;
break;
case 5:
cout << "Postorder Traversal:" << endl;
avl.postorder(r);
cout << endl;
break;
case 6:
exit(1);
break;
default:
cout << "Wrong Choice" << endl;
}
}
return 0;
}
1.Insert Element into the tree
2.show Balanced AVL Tree
3.InOrder traversal
4.PreOrder traversal
5.PostOrder traversal
6.Exit
Enter your Choice: 1
Enter value to be inserted: 13
1.Insert Element into the tree
2.show Balanced AVL Tree
3.InOrder traversal
4.PreOrder traversal
5.PostOrder traversal
6.Exit
Enter your Choice: 1
Enter value to be inserted: 10
1.Insert Element into the tree
2.show Balanced AVL Tree
3.InOrder traversal
4.PreOrder traversal
5.PostOrder traversal
6.Exit
Enter your Choice: 1
Enter value to be inserted: 15
1.Insert Element into the tree
2.show Balanced AVL Tree
3.InOrder traversal
4.PreOrder traversal
5.PostOrder traversal
6.Exit
Enter your Choice: 1
Enter value to be inserted: 5
1.Insert Element into the tree
2.show Balanced AVL Tree
3.InOrder traversal
4.PreOrder traversal
5.PostOrder traversal
6.Exit
Enter your Choice: 1
Enter value to be inserted: 11
1.Insert Element into the tree
2.show Balanced AVL Tree
3.InOrder traversal
4.PreOrder traversal
5.PostOrder traversal
6.Exit
Enter your Choice: 1
Enter value to be inserted: 4
Left-Left Rotation1.Insert Element into the tree
2.show Balanced AVL Tree
3.InOrder traversal
4.PreOrder traversal
5.PostOrder traversal
6.Exit
Enter your Choice: 1
Enter value to be inserted: 8
1.Insert Element into the tree
2.show Balanced AVL Tree
3.InOrder traversal
4.PreOrder traversal
5.PostOrder traversal
6.Exit
Enter your Choice: 1
Enter value to be inserted: 16
1.Insert Element into the tree
2.show Balanced AVL Tree
3.InOrder traversal
4.PreOrder traversal
5.PostOrder traversal
6.Exit
Enter your Choice: 3
Inorder Traversal:
4 5 8 10 11 13 15 16
1.Insert Element into the tree
2.show Balanced AVL Tree
3.InOrder traversal
4.PreOrder traversal
5.PostOrder traversal
6.Exit
Enter your Choice: 4
Preorder Traversal:
10 5 4 8 13 11 15 16
1.Insert Element into the tree
2.show Balanced AVL Tree
3.InOrder traversal
4.PreOrder traversal
5.PostOrder traversal
6.Exit
Enter your Choice: 5
Postorder Traversal:
4 8 5 11 16 15 13 10
1.Insert Element into the tree
2.show Balanced AVL Tree
3.InOrder traversal
4.PreOrder traversal
5.PostOrder traversal
6.Exit
Enter your Choice: 1
Enter value to be inserted: 14
1.Insert Element into the tree
2.show Balanced AVL Tree
3.InOrder traversal
4.PreOrder traversal
5.PostOrder traversal
6.Exit
Enter your Choice: 1
Enter value to be inserted: 3
1.Insert Element into the tree
2.show Balanced AVL Tree
3.InOrder traversal
4.PreOrder traversal
5.PostOrder traversal
6.Exit
Enter your Choice: 1
Enter value to be inserted: 7
1.Insert Element into the tree
2.show Balanced AVL Tree
3.InOrder traversal
4.PreOrder traversal
5.PostOrder traversal
6.Exit
Enter your Choice: 1
Enter value to be inserted: 9
1.Insert Element into the tree
2.show Balanced AVL Tree
3.InOrder traversal
4.PreOrder traversal
5.PostOrder traversal
6.Exit
Enter your Choice: 1
Enter value to be inserted: 52
Right-Right Rotation
1.Insert Element into the tree
2.show Balanced AVL Tree
3.InOrder traversal
4.PreOrder traversal
5.PostOrder traversal
6.Exit
Enter your Choice: 6 | [
{
"code": null,
"e": 1213,
"s": 1062,
"text": "AVL tree is a self-balancing Binary Search Tree where the difference between heights of left and right subtrees cannot be more than one for all nodes."
},
{
"code": null,
"e": 1779,
"s": 1213,
"text": "Tree rotation is an operation that changes the structure without interfering with the order of the elements on an AVL tree. It moves one node up in the tree and one node down. It is used to change the shape of the tree, and to decrease its height by moving smaller subtrees down and larger subtrees up, resulting in improved performance of many tree operations. The direction of a rotation depends on the side which the tree nodes are shifted upon whilst others say that it depends on which child takes the root’s place. This is a C++ Program to Implement AVL Tree."
},
{
"code": null,
"e": 1802,
"s": 1779,
"text": "Function Descriptions:"
},
{
"code": null,
"e": 1865,
"s": 1802,
"text": "height(avl *) : It calculate the height of the given AVL tree."
},
{
"code": null,
"e": 1954,
"s": 1865,
"text": "difference(avl *): It calculate the difference between height of sub trees of given tree"
},
{
"code": null,
"e": 2062,
"s": 1954,
"text": "avl *rr_rotat(avl *): A right-right rotation is a combination of right rotation followed by right rotation."
},
{
"code": null,
"e": 2166,
"s": 2062,
"text": "avl *ll_rotat(avl *): A left-left rotation is a combination of left rotation followed by left rotation."
},
{
"code": null,
"e": 2271,
"s": 2166,
"text": "avl *lr_rotat(avl*): A left-right rotation is a combination of left rotation followed by right rotation."
},
{
"code": null,
"e": 2358,
"s": 2271,
"text": "avl *rl_rotat(avl *): It is a combination of right rotation followed by left rotation."
},
{
"code": null,
"e": 2447,
"s": 2358,
"text": "avl * balance(avl *): It perform balance operation to the tree by getting balance factor"
},
{
"code": null,
"e": 2549,
"s": 2447,
"text": "avl * insert(avl*, int): It perform insert operation. Insert values in the tree using this function. "
},
{
"code": null,
"e": 2602,
"s": 2549,
"text": "show(avl*, int): It display the values of the tree. "
},
{
"code": null,
"e": 2659,
"s": 2602,
"text": "inorder(avl *): Traverses a tree in an in-order manner. "
},
{
"code": null,
"e": 2717,
"s": 2659,
"text": "preorder(avl *): Traverses a tree in a pre-order manner. "
},
{
"code": null,
"e": 2774,
"s": 2717,
"text": "postorder(avl*): Traverses a tree in a post-order manner"
},
{
"code": null,
"e": 7094,
"s": 2774,
"text": "#include<iostream>\n#include<cstdio>\n#include<sstream>\n#include<algorithm>\n#define pow2(n) (1 << (n))\nusing namespace std;\nstruct avl {\n int d;\n struct avl *l;\n struct avl *r;\n}*r;\nclass avl_tree {\n public:\n int height(avl *);\n int difference(avl *);\n avl *rr_rotat(avl *);\n avl *ll_rotat(avl *);\n avl *lr_rotat(avl*);\n avl *rl_rotat(avl *);\n avl * balance(avl *);\n avl * insert(avl*, int);\n void show(avl*, int);\n void inorder(avl *);\n void preorder(avl *);\n void postorder(avl*);\n avl_tree() {\n r = NULL;\n }\n};\nint avl_tree::height(avl *t) {\n int h = 0;\n if (t != NULL) {\n int l_height = height(t->l);\n int r_height = height(t->r);\n int max_height = max(l_height, r_height);\n h = max_height + 1;\n }\n return h;\n}\nint avl_tree::difference(avl *t) {\n int l_height = height(t->l);\n int r_height = height(t->r);\n int b_factor = l_height - r_height;\n return b_factor;\n}\navl *avl_tree::rr_rotat(avl *parent) {\n avl *t;\n t = parent->r;\n parent->r = t->l;\n t->l = parent;\n cout<<\"Right-Right Rotation\";\n return t;\n}\navl *avl_tree::ll_rotat(avl *parent) {\n avl *t;\n t = parent->l;\n parent->l = t->r;\n t->r = parent;\n cout<<\"Left-Left Rotation\";\n return t;\n}\navl *avl_tree::lr_rotat(avl *parent) {\n avl *t;\n t = parent->l;\n parent->l = rr_rotat(t);\n cout<<\"Left-Right Rotation\";\n return ll_rotat(parent);\n}\navl *avl_tree::rl_rotat(avl *parent) {\n avl *t;\n t = parent->r;\n parent->r = ll_rotat(t);\n cout<<\"Right-Left Rotation\";\n return rr_rotat(parent);\n}\navl *avl_tree::balance(avl *t) {\n int bal_factor = difference(t);\n if (bal_factor > 1) {\n if (difference(t->l) > 0)\n t = ll_rotat(t);\n else\n t = lr_rotat(t);\n } else if (bal_factor < -1) {\n if (difference(t->r) > 0)\n t = rl_rotat(t);\n else\n t = rr_rotat(t);\n }\n return t;\n}\navl *avl_tree::insert(avl *r, int v) {\n if (r == NULL) {\n r = new avl;\n r->d = v;\n r->l = NULL;\n r->r = NULL;\n return r;\n } else if (v< r->d) {\n r->l = insert(r->l, v);\n r = balance(r);\n } else if (v >= r->d) {\n r->r = insert(r->r, v);\n r = balance(r);\n } return r;\n}\nvoid avl_tree::show(avl *p, int l) {\n int i;\n if (p != NULL) {\n show(p->r, l+ 1);\n cout<<\" \";\n if (p == r)\n cout << \"Root -> \";\n for (i = 0; i < l&& p != r; i++)\n cout << \" \";\n cout << p->d;\n show(p->l, l + 1);\n }\n}\nvoid avl_tree::inorder(avl *t) {\n if (t == NULL)\n return;\n inorder(t->l);\n cout << t->d << \" \";\n inorder(t->r);\n}\nvoid avl_tree::preorder(avl *t) {\n if (t == NULL)\n return;\n cout << t->d << \" \";\n preorder(t->l);\n preorder(t->r);\n}\nvoid avl_tree::postorder(avl *t) {\n if (t == NULL)\n return;\n postorder(t ->l);\n postorder(t ->r);\n cout << t->d << \" \";\n}\nint main() {\n int c, i;\n avl_tree avl;\n while (1) {\n cout << \"1.Insert Element into the tree\" << endl;\n cout << \"2.show Balanced AVL Tree\" << endl;\n cout << \"3.InOrder traversal\" << endl;\n cout << \"4.PreOrder traversal\" << endl;\n cout << \"5.PostOrder traversal\" << endl;\n cout << \"6.Exit\" << endl;\n cout << \"Enter your Choice: \";\n cin >> c;\n switch (c) {\n case 1:\n cout << \"Enter value to be inserted: \";\n cin >> i;\n r = avl.insert(r, i);\n break;\n case 2:\n if (r == NULL) {\n cout << \"Tree is Empty\" << endl;\n continue;\n }\n cout << \"Balanced AVL Tree:\" << endl;\n avl.show(r, 1);\n cout<<endl;\n break;\n case 3:\n cout << \"Inorder Traversal:\" << endl;\n avl.inorder(r);\n cout << endl;\n break;\n case 4:\n cout << \"Preorder Traversal:\" << endl;\n avl.preorder(r);\n cout << endl;\n break;\n case 5:\n cout << \"Postorder Traversal:\" << endl;\n avl.postorder(r);\n cout << endl;\n break;\n case 6:\n exit(1);\n break;\n default:\n cout << \"Wrong Choice\" << endl;\n }\n }\n return 0;\n}"
},
{
"code": null,
"e": 10152,
"s": 7094,
"text": "1.Insert Element into the tree\n2.show Balanced AVL Tree\n3.InOrder traversal\n4.PreOrder traversal\n5.PostOrder traversal\n6.Exit\nEnter your Choice: 1\nEnter value to be inserted: 13\n1.Insert Element into the tree\n2.show Balanced AVL Tree\n3.InOrder traversal\n4.PreOrder traversal\n5.PostOrder traversal\n6.Exit\nEnter your Choice: 1\nEnter value to be inserted: 10\n1.Insert Element into the tree\n2.show Balanced AVL Tree\n3.InOrder traversal\n4.PreOrder traversal\n5.PostOrder traversal\n6.Exit\nEnter your Choice: 1\nEnter value to be inserted: 15\n1.Insert Element into the tree\n2.show Balanced AVL Tree\n3.InOrder traversal\n4.PreOrder traversal\n5.PostOrder traversal\n6.Exit\nEnter your Choice: 1\nEnter value to be inserted: 5\n1.Insert Element into the tree\n2.show Balanced AVL Tree\n3.InOrder traversal\n4.PreOrder traversal\n5.PostOrder traversal\n6.Exit\nEnter your Choice: 1\nEnter value to be inserted: 11\n1.Insert Element into the tree\n2.show Balanced AVL Tree\n3.InOrder traversal\n4.PreOrder traversal\n5.PostOrder traversal\n6.Exit\nEnter your Choice: 1\nEnter value to be inserted: 4\nLeft-Left Rotation1.Insert Element into the tree\n2.show Balanced AVL Tree\n3.InOrder traversal\n4.PreOrder traversal\n5.PostOrder traversal\n6.Exit\nEnter your Choice: 1\nEnter value to be inserted: 8\n1.Insert Element into the tree\n2.show Balanced AVL Tree\n3.InOrder traversal\n4.PreOrder traversal\n5.PostOrder traversal\n6.Exit\nEnter your Choice: 1\nEnter value to be inserted: 16\n1.Insert Element into the tree\n2.show Balanced AVL Tree\n3.InOrder traversal\n4.PreOrder traversal\n5.PostOrder traversal\n6.Exit\nEnter your Choice: 3\nInorder Traversal:\n4 5 8 10 11 13 15 16\n1.Insert Element into the tree\n2.show Balanced AVL Tree\n3.InOrder traversal\n4.PreOrder traversal\n5.PostOrder traversal\n6.Exit\nEnter your Choice: 4\nPreorder Traversal:\n10 5 4 8 13 11 15 16\n1.Insert Element into the tree\n2.show Balanced AVL Tree\n3.InOrder traversal\n4.PreOrder traversal\n5.PostOrder traversal\n6.Exit\nEnter your Choice: 5\nPostorder Traversal:\n4 8 5 11 16 15 13 10\n1.Insert Element into the tree\n2.show Balanced AVL Tree\n3.InOrder traversal\n4.PreOrder traversal\n5.PostOrder traversal\n6.Exit\nEnter your Choice: 1\nEnter value to be inserted: 14\n1.Insert Element into the tree\n2.show Balanced AVL Tree\n3.InOrder traversal\n4.PreOrder traversal\n5.PostOrder traversal\n6.Exit\nEnter your Choice: 1\nEnter value to be inserted: 3\n1.Insert Element into the tree\n2.show Balanced AVL Tree\n3.InOrder traversal\n4.PreOrder traversal\n5.PostOrder traversal\n6.Exit\nEnter your Choice: 1\nEnter value to be inserted: 7\n1.Insert Element into the tree\n2.show Balanced AVL Tree\n3.InOrder traversal\n4.PreOrder traversal\n5.PostOrder traversal\n6.Exit\nEnter your Choice: 1\nEnter value to be inserted: 9\n1.Insert Element into the tree\n2.show Balanced AVL Tree\n3.InOrder traversal\n4.PreOrder traversal\n5.PostOrder traversal\n6.Exit\nEnter your Choice: 1\nEnter value to be inserted: 52\nRight-Right Rotation\n1.Insert Element into the tree\n2.show Balanced AVL Tree\n3.InOrder traversal\n4.PreOrder traversal\n5.PostOrder traversal\n6.Exit\nEnter your Choice: 6"
}
] |
numpy.asarray() in Python - GeeksforGeeks | 12 Nov, 2021
numpy.asarray()function is used when we want to convert input to an array. Input can be lists, lists of tuples, tuples, tuples of tuples, tuples of lists and arrays.
Syntax : numpy.asarray(arr, dtype=None, order=None)
Parameters :arr : [array_like] Input data, in any form that can be converted to an array. This includes lists, lists of tuples, tuples, tuples of tuples, tuples of lists and ndarrays.dtype : [data-type, optional] By default, the data-type is inferred from the input data.order : Whether to use row-major (C-style) or column-major (Fortran-style) memory representation. Defaults to ‘C’.
Return : [ndarray] Array interpretation of arr. No copy is performed if the input is already ndarray with matching dtype and order. If arr is a subclass of ndarray, a base class ndarray is returned.
Code #1 : List to array
# Python program explaining# numpy.asarray() function import numpy as geekmy_list = [1, 3, 5, 7, 9] print ("Input list : ", my_list) out_arr = geek.asarray(my_list)print ("output array from input list : ", out_arr)
Output :
Input list : [1, 3, 5, 7, 9]
output array from input list : [1 3 5 7 9]
Code #2 : Tuple to array
# Python program explaining# numpy.asarray() function import numpy as geek my_tuple = ([1, 3, 9], [8, 2, 6]) print ("Input tuple : ", my_tuple) out_arr = geek.asarray(my_tuple) print ("output array from input tuple : ", out_arr)
Output :
Input tuple : ([1, 3, 9], [8, 2, 6])
output array from input tuple : [[1 3 9]
[8 2 6]]
gulshankumarar231
Pyhton numpy-arrayCreation
Python-numpy
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Enumerate() in Python
How to Install PIP on Windows ?
Different ways to create Pandas Dataframe
Python String | replace()
Create a Pandas DataFrame from Lists
sum() function in Python
*args and **kwargs in Python
How to drop one or multiple columns in Pandas Dataframe
Print lists in Python (4 Different Ways)
How To Convert Python Dictionary To JSON? | [
{
"code": null,
"e": 24236,
"s": 24208,
"text": "\n12 Nov, 2021"
},
{
"code": null,
"e": 24402,
"s": 24236,
"text": "numpy.asarray()function is used when we want to convert input to an array. Input can be lists, lists of tuples, tuples, tuples of tuples, tuples of lists and arrays."
},
{
"code": null,
"e": 24454,
"s": 24402,
"text": "Syntax : numpy.asarray(arr, dtype=None, order=None)"
},
{
"code": null,
"e": 24840,
"s": 24454,
"text": "Parameters :arr : [array_like] Input data, in any form that can be converted to an array. This includes lists, lists of tuples, tuples, tuples of tuples, tuples of lists and ndarrays.dtype : [data-type, optional] By default, the data-type is inferred from the input data.order : Whether to use row-major (C-style) or column-major (Fortran-style) memory representation. Defaults to ‘C’."
},
{
"code": null,
"e": 25039,
"s": 24840,
"text": "Return : [ndarray] Array interpretation of arr. No copy is performed if the input is already ndarray with matching dtype and order. If arr is a subclass of ndarray, a base class ndarray is returned."
},
{
"code": null,
"e": 25063,
"s": 25039,
"text": "Code #1 : List to array"
},
{
"code": "# Python program explaining# numpy.asarray() function import numpy as geekmy_list = [1, 3, 5, 7, 9] print (\"Input list : \", my_list) out_arr = geek.asarray(my_list)print (\"output array from input list : \", out_arr) ",
"e": 25288,
"s": 25063,
"text": null
},
{
"code": null,
"e": 25297,
"s": 25288,
"text": "Output :"
},
{
"code": null,
"e": 25373,
"s": 25297,
"text": "Input list : [1, 3, 5, 7, 9]\noutput array from input list : [1 3 5 7 9]\n"
},
{
"code": null,
"e": 25399,
"s": 25373,
"text": " Code #2 : Tuple to array"
},
{
"code": "# Python program explaining# numpy.asarray() function import numpy as geek my_tuple = ([1, 3, 9], [8, 2, 6]) print (\"Input tuple : \", my_tuple) out_arr = geek.asarray(my_tuple) print (\"output array from input tuple : \", out_arr) ",
"e": 25637,
"s": 25399,
"text": null
},
{
"code": null,
"e": 25646,
"s": 25637,
"text": "Output :"
},
{
"code": null,
"e": 25738,
"s": 25646,
"text": "Input tuple : ([1, 3, 9], [8, 2, 6])\noutput array from input tuple : [[1 3 9]\n [8 2 6]]\n"
},
{
"code": null,
"e": 25756,
"s": 25738,
"text": "gulshankumarar231"
},
{
"code": null,
"e": 25783,
"s": 25756,
"text": "Pyhton numpy-arrayCreation"
},
{
"code": null,
"e": 25796,
"s": 25783,
"text": "Python-numpy"
},
{
"code": null,
"e": 25803,
"s": 25796,
"text": "Python"
},
{
"code": null,
"e": 25901,
"s": 25803,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 25923,
"s": 25901,
"text": "Enumerate() in Python"
},
{
"code": null,
"e": 25955,
"s": 25923,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 25997,
"s": 25955,
"text": "Different ways to create Pandas Dataframe"
},
{
"code": null,
"e": 26023,
"s": 25997,
"text": "Python String | replace()"
},
{
"code": null,
"e": 26060,
"s": 26023,
"text": "Create a Pandas DataFrame from Lists"
},
{
"code": null,
"e": 26085,
"s": 26060,
"text": "sum() function in Python"
},
{
"code": null,
"e": 26114,
"s": 26085,
"text": "*args and **kwargs in Python"
},
{
"code": null,
"e": 26170,
"s": 26114,
"text": "How to drop one or multiple columns in Pandas Dataframe"
},
{
"code": null,
"e": 26211,
"s": 26170,
"text": "Print lists in Python (4 Different Ways)"
}
] |
How to convert Java object to JSON using Jackson library? | JSON or JavaScript Object Notation is a lightweight text-based open standard designed for human-readable data interchange. Conventions used by JSON are known to programmers, which include C, C++, Java, Python, Perl, etc.
There are several Java libraries available to handle JSON objects. Jackson is a simple java based library to serialize java objects to JSON and vice versa.
The ObjectMapper class of the Jackson API in Java provides methods to convert a Java object to JSON object and vice versa.
The writeValueAsString() method of this class accepts a JSON object as a parameter and returns its respective JSON String
Therefore, to convert a Java object to a JSON String using Jackson library −
Add the following maven dependency to your pom.xml
Add the following maven dependency to your pom.xml
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.10.0.pr2</version>
</dependency>
Create a javabean/POJO object with private variables and setter/getter methods.
Create a javabean/POJO object with private variables and setter/getter methods.
Create another class (make sure that the POJO class is available to this).
Create another class (make sure that the POJO class is available to this).
In it, create an object of the POJO class, set required values to it using the setter methods.
In it, create an object of the POJO class, set required values to it using the setter methods.
Instantiate the ObjectMapper class.
Instantiate the ObjectMapper class.
Invoke the writeValueAsString() method by passing the above created POJO object.
Invoke the writeValueAsString() method by passing the above created POJO object.
Retrieve and print the obtained JSON.
Retrieve and print the obtained JSON.
import com.google.gson.Gson;
class Student {
private int id;
private String name;
private int age;
private long phone;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public long getPhone() {
return phone;
}
public void setPhone(long phone) {
this.phone = phone;
}
}
public class JacksionExample {
public static void main(String args[]) throws Exception {
Student std = new Student();
std.setId(001);
std.setName("Krishna");
std.setAge(30);
std.setPhone(9848022338L);
//Creating the ObjectMapper object
ObjectMapper mapper = new ObjectMapper();
//Converting the Object to JSONString
String jsonString = mapper.writeValueAsString(std);
System.out.println(jsonString);
}
}
{"id":1,"name":"Krishna","age":30,"phone":9848022338} | [
{
"code": null,
"e": 1283,
"s": 1062,
"text": "JSON or JavaScript Object Notation is a lightweight text-based open standard designed for human-readable data interchange. Conventions used by JSON are known to programmers, which include C, C++, Java, Python, Perl, etc."
},
{
"code": null,
"e": 1439,
"s": 1283,
"text": "There are several Java libraries available to handle JSON objects. Jackson is a simple java based library to serialize java objects to JSON and vice versa."
},
{
"code": null,
"e": 1562,
"s": 1439,
"text": "The ObjectMapper class of the Jackson API in Java provides methods to convert a Java object to JSON object and vice versa."
},
{
"code": null,
"e": 1684,
"s": 1562,
"text": "The writeValueAsString() method of this class accepts a JSON object as a parameter and returns its respective JSON String"
},
{
"code": null,
"e": 1761,
"s": 1684,
"text": "Therefore, to convert a Java object to a JSON String using Jackson library −"
},
{
"code": null,
"e": 1812,
"s": 1761,
"text": "Add the following maven dependency to your pom.xml"
},
{
"code": null,
"e": 1863,
"s": 1812,
"text": "Add the following maven dependency to your pom.xml"
},
{
"code": null,
"e": 2017,
"s": 1863,
"text": "<dependency>\n <groupId>com.fasterxml.jackson.core</groupId>\n <artifactId>jackson-databind</artifactId>\n <version>2.10.0.pr2</version>\n</dependency>"
},
{
"code": null,
"e": 2097,
"s": 2017,
"text": "Create a javabean/POJO object with private variables and setter/getter methods."
},
{
"code": null,
"e": 2177,
"s": 2097,
"text": "Create a javabean/POJO object with private variables and setter/getter methods."
},
{
"code": null,
"e": 2252,
"s": 2177,
"text": "Create another class (make sure that the POJO class is available to this)."
},
{
"code": null,
"e": 2327,
"s": 2252,
"text": "Create another class (make sure that the POJO class is available to this)."
},
{
"code": null,
"e": 2422,
"s": 2327,
"text": "In it, create an object of the POJO class, set required values to it using the setter methods."
},
{
"code": null,
"e": 2517,
"s": 2422,
"text": "In it, create an object of the POJO class, set required values to it using the setter methods."
},
{
"code": null,
"e": 2553,
"s": 2517,
"text": "Instantiate the ObjectMapper class."
},
{
"code": null,
"e": 2589,
"s": 2553,
"text": "Instantiate the ObjectMapper class."
},
{
"code": null,
"e": 2670,
"s": 2589,
"text": "Invoke the writeValueAsString() method by passing the above created POJO object."
},
{
"code": null,
"e": 2751,
"s": 2670,
"text": "Invoke the writeValueAsString() method by passing the above created POJO object."
},
{
"code": null,
"e": 2789,
"s": 2751,
"text": "Retrieve and print the obtained JSON."
},
{
"code": null,
"e": 2827,
"s": 2789,
"text": "Retrieve and print the obtained JSON."
},
{
"code": null,
"e": 3882,
"s": 2827,
"text": "import com.google.gson.Gson;\nclass Student {\n private int id;\n private String name;\n private int age;\n private long phone;\n public int getId() {\n return id;\n }\n public void setId(int id) {\n this.id = id;\n }\n public String getName() {\n return name;\n }\n public void setName(String name) {\n this.name = name;\n }\n public int getAge() {\n return age;\n }\n public void setAge(int age) {\n this.age = age;\n }\n public long getPhone() {\n return phone;\n }\n public void setPhone(long phone) {\n this.phone = phone;\n }\n}\npublic class JacksionExample {\n public static void main(String args[]) throws Exception {\n Student std = new Student();\n std.setId(001);\n std.setName(\"Krishna\");\n std.setAge(30);\n std.setPhone(9848022338L);\n //Creating the ObjectMapper object\n ObjectMapper mapper = new ObjectMapper();\n //Converting the Object to JSONString\n String jsonString = mapper.writeValueAsString(std);\n System.out.println(jsonString);\n }\n}"
},
{
"code": null,
"e": 3936,
"s": 3882,
"text": "{\"id\":1,\"name\":\"Krishna\",\"age\":30,\"phone\":9848022338}"
}
] |
Maximum subarray sum modulo m | 09 Mar, 2022
Given an array of n elements and an integer m. The task is to find the maximum value of the sum of its subarray modulo m i.e find the sum of each subarray mod m and print the maximum value of this modulo operation.Examples:
Input : arr[] = { 3, 3, 9, 9, 5 }
m = 7
Output : 6
All sub-arrays and their value:
{ 9 } => 9%7 = 2
{ 3 } => 3%7 = 3
{ 5 } => 5%7 = 5
{ 9, 5 } => 14%7 = 2
{ 9, 9 } => 18%7 = 4
{ 3, 9 } => 12%7 = 5
{ 3, 3 } => 6%7 = 6
{ 3, 9, 9 } => 21%7 = 0
{ 3, 3, 9 } => 15%7 = 1
{ 9, 9, 5 } => 23%7 = 2
{ 3, 3, 9, 9 } => 24%7 = 3
{ 3, 9, 9, 5 } => 26%7 = 5
{ 3, 3, 9, 9, 5 } => 29%7 = 1
Input : arr[] = {10, 7, 18}
m = 13
Output : 12
The subarray {7, 18} has maximum sub-array
sum modulo 13.
Method 1 (Brute Force): Use brute force to find all the subarrays of the given array and find sum of each subarray mod m and keep track of maximum.Method 2 (efficient approach): The idea is to compute prefix sum of array. We find maximum sum ending with every index and finally return overall maximum. To find maximum sum ending at an index, we need to find the starting point of maximum sum ending with i. Below steps explain how to find the starting point.
Let prefix sum for index i be prefixi, i.e.,
prefixi = (arr[0] + arr[1] + .... arr[i] ) % m
Let maximum sum ending with i be, maxSumi.
Let this sum begins with index j.
maxSumi = (prefixi - prefixj + m) % m
From above expression it is clear that the
value of maxSumi becomes maximum when
prefixj is greater than prefixi
and closest to prefixi
We mainly have two operations in above algorithm.
Store all prefixes.For current prefix, prefixi, find the smallest value greater than or equal to prefixi + 1.
Store all prefixes.
For current prefix, prefixi, find the smallest value greater than or equal to prefixi + 1.
For above operations, a self-balancing-binary-search-trees like AVL Tree, Red-Black Tree, etc are best suited. In below implementation we use set in STL which implements a self-balancing-binary-search-tree.Below is the implementation of this approach:
C++
Java
Python3
C#
Javascript
// C++ program to find sub-array having maximum// sum of elements modulo m.#include<bits/stdc++.h>using namespace std; // Return the maximum sum subarray mod m.int maxSubarray(int arr[], int n, int m){ int x, prefix = 0, maxim = 0; set<int> S; S.insert(0); // Traversing the array. for (int i = 0; i < n; i++) { // Finding prefix sum. prefix = (prefix + arr[i])%m; // Finding maximum of prefix sum. maxim = max(maxim, prefix); // Finding iterator pointing to the first // element that is not less than value // "prefix + 1", i.e., greater than or // equal to this value. auto it = S.lower_bound(prefix+1); if (it != S.end()) maxim = max(maxim, prefix - (*it) + m ); // Inserting prefix in the set. S.insert(prefix); } return maxim;} // Driver Programint main(){ int arr[] = { 3, 3, 9, 9, 5 }; int n = sizeof(arr)/sizeof(arr[0]); int m = 7; cout << maxSubarray(arr, n, m) << endl; return 0;}
// Java program to find sub-array// having maximum sum of elements modulo m.import java.util.*;class GFG{ // Return the maximum sum subarray mod m. static int maxSubarray(int[] arr, int n, int m) { int x = 0; int prefix = 0; int maxim = 0; Set<Integer> S = new HashSet<Integer>(); S.add(0); // Traversing the array. for (int i = 0; i < n; i++) { // Finding prefix sum. prefix = (prefix + arr[i]) % m; // Finding maximum of prefix sum. maxim = Math.max(maxim, prefix); // Finding iterator pointing to the first // element that is not less than value // "prefix + 1", i.e., greater than or // equal to this value. int it = 0; for (int j : S) { if (j >= prefix + 1) it = j; } if (it != 0) { maxim = Math.max(maxim, prefix - it + m); } // adding prefix in the set. S.add(prefix); } return maxim; } // Driver code public static void main(String[] args) { // Driver Code int[] arr = new int[] { 3, 3, 9, 9, 5 }; int n = 5; int m = 7; System.out.print(maxSubarray(arr, n, m)); }} // This code is contributed by pratham76.
# Python3 program to find sub-array# having maximum sum of elements modulo m. # Return the maximum sum subarray mod m.def maxSubarray(arr, n, m): x = 0 prefix = 0 maxim = 0 S = set() S.add(0) # Traversing the array. for i in range(n): # Finding prefix sum. prefix = (prefix + arr[i]) % m # Finding maximum of prefix sum. maxim = max(maxim, prefix) # Finding iterator pointing to the first # element that is not less than value # "prefix + 1", i.e., greater than or # equal to this value. it = 0 for i in S: if i >= prefix + 1: it = i if (it != 0) : maxim = max(maxim, prefix - it + m ) # adding prefix in the set. S.add(prefix) return maxim # Driver Codearr = [3, 3, 9, 9, 5]n = 5m = 7print(maxSubarray(arr, n, m)) # This code is contributed by# Shubham Singh(SHUBHAMSINGH10)
// C# program to find sub-array// having maximum sum of elements modulo m.using System;using System.Collections;using System.Collections.Generic; class GFG{ // Return the maximum sum subarray mod m. static int maxSubarray(int[] arr, int n, int m) { int prefix = 0; int maxim = 0; HashSet<int> S = new HashSet<int>(); S.Add(0); // Traversing the array. for (int i = 0; i < n; i++) { // Finding prefix sum. prefix = (prefix + arr[i]) % m; // Finding maximum of prefix sum. maxim = Math.Max(maxim, prefix); // Finding iterator pointing to the first // element that is not less than value // "prefix + 1", i.e., greater than or // equal to this value. int it = 0; foreach(int j in S) { if (j >= prefix + 1) it = j; } if (it != 0) { maxim = Math.Max(maxim, prefix - it + m); } // adding prefix in the set. S.Add(prefix); } return maxim; } // Driver code public static void Main(string[] args) { int[] arr = new int[] { 3, 3, 9, 9, 5 }; int n = 5; int m = 7; Console.Write(maxSubarray(arr, n, m)); }} // This code is contributed by rutvik_56.
<script>// Javascript program to find sub-array// having maximum sum of elements modulo m. // Return the maximum sum subarray mod m.function maxSubarray(arr,n,m){ let x = 0; let prefix = 0; let maxim = 0; let S = new Set(); S.add(0); // Traversing the array. for (let i = 0; i < n; i++) { // Finding prefix sum. prefix = (prefix + arr[i]) % m; // Finding maximum of prefix sum. maxim = Math.max(maxim, prefix); // Finding iterator pointing to the first // element that is not less than value // "prefix + 1", i.e., greater than or // equal to this value. let it = 0; for (let j of S.values()) { if (j >= prefix + 1) it = j; } if (it != 0) { maxim = Math.max(maxim, prefix - it + m); } // adding prefix in the set. S.add(prefix); } return maxim;} // Driver Codelet arr=[3, 3, 9, 9, 5];let n = 5;let m = 7;document.write(maxSubarray(arr, n, m)); // This code is contributed by avanitrachhadiya2155</script>
Output:
6
Reference: http://stackoverflow.com/questions/31113993/maximum-subarray-sum-modulo-mThis article is contributed by Anuj Chauhan. 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.
SHUBHAMSINGH10
pratham76
rutvik_56
lecturedsaece
avanitrachhadiya2155
surinderdawra388
Modular Arithmetic
prefix-sum
Self-Balancing-BST
Mathematical
prefix-sum
Mathematical
Modular Arithmetic
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here. | [
{
"code": null,
"e": 52,
"s": 24,
"text": "\n09 Mar, 2022"
},
{
"code": null,
"e": 278,
"s": 52,
"text": "Given an array of n elements and an integer m. The task is to find the maximum value of the sum of its subarray modulo m i.e find the sum of each subarray mod m and print the maximum value of this modulo operation.Examples: "
},
{
"code": null,
"e": 773,
"s": 278,
"text": "Input : arr[] = { 3, 3, 9, 9, 5 }\n m = 7\nOutput : 6\nAll sub-arrays and their value:\n{ 9 } => 9%7 = 2\n{ 3 } => 3%7 = 3\n{ 5 } => 5%7 = 5\n{ 9, 5 } => 14%7 = 2\n{ 9, 9 } => 18%7 = 4\n{ 3, 9 } => 12%7 = 5\n{ 3, 3 } => 6%7 = 6\n{ 3, 9, 9 } => 21%7 = 0\n{ 3, 3, 9 } => 15%7 = 1\n{ 9, 9, 5 } => 23%7 = 2\n{ 3, 3, 9, 9 } => 24%7 = 3\n{ 3, 9, 9, 5 } => 26%7 = 5\n{ 3, 3, 9, 9, 5 } => 29%7 = 1\n\nInput : arr[] = {10, 7, 18}\n m = 13\nOutput : 12\nThe subarray {7, 18} has maximum sub-array\nsum modulo 13."
},
{
"code": null,
"e": 1236,
"s": 775,
"text": "Method 1 (Brute Force): Use brute force to find all the subarrays of the given array and find sum of each subarray mod m and keep track of maximum.Method 2 (efficient approach): The idea is to compute prefix sum of array. We find maximum sum ending with every index and finally return overall maximum. To find maximum sum ending at an index, we need to find the starting point of maximum sum ending with i. Below steps explain how to find the starting point. "
},
{
"code": null,
"e": 1605,
"s": 1236,
"text": "Let prefix sum for index i be prefixi, i.e., \nprefixi = (arr[0] + arr[1] + .... arr[i] ) % m\n\nLet maximum sum ending with i be, maxSumi. \nLet this sum begins with index j.\n\nmaxSumi = (prefixi - prefixj + m) % m\n \nFrom above expression it is clear that the\nvalue of maxSumi becomes maximum when \nprefixj is greater than prefixi \nand closest to prefixi"
},
{
"code": null,
"e": 1657,
"s": 1605,
"text": "We mainly have two operations in above algorithm. "
},
{
"code": null,
"e": 1767,
"s": 1657,
"text": "Store all prefixes.For current prefix, prefixi, find the smallest value greater than or equal to prefixi + 1."
},
{
"code": null,
"e": 1787,
"s": 1767,
"text": "Store all prefixes."
},
{
"code": null,
"e": 1878,
"s": 1787,
"text": "For current prefix, prefixi, find the smallest value greater than or equal to prefixi + 1."
},
{
"code": null,
"e": 2132,
"s": 1878,
"text": "For above operations, a self-balancing-binary-search-trees like AVL Tree, Red-Black Tree, etc are best suited. In below implementation we use set in STL which implements a self-balancing-binary-search-tree.Below is the implementation of this approach: "
},
{
"code": null,
"e": 2136,
"s": 2132,
"text": "C++"
},
{
"code": null,
"e": 2141,
"s": 2136,
"text": "Java"
},
{
"code": null,
"e": 2149,
"s": 2141,
"text": "Python3"
},
{
"code": null,
"e": 2152,
"s": 2149,
"text": "C#"
},
{
"code": null,
"e": 2163,
"s": 2152,
"text": "Javascript"
},
{
"code": "// C++ program to find sub-array having maximum// sum of elements modulo m.#include<bits/stdc++.h>using namespace std; // Return the maximum sum subarray mod m.int maxSubarray(int arr[], int n, int m){ int x, prefix = 0, maxim = 0; set<int> S; S.insert(0); // Traversing the array. for (int i = 0; i < n; i++) { // Finding prefix sum. prefix = (prefix + arr[i])%m; // Finding maximum of prefix sum. maxim = max(maxim, prefix); // Finding iterator pointing to the first // element that is not less than value // \"prefix + 1\", i.e., greater than or // equal to this value. auto it = S.lower_bound(prefix+1); if (it != S.end()) maxim = max(maxim, prefix - (*it) + m ); // Inserting prefix in the set. S.insert(prefix); } return maxim;} // Driver Programint main(){ int arr[] = { 3, 3, 9, 9, 5 }; int n = sizeof(arr)/sizeof(arr[0]); int m = 7; cout << maxSubarray(arr, n, m) << endl; return 0;}",
"e": 3198,
"s": 2163,
"text": null
},
{
"code": "// Java program to find sub-array// having maximum sum of elements modulo m.import java.util.*;class GFG{ // Return the maximum sum subarray mod m. static int maxSubarray(int[] arr, int n, int m) { int x = 0; int prefix = 0; int maxim = 0; Set<Integer> S = new HashSet<Integer>(); S.add(0); // Traversing the array. for (int i = 0; i < n; i++) { // Finding prefix sum. prefix = (prefix + arr[i]) % m; // Finding maximum of prefix sum. maxim = Math.max(maxim, prefix); // Finding iterator pointing to the first // element that is not less than value // \"prefix + 1\", i.e., greater than or // equal to this value. int it = 0; for (int j : S) { if (j >= prefix + 1) it = j; } if (it != 0) { maxim = Math.max(maxim, prefix - it + m); } // adding prefix in the set. S.add(prefix); } return maxim; } // Driver code public static void main(String[] args) { // Driver Code int[] arr = new int[] { 3, 3, 9, 9, 5 }; int n = 5; int m = 7; System.out.print(maxSubarray(arr, n, m)); }} // This code is contributed by pratham76.",
"e": 4383,
"s": 3198,
"text": null
},
{
"code": "# Python3 program to find sub-array# having maximum sum of elements modulo m. # Return the maximum sum subarray mod m.def maxSubarray(arr, n, m): x = 0 prefix = 0 maxim = 0 S = set() S.add(0) # Traversing the array. for i in range(n): # Finding prefix sum. prefix = (prefix + arr[i]) % m # Finding maximum of prefix sum. maxim = max(maxim, prefix) # Finding iterator pointing to the first # element that is not less than value # \"prefix + 1\", i.e., greater than or # equal to this value. it = 0 for i in S: if i >= prefix + 1: it = i if (it != 0) : maxim = max(maxim, prefix - it + m ) # adding prefix in the set. S.add(prefix) return maxim # Driver Codearr = [3, 3, 9, 9, 5]n = 5m = 7print(maxSubarray(arr, n, m)) # This code is contributed by# Shubham Singh(SHUBHAMSINGH10)",
"e": 5327,
"s": 4383,
"text": null
},
{
"code": "// C# program to find sub-array// having maximum sum of elements modulo m.using System;using System.Collections;using System.Collections.Generic; class GFG{ // Return the maximum sum subarray mod m. static int maxSubarray(int[] arr, int n, int m) { int prefix = 0; int maxim = 0; HashSet<int> S = new HashSet<int>(); S.Add(0); // Traversing the array. for (int i = 0; i < n; i++) { // Finding prefix sum. prefix = (prefix + arr[i]) % m; // Finding maximum of prefix sum. maxim = Math.Max(maxim, prefix); // Finding iterator pointing to the first // element that is not less than value // \"prefix + 1\", i.e., greater than or // equal to this value. int it = 0; foreach(int j in S) { if (j >= prefix + 1) it = j; } if (it != 0) { maxim = Math.Max(maxim, prefix - it + m); } // adding prefix in the set. S.Add(prefix); } return maxim; } // Driver code public static void Main(string[] args) { int[] arr = new int[] { 3, 3, 9, 9, 5 }; int n = 5; int m = 7; Console.Write(maxSubarray(arr, n, m)); }} // This code is contributed by rutvik_56.",
"e": 6533,
"s": 5327,
"text": null
},
{
"code": "<script>// Javascript program to find sub-array// having maximum sum of elements modulo m. // Return the maximum sum subarray mod m.function maxSubarray(arr,n,m){ let x = 0; let prefix = 0; let maxim = 0; let S = new Set(); S.add(0); // Traversing the array. for (let i = 0; i < n; i++) { // Finding prefix sum. prefix = (prefix + arr[i]) % m; // Finding maximum of prefix sum. maxim = Math.max(maxim, prefix); // Finding iterator pointing to the first // element that is not less than value // \"prefix + 1\", i.e., greater than or // equal to this value. let it = 0; for (let j of S.values()) { if (j >= prefix + 1) it = j; } if (it != 0) { maxim = Math.max(maxim, prefix - it + m); } // adding prefix in the set. S.add(prefix); } return maxim;} // Driver Codelet arr=[3, 3, 9, 9, 5];let n = 5;let m = 7;document.write(maxSubarray(arr, n, m)); // This code is contributed by avanitrachhadiya2155</script>",
"e": 7589,
"s": 6533,
"text": null
},
{
"code": null,
"e": 7599,
"s": 7589,
"text": "Output: "
},
{
"code": null,
"e": 7601,
"s": 7599,
"text": "6"
},
{
"code": null,
"e": 8106,
"s": 7601,
"text": "Reference: http://stackoverflow.com/questions/31113993/maximum-subarray-sum-modulo-mThis article is contributed by Anuj Chauhan. 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": 8121,
"s": 8106,
"text": "SHUBHAMSINGH10"
},
{
"code": null,
"e": 8131,
"s": 8121,
"text": "pratham76"
},
{
"code": null,
"e": 8141,
"s": 8131,
"text": "rutvik_56"
},
{
"code": null,
"e": 8155,
"s": 8141,
"text": "lecturedsaece"
},
{
"code": null,
"e": 8176,
"s": 8155,
"text": "avanitrachhadiya2155"
},
{
"code": null,
"e": 8193,
"s": 8176,
"text": "surinderdawra388"
},
{
"code": null,
"e": 8212,
"s": 8193,
"text": "Modular Arithmetic"
},
{
"code": null,
"e": 8223,
"s": 8212,
"text": "prefix-sum"
},
{
"code": null,
"e": 8242,
"s": 8223,
"text": "Self-Balancing-BST"
},
{
"code": null,
"e": 8255,
"s": 8242,
"text": "Mathematical"
},
{
"code": null,
"e": 8266,
"s": 8255,
"text": "prefix-sum"
},
{
"code": null,
"e": 8279,
"s": 8266,
"text": "Mathematical"
},
{
"code": null,
"e": 8298,
"s": 8279,
"text": "Modular Arithmetic"
}
] |
URI getQuery() method in Java with Examples | 02 Jan, 2019
The getQuery() function is a part of URI class. The function getQuery() returns the Query of a specified URI.
Function Signature
public String getQuery()
Syntax
uri.getQuery()
Parameter This function does not require any parameter
Return Type: The function returns String Type
Below programs illustrates the use of getQuery() function:
Example 1: Given a URI we will get the Query using the getQuery() function.
// Java program to show the use of the function getQuery() import java.net.*; class Solution { public static void main(String args[]) { // uri object URI uri = null; try { // create a URI uri = new URI("https://www.geeksforgeeks.org/url-getprotocol-method-in-java-with-examples?title=protocol"); // get the Query String _Query = uri.getQuery(); // display the URL System.out.println("URI = " + uri); // display the Query System.out.println(" Query= " + _Query); } // if any error occurs catch (Exception e) { // display the error System.out.println(e); } }}
URI = https://www.geeksforgeeks.org/url-getprotocol-method-in-java-with-examples?title=protocol
Query= title=protocol
Example 2: Now we will not provide any query and use the function to get the query and see the results.
// Java program to show the use of the function getQuery()import java.net.*;class Solution { public static void main(String args[]) { // uri object URI uri = null; try { // create a URI uri = new URI("https://www.geeksforgeeks.org/url-getprotocol-method-in-java-with-examples"); // get the Query String _Query = uri.getQuery(); // display the URL System.out.println("URI = " + uri); // display the Query System.out.println(" Query=" + _Query); } // if any error occurs catch (URISyntaxException e) { // display the error System.out.println("URI Exception =" + e.getMessage()); } }}
URI = https://www.geeksforgeeks.org/url-getprotocol-method-in-java-with-examples
Query=null
Example 3: The value returned by getQuery() and getRawQuery() is same except that all sequences of escaped octets are decoded.The getRawPath() returns the exact value of the string as provided by the user but the getQuery() function decodes the sequence of escaped octets if any.
// Java program to show the use of the function getQuery()import java.net.*;class Solution { public static void main(String args[]) { // uri object URI uri = null; try { // create a URI uri = new URI("https://www.geeksforgeeks.org/url-getprotocol-method-in-java-with-examples?title=protocol%E2%82%AC"); // get the Query String _Query = uri.getQuery(); // display the URL System.out.println("URI = " + uri); // display the Query System.out.println(" Query=" + _Query); // get the Raw Query String Raw_Query = uri.getRawQuery(); // display the Raw Query System.out.println(" Raw Query=" + Raw_Query); } // if any error occurs catch (URISyntaxException e) { // display the error System.out.println("URI Exception =" + e.getMessage()); } }}
URI = https://www.geeksforgeeks.org/url-getprotocol-method-in-java-with-examples?title=protocol%E2%82%AC
Query=title=protocol?
Raw Query=title=protocol%E2%82%AC
Java-Functions
Java-net-package
Java-URI
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": "\n02 Jan, 2019"
},
{
"code": null,
"e": 138,
"s": 28,
"text": "The getQuery() function is a part of URI class. The function getQuery() returns the Query of a specified URI."
},
{
"code": null,
"e": 157,
"s": 138,
"text": "Function Signature"
},
{
"code": null,
"e": 182,
"s": 157,
"text": "public String getQuery()"
},
{
"code": null,
"e": 189,
"s": 182,
"text": "Syntax"
},
{
"code": null,
"e": 204,
"s": 189,
"text": "uri.getQuery()"
},
{
"code": null,
"e": 259,
"s": 204,
"text": "Parameter This function does not require any parameter"
},
{
"code": null,
"e": 305,
"s": 259,
"text": "Return Type: The function returns String Type"
},
{
"code": null,
"e": 364,
"s": 305,
"text": "Below programs illustrates the use of getQuery() function:"
},
{
"code": null,
"e": 440,
"s": 364,
"text": "Example 1: Given a URI we will get the Query using the getQuery() function."
},
{
"code": "// Java program to show the use of the function getQuery() import java.net.*; class Solution { public static void main(String args[]) { // uri object URI uri = null; try { // create a URI uri = new URI(\"https://www.geeksforgeeks.org/url-getprotocol-method-in-java-with-examples?title=protocol\"); // get the Query String _Query = uri.getQuery(); // display the URL System.out.println(\"URI = \" + uri); // display the Query System.out.println(\" Query= \" + _Query); } // if any error occurs catch (Exception e) { // display the error System.out.println(e); } }}",
"e": 1179,
"s": 440,
"text": null
},
{
"code": null,
"e": 1299,
"s": 1179,
"text": "URI = https://www.geeksforgeeks.org/url-getprotocol-method-in-java-with-examples?title=protocol\n Query= title=protocol\n"
},
{
"code": null,
"e": 1403,
"s": 1299,
"text": "Example 2: Now we will not provide any query and use the function to get the query and see the results."
},
{
"code": "// Java program to show the use of the function getQuery()import java.net.*;class Solution { public static void main(String args[]) { // uri object URI uri = null; try { // create a URI uri = new URI(\"https://www.geeksforgeeks.org/url-getprotocol-method-in-java-with-examples\"); // get the Query String _Query = uri.getQuery(); // display the URL System.out.println(\"URI = \" + uri); // display the Query System.out.println(\" Query=\" + _Query); } // if any error occurs catch (URISyntaxException e) { // display the error System.out.println(\"URI Exception =\" + e.getMessage()); } }}",
"e": 2164,
"s": 1403,
"text": null
},
{
"code": null,
"e": 2258,
"s": 2164,
"text": "URI = https://www.geeksforgeeks.org/url-getprotocol-method-in-java-with-examples\n Query=null\n"
},
{
"code": null,
"e": 2538,
"s": 2258,
"text": "Example 3: The value returned by getQuery() and getRawQuery() is same except that all sequences of escaped octets are decoded.The getRawPath() returns the exact value of the string as provided by the user but the getQuery() function decodes the sequence of escaped octets if any."
},
{
"code": "// Java program to show the use of the function getQuery()import java.net.*;class Solution { public static void main(String args[]) { // uri object URI uri = null; try { // create a URI uri = new URI(\"https://www.geeksforgeeks.org/url-getprotocol-method-in-java-with-examples?title=protocol%E2%82%AC\"); // get the Query String _Query = uri.getQuery(); // display the URL System.out.println(\"URI = \" + uri); // display the Query System.out.println(\" Query=\" + _Query); // get the Raw Query String Raw_Query = uri.getRawQuery(); // display the Raw Query System.out.println(\" Raw Query=\" + Raw_Query); } // if any error occurs catch (URISyntaxException e) { // display the error System.out.println(\"URI Exception =\" + e.getMessage()); } }}",
"e": 3503,
"s": 2538,
"text": null
},
{
"code": null,
"e": 3667,
"s": 3503,
"text": "URI = https://www.geeksforgeeks.org/url-getprotocol-method-in-java-with-examples?title=protocol%E2%82%AC\n Query=title=protocol?\n Raw Query=title=protocol%E2%82%AC\n"
},
{
"code": null,
"e": 3682,
"s": 3667,
"text": "Java-Functions"
},
{
"code": null,
"e": 3699,
"s": 3682,
"text": "Java-net-package"
},
{
"code": null,
"e": 3708,
"s": 3699,
"text": "Java-URI"
},
{
"code": null,
"e": 3713,
"s": 3708,
"text": "Java"
},
{
"code": null,
"e": 3727,
"s": 3713,
"text": "Java Programs"
},
{
"code": null,
"e": 3732,
"s": 3727,
"text": "Java"
}
] |
URL getProtocol() method in Java with Examples | 27 Dec, 2018
The getProtocol() function is a part of URL class. The function getProtocol() returns the Protocol of a specified URL.
Function Signature
public String getProtocol()
Syntax
url.getProtocol()
Parameter This function does not require any parameter
Return Type: The function returns String Type
Below programs illustrates the use of getProtocol() function:
Example 1:
// Java program to show the// use of the function getProtocol() import java.net.*; class GFG { public static void main(String args[]) { // url object URL url = null; try { // create a URL url = new URL("https:// www.geeksforgeeks.org"); // get the Protocol String Protocol = url.getProtocol(); // display the URL System.out.println("URL = " + url); // display the Protocol System.out.println("Protocol = " + Protocol); // create a URL url = new URL("http:// www.geeksforgeeks.org"); // get the Protocol Protocol = url.getProtocol(); // display the URL System.out.println("URL = " + url); // display the Protocol System.out.println("Protocol = " + Protocol); // create a URL url = new URL("ftp:// www.geeksforgeeks.org"); // get the Protocol Protocol = url.getProtocol(); // display the URL System.out.println("URL = " + url); // display the Protocol System.out.println("Protocol = " + Protocol); } // if any error occurs catch (Exception e) { // display the error System.out.println(e); } }}
URL = https:// www.geeksforgeeks.org
Protocol = https
URL = http:// www.geeksforgeeks.org
Protocol = http
URL = ftp:// www.geeksforgeeks.org
Protocol = ftp
Java-Functions
Java-net-package
Java-URL
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": "\n27 Dec, 2018"
},
{
"code": null,
"e": 147,
"s": 28,
"text": "The getProtocol() function is a part of URL class. The function getProtocol() returns the Protocol of a specified URL."
},
{
"code": null,
"e": 166,
"s": 147,
"text": "Function Signature"
},
{
"code": null,
"e": 195,
"s": 166,
"text": "public String getProtocol()\n"
},
{
"code": null,
"e": 202,
"s": 195,
"text": "Syntax"
},
{
"code": null,
"e": 221,
"s": 202,
"text": "url.getProtocol()\n"
},
{
"code": null,
"e": 276,
"s": 221,
"text": "Parameter This function does not require any parameter"
},
{
"code": null,
"e": 322,
"s": 276,
"text": "Return Type: The function returns String Type"
},
{
"code": null,
"e": 384,
"s": 322,
"text": "Below programs illustrates the use of getProtocol() function:"
},
{
"code": null,
"e": 395,
"s": 384,
"text": "Example 1:"
},
{
"code": "// Java program to show the// use of the function getProtocol() import java.net.*; class GFG { public static void main(String args[]) { // url object URL url = null; try { // create a URL url = new URL(\"https:// www.geeksforgeeks.org\"); // get the Protocol String Protocol = url.getProtocol(); // display the URL System.out.println(\"URL = \" + url); // display the Protocol System.out.println(\"Protocol = \" + Protocol); // create a URL url = new URL(\"http:// www.geeksforgeeks.org\"); // get the Protocol Protocol = url.getProtocol(); // display the URL System.out.println(\"URL = \" + url); // display the Protocol System.out.println(\"Protocol = \" + Protocol); // create a URL url = new URL(\"ftp:// www.geeksforgeeks.org\"); // get the Protocol Protocol = url.getProtocol(); // display the URL System.out.println(\"URL = \" + url); // display the Protocol System.out.println(\"Protocol = \" + Protocol); } // if any error occurs catch (Exception e) { // display the error System.out.println(e); } }}",
"e": 1761,
"s": 395,
"text": null
},
{
"code": null,
"e": 1918,
"s": 1761,
"text": "URL = https:// www.geeksforgeeks.org\nProtocol = https\nURL = http:// www.geeksforgeeks.org\nProtocol = http\nURL = ftp:// www.geeksforgeeks.org\nProtocol = ftp\n"
},
{
"code": null,
"e": 1933,
"s": 1918,
"text": "Java-Functions"
},
{
"code": null,
"e": 1950,
"s": 1933,
"text": "Java-net-package"
},
{
"code": null,
"e": 1959,
"s": 1950,
"text": "Java-URL"
},
{
"code": null,
"e": 1964,
"s": 1959,
"text": "Java"
},
{
"code": null,
"e": 1969,
"s": 1964,
"text": "Java"
}
] |
Text Localization, Detection and Recognition using Pytesseract | 30 Nov, 2021
Pytesseract or Python-tesseract is an Optical Character Recognition (OCR) tool for Python. It will read and recognize the text in images, license plates etc. Python-tesseract is actually a wrapper class or a package for Google’s Tesseract-OCR Engine. It is also useful and regarded as a stand-alone invocation script to tesseract, as it can easily read all image types supported by the Pillow and Leptonica imaging libraries, which mainly includes –
jpg
png
gif
bmp
tiff etc
Also additionally, if it is used as a script, Python-tesseract will also print the recognized text instead of writing it to a file. Python-tesseract can be installed using pip as shown below –
pip install pytesseract
If you are using Anaconda Cloud, Python-tesseract can be installed as shown below:-
conda install -c conda-forge/label/cf202003 pytesseract
or
conda install -c conda-forge pytesseract
Note: tesseract should be installed in the system before running the below script.Below is the implementation.
Python3
from pytesseract import*import argparseimport cv2 # We construct the argument parser# and parse the argumentsap = argparse.ArgumentParser() ap.add_argument("-i", "--image", required=True, help="path to input image to be OCR'd")ap.add_argument("-c", "--min-conf", type=int, default=0, help="minimum confidence value to filter weak text detection")args = vars(ap.parse_args()) # We load the input image and then convert# it to RGB from BGR. We then use Tesseract# to localize each area of text in the input# imageimages = cv2.imread(args["image"])rgb = cv2.cvtColor(images, cv2.COLOR_BGR2RGB)results = pytesseract.image_to_data(rgb, output_type=Output.DICT) # Then loop over each of the individual text# localizationsfor i in range(0, len(results["text"])): # We can then extract the bounding box coordinates # of the text region from the current result x = results["left"][i] y = results["top"][i] w = results["width"][i] h = results["height"][i] # We will also extract the OCR text itself along # with the confidence of the text localization text = results["text"][i] conf = int(results["conf"][i]) # filter out weak confidence text localizations if conf > args["min_conf"]: # We will display the confidence and text to # our terminal print("Confidence: {}".format(conf)) print("Text: {}".format(text)) print("") # We then strip out non-ASCII text so we can # draw the text on the image We will be using # OpenCV, then draw a bounding box around the # text along with the text itself text = "".join(text).strip() cv2.rectangle(images, (x, y), (x + w, y + h), (0, 0, 255), 2) cv2.putText(images, text, (x, y - 10), cv2.FONT_HERSHEY_SIMPLEX, 1.2, (0, 255, 255), 3) # After all, we will show the output imagecv2.imshow("Image", images)cv2.waitKey(0)
Output: Execute the command below to view the Output
python ocr.py --image ocr.png
In addition to Output, we will see the Confidence Level and the Text In Command Prompt as shown below –
Confidence: 93
Text: I
Confidence: 93
Text: LOVE
Confidence: 91
Text: TESSERACT
Akanksha_Rai
surindertarika1234
python-modules
Python-OpenCV
python-utility
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here. | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n30 Nov, 2021"
},
{
"code": null,
"e": 479,
"s": 28,
"text": "Pytesseract or Python-tesseract is an Optical Character Recognition (OCR) tool for Python. It will read and recognize the text in images, license plates etc. Python-tesseract is actually a wrapper class or a package for Google’s Tesseract-OCR Engine. It is also useful and regarded as a stand-alone invocation script to tesseract, as it can easily read all image types supported by the Pillow and Leptonica imaging libraries, which mainly includes – "
},
{
"code": null,
"e": 483,
"s": 479,
"text": "jpg"
},
{
"code": null,
"e": 487,
"s": 483,
"text": "png"
},
{
"code": null,
"e": 491,
"s": 487,
"text": "gif"
},
{
"code": null,
"e": 495,
"s": 491,
"text": "bmp"
},
{
"code": null,
"e": 504,
"s": 495,
"text": "tiff etc"
},
{
"code": null,
"e": 699,
"s": 504,
"text": "Also additionally, if it is used as a script, Python-tesseract will also print the recognized text instead of writing it to a file. Python-tesseract can be installed using pip as shown below – "
},
{
"code": null,
"e": 723,
"s": 699,
"text": "pip install pytesseract"
},
{
"code": null,
"e": 809,
"s": 723,
"text": "If you are using Anaconda Cloud, Python-tesseract can be installed as shown below:- "
},
{
"code": null,
"e": 865,
"s": 809,
"text": "conda install -c conda-forge/label/cf202003 pytesseract"
},
{
"code": null,
"e": 870,
"s": 865,
"text": "or "
},
{
"code": null,
"e": 911,
"s": 870,
"text": "conda install -c conda-forge pytesseract"
},
{
"code": null,
"e": 1023,
"s": 911,
"text": "Note: tesseract should be installed in the system before running the below script.Below is the implementation. "
},
{
"code": null,
"e": 1031,
"s": 1023,
"text": "Python3"
},
{
"code": "from pytesseract import*import argparseimport cv2 # We construct the argument parser# and parse the argumentsap = argparse.ArgumentParser() ap.add_argument(\"-i\", \"--image\", required=True, help=\"path to input image to be OCR'd\")ap.add_argument(\"-c\", \"--min-conf\", type=int, default=0, help=\"minimum confidence value to filter weak text detection\")args = vars(ap.parse_args()) # We load the input image and then convert# it to RGB from BGR. We then use Tesseract# to localize each area of text in the input# imageimages = cv2.imread(args[\"image\"])rgb = cv2.cvtColor(images, cv2.COLOR_BGR2RGB)results = pytesseract.image_to_data(rgb, output_type=Output.DICT) # Then loop over each of the individual text# localizationsfor i in range(0, len(results[\"text\"])): # We can then extract the bounding box coordinates # of the text region from the current result x = results[\"left\"][i] y = results[\"top\"][i] w = results[\"width\"][i] h = results[\"height\"][i] # We will also extract the OCR text itself along # with the confidence of the text localization text = results[\"text\"][i] conf = int(results[\"conf\"][i]) # filter out weak confidence text localizations if conf > args[\"min_conf\"]: # We will display the confidence and text to # our terminal print(\"Confidence: {}\".format(conf)) print(\"Text: {}\".format(text)) print(\"\") # We then strip out non-ASCII text so we can # draw the text on the image We will be using # OpenCV, then draw a bounding box around the # text along with the text itself text = \"\".join(text).strip() cv2.rectangle(images, (x, y), (x + w, y + h), (0, 0, 255), 2) cv2.putText(images, text, (x, y - 10), cv2.FONT_HERSHEY_SIMPLEX, 1.2, (0, 255, 255), 3) # After all, we will show the output imagecv2.imshow(\"Image\", images)cv2.waitKey(0)",
"e": 3140,
"s": 1031,
"text": null
},
{
"code": null,
"e": 3194,
"s": 3140,
"text": "Output: Execute the command below to view the Output "
},
{
"code": null,
"e": 3225,
"s": 3194,
"text": "python ocr.py --image ocr.png "
},
{
"code": null,
"e": 3330,
"s": 3225,
"text": "In addition to Output, we will see the Confidence Level and the Text In Command Prompt as shown below – "
},
{
"code": null,
"e": 3412,
"s": 3330,
"text": "Confidence: 93\nText: I\n\nConfidence: 93\nText: LOVE\n\nConfidence: 91\nText: TESSERACT"
},
{
"code": null,
"e": 3425,
"s": 3412,
"text": "Akanksha_Rai"
},
{
"code": null,
"e": 3444,
"s": 3425,
"text": "surindertarika1234"
},
{
"code": null,
"e": 3459,
"s": 3444,
"text": "python-modules"
},
{
"code": null,
"e": 3473,
"s": 3459,
"text": "Python-OpenCV"
},
{
"code": null,
"e": 3488,
"s": 3473,
"text": "python-utility"
},
{
"code": null,
"e": 3495,
"s": 3488,
"text": "Python"
}
] |
Find the number of distinct pairs of vertices which have a distance of exactly k in a tree | 22 Jun, 2022
Given an integer k and a tree with n nodes. The task is to count the number of distinct pairs of vertices that have a distance of exactly k.
Examples:
Input: k = 2
Output: 4Input: k = 3
Output: 2
Approach: This problem can be solved using dynamic programming. For every vertex v of the tree, we calculate values d[v][lev] (0 <= lev <= k). This value indicates the number of vertices having distance lev from v. Note that d[v][0] = 1. Then we calculate the answer. For any vertex v number of pairs will be a product of the number of vertices at level j – 1 and level k – j.
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;#define N 5005 // To store vertices and value of kint n, k; vector<int> gr[N]; // To store number vertices at a level iint d[N][505]; // To store the final answerint ans = 0; // Function to add an edge between two nodesvoid Add_edge(int x, int y){ gr[x].push_back(y); gr[y].push_back(x);} // Function to find the number of distinct// pairs of the vertices which have a distance// of exactly k in a treevoid dfs(int v, int par){ // At level zero vertex itself is counted d[v][0] = 1; for (auto i : gr[v]) { if (i != par) { dfs(i, v); // Count the pair of vertices at // distance k for (int j = 1; j <= k; j++) ans += d[i][j - 1] * d[v][k - j]; // For all levels count vertices for (int j = 1; j <= k; j++) d[v][j] += d[i][j - 1]; } }} // Driver codeint main(){ n = 5, k = 2; // Add edges Add_edge(1, 2); Add_edge(2, 3); Add_edge(3, 4); Add_edge(2, 5); // Function call dfs(1, 0); // Required answer cout << ans; return 0;}
// Java implementation of the approachimport java.util.*; class GFG{ static final int N = 5005; // To store vertices and value of k static int n, k; static Vector<Integer>[] gr = new Vector[N]; // To store number vertices at a level i static int[][] d = new int[N][505]; // To store the final answer static int ans = 0; // Function to add an edge between two nodes static void Add_edge(int x, int y) { gr[x].add(y); gr[y].add(x); } // Function to find the number of distinct // pairs of the vertices which have a distance // of exactly k in a tree static void dfs(int v, int par) { // At level zero vertex itself is counted d[v][0] = 1; for (Integer i : gr[v]) { if (i != par) { dfs(i, v); // Count the pair of vertices at // distance k for (int j = 1; j <= k; j++) ans += d[i][j - 1] * d[v][k - j]; // For all levels count vertices for (int j = 1; j <= k; j++) d[v][j] += d[i][j - 1]; } } } // Driver code public static void main(String[] args) { n = 5; k = 2; for (int i = 0; i < N; i++) gr[i] = new Vector<Integer>(); // Add edges Add_edge(1, 2); Add_edge(2, 3); Add_edge(3, 4); Add_edge(2, 5); // Function call dfs(1, 0); // Required answer System.out.print(ans); }} // This code is contributed by PrinciRaj1992
# Python3 implementation of the approachN = 5005 # To store vertices and value of kn, k = 0, 0 gr = [[] for i in range(N)] # To store number vertices at a level id = [[0 for i in range(505)] for i in range(N)] # To store the final answerans = 0 # Function to add an edge between two nodesdef Add_edge(x, y): gr[x].append(y) gr[y].append(x) # Function to find the number of distinct# pairs of the vertices which have a distance# of exactly k in a treedef dfs(v, par): global ans # At level zero vertex itself is counted d[v][0] = 1 for i in gr[v]: if (i != par): dfs(i, v) # Count the pair of vertices at # distance k for j in range(1, k + 1): ans += d[i][j - 1] * d[v][k - j] # For all levels count vertices for j in range(1, k + 1): d[v][j] += d[i][j - 1] # Driver coden = 5k = 2 # Add edgesAdd_edge(1, 2)Add_edge(2, 3)Add_edge(3, 4)Add_edge(2, 5) # Function calldfs(1, 0) # Required answerprint(ans) # This code is contributed by Mohit Kumar
// C# implementation of the approachusing System;using System.Collections.Generic; class GFG{ static readonly int N = 5005; // To store vertices and value of k static int n, k; static List<int>[] gr = new List<int>[N]; // To store number vertices at a level i static int[,] d = new int[N, 505]; // To store the readonly answer static int ans = 0; // Function to add an edge between two nodes static void Add_edge(int x, int y) { gr[x].Add(y); gr[y].Add(x); } // Function to find the number of distinct // pairs of the vertices which have a distance // of exactly k in a tree static void dfs(int v, int par) { // At level zero vertex itself is counted d[v, 0] = 1; foreach (int i in gr[v]) { if (i != par) { dfs(i, v); // Count the pair of vertices at // distance k for (int j = 1; j <= k; j++) ans += d[i, j - 1] * d[v, k - j]; // For all levels count vertices for (int j = 1; j <= k; j++) d[v, j] += d[i, j - 1]; } } } // Driver code public static void Main(String[] args) { n = 5; k = 2; for (int i = 0; i < N; i++) gr[i] = new List<int>(); // Add edges Add_edge(1, 2); Add_edge(2, 3); Add_edge(3, 4); Add_edge(2, 5); // Function call dfs(1, 0); // Required answer Console.Write(ans); }} // This code is contributed by Rajput-Ji
<?php// PHP implementation of the approach$N = 5005; // To store vertices and value of k$gr = array_fill(0, $N, array()); // To store number vertices// at a level i$d = array_fill(0, $N, array_fill(0, 505, 0)); // To store the final answer$ans = 0; // Function to add an edge between// two nodesfunction Add_edge($x, $y){ global $gr; array_push($gr[$x], $y); array_push($gr[$y], $x);} // Function to find the number of distinct// pairs of the vertices which have a// distance of exactly k in a treefunction dfs($v, $par){ global $d, $ans, $k, $gr; // At level zero vertex itself // is counted $d[$v][0] = 1; foreach ($gr[$v] as &$i) { if ($i != $par) { dfs($i, $v); // Count the pair of vertices // at distance k for ($j = 1; $j <= $k; $j++) $ans += $d[$i][$j - 1] * $d[$v][$k - $j]; // For all levels count vertices for ($j = 1; $j <= $k; $j++) $d[$v][$j] += $d[$i][$j - 1]; } }} // Driver code$n = 5;$k = 2; // Add edgesAdd_edge(1, 2);Add_edge(2, 3);Add_edge(3, 4);Add_edge(2, 5); // Function calldfs(1, 0); // Required answerecho $ans; // This code is contributed by mits?>
<script> // Javascript implementation of the approachlet N = 5005; // To store vertices and value of klet n, k;let gr = new Array(N); // To store number vertices at a level ilet d = new Array(N);for(let i = 0 ; i < N; i++){ d[i] = new Array(505); for(let j = 0; j < 505; j++) { d[i][j] = 0; }} // To store the final answerlet ans = 0; // Function to add an edge between two nodesfunction Add_edge(x, y){ gr[x].push(y); gr[y].push(x);} // Function to find the number of distinct// pairs of the vertices which have a distance// of exactly k in a treefunction dfs(v, par){ // At level zero vertex itself is counted d[v][0] = 1; for(let i = 0; i < gr[v].length; i++) { if (gr[v][i] != par) { dfs(gr[v][i], v); // Count the pair of vertices at // distance k for(let j = 1; j <= k; j++) ans += d[gr[v][i]][j - 1] * d[v][k - j]; // For all levels count vertices for(let j = 1; j <= k; j++) d[v][j] += d[gr[v][i]][j - 1]; } }} // Driver coden = 5;k = 2;for(let i = 0; i < N; i++) gr[i] = []; // Add edgesAdd_edge(1, 2);Add_edge(2, 3);Add_edge(3, 4);Add_edge(2, 5); // Function calldfs(1, 0); // Required answerdocument.write(ans); // This code is contributed by unknown2108 </script>
4
Time Complexity: O(N)
Auxiliary Space: O(N * 505)
Mithun Kumar
mohit kumar 29
princiraj1992
Rajput-Ji
ShubhamShekhaliya
unknown2108
rishavnitro
edit-distance
Competitive Programming
Dynamic Programming
Mathematical
Tree
Dynamic Programming
Mathematical
Tree
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Find two numbers from their sum and XOR
Equal Sum and XOR of three Numbers
The Ultimate Beginner's Guide For DSA
Most important type of Algorithms
Find maximum distance between any city and station
Largest Sum Contiguous Subarray
Program for Fibonacci numbers
0-1 Knapsack Problem | DP-10
Longest Common Subsequence | DP-4
Find if there is a path between two vertices in an undirected graph | [
{
"code": null,
"e": 52,
"s": 24,
"text": "\n22 Jun, 2022"
},
{
"code": null,
"e": 193,
"s": 52,
"text": "Given an integer k and a tree with n nodes. The task is to count the number of distinct pairs of vertices that have a distance of exactly k."
},
{
"code": null,
"e": 204,
"s": 193,
"text": "Examples: "
},
{
"code": null,
"e": 219,
"s": 204,
"text": "Input: k = 2 "
},
{
"code": null,
"e": 243,
"s": 219,
"text": "Output: 4Input: k = 3 "
},
{
"code": null,
"e": 255,
"s": 243,
"text": "Output: 2 "
},
{
"code": null,
"e": 632,
"s": 255,
"text": "Approach: This problem can be solved using dynamic programming. For every vertex v of the tree, we calculate values d[v][lev] (0 <= lev <= k). This value indicates the number of vertices having distance lev from v. Note that d[v][0] = 1. Then we calculate the answer. For any vertex v number of pairs will be a product of the number of vertices at level j – 1 and level k – j."
},
{
"code": null,
"e": 685,
"s": 632,
"text": "Below is the implementation of the above approach: "
},
{
"code": null,
"e": 689,
"s": 685,
"text": "C++"
},
{
"code": null,
"e": 694,
"s": 689,
"text": "Java"
},
{
"code": null,
"e": 702,
"s": 694,
"text": "Python3"
},
{
"code": null,
"e": 705,
"s": 702,
"text": "C#"
},
{
"code": null,
"e": 709,
"s": 705,
"text": "PHP"
},
{
"code": null,
"e": 720,
"s": 709,
"text": "Javascript"
},
{
"code": "// C++ implementation of the approach#include <bits/stdc++.h>using namespace std;#define N 5005 // To store vertices and value of kint n, k; vector<int> gr[N]; // To store number vertices at a level iint d[N][505]; // To store the final answerint ans = 0; // Function to add an edge between two nodesvoid Add_edge(int x, int y){ gr[x].push_back(y); gr[y].push_back(x);} // Function to find the number of distinct// pairs of the vertices which have a distance// of exactly k in a treevoid dfs(int v, int par){ // At level zero vertex itself is counted d[v][0] = 1; for (auto i : gr[v]) { if (i != par) { dfs(i, v); // Count the pair of vertices at // distance k for (int j = 1; j <= k; j++) ans += d[i][j - 1] * d[v][k - j]; // For all levels count vertices for (int j = 1; j <= k; j++) d[v][j] += d[i][j - 1]; } }} // Driver codeint main(){ n = 5, k = 2; // Add edges Add_edge(1, 2); Add_edge(2, 3); Add_edge(3, 4); Add_edge(2, 5); // Function call dfs(1, 0); // Required answer cout << ans; return 0;}",
"e": 1890,
"s": 720,
"text": null
},
{
"code": "// Java implementation of the approachimport java.util.*; class GFG{ static final int N = 5005; // To store vertices and value of k static int n, k; static Vector<Integer>[] gr = new Vector[N]; // To store number vertices at a level i static int[][] d = new int[N][505]; // To store the final answer static int ans = 0; // Function to add an edge between two nodes static void Add_edge(int x, int y) { gr[x].add(y); gr[y].add(x); } // Function to find the number of distinct // pairs of the vertices which have a distance // of exactly k in a tree static void dfs(int v, int par) { // At level zero vertex itself is counted d[v][0] = 1; for (Integer i : gr[v]) { if (i != par) { dfs(i, v); // Count the pair of vertices at // distance k for (int j = 1; j <= k; j++) ans += d[i][j - 1] * d[v][k - j]; // For all levels count vertices for (int j = 1; j <= k; j++) d[v][j] += d[i][j - 1]; } } } // Driver code public static void main(String[] args) { n = 5; k = 2; for (int i = 0; i < N; i++) gr[i] = new Vector<Integer>(); // Add edges Add_edge(1, 2); Add_edge(2, 3); Add_edge(3, 4); Add_edge(2, 5); // Function call dfs(1, 0); // Required answer System.out.print(ans); }} // This code is contributed by PrinciRaj1992",
"e": 3498,
"s": 1890,
"text": null
},
{
"code": "# Python3 implementation of the approachN = 5005 # To store vertices and value of kn, k = 0, 0 gr = [[] for i in range(N)] # To store number vertices at a level id = [[0 for i in range(505)] for i in range(N)] # To store the final answerans = 0 # Function to add an edge between two nodesdef Add_edge(x, y): gr[x].append(y) gr[y].append(x) # Function to find the number of distinct# pairs of the vertices which have a distance# of exactly k in a treedef dfs(v, par): global ans # At level zero vertex itself is counted d[v][0] = 1 for i in gr[v]: if (i != par): dfs(i, v) # Count the pair of vertices at # distance k for j in range(1, k + 1): ans += d[i][j - 1] * d[v][k - j] # For all levels count vertices for j in range(1, k + 1): d[v][j] += d[i][j - 1] # Driver coden = 5k = 2 # Add edgesAdd_edge(1, 2)Add_edge(2, 3)Add_edge(3, 4)Add_edge(2, 5) # Function calldfs(1, 0) # Required answerprint(ans) # This code is contributed by Mohit Kumar",
"e": 4577,
"s": 3498,
"text": null
},
{
"code": "// C# implementation of the approachusing System;using System.Collections.Generic; class GFG{ static readonly int N = 5005; // To store vertices and value of k static int n, k; static List<int>[] gr = new List<int>[N]; // To store number vertices at a level i static int[,] d = new int[N, 505]; // To store the readonly answer static int ans = 0; // Function to add an edge between two nodes static void Add_edge(int x, int y) { gr[x].Add(y); gr[y].Add(x); } // Function to find the number of distinct // pairs of the vertices which have a distance // of exactly k in a tree static void dfs(int v, int par) { // At level zero vertex itself is counted d[v, 0] = 1; foreach (int i in gr[v]) { if (i != par) { dfs(i, v); // Count the pair of vertices at // distance k for (int j = 1; j <= k; j++) ans += d[i, j - 1] * d[v, k - j]; // For all levels count vertices for (int j = 1; j <= k; j++) d[v, j] += d[i, j - 1]; } } } // Driver code public static void Main(String[] args) { n = 5; k = 2; for (int i = 0; i < N; i++) gr[i] = new List<int>(); // Add edges Add_edge(1, 2); Add_edge(2, 3); Add_edge(3, 4); Add_edge(2, 5); // Function call dfs(1, 0); // Required answer Console.Write(ans); }} // This code is contributed by Rajput-Ji",
"e": 6200,
"s": 4577,
"text": null
},
{
"code": "<?php// PHP implementation of the approach$N = 5005; // To store vertices and value of k$gr = array_fill(0, $N, array()); // To store number vertices// at a level i$d = array_fill(0, $N, array_fill(0, 505, 0)); // To store the final answer$ans = 0; // Function to add an edge between// two nodesfunction Add_edge($x, $y){ global $gr; array_push($gr[$x], $y); array_push($gr[$y], $x);} // Function to find the number of distinct// pairs of the vertices which have a// distance of exactly k in a treefunction dfs($v, $par){ global $d, $ans, $k, $gr; // At level zero vertex itself // is counted $d[$v][0] = 1; foreach ($gr[$v] as &$i) { if ($i != $par) { dfs($i, $v); // Count the pair of vertices // at distance k for ($j = 1; $j <= $k; $j++) $ans += $d[$i][$j - 1] * $d[$v][$k - $j]; // For all levels count vertices for ($j = 1; $j <= $k; $j++) $d[$v][$j] += $d[$i][$j - 1]; } }} // Driver code$n = 5;$k = 2; // Add edgesAdd_edge(1, 2);Add_edge(2, 3);Add_edge(3, 4);Add_edge(2, 5); // Function calldfs(1, 0); // Required answerecho $ans; // This code is contributed by mits?>",
"e": 7458,
"s": 6200,
"text": null
},
{
"code": "<script> // Javascript implementation of the approachlet N = 5005; // To store vertices and value of klet n, k;let gr = new Array(N); // To store number vertices at a level ilet d = new Array(N);for(let i = 0 ; i < N; i++){ d[i] = new Array(505); for(let j = 0; j < 505; j++) { d[i][j] = 0; }} // To store the final answerlet ans = 0; // Function to add an edge between two nodesfunction Add_edge(x, y){ gr[x].push(y); gr[y].push(x);} // Function to find the number of distinct// pairs of the vertices which have a distance// of exactly k in a treefunction dfs(v, par){ // At level zero vertex itself is counted d[v][0] = 1; for(let i = 0; i < gr[v].length; i++) { if (gr[v][i] != par) { dfs(gr[v][i], v); // Count the pair of vertices at // distance k for(let j = 1; j <= k; j++) ans += d[gr[v][i]][j - 1] * d[v][k - j]; // For all levels count vertices for(let j = 1; j <= k; j++) d[v][j] += d[gr[v][i]][j - 1]; } }} // Driver coden = 5;k = 2;for(let i = 0; i < N; i++) gr[i] = []; // Add edgesAdd_edge(1, 2);Add_edge(2, 3);Add_edge(3, 4);Add_edge(2, 5); // Function calldfs(1, 0); // Required answerdocument.write(ans); // This code is contributed by unknown2108 </script>",
"e": 8825,
"s": 7458,
"text": null
},
{
"code": null,
"e": 8827,
"s": 8825,
"text": "4"
},
{
"code": null,
"e": 8851,
"s": 8829,
"text": "Time Complexity: O(N)"
},
{
"code": null,
"e": 8879,
"s": 8851,
"text": "Auxiliary Space: O(N * 505)"
},
{
"code": null,
"e": 8892,
"s": 8879,
"text": "Mithun Kumar"
},
{
"code": null,
"e": 8907,
"s": 8892,
"text": "mohit kumar 29"
},
{
"code": null,
"e": 8921,
"s": 8907,
"text": "princiraj1992"
},
{
"code": null,
"e": 8931,
"s": 8921,
"text": "Rajput-Ji"
},
{
"code": null,
"e": 8949,
"s": 8931,
"text": "ShubhamShekhaliya"
},
{
"code": null,
"e": 8961,
"s": 8949,
"text": "unknown2108"
},
{
"code": null,
"e": 8973,
"s": 8961,
"text": "rishavnitro"
},
{
"code": null,
"e": 8987,
"s": 8973,
"text": "edit-distance"
},
{
"code": null,
"e": 9011,
"s": 8987,
"text": "Competitive Programming"
},
{
"code": null,
"e": 9031,
"s": 9011,
"text": "Dynamic Programming"
},
{
"code": null,
"e": 9044,
"s": 9031,
"text": "Mathematical"
},
{
"code": null,
"e": 9049,
"s": 9044,
"text": "Tree"
},
{
"code": null,
"e": 9069,
"s": 9049,
"text": "Dynamic Programming"
},
{
"code": null,
"e": 9082,
"s": 9069,
"text": "Mathematical"
},
{
"code": null,
"e": 9087,
"s": 9082,
"text": "Tree"
},
{
"code": null,
"e": 9185,
"s": 9087,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 9225,
"s": 9185,
"text": "Find two numbers from their sum and XOR"
},
{
"code": null,
"e": 9260,
"s": 9225,
"text": "Equal Sum and XOR of three Numbers"
},
{
"code": null,
"e": 9298,
"s": 9260,
"text": "The Ultimate Beginner's Guide For DSA"
},
{
"code": null,
"e": 9332,
"s": 9298,
"text": "Most important type of Algorithms"
},
{
"code": null,
"e": 9383,
"s": 9332,
"text": "Find maximum distance between any city and station"
},
{
"code": null,
"e": 9415,
"s": 9383,
"text": "Largest Sum Contiguous Subarray"
},
{
"code": null,
"e": 9445,
"s": 9415,
"text": "Program for Fibonacci numbers"
},
{
"code": null,
"e": 9474,
"s": 9445,
"text": "0-1 Knapsack Problem | DP-10"
},
{
"code": null,
"e": 9508,
"s": 9474,
"text": "Longest Common Subsequence | DP-4"
}
] |
How to Create RecyclerView with Multiple ViewType in Android? | 27 Aug, 2020
RecyclerView forms a very crucial part of the UI in Android App development. It is especially important to optimize memory consumption during the display of a long list of items. A RecylerView inflates a customized list of items. This list can have either all similar layouts or multiple distinct layouts. Here, such a RecyclerView with multiple ViewTypes is developed. Following is an example of Android RecyclerView with multiple views.
Step 1: Add the required dependenciesCreate a new project in Android Studio and add the following dependencies in build.gradle(:app) under the Gradle Scripts section:
implementation “androidx.recyclerview:recyclerview:1.1.0”implementation “androidx.cardview:cardview:1.0.0”
For more up-to-date versions of the dependencies, click here. While the first dependency is mandatory, the second one is optional depending upon the UI requirements. Click on Sync Now and proceed.
Step 2: Implement RecyclerView in activity_main.xml
Create a layout that holds the main RecyclerView. Here, it has been created in the activity_main.xml file. The given layout contains merely a Welcome TextView and a RecyclerView, however, it can be customized as per the requirements. Code for activity_main.xml is given below.
activity_main.xml
<?xml version="1.0" encoding="utf-8"?><androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" tools:context=".MainActivity"> <!--Welcome text--> <TextView android:id="@+id/heading" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Welcome to GFG!" android:textColor="#006600" android:textSize="20dp" app:layout_constraintBottom_toBottomOf="parent" app:layout_constraintEnd_toEndOf="parent" app:layout_constraintStart_toStartOf="parent" app:layout_constraintTop_toTopOf="parent" app:layout_constraintVertical_bias="0.058"></TextView> <!-- Main RecyclerView--> <androidx.recyclerview.widget.RecyclerView android:id="@+id/recyclerView" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_marginTop="15dp" android:layout_marginStart="15dp" app:layout_constraintBottom_toBottomOf="parent" app:layout_constraintEnd_toEndOf="parent" app:layout_constraintStart_toStartOf="parent" app:layout_constraintTop_toBottomOf="@+id/heading" app:layout_constraintVertical_bias="0.061" android:paddingBottom="100dp"/> </androidx.constraintlayout.widget.ConstraintLayout>
Step 3: Add the required drawable file
Before proceeding further, make sure all the necessary drawable resources are added under the drawable resource directory. In this tutorial, only the following icon has been used:
Step 4: Create all the item layouts
Identify all the different layouts the RecyclerView is required to hold and implement them all in separate XML files under the layout resource directory. Here, two distinct layouts have been created. The first one is implemented in layout_one.xml while the second one in layout_two.xml. The first layout consists of just a TextView wrapped inside a CardView. The following is its implementation.
layout_one.xml
<?xml version="1.0" encoding="utf-8"?><LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="wrap_content" android:orientation="vertical"> <!--parent CardView--> <androidx.cardview.widget.CardView android:id="@+id/cardview_one" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_marginTop="4dp" android:layout_marginEnd="16dp" app:layout_constraintEnd_toEndOf="parent" app:layout_constraintTop_toTopOf="parent" android:elevation="5dp"> <!--LinearLayout inside the CardView--> <!--This layout is accessed to create toasts when this item is clicked--> <LinearLayout android:id="@+id/linearlayout" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="horizontal"> <!--This layout only holds a TextView inside a CardView--> <TextView android:id="@+id/text" android:layout_width="wrap_content" android:layout_height="wrap_content" android:textColor="#000000" android:textSize="20dp" android:layout_margin="20dp"/> </LinearLayout> </androidx.cardview.widget.CardView> <!-- This is extra space given to maintain a gap between two consecutive CardViews--> <Space android:layout_width="match_parent" android:layout_height="10dp"/> </LinearLayout>
The second item holds three elements wrapped inside a CardView.
An ImageView
A TextView
Another TextView with a relatively smaller font size
layout_two.xml
<?xml version="1.0" encoding="utf-8"?><LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="wrap_content" android:orientation="vertical" android:id="@+id/linearlayout" > <!--parent CardView--> <androidx.cardview.widget.CardView android:id="@+id/cardview_two" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_marginTop="4dp" android:layout_marginEnd="16dp" app:layout_constraintEnd_toEndOf="parent" app:layout_constraintTop_toTopOf="parent" android:elevation="5dp"> <!--LinearLayout inside the CardView--> <!--This layout is accessed to create toasts when this item is clicked--> <LinearLayout android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="horizontal"> <!--This layout consists of an ImageView and two TextViews--> <ImageView android:id="@+id/image" android:layout_width="80dp" android:layout_height="80dp"/> <!-- The purpose of this LinearLayout is to align the two TextViews Vertically--> <LinearLayout android:layout_width="wrap_content" android:layout_height="match_parent" android:orientation="vertical"> <!--These are the 2 TextViews in this layout--> <TextView android:id="@+id/text_one" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_marginTop="10dp" android:layout_marginStart="20dp" android:textColor="#000000" android:textSize="20dp"/> <TextView android:id="@+id/text_two" android:layout_width="wrap_content" android:layout_height="wrap_content" android:textColor="#000000" android:textSize="15dp" android:layout_marginTop="10dp" android:layout_marginStart="20dp"/> </LinearLayout> </LinearLayout> </androidx.cardview.widget.CardView> <!-- This is extra space given to maintain a gap between two CardViews--> <Space android:layout_width="match_parent" android:layout_height="10dp"/> </LinearLayout>
Step 5: Create an Item class
Create a Java class that holds the public constructors corresponding to each layout. Thus, two constructors have been created here in the ItemClass.java file. In addition to constructors, the getter and setter methods too are declared here. This is done in order to safely access the private variables of the ItemClass outside of it. This is how the ItemClass.java looks for the layouts created above:
ItemClass.java
package com.example.android.multilayoutrecyclerview; // ItemClass public class ItemClass { // Integers assigned to each layout // these are declared static so that they can // be accessed from the class name itself // And final so that they are not modified later public static final int LayoutOne = 0; public static final int LayoutTwo = 1; // This variable ViewType specifies // which out of the two layouts // is expected in the given item private int viewType; // String variable to hold the TextView // of the first item. private String text; // public constructor for the first layout public ItemClass(int viewType, String text) { this.text = text; this.viewType = viewType; } // getter and setter methods for the text variable public String getText() { return text; } public void setText(String text) { this.text = text; } // Variables for the item of second layout private int icon; private String text_one, text_two; // public constructor for the second layout public ItemClass(int viewType, int icon, String text_one, String text_two) { this.icon = icon; this.text_one = text_one; this.text_two = text_two; this.viewType = viewType; } // getter and setter methods for // the variables of the second layout public int geticon() { return icon; } public void seticon(int icon) { this.icon = icon; } public String getText_one() { return text_one; } public void setText_one(String text_one) { this.text_one = text_one; } public String getText_two() { return text_two; } public void setText_two(String text_two) { this.text_two = text_two; } public int getViewType() { return viewType; } public void setViewType(int viewType) { this.viewType = viewType; }}
Step 6: Create the Adapter class
Create an adapter class to display the contents of the RecyclerView. In the Adapter class for multiple ViewType RecyclerViews, the following method is overridden in addition to the conventional onCreateViewHolder(), onBindViewHolder() and getItemCount() methods. getItemViewType() method is solely responsible for choosing the layout corresponding to each item. Apart from adding an extra method, the other changes include defining a specific ViewHolder class for each of the item layouts. Follow the code given for a deeper understanding.
AdapterClass.java
package com.example.android.multilayoutrecyclerview; import android.view.LayoutInflater;import android.view.View;import android.view.ViewGroup;import android.widget.ImageView;import android.widget.LinearLayout;import android.widget.TextView;import android.widget.Toast; import androidx.annotation.NonNull;import androidx.recyclerview.widget.RecyclerView; import java.util.List; import static com.example.android.multilayoutrecyclerview.ItemClass.LayoutOne;import static com.example.android.multilayoutrecyclerview.ItemClass.LayoutTwo; public class AdapterClass extends RecyclerView.Adapter { private List<ItemClass> itemClassList; // public constructor for this class public AdapterClass(List<ItemClass> itemClassList) { this.itemClassList = itemClassList; } // Override the getItemViewType method. // This method uses a switch statement // to assign the layout to each item // depending on the viewType passed @Override public int getItemViewType(int position) { switch (itemClassList.get(position).getViewType()) { case 0: return LayoutOne; case 1: return LayoutTwo; default: return -1; } } // Create classes for each layout ViewHolder. class LayoutOneViewHolder extends RecyclerView.ViewHolder { private TextView textview; private LinearLayout linearLayout; public LayoutOneViewHolder(@NonNull View itemView) { super(itemView); // Find the Views textview = itemView.findViewById(R.id.text); linearLayout = itemView.findViewById(R.id.linearlayout); } // method to set the views that will // be used further in onBindViewHolder method. private void setView(String text) { textview.setText(text); } } // similarly a class for the second layout is also // created. class LayoutTwoViewHolder extends RecyclerView.ViewHolder { private ImageView icon; private TextView text_one, text_two; private LinearLayout linearLayout; public LayoutTwoViewHolder(@NonNull View itemView) { super(itemView); icon = itemView.findViewById(R.id.image); text_one = itemView.findViewById(R.id.text_one); text_two = itemView.findViewById(R.id.text_two); linearLayout = itemView.findViewById(R.id.linearlayout); } private void setViews(int image, String textOne, String textTwo) { icon.setImageResource(image); text_one.setText(textOne); text_two.setText(textTwo); } } // In the onCreateViewHolder, inflate the // xml layout as per the viewType. // This method returns either of the // ViewHolder classes defined above, // depending upon the layout passed as a parameter. @NonNull @Override public RecyclerView.ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) { switch (viewType) { case LayoutOne: View layoutOne = LayoutInflater.from(parent.getContext()) .inflate(R.layout.layout_one, parent, false); return new LayoutOneViewHolder(layoutOne); case LayoutTwo: View layoutTwo = LayoutInflater.from(parent.getContext()) .inflate(R.layout.layout_two, parent, false); return new LayoutTwoViewHolder(layoutTwo); default: return null; } } // In onBindViewHolder, set the Views for each element // of the layout using the methods defined in the // respective ViewHolder classes. @Override public void onBindViewHolder( @NonNull RecyclerView.ViewHolder holder, int position) { switch (itemClassList.get(position).getViewType()) { case LayoutOne: String text = itemClassList.get(position).getText(); ((LayoutOneViewHolder)holder).setView(text); // The following code pops a toast message // when the item layout is clicked. // This message indicates the corresponding // layout. ((LayoutOneViewHolder)holder) .linearLayout.setOnClickListener( new View.OnClickListener() { @Override public void onClick(View view) { Toast .makeText( view.getContext(), "Hello from Layout One!", Toast.LENGTH_SHORT) .show(); } }); break; case LayoutTwo: int image = itemClassList.get(position).geticon(); String text_one = itemClassList.get(position).getText_one(); String text_two = itemClassList.get(position).getText_two(); ((LayoutTwoViewHolder)holder) .setViews(image, text_one, text_two); ((LayoutTwoViewHolder)holder) .linearLayout.setOnClickListener( new View.OnClickListener() { @Override public void onClick(View view) { Toast .makeText( view.getContext(), "Hello from Layout Two!", Toast.LENGTH_SHORT) .show(); } }); break; default: return; } } // This method returns the count of items present in the // RecyclerView at any given time. @Override public int getItemCount() { return itemClassList.size(); }}
Step 7: Complete the MainActivity.java file
Following are the important tasks to be implemented in the MainActivity.java file.
Set the content view as the XML activity wherein the main RecyclerView has been implemented, here activity_main.xml.
Set the layout for the RecyclerView.
Pass arguments to the RecyclerView.
Set the Adapter.
MainActivity.java
package com.example.android.multilayoutrecyclerview; import androidx.appcompat.app.AppCompatActivity;import androidx.recyclerview.widget.LinearLayoutManager;import androidx.recyclerview.widget.RecyclerView; import android.os.Bundle;import android.widget.Adapter; import java.util.ArrayList;import java.util.List; public class MainActivity extends AppCompatActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); // From the MainActivity, find the RecyclerView. RecyclerView recyclerView = findViewById(R.id.recyclerView); // Create and set the layout manager // For the RecyclerView. LinearLayoutManager layoutManager = new LinearLayoutManager(this); recyclerView.setLayoutManager(layoutManager); List<ItemClass> itemClasses = new ArrayList<>(); // pass the arguments itemClasses.add(new ItemClass(ItemClass.LayoutOne, "Item Type 1")); itemClasses.add(new ItemClass(ItemClass.LayoutOne, "Item Type 1")); itemClasses.add(new ItemClass( ItemClass.LayoutTwo, R.drawable.icon, "Item Type 2", "Text")); itemClasses.add(new ItemClass(ItemClass.LayoutOne, "Item Type 1")); itemClasses.add(new ItemClass( ItemClass.LayoutTwo, R.drawable.icon, "Item Type 2", "Text")); itemClasses.add(new ItemClass( ItemClass.LayoutTwo, R.drawable.icon, "Item Type 2", "Text")); itemClasses.add(new ItemClass(ItemClass.LayoutOne, "Item Type 1")); itemClasses.add(new ItemClass( ItemClass.LayoutTwo, R.drawable.icon, "Item Type 2", "Text")); AdapterClass adapterClass = new AdapterClass(itemClasses); AdapterClass adapter = new AdapterClass(itemClasses); // set the adapter recyclerView.setAdapter(adapter); }}
android
Java
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here. | [
{
"code": null,
"e": 52,
"s": 24,
"text": "\n27 Aug, 2020"
},
{
"code": null,
"e": 491,
"s": 52,
"text": "RecyclerView forms a very crucial part of the UI in Android App development. It is especially important to optimize memory consumption during the display of a long list of items. A RecylerView inflates a customized list of items. This list can have either all similar layouts or multiple distinct layouts. Here, such a RecyclerView with multiple ViewTypes is developed. Following is an example of Android RecyclerView with multiple views."
},
{
"code": null,
"e": 658,
"s": 491,
"text": "Step 1: Add the required dependenciesCreate a new project in Android Studio and add the following dependencies in build.gradle(:app) under the Gradle Scripts section:"
},
{
"code": null,
"e": 765,
"s": 658,
"text": "implementation “androidx.recyclerview:recyclerview:1.1.0”implementation “androidx.cardview:cardview:1.0.0”"
},
{
"code": null,
"e": 962,
"s": 765,
"text": "For more up-to-date versions of the dependencies, click here. While the first dependency is mandatory, the second one is optional depending upon the UI requirements. Click on Sync Now and proceed."
},
{
"code": null,
"e": 1014,
"s": 962,
"text": "Step 2: Implement RecyclerView in activity_main.xml"
},
{
"code": null,
"e": 1291,
"s": 1014,
"text": "Create a layout that holds the main RecyclerView. Here, it has been created in the activity_main.xml file. The given layout contains merely a Welcome TextView and a RecyclerView, however, it can be customized as per the requirements. Code for activity_main.xml is given below."
},
{
"code": null,
"e": 1309,
"s": 1291,
"text": "activity_main.xml"
},
{
"code": "<?xml version=\"1.0\" encoding=\"utf-8\"?><androidx.constraintlayout.widget.ConstraintLayout xmlns:android=\"http://schemas.android.com/apk/res/android\" xmlns:app=\"http://schemas.android.com/apk/res-auto\" xmlns:tools=\"http://schemas.android.com/tools\" android:layout_width=\"match_parent\" android:layout_height=\"match_parent\" tools:context=\".MainActivity\"> <!--Welcome text--> <TextView android:id=\"@+id/heading\" android:layout_width=\"wrap_content\" android:layout_height=\"wrap_content\" android:text=\"Welcome to GFG!\" android:textColor=\"#006600\" android:textSize=\"20dp\" app:layout_constraintBottom_toBottomOf=\"parent\" app:layout_constraintEnd_toEndOf=\"parent\" app:layout_constraintStart_toStartOf=\"parent\" app:layout_constraintTop_toTopOf=\"parent\" app:layout_constraintVertical_bias=\"0.058\"></TextView> <!-- Main RecyclerView--> <androidx.recyclerview.widget.RecyclerView android:id=\"@+id/recyclerView\" android:layout_width=\"match_parent\" android:layout_height=\"wrap_content\" android:layout_marginTop=\"15dp\" android:layout_marginStart=\"15dp\" app:layout_constraintBottom_toBottomOf=\"parent\" app:layout_constraintEnd_toEndOf=\"parent\" app:layout_constraintStart_toStartOf=\"parent\" app:layout_constraintTop_toBottomOf=\"@+id/heading\" app:layout_constraintVertical_bias=\"0.061\" android:paddingBottom=\"100dp\"/> </androidx.constraintlayout.widget.ConstraintLayout>",
"e": 2849,
"s": 1309,
"text": null
},
{
"code": null,
"e": 2888,
"s": 2849,
"text": "Step 3: Add the required drawable file"
},
{
"code": null,
"e": 3068,
"s": 2888,
"text": "Before proceeding further, make sure all the necessary drawable resources are added under the drawable resource directory. In this tutorial, only the following icon has been used:"
},
{
"code": null,
"e": 3104,
"s": 3068,
"text": "Step 4: Create all the item layouts"
},
{
"code": null,
"e": 3500,
"s": 3104,
"text": "Identify all the different layouts the RecyclerView is required to hold and implement them all in separate XML files under the layout resource directory. Here, two distinct layouts have been created. The first one is implemented in layout_one.xml while the second one in layout_two.xml. The first layout consists of just a TextView wrapped inside a CardView. The following is its implementation."
},
{
"code": null,
"e": 3515,
"s": 3500,
"text": "layout_one.xml"
},
{
"code": "<?xml version=\"1.0\" encoding=\"utf-8\"?><LinearLayout xmlns:android=\"http://schemas.android.com/apk/res/android\" xmlns:app=\"http://schemas.android.com/apk/res-auto\" xmlns:tools=\"http://schemas.android.com/tools\" android:layout_width=\"match_parent\" android:layout_height=\"wrap_content\" android:orientation=\"vertical\"> <!--parent CardView--> <androidx.cardview.widget.CardView android:id=\"@+id/cardview_one\" android:layout_width=\"match_parent\" android:layout_height=\"wrap_content\" android:layout_marginTop=\"4dp\" android:layout_marginEnd=\"16dp\" app:layout_constraintEnd_toEndOf=\"parent\" app:layout_constraintTop_toTopOf=\"parent\" android:elevation=\"5dp\"> <!--LinearLayout inside the CardView--> <!--This layout is accessed to create toasts when this item is clicked--> <LinearLayout android:id=\"@+id/linearlayout\" android:layout_width=\"match_parent\" android:layout_height=\"match_parent\" android:orientation=\"horizontal\"> <!--This layout only holds a TextView inside a CardView--> <TextView android:id=\"@+id/text\" android:layout_width=\"wrap_content\" android:layout_height=\"wrap_content\" android:textColor=\"#000000\" android:textSize=\"20dp\" android:layout_margin=\"20dp\"/> </LinearLayout> </androidx.cardview.widget.CardView> <!-- This is extra space given to maintain a gap between two consecutive CardViews--> <Space android:layout_width=\"match_parent\" android:layout_height=\"10dp\"/> </LinearLayout>",
"e": 5240,
"s": 3515,
"text": null
},
{
"code": null,
"e": 5304,
"s": 5240,
"text": "The second item holds three elements wrapped inside a CardView."
},
{
"code": null,
"e": 5317,
"s": 5304,
"text": "An ImageView"
},
{
"code": null,
"e": 5328,
"s": 5317,
"text": "A TextView"
},
{
"code": null,
"e": 5381,
"s": 5328,
"text": "Another TextView with a relatively smaller font size"
},
{
"code": null,
"e": 5396,
"s": 5381,
"text": "layout_two.xml"
},
{
"code": "<?xml version=\"1.0\" encoding=\"utf-8\"?><LinearLayout xmlns:android=\"http://schemas.android.com/apk/res/android\" xmlns:app=\"http://schemas.android.com/apk/res-auto\" xmlns:tools=\"http://schemas.android.com/tools\" android:layout_width=\"match_parent\" android:layout_height=\"wrap_content\" android:orientation=\"vertical\" android:id=\"@+id/linearlayout\" > <!--parent CardView--> <androidx.cardview.widget.CardView android:id=\"@+id/cardview_two\" android:layout_width=\"match_parent\" android:layout_height=\"wrap_content\" android:layout_marginTop=\"4dp\" android:layout_marginEnd=\"16dp\" app:layout_constraintEnd_toEndOf=\"parent\" app:layout_constraintTop_toTopOf=\"parent\" android:elevation=\"5dp\"> <!--LinearLayout inside the CardView--> <!--This layout is accessed to create toasts when this item is clicked--> <LinearLayout android:layout_width=\"match_parent\" android:layout_height=\"match_parent\" android:orientation=\"horizontal\"> <!--This layout consists of an ImageView and two TextViews--> <ImageView android:id=\"@+id/image\" android:layout_width=\"80dp\" android:layout_height=\"80dp\"/> <!-- The purpose of this LinearLayout is to align the two TextViews Vertically--> <LinearLayout android:layout_width=\"wrap_content\" android:layout_height=\"match_parent\" android:orientation=\"vertical\"> <!--These are the 2 TextViews in this layout--> <TextView android:id=\"@+id/text_one\" android:layout_width=\"wrap_content\" android:layout_height=\"wrap_content\" android:layout_marginTop=\"10dp\" android:layout_marginStart=\"20dp\" android:textColor=\"#000000\" android:textSize=\"20dp\"/> <TextView android:id=\"@+id/text_two\" android:layout_width=\"wrap_content\" android:layout_height=\"wrap_content\" android:textColor=\"#000000\" android:textSize=\"15dp\" android:layout_marginTop=\"10dp\" android:layout_marginStart=\"20dp\"/> </LinearLayout> </LinearLayout> </androidx.cardview.widget.CardView> <!-- This is extra space given to maintain a gap between two CardViews--> <Space android:layout_width=\"match_parent\" android:layout_height=\"10dp\"/> </LinearLayout>",
"e": 8106,
"s": 5396,
"text": null
},
{
"code": null,
"e": 8135,
"s": 8106,
"text": "Step 5: Create an Item class"
},
{
"code": null,
"e": 8537,
"s": 8135,
"text": "Create a Java class that holds the public constructors corresponding to each layout. Thus, two constructors have been created here in the ItemClass.java file. In addition to constructors, the getter and setter methods too are declared here. This is done in order to safely access the private variables of the ItemClass outside of it. This is how the ItemClass.java looks for the layouts created above:"
},
{
"code": null,
"e": 8552,
"s": 8537,
"text": "ItemClass.java"
},
{
"code": "package com.example.android.multilayoutrecyclerview; // ItemClass public class ItemClass { // Integers assigned to each layout // these are declared static so that they can // be accessed from the class name itself // And final so that they are not modified later public static final int LayoutOne = 0; public static final int LayoutTwo = 1; // This variable ViewType specifies // which out of the two layouts // is expected in the given item private int viewType; // String variable to hold the TextView // of the first item. private String text; // public constructor for the first layout public ItemClass(int viewType, String text) { this.text = text; this.viewType = viewType; } // getter and setter methods for the text variable public String getText() { return text; } public void setText(String text) { this.text = text; } // Variables for the item of second layout private int icon; private String text_one, text_two; // public constructor for the second layout public ItemClass(int viewType, int icon, String text_one, String text_two) { this.icon = icon; this.text_one = text_one; this.text_two = text_two; this.viewType = viewType; } // getter and setter methods for // the variables of the second layout public int geticon() { return icon; } public void seticon(int icon) { this.icon = icon; } public String getText_one() { return text_one; } public void setText_one(String text_one) { this.text_one = text_one; } public String getText_two() { return text_two; } public void setText_two(String text_two) { this.text_two = text_two; } public int getViewType() { return viewType; } public void setViewType(int viewType) { this.viewType = viewType; }}",
"e": 10463,
"s": 8552,
"text": null
},
{
"code": null,
"e": 10496,
"s": 10463,
"text": "Step 6: Create the Adapter class"
},
{
"code": null,
"e": 11036,
"s": 10496,
"text": "Create an adapter class to display the contents of the RecyclerView. In the Adapter class for multiple ViewType RecyclerViews, the following method is overridden in addition to the conventional onCreateViewHolder(), onBindViewHolder() and getItemCount() methods. getItemViewType() method is solely responsible for choosing the layout corresponding to each item. Apart from adding an extra method, the other changes include defining a specific ViewHolder class for each of the item layouts. Follow the code given for a deeper understanding."
},
{
"code": null,
"e": 11054,
"s": 11036,
"text": "AdapterClass.java"
},
{
"code": "package com.example.android.multilayoutrecyclerview; import android.view.LayoutInflater;import android.view.View;import android.view.ViewGroup;import android.widget.ImageView;import android.widget.LinearLayout;import android.widget.TextView;import android.widget.Toast; import androidx.annotation.NonNull;import androidx.recyclerview.widget.RecyclerView; import java.util.List; import static com.example.android.multilayoutrecyclerview.ItemClass.LayoutOne;import static com.example.android.multilayoutrecyclerview.ItemClass.LayoutTwo; public class AdapterClass extends RecyclerView.Adapter { private List<ItemClass> itemClassList; // public constructor for this class public AdapterClass(List<ItemClass> itemClassList) { this.itemClassList = itemClassList; } // Override the getItemViewType method. // This method uses a switch statement // to assign the layout to each item // depending on the viewType passed @Override public int getItemViewType(int position) { switch (itemClassList.get(position).getViewType()) { case 0: return LayoutOne; case 1: return LayoutTwo; default: return -1; } } // Create classes for each layout ViewHolder. class LayoutOneViewHolder extends RecyclerView.ViewHolder { private TextView textview; private LinearLayout linearLayout; public LayoutOneViewHolder(@NonNull View itemView) { super(itemView); // Find the Views textview = itemView.findViewById(R.id.text); linearLayout = itemView.findViewById(R.id.linearlayout); } // method to set the views that will // be used further in onBindViewHolder method. private void setView(String text) { textview.setText(text); } } // similarly a class for the second layout is also // created. class LayoutTwoViewHolder extends RecyclerView.ViewHolder { private ImageView icon; private TextView text_one, text_two; private LinearLayout linearLayout; public LayoutTwoViewHolder(@NonNull View itemView) { super(itemView); icon = itemView.findViewById(R.id.image); text_one = itemView.findViewById(R.id.text_one); text_two = itemView.findViewById(R.id.text_two); linearLayout = itemView.findViewById(R.id.linearlayout); } private void setViews(int image, String textOne, String textTwo) { icon.setImageResource(image); text_one.setText(textOne); text_two.setText(textTwo); } } // In the onCreateViewHolder, inflate the // xml layout as per the viewType. // This method returns either of the // ViewHolder classes defined above, // depending upon the layout passed as a parameter. @NonNull @Override public RecyclerView.ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) { switch (viewType) { case LayoutOne: View layoutOne = LayoutInflater.from(parent.getContext()) .inflate(R.layout.layout_one, parent, false); return new LayoutOneViewHolder(layoutOne); case LayoutTwo: View layoutTwo = LayoutInflater.from(parent.getContext()) .inflate(R.layout.layout_two, parent, false); return new LayoutTwoViewHolder(layoutTwo); default: return null; } } // In onBindViewHolder, set the Views for each element // of the layout using the methods defined in the // respective ViewHolder classes. @Override public void onBindViewHolder( @NonNull RecyclerView.ViewHolder holder, int position) { switch (itemClassList.get(position).getViewType()) { case LayoutOne: String text = itemClassList.get(position).getText(); ((LayoutOneViewHolder)holder).setView(text); // The following code pops a toast message // when the item layout is clicked. // This message indicates the corresponding // layout. ((LayoutOneViewHolder)holder) .linearLayout.setOnClickListener( new View.OnClickListener() { @Override public void onClick(View view) { Toast .makeText( view.getContext(), \"Hello from Layout One!\", Toast.LENGTH_SHORT) .show(); } }); break; case LayoutTwo: int image = itemClassList.get(position).geticon(); String text_one = itemClassList.get(position).getText_one(); String text_two = itemClassList.get(position).getText_two(); ((LayoutTwoViewHolder)holder) .setViews(image, text_one, text_two); ((LayoutTwoViewHolder)holder) .linearLayout.setOnClickListener( new View.OnClickListener() { @Override public void onClick(View view) { Toast .makeText( view.getContext(), \"Hello from Layout Two!\", Toast.LENGTH_SHORT) .show(); } }); break; default: return; } } // This method returns the count of items present in the // RecyclerView at any given time. @Override public int getItemCount() { return itemClassList.size(); }}",
"e": 17279,
"s": 11054,
"text": null
},
{
"code": null,
"e": 17323,
"s": 17279,
"text": "Step 7: Complete the MainActivity.java file"
},
{
"code": null,
"e": 17406,
"s": 17323,
"text": "Following are the important tasks to be implemented in the MainActivity.java file."
},
{
"code": null,
"e": 17523,
"s": 17406,
"text": "Set the content view as the XML activity wherein the main RecyclerView has been implemented, here activity_main.xml."
},
{
"code": null,
"e": 17560,
"s": 17523,
"text": "Set the layout for the RecyclerView."
},
{
"code": null,
"e": 17596,
"s": 17560,
"text": "Pass arguments to the RecyclerView."
},
{
"code": null,
"e": 17613,
"s": 17596,
"text": "Set the Adapter."
},
{
"code": null,
"e": 17631,
"s": 17613,
"text": "MainActivity.java"
},
{
"code": "package com.example.android.multilayoutrecyclerview; import androidx.appcompat.app.AppCompatActivity;import androidx.recyclerview.widget.LinearLayoutManager;import androidx.recyclerview.widget.RecyclerView; import android.os.Bundle;import android.widget.Adapter; import java.util.ArrayList;import java.util.List; public class MainActivity extends AppCompatActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); // From the MainActivity, find the RecyclerView. RecyclerView recyclerView = findViewById(R.id.recyclerView); // Create and set the layout manager // For the RecyclerView. LinearLayoutManager layoutManager = new LinearLayoutManager(this); recyclerView.setLayoutManager(layoutManager); List<ItemClass> itemClasses = new ArrayList<>(); // pass the arguments itemClasses.add(new ItemClass(ItemClass.LayoutOne, \"Item Type 1\")); itemClasses.add(new ItemClass(ItemClass.LayoutOne, \"Item Type 1\")); itemClasses.add(new ItemClass( ItemClass.LayoutTwo, R.drawable.icon, \"Item Type 2\", \"Text\")); itemClasses.add(new ItemClass(ItemClass.LayoutOne, \"Item Type 1\")); itemClasses.add(new ItemClass( ItemClass.LayoutTwo, R.drawable.icon, \"Item Type 2\", \"Text\")); itemClasses.add(new ItemClass( ItemClass.LayoutTwo, R.drawable.icon, \"Item Type 2\", \"Text\")); itemClasses.add(new ItemClass(ItemClass.LayoutOne, \"Item Type 1\")); itemClasses.add(new ItemClass( ItemClass.LayoutTwo, R.drawable.icon, \"Item Type 2\", \"Text\")); AdapterClass adapterClass = new AdapterClass(itemClasses); AdapterClass adapter = new AdapterClass(itemClasses); // set the adapter recyclerView.setAdapter(adapter); }}",
"e": 19774,
"s": 17631,
"text": null
},
{
"code": null,
"e": 19782,
"s": 19774,
"text": "android"
},
{
"code": null,
"e": 19787,
"s": 19782,
"text": "Java"
},
{
"code": null,
"e": 19792,
"s": 19787,
"text": "Java"
}
] |
JavaScript Number toString() Method | 31 May, 2022
Below is the example of the Number toString() Method.
Example:
html
<script type="text/javascript"> var num=12; document.write("Output : " + num.toString(2)); </script>
Output:
Output:1100
The toString() method in Javascript is used with a number and converts the number to a string. It is used to return a string representing the specified Number object. Syntax:
num.toString(base)
The toString() method is used with a number num as shown in above syntax using the ‘.’ operator. This method will convert num to a string. Parameters Used: This method accepts a single optional parameter base. This parameter specifies the base in which the integer is represented in the string. It is an integer between 2 and 36 which is used to specify the base for representing numeric values. Return Value: The num.toString() method returns a string representing the specified number object. Below are some examples to illustrate the working of toString() method in JavaScript:
Converting a number to a string with base 2: To convert a number to a string with base 2, we will have to call the toString() method by passing 2 as a parameter.
Converting a number to a string with base 2: To convert a number to a string with base 2, we will have to call the toString() method by passing 2 as a parameter.
html
<script type="text/javascript"> var num=213; document.write("Output : " + num.toString(2)); </script>
Output:
Output:
Output:11010101
Converting a number to a string with base 8: To convert a number to a string with base 8, we will have to call the toString() method by passing 8 as a parameter.
Converting a number to a string with base 8: To convert a number to a string with base 8, we will have to call the toString() method by passing 8 as a parameter.
html
<script type="text/javascript"> var num=213; document.write("Output : " + num.toString(8)); </script>
Output:
Output:
Output : 325
Converting a number to a string with base 16: To convert a number to a string with base 16, we will have to call the toString() method by passing 16 as a parameter.
Converting a number to a string with base 16: To convert a number to a string with base 16, we will have to call the toString() method by passing 16 as a parameter.
html
<script type="text/javascript"> var num=213; document.write("Output : " + num.toString(16)); </script>
Output:
Output:
Output : d5
When no parameter is passed: If the toString() method is called without passing any parameter then the number will be converted to string without change in BASE. Below is the program to illustrate this:
When no parameter is passed: If the toString() method is called without passing any parameter then the number will be converted to string without change in BASE. Below is the program to illustrate this:
html
<script type="text/javascript"> var num=213; document.write("Output : " + num.toString()); </script>
Output:
Output:
Output :213
Supported Browsers:
Google Chrome 1 and above
Internet Explorer 3 and above
Firefox 1 and above
Apple Safari 1 and above
Opera 4 and above
Edge 12 and above
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.
ysachin2314
kumargaurav97520
JavaScript-Methods
JavaScript-Numbers
JavaScript
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here. | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n31 May, 2022"
},
{
"code": null,
"e": 82,
"s": 28,
"text": "Below is the example of the Number toString() Method."
},
{
"code": null,
"e": 92,
"s": 82,
"text": "Example: "
},
{
"code": null,
"e": 97,
"s": 92,
"text": "html"
},
{
"code": "<script type=\"text/javascript\"> var num=12; document.write(\"Output : \" + num.toString(2)); </script>",
"e": 212,
"s": 97,
"text": null
},
{
"code": null,
"e": 220,
"s": 212,
"text": "Output:"
},
{
"code": null,
"e": 232,
"s": 220,
"text": "Output:1100"
},
{
"code": null,
"e": 407,
"s": 232,
"text": "The toString() method in Javascript is used with a number and converts the number to a string. It is used to return a string representing the specified Number object. Syntax:"
},
{
"code": null,
"e": 426,
"s": 407,
"text": "num.toString(base)"
},
{
"code": null,
"e": 1007,
"s": 426,
"text": "The toString() method is used with a number num as shown in above syntax using the ‘.’ operator. This method will convert num to a string. Parameters Used: This method accepts a single optional parameter base. This parameter specifies the base in which the integer is represented in the string. It is an integer between 2 and 36 which is used to specify the base for representing numeric values. Return Value: The num.toString() method returns a string representing the specified number object. Below are some examples to illustrate the working of toString() method in JavaScript:"
},
{
"code": null,
"e": 1170,
"s": 1007,
"text": "Converting a number to a string with base 2: To convert a number to a string with base 2, we will have to call the toString() method by passing 2 as a parameter. "
},
{
"code": null,
"e": 1333,
"s": 1170,
"text": "Converting a number to a string with base 2: To convert a number to a string with base 2, we will have to call the toString() method by passing 2 as a parameter. "
},
{
"code": null,
"e": 1338,
"s": 1333,
"text": "html"
},
{
"code": "<script type=\"text/javascript\"> var num=213; document.write(\"Output : \" + num.toString(2)); </script>",
"e": 1454,
"s": 1338,
"text": null
},
{
"code": null,
"e": 1462,
"s": 1454,
"text": "Output:"
},
{
"code": null,
"e": 1470,
"s": 1462,
"text": "Output:"
},
{
"code": null,
"e": 1486,
"s": 1470,
"text": "Output:11010101"
},
{
"code": null,
"e": 1649,
"s": 1486,
"text": "Converting a number to a string with base 8: To convert a number to a string with base 8, we will have to call the toString() method by passing 8 as a parameter. "
},
{
"code": null,
"e": 1812,
"s": 1649,
"text": "Converting a number to a string with base 8: To convert a number to a string with base 8, we will have to call the toString() method by passing 8 as a parameter. "
},
{
"code": null,
"e": 1817,
"s": 1812,
"text": "html"
},
{
"code": "<script type=\"text/javascript\"> var num=213; document.write(\"Output : \" + num.toString(8)); </script>",
"e": 1933,
"s": 1817,
"text": null
},
{
"code": null,
"e": 1941,
"s": 1933,
"text": "Output:"
},
{
"code": null,
"e": 1949,
"s": 1941,
"text": "Output:"
},
{
"code": null,
"e": 1962,
"s": 1949,
"text": "Output : 325"
},
{
"code": null,
"e": 2128,
"s": 1962,
"text": "Converting a number to a string with base 16: To convert a number to a string with base 16, we will have to call the toString() method by passing 16 as a parameter. "
},
{
"code": null,
"e": 2294,
"s": 2128,
"text": "Converting a number to a string with base 16: To convert a number to a string with base 16, we will have to call the toString() method by passing 16 as a parameter. "
},
{
"code": null,
"e": 2299,
"s": 2294,
"text": "html"
},
{
"code": "<script type=\"text/javascript\"> var num=213; document.write(\"Output : \" + num.toString(16)); </script>",
"e": 2416,
"s": 2299,
"text": null
},
{
"code": null,
"e": 2424,
"s": 2416,
"text": "Output:"
},
{
"code": null,
"e": 2432,
"s": 2424,
"text": "Output:"
},
{
"code": null,
"e": 2444,
"s": 2432,
"text": "Output : d5"
},
{
"code": null,
"e": 2649,
"s": 2444,
"text": " When no parameter is passed: If the toString() method is called without passing any parameter then the number will be converted to string without change in BASE. Below is the program to illustrate this: "
},
{
"code": null,
"e": 2855,
"s": 2651,
"text": "When no parameter is passed: If the toString() method is called without passing any parameter then the number will be converted to string without change in BASE. Below is the program to illustrate this: "
},
{
"code": null,
"e": 2860,
"s": 2855,
"text": "html"
},
{
"code": "<script type=\"text/javascript\"> var num=213; document.write(\"Output : \" + num.toString()); </script>",
"e": 2975,
"s": 2860,
"text": null
},
{
"code": null,
"e": 2983,
"s": 2975,
"text": "Output:"
},
{
"code": null,
"e": 2991,
"s": 2983,
"text": "Output:"
},
{
"code": null,
"e": 3003,
"s": 2991,
"text": "Output :213"
},
{
"code": null,
"e": 3023,
"s": 3003,
"text": "Supported Browsers:"
},
{
"code": null,
"e": 3049,
"s": 3023,
"text": "Google Chrome 1 and above"
},
{
"code": null,
"e": 3079,
"s": 3049,
"text": "Internet Explorer 3 and above"
},
{
"code": null,
"e": 3099,
"s": 3079,
"text": "Firefox 1 and above"
},
{
"code": null,
"e": 3124,
"s": 3099,
"text": "Apple Safari 1 and above"
},
{
"code": null,
"e": 3142,
"s": 3124,
"text": "Opera 4 and above"
},
{
"code": null,
"e": 3160,
"s": 3142,
"text": "Edge 12 and above"
},
{
"code": null,
"e": 3379,
"s": 3160,
"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": 3391,
"s": 3379,
"text": "ysachin2314"
},
{
"code": null,
"e": 3408,
"s": 3391,
"text": "kumargaurav97520"
},
{
"code": null,
"e": 3427,
"s": 3408,
"text": "JavaScript-Methods"
},
{
"code": null,
"e": 3446,
"s": 3427,
"text": "JavaScript-Numbers"
},
{
"code": null,
"e": 3457,
"s": 3446,
"text": "JavaScript"
},
{
"code": null,
"e": 3474,
"s": 3457,
"text": "Web Technologies"
}
] |
Python 3 - Numbers | Number data types store numeric values. They are immutable data types. This means, changing the value of a number data type results in a newly allocated object.
Number objects are created when you assign a value to them. For example −
var1 = 1
var2 = 10
You can also delete the reference to a number object by using the del statement. The syntax of the del statement is −
del var1[,var2[,var3[....,varN]]]]
You can delete a single object or multiple objects by using the del statement. For example −
del var
del var_a, var_b
Python supports different numerical types −
int (signed integers) − They are often called just integers or ints. They are positive or negative whole numbers with no decimal point. Integers in Python 3 are of unlimited size. Python 2 has two integer types - int and long. There is no 'long integer' in Python 3 anymore.
int (signed integers) − They are often called just integers or ints. They are positive or negative whole numbers with no decimal point. Integers in Python 3 are of unlimited size. Python 2 has two integer types - int and long. There is no 'long integer' in Python 3 anymore.
float (floating point real values) − Also called floats, they represent real numbers and are written with a decimal point dividing the integer and the fractional parts. Floats may also be in scientific notation, with E or e indicating the power of 10 (2.5e2 = 2.5 x 102 = 250).
float (floating point real values) − Also called floats, they represent real numbers and are written with a decimal point dividing the integer and the fractional parts. Floats may also be in scientific notation, with E or e indicating the power of 10 (2.5e2 = 2.5 x 102 = 250).
complex (complex numbers) − are of the form a + bJ, where a and b are floats and J (or j) represents the square root of -1 (which is an imaginary number). The real part of the number is a, and the imaginary part is b. Complex numbers are not used much in Python programming.
complex (complex numbers) − are of the form a + bJ, where a and b are floats and J (or j) represents the square root of -1 (which is an imaginary number). The real part of the number is a, and the imaginary part is b. Complex numbers are not used much in Python programming.
It is possible to represent an integer in hexa-decimal or octal form
>>> number = 0xA0F #Hexa-decimal
>>> number
2575
>>> number = 0o37 #Octal
>>> number
31
Here are some examples of numbers.
A complex number consists of an ordered pair of real floating-point numbers denoted by a + bj, where a is the real part and b is the imaginary part of the complex number.
Python converts numbers internally in an expression containing mixed types to a common type for evaluation. Sometimes, you need to coerce a number explicitly from one type to another to satisfy the requirements of an operator or function parameter.
Type int(x) to convert x to a plain integer.
Type int(x) to convert x to a plain integer.
Type long(x) to convert x to a long integer.
Type long(x) to convert x to a long integer.
Type float(x) to convert x to a floating-point number.
Type float(x) to convert x to a floating-point number.
Type complex(x) to convert x to a complex number with real part x and imaginary part zero.
Type complex(x) to convert x to a complex number with real part x and imaginary part zero.
Type complex(x, y) to convert x and y to a complex number with real part x and imaginary part y. x and y are numeric expressions
Type complex(x, y) to convert x and y to a complex number with real part x and imaginary part y. x and y are numeric expressions
Python includes the following functions that perform mathematical calculations.
The absolute value of x: the (positive) distance between x and zero.
The ceiling of x: the smallest integer not less than x.
cmp(x, y)
-1 if x < y, 0 if x == y, or 1 if x > y. Deprecated in Python 3. Instead use return (x>y)-(x<y).
The exponential of x: ex
The absolute value of x.
The floor of x: the largest integer not greater than x.
The natural logarithm of x, for x > 0.
The base-10 logarithm of x for x > 0.
The largest of its arguments: the value closest to positive infinity
The smallest of its arguments: the value closest to negative infinity.
The fractional and integer parts of x in a two-item tuple. Both parts have the same sign as x. The integer part is returned as a float.
The value of x**y.
x rounded to n digits from the decimal point. Python rounds away from zero as a tie-breaker: round(0.5) is 1.0 and round(-0.5) is -1.0.
The square root of x for x > 0.
Random numbers are used for games, simulations, testing, security, and privacy applications. Python includes the following functions that are commonly used.
A random item from a list, tuple, or string.
A randomly selected element from range(start, stop, step).
A random float r, such that 0 is less than or equal to r and r is less than 1
Sets the integer starting value used in generating random numbers. Call this function before calling any other random module function. Returns None.
Randomizes the items of a list in place. Returns None.
A random float r, such that x is less than or equal to r and r is less than y.
Python includes the following functions that perform trigonometric calculations.
Return the arc cosine of x, in radians.
Return the arc sine of x, in radians.
Return the arc tangent of x, in radians.
Return atan(y / x), in radians.
Return the cosine of x radians.
Return the Euclidean norm, sqrt(x*x + y*y).
Return the sine of x radians.
Return the tangent of x radians.
Converts angle x from radians to degrees.
Converts angle x from degrees to radians.
The module also defines two mathematical constants −
pi
The mathematical constant pi.
e
The mathematical constant e.
187 Lectures
17.5 hours
Malhar Lathkar
55 Lectures
8 hours
Arnab Chakraborty
136 Lectures
11 hours
In28Minutes Official
75 Lectures
13 hours
Eduonix Learning Solutions
70 Lectures
8.5 hours
Lets Kode It
63 Lectures
6 hours
Abhilash Nelson
Print
Add Notes
Bookmark this page | [
{
"code": null,
"e": 2501,
"s": 2340,
"text": "Number data types store numeric values. They are immutable data types. This means, changing the value of a number data type results in a newly allocated object."
},
{
"code": null,
"e": 2575,
"s": 2501,
"text": "Number objects are created when you assign a value to them. For example −"
},
{
"code": null,
"e": 2594,
"s": 2575,
"text": "var1 = 1\nvar2 = 10"
},
{
"code": null,
"e": 2712,
"s": 2594,
"text": "You can also delete the reference to a number object by using the del statement. The syntax of the del statement is −"
},
{
"code": null,
"e": 2747,
"s": 2712,
"text": "del var1[,var2[,var3[....,varN]]]]"
},
{
"code": null,
"e": 2840,
"s": 2747,
"text": "You can delete a single object or multiple objects by using the del statement. For example −"
},
{
"code": null,
"e": 2865,
"s": 2840,
"text": "del var\ndel var_a, var_b"
},
{
"code": null,
"e": 2910,
"s": 2865,
"text": "Python supports different numerical types −"
},
{
"code": null,
"e": 3185,
"s": 2910,
"text": "int (signed integers) − They are often called just integers or ints. They are positive or negative whole numbers with no decimal point. Integers in Python 3 are of unlimited size. Python 2 has two integer types - int and long. There is no 'long integer' in Python 3 anymore."
},
{
"code": null,
"e": 3460,
"s": 3185,
"text": "int (signed integers) − They are often called just integers or ints. They are positive or negative whole numbers with no decimal point. Integers in Python 3 are of unlimited size. Python 2 has two integer types - int and long. There is no 'long integer' in Python 3 anymore."
},
{
"code": null,
"e": 3738,
"s": 3460,
"text": "float (floating point real values) − Also called floats, they represent real numbers and are written with a decimal point dividing the integer and the fractional parts. Floats may also be in scientific notation, with E or e indicating the power of 10 (2.5e2 = 2.5 x 102 = 250)."
},
{
"code": null,
"e": 4016,
"s": 3738,
"text": "float (floating point real values) − Also called floats, they represent real numbers and are written with a decimal point dividing the integer and the fractional parts. Floats may also be in scientific notation, with E or e indicating the power of 10 (2.5e2 = 2.5 x 102 = 250)."
},
{
"code": null,
"e": 4291,
"s": 4016,
"text": "complex (complex numbers) − are of the form a + bJ, where a and b are floats and J (or j) represents the square root of -1 (which is an imaginary number). The real part of the number is a, and the imaginary part is b. Complex numbers are not used much in Python programming."
},
{
"code": null,
"e": 4566,
"s": 4291,
"text": "complex (complex numbers) − are of the form a + bJ, where a and b are floats and J (or j) represents the square root of -1 (which is an imaginary number). The real part of the number is a, and the imaginary part is b. Complex numbers are not used much in Python programming."
},
{
"code": null,
"e": 4635,
"s": 4566,
"text": "It is possible to represent an integer in hexa-decimal or octal form"
},
{
"code": null,
"e": 4724,
"s": 4635,
"text": ">>> number = 0xA0F #Hexa-decimal\n>>> number\n2575\n\n>>> number = 0o37 #Octal\n>>> number\n31"
},
{
"code": null,
"e": 4759,
"s": 4724,
"text": "Here are some examples of numbers."
},
{
"code": null,
"e": 4930,
"s": 4759,
"text": "A complex number consists of an ordered pair of real floating-point numbers denoted by a + bj, where a is the real part and b is the imaginary part of the complex number."
},
{
"code": null,
"e": 5179,
"s": 4930,
"text": "Python converts numbers internally in an expression containing mixed types to a common type for evaluation. Sometimes, you need to coerce a number explicitly from one type to another to satisfy the requirements of an operator or function parameter."
},
{
"code": null,
"e": 5224,
"s": 5179,
"text": "Type int(x) to convert x to a plain integer."
},
{
"code": null,
"e": 5269,
"s": 5224,
"text": "Type int(x) to convert x to a plain integer."
},
{
"code": null,
"e": 5314,
"s": 5269,
"text": "Type long(x) to convert x to a long integer."
},
{
"code": null,
"e": 5359,
"s": 5314,
"text": "Type long(x) to convert x to a long integer."
},
{
"code": null,
"e": 5414,
"s": 5359,
"text": "Type float(x) to convert x to a floating-point number."
},
{
"code": null,
"e": 5469,
"s": 5414,
"text": "Type float(x) to convert x to a floating-point number."
},
{
"code": null,
"e": 5560,
"s": 5469,
"text": "Type complex(x) to convert x to a complex number with real part x and imaginary part zero."
},
{
"code": null,
"e": 5651,
"s": 5560,
"text": "Type complex(x) to convert x to a complex number with real part x and imaginary part zero."
},
{
"code": null,
"e": 5780,
"s": 5651,
"text": "Type complex(x, y) to convert x and y to a complex number with real part x and imaginary part y. x and y are numeric expressions"
},
{
"code": null,
"e": 5909,
"s": 5780,
"text": "Type complex(x, y) to convert x and y to a complex number with real part x and imaginary part y. x and y are numeric expressions"
},
{
"code": null,
"e": 5989,
"s": 5909,
"text": "Python includes the following functions that perform mathematical calculations."
},
{
"code": null,
"e": 6058,
"s": 5989,
"text": "The absolute value of x: the (positive) distance between x and zero."
},
{
"code": null,
"e": 6114,
"s": 6058,
"text": "The ceiling of x: the smallest integer not less than x."
},
{
"code": null,
"e": 6124,
"s": 6114,
"text": "cmp(x, y)"
},
{
"code": null,
"e": 6222,
"s": 6124,
"text": "-1 if x < y, 0 if x == y, or 1 if x > y. Deprecated in Python 3. Instead use return (x>y)-(x<y)."
},
{
"code": null,
"e": 6247,
"s": 6222,
"text": "The exponential of x: ex"
},
{
"code": null,
"e": 6272,
"s": 6247,
"text": "The absolute value of x."
},
{
"code": null,
"e": 6328,
"s": 6272,
"text": "The floor of x: the largest integer not greater than x."
},
{
"code": null,
"e": 6367,
"s": 6328,
"text": "The natural logarithm of x, for x > 0."
},
{
"code": null,
"e": 6405,
"s": 6367,
"text": "The base-10 logarithm of x for x > 0."
},
{
"code": null,
"e": 6474,
"s": 6405,
"text": "The largest of its arguments: the value closest to positive infinity"
},
{
"code": null,
"e": 6545,
"s": 6474,
"text": "The smallest of its arguments: the value closest to negative infinity."
},
{
"code": null,
"e": 6681,
"s": 6545,
"text": "The fractional and integer parts of x in a two-item tuple. Both parts have the same sign as x. The integer part is returned as a float."
},
{
"code": null,
"e": 6700,
"s": 6681,
"text": "The value of x**y."
},
{
"code": null,
"e": 6836,
"s": 6700,
"text": "x rounded to n digits from the decimal point. Python rounds away from zero as a tie-breaker: round(0.5) is 1.0 and round(-0.5) is -1.0."
},
{
"code": null,
"e": 6868,
"s": 6836,
"text": "The square root of x for x > 0."
},
{
"code": null,
"e": 7025,
"s": 6868,
"text": "Random numbers are used for games, simulations, testing, security, and privacy applications. Python includes the following functions that are commonly used."
},
{
"code": null,
"e": 7070,
"s": 7025,
"text": "A random item from a list, tuple, or string."
},
{
"code": null,
"e": 7129,
"s": 7070,
"text": "A randomly selected element from range(start, stop, step)."
},
{
"code": null,
"e": 7207,
"s": 7129,
"text": "A random float r, such that 0 is less than or equal to r and r is less than 1"
},
{
"code": null,
"e": 7356,
"s": 7207,
"text": "Sets the integer starting value used in generating random numbers. Call this function before calling any other random module function. Returns None."
},
{
"code": null,
"e": 7411,
"s": 7356,
"text": "Randomizes the items of a list in place. Returns None."
},
{
"code": null,
"e": 7490,
"s": 7411,
"text": "A random float r, such that x is less than or equal to r and r is less than y."
},
{
"code": null,
"e": 7571,
"s": 7490,
"text": "Python includes the following functions that perform trigonometric calculations."
},
{
"code": null,
"e": 7611,
"s": 7571,
"text": "Return the arc cosine of x, in radians."
},
{
"code": null,
"e": 7649,
"s": 7611,
"text": "Return the arc sine of x, in radians."
},
{
"code": null,
"e": 7690,
"s": 7649,
"text": "Return the arc tangent of x, in radians."
},
{
"code": null,
"e": 7722,
"s": 7690,
"text": "Return atan(y / x), in radians."
},
{
"code": null,
"e": 7754,
"s": 7722,
"text": "Return the cosine of x radians."
},
{
"code": null,
"e": 7798,
"s": 7754,
"text": "Return the Euclidean norm, sqrt(x*x + y*y)."
},
{
"code": null,
"e": 7828,
"s": 7798,
"text": "Return the sine of x radians."
},
{
"code": null,
"e": 7861,
"s": 7828,
"text": "Return the tangent of x radians."
},
{
"code": null,
"e": 7903,
"s": 7861,
"text": "Converts angle x from radians to degrees."
},
{
"code": null,
"e": 7945,
"s": 7903,
"text": "Converts angle x from degrees to radians."
},
{
"code": null,
"e": 7998,
"s": 7945,
"text": "The module also defines two mathematical constants −"
},
{
"code": null,
"e": 8001,
"s": 7998,
"text": "pi"
},
{
"code": null,
"e": 8031,
"s": 8001,
"text": "The mathematical constant pi."
},
{
"code": null,
"e": 8033,
"s": 8031,
"text": "e"
},
{
"code": null,
"e": 8062,
"s": 8033,
"text": "The mathematical constant e."
},
{
"code": null,
"e": 8099,
"s": 8062,
"text": "\n 187 Lectures \n 17.5 hours \n"
},
{
"code": null,
"e": 8115,
"s": 8099,
"text": " Malhar Lathkar"
},
{
"code": null,
"e": 8148,
"s": 8115,
"text": "\n 55 Lectures \n 8 hours \n"
},
{
"code": null,
"e": 8167,
"s": 8148,
"text": " Arnab Chakraborty"
},
{
"code": null,
"e": 8202,
"s": 8167,
"text": "\n 136 Lectures \n 11 hours \n"
},
{
"code": null,
"e": 8224,
"s": 8202,
"text": " In28Minutes Official"
},
{
"code": null,
"e": 8258,
"s": 8224,
"text": "\n 75 Lectures \n 13 hours \n"
},
{
"code": null,
"e": 8286,
"s": 8258,
"text": " Eduonix Learning Solutions"
},
{
"code": null,
"e": 8321,
"s": 8286,
"text": "\n 70 Lectures \n 8.5 hours \n"
},
{
"code": null,
"e": 8335,
"s": 8321,
"text": " Lets Kode It"
},
{
"code": null,
"e": 8368,
"s": 8335,
"text": "\n 63 Lectures \n 6 hours \n"
},
{
"code": null,
"e": 8385,
"s": 8368,
"text": " Abhilash Nelson"
},
{
"code": null,
"e": 8392,
"s": 8385,
"text": " Print"
},
{
"code": null,
"e": 8403,
"s": 8392,
"text": " Add Notes"
}
] |
Find four elements a, b, c and d in an array such that a+b = c+d - GeeksforGeeks | 08 Aug, 2021
Given an array of distinct integers, find if there are two pairs (a, b) and (c, d) such that a+b = c+d, and a, b, c and d are distinct elements. If there are multiple answers, then print any of them.
Example:
Input: {3, 4, 7, 1, 2, 9, 8}
Output: (3, 8) and (4, 7)
Explanation: 3+8 = 4+7
Input: {3, 4, 7, 1, 12, 9};
Output: (4, 12) and (7, 9)
Explanation: 4+12 = 7+9
Input: {65, 30, 7, 90, 1, 9, 8};
Output: No pairs found
Expected Time Complexity: O(n2)
A Simple Solution is to run four loops to generate all possible quadruples of the array elements. For every quadruple (a, b, c, d), check if (a+b) = (c+d). The time complexity of this solution is O(n4).An Efficient Solution can solve this problem in O(n2) time. The idea is to use hashing. We use sum as key and pair as the value in the hash table.
Loop i = 0 to n-1 :
Loop j = i + 1 to n-1 :
calculate sum
If in hash table any index already exist
Then print (i, j) and previous pair
from hash table
Else update hash table
EndLoop;
EndLoop;
Below are implementations of the above idea. In the below implementation, the map is used instead of a hash. The time complexity of map insert and search is actually O(Log n) instead of O(1). So below implementation is O(n2 Log n).
C++
Java
Python3
C#
Javascript
// Find four different elements a,b,c and d of array such that// a+b = c+d#include<bits/stdc++.h>using namespace std; bool findPairs(int arr[], int n){ // Create an empty Hash to store mapping from sum to // pair indexes map<int, pair<int, int> > Hash; // Traverse through all possible pairs of arr[] for (int i = 0; i < n; ++i) { for (int j = i + 1; j < n; ++j) { // If sum of current pair is not in hash, // then store it and continue to next pair int sum = arr[i] + arr[j]; if (Hash.find(sum) == Hash.end()) Hash[sum] = make_pair(i, j); else // Else (Sum already present in hash) { // Find previous pair pair<int, int> pp = Hash[sum];// pp->previous pair // Since array elements are distinct, we don't // need to check if any element is common among pairs cout << "(" << arr[pp.first] << ", " << arr[pp.second] << ") and (" << arr[i] << ", " << arr[j] << ")n"; return true; } } } cout << "No pairs found"; return false;} // Driver programint main(){ int arr[] = {3, 4, 7, 1, 2, 9, 8}; int n = sizeof arr / sizeof arr[0]; findPairs(arr, n); return 0;}
// Java Program to find four different elements a,b,c and d of// array such that a+b = c+dimport java.io.*;import java.util.*; class ArrayElements{ // Class to represent a pair class pair { int first, second; pair(int f,int s) { first = f; second = s; } }; boolean findPairs(int arr[]) { // Create an empty Hash to store mapping from sum to // pair indexes HashMap<Integer,pair> map = new HashMap<Integer,pair>(); int n=arr.length; // Traverse through all possible pairs of arr[] for (int i=0; i<n; ++i) { for (int j=i+1; j<n; ++j) { // If sum of current pair is not in hash, // then store it and continue to next pair int sum = arr[i]+arr[j]; if (!map.containsKey(sum)) map.put(sum,new pair(i,j)); else // Else (Sum already present in hash) { // Find previous pair pair p = map.get(sum); // Since array elements are distinct, we don't // need to check if any element is common among pairs System.out.println("("+arr[p.first]+", "+arr[p.second]+ ") and ("+arr[i]+", "+arr[j]+")"); return true; } } } return false; } // Testing program public static void main(String args[]) { int arr[] = {3, 4, 7, 1, 2, 9, 8}; ArrayElements a = new ArrayElements(); a.findPairs(arr); }}// This code is contributed by Aakash Hasija
# Python Program to find four different elements a,b,c and d of# array such that a+b = c+d # function to find a, b, c, d such that# (a + b) = (c + d) def find_pair_of_sum(arr: list, n: int): map = {} for i in range(n): for j in range(i+1, n): sum = arr[i] + arr[j] if sum in map: print(f"{map[sum]} and ({arr[i]}, {arr[j]})") return else: map[sum] = (arr[i], arr[j]) # Driver codeif __name__ == "__main__": arr = [3, 4, 7, 1, 2, 9, 8] n = len(arr) find_pair_of_sum(arr, n)
using System;using System.Collections.Generic; // C# Program to find four different elements a,b,c and d of// array such that a+b = c+d public class ArrayElements{ // Class to represent a pair public class pair { private readonly ArrayElements outerInstance; public int first, second; public pair(ArrayElements outerInstance, int f, int s) { this.outerInstance = outerInstance; first = f; second = s; } } public virtual bool findPairs(int[] arr) { // Create an empty Hash to store mapping from sum to // pair indexes Dictionary<int, pair> map = new Dictionary<int, pair>(); int n = arr.Length; // Traverse through all possible pairs of arr[] for (int i = 0; i < n; ++i) { for (int j = i + 1; j < n; ++j) { // If sum of current pair is not in hash, // then store it and continue to next pair int sum = arr[i] + arr[j]; if (!map.ContainsKey(sum)) { map[sum] = new pair(this, i,j); } else // Else (Sum already present in hash) { // Find previous pair pair p = map[sum]; // Since array elements are distinct, we don't // need to check if any element is common among pairs Console.WriteLine("(" + arr[p.first] + ", " + arr[p.second] + ") and (" + arr[i] + ", " + arr[j] + ")"); return true; } } } return false; } // Testing program public static void Main(string[] args) { int[] arr = new int[] {3, 4, 7, 1, 2, 9, 8}; ArrayElements a = new ArrayElements(); a.findPairs(arr); }} // This code is contributed by Shrikant13
<script>// Find four different elements a,b,c and d of array such that// a+b = c+d function findPairs(arr, n) { // Create an empty Hash to store mapping from sum to // pair indexes let Hash = new Map(); // Traverse through all possible pairs of arr[] for (let i = 0; i < n; ++i) { for (let j = i + 1; j < n; ++j) { // If sum of current pair is not in hash, // then store it and continue to next pair let sum = arr[i] + arr[j]; if (!Hash.has(sum)) Hash.set(sum, [i, j]); else // Else (Sum already present in hash) { // Find previous pair let pp = Hash.get(sum);// pp->previous pair // Since array elements are distinct, we don't // need to check if any element is common among pairs document.write("(" + arr[pp[0]] + ", " + arr[pp[1]] + ") and (" + arr[i] + ", " + arr[j] + ")"); return true; } } } document.write("No pairs found"); return false;} // Driver program let arr = [3, 4, 7, 1, 2, 9, 8];let n = arr.lengthfindPairs(arr, n);</script>
Output:
(3, 8) and (4, 7)
Thanks to Gaurav Ahirwar for suggesting above solutions.Exercise: 1) Extend the above solution with duplicates allowed in array. 2) Further extend the solution to print all quadruples in output instead of just one. And all quadruples should be printed printed in lexicographical order (smaller values before greater ones). Assume we have two solutions S1 and S2.
S1 : a1 b1 c1 d1 ( these are values of indices int the array )
S2 : a2 b2 c2 d2
S1 is lexicographically smaller than S2 iff
a1 < a2 OR
a1 = a2 AND b1 < b2 OR
a1 = a2 AND b1 = b2 AND c1 < c2 OR
a1 = a2 AND b1 = b2 AND c1 = c2 AND d1 < d2
See this for solution of exercise.Related Article : Find all pairs (a,b) and (c,d) in array which satisfy ab = cdPlease write comments if you find anything incorrect, or you want to share more information about the topic discussed above
shrikanth13
gfgking
shindesharad71
Amazon
Arrays
Hash
Amazon
Arrays
Hash
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Stack Data Structure (Introduction and Program)
Top 50 Array Coding Problems for Interviews
Introduction to Arrays
Multidimensional Arrays in Java
Linear Search
Given an array A[] and a number x, check for pair in A[] with sum as x (aka Two Sum)
Internal Working of HashMap in Java
Hashing | Set 1 (Introduction)
Count pairs with given sum
Hashing | Set 3 (Open Addressing) | [
{
"code": null,
"e": 24171,
"s": 24143,
"text": "\n08 Aug, 2021"
},
{
"code": null,
"e": 24372,
"s": 24171,
"text": "Given an array of distinct integers, find if there are two pairs (a, b) and (c, d) such that a+b = c+d, and a, b, c and d are distinct elements. If there are multiple answers, then print any of them. "
},
{
"code": null,
"e": 24382,
"s": 24372,
"text": "Example: "
},
{
"code": null,
"e": 24605,
"s": 24382,
"text": "Input: {3, 4, 7, 1, 2, 9, 8}\nOutput: (3, 8) and (4, 7)\nExplanation: 3+8 = 4+7\n\nInput: {3, 4, 7, 1, 12, 9};\nOutput: (4, 12) and (7, 9)\nExplanation: 4+12 = 7+9\n\nInput: {65, 30, 7, 90, 1, 9, 8};\nOutput: No pairs found"
},
{
"code": null,
"e": 24638,
"s": 24605,
"text": "Expected Time Complexity: O(n2) "
},
{
"code": null,
"e": 24989,
"s": 24638,
"text": "A Simple Solution is to run four loops to generate all possible quadruples of the array elements. For every quadruple (a, b, c, d), check if (a+b) = (c+d). The time complexity of this solution is O(n4).An Efficient Solution can solve this problem in O(n2) time. The idea is to use hashing. We use sum as key and pair as the value in the hash table. "
},
{
"code": null,
"e": 25240,
"s": 24989,
"text": "Loop i = 0 to n-1 :\n Loop j = i + 1 to n-1 :\n calculate sum\n If in hash table any index already exist\n Then print (i, j) and previous pair \n from hash table \n Else update hash table\n EndLoop;\nEndLoop;"
},
{
"code": null,
"e": 25472,
"s": 25240,
"text": "Below are implementations of the above idea. In the below implementation, the map is used instead of a hash. The time complexity of map insert and search is actually O(Log n) instead of O(1). So below implementation is O(n2 Log n)."
},
{
"code": null,
"e": 25476,
"s": 25472,
"text": "C++"
},
{
"code": null,
"e": 25481,
"s": 25476,
"text": "Java"
},
{
"code": null,
"e": 25489,
"s": 25481,
"text": "Python3"
},
{
"code": null,
"e": 25492,
"s": 25489,
"text": "C#"
},
{
"code": null,
"e": 25503,
"s": 25492,
"text": "Javascript"
},
{
"code": "// Find four different elements a,b,c and d of array such that// a+b = c+d#include<bits/stdc++.h>using namespace std; bool findPairs(int arr[], int n){ // Create an empty Hash to store mapping from sum to // pair indexes map<int, pair<int, int> > Hash; // Traverse through all possible pairs of arr[] for (int i = 0; i < n; ++i) { for (int j = i + 1; j < n; ++j) { // If sum of current pair is not in hash, // then store it and continue to next pair int sum = arr[i] + arr[j]; if (Hash.find(sum) == Hash.end()) Hash[sum] = make_pair(i, j); else // Else (Sum already present in hash) { // Find previous pair pair<int, int> pp = Hash[sum];// pp->previous pair // Since array elements are distinct, we don't // need to check if any element is common among pairs cout << \"(\" << arr[pp.first] << \", \" << arr[pp.second] << \") and (\" << arr[i] << \", \" << arr[j] << \")n\"; return true; } } } cout << \"No pairs found\"; return false;} // Driver programint main(){ int arr[] = {3, 4, 7, 1, 2, 9, 8}; int n = sizeof arr / sizeof arr[0]; findPairs(arr, n); return 0;}",
"e": 26822,
"s": 25503,
"text": null
},
{
"code": "// Java Program to find four different elements a,b,c and d of// array such that a+b = c+dimport java.io.*;import java.util.*; class ArrayElements{ // Class to represent a pair class pair { int first, second; pair(int f,int s) { first = f; second = s; } }; boolean findPairs(int arr[]) { // Create an empty Hash to store mapping from sum to // pair indexes HashMap<Integer,pair> map = new HashMap<Integer,pair>(); int n=arr.length; // Traverse through all possible pairs of arr[] for (int i=0; i<n; ++i) { for (int j=i+1; j<n; ++j) { // If sum of current pair is not in hash, // then store it and continue to next pair int sum = arr[i]+arr[j]; if (!map.containsKey(sum)) map.put(sum,new pair(i,j)); else // Else (Sum already present in hash) { // Find previous pair pair p = map.get(sum); // Since array elements are distinct, we don't // need to check if any element is common among pairs System.out.println(\"(\"+arr[p.first]+\", \"+arr[p.second]+ \") and (\"+arr[i]+\", \"+arr[j]+\")\"); return true; } } } return false; } // Testing program public static void main(String args[]) { int arr[] = {3, 4, 7, 1, 2, 9, 8}; ArrayElements a = new ArrayElements(); a.findPairs(arr); }}// This code is contributed by Aakash Hasija",
"e": 28506,
"s": 26822,
"text": null
},
{
"code": "# Python Program to find four different elements a,b,c and d of# array such that a+b = c+d # function to find a, b, c, d such that# (a + b) = (c + d) def find_pair_of_sum(arr: list, n: int): map = {} for i in range(n): for j in range(i+1, n): sum = arr[i] + arr[j] if sum in map: print(f\"{map[sum]} and ({arr[i]}, {arr[j]})\") return else: map[sum] = (arr[i], arr[j]) # Driver codeif __name__ == \"__main__\": arr = [3, 4, 7, 1, 2, 9, 8] n = len(arr) find_pair_of_sum(arr, n)",
"e": 29083,
"s": 28506,
"text": null
},
{
"code": "using System;using System.Collections.Generic; // C# Program to find four different elements a,b,c and d of// array such that a+b = c+d public class ArrayElements{ // Class to represent a pair public class pair { private readonly ArrayElements outerInstance; public int first, second; public pair(ArrayElements outerInstance, int f, int s) { this.outerInstance = outerInstance; first = f; second = s; } } public virtual bool findPairs(int[] arr) { // Create an empty Hash to store mapping from sum to // pair indexes Dictionary<int, pair> map = new Dictionary<int, pair>(); int n = arr.Length; // Traverse through all possible pairs of arr[] for (int i = 0; i < n; ++i) { for (int j = i + 1; j < n; ++j) { // If sum of current pair is not in hash, // then store it and continue to next pair int sum = arr[i] + arr[j]; if (!map.ContainsKey(sum)) { map[sum] = new pair(this, i,j); } else // Else (Sum already present in hash) { // Find previous pair pair p = map[sum]; // Since array elements are distinct, we don't // need to check if any element is common among pairs Console.WriteLine(\"(\" + arr[p.first] + \", \" + arr[p.second] + \") and (\" + arr[i] + \", \" + arr[j] + \")\"); return true; } } } return false; } // Testing program public static void Main(string[] args) { int[] arr = new int[] {3, 4, 7, 1, 2, 9, 8}; ArrayElements a = new ArrayElements(); a.findPairs(arr); }} // This code is contributed by Shrikant13",
"e": 30990,
"s": 29083,
"text": null
},
{
"code": "<script>// Find four different elements a,b,c and d of array such that// a+b = c+d function findPairs(arr, n) { // Create an empty Hash to store mapping from sum to // pair indexes let Hash = new Map(); // Traverse through all possible pairs of arr[] for (let i = 0; i < n; ++i) { for (let j = i + 1; j < n; ++j) { // If sum of current pair is not in hash, // then store it and continue to next pair let sum = arr[i] + arr[j]; if (!Hash.has(sum)) Hash.set(sum, [i, j]); else // Else (Sum already present in hash) { // Find previous pair let pp = Hash.get(sum);// pp->previous pair // Since array elements are distinct, we don't // need to check if any element is common among pairs document.write(\"(\" + arr[pp[0]] + \", \" + arr[pp[1]] + \") and (\" + arr[i] + \", \" + arr[j] + \")\"); return true; } } } document.write(\"No pairs found\"); return false;} // Driver program let arr = [3, 4, 7, 1, 2, 9, 8];let n = arr.lengthfindPairs(arr, n);</script>",
"e": 32158,
"s": 30990,
"text": null
},
{
"code": null,
"e": 32168,
"s": 32158,
"text": "Output: "
},
{
"code": null,
"e": 32186,
"s": 32168,
"text": "(3, 8) and (4, 7)"
},
{
"code": null,
"e": 32551,
"s": 32186,
"text": "Thanks to Gaurav Ahirwar for suggesting above solutions.Exercise: 1) Extend the above solution with duplicates allowed in array. 2) Further extend the solution to print all quadruples in output instead of just one. And all quadruples should be printed printed in lexicographical order (smaller values before greater ones). Assume we have two solutions S1 and S2. "
},
{
"code": null,
"e": 32801,
"s": 32551,
"text": "S1 : a1 b1 c1 d1 ( these are values of indices int the array ) \nS2 : a2 b2 c2 d2\n\nS1 is lexicographically smaller than S2 iff\n a1 < a2 OR\n a1 = a2 AND b1 < b2 OR\n a1 = a2 AND b1 = b2 AND c1 < c2 OR \n a1 = a2 AND b1 = b2 AND c1 = c2 AND d1 < d2 "
},
{
"code": null,
"e": 33039,
"s": 32801,
"text": "See this for solution of exercise.Related Article : Find all pairs (a,b) and (c,d) in array which satisfy ab = cdPlease write comments if you find anything incorrect, or you want to share more information about the topic discussed above "
},
{
"code": null,
"e": 33051,
"s": 33039,
"text": "shrikanth13"
},
{
"code": null,
"e": 33059,
"s": 33051,
"text": "gfgking"
},
{
"code": null,
"e": 33074,
"s": 33059,
"text": "shindesharad71"
},
{
"code": null,
"e": 33081,
"s": 33074,
"text": "Amazon"
},
{
"code": null,
"e": 33088,
"s": 33081,
"text": "Arrays"
},
{
"code": null,
"e": 33093,
"s": 33088,
"text": "Hash"
},
{
"code": null,
"e": 33100,
"s": 33093,
"text": "Amazon"
},
{
"code": null,
"e": 33107,
"s": 33100,
"text": "Arrays"
},
{
"code": null,
"e": 33112,
"s": 33107,
"text": "Hash"
},
{
"code": null,
"e": 33210,
"s": 33112,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 33219,
"s": 33210,
"text": "Comments"
},
{
"code": null,
"e": 33232,
"s": 33219,
"text": "Old Comments"
},
{
"code": null,
"e": 33280,
"s": 33232,
"text": "Stack Data Structure (Introduction and Program)"
},
{
"code": null,
"e": 33324,
"s": 33280,
"text": "Top 50 Array Coding Problems for Interviews"
},
{
"code": null,
"e": 33347,
"s": 33324,
"text": "Introduction to Arrays"
},
{
"code": null,
"e": 33379,
"s": 33347,
"text": "Multidimensional Arrays in Java"
},
{
"code": null,
"e": 33393,
"s": 33379,
"text": "Linear Search"
},
{
"code": null,
"e": 33478,
"s": 33393,
"text": "Given an array A[] and a number x, check for pair in A[] with sum as x (aka Two Sum)"
},
{
"code": null,
"e": 33514,
"s": 33478,
"text": "Internal Working of HashMap in Java"
},
{
"code": null,
"e": 33545,
"s": 33514,
"text": "Hashing | Set 1 (Introduction)"
},
{
"code": null,
"e": 33572,
"s": 33545,
"text": "Count pairs with given sum"
}
] |
CRLFuzz - A Linux Tool To Scan CRLF Vulnerability Written in Go - GeeksforGeeks | 14 Sep, 2021
CRLF injection is a software application coding vulnerability that occurs when an attacker injects a CRLF character sequence where it is not expected. Checking the CRLF Vulnerability manually on the target domain becomes very complicated. So there should be an automated approach for studying the vulnerability. CRLFuzz is a computerized tool designed in the Golang language that scans the CRLF Vulnerability target with a single click. CRLFuzz tool is open-source and free to use.
Note: As CRLFuzz is a Golang language-based tool, so you need to have a Golang environment on your system. So check this link to Install Golang in your system. – Installation of Go Lang in Linux
Step 1: If you have downloaded Golang in your system, verify the installation by checking the version of Golang, use the following command.
go version
Step 2: Open up your Kali Linux terminal and move to Desktop using the following command.
cd Desktop
Step 3: You are on Desktop now create a new directory called CRLFuzz using the following command. In this directory, we will complete the installation of the CRLFuzz tool.
mkdir CRLFuzz
Step 4: Now switch to the CRLFuzz directory using the following command.
cd CRLFuzz
Step 5: Now you have to install the tool. You have to clone the tool from GitHub.
git clone https://github.com/dwisiswant0/crlfuzz
Step 6: The tool has been downloaded successfully in the CRLFuzz directory. Now list out the contents of the tool by using the below command.
ls
Step 7: You can observe that there is a new directory created of the CRLFuzz tool that has been generated while we were installing the tool. Now move to that directory using the below command:
cd crlfuzz/cmd/crlfuzz
Step 8: Build the tool using the following command.
go build
Step 9: Move the tool in /bin directory for quick usage from anywhere.
mv crlfuzz /usr/local/bin
Step 10: Now we are done with our installation, Use the below command to view the help (gives a better understanding of tool) index of the tool.
crlfuzz -h
Example 1: Single URL
crlfuzz -u "http://geeksforgeeks.org"
In this example, we will be performing a CRLF Vulnerability scan on our target domain geeksforgeeks.org. -u tag is used to specify the domain URL.
Example 2: GET Method
crlfuzz -u "http://geeksforgeeks.org" -X "GET"
In this example, we will be changing the method of Scan from POST to GET method. -X tag is used to specify the method of the scan.
Example 3: Silent
crlfuzz -u "http://geeksforgeeks.org" -s
In this example, we will be performing a silent scan. In Silent Scan only the vulnerable targets will be displayed. As geeksforgeeks.org is a secure Website, the tool has not detected any vulnerable target.
Example 4: Verbose
crlfuzz -u "http://geeksforgeeks.org" -v
1. In this example, we will be displaying the verbose or detailed output of our scan. -v tag is used to display output in verbose mode.
2. In the below Screenshot, we have got the detailed reason why the query was not executed on the geeksforgeeks.org target.
Example 5: Version
crlfuzz -V
In this example, we will be displaying the version of the CRLFuzz tool. -V tag is used to display the version of the tool.
Example 6: URLs from a list
crlfuzz -l target.txt
1. In this Example, we are scanning the targets from the text file. In the below Screenshot, We have displayed the targets.txt file.
2. In the below Screenshot, we have got the results of our Scan.
Example 7: From Stdin
sublist3r -d geeksforgeeks.org | crlfuzz
In this example, We are using the crlfuzz tool with the sublist3r tool.
Example 8: Data
crlfuzz -u "http://geeksforgeeks.org" -X "POST" -d "data=body"
In this example, we are using the -d tag for using the custom data.
Example 9: Adding Headers
crlfuzz -u “http://geeksforgeeks.org” -H “authtoken:dba9cad7701495309c43f93e6bd1b3d2”
In this Example, we are adding the Header to the request by using the -H tag.
Example 10: Using Proxy
crlfuzz -u "http://geeksforgeeks.org" -x http://127.0.0.1:8080
In this example, we are using the proxy server specified in the -x tag.
Example 11: Concurrency
crlfuzz -l target.txt -c 50
In this example, we are changing the concurrency value. Concurrency is the number of fuzzing at the same time
Example 12: Output
crlfuzz -l target.txt -o results.txt
In this Example, we are saving the results in the text file. We have used the -o tag for saving the results.
In the below Screenshot, we are displaying the results .txt file.
Example 13: Library
go run library.go
1. In this example, we are using CRLFuzz as a library.
2. In the below Screenshot, we are running the file.
Kali-Linux
Linux-Tools
Linux-Unix
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
scp command in Linux with Examples
nohup Command in Linux with Examples
mv command in Linux with examples
Thread functions in C/C++
Docker - COPY Instruction
chown command in Linux with Examples
nslookup command in Linux with Examples
SED command in Linux | Set 2
Named Pipe or FIFO with example C program
uniq Command in LINUX with examples | [
{
"code": null,
"e": 24015,
"s": 23987,
"text": "\n14 Sep, 2021"
},
{
"code": null,
"e": 24498,
"s": 24015,
"text": "CRLF injection is a software application coding vulnerability that occurs when an attacker injects a CRLF character sequence where it is not expected. Checking the CRLF Vulnerability manually on the target domain becomes very complicated. So there should be an automated approach for studying the vulnerability. CRLFuzz is a computerized tool designed in the Golang language that scans the CRLF Vulnerability target with a single click. CRLFuzz tool is open-source and free to use. "
},
{
"code": null,
"e": 24694,
"s": 24498,
"text": "Note: As CRLFuzz is a Golang language-based tool, so you need to have a Golang environment on your system. So check this link to Install Golang in your system. – Installation of Go Lang in Linux"
},
{
"code": null,
"e": 24834,
"s": 24694,
"text": "Step 1: If you have downloaded Golang in your system, verify the installation by checking the version of Golang, use the following command."
},
{
"code": null,
"e": 24845,
"s": 24834,
"text": "go version"
},
{
"code": null,
"e": 24935,
"s": 24845,
"text": "Step 2: Open up your Kali Linux terminal and move to Desktop using the following command."
},
{
"code": null,
"e": 24946,
"s": 24935,
"text": "cd Desktop"
},
{
"code": null,
"e": 25118,
"s": 24946,
"text": "Step 3: You are on Desktop now create a new directory called CRLFuzz using the following command. In this directory, we will complete the installation of the CRLFuzz tool."
},
{
"code": null,
"e": 25133,
"s": 25118,
"text": "mkdir CRLFuzz "
},
{
"code": null,
"e": 25206,
"s": 25133,
"text": "Step 4: Now switch to the CRLFuzz directory using the following command."
},
{
"code": null,
"e": 25218,
"s": 25206,
"text": "cd CRLFuzz "
},
{
"code": null,
"e": 25300,
"s": 25218,
"text": "Step 5: Now you have to install the tool. You have to clone the tool from GitHub."
},
{
"code": null,
"e": 25349,
"s": 25300,
"text": "git clone https://github.com/dwisiswant0/crlfuzz"
},
{
"code": null,
"e": 25491,
"s": 25349,
"text": "Step 6: The tool has been downloaded successfully in the CRLFuzz directory. Now list out the contents of the tool by using the below command."
},
{
"code": null,
"e": 25494,
"s": 25491,
"text": "ls"
},
{
"code": null,
"e": 25687,
"s": 25494,
"text": "Step 7: You can observe that there is a new directory created of the CRLFuzz tool that has been generated while we were installing the tool. Now move to that directory using the below command:"
},
{
"code": null,
"e": 25710,
"s": 25687,
"text": "cd crlfuzz/cmd/crlfuzz"
},
{
"code": null,
"e": 25762,
"s": 25710,
"text": "Step 8: Build the tool using the following command."
},
{
"code": null,
"e": 25771,
"s": 25762,
"text": "go build"
},
{
"code": null,
"e": 25842,
"s": 25771,
"text": "Step 9: Move the tool in /bin directory for quick usage from anywhere."
},
{
"code": null,
"e": 25868,
"s": 25842,
"text": "mv crlfuzz /usr/local/bin"
},
{
"code": null,
"e": 26013,
"s": 25868,
"text": "Step 10: Now we are done with our installation, Use the below command to view the help (gives a better understanding of tool) index of the tool."
},
{
"code": null,
"e": 26024,
"s": 26013,
"text": "crlfuzz -h"
},
{
"code": null,
"e": 26046,
"s": 26024,
"text": "Example 1: Single URL"
},
{
"code": null,
"e": 26084,
"s": 26046,
"text": "crlfuzz -u \"http://geeksforgeeks.org\""
},
{
"code": null,
"e": 26231,
"s": 26084,
"text": "In this example, we will be performing a CRLF Vulnerability scan on our target domain geeksforgeeks.org. -u tag is used to specify the domain URL."
},
{
"code": null,
"e": 26253,
"s": 26231,
"text": "Example 2: GET Method"
},
{
"code": null,
"e": 26300,
"s": 26253,
"text": "crlfuzz -u \"http://geeksforgeeks.org\" -X \"GET\""
},
{
"code": null,
"e": 26431,
"s": 26300,
"text": "In this example, we will be changing the method of Scan from POST to GET method. -X tag is used to specify the method of the scan."
},
{
"code": null,
"e": 26449,
"s": 26431,
"text": "Example 3: Silent"
},
{
"code": null,
"e": 26490,
"s": 26449,
"text": "crlfuzz -u \"http://geeksforgeeks.org\" -s"
},
{
"code": null,
"e": 26698,
"s": 26490,
"text": "In this example, we will be performing a silent scan. In Silent Scan only the vulnerable targets will be displayed. As geeksforgeeks.org is a secure Website, the tool has not detected any vulnerable target. "
},
{
"code": null,
"e": 26717,
"s": 26698,
"text": "Example 4: Verbose"
},
{
"code": null,
"e": 26758,
"s": 26717,
"text": "crlfuzz -u \"http://geeksforgeeks.org\" -v"
},
{
"code": null,
"e": 26894,
"s": 26758,
"text": "1. In this example, we will be displaying the verbose or detailed output of our scan. -v tag is used to display output in verbose mode."
},
{
"code": null,
"e": 27018,
"s": 26894,
"text": "2. In the below Screenshot, we have got the detailed reason why the query was not executed on the geeksforgeeks.org target."
},
{
"code": null,
"e": 27037,
"s": 27018,
"text": "Example 5: Version"
},
{
"code": null,
"e": 27048,
"s": 27037,
"text": "crlfuzz -V"
},
{
"code": null,
"e": 27171,
"s": 27048,
"text": "In this example, we will be displaying the version of the CRLFuzz tool. -V tag is used to display the version of the tool."
},
{
"code": null,
"e": 27199,
"s": 27171,
"text": "Example 6: URLs from a list"
},
{
"code": null,
"e": 27221,
"s": 27199,
"text": "crlfuzz -l target.txt"
},
{
"code": null,
"e": 27354,
"s": 27221,
"text": "1. In this Example, we are scanning the targets from the text file. In the below Screenshot, We have displayed the targets.txt file."
},
{
"code": null,
"e": 27419,
"s": 27354,
"text": "2. In the below Screenshot, we have got the results of our Scan."
},
{
"code": null,
"e": 27441,
"s": 27419,
"text": "Example 7: From Stdin"
},
{
"code": null,
"e": 27482,
"s": 27441,
"text": "sublist3r -d geeksforgeeks.org | crlfuzz"
},
{
"code": null,
"e": 27554,
"s": 27482,
"text": "In this example, We are using the crlfuzz tool with the sublist3r tool."
},
{
"code": null,
"e": 27570,
"s": 27554,
"text": "Example 8: Data"
},
{
"code": null,
"e": 27633,
"s": 27570,
"text": "crlfuzz -u \"http://geeksforgeeks.org\" -X \"POST\" -d \"data=body\""
},
{
"code": null,
"e": 27701,
"s": 27633,
"text": "In this example, we are using the -d tag for using the custom data."
},
{
"code": null,
"e": 27727,
"s": 27701,
"text": "Example 9: Adding Headers"
},
{
"code": null,
"e": 27813,
"s": 27727,
"text": "crlfuzz -u “http://geeksforgeeks.org” -H “authtoken:dba9cad7701495309c43f93e6bd1b3d2”"
},
{
"code": null,
"e": 27891,
"s": 27813,
"text": "In this Example, we are adding the Header to the request by using the -H tag."
},
{
"code": null,
"e": 27915,
"s": 27891,
"text": "Example 10: Using Proxy"
},
{
"code": null,
"e": 27978,
"s": 27915,
"text": "crlfuzz -u \"http://geeksforgeeks.org\" -x http://127.0.0.1:8080"
},
{
"code": null,
"e": 28050,
"s": 27978,
"text": "In this example, we are using the proxy server specified in the -x tag."
},
{
"code": null,
"e": 28074,
"s": 28050,
"text": "Example 11: Concurrency"
},
{
"code": null,
"e": 28102,
"s": 28074,
"text": "crlfuzz -l target.txt -c 50"
},
{
"code": null,
"e": 28212,
"s": 28102,
"text": "In this example, we are changing the concurrency value. Concurrency is the number of fuzzing at the same time"
},
{
"code": null,
"e": 28231,
"s": 28212,
"text": "Example 12: Output"
},
{
"code": null,
"e": 28268,
"s": 28231,
"text": "crlfuzz -l target.txt -o results.txt"
},
{
"code": null,
"e": 28377,
"s": 28268,
"text": "In this Example, we are saving the results in the text file. We have used the -o tag for saving the results."
},
{
"code": null,
"e": 28443,
"s": 28377,
"text": "In the below Screenshot, we are displaying the results .txt file."
},
{
"code": null,
"e": 28463,
"s": 28443,
"text": "Example 13: Library"
},
{
"code": null,
"e": 28481,
"s": 28463,
"text": "go run library.go"
},
{
"code": null,
"e": 28536,
"s": 28481,
"text": "1. In this example, we are using CRLFuzz as a library."
},
{
"code": null,
"e": 28589,
"s": 28536,
"text": "2. In the below Screenshot, we are running the file."
},
{
"code": null,
"e": 28600,
"s": 28589,
"text": "Kali-Linux"
},
{
"code": null,
"e": 28612,
"s": 28600,
"text": "Linux-Tools"
},
{
"code": null,
"e": 28623,
"s": 28612,
"text": "Linux-Unix"
},
{
"code": null,
"e": 28721,
"s": 28623,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 28730,
"s": 28721,
"text": "Comments"
},
{
"code": null,
"e": 28743,
"s": 28730,
"text": "Old Comments"
},
{
"code": null,
"e": 28778,
"s": 28743,
"text": "scp command in Linux with Examples"
},
{
"code": null,
"e": 28815,
"s": 28778,
"text": "nohup Command in Linux with Examples"
},
{
"code": null,
"e": 28849,
"s": 28815,
"text": "mv command in Linux with examples"
},
{
"code": null,
"e": 28875,
"s": 28849,
"text": "Thread functions in C/C++"
},
{
"code": null,
"e": 28901,
"s": 28875,
"text": "Docker - COPY Instruction"
},
{
"code": null,
"e": 28938,
"s": 28901,
"text": "chown command in Linux with Examples"
},
{
"code": null,
"e": 28978,
"s": 28938,
"text": "nslookup command in Linux with Examples"
},
{
"code": null,
"e": 29007,
"s": 28978,
"text": "SED command in Linux | Set 2"
},
{
"code": null,
"e": 29049,
"s": 29007,
"text": "Named Pipe or FIFO with example C program"
}
] |
Auxiliary Space with Recursive Functions in C Program? | Here we will see how the auxiliary space is required for recursive function call. And how it is differing from the normal function call?
Suppose we have one function like below −
long fact(int n){
if(n == 0 || n == 1)
return 1;
return n * fact(n-1);
}
This function is recursive function. When we call it like fact(5), then it will store addresses inside the stack like below −
fact(5) --->
fact(4) --->
fact(3) --->
fact(2) --->
fact(1)
As the recursive functions are calling itself again and again, addresses are added into stack. So if the function is called n times recursively, it will take O(n) auxiliary space. But that does not mean that if one normal function is called n times, the space complexity will be O(n). For normal function when it is called, the address is pushed into the stack. After that when it is completed, it will pop address from stack and come into the invoker function. Then call again. So it will be O(1). | [
{
"code": null,
"e": 1199,
"s": 1062,
"text": "Here we will see how the auxiliary space is required for recursive function call. And how it is differing from the normal function call?"
},
{
"code": null,
"e": 1241,
"s": 1199,
"text": "Suppose we have one function like below −"
},
{
"code": null,
"e": 1326,
"s": 1241,
"text": "long fact(int n){\n if(n == 0 || n == 1)\n return 1;\n return n * fact(n-1);\n}"
},
{
"code": null,
"e": 1452,
"s": 1326,
"text": "This function is recursive function. When we call it like fact(5), then it will store addresses inside the stack like below −"
},
{
"code": null,
"e": 1512,
"s": 1452,
"text": "fact(5) --->\nfact(4) --->\nfact(3) --->\nfact(2) --->\nfact(1)"
},
{
"code": null,
"e": 2011,
"s": 1512,
"text": "As the recursive functions are calling itself again and again, addresses are added into stack. So if the function is called n times recursively, it will take O(n) auxiliary space. But that does not mean that if one normal function is called n times, the space complexity will be O(n). For normal function when it is called, the address is pushed into the stack. After that when it is completed, it will pop address from stack and come into the invoker function. Then call again. So it will be O(1)."
}
] |
Why Git And How To Use Git As A Data Scientist | by Admond Lee | Towards Data Science | Perhaps you’ve heard of Git somewhere else.
Perhaps someone told you that Git is only for software developers and being a data scientist simple couldn’t care less about this.
If you’re a software engineer turned data scientist, this topic is something very familiar to you.
If you’re as aspiring data scientist from different background hoping to get into this field, this topic is something that you’ll be interested in — be it now or in the near future.
If you’re already a data scientist, then you’ll know what and why I’m writing about here.
At the end of the article, I hope that my sharing of experience in Git will let you understand the importance of Git and how to use that in your data science work as a beginner in data science.
Let’s get started!
Git is a distributed version-control system for tracking changes in source code during software development
— Wikipedia
Looking at this definition given by Wikipedia, I was once in your position before thinking that Git is made for software developers. And me as a data scientist has nothing to do with that to somehow comfort myself.
In fact, Git is the most widely used modern version control system in the world today. It is the most recognized and popular approach to contribute to a project (open source or commercial) in a distributed and collaborative manner.
Beyond distributed version control system, Git has been designed with performance, security and flexibility in mind.
Now that you’ve understood what Git is, the next question in your mind might be, “How does it relate to my work if I’m the only one doing my data science project?”
And it’s understandable to not be able to grasp the importance of Git (like what I did last time). Not until I started working in real world environment that I was so grateful for learning and practising Git even when I worked on my personal projects alone — which you’ll know why in the later section.
For now, keep reading.
Let’s talk about the WHY.
Why Git?
A year ago, I decided to learn Git. I shared and published my simulation codes which I did for my final year thesis project at CERN for the very first time on GitHub.
While having hard time to understand the terms that are commonly used in Git (git add, commit, push, pull etc.), I knew that this is important in data science field and being a part of the contributors towards open source codes made my data science work much more fulfilled than ever.
So I continued learning, and kept “committing”.
My experience in Git came in handy when I joined my current company where Git is the main way of code development and collaboration across different teams.
Even more, Git is especially useful when your organization follows agile software development framework where the distributed version control of Git makes the whole development workflow much efficient, faster and easily adaptable to changes.
I’ve talked about version control quite a few times. So what exactly is version control?
Version control is a system that records changes to a file or set of files over time so that you can recall specific versions later.
Say for example you are a data scientist working with a team where you and another data scientist working on the same function to build a machine learning model. Cool.
If you make some changes on the function and uploaded to a remote repository and the changes are merged with the master branch, your model now becomes version 1.1 (just an example). Another data scientist also makes some changes on the same function with the version 1.1 and the new changes are now merged with the master branch. Now the model becomes version 1.2. At any point in time, if your team finds out that version 1.2 has some bugs during the release they can always recall the previous version 1.1.
And that’s the beauty of version control
— Me
We’ve talked about what Git is and its importance.
The question now boils down to: How to use Git as a data scientist?
You don’t need to be an expert in Git to be a data scientist, neither am I. The key here is to understand the workflow of Git and how to use Git in your day to day work.
Bear in mind that you won’t be able to memorize all the Git commands. Feel free to google for that whenever needed, as what everyone else does. Be resourceful.
I’ll focus on using Git in Bitbucket (FREE for use). Of course, the workflow here is applicable to GitHub as well. To be exact, the workflow that I’m using here is Git Feature Branch Workflow, which is commonly used by open source and commercial projects.
If you want to learn more about the terminology used here, this is a great place to start.
The Feature Branch Workflow assumes a central repository, and master represents the official project history.
Instead of committing directly on their local master branch, developers create a new branch every time they start work on a new feature.
Feature branches can (and should) be pushed to the central repository. This makes it possible to share a feature with other developers without touching any official code — master branch in this case.
Before you start doing anything, type git remote -v to make sure your workspace is pointing to the remote repository that you want to work with.
git checkout mastergit pullgit checkout -b branch-name
Provided that the master branch is always maintained and updated, you switch to the local master branch and pull the latest commits and code to your local master branch.
Let’s assume that you want to create a local branch to add a new feature to the code and upload the changes later to the remote repository.
Once you get the latest code to your local master branch, let’s create and checkout a new branch called branch-name and all changes will be made on this local branch. This means your local master branch will not be affected whatsoever.
git statusgit add <your-files>git commit -m 'your message'git push -u origin branch-name
Okay. There is a lot of stuff going on here. Let’s break it down one by one.
Once you’ve made some updates to add the new feature to your local branch-name and you want to upload the changes to the remote branch in order to be merged to the remote master branch later.
git status will therefore output all the file changes (tracked or untracked) made by you. You will decide what files to be staged by using git add <your-files> before you commit the changes with messages using git commit -m 'your message'.
At this stage your changes only appear in your local branch. In order to make your changes appear in the remote branch on Bitbucket, you need to push your commits using git push -u origin branch-name.
This command pushes branch-name to the central repository (origin), and the -u flag adds it as a remote tracking branch. After setting up the tracking branch, git push can be invoked without any parameters to automatically push the new-feature branch to the central repository on Bitbucket.
Great! Now that you’ve successfully added a new feature and pushed the changes to your remote branch.
You’re so proud of your contribution and you want to get feedback from your team members before merging the remote branch with the remote master branch. This gives other team members an opportunity to review the changes before they become a part of the main codebase.
You can create a pull request on Bitbucket.
Now your team members have taken a look at your code and decided to require some other changes from you before the code can be merge into the main codebase — master branch.
git statusgit add <your-files>git commit -m 'your message'git push
So you follow the same steps as before to make changes, commits and finally push the updates to the central repository. Once you’ve used git push , your updates will be automatically shown in the pull request. And that’s it!
If anyone else has made changes in the destination to the same code you touched, you will have merge conflicts, and this is common in the normal workflow. You can see here on how to resolve merge conflicts.
Once everything is done without problems, your updates will be finally merged with the central repository into the master branch. Congratulations!
Thank you for reading.
When I first started learning Git and I felt very frustrated as I still didn’t really understand the workflow — the big picture — despite my understanding of the terminology in general.
This is one of the main reasons of writing this article to really break down and explain the workflow to you on a higher level of understanding. Because I believe that having a clear understanding of what’s going on in the workflow will make the learning process more effective.
I hope this sharing is beneficial to you in some ways.
As always, if you have any questions or comments feel free to leave your feedback below or you can always reach me on LinkedIn. Till then, see you in the next post! 😄
Admond Lee is now in the mission of making data science accessible to everyone. He is helping companies and digital marketing agencies achieve marketing ROI with actionable insights through innovative data-driven approach.
With his expertise in advanced social analytics and machine learning, Admond aims to bridge the gaps between digital marketing and data science.
Check out his website if you want to understand more about Admond’s story, data science services, and how he can help you in marketing space.
You can connect with him on LinkedIn, Medium, Twitter, and Facebook. | [
{
"code": null,
"e": 91,
"s": 47,
"text": "Perhaps you’ve heard of Git somewhere else."
},
{
"code": null,
"e": 222,
"s": 91,
"text": "Perhaps someone told you that Git is only for software developers and being a data scientist simple couldn’t care less about this."
},
{
"code": null,
"e": 321,
"s": 222,
"text": "If you’re a software engineer turned data scientist, this topic is something very familiar to you."
},
{
"code": null,
"e": 503,
"s": 321,
"text": "If you’re as aspiring data scientist from different background hoping to get into this field, this topic is something that you’ll be interested in — be it now or in the near future."
},
{
"code": null,
"e": 593,
"s": 503,
"text": "If you’re already a data scientist, then you’ll know what and why I’m writing about here."
},
{
"code": null,
"e": 787,
"s": 593,
"text": "At the end of the article, I hope that my sharing of experience in Git will let you understand the importance of Git and how to use that in your data science work as a beginner in data science."
},
{
"code": null,
"e": 806,
"s": 787,
"text": "Let’s get started!"
},
{
"code": null,
"e": 914,
"s": 806,
"text": "Git is a distributed version-control system for tracking changes in source code during software development"
},
{
"code": null,
"e": 926,
"s": 914,
"text": "— Wikipedia"
},
{
"code": null,
"e": 1141,
"s": 926,
"text": "Looking at this definition given by Wikipedia, I was once in your position before thinking that Git is made for software developers. And me as a data scientist has nothing to do with that to somehow comfort myself."
},
{
"code": null,
"e": 1373,
"s": 1141,
"text": "In fact, Git is the most widely used modern version control system in the world today. It is the most recognized and popular approach to contribute to a project (open source or commercial) in a distributed and collaborative manner."
},
{
"code": null,
"e": 1490,
"s": 1373,
"text": "Beyond distributed version control system, Git has been designed with performance, security and flexibility in mind."
},
{
"code": null,
"e": 1654,
"s": 1490,
"text": "Now that you’ve understood what Git is, the next question in your mind might be, “How does it relate to my work if I’m the only one doing my data science project?”"
},
{
"code": null,
"e": 1957,
"s": 1654,
"text": "And it’s understandable to not be able to grasp the importance of Git (like what I did last time). Not until I started working in real world environment that I was so grateful for learning and practising Git even when I worked on my personal projects alone — which you’ll know why in the later section."
},
{
"code": null,
"e": 1980,
"s": 1957,
"text": "For now, keep reading."
},
{
"code": null,
"e": 2006,
"s": 1980,
"text": "Let’s talk about the WHY."
},
{
"code": null,
"e": 2015,
"s": 2006,
"text": "Why Git?"
},
{
"code": null,
"e": 2182,
"s": 2015,
"text": "A year ago, I decided to learn Git. I shared and published my simulation codes which I did for my final year thesis project at CERN for the very first time on GitHub."
},
{
"code": null,
"e": 2467,
"s": 2182,
"text": "While having hard time to understand the terms that are commonly used in Git (git add, commit, push, pull etc.), I knew that this is important in data science field and being a part of the contributors towards open source codes made my data science work much more fulfilled than ever."
},
{
"code": null,
"e": 2515,
"s": 2467,
"text": "So I continued learning, and kept “committing”."
},
{
"code": null,
"e": 2671,
"s": 2515,
"text": "My experience in Git came in handy when I joined my current company where Git is the main way of code development and collaboration across different teams."
},
{
"code": null,
"e": 2913,
"s": 2671,
"text": "Even more, Git is especially useful when your organization follows agile software development framework where the distributed version control of Git makes the whole development workflow much efficient, faster and easily adaptable to changes."
},
{
"code": null,
"e": 3002,
"s": 2913,
"text": "I’ve talked about version control quite a few times. So what exactly is version control?"
},
{
"code": null,
"e": 3135,
"s": 3002,
"text": "Version control is a system that records changes to a file or set of files over time so that you can recall specific versions later."
},
{
"code": null,
"e": 3303,
"s": 3135,
"text": "Say for example you are a data scientist working with a team where you and another data scientist working on the same function to build a machine learning model. Cool."
},
{
"code": null,
"e": 3812,
"s": 3303,
"text": "If you make some changes on the function and uploaded to a remote repository and the changes are merged with the master branch, your model now becomes version 1.1 (just an example). Another data scientist also makes some changes on the same function with the version 1.1 and the new changes are now merged with the master branch. Now the model becomes version 1.2. At any point in time, if your team finds out that version 1.2 has some bugs during the release they can always recall the previous version 1.1."
},
{
"code": null,
"e": 3853,
"s": 3812,
"text": "And that’s the beauty of version control"
},
{
"code": null,
"e": 3858,
"s": 3853,
"text": "— Me"
},
{
"code": null,
"e": 3909,
"s": 3858,
"text": "We’ve talked about what Git is and its importance."
},
{
"code": null,
"e": 3977,
"s": 3909,
"text": "The question now boils down to: How to use Git as a data scientist?"
},
{
"code": null,
"e": 4147,
"s": 3977,
"text": "You don’t need to be an expert in Git to be a data scientist, neither am I. The key here is to understand the workflow of Git and how to use Git in your day to day work."
},
{
"code": null,
"e": 4307,
"s": 4147,
"text": "Bear in mind that you won’t be able to memorize all the Git commands. Feel free to google for that whenever needed, as what everyone else does. Be resourceful."
},
{
"code": null,
"e": 4563,
"s": 4307,
"text": "I’ll focus on using Git in Bitbucket (FREE for use). Of course, the workflow here is applicable to GitHub as well. To be exact, the workflow that I’m using here is Git Feature Branch Workflow, which is commonly used by open source and commercial projects."
},
{
"code": null,
"e": 4654,
"s": 4563,
"text": "If you want to learn more about the terminology used here, this is a great place to start."
},
{
"code": null,
"e": 4764,
"s": 4654,
"text": "The Feature Branch Workflow assumes a central repository, and master represents the official project history."
},
{
"code": null,
"e": 4901,
"s": 4764,
"text": "Instead of committing directly on their local master branch, developers create a new branch every time they start work on a new feature."
},
{
"code": null,
"e": 5101,
"s": 4901,
"text": "Feature branches can (and should) be pushed to the central repository. This makes it possible to share a feature with other developers without touching any official code — master branch in this case."
},
{
"code": null,
"e": 5246,
"s": 5101,
"text": "Before you start doing anything, type git remote -v to make sure your workspace is pointing to the remote repository that you want to work with."
},
{
"code": null,
"e": 5301,
"s": 5246,
"text": "git checkout mastergit pullgit checkout -b branch-name"
},
{
"code": null,
"e": 5471,
"s": 5301,
"text": "Provided that the master branch is always maintained and updated, you switch to the local master branch and pull the latest commits and code to your local master branch."
},
{
"code": null,
"e": 5611,
"s": 5471,
"text": "Let’s assume that you want to create a local branch to add a new feature to the code and upload the changes later to the remote repository."
},
{
"code": null,
"e": 5847,
"s": 5611,
"text": "Once you get the latest code to your local master branch, let’s create and checkout a new branch called branch-name and all changes will be made on this local branch. This means your local master branch will not be affected whatsoever."
},
{
"code": null,
"e": 5936,
"s": 5847,
"text": "git statusgit add <your-files>git commit -m 'your message'git push -u origin branch-name"
},
{
"code": null,
"e": 6013,
"s": 5936,
"text": "Okay. There is a lot of stuff going on here. Let’s break it down one by one."
},
{
"code": null,
"e": 6205,
"s": 6013,
"text": "Once you’ve made some updates to add the new feature to your local branch-name and you want to upload the changes to the remote branch in order to be merged to the remote master branch later."
},
{
"code": null,
"e": 6445,
"s": 6205,
"text": "git status will therefore output all the file changes (tracked or untracked) made by you. You will decide what files to be staged by using git add <your-files> before you commit the changes with messages using git commit -m 'your message'."
},
{
"code": null,
"e": 6646,
"s": 6445,
"text": "At this stage your changes only appear in your local branch. In order to make your changes appear in the remote branch on Bitbucket, you need to push your commits using git push -u origin branch-name."
},
{
"code": null,
"e": 6937,
"s": 6646,
"text": "This command pushes branch-name to the central repository (origin), and the -u flag adds it as a remote tracking branch. After setting up the tracking branch, git push can be invoked without any parameters to automatically push the new-feature branch to the central repository on Bitbucket."
},
{
"code": null,
"e": 7039,
"s": 6937,
"text": "Great! Now that you’ve successfully added a new feature and pushed the changes to your remote branch."
},
{
"code": null,
"e": 7307,
"s": 7039,
"text": "You’re so proud of your contribution and you want to get feedback from your team members before merging the remote branch with the remote master branch. This gives other team members an opportunity to review the changes before they become a part of the main codebase."
},
{
"code": null,
"e": 7351,
"s": 7307,
"text": "You can create a pull request on Bitbucket."
},
{
"code": null,
"e": 7524,
"s": 7351,
"text": "Now your team members have taken a look at your code and decided to require some other changes from you before the code can be merge into the main codebase — master branch."
},
{
"code": null,
"e": 7591,
"s": 7524,
"text": "git statusgit add <your-files>git commit -m 'your message'git push"
},
{
"code": null,
"e": 7816,
"s": 7591,
"text": "So you follow the same steps as before to make changes, commits and finally push the updates to the central repository. Once you’ve used git push , your updates will be automatically shown in the pull request. And that’s it!"
},
{
"code": null,
"e": 8023,
"s": 7816,
"text": "If anyone else has made changes in the destination to the same code you touched, you will have merge conflicts, and this is common in the normal workflow. You can see here on how to resolve merge conflicts."
},
{
"code": null,
"e": 8170,
"s": 8023,
"text": "Once everything is done without problems, your updates will be finally merged with the central repository into the master branch. Congratulations!"
},
{
"code": null,
"e": 8193,
"s": 8170,
"text": "Thank you for reading."
},
{
"code": null,
"e": 8379,
"s": 8193,
"text": "When I first started learning Git and I felt very frustrated as I still didn’t really understand the workflow — the big picture — despite my understanding of the terminology in general."
},
{
"code": null,
"e": 8658,
"s": 8379,
"text": "This is one of the main reasons of writing this article to really break down and explain the workflow to you on a higher level of understanding. Because I believe that having a clear understanding of what’s going on in the workflow will make the learning process more effective."
},
{
"code": null,
"e": 8713,
"s": 8658,
"text": "I hope this sharing is beneficial to you in some ways."
},
{
"code": null,
"e": 8880,
"s": 8713,
"text": "As always, if you have any questions or comments feel free to leave your feedback below or you can always reach me on LinkedIn. Till then, see you in the next post! 😄"
},
{
"code": null,
"e": 9103,
"s": 8880,
"text": "Admond Lee is now in the mission of making data science accessible to everyone. He is helping companies and digital marketing agencies achieve marketing ROI with actionable insights through innovative data-driven approach."
},
{
"code": null,
"e": 9248,
"s": 9103,
"text": "With his expertise in advanced social analytics and machine learning, Admond aims to bridge the gaps between digital marketing and data science."
},
{
"code": null,
"e": 9390,
"s": 9248,
"text": "Check out his website if you want to understand more about Admond’s story, data science services, and how he can help you in marketing space."
}
] |
Counts Zeros Xor Pairs | Practice | GeeksforGeeks | Given an array A[] of size N. Find the number of pairs (i, j) such that
Ai XOR Aj = 0, and 1 ≤ i < j ≤ N.
Example 1:
​Input : arr[ ] = {1, 3, 4, 1, 4}
Output : 2
Explanation:
Index( 0, 3 ) and (2 , 4 ) are only pairs
whose xors is zero so count is 2.
​Example 2:
Input : arr[ ] = {2, 2, 2}
Output : 3
Your Task:
This is a function problem. The input is already taken care of by the driver code. You only need to complete the function calculate() that takes an array (arr), sizeOfArray (n), and return the count of Zeros Xor's Pairs. The driver code takes care of the printing.
Expected Time Complexity: O(N*Log(N)).
Expected Auxiliary Space: O(1).
Output:
For each test case, output a single integer i.e counts of Zeros Xors Pairs
Constraints
2 ≤ N ≤ 10^5
1 ≤ A[i] ≤ 10^5
0
indutammana023 days ago
cnt=0 for i in range(0,n-1): for j in range(i+1,n): if (arr[i]^arr[j]==0): cnt+=1 return cnt
+1
yashchawla1163 weeks ago
Simple To Understand And Easy To Implement.
https://yashboss116.blogspot.com/2022/04/count-zeros-xor-pairs-geeks-for-geeks.html
Approach Explained With Complexities Mentioned.
0
dronzerdracel3 weeks ago
C++|O(n log n) solution with O(1) extra space
long long int calculate(int a[], int n)
{
// Complete the function
sort(a,a+n);
long long int count=1,sum=0;
for(int i=0;i<n-1;i++){
if(a[i]==a[i+1])
count++;
else{
sum+=(count-1)*count/2;
count=1;
}
}
sum+=(count-1)*count/2;
return sum;
}
0
inforajsoni3 weeks ago
// { Driver Code Starts// C++ program to find number // of pairs in an array such// that their XOR is 0#include <bits/stdc++.h>using namespace std;
// Function to calculate the// countlong long int calculate(int a[], int n);
// Driver Codeint main(){
int t;cin>>t;while(t--){ int n; cin>>n; int arr[n+1]; for( int i=0;i<n;i++) cin>>arr[i]; cout << calculate(arr, n)<<endl; }return 0;}
// } Driver Code Ends
long long int calculate(int a[], int n){ // Complete the function long long ans=0; unordered_map<int,int>mpp; for(int i=0;i<n;i++) { mpp[a[i]]++; } for(auto it:mpp) { int count=it.second; ans+=(count*(count-1))/2; } return ans;}
0
shalini21sirothiya3 weeks ago
//c++
long long int calculate(int a[], int n){ // Complete the function map<int,int>mp; for(int i=0;i<n;i++){ mp[a[i]]++; } long long count=0; for(auto i:mp){ if(i.second>1){ count+=(i.second*(i.second-1))/2; } } return count; //OR/// sort(a,a+n); long long count=1;long long ans=0; for(int i=1;i<n;i++){ if(a[i]==a[i-1]){ count++; } else{ ans+=(count*(count-1))/2; count=1; } } ans+=(count*(count-1))/2; return ans;}
0
singhkunal01Premium3 weeks ago
This is The Explanation why Most of solutions contains that Formulae for n numbers : (n*(n-1))/2
Taking a case of the array contains all same valued elements can give you a clear intuition behind it like -
Suppose we have a = [2,2,2,2] (for different values elements we have to sort them or we have to use Frequency array ) , then we need to check the next value for the current index i.e., a[i]==a[i+1] if yes then follow the algorithm steps and all but suppose we have pairs of same values like the given example then-
How we calculate the sum ?
Observe deeply that for every i<j we have to find the pairs which means for every i we have to check n - 1 - i indices so for example -
a = [2,2,2,2] , n = 4 , for 2nd index we have to check 4-1-2 indices = 1 (proved) which makes the formulae which will be added to the result no need to calculate for all same valued pairs
FORMULA = (N * (N-1)) /2
Thank You.
-1
harsat20303 weeks ago
simple c++ solution
long long int calculate(int a[], int n){ sort(a, a+n);
long long ans = 0; int cur =0; for(int i = 0; i < n-1; i++) { for(int j=i+1;j<n;j++) { if(a[i]==a[j]){ cur++; } } } return cur;}
0
vikrantv453 weeks ago
unordered_map<int,int>mp; for(int i=0;i<n;i++) { mp[a[i]]++; } long long ans=0; for(auto it:mp) { ans+=(it.second)*(it.second-1); } return ans/2;
0
ayan9103 weeks ago
long long int calculate(int a[], int n){ // Complete the function long long int res = 0; long long int curr = 1; sort(a, a+n); for (int i = 1; i < n; i++) { if(a[i] == a[i-1]) { curr++; } else { res += curr * (curr-1) / 2; curr = 1; } } if (curr > 1) { res += curr * (curr-1) / 2; } return res;}
0
raunakmishra12433 weeks ago
long long int calculate(int a[], int n)
{
sort(a,a+n);
int ans=0;
int d=0;
for(int i=0;i<n-1;)
{
while(a[i]==a[i+1])
{
d++;
i++;
}
ans=ans+(d*(d+1))/2;
d=0;
i++;
}
return ans;
}
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": 344,
"s": 238,
"text": "Given an array A[] of size N. Find the number of pairs (i, j) such that\nAi XOR Aj = 0, and 1 ≤ i < j ≤ N."
},
{
"code": null,
"e": 355,
"s": 344,
"text": "Example 1:"
},
{
"code": null,
"e": 494,
"s": 355,
"text": "​Input : arr[ ] = {1, 3, 4, 1, 4}\nOutput : 2\nExplanation:\nIndex( 0, 3 ) and (2 , 4 ) are only pairs \nwhose xors is zero so count is 2.\n"
},
{
"code": null,
"e": 510,
"s": 494,
"text": "\n​Example 2:"
},
{
"code": null,
"e": 552,
"s": 510,
"text": "Input : arr[ ] = {2, 2, 2} \nOutput : 3\n\n"
},
{
"code": null,
"e": 830,
"s": 554,
"text": "Your Task:\nThis is a function problem. The input is already taken care of by the driver code. You only need to complete the function calculate() that takes an array (arr), sizeOfArray (n), and return the count of Zeros Xor's Pairs. The driver code takes care of the printing."
},
{
"code": null,
"e": 901,
"s": 830,
"text": "Expected Time Complexity: O(N*Log(N)).\nExpected Auxiliary Space: O(1)."
},
{
"code": null,
"e": 986,
"s": 901,
"text": "\n\nOutput:\nFor each test case, output a single integer i.e counts of Zeros Xors Pairs"
},
{
"code": null,
"e": 1027,
"s": 986,
"text": "Constraints\n2 ≤ N ≤ 10^5\n1 ≤ A[i] ≤ 10^5"
},
{
"code": null,
"e": 1031,
"s": 1029,
"text": "0"
},
{
"code": null,
"e": 1055,
"s": 1031,
"text": "indutammana023 days ago"
},
{
"code": null,
"e": 1187,
"s": 1055,
"text": " cnt=0 for i in range(0,n-1): for j in range(i+1,n): if (arr[i]^arr[j]==0): cnt+=1 return cnt"
},
{
"code": null,
"e": 1190,
"s": 1187,
"text": "+1"
},
{
"code": null,
"e": 1215,
"s": 1190,
"text": "yashchawla1163 weeks ago"
},
{
"code": null,
"e": 1259,
"s": 1215,
"text": "Simple To Understand And Easy To Implement."
},
{
"code": null,
"e": 1345,
"s": 1261,
"text": "https://yashboss116.blogspot.com/2022/04/count-zeros-xor-pairs-geeks-for-geeks.html"
},
{
"code": null,
"e": 1395,
"s": 1347,
"text": "Approach Explained With Complexities Mentioned."
},
{
"code": null,
"e": 1397,
"s": 1395,
"text": "0"
},
{
"code": null,
"e": 1422,
"s": 1397,
"text": "dronzerdracel3 weeks ago"
},
{
"code": null,
"e": 1468,
"s": 1422,
"text": "C++|O(n log n) solution with O(1) extra space"
},
{
"code": null,
"e": 1782,
"s": 1468,
"text": "long long int calculate(int a[], int n)\n{\n // Complete the function\n sort(a,a+n);\n long long int count=1,sum=0;\n for(int i=0;i<n-1;i++){\n if(a[i]==a[i+1])\n count++;\n else{\n sum+=(count-1)*count/2;\n count=1;\n }\n }\n sum+=(count-1)*count/2;\n return sum;\n}\n"
},
{
"code": null,
"e": 1784,
"s": 1782,
"text": "0"
},
{
"code": null,
"e": 1807,
"s": 1784,
"text": "inforajsoni3 weeks ago"
},
{
"code": null,
"e": 1955,
"s": 1807,
"text": "// { Driver Code Starts// C++ program to find number // of pairs in an array such// that their XOR is 0#include <bits/stdc++.h>using namespace std;"
},
{
"code": null,
"e": 2032,
"s": 1955,
"text": "// Function to calculate the// countlong long int calculate(int a[], int n);"
},
{
"code": null,
"e": 2058,
"s": 2032,
"text": "// Driver Codeint main(){"
},
{
"code": null,
"e": 2212,
"s": 2058,
"text": "int t;cin>>t;while(t--){ int n; cin>>n; int arr[n+1]; for( int i=0;i<n;i++) cin>>arr[i]; cout << calculate(arr, n)<<endl; }return 0;}"
},
{
"code": null,
"e": 2234,
"s": 2212,
"text": "// } Driver Code Ends"
},
{
"code": null,
"e": 2502,
"s": 2234,
"text": "long long int calculate(int a[], int n){ // Complete the function long long ans=0; unordered_map<int,int>mpp; for(int i=0;i<n;i++) { mpp[a[i]]++; } for(auto it:mpp) { int count=it.second; ans+=(count*(count-1))/2; } return ans;} "
},
{
"code": null,
"e": 2504,
"s": 2502,
"text": "0"
},
{
"code": null,
"e": 2534,
"s": 2504,
"text": "shalini21sirothiya3 weeks ago"
},
{
"code": null,
"e": 2541,
"s": 2534,
"text": "//c++ "
},
{
"code": null,
"e": 3057,
"s": 2541,
"text": "long long int calculate(int a[], int n){ // Complete the function map<int,int>mp; for(int i=0;i<n;i++){ mp[a[i]]++; } long long count=0; for(auto i:mp){ if(i.second>1){ count+=(i.second*(i.second-1))/2; } } return count; //OR/// sort(a,a+n); long long count=1;long long ans=0; for(int i=1;i<n;i++){ if(a[i]==a[i-1]){ count++; } else{ ans+=(count*(count-1))/2; count=1; } } ans+=(count*(count-1))/2; return ans;} "
},
{
"code": null,
"e": 3059,
"s": 3057,
"text": "0"
},
{
"code": null,
"e": 3090,
"s": 3059,
"text": "singhkunal01Premium3 weeks ago"
},
{
"code": null,
"e": 3187,
"s": 3090,
"text": "This is The Explanation why Most of solutions contains that Formulae for n numbers : (n*(n-1))/2"
},
{
"code": null,
"e": 3299,
"s": 3189,
"text": "Taking a case of the array contains all same valued elements can give you a clear intuition behind it like - "
},
{
"code": null,
"e": 3614,
"s": 3299,
"text": "Suppose we have a = [2,2,2,2] (for different values elements we have to sort them or we have to use Frequency array ) , then we need to check the next value for the current index i.e., a[i]==a[i+1] if yes then follow the algorithm steps and all but suppose we have pairs of same values like the given example then-"
},
{
"code": null,
"e": 3641,
"s": 3614,
"text": "How we calculate the sum ?"
},
{
"code": null,
"e": 3780,
"s": 3641,
"text": "Observe deeply that for every i<j we have to find the pairs which means for every i we have to check n - 1 - i indices so for example - "
},
{
"code": null,
"e": 3970,
"s": 3780,
"text": "a = [2,2,2,2] , n = 4 , for 2nd index we have to check 4-1-2 indices = 1 (proved) which makes the formulae which will be added to the result no need to calculate for all same valued pairs"
},
{
"code": null,
"e": 3996,
"s": 3970,
"text": "FORMULA = (N * (N-1)) /2 "
},
{
"code": null,
"e": 4009,
"s": 3998,
"text": "Thank You."
},
{
"code": null,
"e": 4016,
"s": 4013,
"text": "-1"
},
{
"code": null,
"e": 4038,
"s": 4016,
"text": "harsat20303 weeks ago"
},
{
"code": null,
"e": 4059,
"s": 4038,
"text": "simple c++ solution "
},
{
"code": null,
"e": 4116,
"s": 4059,
"text": "long long int calculate(int a[], int n){ sort(a, a+n);"
},
{
"code": null,
"e": 4338,
"s": 4116,
"text": " long long ans = 0; int cur =0; for(int i = 0; i < n-1; i++) { for(int j=i+1;j<n;j++) { if(a[i]==a[j]){ cur++; } } } return cur;}"
},
{
"code": null,
"e": 4340,
"s": 4338,
"text": "0"
},
{
"code": null,
"e": 4362,
"s": 4340,
"text": "vikrantv453 weeks ago"
},
{
"code": null,
"e": 4539,
"s": 4362,
"text": "unordered_map<int,int>mp; for(int i=0;i<n;i++) { mp[a[i]]++; } long long ans=0; for(auto it:mp) { ans+=(it.second)*(it.second-1); } return ans/2;"
},
{
"code": null,
"e": 4541,
"s": 4539,
"text": "0"
},
{
"code": null,
"e": 4560,
"s": 4541,
"text": "ayan9103 weeks ago"
},
{
"code": null,
"e": 4931,
"s": 4560,
"text": "long long int calculate(int a[], int n){ // Complete the function long long int res = 0; long long int curr = 1; sort(a, a+n); for (int i = 1; i < n; i++) { if(a[i] == a[i-1]) { curr++; } else { res += curr * (curr-1) / 2; curr = 1; } } if (curr > 1) { res += curr * (curr-1) / 2; } return res;}"
},
{
"code": null,
"e": 4933,
"s": 4931,
"text": "0"
},
{
"code": null,
"e": 4961,
"s": 4933,
"text": "raunakmishra12433 weeks ago"
},
{
"code": null,
"e": 5255,
"s": 4961,
"text": "long long int calculate(int a[], int n)\n{\n \n sort(a,a+n);\n int ans=0;\n int d=0;\n for(int i=0;i<n-1;)\n {\n while(a[i]==a[i+1])\n {\n d++;\n i++;\n }\n ans=ans+(d*(d+1))/2;\n d=0;\n i++;\n \n \n }\n \n return ans;\n \n \n \n \n \n}\n"
},
{
"code": null,
"e": 5401,
"s": 5255,
"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": 5437,
"s": 5401,
"text": " Login to access your submissions. "
},
{
"code": null,
"e": 5447,
"s": 5437,
"text": "\nProblem\n"
},
{
"code": null,
"e": 5457,
"s": 5447,
"text": "\nContest\n"
},
{
"code": null,
"e": 5520,
"s": 5457,
"text": "Reset the IDE using the second button on the top right corner."
},
{
"code": null,
"e": 5668,
"s": 5520,
"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": 5876,
"s": 5668,
"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": 5982,
"s": 5876,
"text": "You can access the hints to get an idea about what is expected of you as well as the final solution code."
}
] |
C# - Regular Expressions | A regular expression is a pattern that could be matched against an input text. The .Net framework provides a regular expression engine that allows such matching. A pattern consists of one or more character literals, operators, or constructs.
There are various categories of characters, operators, and constructs that lets you to define regular expressions. Click the following links to find these constructs.
Character escapes
Character escapes
Character classes
Character classes
Anchors
Anchors
Grouping constructs
Grouping constructs
Quantifiers
Quantifiers
Backreference constructs
Backreference constructs
Alternation constructs
Alternation constructs
Substitutions
Substitutions
Miscellaneous constructs
Miscellaneous constructs
The Regex class is used for representing a regular expression. It has the following commonly used methods −
public bool IsMatch(string input)
Indicates whether the regular expression specified in the Regex constructor finds a match in a specified input string.
public bool IsMatch(string input, int startat)
Indicates whether the regular expression specified in the Regex constructor finds a match in the specified input string, beginning at the specified starting position in the string.
public static bool IsMatch(string input, string pattern)
Indicates whether the specified regular expression finds a match in the specified input string.
public MatchCollection Matches(string input)
Searches the specified input string for all occurrences of a regular expression.
public string Replace(string input, string replacement)
In a specified input string, replaces all strings that match a regular expression pattern with a specified replacement string.
public string[] Split(string input)
Splits an input string into an array of substrings at the positions defined by a regular expression pattern specified in the Regex constructor.
For the complete list of methods and properties, please read the Microsoft documentation on C#.
The following example matches words that start with 'S' −
using System;
using System.Text.RegularExpressions;
namespace RegExApplication {
class Program {
private static void showMatch(string text, string expr) {
Console.WriteLine("The Expression: " + expr);
MatchCollection mc = Regex.Matches(text, expr);
foreach (Match m in mc) {
Console.WriteLine(m);
}
}
static void Main(string[] args) {
string str = "A Thousand Splendid Suns";
Console.WriteLine("Matching words that start with 'S': ");
showMatch(str, @"\bS\S*");
Console.ReadKey();
}
}
}
When the above code is compiled and executed, it produces the following result −
Matching words that start with 'S':
The Expression: \bS\S*
Splendid
Suns
The following example matches words that start with 'm' and ends with 'e' −
using System;
using System.Text.RegularExpressions;
namespace RegExApplication {
class Program {
private static void showMatch(string text, string expr) {
Console.WriteLine("The Expression: " + expr);
MatchCollection mc = Regex.Matches(text, expr);
foreach (Match m in mc) {
Console.WriteLine(m);
}
}
static void Main(string[] args) {
string str = "make maze and manage to measure it";
Console.WriteLine("Matching words start with 'm' and ends with 'e':");
showMatch(str, @"\bm\S*e\b");
Console.ReadKey();
}
}
}
When the above code is compiled and executed, it produces the following result −
Matching words start with 'm' and ends with 'e':
The Expression: \bm\S*e\b
make
maze
manage
measure
This example replaces extra white space −
using System;
using System.Text.RegularExpressions;
namespace RegExApplication {
class Program {
static void Main(string[] args) {
string input = "Hello World ";
string pattern = "\\s+";
string replacement = " ";
Regex rgx = new Regex(pattern);
string result = rgx.Replace(input, replacement);
Console.WriteLine("Original String: {0}", input);
Console.WriteLine("Replacement String: {0}", result);
Console.ReadKey();
}
}
}
When the above code is compiled and executed, it produces the following result −
Original String: Hello World
Replacement String: Hello World
119 Lectures
23.5 hours
Raja Biswas
37 Lectures
13 hours
Trevoir Williams
16 Lectures
1 hours
Peter Jepson
159 Lectures
21.5 hours
Ebenezer Ogbu
193 Lectures
17 hours
Arnold Higuit
24 Lectures
2.5 hours
Eric Frick
Print
Add Notes
Bookmark this page | [
{
"code": null,
"e": 2512,
"s": 2270,
"text": "A regular expression is a pattern that could be matched against an input text. The .Net framework provides a regular expression engine that allows such matching. A pattern consists of one or more character literals, operators, or constructs."
},
{
"code": null,
"e": 2679,
"s": 2512,
"text": "There are various categories of characters, operators, and constructs that lets you to define regular expressions. Click the following links to find these constructs."
},
{
"code": null,
"e": 2697,
"s": 2679,
"text": "Character escapes"
},
{
"code": null,
"e": 2715,
"s": 2697,
"text": "Character escapes"
},
{
"code": null,
"e": 2733,
"s": 2715,
"text": "Character classes"
},
{
"code": null,
"e": 2751,
"s": 2733,
"text": "Character classes"
},
{
"code": null,
"e": 2759,
"s": 2751,
"text": "Anchors"
},
{
"code": null,
"e": 2767,
"s": 2759,
"text": "Anchors"
},
{
"code": null,
"e": 2787,
"s": 2767,
"text": "Grouping constructs"
},
{
"code": null,
"e": 2807,
"s": 2787,
"text": "Grouping constructs"
},
{
"code": null,
"e": 2819,
"s": 2807,
"text": "Quantifiers"
},
{
"code": null,
"e": 2831,
"s": 2819,
"text": "Quantifiers"
},
{
"code": null,
"e": 2856,
"s": 2831,
"text": "Backreference constructs"
},
{
"code": null,
"e": 2881,
"s": 2856,
"text": "Backreference constructs"
},
{
"code": null,
"e": 2904,
"s": 2881,
"text": "Alternation constructs"
},
{
"code": null,
"e": 2927,
"s": 2904,
"text": "Alternation constructs"
},
{
"code": null,
"e": 2941,
"s": 2927,
"text": "Substitutions"
},
{
"code": null,
"e": 2955,
"s": 2941,
"text": "Substitutions"
},
{
"code": null,
"e": 2980,
"s": 2955,
"text": "Miscellaneous constructs"
},
{
"code": null,
"e": 3005,
"s": 2980,
"text": "Miscellaneous constructs"
},
{
"code": null,
"e": 3113,
"s": 3005,
"text": "The Regex class is used for representing a regular expression. It has the following commonly used methods −"
},
{
"code": null,
"e": 3147,
"s": 3113,
"text": "public bool IsMatch(string input)"
},
{
"code": null,
"e": 3266,
"s": 3147,
"text": "Indicates whether the regular expression specified in the Regex constructor finds a match in a specified input string."
},
{
"code": null,
"e": 3313,
"s": 3266,
"text": "public bool IsMatch(string input, int startat)"
},
{
"code": null,
"e": 3494,
"s": 3313,
"text": "Indicates whether the regular expression specified in the Regex constructor finds a match in the specified input string, beginning at the specified starting position in the string."
},
{
"code": null,
"e": 3551,
"s": 3494,
"text": "public static bool IsMatch(string input, string pattern)"
},
{
"code": null,
"e": 3647,
"s": 3551,
"text": "Indicates whether the specified regular expression finds a match in the specified input string."
},
{
"code": null,
"e": 3692,
"s": 3647,
"text": "public MatchCollection Matches(string input)"
},
{
"code": null,
"e": 3773,
"s": 3692,
"text": "Searches the specified input string for all occurrences of a regular expression."
},
{
"code": null,
"e": 3829,
"s": 3773,
"text": "public string Replace(string input, string replacement)"
},
{
"code": null,
"e": 3956,
"s": 3829,
"text": "In a specified input string, replaces all strings that match a regular expression pattern with a specified replacement string."
},
{
"code": null,
"e": 3992,
"s": 3956,
"text": "public string[] Split(string input)"
},
{
"code": null,
"e": 4136,
"s": 3992,
"text": "Splits an input string into an array of substrings at the positions defined by a regular expression pattern specified in the Regex constructor."
},
{
"code": null,
"e": 4232,
"s": 4136,
"text": "For the complete list of methods and properties, please read the Microsoft documentation on C#."
},
{
"code": null,
"e": 4290,
"s": 4232,
"text": "The following example matches words that start with 'S' −"
},
{
"code": null,
"e": 4912,
"s": 4290,
"text": "using System;\nusing System.Text.RegularExpressions;\n\nnamespace RegExApplication {\n class Program {\n private static void showMatch(string text, string expr) {\n Console.WriteLine(\"The Expression: \" + expr);\n MatchCollection mc = Regex.Matches(text, expr);\n \n foreach (Match m in mc) {\n Console.WriteLine(m);\n }\n }\n static void Main(string[] args) {\n string str = \"A Thousand Splendid Suns\";\n \n Console.WriteLine(\"Matching words that start with 'S': \");\n showMatch(str, @\"\\bS\\S*\");\n Console.ReadKey();\n }\n }\n}"
},
{
"code": null,
"e": 4993,
"s": 4912,
"text": "When the above code is compiled and executed, it produces the following result −"
},
{
"code": null,
"e": 5067,
"s": 4993,
"text": "Matching words that start with 'S':\nThe Expression: \\bS\\S*\nSplendid\nSuns\n"
},
{
"code": null,
"e": 5143,
"s": 5067,
"text": "The following example matches words that start with 'm' and ends with 'e' −"
},
{
"code": null,
"e": 5781,
"s": 5143,
"text": "using System;\nusing System.Text.RegularExpressions;\n\nnamespace RegExApplication {\n class Program {\n private static void showMatch(string text, string expr) {\n Console.WriteLine(\"The Expression: \" + expr);\n MatchCollection mc = Regex.Matches(text, expr);\n \n foreach (Match m in mc) {\n Console.WriteLine(m);\n }\n }\n static void Main(string[] args) {\n string str = \"make maze and manage to measure it\";\n\n Console.WriteLine(\"Matching words start with 'm' and ends with 'e':\");\n showMatch(str, @\"\\bm\\S*e\\b\");\n Console.ReadKey();\n }\n }\n}"
},
{
"code": null,
"e": 5862,
"s": 5781,
"text": "When the above code is compiled and executed, it produces the following result −"
},
{
"code": null,
"e": 5963,
"s": 5862,
"text": "Matching words start with 'm' and ends with 'e':\nThe Expression: \\bm\\S*e\\b\nmake\nmaze\nmanage\nmeasure\n"
},
{
"code": null,
"e": 6005,
"s": 5963,
"text": "This example replaces extra white space −"
},
{
"code": null,
"e": 6538,
"s": 6005,
"text": "using System;\nusing System.Text.RegularExpressions;\n\nnamespace RegExApplication {\n class Program {\n static void Main(string[] args) {\n string input = \"Hello World \";\n string pattern = \"\\\\s+\";\n string replacement = \" \";\n \n Regex rgx = new Regex(pattern);\n string result = rgx.Replace(input, replacement);\n\n Console.WriteLine(\"Original String: {0}\", input);\n Console.WriteLine(\"Replacement String: {0}\", result); \n Console.ReadKey();\n }\n }\n}"
},
{
"code": null,
"e": 6619,
"s": 6538,
"text": "When the above code is compiled and executed, it produces the following result −"
},
{
"code": null,
"e": 6687,
"s": 6619,
"text": "Original String: Hello World \nReplacement String: Hello World \n"
},
{
"code": null,
"e": 6724,
"s": 6687,
"text": "\n 119 Lectures \n 23.5 hours \n"
},
{
"code": null,
"e": 6737,
"s": 6724,
"text": " Raja Biswas"
},
{
"code": null,
"e": 6771,
"s": 6737,
"text": "\n 37 Lectures \n 13 hours \n"
},
{
"code": null,
"e": 6789,
"s": 6771,
"text": " Trevoir Williams"
},
{
"code": null,
"e": 6822,
"s": 6789,
"text": "\n 16 Lectures \n 1 hours \n"
},
{
"code": null,
"e": 6836,
"s": 6822,
"text": " Peter Jepson"
},
{
"code": null,
"e": 6873,
"s": 6836,
"text": "\n 159 Lectures \n 21.5 hours \n"
},
{
"code": null,
"e": 6888,
"s": 6873,
"text": " Ebenezer Ogbu"
},
{
"code": null,
"e": 6923,
"s": 6888,
"text": "\n 193 Lectures \n 17 hours \n"
},
{
"code": null,
"e": 6938,
"s": 6923,
"text": " Arnold Higuit"
},
{
"code": null,
"e": 6973,
"s": 6938,
"text": "\n 24 Lectures \n 2.5 hours \n"
},
{
"code": null,
"e": 6985,
"s": 6973,
"text": " Eric Frick"
},
{
"code": null,
"e": 6992,
"s": 6985,
"text": " Print"
},
{
"code": null,
"e": 7003,
"s": 6992,
"text": " Add Notes"
}
] |
How do we use Python in interactive mode? | Execute Python from command prompt to run Python interactive shell.
C:\user>python
>>>
Python prompt is made up of three greater than symbols. Any valid expression can now be evaluated interactively. Let us start with evaluating arithmetic expression.
>>> 2+3*5
17
You can assign value to a variable or accept input from user, and print its value.
>>> name=input("enter your name")
enter your name TutorialsPoint
>>> name
' TutorialsPoint' | [
{
"code": null,
"e": 1130,
"s": 1062,
"text": "Execute Python from command prompt to run Python interactive shell."
},
{
"code": null,
"e": 1150,
"s": 1130,
"text": "C:\\user>python\n >>>"
},
{
"code": null,
"e": 1315,
"s": 1150,
"text": "Python prompt is made up of three greater than symbols. Any valid expression can now be evaluated interactively. Let us start with evaluating arithmetic expression."
},
{
"code": null,
"e": 1329,
"s": 1315,
"text": ">>> 2+3*5\n 17"
},
{
"code": null,
"e": 1412,
"s": 1329,
"text": "You can assign value to a variable or accept input from user, and print its value."
},
{
"code": null,
"e": 1505,
"s": 1412,
"text": ">>> name=input(\"enter your name\")\nenter your name TutorialsPoint\n>>> name\n ' TutorialsPoint'"
}
] |
Benchmarking Categorical Encoders | by Denis Vorotyntsev | Towards Data Science | Most tabular datasets contain categorical features. The simplest way to work with these is to encode them with Label Encoder. It is simple, yet sometimes not accurate.
In this post, I would like to show better approaches which could be used “out of the box” (thanks to Category Encoders Python library). I’m going to start by describing different strategies to encode categorical variables. Then I will show you how those could be improved through Single and Double Validation. The final part of the paper is devoted to the discussion of benchmarks results (which also could be found in my GitHub repo — CategoricalEncodingBenchmark).
The following material describes binary classification task, yet all formulas and approaches could be applied to multiclass classification (as far as it could be represented as a binary classification) and regression.
There is no free lunch. You have to try multiple types of encoders to find the best one for your data;However, the most stable and accurate encoders are target-based encoders with Double Validation: Catboost Encoder, James-Stein Encoder, and Target Encoder;encoder.fit_transform() on the whole train is a road to nowhere: it turned out that Single Validation is a much better option than commonly used None Validation. If you want to achieve a stable high score, Double Validation is your choice, but bear in mind that it requires much more time to be trained;Regularization is a must for target-based encoders.
There is no free lunch. You have to try multiple types of encoders to find the best one for your data;
However, the most stable and accurate encoders are target-based encoders with Double Validation: Catboost Encoder, James-Stein Encoder, and Target Encoder;
encoder.fit_transform() on the whole train is a road to nowhere: it turned out that Single Validation is a much better option than commonly used None Validation. If you want to achieve a stable high score, Double Validation is your choice, but bear in mind that it requires much more time to be trained;
Regularization is a must for target-based encoders.
If you are looking for a better understanding of categorical encoding, I recommend you to grab a pen and some paper and make your own calculations with the formulas I provided below. It wouldn’t take much time, but it is really helpful. In the formulas, I’m going to use the following parameters:
y and y+ — the total number of observations and the total number of positive observations (y=1);
xi, yi — the i-th value of category and target;
n and n+ — the number of observations and the number of positive observations (y=1) for a given value of a categorical column;
a — a regularization hyperparameter (selected by a user), prior — an average value of the target.
The example train dataset looks like this:
y=10, y+=5;
ni=”D”, yi=1 for 9th line of the dataset (the last observation);
For category B: n=3, n+=1;
prior = y+/ y= 5/10 = 0.5.
With this in mind, let’s start from simple ones while gradually increasing the encoder’s complexity.
The most common way to deal with categories is to simply map each category with a number. By applying such transformation, a model would treat categories as ordered integers, which in most cases is wrong. Such transformation should not be used “as is” for several types of models (Linear Models, KNN, Neural Nets, etc.). While applying gradient boosting it could be used only if the type of a column is specified as “category”:
df[“category_representation”] = df[“category_representation”].astype(“category”)
New categories in Label Encoder are replaced with “-1” or None. If you are working with tabular data and your model is gradient boosting (especially LightGBM library), LE is the simplest and efficient way for you to work with categories in terms of memory (the category type in python consumes much less memory than the object type).
The One Hot Encoding is another simple way to work with categorical columns. It takes a categorical column that has been Label Encoded and then splits the column into multiple columns. The numbers are replaced by 1s and 0s depending on which column has what value.
OHE expands the size of your dataset, which makes it memory-inefficient encoder. There are several strategies to overcome the memory problem with OHE, one of which is working with sparse not dense data representation.
Sum Encoder compares the mean of the dependent variable (target) for a given level of a categorical column to the overall mean of the target. Sum Encoding is very similar to OHE and both of them are commonly used in Linear Regression (LR) types of models.
However, the difference between them is the interpretation of LR coefficients: whereas in OHE model the intercept represents the mean for the baseline condition and coefficients represents simple effects (the difference between one particular condition and the baseline), in Sum Encoder model the intercept represents the grand mean (across all conditions) and the coefficients can be interpreted directly as the main effects.
Helmert coding is a third commonly used type of categorical encoding for regression along with OHE and Sum Encoding. It compares each level of a categorical variable to the mean of the subsequent levels. Hence, the first contrast compares the mean of the dependent variable for “A” with the mean of all of the subsequent levels of categorical column (“B”, “C”, “D”), the second contrast compares the mean of the dependent variable for “B” with the mean of all of the subsequent levels (“C”, “D”), and the third contrast compares the mean of the dependent variable for “C” with the mean of all of the subsequent levels (in our case only one level — “D”).
This type of encoding can be useful in certain situations where levels of the categorical variable are ordered, say, from lowest to highest, or from smallest to largest.
Frequency Encoding counts the number of a category’s occurrences in the dataset. New categories in test dataset encoded with either “1” or counts of category in a test dataset, which makes this encoder a little bit tricky: encoding for different sizes of test batch might be different. You should think about it beforehand and make preprocessing of the train as close to the test as possible.
To avoid such problem, you might also consider using a Frequency Encoder variation — Rolling Frequency Encoder (RFE). RFE counts the number a category’s occurrences for the last dt timesteps from a given observation (for example, for dt= 24 hours).
Nevertheless, Frequency Encoding and RFE are especially efficient when your categorical column has “long tails”, i.e. several frequent values and the remaining ones have only a few examples in the dataset. In such a case, Frequency Encoding would catch the similarity between rare columns.
Target Encoding has probably become the most popular encoding type because of Kaggle competitions. It takes information about the target to encode categories, which makes it extremely powerful. The encoded category values are calculated according to the following formulas:
Here, mdl — min data (samples) in leaf, a — smoothing parameter, representing the power of regularization. Recommended values for mdl and a are in the range of 1 to 100. New values of category and values with just single appearance in train dataset are replaced with the prior ones.
Target Encoder is a powerful tool, yet it has a huge disadvantage — target leakage: it uses information about the target. Because of the target leakage, model overfits the training data which results in unreliable validation and lower test scores. To reduce the effect of target leakage, we may increase regularization (it’s hard to tune those hyperparameters without unreliable validation), add random noise to the representation of the category in train dataset (some sort of augmentation), or use Double Validation.
M-Estimate Encoder is a simplified version of Target Encoder. It has only one hyperparameter — m, which represents the power of regularization. The higher value of m results into stronger shrinking. Recommended values for m is in the range of 1 to 100.
In different sources, you may find another formula of M-Estimator. Instead of y+ there is n in the denominator. I found that such representation has similar scores.
UPD (17.07.2019): The formula for M-Estimate Encoder in Categorical Encoders library contained a bug. The right one should have n in the denominator. However, both approaches show pretty good scores. The following benchmark is done via “wrong” formula.
Weight Of Evidence is a commonly used target-based encoder in credit scoring. It is a measure of the “strength” of a grouping for separating good and bad risk (default). It is calculated from the basic odds ratio:
a = Distribution of Good Credit Outcomesb = Distribution of Bad Credit OutcomesWoE = ln(a / b)
However, if we use formulas as is, it might lead to target leakage and overfit. To avoid that, regularization parameter a is induced and WoE is calculated in the following way:
James-Stein Encoder is a target-based encoder. This encoder is inspired by James–Stein estimator — the technique named after Charles Stein and Willard James, who simplified Stein’s original Gaussian random vectors mean estimation method of 1956. Stein and James proved that a better estimator than the “perfect” (i.e. mean) estimator exists, which seems to be somewhat of a paradox. However, the James-Stein estimator outperforms the sample mean when there are several unknown populations means — not just one.
The idea behind James-Stein Encoder is simple. Estimation of the mean target for category k could be calculated according to the following formula:
Encoding is aimed to improve the estimation of the category’s mean target (first member of the amount) by shrinking them towards a more central average (second member of the amount). The only hyperparameter in the formula is B — the power of shrinking. It could be understood as the power of regularization, i.e. the bigger values of B will result in the bigger weight of global mean (underfit), while the lower values of B are, the bigger weight of condition mean (overfit).
One way to select B is to tune it like a hyperparameter via cross-validation, but Charles Stein came up with another solution to the problem:
Intuitively, the formula can be seen in the following sense: if we could not rely on the estimation of category mean to target (it has high variance), it means we should assign a bigger weight to the global mean.
Wait, but how we could trust the estimation of variance if we could not rely on the estimation of the mean? Well, we may either say that the variance among all categories is the same and equal to the global variance of y (which might be a good estimation, if we don’t have too many unique categorical values; it is called pooled variance or pooled model) or replace the variances with squared standard errors, which penalize small observation counts (independent model).
Seems quite fair, but James-Stein Estimator has a big disadvantage — it is defined only for normal distribution (which is not the case for any classification task). To avoid that, we can either convert binary targets with a log-odds ratio as it was done in WoE Encoder (which is used by default because it is simple) or use beta distribution.
Leave-one-out Encoding (LOO or LOOE) is another example of target-based encoders. The name of the method clearly speaks for itself: we calculate mean target of category k for observation j if observation j is removed from the dataset:
While encoding the test dataset, a category is replaced with the mean target of the category k in the train dataset:
One of the problems with LOO, just like with all other target-based encoders, is target leakage. But when it comes to LOO, this problem gets really dramatic, as far as we may perfectly classify the training dataset by making a single split: the optimal threshold for category k could be calculated with the following formula:
Another problem with LOO is a shift between values in the train and the test samples. You could observe it from the picture above. Possible values for category “A” in the train sample are 0.67 and 0.33, while in the test one — 0.5. It is a result of the different number of counts in train and test datasets: for category “A” denominator is equal to n for test and n-1 for train dataset. Such a shift may gradually reduce the performance of tree-based models.
Catboost is a recently created target-based categorical encoder. It is intended to overcome target leakage problems inherent in LOO. In order to do that, the authors of Catboost introduced the idea of “time”: the order of observations in the dataset. Clearly, the values of the target statistic for each example rely only on the observed history. To calculate the statistic for observation j in train dataset, we may use only observations, which are collected before observation j, i.e. i≤j:
To prevent overfitting, the process of target encoding for train dataset is repeated several times on shuffled versions of the dataset and results are averaged. Encoded values of the test data are calculated the same way as in LOO Encoder:
Catboost “on the fly” Encoding is one of the core advantages of CatBoost — library for gradient boosting, which showed state of the art results on several tabular datasets when it was presented by Yandex.
Model validation is probably the most important aspect of Machine Learning. While working with data that contains categorical variables, we may want to use one of the three types of validation. None Validation is the simplest one, yet least accurate. Double Validation could show great scores, but it is as slow as a turtle. And Single Validation is kind of a cross between the first two methods.
This section is devoted to the discussion of each validation type in details. For better understanding, for each type of validation, I added block diagrams of the pipeline.
In the case of None Validation, the single encoder is fitted to the whole train data. Validation and test parts of the dataset are processed with the same single encoder. Being the simplest one, this approach is wildly used, but it leads to overfitting during training and unreliable validation scores. The most obvious reasons for that are: for target encoders, None validation induces a shift between train and test part (see an example in LOO encoder); test dataset may contain new categorical values, but neither train nor validation sample contains them during training, that is why:
The model doesn’t know how to handle new categories;
The optimal number of trees for train and test samples may be different.
Single Validation is a better way to carry out validation. By using Single Validation we overcome one of the problems of None Validation: the shift between validation and test datasets. Within this approach, we fit separate categorical encoders to each fold of training data. Validation part of each fold is processed the same way as the test data, so it became more similar to it, which positively affects hyperparameters tuning. The optimal hyperparameters obtained from Single Validation would be closer to optimal hyperparameters of test dataset then the ones obtained from None Validation.
Note: while we are tuning hyperparameters, i.e. a number of trees, on validation part of the data the validation scores are going to be slightly overfitted anyway. So will be the test scores, because the type of encoder is also a hyperparameter of the pipeline. I reduced the overfitting effect by making test bigger (40% of the usual data).
The other good advantage of Single Validation is diversity across folds. By fitting encoder on a subset of the data, we achieve different representation of category, which positively affects the final blending of predictions.
Double Validation is an extension of Single Validation. The pipeline for Double Validation is exactly the same as for Single Validation, except Encoder part: instead of the single encoder for each fold, we will use several encoders fitted on different subsets.
Double Validation aims to reduce the effect of the second problem of None Validation — new categories. It is achieved by splitting each fold into sub-folds, fitting separate encoder to each sub-fold, and then concating (in case of train part) or averaging (in case of validation or test parts) the results. By applying Double Validation we induce a noise (new categories) into training data, which works as augmentation of the data. However, Double Validation has two major disadvantages:
We can not use it “as is” for encoders, which represents single category as multiple columns (for example, OHE, Sum Encoder, Helmert Encoder, and Backward Difference Encoder);
The time complexity of Double Validation is approximately k times bigger than in Single validation (k — number of subfolds).
I hope you aren’t too overwhelmed with the theoretical part and still remember the title of the paper. So, let’s move from that to practice! In the following section, I’m going to show you how I determined the best categorical encoder for tabular data.
I created and tested pipeline for categories benchmarking on the datasets which are presented in the table below. All datasets except poverty_A(B, C) came from different domains; they have a different number of observations, as well as of categorical and numerical features. The objective for all datasets is to perform binary classification. Preprocessing was quite simple: I removed all time-based columns from the datasets. The ones left were either categorical or numerical.
The whole dataset was split into the train (the first 60% of the data) and the test samples (the remaining 40% of the data). The test part is unseen during the training and it is used only once — for final scoring (scoring metric used — ROC AUC). No encoding on whole data, no pseudo labeling, no TTA, etc. were applied during the training or predicting stage. I wanted the experiments to be as close to possible production settings as possible.
After the train-test split, the training data was split into 5 folds with shuffle and stratification. After that, 4 of them were used for the fitting encoder (for a case of None Validation — encoder if fitted to the whole train dataset before splitting) and LightGBM model (LlightGBM — library for gradient boosting from Microsoft), and 1 more fold was used for early stopping. The process was repeated 5 times and in the end, we had 5 trained encoders and 5 LGB models. The LightGBM model parameters were as follows:
"metrics": "AUC", "n_estimators": 5000, "learning_rate": 0.02, "random_state": 42,"early_stopping_rounds": 100
During the predicting stage, test data was processed with each of encoders and prediction was made via each of the models. Predictions were then ranked and summed (ROC AUC metric doesn’t care if predictions are averaged or summed; the only importance is the order).
This section contains the processed results of the experiments. If you’d like to see the raw scores for each dataset, please visit my GitHub repository — CategoricalEncodingBenchmark.
To determine the best encoder, I scaled the ROC AUC scores of each dataset (min-max scale) and then averaged results among the encoder. The obtained result represents the average performance score for each encoder (higher is better). The encoders performance scores for each type of validation are shown in Tables 2.1–2.3.
In order to determine the best validation strategy, I compared the top score of each dataset for each type of validation. The scores improvement (top score for a dataset and an average score for encoder) are shown in Tables 2.4 and 2.5 below.
Best encoder for each dataset and each type of validation was different. However, the non-target encoders (Helmet Encoder and Sum Encoder) dominated all other in None Validation experiment. This is quite an interesting finding because originally these types of encoders were used mostly in Linear Models.
For the case of Single Validation, best encoders were CatBoost Encoder and Ordinal Encoder, which both had a relatively low performance score in None Validation experiment.
Target-based encoders (James-Stein, Catboost, Target, LOO, WOE) with Double Validation showed the best performance scores from all types of validation and encoders. We might call it now the most stable and accurate approach for dealing with categorical variables.
The performance of target-based encoders was improved by inducing the noise to train data. It could be clearly seen in the LOO Encoder — it turned out to be the worse encoder both in None and Sigle Validation with a huge gap to the second worst, but among best in Double Validation. Double Validation (or another variation of regularization) is a must for all target-based encoders.
The results of Frequency Encoder were lowered by increasing the complexity of Validation. This is because the frequency of new categories in the test was counted on the whole test while during Single Validation it was counted on 1/5 of train dataset (5 folds in train dataset), during Double Validation — on 1/25 of train dataset (5 folds in train dataset, 5 subfolds in each fold). Thus, maximum frequencies in testing data were bigger than in train and validation data samples. Do you remember I told you about FE being tricky? That’s why.
I would like to thank Andrey Lukyanenko, Anton Biryukov and Daniel Potapov for fruitful discussion of the results of the work.
R library contrast coding systems for categorical variablesCategory Encoders docsContrast Coding Systems for Categorical VariablesCoding schemes for categorical variables in regression, Coding systems for categorical variables in regression analysisWeight of Evidence (WoE) Introductory OverviewJames–Stein estimator, James-Stein Estimator: Definition, Formulas, Stein’s Paradox in StatisticsA preprocessing scheme for high-cardinality categorical attributes in classification and prediction problemsFeature Engineering in H2O Driverless AI by Dmitry LarkoCatBoost: unbiased boosting with categorical features, Transforming categorical features to numerical features in CatboostThe idea of Double Validation was inspired by Stanislav Semenov talk on “Kaggle BNP Paribas”
R library contrast coding systems for categorical variables
Category Encoders docs
Contrast Coding Systems for Categorical Variables
Coding schemes for categorical variables in regression, Coding systems for categorical variables in regression analysis
Weight of Evidence (WoE) Introductory Overview
James–Stein estimator, James-Stein Estimator: Definition, Formulas, Stein’s Paradox in Statistics
A preprocessing scheme for high-cardinality categorical attributes in classification and prediction problems
Feature Engineering in H2O Driverless AI by Dmitry Larko
CatBoost: unbiased boosting with categorical features, Transforming categorical features to numerical features in Catboost
The idea of Double Validation was inspired by Stanislav Semenov talk on “Kaggle BNP Paribas” | [
{
"code": null,
"e": 340,
"s": 172,
"text": "Most tabular datasets contain categorical features. The simplest way to work with these is to encode them with Label Encoder. It is simple, yet sometimes not accurate."
},
{
"code": null,
"e": 807,
"s": 340,
"text": "In this post, I would like to show better approaches which could be used “out of the box” (thanks to Category Encoders Python library). I’m going to start by describing different strategies to encode categorical variables. Then I will show you how those could be improved through Single and Double Validation. The final part of the paper is devoted to the discussion of benchmarks results (which also could be found in my GitHub repo — CategoricalEncodingBenchmark)."
},
{
"code": null,
"e": 1025,
"s": 807,
"text": "The following material describes binary classification task, yet all formulas and approaches could be applied to multiclass classification (as far as it could be represented as a binary classification) and regression."
},
{
"code": null,
"e": 1637,
"s": 1025,
"text": "There is no free lunch. You have to try multiple types of encoders to find the best one for your data;However, the most stable and accurate encoders are target-based encoders with Double Validation: Catboost Encoder, James-Stein Encoder, and Target Encoder;encoder.fit_transform() on the whole train is a road to nowhere: it turned out that Single Validation is a much better option than commonly used None Validation. If you want to achieve a stable high score, Double Validation is your choice, but bear in mind that it requires much more time to be trained;Regularization is a must for target-based encoders."
},
{
"code": null,
"e": 1740,
"s": 1637,
"text": "There is no free lunch. You have to try multiple types of encoders to find the best one for your data;"
},
{
"code": null,
"e": 1896,
"s": 1740,
"text": "However, the most stable and accurate encoders are target-based encoders with Double Validation: Catboost Encoder, James-Stein Encoder, and Target Encoder;"
},
{
"code": null,
"e": 2200,
"s": 1896,
"text": "encoder.fit_transform() on the whole train is a road to nowhere: it turned out that Single Validation is a much better option than commonly used None Validation. If you want to achieve a stable high score, Double Validation is your choice, but bear in mind that it requires much more time to be trained;"
},
{
"code": null,
"e": 2252,
"s": 2200,
"text": "Regularization is a must for target-based encoders."
},
{
"code": null,
"e": 2549,
"s": 2252,
"text": "If you are looking for a better understanding of categorical encoding, I recommend you to grab a pen and some paper and make your own calculations with the formulas I provided below. It wouldn’t take much time, but it is really helpful. In the formulas, I’m going to use the following parameters:"
},
{
"code": null,
"e": 2646,
"s": 2549,
"text": "y and y+ — the total number of observations and the total number of positive observations (y=1);"
},
{
"code": null,
"e": 2694,
"s": 2646,
"text": "xi, yi — the i-th value of category and target;"
},
{
"code": null,
"e": 2821,
"s": 2694,
"text": "n and n+ — the number of observations and the number of positive observations (y=1) for a given value of a categorical column;"
},
{
"code": null,
"e": 2919,
"s": 2821,
"text": "a — a regularization hyperparameter (selected by a user), prior — an average value of the target."
},
{
"code": null,
"e": 2962,
"s": 2919,
"text": "The example train dataset looks like this:"
},
{
"code": null,
"e": 2974,
"s": 2962,
"text": "y=10, y+=5;"
},
{
"code": null,
"e": 3039,
"s": 2974,
"text": "ni=”D”, yi=1 for 9th line of the dataset (the last observation);"
},
{
"code": null,
"e": 3066,
"s": 3039,
"text": "For category B: n=3, n+=1;"
},
{
"code": null,
"e": 3093,
"s": 3066,
"text": "prior = y+/ y= 5/10 = 0.5."
},
{
"code": null,
"e": 3194,
"s": 3093,
"text": "With this in mind, let’s start from simple ones while gradually increasing the encoder’s complexity."
},
{
"code": null,
"e": 3622,
"s": 3194,
"text": "The most common way to deal with categories is to simply map each category with a number. By applying such transformation, a model would treat categories as ordered integers, which in most cases is wrong. Such transformation should not be used “as is” for several types of models (Linear Models, KNN, Neural Nets, etc.). While applying gradient boosting it could be used only if the type of a column is specified as “category”:"
},
{
"code": null,
"e": 3703,
"s": 3622,
"text": "df[“category_representation”] = df[“category_representation”].astype(“category”)"
},
{
"code": null,
"e": 4037,
"s": 3703,
"text": "New categories in Label Encoder are replaced with “-1” or None. If you are working with tabular data and your model is gradient boosting (especially LightGBM library), LE is the simplest and efficient way for you to work with categories in terms of memory (the category type in python consumes much less memory than the object type)."
},
{
"code": null,
"e": 4302,
"s": 4037,
"text": "The One Hot Encoding is another simple way to work with categorical columns. It takes a categorical column that has been Label Encoded and then splits the column into multiple columns. The numbers are replaced by 1s and 0s depending on which column has what value."
},
{
"code": null,
"e": 4520,
"s": 4302,
"text": "OHE expands the size of your dataset, which makes it memory-inefficient encoder. There are several strategies to overcome the memory problem with OHE, one of which is working with sparse not dense data representation."
},
{
"code": null,
"e": 4776,
"s": 4520,
"text": "Sum Encoder compares the mean of the dependent variable (target) for a given level of a categorical column to the overall mean of the target. Sum Encoding is very similar to OHE and both of them are commonly used in Linear Regression (LR) types of models."
},
{
"code": null,
"e": 5203,
"s": 4776,
"text": "However, the difference between them is the interpretation of LR coefficients: whereas in OHE model the intercept represents the mean for the baseline condition and coefficients represents simple effects (the difference between one particular condition and the baseline), in Sum Encoder model the intercept represents the grand mean (across all conditions) and the coefficients can be interpreted directly as the main effects."
},
{
"code": null,
"e": 5857,
"s": 5203,
"text": "Helmert coding is a third commonly used type of categorical encoding for regression along with OHE and Sum Encoding. It compares each level of a categorical variable to the mean of the subsequent levels. Hence, the first contrast compares the mean of the dependent variable for “A” with the mean of all of the subsequent levels of categorical column (“B”, “C”, “D”), the second contrast compares the mean of the dependent variable for “B” with the mean of all of the subsequent levels (“C”, “D”), and the third contrast compares the mean of the dependent variable for “C” with the mean of all of the subsequent levels (in our case only one level — “D”)."
},
{
"code": null,
"e": 6027,
"s": 5857,
"text": "This type of encoding can be useful in certain situations where levels of the categorical variable are ordered, say, from lowest to highest, or from smallest to largest."
},
{
"code": null,
"e": 6420,
"s": 6027,
"text": "Frequency Encoding counts the number of a category’s occurrences in the dataset. New categories in test dataset encoded with either “1” or counts of category in a test dataset, which makes this encoder a little bit tricky: encoding for different sizes of test batch might be different. You should think about it beforehand and make preprocessing of the train as close to the test as possible."
},
{
"code": null,
"e": 6669,
"s": 6420,
"text": "To avoid such problem, you might also consider using a Frequency Encoder variation — Rolling Frequency Encoder (RFE). RFE counts the number a category’s occurrences for the last dt timesteps from a given observation (for example, for dt= 24 hours)."
},
{
"code": null,
"e": 6959,
"s": 6669,
"text": "Nevertheless, Frequency Encoding and RFE are especially efficient when your categorical column has “long tails”, i.e. several frequent values and the remaining ones have only a few examples in the dataset. In such a case, Frequency Encoding would catch the similarity between rare columns."
},
{
"code": null,
"e": 7233,
"s": 6959,
"text": "Target Encoding has probably become the most popular encoding type because of Kaggle competitions. It takes information about the target to encode categories, which makes it extremely powerful. The encoded category values are calculated according to the following formulas:"
},
{
"code": null,
"e": 7516,
"s": 7233,
"text": "Here, mdl — min data (samples) in leaf, a — smoothing parameter, representing the power of regularization. Recommended values for mdl and a are in the range of 1 to 100. New values of category and values with just single appearance in train dataset are replaced with the prior ones."
},
{
"code": null,
"e": 8035,
"s": 7516,
"text": "Target Encoder is a powerful tool, yet it has a huge disadvantage — target leakage: it uses information about the target. Because of the target leakage, model overfits the training data which results in unreliable validation and lower test scores. To reduce the effect of target leakage, we may increase regularization (it’s hard to tune those hyperparameters without unreliable validation), add random noise to the representation of the category in train dataset (some sort of augmentation), or use Double Validation."
},
{
"code": null,
"e": 8288,
"s": 8035,
"text": "M-Estimate Encoder is a simplified version of Target Encoder. It has only one hyperparameter — m, which represents the power of regularization. The higher value of m results into stronger shrinking. Recommended values for m is in the range of 1 to 100."
},
{
"code": null,
"e": 8453,
"s": 8288,
"text": "In different sources, you may find another formula of M-Estimator. Instead of y+ there is n in the denominator. I found that such representation has similar scores."
},
{
"code": null,
"e": 8706,
"s": 8453,
"text": "UPD (17.07.2019): The formula for M-Estimate Encoder in Categorical Encoders library contained a bug. The right one should have n in the denominator. However, both approaches show pretty good scores. The following benchmark is done via “wrong” formula."
},
{
"code": null,
"e": 8920,
"s": 8706,
"text": "Weight Of Evidence is a commonly used target-based encoder in credit scoring. It is a measure of the “strength” of a grouping for separating good and bad risk (default). It is calculated from the basic odds ratio:"
},
{
"code": null,
"e": 9015,
"s": 8920,
"text": "a = Distribution of Good Credit Outcomesb = Distribution of Bad Credit OutcomesWoE = ln(a / b)"
},
{
"code": null,
"e": 9192,
"s": 9015,
"text": "However, if we use formulas as is, it might lead to target leakage and overfit. To avoid that, regularization parameter a is induced and WoE is calculated in the following way:"
},
{
"code": null,
"e": 9703,
"s": 9192,
"text": "James-Stein Encoder is a target-based encoder. This encoder is inspired by James–Stein estimator — the technique named after Charles Stein and Willard James, who simplified Stein’s original Gaussian random vectors mean estimation method of 1956. Stein and James proved that a better estimator than the “perfect” (i.e. mean) estimator exists, which seems to be somewhat of a paradox. However, the James-Stein estimator outperforms the sample mean when there are several unknown populations means — not just one."
},
{
"code": null,
"e": 9851,
"s": 9703,
"text": "The idea behind James-Stein Encoder is simple. Estimation of the mean target for category k could be calculated according to the following formula:"
},
{
"code": null,
"e": 10327,
"s": 9851,
"text": "Encoding is aimed to improve the estimation of the category’s mean target (first member of the amount) by shrinking them towards a more central average (second member of the amount). The only hyperparameter in the formula is B — the power of shrinking. It could be understood as the power of regularization, i.e. the bigger values of B will result in the bigger weight of global mean (underfit), while the lower values of B are, the bigger weight of condition mean (overfit)."
},
{
"code": null,
"e": 10469,
"s": 10327,
"text": "One way to select B is to tune it like a hyperparameter via cross-validation, but Charles Stein came up with another solution to the problem:"
},
{
"code": null,
"e": 10682,
"s": 10469,
"text": "Intuitively, the formula can be seen in the following sense: if we could not rely on the estimation of category mean to target (it has high variance), it means we should assign a bigger weight to the global mean."
},
{
"code": null,
"e": 11153,
"s": 10682,
"text": "Wait, but how we could trust the estimation of variance if we could not rely on the estimation of the mean? Well, we may either say that the variance among all categories is the same and equal to the global variance of y (which might be a good estimation, if we don’t have too many unique categorical values; it is called pooled variance or pooled model) or replace the variances with squared standard errors, which penalize small observation counts (independent model)."
},
{
"code": null,
"e": 11496,
"s": 11153,
"text": "Seems quite fair, but James-Stein Estimator has a big disadvantage — it is defined only for normal distribution (which is not the case for any classification task). To avoid that, we can either convert binary targets with a log-odds ratio as it was done in WoE Encoder (which is used by default because it is simple) or use beta distribution."
},
{
"code": null,
"e": 11731,
"s": 11496,
"text": "Leave-one-out Encoding (LOO or LOOE) is another example of target-based encoders. The name of the method clearly speaks for itself: we calculate mean target of category k for observation j if observation j is removed from the dataset:"
},
{
"code": null,
"e": 11848,
"s": 11731,
"text": "While encoding the test dataset, a category is replaced with the mean target of the category k in the train dataset:"
},
{
"code": null,
"e": 12174,
"s": 11848,
"text": "One of the problems with LOO, just like with all other target-based encoders, is target leakage. But when it comes to LOO, this problem gets really dramatic, as far as we may perfectly classify the training dataset by making a single split: the optimal threshold for category k could be calculated with the following formula:"
},
{
"code": null,
"e": 12634,
"s": 12174,
"text": "Another problem with LOO is a shift between values in the train and the test samples. You could observe it from the picture above. Possible values for category “A” in the train sample are 0.67 and 0.33, while in the test one — 0.5. It is a result of the different number of counts in train and test datasets: for category “A” denominator is equal to n for test and n-1 for train dataset. Such a shift may gradually reduce the performance of tree-based models."
},
{
"code": null,
"e": 13126,
"s": 12634,
"text": "Catboost is a recently created target-based categorical encoder. It is intended to overcome target leakage problems inherent in LOO. In order to do that, the authors of Catboost introduced the idea of “time”: the order of observations in the dataset. Clearly, the values of the target statistic for each example rely only on the observed history. To calculate the statistic for observation j in train dataset, we may use only observations, which are collected before observation j, i.e. i≤j:"
},
{
"code": null,
"e": 13366,
"s": 13126,
"text": "To prevent overfitting, the process of target encoding for train dataset is repeated several times on shuffled versions of the dataset and results are averaged. Encoded values of the test data are calculated the same way as in LOO Encoder:"
},
{
"code": null,
"e": 13571,
"s": 13366,
"text": "Catboost “on the fly” Encoding is one of the core advantages of CatBoost — library for gradient boosting, which showed state of the art results on several tabular datasets when it was presented by Yandex."
},
{
"code": null,
"e": 13968,
"s": 13571,
"text": "Model validation is probably the most important aspect of Machine Learning. While working with data that contains categorical variables, we may want to use one of the three types of validation. None Validation is the simplest one, yet least accurate. Double Validation could show great scores, but it is as slow as a turtle. And Single Validation is kind of a cross between the first two methods."
},
{
"code": null,
"e": 14141,
"s": 13968,
"text": "This section is devoted to the discussion of each validation type in details. For better understanding, for each type of validation, I added block diagrams of the pipeline."
},
{
"code": null,
"e": 14730,
"s": 14141,
"text": "In the case of None Validation, the single encoder is fitted to the whole train data. Validation and test parts of the dataset are processed with the same single encoder. Being the simplest one, this approach is wildly used, but it leads to overfitting during training and unreliable validation scores. The most obvious reasons for that are: for target encoders, None validation induces a shift between train and test part (see an example in LOO encoder); test dataset may contain new categorical values, but neither train nor validation sample contains them during training, that is why:"
},
{
"code": null,
"e": 14783,
"s": 14730,
"text": "The model doesn’t know how to handle new categories;"
},
{
"code": null,
"e": 14856,
"s": 14783,
"text": "The optimal number of trees for train and test samples may be different."
},
{
"code": null,
"e": 15451,
"s": 14856,
"text": "Single Validation is a better way to carry out validation. By using Single Validation we overcome one of the problems of None Validation: the shift between validation and test datasets. Within this approach, we fit separate categorical encoders to each fold of training data. Validation part of each fold is processed the same way as the test data, so it became more similar to it, which positively affects hyperparameters tuning. The optimal hyperparameters obtained from Single Validation would be closer to optimal hyperparameters of test dataset then the ones obtained from None Validation."
},
{
"code": null,
"e": 15793,
"s": 15451,
"text": "Note: while we are tuning hyperparameters, i.e. a number of trees, on validation part of the data the validation scores are going to be slightly overfitted anyway. So will be the test scores, because the type of encoder is also a hyperparameter of the pipeline. I reduced the overfitting effect by making test bigger (40% of the usual data)."
},
{
"code": null,
"e": 16019,
"s": 15793,
"text": "The other good advantage of Single Validation is diversity across folds. By fitting encoder on a subset of the data, we achieve different representation of category, which positively affects the final blending of predictions."
},
{
"code": null,
"e": 16280,
"s": 16019,
"text": "Double Validation is an extension of Single Validation. The pipeline for Double Validation is exactly the same as for Single Validation, except Encoder part: instead of the single encoder for each fold, we will use several encoders fitted on different subsets."
},
{
"code": null,
"e": 16769,
"s": 16280,
"text": "Double Validation aims to reduce the effect of the second problem of None Validation — new categories. It is achieved by splitting each fold into sub-folds, fitting separate encoder to each sub-fold, and then concating (in case of train part) or averaging (in case of validation or test parts) the results. By applying Double Validation we induce a noise (new categories) into training data, which works as augmentation of the data. However, Double Validation has two major disadvantages:"
},
{
"code": null,
"e": 16945,
"s": 16769,
"text": "We can not use it “as is” for encoders, which represents single category as multiple columns (for example, OHE, Sum Encoder, Helmert Encoder, and Backward Difference Encoder);"
},
{
"code": null,
"e": 17070,
"s": 16945,
"text": "The time complexity of Double Validation is approximately k times bigger than in Single validation (k — number of subfolds)."
},
{
"code": null,
"e": 17323,
"s": 17070,
"text": "I hope you aren’t too overwhelmed with the theoretical part and still remember the title of the paper. So, let’s move from that to practice! In the following section, I’m going to show you how I determined the best categorical encoder for tabular data."
},
{
"code": null,
"e": 17802,
"s": 17323,
"text": "I created and tested pipeline for categories benchmarking on the datasets which are presented in the table below. All datasets except poverty_A(B, C) came from different domains; they have a different number of observations, as well as of categorical and numerical features. The objective for all datasets is to perform binary classification. Preprocessing was quite simple: I removed all time-based columns from the datasets. The ones left were either categorical or numerical."
},
{
"code": null,
"e": 18248,
"s": 17802,
"text": "The whole dataset was split into the train (the first 60% of the data) and the test samples (the remaining 40% of the data). The test part is unseen during the training and it is used only once — for final scoring (scoring metric used — ROC AUC). No encoding on whole data, no pseudo labeling, no TTA, etc. were applied during the training or predicting stage. I wanted the experiments to be as close to possible production settings as possible."
},
{
"code": null,
"e": 18766,
"s": 18248,
"text": "After the train-test split, the training data was split into 5 folds with shuffle and stratification. After that, 4 of them were used for the fitting encoder (for a case of None Validation — encoder if fitted to the whole train dataset before splitting) and LightGBM model (LlightGBM — library for gradient boosting from Microsoft), and 1 more fold was used for early stopping. The process was repeated 5 times and in the end, we had 5 trained encoders and 5 LGB models. The LightGBM model parameters were as follows:"
},
{
"code": null,
"e": 18877,
"s": 18766,
"text": "\"metrics\": \"AUC\", \"n_estimators\": 5000, \"learning_rate\": 0.02, \"random_state\": 42,\"early_stopping_rounds\": 100"
},
{
"code": null,
"e": 19143,
"s": 18877,
"text": "During the predicting stage, test data was processed with each of encoders and prediction was made via each of the models. Predictions were then ranked and summed (ROC AUC metric doesn’t care if predictions are averaged or summed; the only importance is the order)."
},
{
"code": null,
"e": 19327,
"s": 19143,
"text": "This section contains the processed results of the experiments. If you’d like to see the raw scores for each dataset, please visit my GitHub repository — CategoricalEncodingBenchmark."
},
{
"code": null,
"e": 19650,
"s": 19327,
"text": "To determine the best encoder, I scaled the ROC AUC scores of each dataset (min-max scale) and then averaged results among the encoder. The obtained result represents the average performance score for each encoder (higher is better). The encoders performance scores for each type of validation are shown in Tables 2.1–2.3."
},
{
"code": null,
"e": 19893,
"s": 19650,
"text": "In order to determine the best validation strategy, I compared the top score of each dataset for each type of validation. The scores improvement (top score for a dataset and an average score for encoder) are shown in Tables 2.4 and 2.5 below."
},
{
"code": null,
"e": 20198,
"s": 19893,
"text": "Best encoder for each dataset and each type of validation was different. However, the non-target encoders (Helmet Encoder and Sum Encoder) dominated all other in None Validation experiment. This is quite an interesting finding because originally these types of encoders were used mostly in Linear Models."
},
{
"code": null,
"e": 20371,
"s": 20198,
"text": "For the case of Single Validation, best encoders were CatBoost Encoder and Ordinal Encoder, which both had a relatively low performance score in None Validation experiment."
},
{
"code": null,
"e": 20635,
"s": 20371,
"text": "Target-based encoders (James-Stein, Catboost, Target, LOO, WOE) with Double Validation showed the best performance scores from all types of validation and encoders. We might call it now the most stable and accurate approach for dealing with categorical variables."
},
{
"code": null,
"e": 21018,
"s": 20635,
"text": "The performance of target-based encoders was improved by inducing the noise to train data. It could be clearly seen in the LOO Encoder — it turned out to be the worse encoder both in None and Sigle Validation with a huge gap to the second worst, but among best in Double Validation. Double Validation (or another variation of regularization) is a must for all target-based encoders."
},
{
"code": null,
"e": 21560,
"s": 21018,
"text": "The results of Frequency Encoder were lowered by increasing the complexity of Validation. This is because the frequency of new categories in the test was counted on the whole test while during Single Validation it was counted on 1/5 of train dataset (5 folds in train dataset), during Double Validation — on 1/25 of train dataset (5 folds in train dataset, 5 subfolds in each fold). Thus, maximum frequencies in testing data were bigger than in train and validation data samples. Do you remember I told you about FE being tricky? That’s why."
},
{
"code": null,
"e": 21687,
"s": 21560,
"text": "I would like to thank Andrey Lukyanenko, Anton Biryukov and Daniel Potapov for fruitful discussion of the results of the work."
},
{
"code": null,
"e": 22458,
"s": 21687,
"text": "R library contrast coding systems for categorical variablesCategory Encoders docsContrast Coding Systems for Categorical VariablesCoding schemes for categorical variables in regression, Coding systems for categorical variables in regression analysisWeight of Evidence (WoE) Introductory OverviewJames–Stein estimator, James-Stein Estimator: Definition, Formulas, Stein’s Paradox in StatisticsA preprocessing scheme for high-cardinality categorical attributes in classification and prediction problemsFeature Engineering in H2O Driverless AI by Dmitry LarkoCatBoost: unbiased boosting with categorical features, Transforming categorical features to numerical features in CatboostThe idea of Double Validation was inspired by Stanislav Semenov talk on “Kaggle BNP Paribas”"
},
{
"code": null,
"e": 22518,
"s": 22458,
"text": "R library contrast coding systems for categorical variables"
},
{
"code": null,
"e": 22541,
"s": 22518,
"text": "Category Encoders docs"
},
{
"code": null,
"e": 22591,
"s": 22541,
"text": "Contrast Coding Systems for Categorical Variables"
},
{
"code": null,
"e": 22711,
"s": 22591,
"text": "Coding schemes for categorical variables in regression, Coding systems for categorical variables in regression analysis"
},
{
"code": null,
"e": 22758,
"s": 22711,
"text": "Weight of Evidence (WoE) Introductory Overview"
},
{
"code": null,
"e": 22856,
"s": 22758,
"text": "James–Stein estimator, James-Stein Estimator: Definition, Formulas, Stein’s Paradox in Statistics"
},
{
"code": null,
"e": 22965,
"s": 22856,
"text": "A preprocessing scheme for high-cardinality categorical attributes in classification and prediction problems"
},
{
"code": null,
"e": 23022,
"s": 22965,
"text": "Feature Engineering in H2O Driverless AI by Dmitry Larko"
},
{
"code": null,
"e": 23145,
"s": 23022,
"text": "CatBoost: unbiased boosting with categorical features, Transforming categorical features to numerical features in Catboost"
}
] |
Check if a number has two adjacent set bits - GeeksforGeeks | 03 May, 2021
Given a number you have to check whether there is pair of adjacent set bit or not.Examples :
Input : N = 67
Output : Yes
There is a pair of adjacent set bit
The binary representation is 100011
Input : N = 5
Output : No
A simple solution is to traverse all bits. For every set bit, check if next bit is also set.An efficient solution is to shift number by 1 and then do bitwise AND. If bitwise AND is non-zero then there are two adjacent set bits. Else not.
C++
Java
Python3
C#
php
Javascript
// CPP program to check// if there are two// adjacent set bits.#include <iostream>using namespace std; bool adjacentSet(int n){ return (n & (n >> 1));} // Driver Codeint main(){ int n = 3; adjacentSet(n) ? cout << "Yes" : cout << "No"; return 0;}
// Java program to check// if there are two// adjacent set bits.class GFG{ static boolean adjacentSet(int n) { int x = (n & (n >> 1)); if(x > 0) return true; else return false; } // Driver code public static void main(String args[]) { int n = 3; if(adjacentSet(n)) System.out.println("Yes"); else System.out.println("No"); }} // This code is contributed by Sam007.
# Python 3 program to check if there# are two adjacent set bits. def adjacentSet(n): return (n & (n >> 1)) # Driver Codeif __name__ == '__main__': n = 3 if (adjacentSet(n)): print("Yes") else: print("No") # This code is contributed by# Shashank_Sharma
// C# program to check// if there are two// adjacent set bits.using System; class GFG{ static bool adjacentSet(int n) { int x = (n & (n >> 1)); if(x > 0) return true; else return false; } // Driver code public static void Main () { int n = 3; if(adjacentSet(n)) Console.WriteLine("Yes"); else Console.WriteLine("No"); } } // This code is contributed by Sam007.
<?php// PHP program to check// if there are two// adjacent set bits. function adjacentSet($n){ return ($n & ($n >> 1));} // Driver Code$n = 3;adjacentSet($n) ? print("Yes") : print("No"); // This code is contributed by Sam007.?>
<script> // Javascript program to check// if there are two// adjacent set bits. function adjacentSet(n) { let x = (n & (n >> 1)); if(x > 0) return true; else return false; } // driver program let n = 3; if(adjacentSet(n)) document.write("Yes"); else document.write("No"); </script>
Output :
Yes
YouTubeGeeksforGeeks500K subscribersCheck if a number has two adjacent set bits | GeeksforGeeksWatch laterShareCopy linkInfoShoppingTap to unmuteIf playback doesn't begin shortly, try restarting your device.You're signed outVideos you watch may be added to the TV's watch history and influence TV recommendations. To avoid this, cancel and sign in to YouTube on your computer.CancelConfirmMore videosMore videosSwitch cameraShareInclude playlistAn error occurred while retrieving sharing information. Please try again later.Watch on0:000:000:00 / 2:28•Live•<div class="player-unavailable"><h1 class="message">An error occurred.</h1><div class="submessage"><a href="https://www.youtube.com/watch?v=vCBaiGkDItM" target="_blank">Try watching this video on www.youtube.com</a>, or enable JavaScript if it is disabled in your browser.</div></div>
This article is contributed by Pranav. 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.
Sam007
Shashank_Sharma
ashwin1
sanjoy_62
Numbers
Bit Magic
Bit Magic
Numbers
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Cyclic Redundancy Check and Modulo-2 Division
Little and Big Endian Mystery
Add two numbers without using arithmetic operators
Find the element that appears once
Set, Clear and Toggle a given bit of a number in C
Bit Fields in C
Bits manipulation (Important tactics)
Josephus problem | Set 1 (A O(n) Solution)
Write an Efficient C Program to Reverse Bits of a Number
C++ bitset and its application | [
{
"code": null,
"e": 25011,
"s": 24983,
"text": "\n03 May, 2021"
},
{
"code": null,
"e": 25106,
"s": 25011,
"text": "Given a number you have to check whether there is pair of adjacent set bit or not.Examples : "
},
{
"code": null,
"e": 25233,
"s": 25106,
"text": "Input : N = 67\nOutput : Yes\nThere is a pair of adjacent set bit\nThe binary representation is 100011\n\nInput : N = 5\nOutput : No"
},
{
"code": null,
"e": 25475,
"s": 25235,
"text": "A simple solution is to traverse all bits. For every set bit, check if next bit is also set.An efficient solution is to shift number by 1 and then do bitwise AND. If bitwise AND is non-zero then there are two adjacent set bits. Else not. "
},
{
"code": null,
"e": 25479,
"s": 25475,
"text": "C++"
},
{
"code": null,
"e": 25484,
"s": 25479,
"text": "Java"
},
{
"code": null,
"e": 25492,
"s": 25484,
"text": "Python3"
},
{
"code": null,
"e": 25495,
"s": 25492,
"text": "C#"
},
{
"code": null,
"e": 25499,
"s": 25495,
"text": "php"
},
{
"code": null,
"e": 25510,
"s": 25499,
"text": "Javascript"
},
{
"code": "// CPP program to check// if there are two// adjacent set bits.#include <iostream>using namespace std; bool adjacentSet(int n){ return (n & (n >> 1));} // Driver Codeint main(){ int n = 3; adjacentSet(n) ? cout << \"Yes\" : cout << \"No\"; return 0;}",
"e": 25779,
"s": 25510,
"text": null
},
{
"code": "// Java program to check// if there are two// adjacent set bits.class GFG{ static boolean adjacentSet(int n) { int x = (n & (n >> 1)); if(x > 0) return true; else return false; } // Driver code public static void main(String args[]) { int n = 3; if(adjacentSet(n)) System.out.println(\"Yes\"); else System.out.println(\"No\"); }} // This code is contributed by Sam007.",
"e": 26281,
"s": 25779,
"text": null
},
{
"code": "# Python 3 program to check if there# are two adjacent set bits. def adjacentSet(n): return (n & (n >> 1)) # Driver Codeif __name__ == '__main__': n = 3 if (adjacentSet(n)): print(\"Yes\") else: print(\"No\") # This code is contributed by# Shashank_Sharma",
"e": 26567,
"s": 26281,
"text": null
},
{
"code": "// C# program to check// if there are two// adjacent set bits.using System; class GFG{ static bool adjacentSet(int n) { int x = (n & (n >> 1)); if(x > 0) return true; else return false; } // Driver code public static void Main () { int n = 3; if(adjacentSet(n)) Console.WriteLine(\"Yes\"); else Console.WriteLine(\"No\"); } } // This code is contributed by Sam007.",
"e": 27066,
"s": 26567,
"text": null
},
{
"code": "<?php// PHP program to check// if there are two// adjacent set bits. function adjacentSet($n){ return ($n & ($n >> 1));} // Driver Code$n = 3;adjacentSet($n) ? print(\"Yes\") : print(\"No\"); // This code is contributed by Sam007.?>",
"e": 27304,
"s": 27066,
"text": null
},
{
"code": "<script> // Javascript program to check// if there are two// adjacent set bits. function adjacentSet(n) { let x = (n & (n >> 1)); if(x > 0) return true; else return false; } // driver program let n = 3; if(adjacentSet(n)) document.write(\"Yes\"); else document.write(\"No\"); </script>",
"e": 27709,
"s": 27304,
"text": null
},
{
"code": null,
"e": 27720,
"s": 27709,
"text": "Output : "
},
{
"code": null,
"e": 27724,
"s": 27720,
"text": "Yes"
},
{
"code": null,
"e": 28568,
"s": 27726,
"text": "YouTubeGeeksforGeeks500K subscribersCheck if a number has two adjacent set bits | GeeksforGeeksWatch laterShareCopy linkInfoShoppingTap to unmuteIf playback doesn't begin shortly, try restarting your device.You're signed outVideos you watch may be added to the TV's watch history and influence TV recommendations. To avoid this, cancel and sign in to YouTube on your computer.CancelConfirmMore videosMore videosSwitch cameraShareInclude playlistAn error occurred while retrieving sharing information. Please try again later.Watch on0:000:000:00 / 2:28•Live•<div class=\"player-unavailable\"><h1 class=\"message\">An error occurred.</h1><div class=\"submessage\"><a href=\"https://www.youtube.com/watch?v=vCBaiGkDItM\" 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": 28983,
"s": 28568,
"text": "This article is contributed by Pranav. 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": 28990,
"s": 28983,
"text": "Sam007"
},
{
"code": null,
"e": 29006,
"s": 28990,
"text": "Shashank_Sharma"
},
{
"code": null,
"e": 29014,
"s": 29006,
"text": "ashwin1"
},
{
"code": null,
"e": 29024,
"s": 29014,
"text": "sanjoy_62"
},
{
"code": null,
"e": 29032,
"s": 29024,
"text": "Numbers"
},
{
"code": null,
"e": 29042,
"s": 29032,
"text": "Bit Magic"
},
{
"code": null,
"e": 29052,
"s": 29042,
"text": "Bit Magic"
},
{
"code": null,
"e": 29060,
"s": 29052,
"text": "Numbers"
},
{
"code": null,
"e": 29158,
"s": 29060,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 29167,
"s": 29158,
"text": "Comments"
},
{
"code": null,
"e": 29180,
"s": 29167,
"text": "Old Comments"
},
{
"code": null,
"e": 29226,
"s": 29180,
"text": "Cyclic Redundancy Check and Modulo-2 Division"
},
{
"code": null,
"e": 29256,
"s": 29226,
"text": "Little and Big Endian Mystery"
},
{
"code": null,
"e": 29307,
"s": 29256,
"text": "Add two numbers without using arithmetic operators"
},
{
"code": null,
"e": 29342,
"s": 29307,
"text": "Find the element that appears once"
},
{
"code": null,
"e": 29393,
"s": 29342,
"text": "Set, Clear and Toggle a given bit of a number in C"
},
{
"code": null,
"e": 29409,
"s": 29393,
"text": "Bit Fields in C"
},
{
"code": null,
"e": 29447,
"s": 29409,
"text": "Bits manipulation (Important tactics)"
},
{
"code": null,
"e": 29490,
"s": 29447,
"text": "Josephus problem | Set 1 (A O(n) Solution)"
},
{
"code": null,
"e": 29547,
"s": 29490,
"text": "Write an Efficient C Program to Reverse Bits of a Number"
}
] |
How to unbind “hover” event using JQuery? - GeeksforGeeks | 06 Sep, 2019
The problem unbind the hover effect of particular element with the help of JQuery. Here we are using 2 JQuery methods .unbind() and .off() method. Here are few techniques discussed.
Approach:
Select the element whose Hover effect needs to be unbinded.(Make sure Hover effect should be added by JQuery only, Hover effect added by CSS doesn’t work here).
Use either .unbind() or .off() method.
Pass the events that we want to turn off for that particular element.
Example 1: This example using the .unbind() method.
<!DOCTYPE HTML><html> <head> <title> How to unbind “hover” event using JQuery? </title> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"> </script> <style> #div { height: 100px; width: 200px; background: green; color: white; margin: 0 auto; } </style></head> <body style="text-align:center;"> <h1 id="h1" style="color:green;"> GeeksForGeeks </h1> <p id="GFG_UP" style="font-size: 15px; font-weight: bold;"> </p> <div id="div"> Hover It </div> <br> <button onclick="gfg_Run()"> Unbind </button> <p id="GFG_DOWN" style="font-size: 23px; font-weight: bold; color: green; "> </p> <script> var el_up = document.getElementById("GFG_UP"); var el_down = document.getElementById("GFG_DOWN"); var heading = document.getElementById("h1"); var div = document.getElementById("div"); el_up.innerHTML = "Click on the button to unbind the hover from the element."; $("#div").hover(function() { $(this).css("background-color", "blue"); }, function() { $(this).css("background-color", "green"); }); function gfg_Run() { $('#div').unbind('mouseenter mouseleave'); el_down.innerHTML = "Hover effect Unbinded."; } </script></body> </html>
Output:
Before clicking on the button:
On hovering over the element:
After clicking on the button:
Example 2: This example using the .off() method.
<!DOCTYPE HTML><html> <head> <title> How to unbind “hover” event using JQuery? </title> <script src= "https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"> </script> <style> #div { height: 100px; width: 200px; background: green; color: white; margin: 0 auto; } </style></head> <body style="text-align:center;"> <h1 id="h1" style="color:green;"> GeeksForGeeks </h1> <p id="GFG_UP" style="font-size: 15px; font-weight: bold;"> </p> <div id="div"> Hover It </div> <br> <button onclick="gfg_Run()"> Unbind </button> <p id="GFG_DOWN" style="font-size: 23px; font-weight: bold; color: green; "> </p> <script> var el_up = document.getElementById("GFG_UP"); var el_down = document.getElementById("GFG_DOWN"); var heading = document.getElementById("h1"); var div = document.getElementById("div"); el_up.innerHTML = "Click on the button to unbind the hover from the element."; $("#div").hover(function() { $(this).css("background-color", "blue"); }, function() { $(this).css("background-color", "green"); }); function gfg_Run() { $('#div').off('mouseenter mouseleave'); el_down.innerHTML = "Hover effect Unbinded."; } </script></body> </html>
Output:
Before clicking on the button:
On hovering over the element:
After clicking on the button:
jQuery-Misc
JQuery
Web Technologies
Web technologies Questions
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Form validation using jQuery
How to Dynamically Add/Remove Table Rows using jQuery ?
Scroll to the top of the page using JavaScript/jQuery
How to get the ID of the clicked button using JavaScript / jQuery ?
jQuery | children() with Examples
Top 10 Front End Developer Skills That You Need in 2022
Installation of Node.js on Linux
Top 10 Projects For Beginners To Practice HTML and CSS Skills
How to fetch data from an API in ReactJS ?
How to insert spaces/tabs in text using HTML/CSS? | [
{
"code": null,
"e": 25096,
"s": 25068,
"text": "\n06 Sep, 2019"
},
{
"code": null,
"e": 25278,
"s": 25096,
"text": "The problem unbind the hover effect of particular element with the help of JQuery. Here we are using 2 JQuery methods .unbind() and .off() method. Here are few techniques discussed."
},
{
"code": null,
"e": 25288,
"s": 25278,
"text": "Approach:"
},
{
"code": null,
"e": 25449,
"s": 25288,
"text": "Select the element whose Hover effect needs to be unbinded.(Make sure Hover effect should be added by JQuery only, Hover effect added by CSS doesn’t work here)."
},
{
"code": null,
"e": 25488,
"s": 25449,
"text": "Use either .unbind() or .off() method."
},
{
"code": null,
"e": 25558,
"s": 25488,
"text": "Pass the events that we want to turn off for that particular element."
},
{
"code": null,
"e": 25610,
"s": 25558,
"text": "Example 1: This example using the .unbind() method."
},
{
"code": "<!DOCTYPE HTML><html> <head> <title> How to unbind “hover” event using JQuery? </title> <script src=\"https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js\"> </script> <style> #div { height: 100px; width: 200px; background: green; color: white; margin: 0 auto; } </style></head> <body style=\"text-align:center;\"> <h1 id=\"h1\" style=\"color:green;\"> GeeksForGeeks </h1> <p id=\"GFG_UP\" style=\"font-size: 15px; font-weight: bold;\"> </p> <div id=\"div\"> Hover It </div> <br> <button onclick=\"gfg_Run()\"> Unbind </button> <p id=\"GFG_DOWN\" style=\"font-size: 23px; font-weight: bold; color: green; \"> </p> <script> var el_up = document.getElementById(\"GFG_UP\"); var el_down = document.getElementById(\"GFG_DOWN\"); var heading = document.getElementById(\"h1\"); var div = document.getElementById(\"div\"); el_up.innerHTML = \"Click on the button to unbind the hover from the element.\"; $(\"#div\").hover(function() { $(this).css(\"background-color\", \"blue\"); }, function() { $(this).css(\"background-color\", \"green\"); }); function gfg_Run() { $('#div').unbind('mouseenter mouseleave'); el_down.innerHTML = \"Hover effect Unbinded.\"; } </script></body> </html>",
"e": 27124,
"s": 25610,
"text": null
},
{
"code": null,
"e": 27132,
"s": 27124,
"text": "Output:"
},
{
"code": null,
"e": 27163,
"s": 27132,
"text": "Before clicking on the button:"
},
{
"code": null,
"e": 27193,
"s": 27163,
"text": "On hovering over the element:"
},
{
"code": null,
"e": 27223,
"s": 27193,
"text": "After clicking on the button:"
},
{
"code": null,
"e": 27272,
"s": 27223,
"text": "Example 2: This example using the .off() method."
},
{
"code": "<!DOCTYPE HTML><html> <head> <title> How to unbind “hover” event using JQuery? </title> <script src= \"https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js\"> </script> <style> #div { height: 100px; width: 200px; background: green; color: white; margin: 0 auto; } </style></head> <body style=\"text-align:center;\"> <h1 id=\"h1\" style=\"color:green;\"> GeeksForGeeks </h1> <p id=\"GFG_UP\" style=\"font-size: 15px; font-weight: bold;\"> </p> <div id=\"div\"> Hover It </div> <br> <button onclick=\"gfg_Run()\"> Unbind </button> <p id=\"GFG_DOWN\" style=\"font-size: 23px; font-weight: bold; color: green; \"> </p> <script> var el_up = document.getElementById(\"GFG_UP\"); var el_down = document.getElementById(\"GFG_DOWN\"); var heading = document.getElementById(\"h1\"); var div = document.getElementById(\"div\"); el_up.innerHTML = \"Click on the button to unbind the hover from the element.\"; $(\"#div\").hover(function() { $(this).css(\"background-color\", \"blue\"); }, function() { $(this).css(\"background-color\", \"green\"); }); function gfg_Run() { $('#div').off('mouseenter mouseleave'); el_down.innerHTML = \"Hover effect Unbinded.\"; } </script></body> </html>",
"e": 28758,
"s": 27272,
"text": null
},
{
"code": null,
"e": 28766,
"s": 28758,
"text": "Output:"
},
{
"code": null,
"e": 28797,
"s": 28766,
"text": "Before clicking on the button:"
},
{
"code": null,
"e": 28827,
"s": 28797,
"text": "On hovering over the element:"
},
{
"code": null,
"e": 28857,
"s": 28827,
"text": "After clicking on the button:"
},
{
"code": null,
"e": 28869,
"s": 28857,
"text": "jQuery-Misc"
},
{
"code": null,
"e": 28876,
"s": 28869,
"text": "JQuery"
},
{
"code": null,
"e": 28893,
"s": 28876,
"text": "Web Technologies"
},
{
"code": null,
"e": 28920,
"s": 28893,
"text": "Web technologies Questions"
},
{
"code": null,
"e": 29018,
"s": 28920,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 29027,
"s": 29018,
"text": "Comments"
},
{
"code": null,
"e": 29040,
"s": 29027,
"text": "Old Comments"
},
{
"code": null,
"e": 29069,
"s": 29040,
"text": "Form validation using jQuery"
},
{
"code": null,
"e": 29125,
"s": 29069,
"text": "How to Dynamically Add/Remove Table Rows using jQuery ?"
},
{
"code": null,
"e": 29179,
"s": 29125,
"text": "Scroll to the top of the page using JavaScript/jQuery"
},
{
"code": null,
"e": 29247,
"s": 29179,
"text": "How to get the ID of the clicked button using JavaScript / jQuery ?"
},
{
"code": null,
"e": 29281,
"s": 29247,
"text": "jQuery | children() with Examples"
},
{
"code": null,
"e": 29337,
"s": 29281,
"text": "Top 10 Front End Developer Skills That You Need in 2022"
},
{
"code": null,
"e": 29370,
"s": 29337,
"text": "Installation of Node.js on Linux"
},
{
"code": null,
"e": 29432,
"s": 29370,
"text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills"
},
{
"code": null,
"e": 29475,
"s": 29432,
"text": "How to fetch data from an API in ReactJS ?"
}
] |
Customer segmentation with BigQuery ML: unsupervised learning without Python! | by Taís L. Pereira | Towards Data Science | Don’t get me wrong, I’m a big Python fan, both for unsupervised and supervised learning. However, since Kramp Hub’s 1 data warehouse is based on Google Cloud Platform (GCP), an alternative solution got my attention this time: BigQuery ML.
BigQuery Machine Learning (ML) is a GCP’s feature to operationalize ML algorithms directly within the BigQuery environment. Using only SQL, models can be developed, trained, and used for predictions. With that, it democratizes ML’s operationalization for data analysts and other DWH users. Moreover, due to its integration with the DWH, models’ development speed and complexity are reduced.
“BigQuery ML brings ML to the data”.
It supports a wide range of models, such as Linear and Binary Regression, Deep Neural Network, XGBoost, K-means clustering, among others. Considering that our topic is customer segmentation, can you guess the chosen one? Yes, you got it right, I’ll talk about K-means 2.
But first, let’s dive into the business problem that we were trying to solve.
Customer segmentation is a fundamental part of customer analytics. My interest in that was consolidated after researching Peter Fader’s customer-centricity work. Author of the book Customer Centricity: Focus on the Right Customers for Strategic Advantage and professor at the Wharton School of the University of Pennsylvania, Fader proposes the utilization of users’ behavioral data to determine customer value.
“with today’s ability to obtain better data and the computing technology to process that data, combined with a better understanding of analytics, we can gain a better understanding of customers than ever before.”
Given the large amount of clickstream e-commerce data available on our DWH — with more than 64 million rows containing sessions’ information — I decided to do a segmentation based on that. Additionally, Kramp Groep operates in 24 different countries, with varied economical aspects that could turn into a bias in our model. Therefore, instead of the traditional RFM (recency, frequency and monetary value) method, the RFE (recency, frequency and “engagement”) approach was used, in which:
Recency is how recent was the last session captured by our back-end stack;
Frequency is the number of repeated search events;
Engagement is the total duration of the interactions (sessions) in minutes.
In our original dataset, each row is related to a unique session. However, to serve as an input to the K-means model, a different shape is needed. Instead of the previous format, the data needs to be summarized by each user_id (customer_id). With this idea, an RFE table was created:
Later, it was defined that recently acquired users, or users with recency=0 or frequency=0, should be filtered out, as can be seen in the code shown in the next section. With that, our input data contained approximately 70.000 rows.
Now comes the fun technical stuff! First, to generate a model on BQ, the CREATE OR REPLACE MODEL statement has to be used, with the model type specified in sequence. In our case, MODEL_TYPE=’KMEANS’ does the job. Additionally, KMEANS_INIT_METHOD defines the centroids’ initialization method, in which KMEANS++ was the chosen argument, instead of RANDOM. According to GCP’s documentation, KMEANS++ results in a more efficient model than the latter, leading to an optimal solution when compared to an initialization based on randomly selected data points. A nice article with more technical information about those different methods can be seen here. Moreover, STANDARDIZE_FEATURES defines if the model will standardize the numerical inputs, taking the arguments True or False.
CREATE OR REPLACE MODEL data_science_datasets.rfe_clusters OPTIONS(MODEL_TYPE='KMEANS', KMEANS_INIT_METHOD = 'KMEANS++', STANDARDIZE_FEATURES = TRUE) ASWITH rfe_table AS ( SELECT user_id, country_code AS country, DATE_DIFF(MAX(DATE(bq_metric_timestamp)), MIN(DATE(bq_metric_timestamp)), DAY) AS recency, (SUM(search_event_count) -1) AS frequency, ROUND((SUM(session_duration_ms)/1000)/60,2) AS engagement, FROM `your_project.dwh.session_metrics_generic` WHERE DATE(bq_metric_timestamp) >= "2019-07-01" AND DATE(bq_metric_timestamp) < "2020-01-01" GROUP BY user_id, country)SELECT * EXCEPT(user_id, country)FROM rfe_tableWHERE recency>0 AND frequency>0ORDER BY country ASC
You must have been wondering: what about the number of clusters? Yes, it was not defined in the code through the NUM_CLUSTERS parameter. When omitted, BigQuery ML will automatically define it, based on the dataset’s size. This can lead to an optimal cluster number — which in our case was 4 — but it’s not the rule. In order to find an optimal number of clusters, different values should be tested, and the one that yields the lowest Davies-Bouldin index (see next section) is the winner. However, omitting this parameter leads to a reasonable solution and improves the automation for this part, since it’s possible to schedule the CREATE MODEL query to periodically generate a new model. In addition, this is an improvement in terms of the similar Python implementation, where it would be necessary to check an Elbow Method graph and check where the curve flattens, and then choose the number of the clusters:
The model was created using data from 6 months of the last year (2019).
Model evaluation
After creating your model, a table is generated in the specified dataset (thus change the code part data_science_datasets.rfe_clusters to what is applicable for you). Clicking in “evaluation” will display the error value (David-Bouldin index) and the numeric features for each cluster centroid:
As it can be seen, the error for a number of clusters equal to 4 is pretty low (below 1), which can be interpreted as a solid result. In comparison, with NUM_CLUSTERS=5, the index was 0.7927.
With the centroids defined, now we can attribute user-friendly names to each customer segment and predict the segments for data from the current year, using ML.PREDICT. From what can be seen from the variables’ values for centroid 3, these are our most loyal customers, “champions” — old relationship (high recency), high frequency of searches, and high engagement. In contrast, customers with centroid 2 are relatively “new”, since their recency value is considerably lower. Moreover, the centroid=4 shows old users with low frequency and low engagement, so this is our group “at-risk”. Finally, the centroid 1 accounts for “regular” customers:
WITH RFE_segments AS ( WITH rfe_table AS ( SELECT user_id, ANY_VALUE(country_code) AS country, DATE_DIFF(MAX(DATE(bq_metric_timestamp)), MIN(DATE(bq_metric_timestamp)), DAY) AS recency, (SUM(search_event_count) -1) AS frequency, ROUND((SUM(session_duration_ms)/1000)/60,2) AS engagement, FROM `your_project.dwh.session_metrics_generic` WHERE DATE(bq_metric_timestamp) >= "2020-01-01" GROUP BY user_id) SELECT user_id, country, recency, frequency, engagement, FROM rfe_table WHERE recency>0 AND frequency>0 ORDER BY country ASC)SELECT CASE WHEN CENTROID_ID = 1 THEN 'Regular' WHEN CENTROID_ID = 2 THEN 'New' WHEN CENTROID_ID = 3 THEN 'Champions' WHEN CENTROID_ID = 4 THEN 'At Risk'END AS segments, * EXCEPT (nearest_centroids_distance)FROM ML.PREDICT(MODEL data_science_datasets.rfe_clusters, ( SELECT * FROM RFE_segments))
As you can see from the code above, considering that we are interested in predicting clusters in the present year, the date condition was changed to DATE(bq_metric_timestamp) >= “2020–01–01”. Therefore, every time that I run the query above, it will consider data from January 2020 until the current date, with new sessions captured continuously.
The segments can be displayed in a Google Data Studio report, where additional filters can be added, as the country filter in this example. Our report shows the count of users in each segment, the average distribution of variables, and how each segment is positioned in terms of pairs of variables:
From these graphs, we can think about the following implications:
A large number of users “at-risk” can lead to an investigation of the platform features and/or an analysis if the right group is being attracted to the website;
“Champions” can be given special attention to increase cross-selling or up-selling through search features improvements and new functionalities;
The customer segment label can be incorporated in a platform microservice as a metric, and trigger a message to the sales/marketing team;
I hope you enjoyed this post and got inspired to start your own customer segmentation journey!
Special thanks to Jelmer Krauwer and Ernest Micklei for revising it.
[1] Kramp Hub is a corporate start-up part of Kramp Group, Europe’s largest specialist in spare parts and accessories for the agricultural industry. Our technology and products enable both our current tenants, Kramp and Maykers, to stay future-proof with our e-commerce solutions.
[2] A detailed explanation about the K-means algorithm can be seen on Scikit-learn documentation, here. | [
{
"code": null,
"e": 411,
"s": 172,
"text": "Don’t get me wrong, I’m a big Python fan, both for unsupervised and supervised learning. However, since Kramp Hub’s 1 data warehouse is based on Google Cloud Platform (GCP), an alternative solution got my attention this time: BigQuery ML."
},
{
"code": null,
"e": 802,
"s": 411,
"text": "BigQuery Machine Learning (ML) is a GCP’s feature to operationalize ML algorithms directly within the BigQuery environment. Using only SQL, models can be developed, trained, and used for predictions. With that, it democratizes ML’s operationalization for data analysts and other DWH users. Moreover, due to its integration with the DWH, models’ development speed and complexity are reduced."
},
{
"code": null,
"e": 839,
"s": 802,
"text": "“BigQuery ML brings ML to the data”."
},
{
"code": null,
"e": 1110,
"s": 839,
"text": "It supports a wide range of models, such as Linear and Binary Regression, Deep Neural Network, XGBoost, K-means clustering, among others. Considering that our topic is customer segmentation, can you guess the chosen one? Yes, you got it right, I’ll talk about K-means 2."
},
{
"code": null,
"e": 1188,
"s": 1110,
"text": "But first, let’s dive into the business problem that we were trying to solve."
},
{
"code": null,
"e": 1600,
"s": 1188,
"text": "Customer segmentation is a fundamental part of customer analytics. My interest in that was consolidated after researching Peter Fader’s customer-centricity work. Author of the book Customer Centricity: Focus on the Right Customers for Strategic Advantage and professor at the Wharton School of the University of Pennsylvania, Fader proposes the utilization of users’ behavioral data to determine customer value."
},
{
"code": null,
"e": 1813,
"s": 1600,
"text": "“with today’s ability to obtain better data and the computing technology to process that data, combined with a better understanding of analytics, we can gain a better understanding of customers than ever before.”"
},
{
"code": null,
"e": 2302,
"s": 1813,
"text": "Given the large amount of clickstream e-commerce data available on our DWH — with more than 64 million rows containing sessions’ information — I decided to do a segmentation based on that. Additionally, Kramp Groep operates in 24 different countries, with varied economical aspects that could turn into a bias in our model. Therefore, instead of the traditional RFM (recency, frequency and monetary value) method, the RFE (recency, frequency and “engagement”) approach was used, in which:"
},
{
"code": null,
"e": 2377,
"s": 2302,
"text": "Recency is how recent was the last session captured by our back-end stack;"
},
{
"code": null,
"e": 2428,
"s": 2377,
"text": "Frequency is the number of repeated search events;"
},
{
"code": null,
"e": 2504,
"s": 2428,
"text": "Engagement is the total duration of the interactions (sessions) in minutes."
},
{
"code": null,
"e": 2788,
"s": 2504,
"text": "In our original dataset, each row is related to a unique session. However, to serve as an input to the K-means model, a different shape is needed. Instead of the previous format, the data needs to be summarized by each user_id (customer_id). With this idea, an RFE table was created:"
},
{
"code": null,
"e": 3021,
"s": 2788,
"text": "Later, it was defined that recently acquired users, or users with recency=0 or frequency=0, should be filtered out, as can be seen in the code shown in the next section. With that, our input data contained approximately 70.000 rows."
},
{
"code": null,
"e": 3797,
"s": 3021,
"text": "Now comes the fun technical stuff! First, to generate a model on BQ, the CREATE OR REPLACE MODEL statement has to be used, with the model type specified in sequence. In our case, MODEL_TYPE=’KMEANS’ does the job. Additionally, KMEANS_INIT_METHOD defines the centroids’ initialization method, in which KMEANS++ was the chosen argument, instead of RANDOM. According to GCP’s documentation, KMEANS++ results in a more efficient model than the latter, leading to an optimal solution when compared to an initialization based on randomly selected data points. A nice article with more technical information about those different methods can be seen here. Moreover, STANDARDIZE_FEATURES defines if the model will standardize the numerical inputs, taking the arguments True or False."
},
{
"code": null,
"e": 4516,
"s": 3797,
"text": "CREATE OR REPLACE MODEL data_science_datasets.rfe_clusters OPTIONS(MODEL_TYPE='KMEANS', KMEANS_INIT_METHOD = 'KMEANS++', STANDARDIZE_FEATURES = TRUE) ASWITH rfe_table AS ( SELECT user_id, country_code AS country, DATE_DIFF(MAX(DATE(bq_metric_timestamp)), MIN(DATE(bq_metric_timestamp)), DAY) AS recency, (SUM(search_event_count) -1) AS frequency, ROUND((SUM(session_duration_ms)/1000)/60,2) AS engagement, FROM `your_project.dwh.session_metrics_generic` WHERE DATE(bq_metric_timestamp) >= \"2019-07-01\" AND DATE(bq_metric_timestamp) < \"2020-01-01\" GROUP BY user_id, country)SELECT * EXCEPT(user_id, country)FROM rfe_tableWHERE recency>0 AND frequency>0ORDER BY country ASC"
},
{
"code": null,
"e": 5427,
"s": 4516,
"text": "You must have been wondering: what about the number of clusters? Yes, it was not defined in the code through the NUM_CLUSTERS parameter. When omitted, BigQuery ML will automatically define it, based on the dataset’s size. This can lead to an optimal cluster number — which in our case was 4 — but it’s not the rule. In order to find an optimal number of clusters, different values should be tested, and the one that yields the lowest Davies-Bouldin index (see next section) is the winner. However, omitting this parameter leads to a reasonable solution and improves the automation for this part, since it’s possible to schedule the CREATE MODEL query to periodically generate a new model. In addition, this is an improvement in terms of the similar Python implementation, where it would be necessary to check an Elbow Method graph and check where the curve flattens, and then choose the number of the clusters:"
},
{
"code": null,
"e": 5499,
"s": 5427,
"text": "The model was created using data from 6 months of the last year (2019)."
},
{
"code": null,
"e": 5516,
"s": 5499,
"text": "Model evaluation"
},
{
"code": null,
"e": 5811,
"s": 5516,
"text": "After creating your model, a table is generated in the specified dataset (thus change the code part data_science_datasets.rfe_clusters to what is applicable for you). Clicking in “evaluation” will display the error value (David-Bouldin index) and the numeric features for each cluster centroid:"
},
{
"code": null,
"e": 6003,
"s": 5811,
"text": "As it can be seen, the error for a number of clusters equal to 4 is pretty low (below 1), which can be interpreted as a solid result. In comparison, with NUM_CLUSTERS=5, the index was 0.7927."
},
{
"code": null,
"e": 6649,
"s": 6003,
"text": "With the centroids defined, now we can attribute user-friendly names to each customer segment and predict the segments for data from the current year, using ML.PREDICT. From what can be seen from the variables’ values for centroid 3, these are our most loyal customers, “champions” — old relationship (high recency), high frequency of searches, and high engagement. In contrast, customers with centroid 2 are relatively “new”, since their recency value is considerably lower. Moreover, the centroid=4 shows old users with low frequency and low engagement, so this is our group “at-risk”. Finally, the centroid 1 accounts for “regular” customers:"
},
{
"code": null,
"e": 7595,
"s": 6649,
"text": "WITH RFE_segments AS ( WITH rfe_table AS ( SELECT user_id, ANY_VALUE(country_code) AS country, DATE_DIFF(MAX(DATE(bq_metric_timestamp)), MIN(DATE(bq_metric_timestamp)), DAY) AS recency, (SUM(search_event_count) -1) AS frequency, ROUND((SUM(session_duration_ms)/1000)/60,2) AS engagement, FROM `your_project.dwh.session_metrics_generic` WHERE DATE(bq_metric_timestamp) >= \"2020-01-01\" GROUP BY user_id) SELECT user_id, country, recency, frequency, engagement, FROM rfe_table WHERE recency>0 AND frequency>0 ORDER BY country ASC)SELECT CASE WHEN CENTROID_ID = 1 THEN 'Regular' WHEN CENTROID_ID = 2 THEN 'New' WHEN CENTROID_ID = 3 THEN 'Champions' WHEN CENTROID_ID = 4 THEN 'At Risk'END AS segments, * EXCEPT (nearest_centroids_distance)FROM ML.PREDICT(MODEL data_science_datasets.rfe_clusters, ( SELECT * FROM RFE_segments))"
},
{
"code": null,
"e": 7942,
"s": 7595,
"text": "As you can see from the code above, considering that we are interested in predicting clusters in the present year, the date condition was changed to DATE(bq_metric_timestamp) >= “2020–01–01”. Therefore, every time that I run the query above, it will consider data from January 2020 until the current date, with new sessions captured continuously."
},
{
"code": null,
"e": 8241,
"s": 7942,
"text": "The segments can be displayed in a Google Data Studio report, where additional filters can be added, as the country filter in this example. Our report shows the count of users in each segment, the average distribution of variables, and how each segment is positioned in terms of pairs of variables:"
},
{
"code": null,
"e": 8307,
"s": 8241,
"text": "From these graphs, we can think about the following implications:"
},
{
"code": null,
"e": 8468,
"s": 8307,
"text": "A large number of users “at-risk” can lead to an investigation of the platform features and/or an analysis if the right group is being attracted to the website;"
},
{
"code": null,
"e": 8613,
"s": 8468,
"text": "“Champions” can be given special attention to increase cross-selling or up-selling through search features improvements and new functionalities;"
},
{
"code": null,
"e": 8751,
"s": 8613,
"text": "The customer segment label can be incorporated in a platform microservice as a metric, and trigger a message to the sales/marketing team;"
},
{
"code": null,
"e": 8846,
"s": 8751,
"text": "I hope you enjoyed this post and got inspired to start your own customer segmentation journey!"
},
{
"code": null,
"e": 8915,
"s": 8846,
"text": "Special thanks to Jelmer Krauwer and Ernest Micklei for revising it."
},
{
"code": null,
"e": 9196,
"s": 8915,
"text": "[1] Kramp Hub is a corporate start-up part of Kramp Group, Europe’s largest specialist in spare parts and accessories for the agricultural industry. Our technology and products enable both our current tenants, Kramp and Maykers, to stay future-proof with our e-commerce solutions."
}
] |
How to run Invoke-Command in PowerShell Workflow? | To run Invoke-Command in PowerShell Workflow we need to use the InlineScript block because Invoke-Command is not supported directly in the workflow. The below example is without using the InlineScript block we get an error.
Workflow TestInvokeCommand{
Invoke-Command -ComputerName LabMachine2k16 -ScriptBlock{
Get-Service WINRM
}
}
At line:2 char:5
+ Invoke-Command -ComputerName LabMachine2k16 -ScriptBlock{
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Cannot call the 'Invoke-Command' command. Other commands from this module have been packaged as workflow activities, but this
command was specifically excluded. This is likely because the command requires an interactive Windows PowerShell session, or has
behavior not suited for workflows. To run this command anyway, place it within an inline-script (InlineScript { Invoke-Command })
where it will be invoked in isolation.
+ CategoryInfo : ParserError: (:) [], ParseException
+ FullyQualifiedErrorId : CommandActivityExcluded
The above error indicates that the Invoke-Command can’t be directly used with the PowerShell and we need to use it inside the InlineScript block as shown below.
Workflow TestInvokeCommand{
InlineScript{
Invoke-Command -ComputerName LabMachine2k16 -ScriptBlock{
Get-Service WINRM
}
}
}
TestInvokeCommand
To use the outside variable in the scriptblock inside InlineScript block, we need to use $Using:VariableName. For example,
Workflow TestInvokeCommand{
$server = "Labmachine2k16"
InlineScript{
Invoke-Command -ComputerName $using:Server -ScriptBlock{
Get-Service WINRM
}
}
}
TestInvokeCommand
To store the output variable,
Workflow TestInvokeCommand{
$server = "Labmachine2k16"
$Status = InlineScript{
Invoke-Command -ComputerName $using:Server -ScriptBlock{
return( Get-Service WINRM).Status
}
}
Write-Output "WinRM Status: $status"
}
TestInvokeCommand | [
{
"code": null,
"e": 1286,
"s": 1062,
"text": "To run Invoke-Command in PowerShell Workflow we need to use the InlineScript block because Invoke-Command is not supported directly in the workflow. The below example is without using the InlineScript block we get an error."
},
{
"code": null,
"e": 1406,
"s": 1286,
"text": "Workflow TestInvokeCommand{\n Invoke-Command -ComputerName LabMachine2k16 -ScriptBlock{\n Get-Service WINRM\n }\n}"
},
{
"code": null,
"e": 2083,
"s": 1406,
"text": "At line:2 char:5\n+ Invoke-Command -ComputerName LabMachine2k16 -ScriptBlock{\n+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\nCannot call the 'Invoke-Command' command. Other commands from this module have been packaged as workflow activities, but this\ncommand was specifically excluded. This is likely because the command requires an interactive Windows PowerShell session, or has\nbehavior not suited for workflows. To run this command anyway, place it within an inline-script (InlineScript { Invoke-Command })\nwhere it will be invoked in isolation.\n + CategoryInfo : ParserError: (:) [], ParseException\n + FullyQualifiedErrorId : CommandActivityExcluded"
},
{
"code": null,
"e": 2244,
"s": 2083,
"text": "The above error indicates that the Invoke-Command can’t be directly used with the PowerShell and we need to use it inside the InlineScript block as shown below."
},
{
"code": null,
"e": 2414,
"s": 2244,
"text": "Workflow TestInvokeCommand{\n InlineScript{\n Invoke-Command -ComputerName LabMachine2k16 -ScriptBlock{\n Get-Service WINRM\n }\n }\n}\n\nTestInvokeCommand"
},
{
"code": null,
"e": 2537,
"s": 2414,
"text": "To use the outside variable in the scriptblock inside InlineScript block, we need to use $Using:VariableName. For example,"
},
{
"code": null,
"e": 2737,
"s": 2537,
"text": "Workflow TestInvokeCommand{\n$server = \"Labmachine2k16\"\n InlineScript{\n Invoke-Command -ComputerName $using:Server -ScriptBlock{\n Get-Service WINRM\n }\n }\n}\n\nTestInvokeCommand"
},
{
"code": null,
"e": 2767,
"s": 2737,
"text": "To store the output variable,"
},
{
"code": null,
"e": 3034,
"s": 2767,
"text": "Workflow TestInvokeCommand{\n $server = \"Labmachine2k16\"\n $Status = InlineScript{\n Invoke-Command -ComputerName $using:Server -ScriptBlock{\n return( Get-Service WINRM).Status\n }\n }\n Write-Output \"WinRM Status: $status\"\n}\n \nTestInvokeCommand"
}
] |
How to create a thread using lambda expressions in Java?
| The lambda expressions are introduced in Java 8. It is one of the most popular features of Java 8 and brings functional programming capabilities to Java. By using a lambda expression, we can directly write the implementation for a method in Java.
In the below program, we can create a thread by implementing the Runnable interface using lamda expression. While using the lambda expressions, we can skip the new Runnable() and run() method because the compiler knows that Thread object takes a Runnable object and that contains only one method run() that takes no argument.
public class LambdaThreadTest {
public static void main(String args[]) {
// Child thread
new Thread(() -> { // Lambda Expression
for(int i=1; i <= 5; i++) {
System.out.println("Child Thread: "+ i);
try {
Thread.sleep(500);
} catch(Exception e) {
e.printStackTrace();
}
}
}).start();
// Main Thead
for(int j=1; j < 5; j++) {
System.out.println("Main Thread: "+ j);
try {
Thread.sleep(500);
} catch(Exception e) {
e.printStackTrace();
}
}
}
}
Main Thread: 1
Child Thread: 1
Child Thread: 2
Main Thread: 2
Main Thread: 3
Child Thread: 3
Main Thread: 4
Child Thread: 4
Child Thread: 5 | [
{
"code": null,
"e": 1309,
"s": 1062,
"text": "The lambda expressions are introduced in Java 8. It is one of the most popular features of Java 8 and brings functional programming capabilities to Java. By using a lambda expression, we can directly write the implementation for a method in Java."
},
{
"code": null,
"e": 1635,
"s": 1309,
"text": "In the below program, we can create a thread by implementing the Runnable interface using lamda expression. While using the lambda expressions, we can skip the new Runnable() and run() method because the compiler knows that Thread object takes a Runnable object and that contains only one method run() that takes no argument."
},
{
"code": null,
"e": 2274,
"s": 1635,
"text": "public class LambdaThreadTest {\n public static void main(String args[]) {\n // Child thread\n new Thread(() -> { // Lambda Expression\n for(int i=1; i <= 5; i++) {\n System.out.println(\"Child Thread: \"+ i);\n try {\n Thread.sleep(500);\n } catch(Exception e) {\n e.printStackTrace();\n }\n }\n }).start();\n // Main Thead\n for(int j=1; j < 5; j++) {\n System.out.println(\"Main Thread: \"+ j);\n try {\n Thread.sleep(500);\n } catch(Exception e) {\n e.printStackTrace();\n }\n }\n }\n}"
},
{
"code": null,
"e": 2414,
"s": 2274,
"text": "Main Thread: 1\nChild Thread: 1\nChild Thread: 2\nMain Thread: 2\nMain Thread: 3\nChild Thread: 3\nMain Thread: 4\nChild Thread: 4\nChild Thread: 5"
}
] |
How to detect faces in an image using Java OpenCV library? | The CascadeClassifier class of is used to load the classifier file and detects the desired objects in the image.
The detectMultiScale() of this class detects multiple objects of various sizes. This method accepts −
An object of the class Mat holding the input image.
An object of the class Mat holding the input image.
An object of the class MatOfRect to store the detected faces.
An object of the class MatOfRect to store the detected faces.
To get the number of faces in the image −
Load the lbpcascade_frontalface.xml file using the CascadeClassifier class.
Load the lbpcascade_frontalface.xml file using the CascadeClassifier class.
Invoke the detectMultiScale() method.
Invoke the detectMultiScale() method.
Convert the MatOfRect object to an array.
Convert the MatOfRect object to an array.
The length of the array is the number of faces in the image.
The length of the array is the number of faces in the image.
import org.opencv.core.Core;
import org.opencv.core.Mat;
import org.opencv.core.MatOfRect;
import org.opencv.core.Point;
import org.opencv.core.Rect;
import org.opencv.core.Scalar;
import org.opencv.imgcodecs.Imgcodecs;
import org.opencv.imgproc.Imgproc;
import org.opencv.objdetect.CascadeClassifier;
public class FaceDetection {
public static void main (String[] args) {
//Loading the OpenCV core library
System.loadLibrary( Core.NATIVE_LIBRARY_NAME );
//Reading the Image from the file
String file ="D:\\Images\\faces.jpg";
Mat src = Imgcodecs.imread(file);
//Instantiating the CascadeClassifier
String xmlFile = "lbpcascade_frontalface.xml";
CascadeClassifier classifier = new CascadeClassifier(xmlFile);
//Detecting the face in the snap
MatOfRect faceDetections = new MatOfRect();
classifier.detectMultiScale(src, faceDetections);
System.out.println(String.format("Detected %s faces",
faceDetections.toArray().length));
//Drawing boxes
for (Rect rect : faceDetections.toArray()) {
Imgproc.rectangle(
src,
new Point(rect.x, rect.y),
new Point(rect.x + rect.width, rect.y + rect.height),
new Scalar(0, 0, 255),
3
);
}
//Writing the image
Imgcodecs.imwrite("D:\\Images\\face_Detection.jpg", src);
System.out.println("Image Processed");
}
}
No of faces detected: 3 | [
{
"code": null,
"e": 1175,
"s": 1062,
"text": "The CascadeClassifier class of is used to load the classifier file and detects the desired objects in the image."
},
{
"code": null,
"e": 1277,
"s": 1175,
"text": "The detectMultiScale() of this class detects multiple objects of various sizes. This method accepts −"
},
{
"code": null,
"e": 1329,
"s": 1277,
"text": "An object of the class Mat holding the input image."
},
{
"code": null,
"e": 1381,
"s": 1329,
"text": "An object of the class Mat holding the input image."
},
{
"code": null,
"e": 1443,
"s": 1381,
"text": "An object of the class MatOfRect to store the detected faces."
},
{
"code": null,
"e": 1505,
"s": 1443,
"text": "An object of the class MatOfRect to store the detected faces."
},
{
"code": null,
"e": 1547,
"s": 1505,
"text": "To get the number of faces in the image −"
},
{
"code": null,
"e": 1623,
"s": 1547,
"text": "Load the lbpcascade_frontalface.xml file using the CascadeClassifier class."
},
{
"code": null,
"e": 1699,
"s": 1623,
"text": "Load the lbpcascade_frontalface.xml file using the CascadeClassifier class."
},
{
"code": null,
"e": 1737,
"s": 1699,
"text": "Invoke the detectMultiScale() method."
},
{
"code": null,
"e": 1775,
"s": 1737,
"text": "Invoke the detectMultiScale() method."
},
{
"code": null,
"e": 1817,
"s": 1775,
"text": "Convert the MatOfRect object to an array."
},
{
"code": null,
"e": 1859,
"s": 1817,
"text": "Convert the MatOfRect object to an array."
},
{
"code": null,
"e": 1920,
"s": 1859,
"text": "The length of the array is the number of faces in the image."
},
{
"code": null,
"e": 1981,
"s": 1920,
"text": "The length of the array is the number of faces in the image."
},
{
"code": null,
"e": 3421,
"s": 1981,
"text": "import org.opencv.core.Core;\nimport org.opencv.core.Mat;\nimport org.opencv.core.MatOfRect;\nimport org.opencv.core.Point;\nimport org.opencv.core.Rect;\nimport org.opencv.core.Scalar;\nimport org.opencv.imgcodecs.Imgcodecs;\nimport org.opencv.imgproc.Imgproc;\nimport org.opencv.objdetect.CascadeClassifier;\npublic class FaceDetection {\n public static void main (String[] args) {\n //Loading the OpenCV core library\n System.loadLibrary( Core.NATIVE_LIBRARY_NAME );\n //Reading the Image from the file\n String file =\"D:\\\\Images\\\\faces.jpg\";\n Mat src = Imgcodecs.imread(file);\n //Instantiating the CascadeClassifier\n String xmlFile = \"lbpcascade_frontalface.xml\";\n CascadeClassifier classifier = new CascadeClassifier(xmlFile);\n //Detecting the face in the snap\n MatOfRect faceDetections = new MatOfRect();\n classifier.detectMultiScale(src, faceDetections);\n System.out.println(String.format(\"Detected %s faces\",\n faceDetections.toArray().length));\n //Drawing boxes\n for (Rect rect : faceDetections.toArray()) {\n Imgproc.rectangle(\n src,\n new Point(rect.x, rect.y),\n new Point(rect.x + rect.width, rect.y + rect.height),\n new Scalar(0, 0, 255),\n 3\n );\n }\n //Writing the image\n Imgcodecs.imwrite(\"D:\\\\Images\\\\face_Detection.jpg\", src);\n System.out.println(\"Image Processed\");\n }\n}"
},
{
"code": null,
"e": 3445,
"s": 3421,
"text": "No of faces detected: 3"
}
] |
Count of subsequences of length 4 in form (x, x, x+1, x+1) | Set 2 - GeeksforGeeks | 27 Apr, 2021
Given a large number in form of string str of size N, the task is to count the subsequence of length 4 whose digit are in the form of (x, x, x+1, x+1).Example:
Input: str = “1515732322” Output: 3 Explanation: For the given input string str = “1515732322”, there are 3 subsequence {1122}, {1122}, and {1122} which are in the given form of (x, x, x+1, x+1).
Input: str = “224353” Output: 1 Explanation: For the given input string str = “224353”, there is only 1 subsequence possible {2233} in the given form of (x, x, x+1, x+1).
Prefix Sum Approach: Please refer to the Set 1, for the Prefix sum approach.
Dynamic Programming Approach: This problem can be solved using Dynamic Programming. We will be using 2 arrays as count1[][j] and count2[][10] such that count1[i][10] will store the count of consecutive equal element of digit j at current index i traversing string from left and count2[i][j] will store the count of consecutive equal element of digit j at current index i traversing string from right. Below are the steps:
Initialize two count array count1[][10] for filling table from left to right and count2[][10] for filling table from right to left of input string.
Traverse input string and fill the both count1 and count2 array.
Recurrence Relation for count1[][] is given by:
count1[i][j] += count1[i – 1][j] where count1[i][j] is the count of two adjacent at index i for digit j
Recurrence Relation for count2[][] is given by:
count2[i][j] += count1[i + 1][j] where count2[i][j] is the count of two adjacent at index i for digit j
Initialize a variable ans to 0 that stores the resultant count of stable numbers.
Traverse the input string and get the count of numbers from count1[][] and count2[][] array such that the difference between number from count1[][] and count2[][] array is 1 and store it in variable c1 and c2.
Finally update result(say ans) with (c1 * ((c2 * (c2 – 1) / 2))).
Print the answer ans calculated above.
Below is the implementation of the above approach:
C++
Java
Python3
C#
Javascript
// C++ program for the above approach#include <bits/stdc++.h>using namespace std; // Function to count the numbersint countStableNum(string str, int N){ // Array that stores the // digits from left to right int count1[N][10]; // Array that stores the // digits from right to left int count2[N][10]; // Initially both array store zero for (int i = 0; i < N; i++) for (int j = 0; j < 10; j++) count1[i][j] = count2[i][j] = 0; // Fill the table for count1 array for (int i = 0; i < N; i++) { if (i != 0) { for (int j = 0; j < 10; j++) { count1[i][j] += count1[i - 1][j]; } } // Update the count of current character count1[i][str[i] - '0']++; } // Fill the table for count2 array for (int i = N - 1; i >= 0; i--) { if (i != N - 1) { for (int j = 0; j < 10; j++) { count2[i][j] += count2[i + 1][j]; } } // Update the count of cuuent character count2[i][str[i] - '0']++; } // Variable that stores the // count of the numbers int ans = 0; // Traverse Input string and get the // count of digits from count1 and // count2 array such that difference // b/w digit is 1 & store it int c1 &c2. // And store it in variable c1 and c2 for (int i = 1; i < N - 1; i++) { if (str[i] == '9') continue; int c1 = count1[i - 1][str[i] - '0']; int c2 = count2[i + 1][str[i] - '0' + 1]; if (c2 == 0) continue; // Update the ans ans = (ans + (c1 * ((c2 * (c2 - 1) / 2)))); } // Return the final count return ans;} // Driver Codeint main(){ // Given String string str = "224353"; int N = str.length(); // Function Call cout << countStableNum(str, N); return 0;}
// Java program for the above approachimport java.io.*; class GFG{ // Function to count the numbersstatic int countStableNum(String str, int N){ // Array that stores the // digits from left to right int count1[][] = new int[N][10]; // Array that stores the // digits from right to left int count2[][] = new int[N][10]; // Initially both array store zero for(int i = 0; i < N; i++) for(int j = 0; j < 10; j++) count1[i][j] = count2[i][j] = 0; // Fill the table for count1 array for(int i = 0; i < N; i++) { if (i != 0) { for(int j = 0; j < 10; j++) { count1[i][j] += count1[i - 1][j]; } } // Update the count of current character count1[i][str.charAt(i) - '0']++; } // Fill the table for count2 array for(int i = N - 1; i >= 0; i--) { if (i != N - 1) { for(int j = 0; j < 10; j++) { count2[i][j] += count2[i + 1][j]; } } // Update the count of cuuent character count2[i][str.charAt(i) - '0']++; } // Variable that stores the // count of the numbers int ans = 0; // Traverse Input string and get the // count of digits from count1 and // count2 array such that difference // b/w digit is 1 & store it int c1 &c2. // And store it in variable c1 and c2 for(int i = 1; i < N - 1; i++) { if (str.charAt(i) == '9') continue; int c1 = count1[i - 1][str.charAt(i) - '0']; int c2 = count2[i + 1][str.charAt(i) - '0' + 1]; if (c2 == 0) continue; // Update the ans ans = (ans + (c1 * ((c2 * (c2 - 1) / 2)))); } // Return the final count return ans;} // Driver codepublic static void main(String[] args){ // Given String String str = "224353"; int N = str.length(); // Function call System.out.println(countStableNum(str, N));}} // This code is contributed by Pratima Pandey
# Python3 program for the above approach # Function to count the numbersdef countStableNum(Str, N): # Array that stores the # digits from left to right count1 = [[0 for j in range(10)] for i in range(N)] # Array that stores the # digits from right to left count2 = [[0 for j in range(10)] for i in range(N)] # Initially both array store zero for i in range(N): for j in range(10): count1[i][j], count2[i][j] = 0, 0 # Fill the table for count1 array for i in range(N): if (i != 0): for j in range(10): count1[i][j] = (count1[i][j] + count1[i - 1][j]) # Update the count of current character count1[i][ord(Str[i]) - ord('0')] += 1 # Fill the table for count2 array for i in range(N - 1, -1, -1): if (i != N - 1): for j in range(10): count2[i][j] += count2[i + 1][j] # Update the count of cuuent character count2[i][ord(Str[i]) - ord('0')] = count2[i][ord(Str[i]) - ord('0')] + 1 # Variable that stores the # count of the numbers ans = 0 # Traverse Input string and get the # count of digits from count1 and # count2 array such that difference # b/w digit is 1 & store it int c1 &c2. # And store it in variable c1 and c2 for i in range(1, N - 1): if (Str[i] == '9'): continue c1 = count1[i - 1][ord(Str[i]) - ord('0')] c2 = count2[i + 1][ord(Str[i]) - ord('0') + 1] if (c2 == 0): continue # Update the ans ans = (ans + (c1 * ((c2 * (c2 - 1) // 2)))) # Return the final count return ans # Driver code # Given StringStr = "224353"N = len(Str) # Function callprint(countStableNum(Str, N)) # This code is contributed by divyeshrabadiya07
// C# program for the above approachusing System; class GFG{ // Function to count the numbersstatic int countStableNum(String str, int N){ // Array that stores the // digits from left to right int [,]count1 = new int[N, 10]; // Array that stores the // digits from right to left int [,]count2 = new int[N, 10]; // Initially both array store zero for(int i = 0; i < N; i++) for(int j = 0; j < 10; j++) count1[i, j] = count2[i, j] = 0; // Fill the table for count1 array for(int i = 0; i < N; i++) { if (i != 0) { for(int j = 0; j < 10; j++) { count1[i, j] += count1[i - 1, j]; } } // Update the count of current character count1[i, str[i] - '0']++; } // Fill the table for count2 array for(int i = N - 1; i >= 0; i--) { if (i != N - 1) { for(int j = 0; j < 10; j++) { count2[i, j] += count2[i + 1, j]; } } // Update the count of cuuent character count2[i, str[i] - '0']++; } // Variable that stores the // count of the numbers int ans = 0; // Traverse Input string and get the // count of digits from count1 and // count2 array such that difference // b/w digit is 1 & store it int c1 &c2. // And store it in variable c1 and c2 for(int i = 1; i < N - 1; i++) { if (str[i] == '9') continue; int c1 = count1[i - 1, str[i] - '0']; int c2 = count2[i + 1, str[i] - '0' + 1]; if (c2 == 0) continue; // Update the ans ans = (ans + (c1 * ((c2 * (c2 - 1) / 2)))); } // Return the readonly count return ans;} // Driver codepublic static void Main(String[] args){ // Given String String str = "224353"; int N = str.Length; // Function call Console.WriteLine(countStableNum(str, N));}} // This code is contributed by Amit Katiyar
<script> // Javascript program for the above approach // Function to count the numbersfunction countStableNum(str, N){ // Array that stores the // digits from left to right var count1 = Array.from(Array(N), ()=>Array(10)); // Array that stores the // digits from right to left var count2 = Array.from(Array(N), ()=>Array(10)); // Initially both array store zero for (var i = 0; i < N; i++) for (var j = 0; j < 10; j++) count1[i][j] = count2[i][j] = 0; // Fill the table for count1 array for (var i = 0; i < N; i++) { if (i != 0) { for (var j = 0; j < 10; j++) { count1[i][j] += count1[i - 1][j]; } } // Update the count of current character count1[i][str[i] - '0']++; } // Fill the table for count2 array for (var i = N - 1; i >= 0; i--) { if (i != N - 1) { for (var j = 0; j < 10; j++) { count2[i][j] += count2[i + 1][j]; } } // Update the count of cuuent character count2[i][str[i] - '0']++; } // Variable that stores the // count of the numbers var ans = 0; // Traverse Input string and get the // count of digits from count1 and // count2 array such that difference // b/w digit is 1 & store it var c1 &c2. // And store it in variable c1 and c2 for (var i = 1; i < N - 1; i++) { if (str[i] == '9') continue; var c1 = count1[i - 1][str[i] - '0']; var c2 = count2[i + 1][str[i] - '0' + 1]; if (c2 == 0) continue; // Update the ans ans = (ans + (c1 * ((c2 * (c2 - 1) / 2)))); } // Return the final count return ans;} // Driver Code // Given Stringvar str = "224353";var N = str.length; // Function Calldocument.write( countStableNum(str, N)); </script>
1
Time Complexity: O(N) Auxiliary Space Complexity: O(N)
dewantipandeydp
amit143katiyar
divyeshrabadiya07
khushboogoyal499
rrrtnx
number-digits
number-theory
subsequence
Algorithms
Competitive Programming
Dynamic Programming
Mathematical
Strings
number-theory
Strings
Dynamic Programming
Mathematical
Algorithms
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
DSA Sheet by Love Babbar
Quadratic Probing in Hashing
K means Clustering - Introduction
SCAN (Elevator) Disk Scheduling Algorithms
Difference between Informed and Uninformed Search in AI
Practice for cracking any coding interview
Arrow operator -> in C/C++ with Examples
Competitive Programming - A Complete Guide
Modulo 10^9+7 (1000000007)
Prefix Sum Array - Implementation and Applications in Competitive Programming | [
{
"code": null,
"e": 24612,
"s": 24584,
"text": "\n27 Apr, 2021"
},
{
"code": null,
"e": 24772,
"s": 24612,
"text": "Given a large number in form of string str of size N, the task is to count the subsequence of length 4 whose digit are in the form of (x, x, x+1, x+1).Example:"
},
{
"code": null,
"e": 24968,
"s": 24772,
"text": "Input: str = “1515732322” Output: 3 Explanation: For the given input string str = “1515732322”, there are 3 subsequence {1122}, {1122}, and {1122} which are in the given form of (x, x, x+1, x+1)."
},
{
"code": null,
"e": 25139,
"s": 24968,
"text": "Input: str = “224353” Output: 1 Explanation: For the given input string str = “224353”, there is only 1 subsequence possible {2233} in the given form of (x, x, x+1, x+1)."
},
{
"code": null,
"e": 25216,
"s": 25139,
"text": "Prefix Sum Approach: Please refer to the Set 1, for the Prefix sum approach."
},
{
"code": null,
"e": 25638,
"s": 25216,
"text": "Dynamic Programming Approach: This problem can be solved using Dynamic Programming. We will be using 2 arrays as count1[][j] and count2[][10] such that count1[i][10] will store the count of consecutive equal element of digit j at current index i traversing string from left and count2[i][j] will store the count of consecutive equal element of digit j at current index i traversing string from right. Below are the steps:"
},
{
"code": null,
"e": 25786,
"s": 25638,
"text": "Initialize two count array count1[][10] for filling table from left to right and count2[][10] for filling table from right to left of input string."
},
{
"code": null,
"e": 25851,
"s": 25786,
"text": "Traverse input string and fill the both count1 and count2 array."
},
{
"code": null,
"e": 25899,
"s": 25851,
"text": "Recurrence Relation for count1[][] is given by:"
},
{
"code": null,
"e": 26003,
"s": 25899,
"text": "count1[i][j] += count1[i – 1][j] where count1[i][j] is the count of two adjacent at index i for digit j"
},
{
"code": null,
"e": 26051,
"s": 26003,
"text": "Recurrence Relation for count2[][] is given by:"
},
{
"code": null,
"e": 26156,
"s": 26051,
"text": " count2[i][j] += count1[i + 1][j] where count2[i][j] is the count of two adjacent at index i for digit j"
},
{
"code": null,
"e": 26238,
"s": 26156,
"text": "Initialize a variable ans to 0 that stores the resultant count of stable numbers."
},
{
"code": null,
"e": 26448,
"s": 26238,
"text": "Traverse the input string and get the count of numbers from count1[][] and count2[][] array such that the difference between number from count1[][] and count2[][] array is 1 and store it in variable c1 and c2."
},
{
"code": null,
"e": 26514,
"s": 26448,
"text": "Finally update result(say ans) with (c1 * ((c2 * (c2 – 1) / 2)))."
},
{
"code": null,
"e": 26553,
"s": 26514,
"text": "Print the answer ans calculated above."
},
{
"code": null,
"e": 26604,
"s": 26553,
"text": "Below is the implementation of the above approach:"
},
{
"code": null,
"e": 26608,
"s": 26604,
"text": "C++"
},
{
"code": null,
"e": 26613,
"s": 26608,
"text": "Java"
},
{
"code": null,
"e": 26621,
"s": 26613,
"text": "Python3"
},
{
"code": null,
"e": 26624,
"s": 26621,
"text": "C#"
},
{
"code": null,
"e": 26635,
"s": 26624,
"text": "Javascript"
},
{
"code": "// C++ program for the above approach#include <bits/stdc++.h>using namespace std; // Function to count the numbersint countStableNum(string str, int N){ // Array that stores the // digits from left to right int count1[N][10]; // Array that stores the // digits from right to left int count2[N][10]; // Initially both array store zero for (int i = 0; i < N; i++) for (int j = 0; j < 10; j++) count1[i][j] = count2[i][j] = 0; // Fill the table for count1 array for (int i = 0; i < N; i++) { if (i != 0) { for (int j = 0; j < 10; j++) { count1[i][j] += count1[i - 1][j]; } } // Update the count of current character count1[i][str[i] - '0']++; } // Fill the table for count2 array for (int i = N - 1; i >= 0; i--) { if (i != N - 1) { for (int j = 0; j < 10; j++) { count2[i][j] += count2[i + 1][j]; } } // Update the count of cuuent character count2[i][str[i] - '0']++; } // Variable that stores the // count of the numbers int ans = 0; // Traverse Input string and get the // count of digits from count1 and // count2 array such that difference // b/w digit is 1 & store it int c1 &c2. // And store it in variable c1 and c2 for (int i = 1; i < N - 1; i++) { if (str[i] == '9') continue; int c1 = count1[i - 1][str[i] - '0']; int c2 = count2[i + 1][str[i] - '0' + 1]; if (c2 == 0) continue; // Update the ans ans = (ans + (c1 * ((c2 * (c2 - 1) / 2)))); } // Return the final count return ans;} // Driver Codeint main(){ // Given String string str = \"224353\"; int N = str.length(); // Function Call cout << countStableNum(str, N); return 0;}",
"e": 28509,
"s": 26635,
"text": null
},
{
"code": "// Java program for the above approachimport java.io.*; class GFG{ // Function to count the numbersstatic int countStableNum(String str, int N){ // Array that stores the // digits from left to right int count1[][] = new int[N][10]; // Array that stores the // digits from right to left int count2[][] = new int[N][10]; // Initially both array store zero for(int i = 0; i < N; i++) for(int j = 0; j < 10; j++) count1[i][j] = count2[i][j] = 0; // Fill the table for count1 array for(int i = 0; i < N; i++) { if (i != 0) { for(int j = 0; j < 10; j++) { count1[i][j] += count1[i - 1][j]; } } // Update the count of current character count1[i][str.charAt(i) - '0']++; } // Fill the table for count2 array for(int i = N - 1; i >= 0; i--) { if (i != N - 1) { for(int j = 0; j < 10; j++) { count2[i][j] += count2[i + 1][j]; } } // Update the count of cuuent character count2[i][str.charAt(i) - '0']++; } // Variable that stores the // count of the numbers int ans = 0; // Traverse Input string and get the // count of digits from count1 and // count2 array such that difference // b/w digit is 1 & store it int c1 &c2. // And store it in variable c1 and c2 for(int i = 1; i < N - 1; i++) { if (str.charAt(i) == '9') continue; int c1 = count1[i - 1][str.charAt(i) - '0']; int c2 = count2[i + 1][str.charAt(i) - '0' + 1]; if (c2 == 0) continue; // Update the ans ans = (ans + (c1 * ((c2 * (c2 - 1) / 2)))); } // Return the final count return ans;} // Driver codepublic static void main(String[] args){ // Given String String str = \"224353\"; int N = str.length(); // Function call System.out.println(countStableNum(str, N));}} // This code is contributed by Pratima Pandey",
"e": 30600,
"s": 28509,
"text": null
},
{
"code": "# Python3 program for the above approach # Function to count the numbersdef countStableNum(Str, N): # Array that stores the # digits from left to right count1 = [[0 for j in range(10)] for i in range(N)] # Array that stores the # digits from right to left count2 = [[0 for j in range(10)] for i in range(N)] # Initially both array store zero for i in range(N): for j in range(10): count1[i][j], count2[i][j] = 0, 0 # Fill the table for count1 array for i in range(N): if (i != 0): for j in range(10): count1[i][j] = (count1[i][j] + count1[i - 1][j]) # Update the count of current character count1[i][ord(Str[i]) - ord('0')] += 1 # Fill the table for count2 array for i in range(N - 1, -1, -1): if (i != N - 1): for j in range(10): count2[i][j] += count2[i + 1][j] # Update the count of cuuent character count2[i][ord(Str[i]) - ord('0')] = count2[i][ord(Str[i]) - ord('0')] + 1 # Variable that stores the # count of the numbers ans = 0 # Traverse Input string and get the # count of digits from count1 and # count2 array such that difference # b/w digit is 1 & store it int c1 &c2. # And store it in variable c1 and c2 for i in range(1, N - 1): if (Str[i] == '9'): continue c1 = count1[i - 1][ord(Str[i]) - ord('0')] c2 = count2[i + 1][ord(Str[i]) - ord('0') + 1] if (c2 == 0): continue # Update the ans ans = (ans + (c1 * ((c2 * (c2 - 1) // 2)))) # Return the final count return ans # Driver code # Given StringStr = \"224353\"N = len(Str) # Function callprint(countStableNum(Str, N)) # This code is contributed by divyeshrabadiya07",
"e": 32555,
"s": 30600,
"text": null
},
{
"code": "// C# program for the above approachusing System; class GFG{ // Function to count the numbersstatic int countStableNum(String str, int N){ // Array that stores the // digits from left to right int [,]count1 = new int[N, 10]; // Array that stores the // digits from right to left int [,]count2 = new int[N, 10]; // Initially both array store zero for(int i = 0; i < N; i++) for(int j = 0; j < 10; j++) count1[i, j] = count2[i, j] = 0; // Fill the table for count1 array for(int i = 0; i < N; i++) { if (i != 0) { for(int j = 0; j < 10; j++) { count1[i, j] += count1[i - 1, j]; } } // Update the count of current character count1[i, str[i] - '0']++; } // Fill the table for count2 array for(int i = N - 1; i >= 0; i--) { if (i != N - 1) { for(int j = 0; j < 10; j++) { count2[i, j] += count2[i + 1, j]; } } // Update the count of cuuent character count2[i, str[i] - '0']++; } // Variable that stores the // count of the numbers int ans = 0; // Traverse Input string and get the // count of digits from count1 and // count2 array such that difference // b/w digit is 1 & store it int c1 &c2. // And store it in variable c1 and c2 for(int i = 1; i < N - 1; i++) { if (str[i] == '9') continue; int c1 = count1[i - 1, str[i] - '0']; int c2 = count2[i + 1, str[i] - '0' + 1]; if (c2 == 0) continue; // Update the ans ans = (ans + (c1 * ((c2 * (c2 - 1) / 2)))); } // Return the readonly count return ans;} // Driver codepublic static void Main(String[] args){ // Given String String str = \"224353\"; int N = str.Length; // Function call Console.WriteLine(countStableNum(str, N));}} // This code is contributed by Amit Katiyar",
"e": 34597,
"s": 32555,
"text": null
},
{
"code": "<script> // Javascript program for the above approach // Function to count the numbersfunction countStableNum(str, N){ // Array that stores the // digits from left to right var count1 = Array.from(Array(N), ()=>Array(10)); // Array that stores the // digits from right to left var count2 = Array.from(Array(N), ()=>Array(10)); // Initially both array store zero for (var i = 0; i < N; i++) for (var j = 0; j < 10; j++) count1[i][j] = count2[i][j] = 0; // Fill the table for count1 array for (var i = 0; i < N; i++) { if (i != 0) { for (var j = 0; j < 10; j++) { count1[i][j] += count1[i - 1][j]; } } // Update the count of current character count1[i][str[i] - '0']++; } // Fill the table for count2 array for (var i = N - 1; i >= 0; i--) { if (i != N - 1) { for (var j = 0; j < 10; j++) { count2[i][j] += count2[i + 1][j]; } } // Update the count of cuuent character count2[i][str[i] - '0']++; } // Variable that stores the // count of the numbers var ans = 0; // Traverse Input string and get the // count of digits from count1 and // count2 array such that difference // b/w digit is 1 & store it var c1 &c2. // And store it in variable c1 and c2 for (var i = 1; i < N - 1; i++) { if (str[i] == '9') continue; var c1 = count1[i - 1][str[i] - '0']; var c2 = count2[i + 1][str[i] - '0' + 1]; if (c2 == 0) continue; // Update the ans ans = (ans + (c1 * ((c2 * (c2 - 1) / 2)))); } // Return the final count return ans;} // Driver Code // Given Stringvar str = \"224353\";var N = str.length; // Function Calldocument.write( countStableNum(str, N)); </script>",
"e": 36468,
"s": 34597,
"text": null
},
{
"code": null,
"e": 36470,
"s": 36468,
"text": "1"
},
{
"code": null,
"e": 36526,
"s": 36470,
"text": "Time Complexity: O(N) Auxiliary Space Complexity: O(N) "
},
{
"code": null,
"e": 36542,
"s": 36526,
"text": "dewantipandeydp"
},
{
"code": null,
"e": 36557,
"s": 36542,
"text": "amit143katiyar"
},
{
"code": null,
"e": 36575,
"s": 36557,
"text": "divyeshrabadiya07"
},
{
"code": null,
"e": 36592,
"s": 36575,
"text": "khushboogoyal499"
},
{
"code": null,
"e": 36599,
"s": 36592,
"text": "rrrtnx"
},
{
"code": null,
"e": 36613,
"s": 36599,
"text": "number-digits"
},
{
"code": null,
"e": 36627,
"s": 36613,
"text": "number-theory"
},
{
"code": null,
"e": 36639,
"s": 36627,
"text": "subsequence"
},
{
"code": null,
"e": 36650,
"s": 36639,
"text": "Algorithms"
},
{
"code": null,
"e": 36674,
"s": 36650,
"text": "Competitive Programming"
},
{
"code": null,
"e": 36694,
"s": 36674,
"text": "Dynamic Programming"
},
{
"code": null,
"e": 36707,
"s": 36694,
"text": "Mathematical"
},
{
"code": null,
"e": 36715,
"s": 36707,
"text": "Strings"
},
{
"code": null,
"e": 36729,
"s": 36715,
"text": "number-theory"
},
{
"code": null,
"e": 36737,
"s": 36729,
"text": "Strings"
},
{
"code": null,
"e": 36757,
"s": 36737,
"text": "Dynamic Programming"
},
{
"code": null,
"e": 36770,
"s": 36757,
"text": "Mathematical"
},
{
"code": null,
"e": 36781,
"s": 36770,
"text": "Algorithms"
},
{
"code": null,
"e": 36879,
"s": 36781,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 36888,
"s": 36879,
"text": "Comments"
},
{
"code": null,
"e": 36901,
"s": 36888,
"text": "Old Comments"
},
{
"code": null,
"e": 36926,
"s": 36901,
"text": "DSA Sheet by Love Babbar"
},
{
"code": null,
"e": 36955,
"s": 36926,
"text": "Quadratic Probing in Hashing"
},
{
"code": null,
"e": 36989,
"s": 36955,
"text": "K means Clustering - Introduction"
},
{
"code": null,
"e": 37032,
"s": 36989,
"text": "SCAN (Elevator) Disk Scheduling Algorithms"
},
{
"code": null,
"e": 37088,
"s": 37032,
"text": "Difference between Informed and Uninformed Search in AI"
},
{
"code": null,
"e": 37131,
"s": 37088,
"text": "Practice for cracking any coding interview"
},
{
"code": null,
"e": 37172,
"s": 37131,
"text": "Arrow operator -> in C/C++ with Examples"
},
{
"code": null,
"e": 37215,
"s": 37172,
"text": "Competitive Programming - A Complete Guide"
},
{
"code": null,
"e": 37242,
"s": 37215,
"text": "Modulo 10^9+7 (1000000007)"
}
] |
Aptitude | GATE CS 1998 | Question 9 - GeeksforGeeks | 21 May, 2020
If the regular set ‘A’ is represented by A= (01+1)* and the regular set ‘B’ is represented by B= ((01)* 1*)*, which of the following is true ?(A) A ⊂ B(B) B ⊂ A(C) A and B are incomparable(D) A = BAnswer: (D)Explanation: Some of the regular expression always equivalent to (0+1)* such that
(0+1)*
= (0*+1*)*
= (01*)*
= (0*+1)*
= (0+1*)*
= 0*(10*)*
= 1*(01*)*
Since,
(01+1)* = ((01)* 1* )*
Therefore A = B.Quiz of this Question
vivekkumarmth0077
Aptitude
Aptitude-GATE CS 1998
GATE CS 1998
GATE
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
GATE | GATE-IT-2004 | Question 71
GATE | GATE CS 2011 | Question 7
GATE | GATE-CS-2015 (Set 3) | Question 65
GATE | GATE-CS-2014-(Set-3) | Question 38
GATE | GATE CS 2018 | Question 37
GATE | GATE-CS-2016 (Set 1) | Question 65
GATE | GATE-IT-2004 | Question 83
GATE | GATE-CS-2016 (Set 1) | Question 63
GATE | GATE-CS-2014-(Set-2) | Question 65
GATE | GATE-CS-2007 | Question 64 | [
{
"code": null,
"e": 24466,
"s": 24438,
"text": "\n21 May, 2020"
},
{
"code": null,
"e": 24756,
"s": 24466,
"text": "If the regular set ‘A’ is represented by A= (01+1)* and the regular set ‘B’ is represented by B= ((01)* 1*)*, which of the following is true ?(A) A ⊂ B(B) B ⊂ A(C) A and B are incomparable(D) A = BAnswer: (D)Explanation: Some of the regular expression always equivalent to (0+1)* such that"
},
{
"code": null,
"e": 24832,
"s": 24756,
"text": "(0+1)* \n= (0*+1*)* \n= (01*)* \n= (0*+1)* \n= (0+1*)* \n= 0*(10*)* \n= 1*(01*)* "
},
{
"code": null,
"e": 24839,
"s": 24832,
"text": "Since,"
},
{
"code": null,
"e": 24864,
"s": 24839,
"text": "(01+1)* = ((01)* 1* )* "
},
{
"code": null,
"e": 24902,
"s": 24864,
"text": "Therefore A = B.Quiz of this Question"
},
{
"code": null,
"e": 24920,
"s": 24902,
"text": "vivekkumarmth0077"
},
{
"code": null,
"e": 24929,
"s": 24920,
"text": "Aptitude"
},
{
"code": null,
"e": 24951,
"s": 24929,
"text": "Aptitude-GATE CS 1998"
},
{
"code": null,
"e": 24964,
"s": 24951,
"text": "GATE CS 1998"
},
{
"code": null,
"e": 24969,
"s": 24964,
"text": "GATE"
},
{
"code": null,
"e": 25067,
"s": 24969,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 25076,
"s": 25067,
"text": "Comments"
},
{
"code": null,
"e": 25089,
"s": 25076,
"text": "Old Comments"
},
{
"code": null,
"e": 25123,
"s": 25089,
"text": "GATE | GATE-IT-2004 | Question 71"
},
{
"code": null,
"e": 25156,
"s": 25123,
"text": "GATE | GATE CS 2011 | Question 7"
},
{
"code": null,
"e": 25198,
"s": 25156,
"text": "GATE | GATE-CS-2015 (Set 3) | Question 65"
},
{
"code": null,
"e": 25240,
"s": 25198,
"text": "GATE | GATE-CS-2014-(Set-3) | Question 38"
},
{
"code": null,
"e": 25274,
"s": 25240,
"text": "GATE | GATE CS 2018 | Question 37"
},
{
"code": null,
"e": 25316,
"s": 25274,
"text": "GATE | GATE-CS-2016 (Set 1) | Question 65"
},
{
"code": null,
"e": 25350,
"s": 25316,
"text": "GATE | GATE-IT-2004 | Question 83"
},
{
"code": null,
"e": 25392,
"s": 25350,
"text": "GATE | GATE-CS-2016 (Set 1) | Question 63"
},
{
"code": null,
"e": 25434,
"s": 25392,
"text": "GATE | GATE-CS-2014-(Set-2) | Question 65"
}
] |
Find an element in an array such that elements form a strictly decreasing and increasing sequence - GeeksforGeeks | 19 Jan, 2022
Given an array of positive integers, the task is to find a point/element up to which elements form a strictly decreasing sequence first followed by a sequence of strictly increasing integers.
Both of the sequences must at least be of length 2 (considering the common element).
The last value of the decreasing sequence is the first value of the increasing sequence.
Note: Print “No such element exist”, if not found.Examples:
Input: arr[] = {3, 2, 1, 2}
Output: 1
{3, 2, 1} is strictly decreasing
then {1, 2} is strictly increasing.
Input: arr[] = {3, 2, 1}
Output: No such element exist
Approach:
First start traversing the array and keep traversing till the elements are in strictly decreasing order.If next elements is greater than the previous element store that element in point variable.Start traversing the elements from that point and keep traversing till the elements are in the strictly increasing order.After step 3, if all the elements get traversed then print that point.Else print “No such element exist.”
First start traversing the array and keep traversing till the elements are in strictly decreasing order.
If next elements is greater than the previous element store that element in point variable.
Start traversing the elements from that point and keep traversing till the elements are in the strictly increasing order.
After step 3, if all the elements get traversed then print that point.
Else print “No such element exist.”
Note: If any of the two elements are equal then also print “No such element exist” as it should be strictly decreasing and increasing. Below is the implementation of above approach:
C++
Java
Python
C#
PHP
Javascript
// C++ implementation of above approach#include <bits/stdc++.h>using namespace std; // Function to check such sequenceint findElement(int a[], int n){ // set increasing/decreasing sequence counter to 1 int inc = 1, dec = 1, point; // for loop counter from 1 to last index of list for (int i = 1; i < n; i++) { // check if current int is // smaller than previous int if (a[i] < a[i - 1]) { // if inc is 1, i.e., increasing // seq. never started if (inc == 1) // increase dec by 1 dec++; else return -1; } // check if current int is greater than previous int else if (a[i] > a[i - 1]) { // if inc is 1, i.e., increasing seq. // starting for first time, if (inc == 1) // store a[i-1] in point point = a[i - 1]; // only if decreasing seq. minimum // count has been met, if (dec >= 2) // increase inc by 1 inc++; else // return -1 as decreasing seq. // min. count must be 2 return -1; } // check if current int is equal // to previous int, if so, else if (a[i] == a[i - 1]) return -1; } // check if inc >= 2 and dec >= 2 // return point if (inc >= 2 && dec >= 2) return point; // otherwise return -1 else return -1;} // Driver codeint main(){ int arr[] = { 3, 2, 1, 2 }; int n = sizeof(arr) / sizeof(arr[0]); int ele = findElement(arr, n); if (ele == -1) cout << "No such element exist"; else cout << ele; return 0;}
// Java implementation of above approach public class GFG { // Function to check such sequence static int findElement(int a[], int n) { // set increasing/decreasing sequence counter to 1 int inc = 1, dec = 1, point = 0; // for loop counter from 1 to last index of list for (int i = 1; i < n; i++) { // check if current int is // smaller than previous int if (a[i] < a[i - 1]) { // if inc is 1, i.e., increasing // seq. never started if (inc == 1) // increase dec by 1 dec++; else return -1; } // check if current int is greater than previous int else if (a[i] > a[i - 1]) { // if inc is 1, i.e., increasing seq. // starting for first time, if (inc == 1) // store a[i-1] in point point = a[i - 1]; // only if decreasing seq. minimum // count has been met, if (dec >= 2) // increase inc by 1 inc++; else // return -1 as decreasing seq. // min. count must be 2 return -1; } // check if current int is equal // to previous int, if so, else if (a[i] == a[i - 1]) return -1; } // check if inc >= 2 and dec >= 2 // return point if (inc >= 2 && dec >= 2) return point; // otherwise return -1 else return -1; } // Driver code public static void main(String args[]) { int arr[] = { 3, 2, 1, 2 }; int n = arr.length ; int ele = findElement(arr, n); if (ele == -1) System.out.println("No such element exist"); else System.out.println(ele); } // This Code is contributed by ANKITRAI1}
# Python implementation of above approachdef findElement(a, n): # set increasing sequence counter to 1 inc = 1 # set decreasing sequence counter to 1 dec = 1 # for loop counter from 1 to last # index of list [len(array)-1] for i in range(1, n): # check if current int is smaller than previous int if(a[i] < a[i-1]): # if inc is 1, i.e., increasing seq. never started, if inc == 1: # increase dec by 1 dec = dec + 1 else: # return -1 since if increasing seq. has started, # there cannot be a decreasing seq. in a valley return -1 # check if current int is greater than previous int elif(a[i] > a[i-1]): # if inc is 1, i.e., increasing seq. # starting for first time, if inc == 1: # store a[i-1] in point point = a[i-1] # only if decreasing seq. minimum count has been met, if dec >= 2: # increase inc by 1 inc = inc + 1 else: # return -1 as decreasing seq. min. count must be 2 return -1 # check if current int is equal to previous int, if so, elif(a[i] == a[i-1]): # return false as valley is always # strictly increasing / decreasing return -1 # check if inc >= 2 and dec >= 2, if(inc >= 2 and dec >= 2): # return point return point else: # otherwise return -1 return -1 a = [2, 1, 2]n = len(a)ele = findElement(a, n)if ( ele == -1 ): print("No such element exist")else: print(ele)
// C# implementation of above approachusing System; class GFG{ // Function to check such sequencestatic int findElement(int []a, int n){ // set increasing/decreasing // sequence counter to 1 int inc = 1, dec = 1, point = 0; // for loop counter from 1 to // last index of list for (int i = 1; i < n; i++) { // check if current int is // smaller than previous int if (a[i] < a[i - 1]) { // if inc is 1, i.e., increasing // seq. never started if (inc == 1) // increase dec by 1 dec++; else return -1; } // check if current int is greater // than previous int else if (a[i] > a[i - 1]) { // if inc is 1, i.e., increasing // seq. starting for first time, if (inc == 1) // store a[i-1] in point point = a[i - 1]; // only if decreasing seq. // minimum count has been met, if (dec >= 2) // increase inc by 1 inc++; else // return -1 as decreasing // seq. min. count must be 2 return -1; } // check if current int is equal // to previous int, if so, else if (a[i] == a[i - 1]) return -1; } // check if inc >= 2 and // dec >= 2, return point if (inc >= 2 && dec >= 2) return point; // otherwise return -1 else return -1;} // Driver codepublic static void Main(){ int []arr = { 3, 2, 1, 2 }; int n = arr.Length ; int ele = findElement(arr, n); if (ele == -1) Console.WriteLine("No such element exist"); else Console.WriteLine(ele); }} // This code is contributed by Shashank
<?php// PHP implementation of above approach // Function to check such sequencefunction findElement(&$a, $n){ // set increasing/decreasing // sequence counter to 1 $inc = 1; $dec = 1; // for loop counter from 1 // to last index of list for ($i = 1; $i < $n; $i++) { // check if current int is // smaller than previous int if ($a[$i] < $a[$i - 1]) { // if inc is 1, i.e., increasing // seq. never started if ($inc == 1) // increase dec by 1 $dec++; else return -1; } // check if current int is greater // than previous int else if ($a[$i] > $a[$i - 1]) { // if inc is 1, i.e., increasing // seq. starting for first time, if ($inc == 1) // store a[i-1] in point $point = $a[$i - 1]; // only if decreasing seq. // minimum count has been met, if ($dec >= 2) // increase inc by 1 $inc++; else // return -1 as decreasing // seq. min. count must be 2 return -1; } // check if current int is equal // to previous int, if so, else if ($a[$i] == $a[$i - 1]) return -1; } // check if inc >= 2 and // dec >= 2, return point if ($inc >= 2 && $dec >= 2) return $point; // otherwise return -1 else return -1;} // Driver code$arr = array(3, 2, 1, 2);$n = sizeof($arr); $ele = findElement($arr, $n); if ($ele == -1) echo "No such element exist";else echo $ele; // This code is contributed// by ChitraNayal?>
<script>// Java Script implementation of above approach // Function to check such sequence function findElement(a,n) { // set increasing/decreasing sequence counter to 1 let inc = 1, dec = 1, point = 0; // for loop counter from 1 to last index of list for (let i = 1; i < n; i++) { // check if current int is // smaller than previous int if (a[i] < a[i - 1]) { // if inc is 1, i.e., increasing // seq. never started if (inc == 1) // increase dec by 1 dec++; else return -1; } // check if current int is greater than previous int else if (a[i] > a[i - 1]) { // if inc is 1, i.e., increasing seq. // starting for first time, if (inc == 1) // store a[i-1] in point point = a[i - 1]; // only if decreasing seq. minimum // count has been met, if (dec >= 2) // increase inc by 1 inc++; else // return -1 as decreasing seq. // min. count must be 2 return -1; } // check if current int is equal // to previous int, if so, else if (a[i] == a[i - 1]) return -1; } // check if inc >= 2 and dec >= 2 // return point if (inc >= 2 && dec >= 2) return point; // otherwise return -1 else return -1; } // Driver code let arr = [3, 2, 1, 2 ]; let n = arr.length ; let ele = findElement(arr, n); if (ele == -1) document.write("No such element exist"); else document.write(ele); // This code is contributed by sravan kumar Gottumukkala</script>
1
Time Complexity: O(n)
Auxiliary Space: O(1)
ankthon
Shashank12
ukasp
sravankumar8128
samim2000
Traversal
Arrays
Arrays
Traversal
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Stack Data Structure (Introduction and Program)
Top 50 Array Coding Problems for Interviews
Multidimensional Arrays in Java
Introduction to Arrays
Linear Search
Maximum and minimum of an array using minimum number of comparisons
Python | Using 2D arrays/lists the right way
Linked List vs Array
Queue | Set 1 (Introduction and Array Implementation)
Find the Missing Number | [
{
"code": null,
"e": 25522,
"s": 25494,
"text": "\n19 Jan, 2022"
},
{
"code": null,
"e": 25716,
"s": 25522,
"text": "Given an array of positive integers, the task is to find a point/element up to which elements form a strictly decreasing sequence first followed by a sequence of strictly increasing integers. "
},
{
"code": null,
"e": 25801,
"s": 25716,
"text": "Both of the sequences must at least be of length 2 (considering the common element)."
},
{
"code": null,
"e": 25890,
"s": 25801,
"text": "The last value of the decreasing sequence is the first value of the increasing sequence."
},
{
"code": null,
"e": 25952,
"s": 25890,
"text": "Note: Print “No such element exist”, if not found.Examples: "
},
{
"code": null,
"e": 26116,
"s": 25952,
"text": "Input: arr[] = {3, 2, 1, 2}\nOutput: 1\n{3, 2, 1} is strictly decreasing \nthen {1, 2} is strictly increasing.\n\nInput: arr[] = {3, 2, 1}\nOutput: No such element exist"
},
{
"code": null,
"e": 26130,
"s": 26118,
"text": "Approach: "
},
{
"code": null,
"e": 26552,
"s": 26130,
"text": "First start traversing the array and keep traversing till the elements are in strictly decreasing order.If next elements is greater than the previous element store that element in point variable.Start traversing the elements from that point and keep traversing till the elements are in the strictly increasing order.After step 3, if all the elements get traversed then print that point.Else print “No such element exist.”"
},
{
"code": null,
"e": 26657,
"s": 26552,
"text": "First start traversing the array and keep traversing till the elements are in strictly decreasing order."
},
{
"code": null,
"e": 26749,
"s": 26657,
"text": "If next elements is greater than the previous element store that element in point variable."
},
{
"code": null,
"e": 26871,
"s": 26749,
"text": "Start traversing the elements from that point and keep traversing till the elements are in the strictly increasing order."
},
{
"code": null,
"e": 26942,
"s": 26871,
"text": "After step 3, if all the elements get traversed then print that point."
},
{
"code": null,
"e": 26978,
"s": 26942,
"text": "Else print “No such element exist.”"
},
{
"code": null,
"e": 27162,
"s": 26978,
"text": "Note: If any of the two elements are equal then also print “No such element exist” as it should be strictly decreasing and increasing. Below is the implementation of above approach: "
},
{
"code": null,
"e": 27166,
"s": 27162,
"text": "C++"
},
{
"code": null,
"e": 27171,
"s": 27166,
"text": "Java"
},
{
"code": null,
"e": 27178,
"s": 27171,
"text": "Python"
},
{
"code": null,
"e": 27181,
"s": 27178,
"text": "C#"
},
{
"code": null,
"e": 27185,
"s": 27181,
"text": "PHP"
},
{
"code": null,
"e": 27196,
"s": 27185,
"text": "Javascript"
},
{
"code": "// C++ implementation of above approach#include <bits/stdc++.h>using namespace std; // Function to check such sequenceint findElement(int a[], int n){ // set increasing/decreasing sequence counter to 1 int inc = 1, dec = 1, point; // for loop counter from 1 to last index of list for (int i = 1; i < n; i++) { // check if current int is // smaller than previous int if (a[i] < a[i - 1]) { // if inc is 1, i.e., increasing // seq. never started if (inc == 1) // increase dec by 1 dec++; else return -1; } // check if current int is greater than previous int else if (a[i] > a[i - 1]) { // if inc is 1, i.e., increasing seq. // starting for first time, if (inc == 1) // store a[i-1] in point point = a[i - 1]; // only if decreasing seq. minimum // count has been met, if (dec >= 2) // increase inc by 1 inc++; else // return -1 as decreasing seq. // min. count must be 2 return -1; } // check if current int is equal // to previous int, if so, else if (a[i] == a[i - 1]) return -1; } // check if inc >= 2 and dec >= 2 // return point if (inc >= 2 && dec >= 2) return point; // otherwise return -1 else return -1;} // Driver codeint main(){ int arr[] = { 3, 2, 1, 2 }; int n = sizeof(arr) / sizeof(arr[0]); int ele = findElement(arr, n); if (ele == -1) cout << \"No such element exist\"; else cout << ele; return 0;}",
"e": 28954,
"s": 27196,
"text": null
},
{
"code": "// Java implementation of above approach public class GFG { // Function to check such sequence static int findElement(int a[], int n) { // set increasing/decreasing sequence counter to 1 int inc = 1, dec = 1, point = 0; // for loop counter from 1 to last index of list for (int i = 1; i < n; i++) { // check if current int is // smaller than previous int if (a[i] < a[i - 1]) { // if inc is 1, i.e., increasing // seq. never started if (inc == 1) // increase dec by 1 dec++; else return -1; } // check if current int is greater than previous int else if (a[i] > a[i - 1]) { // if inc is 1, i.e., increasing seq. // starting for first time, if (inc == 1) // store a[i-1] in point point = a[i - 1]; // only if decreasing seq. minimum // count has been met, if (dec >= 2) // increase inc by 1 inc++; else // return -1 as decreasing seq. // min. count must be 2 return -1; } // check if current int is equal // to previous int, if so, else if (a[i] == a[i - 1]) return -1; } // check if inc >= 2 and dec >= 2 // return point if (inc >= 2 && dec >= 2) return point; // otherwise return -1 else return -1; } // Driver code public static void main(String args[]) { int arr[] = { 3, 2, 1, 2 }; int n = arr.length ; int ele = findElement(arr, n); if (ele == -1) System.out.println(\"No such element exist\"); else System.out.println(ele); } // This Code is contributed by ANKITRAI1} ",
"e": 31156,
"s": 28954,
"text": null
},
{
"code": "# Python implementation of above approachdef findElement(a, n): # set increasing sequence counter to 1 inc = 1 # set decreasing sequence counter to 1 dec = 1 # for loop counter from 1 to last # index of list [len(array)-1] for i in range(1, n): # check if current int is smaller than previous int if(a[i] < a[i-1]): # if inc is 1, i.e., increasing seq. never started, if inc == 1: # increase dec by 1 dec = dec + 1 else: # return -1 since if increasing seq. has started, # there cannot be a decreasing seq. in a valley return -1 # check if current int is greater than previous int elif(a[i] > a[i-1]): # if inc is 1, i.e., increasing seq. # starting for first time, if inc == 1: # store a[i-1] in point point = a[i-1] # only if decreasing seq. minimum count has been met, if dec >= 2: # increase inc by 1 inc = inc + 1 else: # return -1 as decreasing seq. min. count must be 2 return -1 # check if current int is equal to previous int, if so, elif(a[i] == a[i-1]): # return false as valley is always # strictly increasing / decreasing return -1 # check if inc >= 2 and dec >= 2, if(inc >= 2 and dec >= 2): # return point return point else: # otherwise return -1 return -1 a = [2, 1, 2]n = len(a)ele = findElement(a, n)if ( ele == -1 ): print(\"No such element exist\")else: print(ele)",
"e": 32859,
"s": 31156,
"text": null
},
{
"code": "// C# implementation of above approachusing System; class GFG{ // Function to check such sequencestatic int findElement(int []a, int n){ // set increasing/decreasing // sequence counter to 1 int inc = 1, dec = 1, point = 0; // for loop counter from 1 to // last index of list for (int i = 1; i < n; i++) { // check if current int is // smaller than previous int if (a[i] < a[i - 1]) { // if inc is 1, i.e., increasing // seq. never started if (inc == 1) // increase dec by 1 dec++; else return -1; } // check if current int is greater // than previous int else if (a[i] > a[i - 1]) { // if inc is 1, i.e., increasing // seq. starting for first time, if (inc == 1) // store a[i-1] in point point = a[i - 1]; // only if decreasing seq. // minimum count has been met, if (dec >= 2) // increase inc by 1 inc++; else // return -1 as decreasing // seq. min. count must be 2 return -1; } // check if current int is equal // to previous int, if so, else if (a[i] == a[i - 1]) return -1; } // check if inc >= 2 and // dec >= 2, return point if (inc >= 2 && dec >= 2) return point; // otherwise return -1 else return -1;} // Driver codepublic static void Main(){ int []arr = { 3, 2, 1, 2 }; int n = arr.Length ; int ele = findElement(arr, n); if (ele == -1) Console.WriteLine(\"No such element exist\"); else Console.WriteLine(ele); }} // This code is contributed by Shashank",
"e": 34696,
"s": 32859,
"text": null
},
{
"code": "<?php// PHP implementation of above approach // Function to check such sequencefunction findElement(&$a, $n){ // set increasing/decreasing // sequence counter to 1 $inc = 1; $dec = 1; // for loop counter from 1 // to last index of list for ($i = 1; $i < $n; $i++) { // check if current int is // smaller than previous int if ($a[$i] < $a[$i - 1]) { // if inc is 1, i.e., increasing // seq. never started if ($inc == 1) // increase dec by 1 $dec++; else return -1; } // check if current int is greater // than previous int else if ($a[$i] > $a[$i - 1]) { // if inc is 1, i.e., increasing // seq. starting for first time, if ($inc == 1) // store a[i-1] in point $point = $a[$i - 1]; // only if decreasing seq. // minimum count has been met, if ($dec >= 2) // increase inc by 1 $inc++; else // return -1 as decreasing // seq. min. count must be 2 return -1; } // check if current int is equal // to previous int, if so, else if ($a[$i] == $a[$i - 1]) return -1; } // check if inc >= 2 and // dec >= 2, return point if ($inc >= 2 && $dec >= 2) return $point; // otherwise return -1 else return -1;} // Driver code$arr = array(3, 2, 1, 2);$n = sizeof($arr); $ele = findElement($arr, $n); if ($ele == -1) echo \"No such element exist\";else echo $ele; // This code is contributed// by ChitraNayal?>",
"e": 36450,
"s": 34696,
"text": null
},
{
"code": "<script>// Java Script implementation of above approach // Function to check such sequence function findElement(a,n) { // set increasing/decreasing sequence counter to 1 let inc = 1, dec = 1, point = 0; // for loop counter from 1 to last index of list for (let i = 1; i < n; i++) { // check if current int is // smaller than previous int if (a[i] < a[i - 1]) { // if inc is 1, i.e., increasing // seq. never started if (inc == 1) // increase dec by 1 dec++; else return -1; } // check if current int is greater than previous int else if (a[i] > a[i - 1]) { // if inc is 1, i.e., increasing seq. // starting for first time, if (inc == 1) // store a[i-1] in point point = a[i - 1]; // only if decreasing seq. minimum // count has been met, if (dec >= 2) // increase inc by 1 inc++; else // return -1 as decreasing seq. // min. count must be 2 return -1; } // check if current int is equal // to previous int, if so, else if (a[i] == a[i - 1]) return -1; } // check if inc >= 2 and dec >= 2 // return point if (inc >= 2 && dec >= 2) return point; // otherwise return -1 else return -1; } // Driver code let arr = [3, 2, 1, 2 ]; let n = arr.length ; let ele = findElement(arr, n); if (ele == -1) document.write(\"No such element exist\"); else document.write(ele); // This code is contributed by sravan kumar Gottumukkala</script>",
"e": 38626,
"s": 36450,
"text": null
},
{
"code": null,
"e": 38628,
"s": 38626,
"text": "1"
},
{
"code": null,
"e": 38654,
"s": 38630,
"text": "Time Complexity: O(n) "
},
{
"code": null,
"e": 38676,
"s": 38654,
"text": "Auxiliary Space: O(1)"
},
{
"code": null,
"e": 38684,
"s": 38676,
"text": "ankthon"
},
{
"code": null,
"e": 38695,
"s": 38684,
"text": "Shashank12"
},
{
"code": null,
"e": 38701,
"s": 38695,
"text": "ukasp"
},
{
"code": null,
"e": 38717,
"s": 38701,
"text": "sravankumar8128"
},
{
"code": null,
"e": 38727,
"s": 38717,
"text": "samim2000"
},
{
"code": null,
"e": 38737,
"s": 38727,
"text": "Traversal"
},
{
"code": null,
"e": 38744,
"s": 38737,
"text": "Arrays"
},
{
"code": null,
"e": 38751,
"s": 38744,
"text": "Arrays"
},
{
"code": null,
"e": 38761,
"s": 38751,
"text": "Traversal"
},
{
"code": null,
"e": 38859,
"s": 38761,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 38907,
"s": 38859,
"text": "Stack Data Structure (Introduction and Program)"
},
{
"code": null,
"e": 38951,
"s": 38907,
"text": "Top 50 Array Coding Problems for Interviews"
},
{
"code": null,
"e": 38983,
"s": 38951,
"text": "Multidimensional Arrays in Java"
},
{
"code": null,
"e": 39006,
"s": 38983,
"text": "Introduction to Arrays"
},
{
"code": null,
"e": 39020,
"s": 39006,
"text": "Linear Search"
},
{
"code": null,
"e": 39088,
"s": 39020,
"text": "Maximum and minimum of an array using minimum number of comparisons"
},
{
"code": null,
"e": 39133,
"s": 39088,
"text": "Python | Using 2D arrays/lists the right way"
},
{
"code": null,
"e": 39154,
"s": 39133,
"text": "Linked List vs Array"
},
{
"code": null,
"e": 39208,
"s": 39154,
"text": "Queue | Set 1 (Introduction and Array Implementation)"
}
] |
VHDL Programming Combinational Circuits | This chapter explains the VHDL programming for Combinational Circuits.
VHDL Code:
Library ieee;
use ieee.std_logic_1164.all;
entity half_adder is
port(a,b:in bit; sum,carry:out bit);
end half_adder;
architecture data of half_adder is
begin
sum<= a xor b;
carry <= a and b;
end data;
Library ieee;
use ieee.std_logic_1164.all;
entity full_adder is port(a,b,c:in bit; sum,carry:out bit);
end full_adder;
architecture data of full_adder is
begin
sum<= a xor b xor c;
carry <= ((a and b) or (b and c) or (a and c));
end data;
Library ieee;
use ieee.std_logic_1164.all;
entity half_sub is
port(a,c:in bit; d,b:out bit);
end half_sub;
architecture data of half_sub is
begin
d<= a xor c;
b<= (a and (not c));
end data;
Library ieee;
use ieee.std_logic_1164.all;
entity full_sub is
port(a,b,c:in bit; sub,borrow:out bit);
end full_sub;
architecture data of full_sub is
begin
sub<= a xor b xor c;
borrow <= ((b xor c) and (not a)) or (b and c);
end data;
Library ieee;
use ieee.std_logic_1164.all;
entity mux is
port(S1,S0,D0,D1,D2,D3:in bit; Y:out bit);
end mux;
architecture data of mux is
begin
Y<= (not S0 and not S1 and D0) or
(S0 and not S1 and D1) or
(not S0 and S1 and D2) or
(S0 and S1 and D3);
end data;
Library ieee;
use ieee.std_logic_1164.all;
entity demux is
port(S1,S0,D:in bit; Y0,Y1,Y2,Y3:out bit);
end demux;
architecture data of demux is
begin
Y0<= ((Not S0) and (Not S1) and D);
Y1<= ((Not S0) and S1 and D);
Y2<= (S0 and (Not S1) and D);
Y3<= (S0 and S1 and D);
end data;
library ieee;
use ieee.std_logic_1164.all;
entity enc is
port(i0,i1,i2,i3,i4,i5,i6,i7:in bit; o0,o1,o2: out bit);
end enc;
architecture vcgandhi of enc is
begin
o0<=i4 or i5 or i6 or i7;
o1<=i2 or i3 or i6 or i7;
o2<=i1 or i3 or i5 or i7;
end vcgandhi;
library ieee;
use ieee.std_logic_1164.all;
entity dec is
port(i0,i1,i2:in bit; o0,o1,o2,o3,o4,o5,o6,o7: out bit);
end dec;
architecture vcgandhi of dec is
begin
o0<=(not i0) and (not i1) and (not i2);
o1<=(not i0) and (not i1) and i2;
o2<=(not i0) and i1 and (not i2);
o3<=(not i0) and i1 and i2;
o4<=i0 and (not i1) and (not i2);
o5<=i0 and (not i1) and i2;
o6<=i0 and i1 and (not i2);
o7<=i0 and i1 and i2;
end vcgandhi;
library IEEE;
use IEEE.STD_LOGIC_1164.all;
entity pa is
port(a : in STD_LOGIC_VECTOR(3 downto 0);
b : in STD_LOGIC_VECTOR(3 downto 0);
ca : out STD_LOGIC;
sum : out STD_LOGIC_VECTOR(3 downto 0)
);
end pa;
architecture vcgandhi of pa is
Component fa is
port (a : in STD_LOGIC;
b : in STD_LOGIC;
c : in STD_LOGIC;
sum : out STD_LOGIC;
ca : out STD_LOGIC
);
end component;
signal s : std_logic_vector (2 downto 0);
signal temp: std_logic;
begin
temp<='0';
u0 : fa port map (a(0),b(0),temp,sum(0),s(0));
u1 : fa port map (a(1),b(1),s(0),sum(1),s(1));
u2 : fa port map (a(2),b(2),s(1),sum(2),s(2));
ue : fa port map (a(3),b(3),s(2),sum(3),ca);
end vcgandhi;
library ieee;
use ieee.std_logic_1164.all;
entity parity_checker is
port (a0,a1,a2,a3 : in std_logic;
p : out std_logic);
end parity_checker;
architecture vcgandhi of parity_checker is
begin
p <= (((a0 xor a1) xor a2) xor a3);
end vcgandhi;
library ieee;
use ieee.std_logic_1164.all;
entity paritygen is
port (a0, a1, a2, a3: in std_logic; p_odd, p_even: out std_logic);
end paritygen;
architecture vcgandhi of paritygen is
begin
process (a0, a1, a2, a3)
if (a0 ='0' and a1 ='0' and a2 ='0' and a3 =’0’)
then odd_out <= "0";
even_out <= "0";
else
p_odd <= (((a0 xor a1) xor a2) xor a3);
p_even <= not(((a0 xor a1) xor a2) xor a3);
end vcgandhi
23 Lectures
12 hours
Uplatz
12 Lectures
1.5 hours
Rajeev Raghu Raman Arunachalam
Print
Add Notes
Bookmark this page | [
{
"code": null,
"e": 2010,
"s": 1939,
"text": "This chapter explains the VHDL programming for Combinational Circuits."
},
{
"code": null,
"e": 2247,
"s": 2010,
"text": "VHDL Code:\n \nLibrary ieee; \nuse ieee.std_logic_1164.all;\n \nentity half_adder is\n port(a,b:in bit; sum,carry:out bit); \nend half_adder; \n \narchitecture data of half_adder is\nbegin\n sum<= a xor b; \n carry <= a and b; \nend data; "
},
{
"code": null,
"e": 2501,
"s": 2247,
"text": "Library ieee; \nuse ieee.std_logic_1164.all;\n \nentity full_adder is port(a,b,c:in bit; sum,carry:out bit); \nend full_adder;\n \narchitecture data of full_adder is\nbegin\n sum<= a xor b xor c; \n carry <= ((a and b) or (b and c) or (a and c)); \nend data;"
},
{
"code": null,
"e": 2707,
"s": 2501,
"text": "Library ieee;\nuse ieee.std_logic_1164.all;\n \nentity half_sub is\n port(a,c:in bit; d,b:out bit);\nend half_sub; \n\narchitecture data of half_sub is\nbegin\n d<= a xor c;\n b<= (a and (not c));\nend data;\n"
},
{
"code": null,
"e": 2961,
"s": 2707,
"text": "Library ieee; \nuse ieee.std_logic_1164.all;\n \nentity full_sub is\n port(a,b,c:in bit; sub,borrow:out bit); \nend full_sub; \n \narchitecture data of full_sub is\nbegin\n sub<= a xor b xor c; \n borrow <= ((b xor c) and (not a)) or (b and c); \nend data; "
},
{
"code": null,
"e": 3255,
"s": 2961,
"text": "Library ieee; \nuse ieee.std_logic_1164.all;\n \nentity mux is\n port(S1,S0,D0,D1,D2,D3:in bit; Y:out bit);\nend mux;\n \narchitecture data of mux is\nbegin \n Y<= (not S0 and not S1 and D0) or \n (S0 and not S1 and D1) or \n (not S0 and S1 and D2) or\n (S0 and S1 and D3); \nend data;"
},
{
"code": null,
"e": 3566,
"s": 3255,
"text": "Library ieee; \nuse ieee.std_logic_1164.all;\n \nentity demux is\n port(S1,S0,D:in bit; Y0,Y1,Y2,Y3:out bit); \nend demux;\n \narchitecture data of demux is\nbegin \n Y0<= ((Not S0) and (Not S1) and D); \n Y1<= ((Not S0) and S1 and D); \n Y2<= (S0 and (Not S1) and D); \n Y3<= (S0 and S1 and D); \nend data;"
},
{
"code": null,
"e": 3843,
"s": 3566,
"text": "library ieee; \nuse ieee.std_logic_1164.all; \n \nentity enc is\n port(i0,i1,i2,i3,i4,i5,i6,i7:in bit; o0,o1,o2: out bit); \nend enc; \n \narchitecture vcgandhi of enc is\nbegin \n o0<=i4 or i5 or i6 or i7; \n o1<=i2 or i3 or i6 or i7; \n o2<=i1 or i3 or i5 or i7; \nend vcgandhi;"
},
{
"code": null,
"e": 4308,
"s": 3843,
"text": "library ieee; \nuse ieee.std_logic_1164.all;\n\nentity dec is\n port(i0,i1,i2:in bit; o0,o1,o2,o3,o4,o5,o6,o7: out bit); \nend dec; \n \narchitecture vcgandhi of dec is\nbegin \n o0<=(not i0) and (not i1) and (not i2); \n o1<=(not i0) and (not i1) and i2; \n o2<=(not i0) and i1 and (not i2); \n o3<=(not i0) and i1 and i2; \n o4<=i0 and (not i1) and (not i2); \n o5<=i0 and (not i1) and i2; \n o6<=i0 and i1 and (not i2); \n o7<=i0 and i1 and i2; \nend vcgandhi;"
},
{
"code": null,
"e": 5090,
"s": 4308,
"text": "library IEEE; \nuse IEEE.STD_LOGIC_1164.all;\n \nentity pa is\n port(a : in STD_LOGIC_VECTOR(3 downto 0);\n b : in STD_LOGIC_VECTOR(3 downto 0);\n ca : out STD_LOGIC;\n sum : out STD_LOGIC_VECTOR(3 downto 0) \n ); \nend pa; \n \narchitecture vcgandhi of pa is\n Component fa is\n port (a : in STD_LOGIC; \n b : in STD_LOGIC; \n c : in STD_LOGIC; \n sum : out STD_LOGIC; \n ca : out STD_LOGIC\n ); \n end component; \n signal s : std_logic_vector (2 downto 0); \n signal temp: std_logic;\nbegin \n temp<='0'; \n u0 : fa port map (a(0),b(0),temp,sum(0),s(0)); \n u1 : fa port map (a(1),b(1),s(0),sum(1),s(1)); \n u2 : fa port map (a(2),b(2),s(1),sum(2),s(2));\n ue : fa port map (a(3),b(3),s(2),sum(3),ca); \nend vcgandhi;"
},
{
"code": null,
"e": 5359,
"s": 5090,
"text": "library ieee; \nuse ieee.std_logic_1164.all; \n \nentity parity_checker is \n port (a0,a1,a2,a3 : in std_logic; \n p : out std_logic); \nend parity_checker; \n\narchitecture vcgandhi of parity_checker is \nbegin \n p <= (((a0 xor a1) xor a2) xor a3); \nend vcgandhi;"
},
{
"code": null,
"e": 5808,
"s": 5359,
"text": "library ieee;\nuse ieee.std_logic_1164.all;\n\nentity paritygen is\n port (a0, a1, a2, a3: in std_logic; p_odd, p_even: out std_logic);\nend paritygen; \n\narchitecture vcgandhi of paritygen is\nbegin\n process (a0, a1, a2, a3)\n \n if (a0 ='0' and a1 ='0' and a2 ='0' and a3 =’0’)\n then odd_out <= \"0\";\n even_out <= \"0\";\n else\n p_odd <= (((a0 xor a1) xor a2) xor a3);\n p_even <= not(((a0 xor a1) xor a2) xor a3); \nend vcgandhi"
},
{
"code": null,
"e": 5842,
"s": 5808,
"text": "\n 23 Lectures \n 12 hours \n"
},
{
"code": null,
"e": 5850,
"s": 5842,
"text": " Uplatz"
},
{
"code": null,
"e": 5885,
"s": 5850,
"text": "\n 12 Lectures \n 1.5 hours \n"
},
{
"code": null,
"e": 5917,
"s": 5885,
"text": " Rajeev Raghu Raman Arunachalam"
},
{
"code": null,
"e": 5924,
"s": 5917,
"text": " Print"
},
{
"code": null,
"e": 5935,
"s": 5924,
"text": " Add Notes"
}
] |
Matplotlib - Scatter Plot | Scatter plots are used to plot data points on horizontal and vertical axis in the attempt to show how much one variable is affected by another. Each row in the data table is represented by a marker the position depends on its values in the columns set on the X and Y axes. A third variable can be set to correspond to the color or size of the markers, thus adding yet another dimension to the plot.
The script below plots a scatter diagram of grades range vs grades of boys and girls in two different colors.
import matplotlib.pyplot as plt
girls_grades = [89, 90, 70, 89, 100, 80, 90, 100, 80, 34]
boys_grades = [30, 29, 49, 48, 100, 48, 38, 45, 20, 30]
grades_range = [10, 20, 30, 40, 50, 60, 70, 80, 90, 100]
fig=plt.figure()
ax=fig.add_axes([0,0,1,1])
ax.scatter(grades_range, girls_grades, color='r')
ax.scatter(grades_range, boys_grades, color='b')
ax.set_xlabel('Grades Range')
ax.set_ylabel('Grades Scored')
ax.set_title('scatter plot')
plt.show()
63 Lectures
6 hours
Abhilash Nelson
11 Lectures
4 hours
DATAhill Solutions Srinivas Reddy
9 Lectures
2.5 hours
DATAhill Solutions Srinivas Reddy
32 Lectures
4 hours
Aipython
10 Lectures
2.5 hours
Akbar Khan
63 Lectures
6 hours
Anmol
Print
Add Notes
Bookmark this page | [
{
"code": null,
"e": 2915,
"s": 2516,
"text": "Scatter plots are used to plot data points on horizontal and vertical axis in the attempt to show how much one variable is affected by another. Each row in the data table is represented by a marker the position depends on its values in the columns set on the X and Y axes. A third variable can be set to correspond to the color or size of the markers, thus adding yet another dimension to the plot."
},
{
"code": null,
"e": 3025,
"s": 2915,
"text": "The script below plots a scatter diagram of grades range vs grades of boys and girls in two different colors."
},
{
"code": null,
"e": 3472,
"s": 3025,
"text": "import matplotlib.pyplot as plt\ngirls_grades = [89, 90, 70, 89, 100, 80, 90, 100, 80, 34]\nboys_grades = [30, 29, 49, 48, 100, 48, 38, 45, 20, 30]\ngrades_range = [10, 20, 30, 40, 50, 60, 70, 80, 90, 100]\nfig=plt.figure()\nax=fig.add_axes([0,0,1,1])\nax.scatter(grades_range, girls_grades, color='r')\nax.scatter(grades_range, boys_grades, color='b')\nax.set_xlabel('Grades Range')\nax.set_ylabel('Grades Scored')\nax.set_title('scatter plot')\nplt.show()"
},
{
"code": null,
"e": 3505,
"s": 3472,
"text": "\n 63 Lectures \n 6 hours \n"
},
{
"code": null,
"e": 3522,
"s": 3505,
"text": " Abhilash Nelson"
},
{
"code": null,
"e": 3555,
"s": 3522,
"text": "\n 11 Lectures \n 4 hours \n"
},
{
"code": null,
"e": 3590,
"s": 3555,
"text": " DATAhill Solutions Srinivas Reddy"
},
{
"code": null,
"e": 3624,
"s": 3590,
"text": "\n 9 Lectures \n 2.5 hours \n"
},
{
"code": null,
"e": 3659,
"s": 3624,
"text": " DATAhill Solutions Srinivas Reddy"
},
{
"code": null,
"e": 3692,
"s": 3659,
"text": "\n 32 Lectures \n 4 hours \n"
},
{
"code": null,
"e": 3702,
"s": 3692,
"text": " Aipython"
},
{
"code": null,
"e": 3737,
"s": 3702,
"text": "\n 10 Lectures \n 2.5 hours \n"
},
{
"code": null,
"e": 3749,
"s": 3737,
"text": " Akbar Khan"
},
{
"code": null,
"e": 3782,
"s": 3749,
"text": "\n 63 Lectures \n 6 hours \n"
},
{
"code": null,
"e": 3789,
"s": 3782,
"text": " Anmol"
},
{
"code": null,
"e": 3796,
"s": 3789,
"text": " Print"
},
{
"code": null,
"e": 3807,
"s": 3796,
"text": " Add Notes"
}
] |
Java String length() Method | ❮ String Methods
Return the number of characters in a string:
String txt = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
System.out.println(txt.length());
Try it Yourself »
The length() method returns the length of a specified string.
Note: The length of an empty string is 0.
public int length()
None.
We just launchedW3Schools videos
Get certifiedby completinga course today!
If you want to report an error, or if you want to make a suggestion, do not hesitate to send us an e-mail:
[email protected]
Your message has been sent to W3Schools. | [
{
"code": null,
"e": 19,
"s": 0,
"text": "\n❮ String Methods\n"
},
{
"code": null,
"e": 64,
"s": 19,
"text": "Return the number of characters in a string:"
},
{
"code": null,
"e": 141,
"s": 64,
"text": "String txt = \"ABCDEFGHIJKLMNOPQRSTUVWXYZ\";\nSystem.out.println(txt.length());"
},
{
"code": null,
"e": 161,
"s": 141,
"text": "\nTry it Yourself »\n"
},
{
"code": null,
"e": 223,
"s": 161,
"text": "The length() method returns the length of a specified string."
},
{
"code": null,
"e": 265,
"s": 223,
"text": "Note: The length of an empty string is 0."
},
{
"code": null,
"e": 286,
"s": 265,
"text": "public int length()\n"
},
{
"code": null,
"e": 292,
"s": 286,
"text": "None."
},
{
"code": null,
"e": 325,
"s": 292,
"text": "We just launchedW3Schools videos"
},
{
"code": null,
"e": 367,
"s": 325,
"text": "Get certifiedby completinga course today!"
},
{
"code": null,
"e": 474,
"s": 367,
"text": "If you want to report an error, or if you want to make a suggestion, do not hesitate to send us an e-mail:"
},
{
"code": null,
"e": 493,
"s": 474,
"text": "[email protected]"
}
] |
<climits> (limits.h) in C/C++ - GeeksforGeeks | 25 Aug, 2021
The maximum and minimum size of integral values are quite useful or in simple terms limits of any integral type plays quite a role in programming. Instead of remembering these values different macros can be used.
<climits>(limits.h) defines sizes of integral types. This header defines constants with the limits of fundamental integral types for the specific system and compiler implementation used.The limits for fundamental floating-point types are defined in <cfloat> (<float.h>). The limits for width-specific integral types and other typedef types are defined in <cstdint> (<stdint.h>).
Different macro constants are :
1. CHAR_MIN :
Minimum value for an object of type char
Value of CHAR_MIN is either -127 (-27+1) or less* or 0
2. CHAR_MAX :
Maximum value for an object of type char
Value of CHAR_MAX is either 127 (27-1) or 255 (28-1) or greater*
3. SHRT_MIN :
Minimum value for an object of type short int
Value of SHRT_MIN is -32767 (-215+1) or less*
4. SHRT_MAX :
Maximum value for an object of type short int
Value of SHRT_MAX is 32767 (215-1) or greater*
5. USHRT_MAX :
Maximum value for an object of type unsigned short int
Value of USHRT_MAX is 65535 (216-1) or greater*
6. INT_MIN :
Minimum value for an object of type int
Value of INT_MIN is -32767 (-215+1) or less*
7. INT_MAX :
Maximum value for an object of type int
Value of INT_MAX is 32767 (215-1) or greater*
8. UINT_MAX :
Maximum value for an object of type unsigned int
Value of UINT_MAX is 65535 (216-1) or greater*
9. LONG_MIN :
Minimum value for an object of type long int
Value of LONG_MIN is -2147483647 (-231+1) or less*
10. LONG_MAX :
Maximum value for an object of type long int
Value of LONG_MAX is 2147483647 (231-1) or greater*
11. ULONG_MAX :
Maximum value for an object of type unsigned long int
Value of ULONG_MAX is 4294967295 (232-1) or greater*
12. LLONG_MIN :
Minimum value for an object of type long long int
Value of LLONG_MIN is -9223372036854775807 (-263+1) or less*
13. LLONG_MAX :
Maximum value for an object of type long long int
Value of LLONG_MAX is 9223372036854775807 (263-1) or greater*
14. ULLONG_MAX :
Maximum value for an object of type unsigned long long int
Value of ULLONG_MAX is 18446744073709551615 (264-1) or greater*
NOTE** the actual value depends on the particular system and library implementation, but shall reflect the limits of these types in the target platform.Your Machine’s values might depending upon whether it is 32-bit machine or 64 bit machine.
Compatibility : LLONG_MIN, LLONG_MAX and ULLONG_MAX are defined for libraries complying with the C standard of 1999 or later (which only includes the C++ standard since 2011: C++11).Two Applications of these MACROS are Checking for integer overflow and Computing minimum or maximum in an array of very large or very small elements.
Below Program will display the respective values for your machine:
C++
// C++ program to demonstrate working of// constants in climits.#include <climits>#include <iostream> using namespace std; int main(){ cout << "CHAR_MIN : " << CHAR_MIN << endl; cout << "CHAR_MAX : " << CHAR_MAX << endl; cout << "SHRT_MIN : " << SHRT_MIN << endl; cout << "SHRT_MAX : " << SHRT_MAX << endl; cout << "USHRT_MAX : " << USHRT_MAX << endl; cout << "INT_MIN : " << INT_MIN << endl; cout << "INT_MAX : " << INT_MAX << endl; cout << "UINT_MAX : " << UINT_MAX << endl; cout << "LONG_MIN : " << LONG_MIN << endl; cout << "LONG_MAX : " << LONG_MAX << endl; cout << "ULONG_MAX : " << ULONG_MAX << endl; cout << "LLONG_MIN : " << LLONG_MIN << endl; cout << "LLONG_MAX : " << LLONG_MAX << endl; cout << "ULLONG_MAX : " << ULLONG_MAX << endl; return 0;}
Output (Machine dependent):
CHAR_MIN : -128
CHAR_MAX : 127
SHRT_MIN : -32768
SHRT_MAX : 32767
USHRT_MAX : 65535
INT_MIN : -2147483648
INT_MAX : 2147483647
UINT_MAX : 4294967295
LONG_MIN : -9223372036854775808
LONG_MAX : 9223372036854775807
ULONG_MAX : 18446744073709551615
LLONG_MIN : -9223372036854775808
LLONG_MAX : 9223372036854775807
ULLONG_MAX : 18446744073709551615
sweetyty
CPP-Library
C Language
C++
CPP
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
TCP Server-Client implementation in C
Exception Handling in C++
Multithreading in C
Arrow operator -> in C/C++ with Examples
'this' pointer in C++
Vector in C++ STL
Initialize a vector in C++ (6 different ways)
Map in C++ Standard Template Library (STL)
Inheritance in C++
C++ Classes and Objects | [
{
"code": null,
"e": 23843,
"s": 23815,
"text": "\n25 Aug, 2021"
},
{
"code": null,
"e": 24056,
"s": 23843,
"text": "The maximum and minimum size of integral values are quite useful or in simple terms limits of any integral type plays quite a role in programming. Instead of remembering these values different macros can be used."
},
{
"code": null,
"e": 24435,
"s": 24056,
"text": "<climits>(limits.h) defines sizes of integral types. This header defines constants with the limits of fundamental integral types for the specific system and compiler implementation used.The limits for fundamental floating-point types are defined in <cfloat> (<float.h>). The limits for width-specific integral types and other typedef types are defined in <cstdint> (<stdint.h>)."
},
{
"code": null,
"e": 24467,
"s": 24435,
"text": "Different macro constants are :"
},
{
"code": null,
"e": 24482,
"s": 24467,
"text": "1. CHAR_MIN : "
},
{
"code": null,
"e": 24578,
"s": 24482,
"text": "Minimum value for an object of type char\nValue of CHAR_MIN is either -127 (-27+1) or less* or 0"
},
{
"code": null,
"e": 24594,
"s": 24578,
"text": "2. CHAR_MAX : "
},
{
"code": null,
"e": 24704,
"s": 24594,
"text": "Maximum value for an object of type char\nValue of CHAR_MAX is either 127 (27-1) or 255 (28-1) or greater* "
},
{
"code": null,
"e": 24720,
"s": 24704,
"text": "3. SHRT_MIN : "
},
{
"code": null,
"e": 24812,
"s": 24720,
"text": "Minimum value for an object of type short int\nValue of SHRT_MIN is -32767 (-215+1) or less*"
},
{
"code": null,
"e": 24828,
"s": 24812,
"text": "4. SHRT_MAX : "
},
{
"code": null,
"e": 24921,
"s": 24828,
"text": "Maximum value for an object of type short int\nValue of SHRT_MAX is 32767 (215-1) or greater*"
},
{
"code": null,
"e": 24938,
"s": 24921,
"text": "5. USHRT_MAX : "
},
{
"code": null,
"e": 25045,
"s": 24938,
"text": "Maximum value for an object of type unsigned short int \nValue of USHRT_MAX is 65535 (216-1) or greater*"
},
{
"code": null,
"e": 25060,
"s": 25045,
"text": "6. INT_MIN : "
},
{
"code": null,
"e": 25149,
"s": 25060,
"text": "Minimum value for an object of type int \nValue of INT_MIN is -32767 (-215+1) or less*"
},
{
"code": null,
"e": 25163,
"s": 25149,
"text": "7. INT_MAX : "
},
{
"code": null,
"e": 25253,
"s": 25163,
"text": "Maximum value for an object of type int \nValue of INT_MAX is 32767 (215-1) or greater*"
},
{
"code": null,
"e": 25269,
"s": 25253,
"text": "8. UINT_MAX : "
},
{
"code": null,
"e": 25369,
"s": 25269,
"text": "Maximum value for an object of type unsigned int \nValue of UINT_MAX is 65535 (216-1) or greater*"
},
{
"code": null,
"e": 25385,
"s": 25369,
"text": "9. LONG_MIN : "
},
{
"code": null,
"e": 25485,
"s": 25385,
"text": "Minimum value for an object of type long int \nValue of LONG_MIN is -2147483647 (-231+1) or less*"
},
{
"code": null,
"e": 25502,
"s": 25485,
"text": "10. LONG_MAX : "
},
{
"code": null,
"e": 25603,
"s": 25502,
"text": "Maximum value for an object of type long int \nValue of LONG_MAX is 2147483647 (231-1) or greater*"
},
{
"code": null,
"e": 25621,
"s": 25603,
"text": "11. ULONG_MAX : "
},
{
"code": null,
"e": 25732,
"s": 25621,
"text": "Maximum value for an object of type unsigned long int \nValue of ULONG_MAX is 4294967295 (232-1) or greater*"
},
{
"code": null,
"e": 25750,
"s": 25732,
"text": "12. LLONG_MIN : "
},
{
"code": null,
"e": 25865,
"s": 25750,
"text": "Minimum value for an object of type long long int \nValue of LLONG_MIN is -9223372036854775807 (-263+1) or less*"
},
{
"code": null,
"e": 25883,
"s": 25865,
"text": "13. LLONG_MAX : "
},
{
"code": null,
"e": 25999,
"s": 25883,
"text": "Maximum value for an object of type long long int \nValue of LLONG_MAX is 9223372036854775807 (263-1) or greater*"
},
{
"code": null,
"e": 26018,
"s": 25999,
"text": "14. ULLONG_MAX : "
},
{
"code": null,
"e": 26145,
"s": 26018,
"text": "Maximum value for an object of type unsigned long long int \nValue of ULLONG_MAX is 18446744073709551615 (264-1) or greater*"
},
{
"code": null,
"e": 26388,
"s": 26145,
"text": "NOTE** the actual value depends on the particular system and library implementation, but shall reflect the limits of these types in the target platform.Your Machine’s values might depending upon whether it is 32-bit machine or 64 bit machine."
},
{
"code": null,
"e": 26720,
"s": 26388,
"text": "Compatibility : LLONG_MIN, LLONG_MAX and ULLONG_MAX are defined for libraries complying with the C standard of 1999 or later (which only includes the C++ standard since 2011: C++11).Two Applications of these MACROS are Checking for integer overflow and Computing minimum or maximum in an array of very large or very small elements."
},
{
"code": null,
"e": 26789,
"s": 26720,
"text": "Below Program will display the respective values for your machine: "
},
{
"code": null,
"e": 26793,
"s": 26789,
"text": "C++"
},
{
"code": "// C++ program to demonstrate working of// constants in climits.#include <climits>#include <iostream> using namespace std; int main(){ cout << \"CHAR_MIN : \" << CHAR_MIN << endl; cout << \"CHAR_MAX : \" << CHAR_MAX << endl; cout << \"SHRT_MIN : \" << SHRT_MIN << endl; cout << \"SHRT_MAX : \" << SHRT_MAX << endl; cout << \"USHRT_MAX : \" << USHRT_MAX << endl; cout << \"INT_MIN : \" << INT_MIN << endl; cout << \"INT_MAX : \" << INT_MAX << endl; cout << \"UINT_MAX : \" << UINT_MAX << endl; cout << \"LONG_MIN : \" << LONG_MIN << endl; cout << \"LONG_MAX : \" << LONG_MAX << endl; cout << \"ULONG_MAX : \" << ULONG_MAX << endl; cout << \"LLONG_MIN : \" << LLONG_MIN << endl; cout << \"LLONG_MAX : \" << LLONG_MAX << endl; cout << \"ULLONG_MAX : \" << ULLONG_MAX << endl; return 0;}",
"e": 27594,
"s": 26793,
"text": null
},
{
"code": null,
"e": 27623,
"s": 27594,
"text": "Output (Machine dependent): "
},
{
"code": null,
"e": 27967,
"s": 27623,
"text": "CHAR_MIN : -128\nCHAR_MAX : 127\nSHRT_MIN : -32768\nSHRT_MAX : 32767\nUSHRT_MAX : 65535\nINT_MIN : -2147483648\nINT_MAX : 2147483647\nUINT_MAX : 4294967295\nLONG_MIN : -9223372036854775808\nLONG_MAX : 9223372036854775807\nULONG_MAX : 18446744073709551615\nLLONG_MIN : -9223372036854775808\nLLONG_MAX : 9223372036854775807\nULLONG_MAX : 18446744073709551615"
},
{
"code": null,
"e": 27978,
"s": 27969,
"text": "sweetyty"
},
{
"code": null,
"e": 27990,
"s": 27978,
"text": "CPP-Library"
},
{
"code": null,
"e": 28001,
"s": 27990,
"text": "C Language"
},
{
"code": null,
"e": 28005,
"s": 28001,
"text": "C++"
},
{
"code": null,
"e": 28009,
"s": 28005,
"text": "CPP"
},
{
"code": null,
"e": 28107,
"s": 28009,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 28116,
"s": 28107,
"text": "Comments"
},
{
"code": null,
"e": 28129,
"s": 28116,
"text": "Old Comments"
},
{
"code": null,
"e": 28167,
"s": 28129,
"text": "TCP Server-Client implementation in C"
},
{
"code": null,
"e": 28193,
"s": 28167,
"text": "Exception Handling in C++"
},
{
"code": null,
"e": 28213,
"s": 28193,
"text": "Multithreading in C"
},
{
"code": null,
"e": 28254,
"s": 28213,
"text": "Arrow operator -> in C/C++ with Examples"
},
{
"code": null,
"e": 28276,
"s": 28254,
"text": "'this' pointer in C++"
},
{
"code": null,
"e": 28294,
"s": 28276,
"text": "Vector in C++ STL"
},
{
"code": null,
"e": 28340,
"s": 28294,
"text": "Initialize a vector in C++ (6 different ways)"
},
{
"code": null,
"e": 28383,
"s": 28340,
"text": "Map in C++ Standard Template Library (STL)"
},
{
"code": null,
"e": 28402,
"s": 28383,
"text": "Inheritance in C++"
}
] |
What is an anonymous function in Python? | In Python, anonymous function is a function that is defined without a name. While normal functions are defined using the def keyword, in Python anonymous functions are defined using the lambda keyword. Hence, anonymous functions are also called lambda functions.
If we run the given code we get the following output
C:/Users/TutorialsPoint1/~.py
[(13, -3), (4, 1), (1, 2), (9, 10)] | [
{
"code": null,
"e": 1325,
"s": 1062,
"text": "In Python, anonymous function is a function that is defined without a name. While normal functions are defined using the def keyword, in Python anonymous functions are defined using the lambda keyword. Hence, anonymous functions are also called lambda functions."
},
{
"code": null,
"e": 1379,
"s": 1325,
"text": " If we run the given code we get the following output"
},
{
"code": null,
"e": 1447,
"s": 1379,
"text": "C:/Users/TutorialsPoint1/~.py\n[(13, -3), (4, 1), (1, 2), (9, 10)]\n\n"
}
] |
Python Pandas - Get the levels in MultiIndex | To get the levels in MultiIndex, use the MultiIndex.levels property in Pandas. At first, import the required libraries −
import pandas as pd
MultiIndex is a multi-level, or hierarchical, index object for pandas objects. Create arrays −
arrays = [[1, 2, 3, 4, 5], ['John', 'Tim', 'Jacob', 'Chris', 'Keiron']]
The "names" parameter sets the names for each of the index levels. The from_arrays() is used to create a Multiindex −
multiIndex = pd.MultiIndex.from_arrays(arrays, names=('ranks', 'student'))
Get the levels in Multiindex −
print("\nThe levels in Multi-index...\n",multiIndex.levels)
Following is the code −
import pandas as pd
# MultiIndex is a multi-level, or hierarchical, index object for pandas objects
# Create arrays
arrays = [[1, 2, 3, 4, 5], ['John', 'Tim', 'Jacob', 'Chris', 'Keiron']]
# The "names" parameter sets the names for each of the index levels
# The from_arrays() uis used to create a Multiindex
multiIndex = pd.MultiIndex.from_arrays(arrays, names=('ranks', 'student'))
# display the Multiindex
print("The Multi-index...\n",multiIndex)
# get the levels in Multiindex
print("\nThe levels in Multi-index...\n",multiIndex.levels)
This will produce the following output −
The Multi-index...
MultiIndex([(1, 'John'),
(2, 'Tim'),
(3, 'Jacob'),
(4, 'Chris'),
(5, 'Keiron')],
names=['ranks', 'student'])
The levels in Multi-index...
[[1, 2, 3, 4, 5], ['Chris', 'Jacob', 'John', 'Keiron', 'Tim']] | [
{
"code": null,
"e": 1183,
"s": 1062,
"text": "To get the levels in MultiIndex, use the MultiIndex.levels property in Pandas. At first, import the required libraries −"
},
{
"code": null,
"e": 1203,
"s": 1183,
"text": "import pandas as pd"
},
{
"code": null,
"e": 1298,
"s": 1203,
"text": "MultiIndex is a multi-level, or hierarchical, index object for pandas objects. Create arrays −"
},
{
"code": null,
"e": 1371,
"s": 1298,
"text": "arrays = [[1, 2, 3, 4, 5], ['John', 'Tim', 'Jacob', 'Chris', 'Keiron']]\n"
},
{
"code": null,
"e": 1489,
"s": 1371,
"text": "The \"names\" parameter sets the names for each of the index levels. The from_arrays() is used to create a Multiindex −"
},
{
"code": null,
"e": 1564,
"s": 1489,
"text": "multiIndex = pd.MultiIndex.from_arrays(arrays, names=('ranks', 'student'))"
},
{
"code": null,
"e": 1595,
"s": 1564,
"text": "Get the levels in Multiindex −"
},
{
"code": null,
"e": 1656,
"s": 1595,
"text": "print(\"\\nThe levels in Multi-index...\\n\",multiIndex.levels)\n"
},
{
"code": null,
"e": 1680,
"s": 1656,
"text": "Following is the code −"
},
{
"code": null,
"e": 2224,
"s": 1680,
"text": "import pandas as pd\n\n# MultiIndex is a multi-level, or hierarchical, index object for pandas objects\n# Create arrays\narrays = [[1, 2, 3, 4, 5], ['John', 'Tim', 'Jacob', 'Chris', 'Keiron']]\n\n# The \"names\" parameter sets the names for each of the index levels\n# The from_arrays() uis used to create a Multiindex\nmultiIndex = pd.MultiIndex.from_arrays(arrays, names=('ranks', 'student'))\n\n# display the Multiindex\nprint(\"The Multi-index...\\n\",multiIndex)\n\n# get the levels in Multiindex\nprint(\"\\nThe levels in Multi-index...\\n\",multiIndex.levels)"
},
{
"code": null,
"e": 2265,
"s": 2224,
"text": "This will produce the following output −"
},
{
"code": null,
"e": 2549,
"s": 2265,
"text": "The Multi-index...\nMultiIndex([(1, 'John'),\n (2, 'Tim'),\n (3, 'Jacob'),\n (4, 'Chris'),\n (5, 'Keiron')],\n names=['ranks', 'student'])\n\nThe levels in Multi-index...\n [[1, 2, 3, 4, 5], ['Chris', 'Jacob', 'John', 'Keiron', 'Tim']]"
}
] |
CSS Padding vs Margin - GeeksforGeeks | 24 May, 2021
In this article, we will explain the difference between CSS padding and margin.
Margin: It is the space around an element. Margins are used to move an element up or down on a page as well as left or right. Margin is completely transparent, and it does not have any background color. It clears the area around the element. Each side of the element has a margin size you can change individually. In creating the gap, the margin pushes adjacent elements away.
Padding: It is the space between the element and the related content inside it. It determines how elements look and sit within a container. It also shows the container background around the element in it. Padding can be affected by background colors as it clears the area around the content. To create the gap, it either grows the element size or shrinks the content inside. By default, the size of the element increases.
When to use Margin and Padding?
When you are adjusting the layout of your design, you will need to determine whether to adjust the margins or the padding. If the width of your page is fixed, centering an element horizontally is very simple, just assign the value margin: auto. You would also use the margin to set the distance between nearby elements.
You would change the padding if you want to create the space between the element and the edge of the container, or border.
Note: Margins are used to add spaces between an image and the description of that image.
CSS Padding is used if we want to create a space between an element and the edge of the container or the border. It is also useful in the requirement of changing the size of the element.
CSS code:
.center {
margin: auto;
background: lime;
width: 66%;
}
.outside {
margin: 3rem 0 0 -3rem;
background: cyan;
width: 66%;
}
Complete code:
HTML
<!DOCTYPE html><html><head><style> .center {margin: auto;background: lime;width: 66%;} .outside {margin: 3rem 0 0 -3rem;background: cyan;width: 66%;}</style></head><body> <h2 style="color:green">GeeksforGeeks</h2> <p class="center">This element is centered.</p> <p class="outside">The element is positioned outside of its corner.</p> </body></html>
Output:
Element outside corner
Note: When there is an increase in the padding value, the text will remain the same, but the surrounding space will increase.
CSS code:
h4 {
background-color: lime;
padding: 20px 50px;
}
h3 {
background-color: cyan;
padding: 110px 50px 50px 110px;
}
Complete code:
HTML
<!DOCTYPE html><html><head><style>h4 { background-color: lime;padding: 20px 50px;} h3 {background-color: cyan;padding: 110px 50px 50px 110px;}</style></head><body> <h2 style="color:green">GeeksforGeeks</h2> <h4>This element has moderate padding.</h4> <h3>The padding is huge in this element!</h3> </body></html>
Output:
moderate and huge padding
The tabular difference between Padding and Margin.
The different attributes of margin and padding
CSS-Properties
Picked
CSS
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Design a web page using HTML and CSS
Form validation using jQuery
How to set space between the flexbox ?
Search Bar using HTML, CSS and JavaScript
How to style a checkbox using CSS?
Top 10 Front End Developer Skills That You Need in 2022
Installation of Node.js on Linux
How to fetch data from an API in ReactJS ?
Difference between var, let and const keywords in JavaScript
Convert a string to an integer in JavaScript | [
{
"code": null,
"e": 25010,
"s": 24982,
"text": "\n24 May, 2021"
},
{
"code": null,
"e": 25090,
"s": 25010,
"text": "In this article, we will explain the difference between CSS padding and margin."
},
{
"code": null,
"e": 25467,
"s": 25090,
"text": "Margin: It is the space around an element. Margins are used to move an element up or down on a page as well as left or right. Margin is completely transparent, and it does not have any background color. It clears the area around the element. Each side of the element has a margin size you can change individually. In creating the gap, the margin pushes adjacent elements away."
},
{
"code": null,
"e": 25889,
"s": 25467,
"text": "Padding: It is the space between the element and the related content inside it. It determines how elements look and sit within a container. It also shows the container background around the element in it. Padding can be affected by background colors as it clears the area around the content. To create the gap, it either grows the element size or shrinks the content inside. By default, the size of the element increases."
},
{
"code": null,
"e": 25921,
"s": 25889,
"text": "When to use Margin and Padding?"
},
{
"code": null,
"e": 26241,
"s": 25921,
"text": "When you are adjusting the layout of your design, you will need to determine whether to adjust the margins or the padding. If the width of your page is fixed, centering an element horizontally is very simple, just assign the value margin: auto. You would also use the margin to set the distance between nearby elements."
},
{
"code": null,
"e": 26364,
"s": 26241,
"text": "You would change the padding if you want to create the space between the element and the edge of the container, or border."
},
{
"code": null,
"e": 26453,
"s": 26364,
"text": "Note: Margins are used to add spaces between an image and the description of that image."
},
{
"code": null,
"e": 26641,
"s": 26453,
"text": "CSS Padding is used if we want to create a space between an element and the edge of the container or the border. It is also useful in the requirement of changing the size of the element. "
},
{
"code": null,
"e": 26651,
"s": 26641,
"text": "CSS code:"
},
{
"code": null,
"e": 26775,
"s": 26651,
"text": ".center {\nmargin: auto;\nbackground: lime;\nwidth: 66%;\n}\n\n.outside {\nmargin: 3rem 0 0 -3rem;\nbackground: cyan;\nwidth: 66%;\n}"
},
{
"code": null,
"e": 26790,
"s": 26775,
"text": "Complete code:"
},
{
"code": null,
"e": 26795,
"s": 26790,
"text": "HTML"
},
{
"code": "<!DOCTYPE html><html><head><style> .center {margin: auto;background: lime;width: 66%;} .outside {margin: 3rem 0 0 -3rem;background: cyan;width: 66%;}</style></head><body> <h2 style=\"color:green\">GeeksforGeeks</h2> <p class=\"center\">This element is centered.</p> <p class=\"outside\">The element is positioned outside of its corner.</p> </body></html>",
"e": 27152,
"s": 26795,
"text": null
},
{
"code": null,
"e": 27160,
"s": 27152,
"text": "Output:"
},
{
"code": null,
"e": 27196,
"s": 27173,
"text": "Element outside corner"
},
{
"code": null,
"e": 27345,
"s": 27219,
"text": "Note: When there is an increase in the padding value, the text will remain the same, but the surrounding space will increase."
},
{
"code": null,
"e": 27355,
"s": 27345,
"text": "CSS code:"
},
{
"code": null,
"e": 27471,
"s": 27355,
"text": "h4 {\n background-color: lime;\npadding: 20px 50px;\n}\n\nh3 {\nbackground-color: cyan;\npadding: 110px 50px 50px 110px;\n}"
},
{
"code": null,
"e": 27486,
"s": 27471,
"text": "Complete code:"
},
{
"code": null,
"e": 27491,
"s": 27486,
"text": "HTML"
},
{
"code": "<!DOCTYPE html><html><head><style>h4 { background-color: lime;padding: 20px 50px;} h3 {background-color: cyan;padding: 110px 50px 50px 110px;}</style></head><body> <h2 style=\"color:green\">GeeksforGeeks</h2> <h4>This element has moderate padding.</h4> <h3>The padding is huge in this element!</h3> </body></html>",
"e": 27810,
"s": 27491,
"text": null
},
{
"code": null,
"e": 27818,
"s": 27810,
"text": "Output:"
},
{
"code": null,
"e": 27856,
"s": 27830,
"text": "moderate and huge padding"
},
{
"code": null,
"e": 27924,
"s": 27873,
"text": "The tabular difference between Padding and Margin."
},
{
"code": null,
"e": 27971,
"s": 27924,
"text": "The different attributes of margin and padding"
},
{
"code": null,
"e": 27986,
"s": 27971,
"text": "CSS-Properties"
},
{
"code": null,
"e": 27993,
"s": 27986,
"text": "Picked"
},
{
"code": null,
"e": 27997,
"s": 27993,
"text": "CSS"
},
{
"code": null,
"e": 28014,
"s": 27997,
"text": "Web Technologies"
},
{
"code": null,
"e": 28112,
"s": 28014,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 28121,
"s": 28112,
"text": "Comments"
},
{
"code": null,
"e": 28134,
"s": 28121,
"text": "Old Comments"
},
{
"code": null,
"e": 28171,
"s": 28134,
"text": "Design a web page using HTML and CSS"
},
{
"code": null,
"e": 28200,
"s": 28171,
"text": "Form validation using jQuery"
},
{
"code": null,
"e": 28239,
"s": 28200,
"text": "How to set space between the flexbox ?"
},
{
"code": null,
"e": 28281,
"s": 28239,
"text": "Search Bar using HTML, CSS and JavaScript"
},
{
"code": null,
"e": 28316,
"s": 28281,
"text": "How to style a checkbox using CSS?"
},
{
"code": null,
"e": 28372,
"s": 28316,
"text": "Top 10 Front End Developer Skills That You Need in 2022"
},
{
"code": null,
"e": 28405,
"s": 28372,
"text": "Installation of Node.js on Linux"
},
{
"code": null,
"e": 28448,
"s": 28405,
"text": "How to fetch data from an API in ReactJS ?"
},
{
"code": null,
"e": 28509,
"s": 28448,
"text": "Difference between var, let and const keywords in JavaScript"
}
] |
Collections singletonMap() method in Java with Examples - GeeksforGeeks | 11 May, 2021
The singletonMap() method of java.util.Collections class is used to return an immutable map, mapping only the specified key to the specified value. The returned map is serializable.
Syntax:
public static Map singletonMap(K key, V value)
Parameters: This method takes the following parameters as a argument:
key – the sole key to be stored in the returned map.
value – the value to which the returned map maps key.
Return Value: This method returns an immutable map containing only the specified key-value mapping.
Below are the examples to illustrate the singletonMap() method
Example 1:
Java
// Java program to demonstrate// singletonMap() method// for <String, String> Value import java.util.*; public class GFG1 { public static void main(String[] argv) throws Exception { try { // create singleton map // using singletonMap() method Map<String, String> map = Collections .singletonMap("key", "Value"); // printing the singletonMap System.out.println("Singleton map is: " + map); } catch (IllegalArgumentException e) { System.out.println("Exception thrown : " + e); } }}
Singleton map is: {key=Value}
Example 2:
Java
// Java program to demonstrate// singletonMap() method// for <Integer, Boolean> Value import java.util.*; public class GFG1 { public static void main(String[] argv) throws Exception { try { // create singleton map // using singletonMap() method Map<Integer, Boolean> map = Collections .singletonMap(100, true); // printing the singletonMap System.out.println("Singleton map is: " + map); } catch (IllegalArgumentException e) { System.out.println("Exception thrown : " + e); } }}
Singleton map is: {100=true}
sweetyty
Java - util package
Java-Collections
Java-Functions
Java
Java
Java-Collections
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Stream In Java
Constructors in Java
Exceptions in Java
Functional Interfaces in Java
Different ways of Reading a text file in Java
Generics in Java
Introduction to Java
Comparator Interface in Java with Examples
Internal Working of HashMap in Java
Strings in Java | [
{
"code": null,
"e": 25225,
"s": 25197,
"text": "\n11 May, 2021"
},
{
"code": null,
"e": 25407,
"s": 25225,
"text": "The singletonMap() method of java.util.Collections class is used to return an immutable map, mapping only the specified key to the specified value. The returned map is serializable."
},
{
"code": null,
"e": 25416,
"s": 25407,
"text": "Syntax: "
},
{
"code": null,
"e": 25464,
"s": 25416,
"text": "public static Map singletonMap(K key, V value)"
},
{
"code": null,
"e": 25535,
"s": 25464,
"text": "Parameters: This method takes the following parameters as a argument: "
},
{
"code": null,
"e": 25588,
"s": 25535,
"text": "key – the sole key to be stored in the returned map."
},
{
"code": null,
"e": 25642,
"s": 25588,
"text": "value – the value to which the returned map maps key."
},
{
"code": null,
"e": 25742,
"s": 25642,
"text": "Return Value: This method returns an immutable map containing only the specified key-value mapping."
},
{
"code": null,
"e": 25805,
"s": 25742,
"text": "Below are the examples to illustrate the singletonMap() method"
},
{
"code": null,
"e": 25818,
"s": 25805,
"text": "Example 1: "
},
{
"code": null,
"e": 25823,
"s": 25818,
"text": "Java"
},
{
"code": "// Java program to demonstrate// singletonMap() method// for <String, String> Value import java.util.*; public class GFG1 { public static void main(String[] argv) throws Exception { try { // create singleton map // using singletonMap() method Map<String, String> map = Collections .singletonMap(\"key\", \"Value\"); // printing the singletonMap System.out.println(\"Singleton map is: \" + map); } catch (IllegalArgumentException e) { System.out.println(\"Exception thrown : \" + e); } }}",
"e": 26487,
"s": 25823,
"text": null
},
{
"code": null,
"e": 26517,
"s": 26487,
"text": "Singleton map is: {key=Value}"
},
{
"code": null,
"e": 26530,
"s": 26519,
"text": "Example 2:"
},
{
"code": null,
"e": 26535,
"s": 26530,
"text": "Java"
},
{
"code": "// Java program to demonstrate// singletonMap() method// for <Integer, Boolean> Value import java.util.*; public class GFG1 { public static void main(String[] argv) throws Exception { try { // create singleton map // using singletonMap() method Map<Integer, Boolean> map = Collections .singletonMap(100, true); // printing the singletonMap System.out.println(\"Singleton map is: \" + map); } catch (IllegalArgumentException e) { System.out.println(\"Exception thrown : \" + e); } }}",
"e": 27198,
"s": 26535,
"text": null
},
{
"code": null,
"e": 27227,
"s": 27198,
"text": "Singleton map is: {100=true}"
},
{
"code": null,
"e": 27238,
"s": 27229,
"text": "sweetyty"
},
{
"code": null,
"e": 27258,
"s": 27238,
"text": "Java - util package"
},
{
"code": null,
"e": 27275,
"s": 27258,
"text": "Java-Collections"
},
{
"code": null,
"e": 27290,
"s": 27275,
"text": "Java-Functions"
},
{
"code": null,
"e": 27295,
"s": 27290,
"text": "Java"
},
{
"code": null,
"e": 27300,
"s": 27295,
"text": "Java"
},
{
"code": null,
"e": 27317,
"s": 27300,
"text": "Java-Collections"
},
{
"code": null,
"e": 27415,
"s": 27317,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 27430,
"s": 27415,
"text": "Stream In Java"
},
{
"code": null,
"e": 27451,
"s": 27430,
"text": "Constructors in Java"
},
{
"code": null,
"e": 27470,
"s": 27451,
"text": "Exceptions in Java"
},
{
"code": null,
"e": 27500,
"s": 27470,
"text": "Functional Interfaces in Java"
},
{
"code": null,
"e": 27546,
"s": 27500,
"text": "Different ways of Reading a text file in Java"
},
{
"code": null,
"e": 27563,
"s": 27546,
"text": "Generics in Java"
},
{
"code": null,
"e": 27584,
"s": 27563,
"text": "Introduction to Java"
},
{
"code": null,
"e": 27627,
"s": 27584,
"text": "Comparator Interface in Java with Examples"
},
{
"code": null,
"e": 27663,
"s": 27627,
"text": "Internal Working of HashMap in Java"
}
] |
Perl | exists() Function - GeeksforGeeks | 07 May, 2019
The exists() function in Perl is used to check whether an element in an given array or hash exists or not. This function returns 1 if the desired element is present in the given array or hash else returns 0.
Syntax: exists(Expression)
Parameters:Expression : This expression is either array or hash on which exists function is to be called.
Returns: 1 if the desired element is present in the given array or hash else returns 0.
Example 1: This example uses exists() function over an array.
#!/usr/bin/perl # Initialising an array@Array = (10, 20, 30, 40, 50); # Calling the for() loop over# each element of the Array# using index of the elementsfor ($i = 0; $i < 10; $i++){ # Calling the exists() function # using index of the array elements # as the parameter if(exists($Array[$i])) { print "Exists\n"; } else { print "Not Exists\n" }}
Output:
Exists
Exists
Exists
Exists
Exists
Not Exists
Not Exists
Not Exists
Not Exists
Not Exists
In the above code, it can be seen that parameter of the exists() function is the index of each element of the given array and hence till index 4 (index starts from 0) it gives output as “Exists” and later gives “Not Exists” because index gets out of the array.
Example 2: This example uses exists() function over a hash.
#!/usr/bin/perl # Initialising a Hash%Hash = (Mumbai => 1, Kolkata => 2, Delhi => 3); # Calling the exists() functionif(exists($Hash{Mumbai})){ print "Exists\n";}else{ print "Not Exists\n"} # Calling the exists() function# with different parameterif(exists($Hash{patna})){ print "Exists\n";}else{ print "Not Exists\n"}
Output :
Exists
Not Exists
In the above code, exists() function takes the key of the given hash as the parameter and check whether it is present or not.
Perl-Array-Functions
Perl-function
Perl-Hash-Functions
Perl
Perl
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Perl | Arrays (push, pop, shift, unshift)
Perl | Arrays
Perl Tutorial - Learn Perl With Examples
Use of print() and say() in Perl
Perl | join() Function
Perl | Basic Syntax of a Perl Program
Perl | Boolean Values
Perl | Subroutines or Functions
Perl | sleep() Function
Perl | Multidimensional Arrays | [
{
"code": null,
"e": 25287,
"s": 25259,
"text": "\n07 May, 2019"
},
{
"code": null,
"e": 25495,
"s": 25287,
"text": "The exists() function in Perl is used to check whether an element in an given array or hash exists or not. This function returns 1 if the desired element is present in the given array or hash else returns 0."
},
{
"code": null,
"e": 25522,
"s": 25495,
"text": "Syntax: exists(Expression)"
},
{
"code": null,
"e": 25628,
"s": 25522,
"text": "Parameters:Expression : This expression is either array or hash on which exists function is to be called."
},
{
"code": null,
"e": 25716,
"s": 25628,
"text": "Returns: 1 if the desired element is present in the given array or hash else returns 0."
},
{
"code": null,
"e": 25778,
"s": 25716,
"text": "Example 1: This example uses exists() function over an array."
},
{
"code": "#!/usr/bin/perl # Initialising an array@Array = (10, 20, 30, 40, 50); # Calling the for() loop over# each element of the Array# using index of the elementsfor ($i = 0; $i < 10; $i++){ # Calling the exists() function # using index of the array elements # as the parameter if(exists($Array[$i])) { print \"Exists\\n\"; } else { print \"Not Exists\\n\" }}",
"e": 26175,
"s": 25778,
"text": null
},
{
"code": null,
"e": 26183,
"s": 26175,
"text": "Output:"
},
{
"code": null,
"e": 26274,
"s": 26183,
"text": "Exists\nExists\nExists\nExists\nExists\nNot Exists\nNot Exists\nNot Exists\nNot Exists\nNot Exists\n"
},
{
"code": null,
"e": 26535,
"s": 26274,
"text": "In the above code, it can be seen that parameter of the exists() function is the index of each element of the given array and hence till index 4 (index starts from 0) it gives output as “Exists” and later gives “Not Exists” because index gets out of the array."
},
{
"code": null,
"e": 26595,
"s": 26535,
"text": "Example 2: This example uses exists() function over a hash."
},
{
"code": "#!/usr/bin/perl # Initialising a Hash%Hash = (Mumbai => 1, Kolkata => 2, Delhi => 3); # Calling the exists() functionif(exists($Hash{Mumbai})){ print \"Exists\\n\";}else{ print \"Not Exists\\n\"} # Calling the exists() function# with different parameterif(exists($Hash{patna})){ print \"Exists\\n\";}else{ print \"Not Exists\\n\"}",
"e": 26930,
"s": 26595,
"text": null
},
{
"code": null,
"e": 26939,
"s": 26930,
"text": "Output :"
},
{
"code": null,
"e": 26958,
"s": 26939,
"text": "Exists\nNot Exists\n"
},
{
"code": null,
"e": 27084,
"s": 26958,
"text": "In the above code, exists() function takes the key of the given hash as the parameter and check whether it is present or not."
},
{
"code": null,
"e": 27105,
"s": 27084,
"text": "Perl-Array-Functions"
},
{
"code": null,
"e": 27119,
"s": 27105,
"text": "Perl-function"
},
{
"code": null,
"e": 27139,
"s": 27119,
"text": "Perl-Hash-Functions"
},
{
"code": null,
"e": 27144,
"s": 27139,
"text": "Perl"
},
{
"code": null,
"e": 27149,
"s": 27144,
"text": "Perl"
},
{
"code": null,
"e": 27247,
"s": 27149,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 27289,
"s": 27247,
"text": "Perl | Arrays (push, pop, shift, unshift)"
},
{
"code": null,
"e": 27303,
"s": 27289,
"text": "Perl | Arrays"
},
{
"code": null,
"e": 27344,
"s": 27303,
"text": "Perl Tutorial - Learn Perl With Examples"
},
{
"code": null,
"e": 27377,
"s": 27344,
"text": "Use of print() and say() in Perl"
},
{
"code": null,
"e": 27400,
"s": 27377,
"text": "Perl | join() Function"
},
{
"code": null,
"e": 27438,
"s": 27400,
"text": "Perl | Basic Syntax of a Perl Program"
},
{
"code": null,
"e": 27460,
"s": 27438,
"text": "Perl | Boolean Values"
},
{
"code": null,
"e": 27492,
"s": 27460,
"text": "Perl | Subroutines or Functions"
},
{
"code": null,
"e": 27516,
"s": 27492,
"text": "Perl | sleep() Function"
}
] |
How to Change the Text Font of Side Navigation Drawer Items in Android? - GeeksforGeeks | 06 Jan, 2021
The navigation drawer is the most common feature offered by android and the navigation drawer is a UI panel that shows your app’s main navigation menu. It is also one of the important UI elements, which provides actions preferable to the users like example changing user profile, changing settings of the application, etc. The user can view the navigation drawer when the user swipes a finger from the left edge of the activity. They can also find it from the home activity by tapping the app icon in the action bar. The drawer icon is displayed on all top-level destinations that use a DrawerLayout. Have a look at the following image to get an idea about the Navigation drawer.
In this article, we will see how we change the text font of the navigation drawer’s item. Before starting we need to create a project with Side Navigation Drawer.
Method 1: Create a new project from the file option in the left corner. Go to the File > New > New Project and Select the Navigation Drawer Activity option and enter the project name. Let the remaining things be as it is.
Method 2: You can create a side navigation drawer manually. To do so click here Navigation Drawer in Android.
Step 1: Go to the app > res > values > themes > themes.xml file and write down the flowing code inside the <resources> tag.
XML
<!--new style is created here--><style name="NewFontStyle" parent="android:Widget.TextView"> <item name="android:fontFamily">sans-serif-smallcaps</item></style>
Step 2: Open activity_main.xml file and go to NavigationView tag and set the style in itemTextAppearance attribute.
app:itemTextAppearance=”@style/NewFontStyle”
Below is the complete code for the activity_main.xml file.
XML
<?xml version="1.0" encoding="utf-8"?><androidx.drawerlayout.widget.DrawerLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto" xmlns:tools="http://schemas.android.com/tools" android:id="@+id/drawer_layout" android:layout_width="match_parent" android:layout_height="match_parent" android:fitsSystemWindows="true" tools:openDrawer="start"> <include layout="@layout/app_bar_main" android:layout_width="match_parent" android:layout_height="match_parent" /> <com.google.android.material.navigation.NavigationView android:id="@+id/nav_view" android:layout_width="wrap_content" android:layout_height="match_parent" android:layout_gravity="start" android:fitsSystemWindows="true" app:headerLayout="@layout/nav_header_main" app:itemTextAppearance="@style/NewFontStyle" app:menu="@menu/activity_main_drawer" /> </androidx.drawerlayout.widget.DrawerLayout>
Before:
After:
android
Android
Android
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Resource Raw Folder in Android Studio
Flutter - Custom Bottom Navigation Bar
How to Read Data from SQLite Database in Android?
How to Post Data to API using Retrofit in Android?
Retrofit with Kotlin Coroutine in Android
How to Get Current Location in Android?
Android Listview in Java with Example
Flexbox-Layout in Android
How to Save Data to the Firebase Realtime Database in Android?
How to Change the Background Color After Clicking the Button in Android? | [
{
"code": null,
"e": 26381,
"s": 26353,
"text": "\n06 Jan, 2021"
},
{
"code": null,
"e": 27061,
"s": 26381,
"text": "The navigation drawer is the most common feature offered by android and the navigation drawer is a UI panel that shows your app’s main navigation menu. It is also one of the important UI elements, which provides actions preferable to the users like example changing user profile, changing settings of the application, etc. The user can view the navigation drawer when the user swipes a finger from the left edge of the activity. They can also find it from the home activity by tapping the app icon in the action bar. The drawer icon is displayed on all top-level destinations that use a DrawerLayout. Have a look at the following image to get an idea about the Navigation drawer."
},
{
"code": null,
"e": 27225,
"s": 27061,
"text": "In this article, we will see how we change the text font of the navigation drawer’s item. Before starting we need to create a project with Side Navigation Drawer. "
},
{
"code": null,
"e": 27447,
"s": 27225,
"text": "Method 1: Create a new project from the file option in the left corner. Go to the File > New > New Project and Select the Navigation Drawer Activity option and enter the project name. Let the remaining things be as it is."
},
{
"code": null,
"e": 27557,
"s": 27447,
"text": "Method 2: You can create a side navigation drawer manually. To do so click here Navigation Drawer in Android."
},
{
"code": null,
"e": 27681,
"s": 27557,
"text": "Step 1: Go to the app > res > values > themes > themes.xml file and write down the flowing code inside the <resources> tag."
},
{
"code": null,
"e": 27685,
"s": 27681,
"text": "XML"
},
{
"code": "<!--new style is created here--><style name=\"NewFontStyle\" parent=\"android:Widget.TextView\"> <item name=\"android:fontFamily\">sans-serif-smallcaps</item></style>",
"e": 27847,
"s": 27685,
"text": null
},
{
"code": null,
"e": 27964,
"s": 27847,
"text": "Step 2: Open activity_main.xml file and go to NavigationView tag and set the style in itemTextAppearance attribute. "
},
{
"code": null,
"e": 28009,
"s": 27964,
"text": "app:itemTextAppearance=”@style/NewFontStyle”"
},
{
"code": null,
"e": 28068,
"s": 28009,
"text": "Below is the complete code for the activity_main.xml file."
},
{
"code": null,
"e": 28072,
"s": 28068,
"text": "XML"
},
{
"code": "<?xml version=\"1.0\" encoding=\"utf-8\"?><androidx.drawerlayout.widget.DrawerLayout xmlns:android=\"http://schemas.android.com/apk/res/android\" xmlns:app=\"http://schemas.android.com/apk/res-auto\" xmlns:tools=\"http://schemas.android.com/tools\" android:id=\"@+id/drawer_layout\" android:layout_width=\"match_parent\" android:layout_height=\"match_parent\" android:fitsSystemWindows=\"true\" tools:openDrawer=\"start\"> <include layout=\"@layout/app_bar_main\" android:layout_width=\"match_parent\" android:layout_height=\"match_parent\" /> <com.google.android.material.navigation.NavigationView android:id=\"@+id/nav_view\" android:layout_width=\"wrap_content\" android:layout_height=\"match_parent\" android:layout_gravity=\"start\" android:fitsSystemWindows=\"true\" app:headerLayout=\"@layout/nav_header_main\" app:itemTextAppearance=\"@style/NewFontStyle\" app:menu=\"@menu/activity_main_drawer\" /> </androidx.drawerlayout.widget.DrawerLayout>",
"e": 29100,
"s": 28072,
"text": null
},
{
"code": null,
"e": 29108,
"s": 29100,
"text": "Before:"
},
{
"code": null,
"e": 29115,
"s": 29108,
"text": "After:"
},
{
"code": null,
"e": 29123,
"s": 29115,
"text": "android"
},
{
"code": null,
"e": 29131,
"s": 29123,
"text": "Android"
},
{
"code": null,
"e": 29139,
"s": 29131,
"text": "Android"
},
{
"code": null,
"e": 29237,
"s": 29139,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 29275,
"s": 29237,
"text": "Resource Raw Folder in Android Studio"
},
{
"code": null,
"e": 29314,
"s": 29275,
"text": "Flutter - Custom Bottom Navigation Bar"
},
{
"code": null,
"e": 29364,
"s": 29314,
"text": "How to Read Data from SQLite Database in Android?"
},
{
"code": null,
"e": 29415,
"s": 29364,
"text": "How to Post Data to API using Retrofit in Android?"
},
{
"code": null,
"e": 29457,
"s": 29415,
"text": "Retrofit with Kotlin Coroutine in Android"
},
{
"code": null,
"e": 29497,
"s": 29457,
"text": "How to Get Current Location in Android?"
},
{
"code": null,
"e": 29535,
"s": 29497,
"text": "Android Listview in Java with Example"
},
{
"code": null,
"e": 29561,
"s": 29535,
"text": "Flexbox-Layout in Android"
},
{
"code": null,
"e": 29624,
"s": 29561,
"text": "How to Save Data to the Firebase Realtime Database in Android?"
}
] |
Python Number degrees() Method | Python number method degrees() converts angle x from radians to degrees.
Following is the syntax for degrees() method −
degrees(x)
Note − This function is not accessible directly, so we need to import math module and then we need to call this function using math static object.
x − This must be a numeric value.
x − This must be a numeric value.
This method returns degree value of an angle.
The following example shows the usage of degrees() method.
#!/usr/bin/python
import math
print "degrees(3) : ", math.degrees(3)
print "degrees(-3) : ", math.degrees(-3)
print "degrees(0) : ", math.degrees(0)
print "degrees(math.pi) : ", math.degrees(math.pi)
print "degrees(math.pi/2) : ", math.degrees(math.pi/2)
print "degrees(math.pi/4) : ", math.degrees(math.pi/4)
When we run above program, it produces following result −
degrees(3) : 171.887338539
degrees(-3) : -171.887338539
degrees(0) : 0.0
degrees(math.pi) : 180.0
degrees(math.pi/2) : 90.0
degrees(math.pi/4) : 45.0
187 Lectures
17.5 hours
Malhar Lathkar
55 Lectures
8 hours
Arnab Chakraborty
136 Lectures
11 hours
In28Minutes Official
75 Lectures
13 hours
Eduonix Learning Solutions
70 Lectures
8.5 hours
Lets Kode It
63 Lectures
6 hours
Abhilash Nelson
Print
Add Notes
Bookmark this page | [
{
"code": null,
"e": 2318,
"s": 2244,
"text": "Python number method degrees() converts angle x from radians to degrees."
},
{
"code": null,
"e": 2365,
"s": 2318,
"text": "Following is the syntax for degrees() method −"
},
{
"code": null,
"e": 2377,
"s": 2365,
"text": "degrees(x)\n"
},
{
"code": null,
"e": 2524,
"s": 2377,
"text": "Note − This function is not accessible directly, so we need to import math module and then we need to call this function using math static object."
},
{
"code": null,
"e": 2558,
"s": 2524,
"text": "x − This must be a numeric value."
},
{
"code": null,
"e": 2592,
"s": 2558,
"text": "x − This must be a numeric value."
},
{
"code": null,
"e": 2638,
"s": 2592,
"text": "This method returns degree value of an angle."
},
{
"code": null,
"e": 2697,
"s": 2638,
"text": "The following example shows the usage of degrees() method."
},
{
"code": null,
"e": 3014,
"s": 2697,
"text": "#!/usr/bin/python\nimport math\n\nprint \"degrees(3) : \", math.degrees(3)\nprint \"degrees(-3) : \", math.degrees(-3)\nprint \"degrees(0) : \", math.degrees(0)\nprint \"degrees(math.pi) : \", math.degrees(math.pi)\nprint \"degrees(math.pi/2) : \", math.degrees(math.pi/2)\nprint \"degrees(math.pi/4) : \", math.degrees(math.pi/4)"
},
{
"code": null,
"e": 3072,
"s": 3014,
"text": "When we run above program, it produces following result −"
},
{
"code": null,
"e": 3229,
"s": 3072,
"text": "degrees(3) : 171.887338539\ndegrees(-3) : -171.887338539\ndegrees(0) : 0.0\ndegrees(math.pi) : 180.0\ndegrees(math.pi/2) : 90.0\ndegrees(math.pi/4) : 45.0\n"
},
{
"code": null,
"e": 3266,
"s": 3229,
"text": "\n 187 Lectures \n 17.5 hours \n"
},
{
"code": null,
"e": 3282,
"s": 3266,
"text": " Malhar Lathkar"
},
{
"code": null,
"e": 3315,
"s": 3282,
"text": "\n 55 Lectures \n 8 hours \n"
},
{
"code": null,
"e": 3334,
"s": 3315,
"text": " Arnab Chakraborty"
},
{
"code": null,
"e": 3369,
"s": 3334,
"text": "\n 136 Lectures \n 11 hours \n"
},
{
"code": null,
"e": 3391,
"s": 3369,
"text": " In28Minutes Official"
},
{
"code": null,
"e": 3425,
"s": 3391,
"text": "\n 75 Lectures \n 13 hours \n"
},
{
"code": null,
"e": 3453,
"s": 3425,
"text": " Eduonix Learning Solutions"
},
{
"code": null,
"e": 3488,
"s": 3453,
"text": "\n 70 Lectures \n 8.5 hours \n"
},
{
"code": null,
"e": 3502,
"s": 3488,
"text": " Lets Kode It"
},
{
"code": null,
"e": 3535,
"s": 3502,
"text": "\n 63 Lectures \n 6 hours \n"
},
{
"code": null,
"e": 3552,
"s": 3535,
"text": " Abhilash Nelson"
},
{
"code": null,
"e": 3559,
"s": 3552,
"text": " Print"
},
{
"code": null,
"e": 3570,
"s": 3559,
"text": " Add Notes"
}
] |
How to delete a particular element from a JavaScript array? | To delete an element from a JavaScript array, firstly use the indexOf() method to get the index of the element to be deleted. After that use splice() method −
Live Demo
<html>
<body>
<script>
var array = [40, 20, 70, 50];
var index = array.indexOf(70);
document.write("Original array: "+array);
if (index > -1) {
array.splice(index, 1);
}
document.write("<br>New array after deletion: "+array);
</script>
</body>
</html>
Original array: 40,20,70,50
New array after deletion: 40,20,50 | [
{
"code": null,
"e": 1221,
"s": 1062,
"text": "To delete an element from a JavaScript array, firstly use the indexOf() method to get the index of the element to be deleted. After that use splice() method −"
},
{
"code": null,
"e": 1231,
"s": 1221,
"text": "Live Demo"
},
{
"code": null,
"e": 1643,
"s": 1231,
"text": "<html> \n <body> \n <script> \n var array = [40, 20, 70, 50]; \n var index = array.indexOf(70); \n document.write(\"Original array: \"+array); \n if (index > -1) { \n array.splice(index, 1); \n } \n document.write(\"<br>New array after deletion: \"+array); \n </script> \n </body>\n</html>"
},
{
"code": null,
"e": 1706,
"s": 1643,
"text": "Original array: 40,20,70,50\nNew array after deletion: 40,20,50"
}
] |
C library function - sscanf() | The C library function int sscanf(const char *str, const char *format, ...) reads formatted input from a string.
Following is the declaration for sscanf() function.
int sscanf(const char *str, const char *format, ...)
str − This is the C string that the function processes as its source to retrieve the data.
str − This is the C string that the function processes as its source to retrieve the data.
format − This is the C string that contains one or more of the following items: Whitespace character, Non-whitespace character and Format specifiers
A format specifier follows this prototype: [=%[*][width][modifiers]type=]
format − This is the C string that contains one or more of the following items: Whitespace character, Non-whitespace character and Format specifiers
A format specifier follows this prototype: [=%[*][width][modifiers]type=]
*
This is an optional starting asterisk, which indicates that the data is to be read from the stream but ignored, i.e. it is not stored in the corresponding argument.
width
This specifies the maximum number of characters to be read in the current reading operation.
modifiers
Specifies a size different from int (in the case of d, i and n), unsigned int (in the case of o, u and x) or float (in the case of e, f and g) for the data pointed by the corresponding additional argument: h : short int (for d, i and n), or unsigned short int (for o, u and x) l : long int (for d, i and n), or unsigned long int (for o, u and x), or double (for e, f and g) L : long double (for e, f and g)
type
A character specifying the type of data to be read and how it is expected to be read. See next table.
other arguments − This function expects a sequence of pointers as additional arguments, each one pointing to an object of the type specified by their corresponding %-tag within the format string, in the same order.
For each format specifier in the format string that retrieves data, an additional argument should be specified. If you want to store the result of a sscanf operation on a regular variable you should precede its identifier with the reference operator, i.e. an ampersand sign (&), like: int n; sscanf (str,"%d",&n);
other arguments − This function expects a sequence of pointers as additional arguments, each one pointing to an object of the type specified by their corresponding %-tag within the format string, in the same order.
For each format specifier in the format string that retrieves data, an additional argument should be specified. If you want to store the result of a sscanf operation on a regular variable you should precede its identifier with the reference operator, i.e. an ampersand sign (&), like: int n; sscanf (str,"%d",&n);
On success, the function returns the number of variables filled. In the case of an input failure before any data could be successfully read, EOF is returned.
The following example shows the usage of sscanf() function.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main () {
int day, year;
char weekday[20], month[20], dtm[100];
strcpy( dtm, "Saturday March 25 1989" );
sscanf( dtm, "%s %s %d %d", weekday, month, &day, &year );
printf("%s %d, %d = %s\n", month, day, year, weekday );
return(0);
}
Let us compile and run the above program that will produce the following result −
March 25, 1989 = Saturday
12 Lectures
2 hours
Nishant Malik
12 Lectures
2.5 hours
Nishant Malik
48 Lectures
6.5 hours
Asif Hussain
12 Lectures
2 hours
Richa Maheshwari
20 Lectures
3.5 hours
Vandana Annavaram
44 Lectures
1 hours
Amit Diwan
Print
Add Notes
Bookmark this page | [
{
"code": null,
"e": 2120,
"s": 2007,
"text": "The C library function int sscanf(const char *str, const char *format, ...) reads formatted input from a string."
},
{
"code": null,
"e": 2172,
"s": 2120,
"text": "Following is the declaration for sscanf() function."
},
{
"code": null,
"e": 2225,
"s": 2172,
"text": "int sscanf(const char *str, const char *format, ...)"
},
{
"code": null,
"e": 2316,
"s": 2225,
"text": "str − This is the C string that the function processes as its source to retrieve the data."
},
{
"code": null,
"e": 2407,
"s": 2316,
"text": "str − This is the C string that the function processes as its source to retrieve the data."
},
{
"code": null,
"e": 2630,
"s": 2407,
"text": "format − This is the C string that contains one or more of the following items: Whitespace character, Non-whitespace character and Format specifiers\nA format specifier follows this prototype: [=%[*][width][modifiers]type=]"
},
{
"code": null,
"e": 2779,
"s": 2630,
"text": "format − This is the C string that contains one or more of the following items: Whitespace character, Non-whitespace character and Format specifiers"
},
{
"code": null,
"e": 2853,
"s": 2779,
"text": "A format specifier follows this prototype: [=%[*][width][modifiers]type=]"
},
{
"code": null,
"e": 2855,
"s": 2853,
"text": "*"
},
{
"code": null,
"e": 3020,
"s": 2855,
"text": "This is an optional starting asterisk, which indicates that the data is to be read from the stream but ignored, i.e. it is not stored in the corresponding argument."
},
{
"code": null,
"e": 3026,
"s": 3020,
"text": "width"
},
{
"code": null,
"e": 3119,
"s": 3026,
"text": "This specifies the maximum number of characters to be read in the current reading operation."
},
{
"code": null,
"e": 3129,
"s": 3119,
"text": "modifiers"
},
{
"code": null,
"e": 3536,
"s": 3129,
"text": "Specifies a size different from int (in the case of d, i and n), unsigned int (in the case of o, u and x) or float (in the case of e, f and g) for the data pointed by the corresponding additional argument: h : short int (for d, i and n), or unsigned short int (for o, u and x) l : long int (for d, i and n), or unsigned long int (for o, u and x), or double (for e, f and g) L : long double (for e, f and g)"
},
{
"code": null,
"e": 3541,
"s": 3536,
"text": "type"
},
{
"code": null,
"e": 3643,
"s": 3541,
"text": "A character specifying the type of data to be read and how it is expected to be read. See next table."
},
{
"code": null,
"e": 4172,
"s": 3643,
"text": "other arguments − This function expects a sequence of pointers as additional arguments, each one pointing to an object of the type specified by their corresponding %-tag within the format string, in the same order.\nFor each format specifier in the format string that retrieves data, an additional argument should be specified. If you want to store the result of a sscanf operation on a regular variable you should precede its identifier with the reference operator, i.e. an ampersand sign (&), like: int n; sscanf (str,\"%d\",&n);"
},
{
"code": null,
"e": 4387,
"s": 4172,
"text": "other arguments − This function expects a sequence of pointers as additional arguments, each one pointing to an object of the type specified by their corresponding %-tag within the format string, in the same order."
},
{
"code": null,
"e": 4701,
"s": 4387,
"text": "For each format specifier in the format string that retrieves data, an additional argument should be specified. If you want to store the result of a sscanf operation on a regular variable you should precede its identifier with the reference operator, i.e. an ampersand sign (&), like: int n; sscanf (str,\"%d\",&n);"
},
{
"code": null,
"e": 4859,
"s": 4701,
"text": "On success, the function returns the number of variables filled. In the case of an input failure before any data could be successfully read, EOF is returned."
},
{
"code": null,
"e": 4919,
"s": 4859,
"text": "The following example shows the usage of sscanf() function."
},
{
"code": null,
"e": 5242,
"s": 4919,
"text": "#include <stdio.h>\n#include <stdlib.h>\n#include <string.h>\n\nint main () {\n int day, year;\n char weekday[20], month[20], dtm[100];\n\n strcpy( dtm, \"Saturday March 25 1989\" );\n sscanf( dtm, \"%s %s %d %d\", weekday, month, &day, &year );\n\n printf(\"%s %d, %d = %s\\n\", month, day, year, weekday );\n \n return(0);\n}"
},
{
"code": null,
"e": 5324,
"s": 5242,
"text": "Let us compile and run the above program that will produce the following result −"
},
{
"code": null,
"e": 5351,
"s": 5324,
"text": "March 25, 1989 = Saturday\n"
},
{
"code": null,
"e": 5384,
"s": 5351,
"text": "\n 12 Lectures \n 2 hours \n"
},
{
"code": null,
"e": 5399,
"s": 5384,
"text": " Nishant Malik"
},
{
"code": null,
"e": 5434,
"s": 5399,
"text": "\n 12 Lectures \n 2.5 hours \n"
},
{
"code": null,
"e": 5449,
"s": 5434,
"text": " Nishant Malik"
},
{
"code": null,
"e": 5484,
"s": 5449,
"text": "\n 48 Lectures \n 6.5 hours \n"
},
{
"code": null,
"e": 5498,
"s": 5484,
"text": " Asif Hussain"
},
{
"code": null,
"e": 5531,
"s": 5498,
"text": "\n 12 Lectures \n 2 hours \n"
},
{
"code": null,
"e": 5549,
"s": 5531,
"text": " Richa Maheshwari"
},
{
"code": null,
"e": 5584,
"s": 5549,
"text": "\n 20 Lectures \n 3.5 hours \n"
},
{
"code": null,
"e": 5603,
"s": 5584,
"text": " Vandana Annavaram"
},
{
"code": null,
"e": 5636,
"s": 5603,
"text": "\n 44 Lectures \n 1 hours \n"
},
{
"code": null,
"e": 5648,
"s": 5636,
"text": " Amit Diwan"
},
{
"code": null,
"e": 5655,
"s": 5648,
"text": " Print"
},
{
"code": null,
"e": 5666,
"s": 5655,
"text": " Add Notes"
}
] |
Subsets and Splits